From 204ea9420a8ce2ff0bd5bcf43e1827f6edfad1ec Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 13:02:18 -0800 Subject: [PATCH 01/20] fix(storage): omit credentials from saved jobs --- changelog.d/ITL-1394.md | 11 + docs/concepts/pipeline-job.md | 29 +- docs/dev/design_issues/ITL-1394-JB1.md | 16 + .../core/sources/postgresql_table_source.py | 11 +- src/orcapod/databases/delta_lake_databases.py | 46 ++- src/orcapod/databases/postgresql_connector.py | 50 ++- src/orcapod/pipeline/job.py | 11 +- src/orcapod/pipeline/serialization.py | 56 +++- .../sources/test_postgresql_table_source.py | 11 +- .../test_postgresql_connector.py | 55 +++- .../test_load_connector_database.py | 19 ++ .../loaded_job/test_saved_credentials.py | 288 ++++++++++++++++++ 12 files changed, 563 insertions(+), 40 deletions(-) create mode 100644 changelog.d/ITL-1394.md create mode 100644 docs/dev/design_issues/ITL-1394-JB1.md create mode 100644 tests/test_pipeline/loaded_job/test_saved_credentials.py diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md new file mode 100644 index 000000000..4545b8cc3 --- /dev/null +++ b/changelog.d/ITL-1394.md @@ -0,0 +1,11 @@ +### Breaking changes and migration + +- Saved job files omit Delta credential values and passwords in PostgreSQL connection + strings. Provide credentials through the storage backend's environment or credential + provider, pass the configured database to `PipelineJob.load()`, or bind a source that + could not be rebuilt with `job.bind(sources=...)`. + +### Fixed + +- Delta databases, PostgreSQL connectors and the sources that wrap them keep credentials + out of newly saved job files. Earlier files still load with their recorded settings. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 5111c077a..0cf08f4d6 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -526,16 +526,25 @@ the **Nodes** table below the picture for each node's columns and status. ## Saving and loading -`job.save(path)` writes the job to a JSON file: the graph, the database's location (and the -result database's, when one was given) and how each source was configured. `PipelineJob.load(path)` reads it back, for example in a later -Python session. An `InMemoryArrowDatabase` has no location to record, so here the database -is passed again; `PipelineJob.load(path, database=...)` is also how you point a loaded job -at a database that has moved, and `PipelineJob.load(path, result_database=...)` at a result -database. A connector database (SQLite, PostgreSQL, SpiralDB) is never rebuilt from the -file: pass it, built over your connector, or the load raises an error that names what to -pass. Saving a loaded job writes the database actually bound, the one you passed, in place of -the recorded one. The recorded one is kept only while nothing is bound in its slot, which -happens when a database of another kind could not be rebuilt and none was passed. The file records each node's own Arrow types, so saving types +`job.save(path)` writes the graph, database locations and source settings to a JSON file. +The file holds no credentials for Orcapod's built-in storage and sources. Delta database +configs keep option names and routing settings such as the region and endpoint URL. +Omitted option values are written as JSON `null`. PostgreSQL configs keep connection +settings such as the host and password-file path and omit passwords. A user-written +`PollingSource` implementer is responsible for keeping credentials out of its +`to_config()` return value. + +`PipelineJob.load(path)` reads the job back, for example in a later Python session. +Storage backends that rebuild from the file can obtain credentials from the environment +or their usual credential providers, such as a PostgreSQL password file. Supply a +database explicitly with `PipelineJob.load(path, database=...)` or +`PipelineJob.load(path, result_database=...)` when it needs explicit credentials or has +moved. For a connector database (SQLite, PostgreSQL, SpiralDB), always pass the database +built over your connector. If a source cannot be rebuilt, bind it after loading with +`job.bind(sources={...})`. Saving a loaded job writes the bound database's settings when +available and otherwise keeps the recorded settings. + +The file records each node's own Arrow types, so saving types every node from its inputs' types, as previewing an empty job does, and costs what that preview costs: a pipeline whose joins keep many system-tag columns saves as slowly as it previews. diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md new file mode 100644 index 000000000..95ec16a75 --- /dev/null +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -0,0 +1,16 @@ +## `src/orcapod/pipeline/job.py` + +### JB1 — Saved jobs expose cloud and PostgreSQL credentials +**Status:** resolved +**Severity:** high +**Issue:** ITL-1394 + +Delta database configs can contain credentials supplied directly or through a UPath. +PostgreSQL connector and table source configs can contain passwords in connection +strings. Saving a job exposes those values in plain text, including in wrapped configs. + +**Fix:** Delta saves option names and only the values of recognized routing options. +The PostgreSQL connector omits parameters marked as passwords by libpq, including +when its config is embedded in a source or database. Older files still use their +recorded values when loaded, and subsequent saves apply the same storage rules to +fallback configs. The job format version and source identities stay the same. diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 58acc1f17..aff31a9b2 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -191,7 +191,7 @@ def __init__( *, tag_only_columns: TagOnlyColumns = (), ) -> None: - self._dsn = dsn # store before try — needed by to_config even if super() raises + self._dsn = dsn connector = PostgreSQLConnector( dsn ) # outside try — if this raises, finally never runs @@ -273,13 +273,10 @@ def _open_connector(self) -> Iterator[PostgreSQLConnector]: connector.close() def to_config(self, db_registry=None) -> dict[str, Any]: - """Serialize source configuration to a JSON-compatible dict.""" - # super().to_config() calls self._connector.to_config(), which reads only - # self._connector._dsn (a stored string) — safe even though the connector - # was closed after construction. + """Serialize the source using the connector's saved connection settings.""" base = super().to_config() - base.pop("connector", None) - return {**base, "source_type": self.SOURCE_KIND, "dsn": self._dsn} + connector = base.pop("connector") + return {**base, "dsn": connector["dsn"]} @classmethod def from_config( diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 9e2877228..091a523c8 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1771,6 +1771,27 @@ class _CommittedSnapshot: dataset_filesystem: "pa_fs.FileSystem | None" = None +# Only these deltalake S3 settings keep their values in a saved config. Orcapod +# has no provider-specific option mapping for Azure or GCS. +_SAVED_STORAGE_OPTION_VALUES = frozenset( + { + "aws_region", + "region", + "aws_default_region", + "default_region", + "aws_endpoint_url", + "aws_endpoint", + "endpoint_url", + "endpoint", + "aws_endpoint_url_s3", + "aws_allow_http", + "allow_http", + "aws_virtual_hosted_style_request", + "virtual_hosted_style_request", + } +) + + class DeltaTableDatabase: """ A Delta table database with clear insert vs update semantics. @@ -3499,7 +3520,7 @@ def get_records_by_ids( ) def to_config(self, db_registry: Any = None) -> dict[str, Any]: - """Serialize database configuration to a JSON-compatible dict.""" + """Serialize database configuration with credential values omitted.""" config: dict[str, Any] = { "type": "delta_table", "root_uri": self._root_uri, # renamed from "base_path" @@ -3510,7 +3531,23 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: } if self._storage_options: config["storage_options"] = self._storage_options - return config + return self.config_for_resave(config) + + @staticmethod + def config_for_resave(config: dict[str, Any]) -> dict[str, Any]: + """Apply the storage-option policy to a config, even if it failed to rebuild.""" + if "storage_options" not in config: + return config + options = config["storage_options"] + if not isinstance(options, dict): + return {**config, "storage_options": None} + return { + **config, + "storage_options": { + name: value if name.lower() in _SAVED_STORAGE_OPTION_VALUES else None + for name, value in cast("dict[str, Any]", options).items() + }, + } @classmethod def from_config(cls, config: dict[str, Any]) -> "DeltaTableDatabase": @@ -3531,9 +3568,12 @@ def from_config(cls, config: dict[str, Any]) -> "DeltaTableDatabase": # Legacy format (pre-ENG-341): "base_path" was the root URI string root_uri = config["base_path"] _path_prefix = () + options: dict[str, str | None] = config.get("storage_options") or {} return cls( base_path=root_uri, - storage_options=config.get("storage_options"), + storage_options={ + name: value for name, value in options.items() if value is not None + }, create_base_path=True, batch_size=config.get("batch_size", 1000), max_hierarchy_depth=config.get("max_hierarchy_depth", 10), diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index b767a955d..89cd61e47 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -383,6 +383,17 @@ def _field_has_metadata(field: pa.Field) -> bool: return False +def _parse_dsn(dsn: str) -> list[psycopg.pq.ConninfoOption]: + """Parse a libpq DSN without echoing invalid input in an error.""" + from psycopg import OperationalError, ProgrammingError, pq + + try: + return pq.Conninfo.parse(dsn.encode()) + except (OperationalError, UnicodeError): + pass + raise ProgrammingError("Invalid PostgreSQL connection string.") + + def _psycopg_server(dsn: str) -> tuple[str, str]: """Return the ``host`` and ``hostaddr`` psycopg reads for ``dsn``, now. @@ -390,9 +401,11 @@ def _psycopg_server(dsn: str) -> tuple[str, str]: libpq's, and psycopg does not read it), ``""`` when neither gives one. psycopg decides from these whether it resolves the host itself. """ - from psycopg.conninfo import conninfo_to_dict - - given = conninfo_to_dict(dsn) + given = { + option.keyword.decode(): option.val.decode() + for option in _parse_dsn(dsn) + if option.val is not None + } def supplied(key: str, envvar: str) -> str: return str((given[key] if key in given else os.environ.get(envvar)) or "") @@ -1037,12 +1050,39 @@ def __exit__(self, *args: Any) -> None: # ── Serialization ───────────────────────────────────────────────────────── def to_config(self) -> dict[str, Any]: - """Serialize connection configuration to a JSON-compatible dict.""" + """Serialize libpq connection settings with secret parameters omitted.""" return { "connector_type": "postgresql", - "dsn": self._dsn, + "dsn": self._dsn_for_save(self._dsn), } + @staticmethod + def _dsn_for_save(dsn: str) -> str: + """Keep libpq parameters that it does not mark as passwords.""" + from psycopg.conninfo import make_conninfo + + return make_conninfo( + **{ + option.keyword.decode(): option.val.decode() + for option in _parse_dsn(dsn) + if option.val is not None and option.dispchar != b"*" + } + ) + + @classmethod + def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: + """Make a legacy config safe to retain when its connection could not open.""" + if "dsn" not in config: + return config + dsn = config["dsn"] + if isinstance(dsn, str): + try: + return {**config, "dsn": cls._dsn_for_save(dsn)} + except (ImportError, UnicodeError, psycopg.ProgrammingError): + pass + # Without a parseable DSN, a later load needs a new binding. + return {key: value for key, value in config.items() if key != "dsn"} + @classmethod def from_config(cls, config: dict[str, Any]) -> PostgreSQLConnector: """Reconstruct a PostgreSQLConnector from a config dict.""" diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index d64b113dc..de87e9c63 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1943,6 +1943,7 @@ def load( PIPELINE_JOB_FORMAT_VERSION, check_saved_source_config, check_source_config_binding, + database_config_for_resave, require_current_format, require_tag_only_columns, resolve_source_from_config, @@ -2031,7 +2032,9 @@ def load( raise ValueError(f"{path}: source {spec_name!r}: {exc}") from exc failure: Exception | None = None try: - # Slots written with the same complete config share one rebuild. + # Slots with equal saved configs share a rebuild. Storage credentials + # are outside source identity: two live objects that differ only in + # credentials already need distinct source IDs to be saved together. config_key = _json.dumps(src_config, sort_keys=True) if config_key not in sources_by_config: sources_by_config[config_key] = resolve_source_from_config( @@ -2115,7 +2118,7 @@ def load( effective_database = resolve_database_from_config(store_config) except Exception as exc: - unresolved_database = store_config + unresolved_database = database_config_for_resave(store_config) # The exception's type, never its text (ITL-1391). logger.warning( "Could not reconstruct the database from its saved config: " @@ -2157,7 +2160,9 @@ def load( result_config ) except Exception as exc: - unresolved_result_database = result_config + unresolved_result_database = database_config_for_resave( + result_config + ) logger.warning( "Could not reconstruct the job's separate result database " "(bindings.result_database) from its saved config (%s): %s. The " diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 0f647fe96..038d96903 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -568,6 +568,60 @@ def saved_connector_kind(config: Any) -> str | None: return "unknown connector kind" +def _connector_owner_config_for_resave(config: dict[str, Any]) -> dict[str, Any]: + """Ask the connector to clean a config retained by one of its wrappers.""" + from orcapod.databases.postgresql_connector import PostgreSQLConnector + + connector = config.get("connector") + if isinstance(connector, dict) and connector.get("connector_type") == "postgresql": + return { + **config, + "connector": PostgreSQLConnector.config_for_resave( + cast("dict[str, Any]", connector) + ), + } + return config + + +def database_config_for_resave(config: dict[str, Any]) -> dict[str, Any]: + """Apply the database's save policy to a retained legacy config.""" + from orcapod.databases.connector_arrow_database import CONNECTOR_DATABASE_TYPE + from orcapod.databases.delta_lake_databases import DeltaTableDatabase + + if config.get("type") == "delta_table": + return DeltaTableDatabase.config_for_resave(config) + if config.get("type") == CONNECTOR_DATABASE_TYPE: + return _connector_owner_config_for_resave(config) + return config + + +def _source_config_for_resave(config: dict[str, Any]) -> dict[str, Any]: + """Apply the wrapped storage's save policy to a retained legacy source config.""" + from orcapod.core.sources.cached_source import CachedSource + from orcapod.core.sources.db_table_source import DBTableSource + from orcapod.core.sources.derived_source import DerivedSource + from orcapod.core.sources.postgresql_table_source import PostgreSQLTableSource + from orcapod.databases.postgresql_connector import PostgreSQLConnector + + kind = config.get("source_type") + if kind == PostgreSQLTableSource.SOURCE_KIND: + return PostgreSQLConnector.config_for_resave(config) + if kind == DBTableSource.SOURCE_KIND: + return _connector_owner_config_for_resave(config) + if kind in (CachedSource.SOURCE_KIND, DerivedSource.SOURCE_KIND): + config = dict(config) + for key in NESTED_SOURCE_CONFIG_KEYS: + nested = config.get(key) + if isinstance(nested, dict): + config[key] = _source_config_for_resave(cast("dict[str, Any]", nested)) + cache_database = config.get("cache_database") + if kind == CachedSource.SOURCE_KIND and isinstance(cache_database, dict): + config["cache_database"] = database_config_for_resave( + cast("dict[str, Any]", cache_database) + ) + return config + + def resolve_operator_from_config(config: dict[str, Any]) -> Any: """Reconstruct an operator instance from a config dict. @@ -830,7 +884,7 @@ def _source_proxy_from_config( tag_schema=tag_schema, data_schema=data_schema, expected_class_name=expected_class_name, - source_config=config, + source_config=_source_config_for_resave(config), ) diff --git a/tests/test_core/sources/test_postgresql_table_source.py b/tests/test_core/sources/test_postgresql_table_source.py index b4958c930..0531ae365 100644 --- a/tests/test_core/sources/test_postgresql_table_source.py +++ b/tests/test_core/sources/test_postgresql_table_source.py @@ -35,6 +35,7 @@ def test_in_core_sources_all(): # --------------------------------------------------------------------------- DSN = "postgresql://user:pass@localhost:5432/testdb" +SAVED_DSN = "user=user dbname=testdb host=localhost port=5432" _PATCH = "orcapod.core.sources.postgresql_table_source.PostgreSQLConnector" @@ -78,6 +79,7 @@ def _make_mock_connector( mock.given_server.return_value = ("localhost", "") mock.get_column_info.return_value = [] mock.iter_batches.return_value = iter(batches) + mock.to_config.return_value = {"connector_type": "postgresql", "dsn": SAVED_DSN} return mock @@ -437,8 +439,8 @@ def _make_src(self): def test_has_source_type_postgresql_table(self): assert self._make_src().to_config()["source_type"] == "postgresql_table" - def test_has_dsn(self): - assert self._make_src().to_config()["dsn"] == DSN + def test_uses_the_connector_saved_dsn(self): + assert self._make_src().to_config()["dsn"] == SAVED_DSN def test_has_table_name(self): assert self._make_src().to_config()["table_name"] == "measurements" @@ -500,7 +502,8 @@ def test_from_config_hashes_match(self): assert src2.content_hash() == src.content_hash() assert src2.pipeline_hash() == src.pipeline_hash() - def test_from_config_with_explicit_tag_columns(self): + @pytest.mark.parametrize("saved_dsn", [SAVED_DSN, DSN]) + def test_from_config_with_explicit_tag_columns(self, saved_dsn: str): from orcapod.core.sources import PostgreSQLTableSource with patch(_PATCH) as mock_cls: @@ -509,9 +512,11 @@ def test_from_config_with_explicit_tag_columns(self): DSN, "measurements", tag_columns=["trial"], tag_only_columns=True ) config = src.to_config() + config["dsn"] = saved_dsn with patch(_PATCH) as mock_cls: mock_cls.return_value = _make_mock_connector() src2 = PostgreSQLTableSource.from_config(config) + mock_cls.assert_called_once_with(saved_dsn) tag_schema, _ = src2.output_schema() assert "trial" in tag_schema diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index 900535e90..a1e52b875 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -11,6 +11,7 @@ import psycopg import pyarrow as pa import pytest +from psycopg.conninfo import conninfo_to_dict from orcapod.databases.postgresql_connector import ( PostgreSQLConnector, @@ -197,26 +198,64 @@ def test_isinstance_dbconnector_protocol(self) -> None: class TestConfig: - def test_to_config(self) -> None: + @pytest.mark.parametrize( + "dsn", + [ + "postgresql://user:s%40fe@localhost:5432/mydb?" + "sslpassword=ssl-marker&passfile=%2Ftmp%2Ftest.pgpass", + "sslpassword=ssl-marker dbname=mydb password='s@fe' port=5432 " + "passfile=/tmp/test.pgpass user=user host=localhost", + ], + ) + def test_to_config(self, dsn: str) -> None: with patch("psycopg.connect") as mock_connect: mock_connect.return_value = MagicMock() - connector = PostgreSQLConnector( - "postgresql://user:pass@localhost:5432/mydb" - ) + connector = PostgreSQLConnector(dsn) config = connector.to_config() assert config["connector_type"] == "postgresql" - assert config["dsn"] == "postgresql://user:pass@localhost:5432/mydb" + assert conninfo_to_dict(config["dsn"]) == { + "user": "user", + "host": "localhost", + "port": "5432", + "dbname": "mydb", + "passfile": "/tmp/test.pgpass", + } + mock_connect.assert_called_once_with(dsn, autocommit=False) + mock_connect.reset_mock() + rebuilt = PostgreSQLConnector.from_config(config) + mock_connect.assert_called_once_with(config["dsn"], autocommit=False) + assert rebuilt.to_config() == config connector._conn = None - - def test_from_config_roundtrip(self) -> None: + rebuilt._conn = None + + @pytest.mark.skipif(psycopg.pq.version() < 180000, reason="libpq 18 adds OAuth") + def test_to_config_omits_oauth_client_secret(self) -> None: + dsn = "host=localhost oauth_client_id=client oauth_client_secret=oauth-marker" + with patch("psycopg.connect"): + with PostgreSQLConnector(dsn) as connector: + assert conninfo_to_dict(connector.to_config()["dsn"]) == { + "host": "localhost", + "oauth_client_id": "client", + } + + def test_invalid_dsn_error_omits_the_input(self) -> None: + with pytest.raises( + psycopg.ProgrammingError, match="Invalid PostgreSQL" + ) as failure: + PostgreSQLConnector("postgresq://user:password-marker@localhost/db") + assert "password-marker" not in str(failure.value) + assert failure.value.__context__ is None + + def test_from_config_reads_legacy_password(self) -> None: with patch("psycopg.connect") as mock_connect: mock_connect.return_value = MagicMock() config = { "connector_type": "postgresql", - "dsn": "postgresql://localhost/test", + "dsn": "postgresql://user:legacy-marker@localhost/test", } connector = PostgreSQLConnector.from_config(config) assert isinstance(connector, PostgreSQLConnector) + mock_connect.assert_called_once_with(config["dsn"], autocommit=False) connector._conn = None def test_from_config_wrong_type_raises(self) -> None: diff --git a/tests/test_pipeline/loaded_job/test_load_connector_database.py b/tests/test_pipeline/loaded_job/test_load_connector_database.py index d1c9e4e08..4cdae3771 100644 --- a/tests/test_pipeline/loaded_job/test_load_connector_database.py +++ b/tests/test_pipeline/loaded_job/test_load_connector_database.py @@ -151,6 +151,25 @@ def test_load_without_the_database_names_the_slot_and_what_to_pass( assert MARKER not in message +def test_legacy_connector_dsn_is_ignored_when_the_database_is_supplied( + databases: Databases, tmp_path: Path +) -> None: + path = tmp_path / "job.json" + _save_over(path, databases, "postgresql") + data = json.loads(path.read_text()) + # Older files held the full DSN. Check the original error path with that value. + data["bindings"]["database"]["connector"]["dsn"] = f"postgresql://u:{MARKER}@h/a" + path.write_text(json.dumps(data)) + with pytest.raises(ValueError, match="pass database=") as refused: + PipelineJob.load(path) + assert MARKER not in str(refused.value) + supplied = databases.make("postgresql", "a") + loaded = PipelineJob.load(path, database=supplied) + assert loaded.database is supplied + loaded.save(path) + assert MARKER not in path.read_text() + + @pytest.mark.parametrize("kind", KINDS) @pytest.mark.parametrize("result_kind", KINDS) def test_every_missing_slot_is_named( diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py new file mode 100644 index 000000000..d6821ef5d --- /dev/null +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -0,0 +1,288 @@ +"""Storage bindings save connection settings without their credentials.""" + +from __future__ import annotations + +import json +from collections.abc import Iterator +from pathlib import Path +from typing import Any, cast +from unittest.mock import MagicMock, patch + +import pyarrow as pa +import pytest +from psycopg.conninfo import conninfo_to_dict +from upath import UPath + +from orcapod import PipelineJob +from orcapod.core.sources.base import RootSource +from orcapod.core.sources.db_table_source import DBTableSource +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + PostgreSQLConnector, +) +from orcapod.databases.storage_utils import parse_base_path +from orcapod.errors import InconsistentSourceError +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.sources import ( + ArrowTableSource, + CachedSource, + DerivedSource, + PostgreSQLTableSource, +) + +SECRET = "SYNTHETIC-SECRET-123" +PASSWORD = "synthetic-postgres-password" +SSL_PASSWORD = "synthetic-ssl-password" +PUBLIC_OPTIONS = { + "AWS_REGION": "us-east-1", + "aws_DEFAULT_region": "us-east-2", + "AWS_ENDPOINT_URL": "https://storage.example.test", + "allow_http": "false", + "AWS_VIRTUAL_HOSTED_STYLE_REQUEST": "true", +} +PRIVATE_OPTIONS = { + "AWS_ACCESS_KEY_ID": "synthetic-access-key", + "AWS_SECRET_ACCESS_KEY": SECRET, + "AWS_SESSION_TOKEN": "synthetic-session-token", + "AZURE_STORAGE_SAS_KEY": "synthetic-sas", + "GOOGLE_SERVICE_ACCOUNT_KEY": "synthetic-service-account", + "unknown": "synthetic-unknown", +} + + +def _dsn(password: str = PASSWORD) -> str: + return ( + f"postgresql://user:{password}@localhost:5432/mydb?" + f"sslpassword={SSL_PASSWORD}&passfile=%2Ftmp%2Ftest.pgpass" + ) + + +@pytest.fixture +def postgres() -> Iterator[MagicMock]: + """Exercise actual connector and source serialization without a server.""" + batches = pa.table( + {"t1": [1, 2], "t2": ["x", "y"], "x": [3, 4], "y": [5, 6]} + ).to_batches() + with ( + patch("psycopg.connect") as connect, + patch.object(PostgreSQLConnector, "get_table_names", return_value=["records"]), + patch.object(PostgreSQLConnector, "get_pk_columns", return_value=["t1", "t2"]), + patch.object(PostgreSQLConnector, "get_column_info", return_value=[]), + patch.object( + PostgreSQLConnector, "iter_batches", side_effect=lambda _: iter(batches) + ), + patch.object( + PostgreSQLConnector, + "current_location", + return_value=("localhost", 5432, "mydb", "public"), + ), + ): + yield connect + + +def _arrow_source(source_id: str = "data") -> ArrowTableSource: + return ArrowTableSource( + pa.table({"t1": [1, 2], "t2": ["x", "y"], "x": [3, 4], "y": [5, 6]}), + source_id=source_id, + tag_columns=["t1", "t2"], + tag_only_columns=True, + ) + + +def _save( + path: Path, source: RootSource, database: ArrowDatabaseProtocol | None = None +) -> dict[str, Any]: + with PipelineJob(database=database) as job: + _ = source.select_data_columns(["x", "y"], label="selected") + job.save(path) + raw = path.read_text() + for secret in (*PRIVATE_OPTIONS.values(), PASSWORD, SSL_PASSWORD): + assert secret not in raw + return cast("dict[str, Any]", json.loads(raw)["bindings"]) + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("via_upath", [False, True]) +def test_delta_job_and_cached_source( + tmp_path: Path, reverse: bool, via_upath: bool +) -> None: + if via_upath: + upath_options = { + "key": PRIVATE_OPTIONS["AWS_ACCESS_KEY_ID"], + "secret": SECRET, + "token": PRIVATE_OPTIONS["AWS_SESSION_TOKEN"], + "client_kwargs": {"endpoint_url": PUBLIC_OPTIONS["AWS_ENDPOINT_URL"]}, + } + if reverse: + upath_options = dict(reversed(upath_options.items())) + database = DeltaTableDatabase( + UPath("s3://test-bucket/data", **cast("dict[str, Any]", upath_options)) + ) + public = {"AWS_ENDPOINT_URL": PUBLIC_OPTIONS["AWS_ENDPOINT_URL"]} + private = {key: None for key in list(PRIVATE_OPTIONS)[:3]} + else: + options = PUBLIC_OPTIONS | PRIVATE_OPTIONS + if reverse: + options = dict(reversed(options.items())) + database = DeltaTableDatabase(tmp_path / "delta", storage_options=options) + public = PUBLIC_OPTIONS + private = dict.fromkeys(PRIVATE_OPTIONS) + + path = tmp_path / "job.json" + bindings = _save(path, _arrow_source(), database) + assert bindings["database"]["storage_options"] == public | private + + loaded_database = PipelineJob.load(path).database + assert isinstance(loaded_database, DeltaTableDatabase) + assert loaded_database.to_config()["storage_options"] == public + assert PipelineJob.load(path, database=database).database is database + + bindings = _save(path, CachedSource(_arrow_source(), cache_database=database)) + (cached,) = bindings["sources"].values() + assert cached["cache_database"]["storage_options"] == public | private + + +@pytest.mark.usefixtures("postgres") +def test_postgres_job_database_and_source_wrappers(tmp_path: Path) -> None: + path = tmp_path / "job.json" + database = ConnectorArrowDatabase(PostgreSQLConnector(_dsn())) + bindings = _save(path, _arrow_source(), database) + connector = bindings["database"]["connector"] + assert conninfo_to_dict(connector["dsn"]) == { + "user": "user", + "host": "localhost", + "port": "5432", + "dbname": "mydb", + "passfile": "/tmp/test.pgpass", + } + assert PipelineJob.load(path, database=database).database is database + + generic = DBTableSource( + PostgreSQLConnector(_dsn()), "records", source_id="data", tag_only_columns=True + ) + (saved_generic,) = _save(path, generic)["sources"].values() + assert saved_generic["connector"] == connector + + source = PostgreSQLTableSource(_dsn(), "records", tag_only_columns=True) + (saved_source,) = _save(path, source)["sources"].values() + assert saved_source["dsn"] == connector["dsn"] + + cached = CachedSource(source, cache_database=database) + (saved_cached,) = _save(path, cached)["sources"].values() + assert saved_cached["cache_database"]["connector"] == connector + assert saved_cached["inner_source"] == saved_source + + for mapping in ({"t1": "copy1", "t2": "copy2"}, {"t2": "copy2", "t1": "copy1"}): + derived = DerivedSource(source, tags_as_data=mapping, source_id="derived") + (saved_derived,) = _save(path, derived)["sources"].values() + assert saved_derived["origin"] == saved_source + + +@pytest.mark.parametrize("slot", ["database", "result_database"]) +def test_legacy_delta_options_load_and_are_scrubbed_on_resave( + tmp_path: Path, slot: str +) -> None: + path = tmp_path / "job.json" + _ = _save(path, _arrow_source()) + data = json.loads(path.read_text()) + config = DeltaTableDatabase(tmp_path / "delta").to_config() + data["bindings"][slot] = { + **config, + "storage_options": PUBLIC_OPTIONS | PRIVATE_OPTIONS, + } + _ = path.write_text(json.dumps(data)) + with patch( + "orcapod.databases.delta_lake_databases.parse_base_path", + wraps=parse_base_path, + ) as parse: + loaded = PipelineJob.load(path) + parse.assert_any_call(config["root_uri"], PUBLIC_OPTIONS | PRIVATE_OPTIONS) + loaded.save(path) + assert SECRET not in path.read_text() + + # An unresolved binding is retained for the next load, with its option + # values subject to the same save policy as a live database. + blocked = tmp_path / "blocked" + blocked.touch() + data["bindings"][slot]["root_uri"] = str(blocked / "delta") + _ = path.write_text(json.dumps(data)) + loaded = PipelineJob.load(path) + assert getattr(loaded, slot) is None + loaded.save(path) + raw = path.read_text() + assert SECRET not in raw + assert json.loads(raw)["bindings"][slot]["storage_options"] == ( + PUBLIC_OPTIONS | dict.fromkeys(PRIVATE_OPTIONS) + ) + + +def test_cached_source_fallback_scrubs_a_legacy_dsn( + tmp_path: Path, postgres: MagicMock, caplog: pytest.LogCaptureFixture +) -> None: + path = tmp_path / "job.json" + source = PostgreSQLTableSource(_dsn(), "records", tag_only_columns=True) + cached = CachedSource(source, cache_database=DeltaTableDatabase(tmp_path / "cache")) + _ = _save(path, cached) + data = json.loads(path.read_text()) + (config,) = data["bindings"]["sources"].values() + config["inner_source"]["dsn"] = _dsn() + _ = path.write_text(json.dumps(data)) + + postgres.reset_mock() + postgres.side_effect = RuntimeError(PASSWORD) + loaded = CachedSource.from_config(config) + postgres.assert_called_once_with(_dsn(), autocommit=False) + saved = loaded.to_config() + assert PASSWORD not in json.dumps(saved) + caplog.text + assert SSL_PASSWORD not in json.dumps(saved) + caplog.text + assert saved["inner_source"]["dsn"] == source.to_config()["dsn"] + + +@pytest.mark.parametrize("slots", [("a", "b"), ("b", "a")]) +@pytest.mark.usefixtures("postgres") +def test_password_removal_preserves_source_object_consistency( + tmp_path: Path, slots: tuple[str, str] +) -> None: + path = tmp_path / "job.json" + with PipelineJob() as job: + for slot in slots: + _ = _arrow_source(slot).select_data_columns( + ["x", "y"], label=f"select_{slot}" + ) + a, b = slots + first = PostgreSQLTableSource(_dsn(), "records", tag_only_columns=True) + second = PostgreSQLTableSource( + _dsn("other-password"), "records", tag_only_columns=True + ) + assert first.to_config() == second.to_config() + assert first.content_hash() == second.content_hash() + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + job.bind(sources={a: first, b: second}) + + job.bind(sources={a: first, b: first}) + job.save(path) + loaded = PipelineJob.load(path) + assert loaded.sources[a] is loaded.sources[b] + + # Older files that explicitly recorded different credentials still take + # separate rebuild paths and are subject to the normal consistency check. + legacy = json.loads(path.read_text()) + legacy["bindings"]["sources"][a]["dsn"] = _dsn() + legacy["bindings"]["sources"][b]["dsn"] = _dsn("other-password") + _ = path.write_text(json.dumps(legacy)) + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + _ = PipelineJob.load(path) + + second = PostgreSQLTableSource( + _dsn("other-password"), + "records", + source_id="another-reading", + tag_only_columns=True, + ) + job.bind(sources={a: first, b: second}) + job.save(path) + loaded = PipelineJob.load(path) + assert loaded.sources[a] is not loaded.sources[b] + assert loaded.sources[a].content_hash() == first.content_hash() + assert loaded.sources[b].content_hash() == second.content_hash() From db485785f85e53575ad32b628f85eb958336b1f0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 13:04:56 -0800 Subject: [PATCH 02/20] fix(storage): handle legacy DSNs without psycopg --- src/orcapod/databases/postgresql_connector.py | 5 ++++- .../test_databases/test_postgresql_connector.py | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 89cd61e47..65c02c74d 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -1078,7 +1078,10 @@ def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: if isinstance(dsn, str): try: return {**config, "dsn": cls._dsn_for_save(dsn)} - except (ImportError, UnicodeError, psycopg.ProgrammingError): + except (ImportError, UnicodeError): + # Handle a missing psycopg before looking up its exception type. + pass + except psycopg.ProgrammingError: pass # Without a parseable DSN, a later load needs a new binding. return {key: value for key, value in config.items() if key != "dsn"} diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index a1e52b875..da330eaa5 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -20,6 +20,7 @@ _pg_type_to_arrow, ) from orcapod.protocols.db_connector_protocol import DBConnectorProtocol +from orcapod.utils.lazy_module import LazyModule class TestPgTypeToArrow: @@ -246,6 +247,22 @@ def test_invalid_dsn_error_omits_the_input(self) -> None: assert "password-marker" not in str(failure.value) assert failure.value.__context__ is None + def test_legacy_config_drops_the_dsn_without_the_postgresql_extra(self) -> None: + config = { + "connector_type": "postgresql", + "dsn": "postgresql://user:legacy-marker@localhost/test", + } + with ( + patch.object(PostgreSQLConnector, "_dsn_for_save", side_effect=ImportError), + patch( + "orcapod.databases.postgresql_connector.psycopg", + LazyModule("missing_psycopg_for_test"), + ), + ): + assert PostgreSQLConnector.config_for_resave(config) == { + "connector_type": "postgresql" + } + def test_from_config_reads_legacy_password(self) -> None: with patch("psycopg.connect") as mock_connect: mock_connect.return_value = MagicMock() From 7163a6d9bd9be4a5355e138d6e9973463c7eb3c2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 13:40:04 -0800 Subject: [PATCH 03/20] fix(storage): preserve public Delta options in saved jobs --- changelog.d/ITL-1394.md | 1 + docs/concepts/pipeline-job.md | 3 +- docs/dev/design_issues/ITL-1394-JB1.md | 3 +- src/orcapod/databases/delta_lake_databases.py | 218 ++++++++++++++++-- .../test_delta_table_database_s3.py | 37 +++ .../loaded_job/test_saved_credentials.py | 136 +++++++++++ 6 files changed, 379 insertions(+), 19 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index 4545b8cc3..4fda08120 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -9,3 +9,4 @@ - Delta databases, PostgreSQL connectors and the sources that wrap them keep credentials out of newly saved job files. Earlier files still load with their recorded settings. +- Saved Delta databases retain supported non-credential settings for S3, Azure, and GCS. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 0cf08f4d6..0d92171f2 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -528,7 +528,8 @@ the **Nodes** table below the picture for each node's columns and status. `job.save(path)` writes the graph, database locations and source settings to a JSON file. The file holds no credentials for Orcapod's built-in storage and sources. Delta database -configs keep option names and routing settings such as the region and endpoint URL. +configs keep option names and supported non-credential settings for S3, Azure, and GCS, +including account names, regions, endpoints, and HTTP client options. Omitted option values are written as JSON `null`. PostgreSQL configs keep connection settings such as the host and password-file path and omit passwords. A user-written `PollingSource` implementer is responsible for keeping credentials out of its diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index 95ec16a75..b9da29086 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -9,7 +9,8 @@ Delta database configs can contain credentials supplied directly or through a UP PostgreSQL connector and table source configs can contain passwords in connection strings. Saving a job exposes those values in plain text, including in wrapped configs. -**Fix:** Delta saves option names and only the values of recognized routing options. +**Fix:** Delta saves option names and the values of recognized non-credential +S3, Azure, and GCS options. The PostgreSQL connector omits parameters marked as passwords by libpq, including when its config is embedded in a source or database. Older files still use their recorded values when loaded, and subsequent saves apply the same storage rules to diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 091a523c8..8a3713297 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -13,6 +13,7 @@ from pathlib import Path from time import sleep from typing import TYPE_CHECKING, Any, BinaryIO, Literal, cast +from urllib.parse import urlsplit import polars as pl import pyarrow as pa @@ -1771,26 +1772,209 @@ class _CommittedSnapshot: dataset_filesystem: "pa_fs.FileSystem | None" = None -# Only these deltalake S3 settings keep their values in a saved config. Orcapod -# has no provider-specific option mapping for Azure or GCS. -_SAVED_STORAGE_OPTION_VALUES = frozenset( +# Credential material and paths to it must come from the caller or credential provider. +_CREDENTIAL_STORAGE_OPTION_KEYS = frozenset( { - "aws_region", - "region", - "aws_default_region", - "default_region", - "aws_endpoint_url", - "aws_endpoint", - "endpoint_url", - "endpoint", - "aws_endpoint_url_s3", - "aws_allow_http", - "allow_http", - "aws_virtual_hosted_style_request", - "virtual_hosted_style_request", + "access_key", + "access_key_id", + "account_key", + "application_credentials", + "aws_access_key_id", + "aws_access_key_id_dynamodb", + "aws_container_authorization_token_file", + "aws_secret_access_key", + "aws_secret_access_key_dynamodb", + "aws_session_token", + "aws_session_token_dynamodb", + "aws_sse_customer_key_base64", + "aws_token", + "aws_web_identity_token_file", + "azure_client_secret", + "azure_fabric_session_token", + "azure_federated_token_file", + "azure_storage_access_key", + "azure_storage_account_key", + "azure_storage_client_secret", + "azure_storage_master_key", + "azure_storage_sas_key", + "azure_storage_sas_token", + "azure_storage_token", + "bearer_token", + "certificate_password", + "client_secret", + "container_authorization_token_file", + "fabric_session_token", + "federated_token_file", + "google_application_credentials", + "google_bearer_token", + "google_service_account", + "google_service_account_key", + "google_service_account_path", + "master_key", + "sas_key", + "sas_token", + "secret_access_key", + "service_account", + "service_account_key", + "service_account_path", + "session_token", + "sse_customer_key_base64", + "token", + "web_identity_token_file", } ) +# Keep recognized identifiers, routing and behavior settings so the store can be reopened. +# Spellings come from object_store 0.13.2's S3, Azure, GCS and HTTP client key parsers +# and Delta Lake's storage configuration. Unknown keys have their values dropped. +_SAVED_STORAGE_OPTION_VALUES = ( + frozenset( + { + # S3 spellings with no simple prefixed/unprefixed pair. + "aws_endpoint_url", + "endpoint_url", + "aws_endpoint_url_s3", + # Azure. + "account_name", + "azure_storage_account_name", + "azure_storage_client_id", + "azure_client_id", + "client_id", + "azure_storage_tenant_id", + "azure_storage_authority_id", + "azure_tenant_id", + "azure_authority_id", + "tenant_id", + "authority_id", + "azure_storage_authority_host", + "azure_authority_host", + "authority_host", + "azure_storage_use_emulator", + "use_emulator", + "azure_storage_endpoint", + "azure_endpoint", + "azure_msi_endpoint", + "azure_identity_endpoint", + "identity_endpoint", + "msi_endpoint", + "azure_object_id", + "object_id", + "azure_msi_resource_id", + "msi_resource_id", + "azure_use_fabric_endpoint", + "use_fabric_endpoint", + "azure_use_azure_cli", + "use_azure_cli", + "azure_skip_signature", + "azure_container_name", + "container_name", + "azure_disable_tagging", + "azure_fabric_token_service_url", + "fabric_token_service_url", + "azure_fabric_workload_host", + "fabric_workload_host", + "azure_fabric_cluster_identifier", + "fabric_cluster_identifier", + # GCS. + "google_bucket", + "google_bucket_name", + "google_base_url", + "base_url", + "google_skip_signature", + # Delta Lake options outside the object_store key parsers. + "aws_force_credential_load", + "aws_s3_allow_unsafe_rename", + "aws_s3_locking_provider", + "backoff_config.base", + "backoff_config.init_backoff", + "backoff_config.max_backoff", + "certificate_path", + "concurrency_limit", + "enable_io", + "enable_time", + "max_concurrency", + "max_retries", + "multi_threaded", + "retry_timeout", + "thread_name", + "worker_threads", + } + | { + prefix + key + for prefix in ("", "aws_") + for key in ( + "bucket", + "bucket_name", + "checksum_algorithm", + "conditional_put", + "container_credentials_full_uri", + "container_credentials_relative_uri", + "copy_if_not_exists", + "default_region", + "disable_tagging", + "endpoint", + "endpoint_url_sts", + "imdsv1_fallback", + "metadata_endpoint", + "region", + "request_payer", + "role_arn", + "role_session_name", + "s3_express", + "server_side_encryption", + "skip_signature", + "sse_bucket_key_enabled", + "sse_kms_key_id", + "unsigned_payload", + "virtual_hosted_style_request", + ) + } + | { + prefix + key + for prefix in ("", "aws_", "azure_", "google_") + for key in ( + "allow_http", + "allow_invalid_certificates", + "connect_timeout", + "default_content_type", + "http1_only", + "http2_only", + "http2_keep_alive_interval", + "http2_keep_alive_timeout", + "http2_keep_alive_while_idle", + "http2_max_frame_size", + "pool_idle_timeout", + "pool_max_idle_per_host", + "proxy_url", + "proxy_ca_certificate", + "proxy_excludes", + "randomize_addresses", + "timeout", + "user_agent", + ) + } + ) + - _CREDENTIAL_STORAGE_OPTION_KEYS +) +_PROXY_URL_OPTION_KEYS = frozenset( + {"proxy_url", "aws_proxy_url", "azure_proxy_url", "google_proxy_url"} +) + + +def _saved_storage_option_value(key: str, value: Any) -> Any: + key = key.lower() + if key not in _SAVED_STORAGE_OPTION_VALUES: + return None + if key in _PROXY_URL_OPTION_KEYS and isinstance(value, str): + # The HTTP client also accepts proxy URLs carrying login credentials. + try: + proxy = urlsplit(value if "://" in value else f"//{value}") + if proxy.username is not None: + return None + except ValueError: + return None + return value + class DeltaTableDatabase: """ @@ -3544,7 +3728,7 @@ def config_for_resave(config: dict[str, Any]) -> dict[str, Any]: return { **config, "storage_options": { - name: value if name.lower() in _SAVED_STORAGE_OPTION_VALUES else None + name: _saved_storage_option_value(name, value) for name, value in cast("dict[str, Any]", options).items() }, } diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index ba6a1a497..71514bd52 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -14,6 +14,7 @@ """ import json +from pathlib import Path import deltalake import pyarrow as pa @@ -21,11 +22,47 @@ import s3fs from upath import UPath +from orcapod import PipelineJob from orcapod.databases import DeltaTableDatabase +from orcapod.sources import ArrowTableSource pytestmark = pytest.mark.s3 +def test_saved_job_reopens_s3_tables_with_environment_credentials( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + s3_base_uri: str, + s3_storage_options: dict[str, str], +) -> None: + options = { + **s3_storage_options, + "AWS_ENDPOINT_URL_STS": "https://sts.example.test", + "AWS_VIRTUAL_HOSTED_STYLE_REQUEST": "false", + } + database = DeltaTableDatabase(s3_base_uri, storage_options=options) + database.add_record(("table",), b"id", pa.table({"x": [1]}), flush=True) + path = tmp_path / "job.json" + with PipelineJob(database=database) as job: + source = ArrowTableSource( + pa.table({"tag": [1], "x": [1]}), + source_id="data", + tag_columns=["tag"], + tag_only_columns=True, + ) + _ = source.select_data_columns(["x"], label="selected") + job.save(path) + + for key in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"): + monkeypatch.setenv(key, options.pop(key)) + loaded = PipelineJob.load(path).database + assert isinstance(loaded, DeltaTableDatabase) + rows = loaded.get_record_by_id(("table",), b"id") + assert rows is not None + assert rows["x"].to_pylist() == [1] + assert loaded.to_config()["storage_options"] == options + + # --------------------------------------------------------------------------- # Core S3 operations # --------------------------------------------------------------------------- diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index d6821ef5d..074f3707a 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -10,6 +10,8 @@ import pyarrow as pa import pytest +from deltalake.exceptions import TableNotFoundError +from deltalake.fs import DeltaStorageHandler from psycopg.conninfo import conninfo_to_dict from upath import UPath @@ -143,6 +145,140 @@ def test_delta_job_and_cached_source( assert cached["cache_database"]["storage_options"] == public | private +@pytest.mark.parametrize( + ("uri", "public", "private_keys"), + [ + pytest.param( + "az://fixtures/data", + { + "azure_storage_account_name": "fixtureaccount", + "AZURE_STORAGE_ENDPOINT": "http://127.0.0.1:10000/fixtureaccount", + "azure_allow_http": "true", + "account_name": "fixtureaccount", + "azure_endpoint": "http://127.0.0.1:10000/fixtureaccount", + "azure_client_id": "fixtureclientid", + "tenant_id": "fixturetenantid", + "azure_container_name": "fixtures", + "azure_identity_endpoint": "http://localhost:10001", + "azure_use_fabric_endpoint": "false", + "disable_tagging": "true", + "azure_connect_timeout": "10s", + }, + ( + "account_key", + "azure_storage_access_key", + "sas_token", + "bearer_token", + "azure_client_secret", + "federated_token_file", + "azure_fabric_session_token", + ), + id="azure", + ), + pytest.param( + "gs://fixtures/data", + { + "google_base_url": "http://localhost:4443", + "base_url": "http://localhost:4443", + "GOOGLE_ALLOW_HTTP": "true", + "google_bucket_name": "fixtures", + "google_skip_signature": "false", + "google_pool_max_idle_per_host": "3", + "google_proxy_url": "http://proxy.example.test:8080", + }, + ( + "google_service_account", + "service_account_path", + "google_service_account_path", + "google_service_account_key", + "application_credentials", + "google_bearer_token", + "certificate_password", + ), + id="gcs", + ), + pytest.param( + "s3://fixtures/data", + { + "AWS_ENDPOINT_URL_STS": "https://sts.example.test", + "endpoint_url_sts": "https://sts.example.test", + "aws_region": "us-east-2", + "aws_bucket_name": "fixtures", + "aws_metadata_endpoint": "http://localhost:10002", + "aws_container_credentials_relative_uri": "/v2/credentials/fixture", + "aws_role_arn": "arn:aws:iam::123456789012:role/fixture", + "role_session_name": "fixture-session", + "aws_request_payer": "true", + "aws_virtual_hosted_style_request": "false", + "aws_skip_signature": "false", + "aws_sse_kms_key_id": "alias/test-key", + "aws_connect_timeout": "5s", + }, + ( + "access_key_id", + "secret_access_key", + "aws_token", + "aws_web_identity_token_file", + "container_authorization_token_file", + "aws_sse_customer_key_base64", + ), + id="s3", + ), + ], +) +def test_delta_cloud_options_reach_backend_after_round_trip( + tmp_path: Path, uri: str, public: dict[str, str], private_keys: tuple[str, ...] +) -> None: + path = tmp_path / "job.json" + private = dict.fromkeys((*private_keys, "unknown_option"), SECRET) + if uri.startswith("gs://"): + private["proxy_url"] = f"http://fixture-user:{SECRET}@proxy.example.test:8080" + database = DeltaTableDatabase(uri, storage_options=public | private) + with PipelineJob(database=database) as job: + _ = _arrow_source().select_data_columns(["x", "y"], label="selected") + job.save(path) + + loaded = PipelineJob.load(path).database + assert isinstance(loaded, DeltaTableDatabase) + with patch("deltalake.DeltaTable", side_effect=TableNotFoundError) as open_table: + assert not loaded.table_exists(("table",)) + open_table.assert_called_once_with(f"{uri}/table", storage_options=public) + raw = path.read_text() + assert SECRET not in raw + assert json.loads(raw)["bindings"]["database"]["storage_options"] == ( + public | dict.fromkeys(private) + ) + + +def test_delta_azure_round_trip_uses_environment_access_key( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + uri = "az://fixtures/data" + database = DeltaTableDatabase( + uri, + storage_options={ + "azure_storage_account_name": "fixtureaccount", + "azure_storage_endpoint": "http://127.0.0.1:10000/fixtureaccount", + "azure_allow_http": "true", + }, + ) + path = tmp_path / "job.json" + _ = _save(path, _arrow_source(), database) + loaded = PipelineJob.load(path).database + assert isinstance(loaded, DeltaTableDatabase) + + monkeypatch.setenv("AZURE_STORAGE_ACCESS_KEY", "ZmFrZS1rZXk=") + + def open_table(table_uri: str, storage_options: dict[str, str]) -> None: + # Construct the real storage handler without making a request. + _ = DeltaStorageHandler(table_uri, options=storage_options) + raise TableNotFoundError(table_uri) + + with patch("deltalake.DeltaTable", side_effect=open_table) as open_delta: + assert not loaded.table_exists(("table",)) + open_delta.assert_called_once() + + @pytest.mark.usefixtures("postgres") def test_postgres_job_database_and_source_wrappers(tmp_path: Path) -> None: path = tmp_path / "job.json" From 596feb27c7ed6b0bf14cde38e7be3b53bb16bc4d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 14:46:49 -0800 Subject: [PATCH 04/20] fix(storage): complete Delta job credential redaction --- changelog.d/ITL-1394.md | 4 +- docs/concepts/pipeline-job.md | 9 +- docs/dev/design_issues/ITL-1394-JB1.md | 3 +- src/orcapod/databases/delta_lake_databases.py | 108 +++++++++++--- .../test_delta_table_database_s3.py | 18 ++- .../loaded_job/test_saved_credentials.py | 135 +++++++++++++++++- 6 files changed, 242 insertions(+), 35 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index 4fda08120..1ce492e2b 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -9,4 +9,6 @@ - Delta databases, PostgreSQL connectors and the sources that wrap them keep credentials out of newly saved job files. Earlier files still load with their recorded settings. -- Saved Delta databases retain supported non-credential settings for S3, Azure, and GCS. +- Saved Delta databases retain supported non-credential settings for S3, Azure, and GCS, + including AWS role identifiers. Saved option URLs omit embedded credentials, and + redacted option names survive subsequent saves. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 0d92171f2..2f5ca70be 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -529,9 +529,12 @@ the **Nodes** table below the picture for each node's columns and status. `job.save(path)` writes the graph, database locations and source settings to a JSON file. The file holds no credentials for Orcapod's built-in storage and sources. Delta database configs keep option names and supported non-credential settings for S3, Azure, and GCS, -including account names, regions, endpoints, and HTTP client options. -Omitted option values are written as JSON `null`. PostgreSQL configs keep connection -settings such as the host and password-file path and omit passwords. A user-written +including account names, regions, endpoints, HTTP client options, and AWS role settings +such as the role ARN, session name, and web identity token file path. Saved option URLs +omit user info and credential query parameters, including SAS signatures. +Omitted option values are written as JSON `null` and stay that way when a loaded job +is saved again. PostgreSQL configs keep connection settings such as the host and +password-file path and omit passwords. A user-written `PollingSource` implementer is responsible for keeping credentials out of its `to_config()` return value. diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index b9da29086..47b4446a7 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -10,7 +10,8 @@ PostgreSQL connector and table source configs can contain passwords in connectio strings. Saving a job exposes those values in plain text, including in wrapped configs. **Fix:** Delta saves option names and the values of recognized non-credential -S3, Azure, and GCS options. +S3, Azure, and GCS options, including AWS role identifiers. It removes user info and +credential query parameters from saved option URLs and retains redacted names across saves. The PostgreSQL connector omits parameters marked as passwords by libpq, including when its config is embedded in a source or database. Older files still use their recorded values when loaded, and subsequent saves apply the same storage rules to diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 8a3713297..b62b75068 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -13,7 +13,7 @@ from pathlib import Path from time import sleep from typing import TYPE_CHECKING, Any, BinaryIO, Literal, cast -from urllib.parse import urlsplit +from urllib.parse import unquote_plus, urlsplit, urlunsplit import polars as pl import pyarrow as pa @@ -1772,7 +1772,7 @@ class _CommittedSnapshot: dataset_filesystem: "pa_fs.FileSystem | None" = None -# Credential material and paths to it must come from the caller or credential provider. +# Credential material and credential-file settings outside the save policy. _CREDENTIAL_STORAGE_OPTION_KEYS = frozenset( { "access_key", @@ -1782,13 +1782,13 @@ class _CommittedSnapshot: "aws_access_key_id", "aws_access_key_id_dynamodb", "aws_container_authorization_token_file", + "aws_external_id", "aws_secret_access_key", "aws_secret_access_key_dynamodb", "aws_session_token", "aws_session_token_dynamodb", "aws_sse_customer_key_base64", "aws_token", - "aws_web_identity_token_file", "azure_client_secret", "azure_fabric_session_token", "azure_federated_token_file", @@ -1803,6 +1803,7 @@ class _CommittedSnapshot: "certificate_password", "client_secret", "container_authorization_token_file", + "external_id", "fabric_session_token", "federated_token_file", "google_application_credentials", @@ -1820,7 +1821,6 @@ class _CommittedSnapshot: "session_token", "sse_customer_key_base64", "token", - "web_identity_token_file", } ) @@ -1883,8 +1883,12 @@ class _CommittedSnapshot: "google_skip_signature", # Delta Lake options outside the object_store key parsers. "aws_force_credential_load", + "aws_iam_role_arn", + "aws_iam_role_session_name", "aws_s3_allow_unsafe_rename", + "aws_s3_assume_role_arn", "aws_s3_locking_provider", + "aws_s3_role_session_name", "backoff_config.base", "backoff_config.init_backoff", "backoff_config.max_backoff", @@ -1927,6 +1931,7 @@ class _CommittedSnapshot: "sse_kms_key_id", "unsigned_payload", "virtual_hosted_style_request", + "web_identity_token_file", ) } | { @@ -1959,21 +1964,80 @@ class _CommittedSnapshot: _PROXY_URL_OPTION_KEYS = frozenset( {"proxy_url", "aws_proxy_url", "azure_proxy_url", "google_proxy_url"} ) +_RELATIVE_URL_OPTION_KEYS = frozenset( + {"container_credentials_relative_uri", "aws_container_credentials_relative_uri"} +) +_CREDENTIAL_URL_QUERY_KEYS = _CREDENTIAL_STORAGE_OPTION_KEYS | frozenset( + { + "access_token", + "api_key", + "assertion", + "auth_token", + "authorization", + "awsaccesskeyid", + "client_assertion", + "code", + "credential", + "googleaccessid", + "id_token", + "key", + "password", + "refresh_token", + "sas", + "security_token", + "sig", + "signature", + "x_amz_credential", + "x_amz_security_token", + "x_amz_signature", + "x_goog_credential", + "x_goog_security_token", + "x_goog_signature", + "x_ms_sas_token", + } +) -def _saved_storage_option_value(key: str, value: Any) -> Any: +def _saved_storage_option_value(key: str, value: object) -> object: + """Keep recognized settings and strip credentials from URL values.""" key = key.lower() if key not in _SAVED_STORAGE_OPTION_VALUES: return None - if key in _PROXY_URL_OPTION_KEYS and isinstance(value, str): - # The HTTP client also accepts proxy URLs carrying login credentials. - try: - proxy = urlsplit(value if "://" in value else f"//{value}") - if proxy.username is not None: - return None - except ValueError: + if not isinstance(value, str): + return value + + has_scheme = "://" in value or bool( + re.match(r"^(?:https?|socks[45][ah]?):", value, re.IGNORECASE) + ) + has_authority = value.startswith("//") + proxy_without_scheme = ( + key in _PROXY_URL_OPTION_KEYS and not has_scheme and not has_authority + ) + expects_host = has_scheme or has_authority or proxy_without_scheme + if not expects_host and key not in _RELATIVE_URL_OPTION_KEYS: + return value + try: + url = urlsplit(f"//{value}" if proxy_without_scheme else value) + # Accessing the port validates its syntax and range. + _ = url.port + if re.search(r"[\x00-\x20\x7f\\]", value) or ( + expects_host and url.scheme != "file" and not url.hostname + ): return None - return value + except ValueError: + return None + # Preserve the original escaping and order of public query parameters. + query = "&".join( + field + for field in url.query.split("&") + if unquote_plus(field.partition("=")[0]).lower().replace("-", "_") + not in _CREDENTIAL_URL_QUERY_KEYS + ) + host = url.netloc.rsplit("@", 1)[-1] + if host == url.netloc and query == url.query and not url.fragment: + return value + saved = urlunsplit((url.scheme, host, url.path, query, "")) + return saved.removeprefix("//") if proxy_without_scheme else saved class DeltaTableDatabase: @@ -2016,6 +2080,9 @@ def __init__( self._root_uri, self._storage_options = parse_base_path( base_path, storage_options ) + self._redacted_storage_option_names: frozenset[str] = ( + _root._redacted_storage_option_names if _root is not None else frozenset() + ) self._is_cloud: bool = is_cloud_uri(self._root_uri) self._path_prefix = _path_prefix self._root = _root @@ -3713,8 +3780,11 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: "max_hierarchy_depth": self.max_hierarchy_depth, "allow_schema_evolution": self.allow_schema_evolution, } - if self._storage_options: - config["storage_options"] = self._storage_options + if self._storage_options or self._redacted_storage_option_names: + config["storage_options"] = ( + dict.fromkeys(self._redacted_storage_option_names) + | self._storage_options + ) return self.config_for_resave(config) @staticmethod @@ -3729,7 +3799,7 @@ def config_for_resave(config: dict[str, Any]) -> dict[str, Any]: **config, "storage_options": { name: _saved_storage_option_value(name, value) - for name, value in cast("dict[str, Any]", options).items() + for name, value in sorted(cast("dict[str, object]", options).items()) }, } @@ -3753,7 +3823,7 @@ def from_config(cls, config: dict[str, Any]) -> "DeltaTableDatabase": root_uri = config["base_path"] _path_prefix = () options: dict[str, str | None] = config.get("storage_options") or {} - return cls( + database = cls( base_path=root_uri, storage_options={ name: value for name, value in options.items() if value is not None @@ -3764,6 +3834,10 @@ def from_config(cls, config: dict[str, Any]) -> "DeltaTableDatabase": allow_schema_evolution=config.get("allow_schema_evolution", True), _path_prefix=_path_prefix, ) + database._redacted_storage_option_names = frozenset( + name for name, value in options.items() if value is None + ) + return database @property def keeps_field_metadata(self) -> bool: diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index 71514bd52..55776e391 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -41,26 +41,30 @@ def test_saved_job_reopens_s3_tables_with_environment_credentials( "AWS_VIRTUAL_HOSTED_STYLE_REQUEST": "false", } database = DeltaTableDatabase(s3_base_uri, storage_options=options) - database.add_record(("table",), b"id", pa.table({"x": [1]}), flush=True) + data = pa.table({"x": [1], "y": [2]}) + database.add_record(("table",), b"id", data, flush=True) path = tmp_path / "job.json" with PipelineJob(database=database) as job: source = ArrowTableSource( - pa.table({"tag": [1], "x": [1]}), + pa.table({"t1": [1], "t2": [2], "x": [1], "y": [2]}), source_id="data", - tag_columns=["tag"], + tag_columns=["t1", "t2"], tag_only_columns=True, ) - _ = source.select_data_columns(["x"], label="selected") + _ = source.select_data_columns(["x", "y"], label="selected") job.save(path) - for key in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"): + credential_keys = ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY") + for key in credential_keys: monkeypatch.setenv(key, options.pop(key)) loaded = PipelineJob.load(path).database assert isinstance(loaded, DeltaTableDatabase) rows = loaded.get_record_by_id(("table",), b"id") assert rows is not None - assert rows["x"].to_pylist() == [1] - assert loaded.to_config()["storage_options"] == options + assert rows.select(["x", "y"]) == data + assert loaded.to_config()["storage_options"] == options | dict.fromkeys( + credential_keys + ) # --------------------------------------------------------------------------- diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index 074f3707a..767f83f03 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -137,7 +137,7 @@ def test_delta_job_and_cached_source( loaded_database = PipelineJob.load(path).database assert isinstance(loaded_database, DeltaTableDatabase) - assert loaded_database.to_config()["storage_options"] == public + assert loaded_database.to_config()["storage_options"] == public | private assert PipelineJob.load(path, database=database).database is database bindings = _save(path, CachedSource(_arrow_source(), cache_database=database)) @@ -145,6 +145,7 @@ def test_delta_job_and_cached_source( assert cached["cache_database"]["storage_options"] == public | private +@pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize( ("uri", "public", "private_keys"), [ @@ -208,6 +209,7 @@ def test_delta_job_and_cached_source( "aws_container_credentials_relative_uri": "/v2/credentials/fixture", "aws_role_arn": "arn:aws:iam::123456789012:role/fixture", "role_session_name": "fixture-session", + "aws_web_identity_token_file": "/var/run/fixture/web-identity.jwt", "aws_request_payer": "true", "aws_virtual_hosted_style_request": "false", "aws_skip_signature": "false", @@ -218,7 +220,6 @@ def test_delta_job_and_cached_source( "access_key_id", "secret_access_key", "aws_token", - "aws_web_identity_token_file", "container_authorization_token_file", "aws_sse_customer_key_base64", ), @@ -227,13 +228,18 @@ def test_delta_job_and_cached_source( ], ) def test_delta_cloud_options_reach_backend_after_round_trip( - tmp_path: Path, uri: str, public: dict[str, str], private_keys: tuple[str, ...] + tmp_path: Path, + uri: str, + public: dict[str, str], + private_keys: tuple[str, ...], + reverse: bool, ) -> None: path = tmp_path / "job.json" private = dict.fromkeys((*private_keys, "unknown_option"), SECRET) - if uri.startswith("gs://"): - private["proxy_url"] = f"http://fixture-user:{SECRET}@proxy.example.test:8080" - database = DeltaTableDatabase(uri, storage_options=public | private) + options = public | private + if reverse: + options = dict(reversed(options.items())) + database = DeltaTableDatabase(uri, storage_options=options) with PipelineJob(database=database) as job: _ = _arrow_source().select_data_columns(["x", "y"], label="selected") job.save(path) @@ -279,6 +285,123 @@ def open_table(table_uri: str, storage_options: dict[str, str]) -> None: open_delta.assert_called_once() +@pytest.mark.parametrize("reverse", [False, True]) +def test_delta_saved_urls_strip_credentials_and_keep_routing( + tmp_path: Path, reverse: bool +) -> None: + uri = "az://fixtures/data" + public = { + "azure_storage_account_name": "fixtureaccount", + "azure_storage_endpoint": "https://storage.example.test:8443/account?route=a%20b", + "azure_identity_endpoint": "https://identity.example.test/tenant", + "azure_proxy_url": "proxy.example.test:3128", + } + options = public | { + "azure_storage_endpoint": ( + f"https://fixture-user:{SECRET}@storage.example.test:8443/account" + "?route=a%20b&%53IG=synthetic-sas-signature" + ), + "azure_identity_endpoint": ( + "https://identity.example.test/tenant?X-Amz-Signature=synthetic-signature" + "&X-Goog-Credential=synthetic-credential&ACCESS_TOKEN=synthetic-token" + ), + "azure_proxy_url": f"fixture-proxy-user:{SECRET}@proxy.example.test:3128", + "azure_authority_host": f"https://[broken-{SECRET}", + } + if reverse: + options = dict(reversed(options.items())) + path = tmp_path / "job.json" + bindings = _save(path, _arrow_source(), DeltaTableDatabase(uri, options)) + raw = path.read_text() + for credential in ( + "fixture-user", + "fixture-proxy-user", + "synthetic-sas-signature", + "synthetic-signature", + "synthetic-credential", + "synthetic-token", + ): + assert credential not in raw + assert bindings["database"]["storage_options"] == public | { + "azure_authority_host": None, + } + loaded = PipelineJob.load(path).database + assert isinstance(loaded, DeltaTableDatabase) + with patch("deltalake.DeltaTable", side_effect=TableNotFoundError) as open_table: + assert not loaded.table_exists(("table",)) + open_table.assert_called_once_with(f"{uri}/table", storage_options=public) + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize( + ("arn_key", "session_key", "token_file_key"), + [ + ( + "AWS_IAM_ROLE_ARN", + "AWS_IAM_ROLE_SESSION_NAME", + "AWS_WEB_IDENTITY_TOKEN_FILE", + ), + ( + "AWS_S3_ASSUME_ROLE_ARN", + "AWS_S3_ROLE_SESSION_NAME", + "web_identity_token_file", + ), + ], +) +def test_delta_aws_role_settings_reach_backend_after_round_trip( + tmp_path: Path, reverse: bool, arn_key: str, session_key: str, token_file_key: str +) -> None: + uri = "s3://fixtures/data" + public = { + arn_key: "arn:aws:iam::123456789012:role/fixture", + session_key: "fixture-session", + token_file_key: str(tmp_path / "web-identity.jwt"), + "AWS_REGION": "us-east-1", + } + private = {"AWS_EXTERNAL_ID": SECRET, "AWS_SECRET_ACCESS_KEY": SECRET} + options = public | private + if reverse: + options = dict(reversed(options.items())) + path = tmp_path / "job.json" + bindings = _save(path, _arrow_source(), DeltaTableDatabase(uri, options)) + assert bindings["database"]["storage_options"] == public | dict.fromkeys(private) + loaded = PipelineJob.load(path).database + assert isinstance(loaded, DeltaTableDatabase) + with patch("deltalake.DeltaTable", side_effect=TableNotFoundError) as open_table: + assert not loaded.table_exists(("table",)) + open_table.assert_called_once_with(f"{uri}/table", storage_options=public) + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("public", [{}, PUBLIC_OPTIONS]) +def test_delta_resave_keeps_redacted_option_names( + tmp_path: Path, reverse: bool, public: dict[str, str] +) -> None: + uri = "s3://fixtures/data" + options = public | PRIVATE_OPTIONS + if reverse: + options = dict(reversed(options.items())) + path = tmp_path / "job.json" + initial = _save(path, _arrow_source(), DeltaTableDatabase(uri, options)) + loaded = PipelineJob.load(path) + assert isinstance(loaded.database, DeltaTableDatabase) + with patch("deltalake.DeltaTable", side_effect=TableNotFoundError) as open_table: + assert not loaded.database.table_exists(("table",)) + open_table.assert_called_once_with( + f"{uri}/table", storage_options=public or None + ) + loaded.save(path) + resaved = json.loads(path.read_text())["bindings"]["database"] + assert json.dumps(resaved["storage_options"]) == json.dumps( + initial["database"]["storage_options"] + ) + + scoped = _save(path, _arrow_source(), loaded.database.at("scope", "nested")) + assert scoped["database"]["storage_options"] == public | dict.fromkeys( + PRIVATE_OPTIONS + ) + + @pytest.mark.usefixtures("postgres") def test_postgres_job_database_and_source_wrappers(tmp_path: Path) -> None: path = tmp_path / "job.json" From 5baba64deee62f80a63abb589667df143717f085 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 15:31:23 -0800 Subject: [PATCH 05/20] fix(storage): redact credentials from unresolved job bindings --- changelog.d/ITL-1394.md | 2 + docs/dev/design_issues/ITL-1394-JB1.md | 4 +- src/orcapod/core/sources/cached_source.py | 23 ++++- src/orcapod/core/sources/db_table_source.py | 7 ++ src/orcapod/core/sources/derived_source.py | 17 +++- .../core/sources/postgresql_table_source.py | 5 + src/orcapod/core/sources/source_proxy.py | 8 +- .../databases/connector_arrow_database.py | 7 ++ src/orcapod/databases/delta_lake_databases.py | 4 +- src/orcapod/databases/postgresql_connector.py | 7 +- src/orcapod/pipeline/job.py | 32 ++++--- src/orcapod/pipeline/serialization.py | 91 ++++++++++-------- .../loaded_job/test_saved_credentials.py | 94 ++++++++++++++++++- 13 files changed, 232 insertions(+), 69 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index 1ce492e2b..bafa7b04c 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -12,3 +12,5 @@ - Saved Delta databases retain supported non-credential settings for S3, Azure, and GCS, including AWS role identifiers. Saved option URLs omit embedded credentials, and redacted option names survive subsequent saves. +- Resaving a legacy job applies the same credential rules to retained source + and database configurations, including nested storage wrappers. diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index 47b4446a7..981916ec7 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -15,4 +15,6 @@ credential query parameters from saved option URLs and retains redacted names ac The PostgreSQL connector omits parameters marked as passwords by libpq, including when its config is embedded in a source or database. Older files still use their recorded values when loaded, and subsequent saves apply the same storage rules to -fallback configs. The job format version and source identities stay the same. +the retained configs of sources and databases that could not be rebuilt. Unknown +config types are retained as saved and trigger a credential warning. The job +format version and source identities stay the same. diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 6795e9a16..345482744 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -4,7 +4,7 @@ import logging from datetime import datetime from collections.abc import Iterator -from typing import Any, ClassVar, TYPE_CHECKING +from typing import Any, ClassVar, TYPE_CHECKING, cast import pyarrow as pa from typing_extensions import override @@ -202,6 +202,27 @@ def to_config( # rebuilt takes it from there (serialization._source_proxy_from_config). } + @classmethod + def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: + """Apply the save policies of the retained source and cache database.""" + from orcapod.pipeline.serialization import ( + database_config_for_resave, + source_config_for_resave, + ) + + saved = dict(config) + inner = config.get("inner_source") + if isinstance(inner, dict): + saved["inner_source"] = source_config_for_resave( + cast("dict[str, Any]", inner), block="inner_source" + ) + cache = config.get("cache_database") + if isinstance(cache, dict): + saved["cache_database"] = database_config_for_resave( + cast("dict[str, Any]", cache), block="cache_database" + ) + return saved + @classmethod def from_config( cls, diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 7bb5019de..8638a8ea1 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -331,6 +331,13 @@ def to_config(self, db_registry=None) -> dict[str, Any]: **self._identity_config(), } + @classmethod + def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: + """Apply the save policy of the retained connector.""" + from orcapod.pipeline.serialization import connector_owner_config_for_resave + + return connector_owner_config_for_resave(config) + @classmethod def from_config(cls, config: dict[str, Any], db_registry=None) -> DBTableSource: """Not yet implemented — requires a connector factory registry. diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1b00e7b05..aa5aebebb 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -3,7 +3,7 @@ import dataclasses from collections.abc import Collection, Mapping from datetime import datetime -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING, Any, ClassVar, cast import pyarrow as pa @@ -384,6 +384,21 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: config.update(self._identity_config()) return config + @classmethod + def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: + """Apply the save policy of the retained origin.""" + from orcapod.pipeline.serialization import source_config_for_resave + + origin = config.get("origin") + if not isinstance(origin, dict): + return config + return { + **config, + "origin": source_config_for_resave( + cast("dict[str, Any]", origin), block="origin" + ), + } + @classmethod def from_config( cls, config: dict[str, Any], db_registry: Any = None diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index aff31a9b2..d0fd966d7 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -278,6 +278,11 @@ def to_config(self, db_registry=None) -> dict[str, Any]: connector = base.pop("connector") return {**base, "dsn": connector["dsn"]} + @classmethod + def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: + """Apply the connector's policy to the DSN stored directly on this source.""" + return PostgreSQLConnector.config_for_resave(config) + @classmethod def from_config( cls, config: dict[str, Any], db_registry=None diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 441d9fb88..4497340b2 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -349,8 +349,12 @@ def head( # ------------------------------------------------------------------------- def to_config(self, db_registry=None) -> dict[str, Any]: - """Return the original source's config (preserves source_type).""" - return dict(self._source_config) + """Return the original source's config with its save policy applied.""" + from orcapod.pipeline.serialization import source_config_for_resave + + return source_config_for_resave( + dict(self._source_config), block=f"source proxy {self.source_id!r}" + ) @classmethod def from_config(cls, config: dict[str, Any], db_registry=None) -> SourceProxy: diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 267caf622..9a48beec9 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1132,6 +1132,13 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: "max_hierarchy_depth": self.max_hierarchy_depth, } + @classmethod + def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: + """Apply the save policy of the retained connector.""" + from orcapod.pipeline.serialization import connector_owner_config_for_resave + + return connector_owner_config_for_resave(config) + @classmethod def from_config(cls, config: dict[str, Any]) -> ConnectorArrowDatabase: """Refuse: a connector is not rebuilt from a saved configuration (ITL-1391). diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index b62b75068..d663d72d2 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -3787,8 +3787,8 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: ) return self.config_for_resave(config) - @staticmethod - def config_for_resave(config: dict[str, Any]) -> dict[str, Any]: + @classmethod + def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: """Apply the storage-option policy to a config, even if it failed to rebuild.""" if "storage_options" not in config: return config diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 65c02c74d..3548967d8 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -1051,10 +1051,9 @@ def __exit__(self, *args: Any) -> None: def to_config(self) -> dict[str, Any]: """Serialize libpq connection settings with secret parameters omitted.""" - return { - "connector_type": "postgresql", - "dsn": self._dsn_for_save(self._dsn), - } + return self.config_for_resave( + {"connector_type": "postgresql", "dsn": self._dsn} + ) @staticmethod def _dsn_for_save(dsn: str) -> str: diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 2d5f65fed..af55b1896 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1767,7 +1767,9 @@ def save(self, path: "str | Path") -> None: from orcapod.pipeline.serialization import ( PIPELINE_JOB_FORMAT_VERSION, + database_config_for_resave, saved_source_identifiers, + source_config_for_resave, ) # Allow save when either compile() was called or _compiled_pipeline is @@ -1818,21 +1820,26 @@ def save(self, path: "str | Path") -> None: } for name, config in self._unresolved_sources.items(): if live_identities.isdisjoint(saved_source_identifiers(config)): - sources_block[name] = config + sources_block[name] = source_config_for_resave( + config, block=f"bindings.sources[{name!r}]" + ) sources_block = dict(sorted(sources_block.items())) - # Database config (best-effort). A loaded job's database that could not be - # rebuilt is written back as it was saved (ITL-1391). - database_block = self._unresolved_database + # Keep unresolved bindings, applying the same storage policies at save time. + database_block = None if self._database is not None and hasattr(self._database, "to_config"): database_block = self._database.to_config() - # A separate result database (ITL-1408), saved by the same rule; ``None`` when - # the results are in the job's own database (``/_result``). - # A loaded job's binding that was not available is written back as it was, so - # the next load refuses it again rather than reading ``_result``. - result_database_block = self._unresolved_result_database + elif self._unresolved_database is not None: + database_block = database_config_for_resave( + self._unresolved_database, block="bindings.database" + ) + result_database_block = None if self._result_database is not None: result_database_block = self._result_database.to_config() + elif self._unresolved_result_database is not None: + result_database_block = database_config_for_resave( + self._unresolved_result_database, block="bindings.result_database" + ) output: dict[str, Any] = { "orcapod_pipeline_job_version": PIPELINE_JOB_FORMAT_VERSION, @@ -1980,7 +1987,6 @@ def load( PIPELINE_JOB_FORMAT_VERSION, check_saved_source_config, check_source_config_binding, - database_config_for_resave, require_current_format, require_tag_only_columns, resolve_source_from_config, @@ -2160,7 +2166,7 @@ def load( effective_database = resolve_database_from_config(store_config) except Exception as exc: - unresolved_database = database_config_for_resave(store_config) + unresolved_database = store_config # The exception's type, never its text (ITL-1391). logger.warning( "Could not reconstruct the database from its saved config: " @@ -2202,9 +2208,7 @@ def load( result_config ) except Exception as exc: - unresolved_result_database = database_config_for_resave( - result_config - ) + unresolved_result_database = result_config logger.warning( "Could not reconstruct the job's separate result database " "(bindings.result_database) from its saved config (%s): %s. The " diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index bedd22968..05dcdce98 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -568,58 +568,69 @@ def saved_connector_kind(config: Any) -> str | None: return "unknown connector kind" -def _connector_owner_config_for_resave(config: dict[str, Any]) -> dict[str, Any]: - """Ask the connector to clean a config retained by one of its wrappers.""" +def _warn_unknown_resave_block(block: str) -> None: + """Name the retained block without logging its type or values.""" + logger.warning("Saving unknown %s block unchanged. It may hold credentials.", block) + + +def _owned_config_for_resave( + config: dict[str, Any], owner: type | None, block: str +) -> dict[str, Any]: + """Apply the owning class's policy or warn when no owner is available.""" + if owner is None: + _warn_unknown_resave_block(block) + return config + redact = getattr(owner, "config_for_resave", None) + return config if redact is None else redact(config) + + +def connector_owner_config_for_resave(config: dict[str, Any]) -> dict[str, Any]: + """Apply the connector's save policy to the block embedded by a wrapper.""" from orcapod.databases.postgresql_connector import PostgreSQLConnector connector = config.get("connector") - if isinstance(connector, dict) and connector.get("connector_type") == "postgresql": - return { - **config, - "connector": PostgreSQLConnector.config_for_resave( - cast("dict[str, Any]", connector) - ), - } + if not isinstance(connector, dict): + return config + connector = cast("dict[str, Any]", connector) + kind = connector.get("connector_type") + if kind == "postgresql": + return {**config, "connector": PostgreSQLConnector.config_for_resave(connector)} + if kind not in _CONNECTOR_KINDS: + _warn_unknown_resave_block("connector") return config -def database_config_for_resave(config: dict[str, Any]) -> dict[str, Any]: +def database_config_for_resave(config: dict[str, Any], *, block: str) -> dict[str, Any]: """Apply the database's save policy to a retained legacy config.""" - from orcapod.databases.connector_arrow_database import CONNECTOR_DATABASE_TYPE - from orcapod.databases.delta_lake_databases import DeltaTableDatabase + from orcapod.databases.connector_arrow_database import ( + CONNECTOR_DATABASE_TYPE, + ConnectorArrowDatabase, + ) - if config.get("type") == "delta_table": - return DeltaTableDatabase.config_for_resave(config) - if config.get("type") == CONNECTOR_DATABASE_TYPE: - return _connector_owner_config_for_resave(config) - return config + kind = config.get("type") + if kind == "scoped": + return config # A registry reference and path, with no storage settings. + owner = DATABASE_REGISTRY.get(kind) if isinstance(kind, str) else None + if owner is None and kind == CONNECTOR_DATABASE_TYPE: + # The connector is supplied by the caller rather than reconstructed. + owner = ConnectorArrowDatabase + return _owned_config_for_resave(config, owner, block) -def _source_config_for_resave(config: dict[str, Any]) -> dict[str, Any]: - """Apply the wrapped storage's save policy to a retained legacy source config.""" - from orcapod.core.sources.cached_source import CachedSource +def source_config_for_resave(config: dict[str, Any], *, block: str) -> dict[str, Any]: + """Apply the source's save policy to a retained legacy config.""" from orcapod.core.sources.db_table_source import DBTableSource - from orcapod.core.sources.derived_source import DerivedSource - from orcapod.core.sources.postgresql_table_source import PostgreSQLTableSource - from orcapod.databases.postgresql_connector import PostgreSQLConnector + from orcapod.core.sources.polling_source import PollingSource kind = config.get("source_type") - if kind == PostgreSQLTableSource.SOURCE_KIND: - return PostgreSQLConnector.config_for_resave(config) - if kind == DBTableSource.SOURCE_KIND: - return _connector_owner_config_for_resave(config) - if kind in (CachedSource.SOURCE_KIND, DerivedSource.SOURCE_KIND): - config = dict(config) - for key in NESTED_SOURCE_CONFIG_KEYS: - nested = config.get(key) - if isinstance(nested, dict): - config[key] = _source_config_for_resave(cast("dict[str, Any]", nested)) - cache_database = config.get("cache_database") - if kind == CachedSource.SOURCE_KIND and isinstance(cache_database, dict): - config["cache_database"] = database_config_for_resave( - cast("dict[str, Any]", cache_database) - ) - return config + owner = SOURCE_REGISTRY.get(kind) if isinstance(kind, str) else None + if owner is None: + # These built-in source classes can save but cannot be rebuilt. + if kind == DBTableSource.SOURCE_KIND: + owner = DBTableSource + elif kind == PollingSource.SOURCE_KIND: + owner = PollingSource + return _owned_config_for_resave(config, owner, block) def resolve_operator_from_config(config: dict[str, Any]) -> Any: @@ -901,7 +912,7 @@ def _source_proxy_from_config( tag_schema=tag_schema, data_schema=data_schema, expected_class_name=expected_class_name, - source_config=_source_config_for_resave(config), + source_config=config, ) diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index 767f83f03..319d35038 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -470,10 +470,12 @@ def test_legacy_delta_options_load_and_are_scrubbed_on_resave( assert getattr(loaded, slot) is None loaded.save(path) raw = path.read_text() - assert SECRET not in raw - assert json.loads(raw)["bindings"][slot]["storage_options"] == ( - PUBLIC_OPTIONS | dict.fromkeys(PRIVATE_OPTIONS) - ) + for secret in PRIVATE_OPTIONS.values(): + assert secret not in raw + assert json.loads(raw)["bindings"][slot] == { + **data["bindings"][slot], + "storage_options": PUBLIC_OPTIONS | dict.fromkeys(PRIVATE_OPTIONS), + } def test_cached_source_fallback_scrubs_a_legacy_dsn( @@ -498,6 +500,90 @@ def test_cached_source_fallback_scrubs_a_legacy_dsn( assert saved["inner_source"]["dsn"] == source.to_config()["dsn"] +@pytest.mark.parametrize("wrapper", ["table", "generic", "derived", "cached", "delta"]) +def test_resaving_unresolved_legacy_source_omits_credentials( + tmp_path: Path, postgres: MagicMock, wrapper: str +) -> None: + path = tmp_path / "legacy.json" + table = PostgreSQLTableSource(_dsn(), "records", tag_only_columns=True) + source: RootSource = table + if wrapper == "generic": + source = DBTableSource( + PostgreSQLConnector(_dsn()), + "records", + source_id="data", + tag_only_columns=True, + ) + elif wrapper == "derived": + source = DerivedSource(table, tags_as_data={"t1": "copy"}, source_id="derived") + elif wrapper == "cached": + source = CachedSource( + table, cache_database=ConnectorArrowDatabase(PostgreSQLConnector(_dsn())) + ) + elif wrapper == "delta": + source = CachedSource( + table, + cache_database=DeltaTableDatabase( + tmp_path / "cache", storage_options=PUBLIC_OPTIONS | PRIVATE_OPTIONS + ), + ) + expected = _save(path, source)["sources"] + data = json.loads(path.read_text()) + (legacy,) = data["bindings"]["sources"].values() + if wrapper == "generic": + legacy["connector"]["dsn"] = _dsn() + elif wrapper == "derived": + legacy["origin"]["dsn"] = _dsn() + elif wrapper in ("cached", "delta"): + legacy["inner_source"]["dsn"] = _dsn() + if wrapper == "cached": + legacy["cache_database"]["connector"]["dsn"] = _dsn() + else: + legacy["cache_database"]["storage_options"] = ( + PUBLIC_OPTIONS | PRIVATE_OPTIONS + ) + else: + legacy["dsn"] = _dsn() + _ = path.write_text(json.dumps(data)) + + if wrapper == "delta": + # The cache's former directory can no longer be opened. + (tmp_path / "cache").rmdir() + (tmp_path / "cache").touch() + postgres.side_effect = RuntimeError(PASSWORD) + loaded = PipelineJob.load(path) + assert set(loaded.unbound_sources) == set(expected) + target = tmp_path / "resaved.json" + loaded.save(target) + raw = target.read_text() + for secret in (*PRIVATE_OPTIONS.values(), PASSWORD, SSL_PASSWORD): + assert secret not in raw + assert json.loads(raw)["bindings"]["sources"] == expected + + +@pytest.mark.parametrize("slot", ["database", "result_database"]) +def test_resaving_unknown_binding_warns_and_preserves_config( + tmp_path: Path, caplog: pytest.LogCaptureFixture, slot: str +) -> None: + path = tmp_path / "job.json" + _ = _save(path, _arrow_source()) + data = json.loads(path.read_text()) + (name,) = data["bindings"]["sources"] + data["bindings"]["sources"][name]["source_type"] = "unavailable_plugin" + data["bindings"][slot] = {"type": "unavailable_plugin", "option": SECRET} + _ = path.write_text(json.dumps(data)) + loaded = PipelineJob.load(path) + caplog.clear() + loaded.save(path) + bindings = json.loads(path.read_text())["bindings"] + assert bindings["sources"] == data["bindings"]["sources"] + assert bindings[slot] == data["bindings"][slot] + assert f"bindings.sources[{name!r}]" in caplog.text + assert f"bindings.{slot}" in caplog.text + assert caplog.text.count("may hold credentials") == 2 + assert SECRET not in caplog.text + + @pytest.mark.parametrize("slots", [("a", "b"), ("b", "a")]) @pytest.mark.usefixtures("postgres") def test_password_removal_preserves_source_object_consistency( From cb79c8c2392f0ec8667d3e6297e65d6cb4ddd67c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 16:05:59 -0800 Subject: [PATCH 06/20] fix(storage): preserve retained connection settings --- changelog.d/ITL-1394.md | 4 +- docs/dev/design_issues/ITL-1394-JB1.md | 5 + src/orcapod/databases/delta_lake_databases.py | 23 ++-- src/orcapod/databases/postgresql_connector.py | 85 +++++++++--- .../test_postgresql_connector.py | 17 --- .../loaded_job/test_saved_credentials.py | 121 +++++++++++++++++- 6 files changed, 208 insertions(+), 47 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index bafa7b04c..20f03baa0 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -13,4 +13,6 @@ including AWS role identifiers. Saved option URLs omit embedded credentials, and redacted option names survive subsequent saves. - Resaving a legacy job applies the same credential rules to retained source - and database configurations, including nested storage wrappers. + and database configurations, including nested storage wrappers. Credential-free + retained blocks are written back unchanged, and PostgreSQL connection settings + survive a resave without the PostgreSQL extra. diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index 981916ec7..8915bcc15 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -18,3 +18,8 @@ recorded values when loaded, and subsequent saves apply the same storage rules t the retained configs of sources and databases that could not be rebuilt. Unknown config types are retained as saved and trigger a credential warning. The job format version and source identities stay the same. + +Resaving a retained config preserves its spelling and key order when there is +nothing to redact. If psycopg is unavailable, the save removes known secret +parameters from PostgreSQL URI and keyword connection strings while preserving +the connection settings needed to rebuild the source later. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index d663d72d2..007baeeaf 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -3781,10 +3781,11 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: "allow_schema_evolution": self.allow_schema_evolution, } if self._storage_options or self._redacted_storage_option_names: - config["storage_options"] = ( + options = ( dict.fromkeys(self._redacted_storage_option_names) | self._storage_options ) + config["storage_options"] = dict(sorted(options.items())) return self.config_for_resave(config) @classmethod @@ -3792,16 +3793,16 @@ def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: """Apply the storage-option policy to a config, even if it failed to rebuild.""" if "storage_options" not in config: return config - options = config["storage_options"] - if not isinstance(options, dict): - return {**config, "storage_options": None} - return { - **config, - "storage_options": { - name: _saved_storage_option_value(name, value) - for name, value in sorted(cast("dict[str, object]", options).items()) - }, - } + options: object = config["storage_options"] + if isinstance(options, dict): + options = cast("dict[str, object]", options) + for name, value in options.items(): + saved = _saved_storage_option_value(name, value) + if saved is not value: + options[name] = saved + else: + config["storage_options"] = None + return config @classmethod def from_config(cls, config: dict[str, Any]) -> "DeltaTableDatabase": diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 3548967d8..4f05a47bf 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -22,6 +22,7 @@ from collections.abc import Iterator from contextlib import contextmanager from typing import TYPE_CHECKING, Any, cast +from urllib.parse import unquote import pyarrow as pa @@ -394,6 +395,53 @@ def _parse_dsn(dsn: str) -> list[psycopg.pq.ConninfoOption]: raise ProgrammingError("Invalid PostgreSQL connection string.") +# libpq's password parameters through version 18. With psycopg installed, use +# libpq's own classification so later parameters are covered too. +_DSN_SECRET_KEYS = frozenset({"password", "sslpassword", "oauth_client_secret"}) +_CONNINFO_OPTION = re.compile( + r""" + (?P[^=\s]+)\s*=\s* + (?: + '(?:[^'\\]|\\(?:.|\Z))*(?:'|\Z) # Single-quoted value. + | (?!')(?:[^\s\\]|\\(?:.|\Z))* # Unquoted value. + ) + """, + re.ASCII | re.DOTALL | re.VERBOSE, +) + + +def _dsn_without_psycopg(dsn: str) -> str: + """Strip known secrets from a libpq URI or keyword/value connection string.""" + if not dsn.startswith(("postgresql://", "postgres://")): + # Match whole options so a quoted or escaped public value can contain + # any text, including what looks like a separate password parameter. + return _CONNINFO_OPTION.sub( + lambda option: ( + "" if option["key"].lower() in _DSN_SECRET_KEYS else option[0] + ), + dsn, + ) + + scheme, separator, location = dsn.partition("://") + # Like libpq, look for the first @ before the first slash. A raw question + # mark in user info does not start the query. + userinfo, at, _ = location.partition("/")[0].partition("@") + user, _, password = userinfo.partition(":") + prefix = scheme + separator + if at: + prefix += (user if password else userinfo) + at + location = location[len(userinfo) + 1 :] + address, question, query = location.partition("?") + public_query = "&".join( + field + for field in query.split("&") + if unquote(field.partition("=")[0]).lower() not in _DSN_SECRET_KEYS + ) + if public_query or public_query == query: + return prefix + address + question + public_query + return prefix + address + + def _psycopg_server(dsn: str) -> tuple[str, str]: """Return the ``host`` and ``hostaddr`` psycopg reads for ``dsn``, now. @@ -1051,19 +1099,20 @@ def __exit__(self, *args: Any) -> None: def to_config(self) -> dict[str, Any]: """Serialize libpq connection settings with secret parameters omitted.""" - return self.config_for_resave( - {"connector_type": "postgresql", "dsn": self._dsn} - ) + return {"connector_type": "postgresql", "dsn": self._dsn_for_save(self._dsn)} @staticmethod - def _dsn_for_save(dsn: str) -> str: + def _dsn_for_save(dsn: str, *, preserve_clean: bool = False) -> str: """Keep libpq parameters that it does not mark as passwords.""" from psycopg.conninfo import make_conninfo + options = [option for option in _parse_dsn(dsn) if option.val is not None] + if preserve_clean and all(option.dispchar != b"*" for option in options): + return dsn return make_conninfo( **{ option.keyword.decode(): option.val.decode() - for option in _parse_dsn(dsn) + for option in options if option.val is not None and option.dispchar != b"*" } ) @@ -1073,17 +1122,21 @@ def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: """Make a legacy config safe to retain when its connection could not open.""" if "dsn" not in config: return config - dsn = config["dsn"] - if isinstance(dsn, str): - try: - return {**config, "dsn": cls._dsn_for_save(dsn)} - except (ImportError, UnicodeError): - # Handle a missing psycopg before looking up its exception type. - pass - except psycopg.ProgrammingError: - pass - # Without a parseable DSN, a later load needs a new binding. - return {key: value for key, value in config.items() if key != "dsn"} + dsn: object = config["dsn"] + if not isinstance(dsn, str): + del config["dsn"] + return config + try: + saved_dsn = cls._dsn_for_save(dsn, preserve_clean=True) + except ImportError: + # Handle a missing psycopg before looking up its exception type. + saved_dsn = _dsn_without_psycopg(dsn) + except (UnicodeError, psycopg.ProgrammingError): + del config["dsn"] + return config + if saved_dsn != dsn: + config["dsn"] = saved_dsn + return config @classmethod def from_config(cls, config: dict[str, Any]) -> PostgreSQLConnector: diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index da330eaa5..a1e52b875 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -20,7 +20,6 @@ _pg_type_to_arrow, ) from orcapod.protocols.db_connector_protocol import DBConnectorProtocol -from orcapod.utils.lazy_module import LazyModule class TestPgTypeToArrow: @@ -247,22 +246,6 @@ def test_invalid_dsn_error_omits_the_input(self) -> None: assert "password-marker" not in str(failure.value) assert failure.value.__context__ is None - def test_legacy_config_drops_the_dsn_without_the_postgresql_extra(self) -> None: - config = { - "connector_type": "postgresql", - "dsn": "postgresql://user:legacy-marker@localhost/test", - } - with ( - patch.object(PostgreSQLConnector, "_dsn_for_save", side_effect=ImportError), - patch( - "orcapod.databases.postgresql_connector.psycopg", - LazyModule("missing_psycopg_for_test"), - ), - ): - assert PostgreSQLConnector.config_for_resave(config) == { - "connector_type": "postgresql" - } - def test_from_config_reads_legacy_password(self) -> None: with patch("psycopg.connect") as mock_connect: mock_connect.return_value = MagicMock() diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index 319d35038..c4c34bf7a 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -2,8 +2,9 @@ from __future__ import annotations +import builtins import json -from collections.abc import Iterator +from collections.abc import Iterator, Mapping, Sequence from pathlib import Path from typing import Any, cast from unittest.mock import MagicMock, patch @@ -36,6 +37,7 @@ SECRET = "SYNTHETIC-SECRET-123" PASSWORD = "synthetic-postgres-password" SSL_PASSWORD = "synthetic-ssl-password" +CLEAN_DSN = "postgresql://user@localhost:5432/mydb?application_name=app%20name" PUBLIC_OPTIONS = { "AWS_REGION": "us-east-1", "aws_DEFAULT_region": "us-east-2", @@ -472,10 +474,11 @@ def test_legacy_delta_options_load_and_are_scrubbed_on_resave( raw = path.read_text() for secret in PRIVATE_OPTIONS.values(): assert secret not in raw - assert json.loads(raw)["bindings"][slot] == { + expected = { **data["bindings"][slot], "storage_options": PUBLIC_OPTIONS | dict.fromkeys(PRIVATE_OPTIONS), } + assert json.dumps(json.loads(raw)["bindings"][slot]) == json.dumps(expected) def test_cached_source_fallback_scrubs_a_legacy_dsn( @@ -500,6 +503,120 @@ def test_cached_source_fallback_scrubs_a_legacy_dsn( assert saved["inner_source"]["dsn"] == source.to_config()["dsn"] +@pytest.mark.parametrize("binding", ["postgresql", "delta", "nested"]) +def test_resaving_clean_retained_blocks_preserves_saved_bytes( + tmp_path: Path, postgres: MagicMock, binding: str +) -> None: + path = tmp_path / "original.json" + store = tmp_path / "store" + database = DeltaTableDatabase(store, storage_options=PUBLIC_OPTIONS) + source: RootSource + if binding == "delta": + source = _arrow_source() + else: + source = PostgreSQLTableSource(CLEAN_DSN, "records", tag_only_columns=True) + if binding == "nested": + source = CachedSource( + DerivedSource(source, tags_as_data={"t1": "copy"}, source_id="derived"), + cache_database=database, + ) + _ = _save(path, source, database if binding == "delta" else None) + data = json.loads(path.read_text()) + bindings = data["bindings"] + (source_config,) = bindings["sources"].values() + # Use the spelling and insertion order that the legacy writer emitted. + if binding == "postgresql": + source_config["dsn"] = CLEAN_DSN + elif binding == "delta": + bindings["database"]["storage_options"] = PUBLIC_OPTIONS + else: + source_config["inner_source"]["origin"]["dsn"] = CLEAN_DSN + source_config["cache_database"]["storage_options"] = PUBLIC_OPTIONS + _ = path.write_text(json.dumps(data, indent=2)) + + store.rmdir() + store.touch() + postgres.side_effect = RuntimeError("connection unavailable") + loaded = PipelineJob.load(path) + if binding == "delta": + assert loaded.database is None + else: + assert len(loaded.unbound_sources) == 1 + target = tmp_path / "resaved.json" + loaded.save(target) + field = "database" if binding == "delta" else "sources" + assert json.dumps(json.loads(target.read_text())["bindings"][field], indent=2) == ( + json.dumps(bindings[field], indent=2) + ) + + +@pytest.mark.parametrize( + ("legacy_dsn", "saved_dsn"), + [ + pytest.param(CLEAN_DSN, CLEAN_DSN, id="clean-uri"), + pytest.param( + " host = localhost application_name='password=public label' user=user", + " host = localhost application_name='password=public label' user=user", + id="clean-conninfo", + ), + pytest.param( + "postgres://u%3As:secret%2Fword@localhost:5432/mydb?" + "application_name=app%20name&%70assword=query-secret&" + "%73slpassword=ssl-secret&connect_timeout=3", + "postgres://u%3As@localhost:5432/mydb?" + "application_name=app%20name&connect_timeout=3", + id="credential-uri", + ), + pytest.param( + "host=localhost password = 'secret\\' word' " + "application_name='password=public label' sslpassword=ssl\\ secret " + "user=user password=''oauth_client_secret='oauth marker'", + "host=localhost application_name='password=public label' user=user ", + id="credential-conninfo", + ), + ], +) +def test_resaving_without_postgresql_extra_keeps_rebuildable_dsn( + tmp_path: Path, + postgres: MagicMock, + monkeypatch: pytest.MonkeyPatch, + legacy_dsn: str, + saved_dsn: str, +) -> None: + path = tmp_path / "original.json" + source = PostgreSQLTableSource(CLEAN_DSN, "records", tag_only_columns=True) + _ = _save(path, source) + data = json.loads(path.read_text()) + (slot,) = data["bindings"]["sources"] + data["bindings"]["sources"][slot]["dsn"] = legacy_dsn + _ = path.write_text(json.dumps(data)) + original_import = builtins.__import__ + + def without_psycopg( + name: str, + globals: Mapping[str, object] | None = None, + locals: Mapping[str, object] | None = None, + fromlist: Sequence[str] = (), + level: int = 0, + ) -> object: + if name == "psycopg" or name.startswith("psycopg."): + raise ModuleNotFoundError(name=name) + return original_import(name, globals, locals, fromlist, level) + + target = tmp_path / "resaved.json" + with monkeypatch.context() as scoped: + scoped.setattr(builtins, "__import__", without_psycopg) + loaded = PipelineJob.load(path) + assert loaded.unbound_sources == [slot] + loaded.save(target) + + actual = json.loads(target.read_text())["bindings"]["sources"][slot]["dsn"] + assert actual == saved_dsn + restored = PipelineJob.load(target) + assert list(restored.sources) == [slot] + postgres.assert_called_with(saved_dsn, autocommit=False) + + @pytest.mark.parametrize("wrapper", ["table", "generic", "derived", "cached", "delta"]) def test_resaving_unresolved_legacy_source_omits_credentials( tmp_path: Path, postgres: MagicMock, wrapper: str From d8a8d20a252dd518e6759ade67a4ae76fab4277b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 17:08:04 -0800 Subject: [PATCH 07/20] fix(postgresql): preserve newer DSN options when saving jobs --- changelog.d/ITL-1394.md | 5 +- docs/dev/design_issues/ITL-1394-JB1.md | 13 +- src/orcapod/databases/postgresql_connector.py | 138 +++++++++++------- .../test_postgresql_connector.py | 62 ++++++-- .../loaded_job/test_saved_credentials.py | 73 +++++++++ 5 files changed, 215 insertions(+), 76 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index 20f03baa0..75626a685 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -14,5 +14,6 @@ redacted option names survive subsequent saves. - Resaving a legacy job applies the same credential rules to retained source and database configurations, including nested storage wrappers. Credential-free - retained blocks are written back unchanged, and PostgreSQL connection settings - survive a resave without the PostgreSQL extra. + retained blocks are written back unchanged. PostgreSQL connection settings keep + their original spelling and survive a resave with an older libpq or without + the PostgreSQL extra. diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index 8915bcc15..e74bf02dd 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -12,14 +12,15 @@ strings. Saving a job exposes those values in plain text, including in wrapped c **Fix:** Delta saves option names and the values of recognized non-credential S3, Azure, and GCS options, including AWS role identifiers. It removes user info and credential query parameters from saved option URLs and retains redacted names across saves. -The PostgreSQL connector omits parameters marked as passwords by libpq, including -when its config is embedded in a source or database. Older files still use their -recorded values when loaded, and subsequent saves apply the same storage rules to +The PostgreSQL connector omits `password`, `sslpassword`, `oauth_client_secret`, +and URI userinfo passwords, including when its config is embedded in a source or +database. Older files still use their recorded values when loaded, and subsequent +saves apply the same storage rules to the retained configs of sources and databases that could not be rebuilt. Unknown config types are retained as saved and trigger a credential warning. The job format version and source identities stay the same. Resaving a retained config preserves its spelling and key order when there is -nothing to redact. If psycopg is unavailable, the save removes known secret -parameters from PostgreSQL URI and keyword connection strings while preserving -the connection settings needed to rebuild the source later. +nothing to redact. Fresh saves and resaves preserve the original text of +non-secret PostgreSQL options, including options the installed libpq does not +recognize. Redaction works without psycopg. diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 4f05a47bf..92b7af7e0 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -395,53 +395,101 @@ def _parse_dsn(dsn: str) -> list[psycopg.pq.ConninfoOption]: raise ProgrammingError("Invalid PostgreSQL connection string.") -# libpq's password parameters through version 18. With psycopg installed, use -# libpq's own classification so later parameters are covered too. +# Secret parameters through libpq 18. Saving must also work with older libpq +# versions that reject newer non-secret options, or without psycopg installed. _DSN_SECRET_KEYS = frozenset({"password", "sslpassword", "oauth_client_secret"}) _CONNINFO_OPTION = re.compile( r""" - (?P[^=\s]+)\s*=\s* - (?: - '(?:[^'\\]|\\(?:.|\Z))*(?:'|\Z) # Single-quoted value. - | (?!')(?:[^\s\\]|\\(?:.|\Z))* # Unquoted value. + \s*(?: + (?P[a-zA-Z_][a-zA-Z_0-9-]*)\s*=\s* + (?: + '(?:[^'\\]|\\.)*' # Single-quoted value. + | (?!')(?:[^\s\\]|\\(?:.|\Z))*(?=\s|\Z) # Unquoted value. + ) + | \Z ) """, re.ASCII | re.DOTALL | re.VERBOSE, ) - - -def _dsn_without_psycopg(dsn: str) -> str: - """Strip known secrets from a libpq URI or keyword/value connection string.""" - if not dsn.startswith(("postgresql://", "postgres://")): - # Match whole options so a quoted or escaped public value can contain - # any text, including what looks like a separate password parameter. - return _CONNINFO_OPTION.sub( - lambda option: ( - "" if option["key"].lower() in _DSN_SECRET_KEYS else option[0] - ), - dsn, - ) - +_MALFORMED_URI_ESCAPE = re.compile(r"%(?:00|(?![0-9a-fA-F]{2}))") + + +def _redact_conninfo(dsn: str) -> str | None: + """Remove secret keyword/value options, or return None on invalid syntax.""" + parts: list[str] = [] + offset = kept_from = 0 + while offset < len(dsn): + option = _CONNINFO_OPTION.match(dsn, offset) + if option is None: + return None + offset = option.end() + key = option["key"] + if key is not None and key.lower() in _DSN_SECRET_KEYS: + parts.append(dsn[kept_from : option.start("key")]) + kept_from = offset + parts.append(dsn[kept_from:]) + return "".join(parts) + + +def _redact_dsn_uri(dsn: str) -> str | None: + """Remove secrets from URI user info and query fields, preserving their encoding.""" + if _MALFORMED_URI_ESCAPE.search(dsn): + return None scheme, separator, location = dsn.partition("://") # Like libpq, look for the first @ before the first slash. A raw question # mark in user info does not start the query. userinfo, at, _ = location.partition("/")[0].partition("@") - user, _, password = userinfo.partition(":") prefix = scheme + separator if at: - prefix += (user if password else userinfo) + at + prefix += userinfo.partition(":")[0] + at location = location[len(userinfo) + 1 :] address, question, query = location.partition("?") - public_query = "&".join( - field - for field in query.split("&") - if unquote(field.partition("=")[0]).lower() not in _DSN_SECRET_KEYS - ) - if public_query or public_query == query: - return prefix + address + question + public_query + fields = query.removesuffix("&").split("&") if query else [] + public_fields: list[str] = [] + for field in fields: + name, equals, value = field.partition("=") + if not equals or "=" in value: + return None + # libpq trims raw whitespace before decoding URI query parameter names. + if unquote(name.strip(" \t\n\r\v\f")).lower() not in _DSN_SECRET_KEYS: + public_fields.append(field) + if len(public_fields) == len(fields): + return prefix + address + question + query + if public_fields: + trailing_separator = "&" if query.endswith("&") else "" + return ( + prefix + address + question + "&".join(public_fields) + trailing_separator + ) return prefix + address +def _dsn_for_save(dsn: str) -> str | None: + """Remove connection secrets without validating options against installed libpq.""" + redacted = None + if "\0" not in dsn: + if dsn.startswith(("postgresql://", "postgres://")): + redacted = _redact_dsn_uri(dsn) + else: + redacted = _redact_conninfo(dsn) + if redacted is not None: + return redacted + + # If token boundaries are unclear, omit a potentially secret DSN without + # logging its text. Keep malformed strings that show no sign of credentials. + decoded = unquote(dsn).lower() + before_at, at, _ = decoded.partition("@") + if ( + "password" not in decoded + and "oauth_client_secret" not in decoded + and not (at and ":" in before_at) + ): + return dsn + logger.warning( + "Omitting malformed PostgreSQL connection string that may contain credentials." + ) + return None + + def _psycopg_server(dsn: str) -> tuple[str, str]: """Return the ``host`` and ``hostaddr`` psycopg reads for ``dsn``, now. @@ -1099,22 +1147,8 @@ def __exit__(self, *args: Any) -> None: def to_config(self) -> dict[str, Any]: """Serialize libpq connection settings with secret parameters omitted.""" - return {"connector_type": "postgresql", "dsn": self._dsn_for_save(self._dsn)} - - @staticmethod - def _dsn_for_save(dsn: str, *, preserve_clean: bool = False) -> str: - """Keep libpq parameters that it does not mark as passwords.""" - from psycopg.conninfo import make_conninfo - - options = [option for option in _parse_dsn(dsn) if option.val is not None] - if preserve_clean and all(option.dispchar != b"*" for option in options): - return dsn - return make_conninfo( - **{ - option.keyword.decode(): option.val.decode() - for option in options - if option.val is not None and option.dispchar != b"*" - } + return self.config_for_resave( + {"connector_type": "postgresql", "dsn": self._dsn} ) @classmethod @@ -1123,18 +1157,10 @@ def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: if "dsn" not in config: return config dsn: object = config["dsn"] - if not isinstance(dsn, str): + saved_dsn = _dsn_for_save(dsn) if isinstance(dsn, str) else None + if saved_dsn is None: del config["dsn"] - return config - try: - saved_dsn = cls._dsn_for_save(dsn, preserve_clean=True) - except ImportError: - # Handle a missing psycopg before looking up its exception type. - saved_dsn = _dsn_without_psycopg(dsn) - except (UnicodeError, psycopg.ProgrammingError): - del config["dsn"] - return config - if saved_dsn != dsn: + elif saved_dsn != dsn: config["dsn"] = saved_dsn return config diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index a1e52b875..67035d778 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -199,26 +199,44 @@ def test_isinstance_dbconnector_protocol(self) -> None: class TestConfig: @pytest.mark.parametrize( - "dsn", + ("dsn", "saved_dsn"), [ - "postgresql://user:s%40fe@localhost:5432/mydb?" - "sslpassword=ssl-marker&passfile=%2Ftmp%2Ftest.pgpass", - "sslpassword=ssl-marker dbname=mydb password='s@fe' port=5432 " - "passfile=/tmp/test.pgpass user=user host=localhost", + ( + "postgresql://u%3Aser:s%40fe@localhost:5432/mydb?" + "application_name=my%20app&%73slpassword=ssl-marker&password =query%26secret" + "&passfile=%2Ftmp%2Ftest.pgpass", + "postgresql://u%3Aser@localhost:5432/mydb?" + "application_name=my%20app&passfile=%2Ftmp%2Ftest.pgpass", + ), + ( + " sslpassword=ssl\\ marker dbname = mydb password='s\\' afe' port=5432 " + "passfile=/tmp/test.pgpass user=user host=localhost ", + " dbname = mydb port=5432 passfile=/tmp/test.pgpass " + "user=user host=localhost ", + ), + ("postgres://user:@localhost?password=", "postgres://user@localhost"), + ( + "postgres://localhost/mydb?application_name=my%20app", + "postgres://localhost/mydb?application_name=my%20app", + ), + ( + " host = localhost application_name='password=public label' ", + " host = localhost application_name='password=public label' ", + ), ], ) - def test_to_config(self, dsn: str) -> None: + def test_to_config(self, dsn: str, saved_dsn: str) -> None: with patch("psycopg.connect") as mock_connect: mock_connect.return_value = MagicMock() connector = PostgreSQLConnector(dsn) config = connector.to_config() assert config["connector_type"] == "postgresql" - assert conninfo_to_dict(config["dsn"]) == { - "user": "user", - "host": "localhost", - "port": "5432", - "dbname": "mydb", - "passfile": "/tmp/test.pgpass", + assert config["dsn"] == saved_dsn + options = conninfo_to_dict(dsn) + assert conninfo_to_dict(saved_dsn) == { + key: value + for key, value in options.items() + if key not in {"password", "sslpassword"} } mock_connect.assert_called_once_with(dsn, autocommit=False) mock_connect.reset_mock() @@ -228,6 +246,26 @@ def test_to_config(self, dsn: str) -> None: connector._conn = None rebuilt._conn = None + @pytest.mark.parametrize( + ("dsn", "keep"), + [ + ("host=localhost application_name='broken", True), + ("host=localhost password='fixture-secret", False), + ("postgresq://user:fixture-secret@localhost/db", False), + ("postgres://localhost/db?broken&%70assword=fixture-secret", False), + ], + ) + def test_config_for_resave_handles_malformed_dsn( + self, dsn: str, keep: bool, caplog: pytest.LogCaptureFixture + ) -> None: + saved = PostgreSQLConnector.config_for_resave({"dsn": dsn}) + if keep: + assert saved["dsn"] == dsn + else: + assert "dsn" not in saved + assert "malformed PostgreSQL connection string" in caplog.text + assert "fixture-secret" not in caplog.text + @pytest.mark.skipif(psycopg.pq.version() < 180000, reason="libpq 18 adds OAuth") def test_to_config_omits_oauth_client_secret(self) -> None: dsn = "host=localhost oauth_client_id=client oauth_client_secret=oauth-marker" diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index c4c34bf7a..89fd5f5c3 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -10,6 +10,7 @@ from unittest.mock import MagicMock, patch import pyarrow as pa +import psycopg import pytest from deltalake.exceptions import TableNotFoundError from deltalake.fs import DeltaStorageHandler @@ -24,6 +25,7 @@ DeltaTableDatabase, PostgreSQLConnector, ) +from orcapod.databases import postgresql_connector from orcapod.databases.storage_utils import parse_base_path from orcapod.errors import InconsistentSourceError from orcapod.protocols.database_protocols import ArrowDatabaseProtocol @@ -617,6 +619,77 @@ def without_psycopg( postgres.assert_called_with(saved_dsn, autocommit=False) +@pytest.mark.parametrize( + ("dsn", "saved_dsn"), + [ + pytest.param( + " host = localhost sslmode=require sslnegotiation=direct ", + " host = localhost sslmode=require sslnegotiation=direct ", + id="clean-conninfo", + ), + pytest.param( + "postgresql://u%3As@localhost/mydb?sslmode=require&sslnegotiation=direct", + "postgresql://u%3As@localhost/mydb?sslmode=require&sslnegotiation=direct", + id="clean-uri", + ), + pytest.param( + "host=localhost password='secret\\' word' sslmode=require sslnegotiation=direct", + "host=localhost sslmode=require sslnegotiation=direct", + id="credential-conninfo", + ), + pytest.param( + "postgresql://u%3As:secret%2Fword@localhost/mydb?" + "sslmode=require&%70assword=query-secret&sslnegotiation=direct", + "postgresql://u%3As@localhost/mydb?sslmode=require&sslnegotiation=direct", + id="credential-uri", + ), + ], +) +def test_resaving_with_older_libpq_keeps_rebuildable_dsn( + tmp_path: Path, + postgres: MagicMock, + monkeypatch: pytest.MonkeyPatch, + dsn: str, + saved_dsn: str, +) -> None: + original_parse = postgresql_connector._parse_dsn + + def modern_parse(conninfo: str) -> list[psycopg.pq.ConninfoOption]: + # Allow the newer option even on test installations with older libpq. + compatible = conninfo.replace("&sslnegotiation=direct", "").replace( + " sslnegotiation=direct", "" + ) + return original_parse(compatible) + + def older_parse(conninfo: str) -> list[psycopg.pq.ConninfoOption]: + if "sslnegotiation=direct" in conninfo: + raise psycopg.ProgrammingError("Invalid PostgreSQL connection string.") + return original_parse(conninfo) + + monkeypatch.setattr(postgresql_connector, "_parse_dsn", modern_parse) + path = tmp_path / "original.json" + source = PostgreSQLTableSource(CLEAN_DSN, "records", tag_only_columns=True) + _ = _save(path, source) + data = json.loads(path.read_text()) + (slot,) = data["bindings"]["sources"] + data["bindings"]["sources"][slot]["dsn"] = dsn + _ = path.write_text(json.dumps(data)) + + target = tmp_path / "resaved.json" + with monkeypatch.context() as scoped: + scoped.setattr(postgresql_connector, "_parse_dsn", older_parse) + loaded = PipelineJob.load(path) + assert loaded.unbound_sources == [slot] + loaded.save(target) + + assert ( + json.loads(target.read_text())["bindings"]["sources"][slot]["dsn"] == saved_dsn + ) + restored = PipelineJob.load(target) + assert list(restored.sources) == [slot] + postgres.assert_called_with(saved_dsn, autocommit=False) + + @pytest.mark.parametrize("wrapper", ["table", "generic", "derived", "cached", "delta"]) def test_resaving_unresolved_legacy_source_omits_credentials( tmp_path: Path, postgres: MagicMock, wrapper: str From 92265044d4c0cddbe9b6dc046f09e90ee7da2241 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:01:56 -0800 Subject: [PATCH 08/20] fix(storage): preserve non-URL Delta option values --- changelog.d/ITL-1394.md | 5 +- docs/concepts/pipeline-job.md | 5 +- docs/dev/design_issues/ITL-1394-JB1.md | 3 +- src/orcapod/databases/delta_lake_databases.py | 94 +++++++++++-------- .../loaded_job/test_saved_credentials.py | 37 +++++++- 5 files changed, 99 insertions(+), 45 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index 75626a685..5e0effef1 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -10,8 +10,9 @@ - Delta databases, PostgreSQL connectors and the sources that wrap them keep credentials out of newly saved job files. Earlier files still load with their recorded settings. - Saved Delta databases retain supported non-credential settings for S3, Azure, and GCS, - including AWS role identifiers. Saved option URLs omit embedded credentials, and - redacted option names survive subsequent saves. + including AWS role identifiers. URL-valued options omit embedded credentials. + Other supported settings keep their original text, and redacted option names + survive subsequent saves. - Resaving a legacy job applies the same credential rules to retained source and database configurations, including nested storage wrappers. Credential-free retained blocks are written back unchanged. PostgreSQL connection settings keep diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 72611e256..05a3cb643 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -533,8 +533,9 @@ the **Nodes** table below the picture for each node's columns and status. The file holds no credentials for Orcapod's built-in storage and sources. Delta database configs keep option names and supported non-credential settings for S3, Azure, and GCS, including account names, regions, endpoints, HTTP client options, and AWS role settings -such as the role ARN, session name, and web identity token file path. Saved option URLs -omit user info and credential query parameters, including SAS signatures. +such as the role ARN, session name, and web identity token file path. URL-valued options, +such as endpoints and proxies, omit user info and credential query parameters, including +SAS signatures. Other supported option values are saved verbatim. Omitted option values are written as JSON `null` and stay that way when a loaded job is saved again. PostgreSQL configs keep connection settings such as the host and password-file path and omit passwords. A user-written diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index e74bf02dd..7d748a8b6 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -11,7 +11,8 @@ strings. Saving a job exposes those values in plain text, including in wrapped c **Fix:** Delta saves option names and the values of recognized non-credential S3, Azure, and GCS options, including AWS role identifiers. It removes user info and -credential query parameters from saved option URLs and retains redacted names across saves. +credential query parameters from URL-valued options, preserves other supported option +values verbatim, and retains redacted names across saves. The PostgreSQL connector omits `password`, `sslpassword`, `oauth_client_secret`, and URI userinfo passwords, including when its config is embedded in a source or database. Older files still use their recorded values when loaded, and subsequent diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 007baeeaf..e58463d51 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1824,16 +1824,51 @@ class _CommittedSnapshot: } ) +# URL-valued endpoints and proxies may embed credentials in their authority or query. +_PROXY_URL_OPTION_KEYS = frozenset( + {prefix + "proxy_url" for prefix in ("", "aws_", "azure_", "google_")} +) +_RELATIVE_URL_OPTION_KEYS = frozenset( + {"container_credentials_relative_uri", "aws_container_credentials_relative_uri"} +) +_URL_STORAGE_OPTION_KEYS = ( + _PROXY_URL_OPTION_KEYS + | _RELATIVE_URL_OPTION_KEYS + | { + prefix + key + for prefix in ("", "aws_") + for key in ( + "container_credentials_full_uri", + "endpoint", + "endpoint_url", + "endpoint_url_sts", + "metadata_endpoint", + ) + } + | { + "aws_endpoint_url_s3", + "azure_storage_endpoint", + "azure_endpoint", + "azure_storage_authority_host", + "azure_authority_host", + "authority_host", + "azure_msi_endpoint", + "azure_identity_endpoint", + "identity_endpoint", + "msi_endpoint", + "azure_fabric_token_service_url", + "fabric_token_service_url", + "google_base_url", + "base_url", + } +) + # Keep recognized identifiers, routing and behavior settings so the store can be reopened. # Spellings come from object_store 0.13.2's S3, Azure, GCS and HTTP client key parsers # and Delta Lake's storage configuration. Unknown keys have their values dropped. _SAVED_STORAGE_OPTION_VALUES = ( frozenset( { - # S3 spellings with no simple prefixed/unprefixed pair. - "aws_endpoint_url", - "endpoint_url", - "aws_endpoint_url_s3", # Azure. "account_name", "azure_storage_account_name", @@ -1846,17 +1881,8 @@ class _CommittedSnapshot: "azure_authority_id", "tenant_id", "authority_id", - "azure_storage_authority_host", - "azure_authority_host", - "authority_host", "azure_storage_use_emulator", "use_emulator", - "azure_storage_endpoint", - "azure_endpoint", - "azure_msi_endpoint", - "azure_identity_endpoint", - "identity_endpoint", - "msi_endpoint", "azure_object_id", "object_id", "azure_msi_resource_id", @@ -1869,8 +1895,6 @@ class _CommittedSnapshot: "azure_container_name", "container_name", "azure_disable_tagging", - "azure_fabric_token_service_url", - "fabric_token_service_url", "azure_fabric_workload_host", "fabric_workload_host", "azure_fabric_cluster_identifier", @@ -1878,8 +1902,6 @@ class _CommittedSnapshot: # GCS. "google_bucket", "google_bucket_name", - "google_base_url", - "base_url", "google_skip_signature", # Delta Lake options outside the object_store key parsers. "aws_force_credential_load", @@ -1911,15 +1933,10 @@ class _CommittedSnapshot: "bucket_name", "checksum_algorithm", "conditional_put", - "container_credentials_full_uri", - "container_credentials_relative_uri", "copy_if_not_exists", "default_region", "disable_tagging", - "endpoint", - "endpoint_url_sts", "imdsv1_fallback", - "metadata_endpoint", "region", "request_payer", "role_arn", @@ -1950,7 +1967,6 @@ class _CommittedSnapshot: "http2_max_frame_size", "pool_idle_timeout", "pool_max_idle_per_host", - "proxy_url", "proxy_ca_certificate", "proxy_excludes", "randomize_addresses", @@ -1959,14 +1975,8 @@ class _CommittedSnapshot: ) } ) - - _CREDENTIAL_STORAGE_OPTION_KEYS -) -_PROXY_URL_OPTION_KEYS = frozenset( - {"proxy_url", "aws_proxy_url", "azure_proxy_url", "google_proxy_url"} -) -_RELATIVE_URL_OPTION_KEYS = frozenset( - {"container_credentials_relative_uri", "aws_container_credentials_relative_uri"} -) + | _URL_STORAGE_OPTION_KEYS +) - _CREDENTIAL_STORAGE_OPTION_KEYS _CREDENTIAL_URL_QUERY_KEYS = _CREDENTIAL_STORAGE_OPTION_KEYS | frozenset( { "access_token", @@ -2000,22 +2010,23 @@ class _CommittedSnapshot: def _saved_storage_option_value(key: str, value: object) -> object: """Keep recognized settings and strip credentials from URL values.""" - key = key.lower() if key not in _SAVED_STORAGE_OPTION_VALUES: return None - if not isinstance(value, str): + if key not in _URL_STORAGE_OPTION_KEYS or value is None: return value + if not isinstance(value, str): + return None - has_scheme = "://" in value or bool( - re.match(r"^(?:https?|socks[45][ah]?):", value, re.IGNORECASE) + has_scheme = bool( + re.match( + r"^(?:[a-z][a-z0-9+.-]*://|https?:|socks[45][ah]?:)", value, re.IGNORECASE + ) ) has_authority = value.startswith("//") proxy_without_scheme = ( key in _PROXY_URL_OPTION_KEYS and not has_scheme and not has_authority ) - expects_host = has_scheme or has_authority or proxy_without_scheme - if not expects_host and key not in _RELATIVE_URL_OPTION_KEYS: - return value + expects_host = has_scheme or has_authority or key not in _RELATIVE_URL_OPTION_KEYS try: url = urlsplit(f"//{value}" if proxy_without_scheme else value) # Accessing the port validates its syntax and range. @@ -3797,8 +3808,13 @@ def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: if isinstance(options, dict): options = cast("dict[str, object]", options) for name, value in options.items(): - saved = _saved_storage_option_value(name, value) + key = name.lower() + saved = _saved_storage_option_value(key, value) if saved is not value: + if saved is None and key in _URL_STORAGE_OPTION_KEYS: + logger.warning( + "Omitted malformed Delta storage option URL for %s", name + ) options[name] = saved else: config["storage_options"] = None diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index 89fd5f5c3..f3039e274 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -26,6 +26,10 @@ PostgreSQLConnector, ) from orcapod.databases import postgresql_connector +from orcapod.databases.delta_lake_databases import ( + _SAVED_STORAGE_OPTION_VALUES, + _URL_STORAGE_OPTION_KEYS, +) from orcapod.databases.storage_utils import parse_base_path from orcapod.errors import InconsistentSourceError from orcapod.protocols.database_protocols import ArrowDatabaseProtocol @@ -289,9 +293,35 @@ def open_table(table_uri: str, storage_options: dict[str, str]) -> None: open_delta.assert_called_once() +@pytest.mark.parametrize( + "uri", ["s3://fixtures/data", "az://fixtures/data", "gs://fixtures/data"] +) +@pytest.mark.parametrize( + "key", sorted(_SAVED_STORAGE_OPTION_VALUES - _URL_STORAGE_OPTION_KEYS) +) +def test_delta_non_url_options_preserve_text( + tmp_path: Path, uri: str, key: str +) -> None: + value = "fixture-loader/1.0 (+https://example.test/project?sig=example; ops@example.test)" + public = {key: value} + path = tmp_path / "job.json" + bindings = _save( + path, _arrow_source(), DeltaTableDatabase(uri, public | PRIVATE_OPTIONS) + ) + assert bindings["database"]["storage_options"] == public | dict.fromkeys( + PRIVATE_OPTIONS + ) + assert SECRET not in path.read_text() + loaded = PipelineJob.load(path).database + assert isinstance(loaded, DeltaTableDatabase) + with patch("deltalake.DeltaTable", side_effect=TableNotFoundError) as open_table: + assert not loaded.table_exists(("table",)) + open_table.assert_called_once_with(f"{uri}/table", storage_options=public) + + @pytest.mark.parametrize("reverse", [False, True]) def test_delta_saved_urls_strip_credentials_and_keep_routing( - tmp_path: Path, reverse: bool + tmp_path: Path, caplog: pytest.LogCaptureFixture, reverse: bool ) -> None: uri = "az://fixtures/data" public = { @@ -329,6 +359,11 @@ def test_delta_saved_urls_strip_credentials_and_keep_routing( assert bindings["database"]["storage_options"] == public | { "azure_authority_host": None, } + assert ( + "Omitted malformed Delta storage option URL for azure_authority_host" + in caplog.text + ) + assert SECRET not in caplog.text loaded = PipelineJob.load(path).database assert isinstance(loaded, DeltaTableDatabase) with patch("deltalake.DeltaTable", side_effect=TableNotFoundError) as open_table: From 365f8b36f33a9c36a567e2c449ac9c5f0ba9e4d4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:52:00 -0800 Subject: [PATCH 09/20] fix(storage): simplify saved credential handling --- changelog.d/ITL-1394.md | 21 +- docs/concepts/pipeline-job.md | 22 +- docs/dev/design_issues/ITL-1394-JB1.md | 24 +- src/orcapod/databases/delta_lake_databases.py | 267 +++----------- src/orcapod/databases/postgresql_connector.py | 127 ++----- .../test_delta_table_database_s3.py | 4 +- .../test_postgresql_connector.py | 57 +-- .../loaded_job/test_saved_credentials.py | 346 +++++++++--------- 8 files changed, 295 insertions(+), 573 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index 5e0effef1..6b230d83b 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -1,20 +1,21 @@ ### Breaking changes and migration -- Saved job files omit Delta credential values and passwords in PostgreSQL connection - strings. Provide credentials through the storage backend's environment or credential +- Saved job files omit known Delta credential options and secret PostgreSQL connection + parameters. Provide credentials through the storage backend's environment or credential provider, pass the configured database to `PipelineJob.load()`, or bind a source that could not be rebuilt with `job.bind(sources=...)`. +- Saving now refuses Delta URLs with embedded credentials, including URLs that + previously saved with those fields removed. Remove the credential from the URL + and supply it through the environment or a dedicated storage option. +- Saving PostgreSQL bindings requires psycopg and a libpq version that understands + the connection string. Install a compatible version or supply a valid connection string. ### Fixed - Delta databases, PostgreSQL connectors and the sources that wrap them keep credentials out of newly saved job files. Earlier files still load with their recorded settings. -- Saved Delta databases retain supported non-credential settings for S3, Azure, and GCS, - including AWS role identifiers. URL-valued options omit embedded credentials. - Other supported settings keep their original text, and redacted option names - survive subsequent saves. +- Saved Delta databases retain other option values verbatim, including endpoints, + regions, and AWS role identifiers. - Resaving a legacy job applies the same credential rules to retained source - and database configurations, including nested storage wrappers. Credential-free - retained blocks are written back unchanged. PostgreSQL connection settings keep - their original spelling and survive a resave with an older libpq or without - the PostgreSQL extra. + and database configurations, including nested storage wrappers. PostgreSQL uses + psycopg to serialize the remaining connection settings. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 56420b9f9..d06a9e58e 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -546,21 +546,21 @@ the **Nodes** table below the picture for each node's columns and status. ## Saving and loading `job.save(path)` writes the graph, database locations and source settings to a JSON file. -The file holds no credentials for Orcapod's built-in storage and sources. Delta database -configs keep option names and supported non-credential settings for S3, Azure, and GCS, -including account names, regions, endpoints, HTTP client options, and AWS role settings -such as the role ARN, session name, and web identity token file path. URL-valued options, -such as endpoints and proxies, omit user info and credential query parameters, including -SAS signatures. Other supported option values are saved verbatim. -Omitted option values are written as JSON `null` and stay that way when a loaded job -is saved again. PostgreSQL configs keep connection settings such as the host and -password-file path and omit passwords. A user-written +Delta omits its known credential options and saves all other option values verbatim. +Keep credentials in the backend's dedicated credential options or environment. Saving +refuses a Delta storage root, endpoint or proxy URL with an embedded password or a +known credential query parameter, such as a SAS signature. To save the job, remove the +embedded credential from the URL and supply it separately. + +PostgreSQL uses psycopg to parse the connection string, omit secret parameters and +serialize the remaining settings, including any password-file path. Saving requires +psycopg with a libpq version that understands the connection string. A user-written `PollingSource` implementer is responsible for keeping credentials out of its `to_config()` return value. `PipelineJob.load(path)` reads the job back, for example in a later Python session. -Storage backends that rebuild from the file can obtain credentials from the environment -or their usual credential providers, such as a PostgreSQL password file. Supply a +Supply omitted credentials again through the backend's environment or its usual +credential provider, such as a PostgreSQL password file. Supply a database explicitly with `PipelineJob.load(path, database=...)` or `PipelineJob.load(path, result_database=...)` when it needs explicit credentials or has moved. For a connector database (SQLite, PostgreSQL, SpiralDB), always pass the database diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index 7d748a8b6..311549f53 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -9,19 +9,11 @@ Delta database configs can contain credentials supplied directly or through a UP PostgreSQL connector and table source configs can contain passwords in connection strings. Saving a job exposes those values in plain text, including in wrapped configs. -**Fix:** Delta saves option names and the values of recognized non-credential -S3, Azure, and GCS options, including AWS role identifiers. It removes user info and -credential query parameters from URL-valued options, preserves other supported option -values verbatim, and retains redacted names across saves. -The PostgreSQL connector omits `password`, `sslpassword`, `oauth_client_secret`, -and URI userinfo passwords, including when its config is embedded in a source or -database. Older files still use their recorded values when loaded, and subsequent -saves apply the same storage rules to -the retained configs of sources and databases that could not be rebuilt. Unknown -config types are retained as saved and trigger a credential warning. The job -format version and source identities stay the same. - -Resaving a retained config preserves its spelling and key order when there is -nothing to redact. Fresh saves and resaves preserve the original text of -non-secret PostgreSQL options, including options the installed libpq does not -recognize. Redaction works without psycopg. +**Fix:** Delta omits known credential options, preserves other values verbatim, +and refuses a root or endpoint URL with an embedded password or known credential +query parameter. The PostgreSQL connector parses and serializes connection strings +with psycopg, omitting `password`, `sslpassword`, and `oauth_client_secret`. It +refuses to save a connection string that psycopg cannot parse. Older files still +load their recorded values. Subsequent saves apply the same storage rules to +retained configs, including nested bindings. Unknown config types are retained +as saved and trigger a credential warning. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 68bc0c02b..816fe62f0 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -13,7 +13,7 @@ from pathlib import Path from time import sleep from typing import TYPE_CHECKING, Any, BinaryIO, Literal, cast -from urllib.parse import unquote_plus, urlsplit, urlunsplit +from urllib.parse import unquote_plus import polars as pl import pyarrow as pa @@ -1821,7 +1821,7 @@ class _CommittedSnapshot: dataset_filesystem: "pa_fs.FileSystem | None" = None -# Credential material and credential-file settings outside the save policy. +# Option keys that carry credentials or point to credential material. _CREDENTIAL_STORAGE_OPTION_KEYS = frozenset( { "access_key", @@ -1874,20 +1874,14 @@ class _CommittedSnapshot: ) # URL-valued endpoints and proxies may embed credentials in their authority or query. -_PROXY_URL_OPTION_KEYS = frozenset( - {prefix + "proxy_url" for prefix in ("", "aws_", "azure_", "google_")} -) -_RELATIVE_URL_OPTION_KEYS = frozenset( - {"container_credentials_relative_uri", "aws_container_credentials_relative_uri"} -) _URL_STORAGE_OPTION_KEYS = ( - _PROXY_URL_OPTION_KEYS - | _RELATIVE_URL_OPTION_KEYS + {prefix + "proxy_url" for prefix in ("", "aws_", "azure_", "google_")} | { prefix + key for prefix in ("", "aws_") for key in ( "container_credentials_full_uri", + "container_credentials_relative_uri", "endpoint", "endpoint_url", "endpoint_url_sts", @@ -1912,192 +1906,46 @@ class _CommittedSnapshot: } ) -# Keep recognized identifiers, routing and behavior settings so the store can be reopened. -# Spellings come from object_store 0.13.2's S3, Azure, GCS and HTTP client key parsers -# and Delta Lake's storage configuration. Unknown keys have their values dropped. -_SAVED_STORAGE_OPTION_VALUES = ( - frozenset( - { - # Azure. - "account_name", - "azure_storage_account_name", - "azure_storage_client_id", - "azure_client_id", - "client_id", - "azure_storage_tenant_id", - "azure_storage_authority_id", - "azure_tenant_id", - "azure_authority_id", - "tenant_id", - "authority_id", - "azure_storage_use_emulator", - "use_emulator", - "azure_object_id", - "object_id", - "azure_msi_resource_id", - "msi_resource_id", - "azure_use_fabric_endpoint", - "use_fabric_endpoint", - "azure_use_azure_cli", - "use_azure_cli", - "azure_skip_signature", - "azure_container_name", - "container_name", - "azure_disable_tagging", - "azure_fabric_workload_host", - "fabric_workload_host", - "azure_fabric_cluster_identifier", - "fabric_cluster_identifier", - # GCS. - "google_bucket", - "google_bucket_name", - "google_skip_signature", - # Delta Lake options outside the object_store key parsers. - "aws_force_credential_load", - "aws_iam_role_arn", - "aws_iam_role_session_name", - "aws_s3_allow_unsafe_rename", - "aws_s3_assume_role_arn", - "aws_s3_locking_provider", - "aws_s3_role_session_name", - "backoff_config.base", - "backoff_config.init_backoff", - "backoff_config.max_backoff", - "certificate_path", - "concurrency_limit", - "enable_io", - "enable_time", - "max_concurrency", - "max_retries", - "multi_threaded", - "retry_timeout", - "thread_name", - "worker_threads", - } - | { - prefix + key - for prefix in ("", "aws_") - for key in ( - "bucket", - "bucket_name", - "checksum_algorithm", - "conditional_put", - "copy_if_not_exists", - "default_region", - "disable_tagging", - "imdsv1_fallback", - "region", - "request_payer", - "role_arn", - "role_session_name", - "s3_express", - "server_side_encryption", - "skip_signature", - "sse_bucket_key_enabled", - "sse_kms_key_id", - "unsigned_payload", - "virtual_hosted_style_request", - "web_identity_token_file", - ) - } - | { - prefix + key - for prefix in ("", "aws_", "azure_", "google_") - for key in ( - "allow_http", - "allow_invalid_certificates", - "connect_timeout", - "default_content_type", - "http1_only", - "http2_only", - "http2_keep_alive_interval", - "http2_keep_alive_timeout", - "http2_keep_alive_while_idle", - "http2_max_frame_size", - "pool_idle_timeout", - "pool_max_idle_per_host", - "proxy_ca_certificate", - "proxy_excludes", - "randomize_addresses", - "timeout", - "user_agent", - ) - } - ) - | _URL_STORAGE_OPTION_KEYS -) - _CREDENTIAL_STORAGE_OPTION_KEYS -_CREDENTIAL_URL_QUERY_KEYS = _CREDENTIAL_STORAGE_OPTION_KEYS | frozenset( +_CREDENTIAL_QUERY_KEYS = frozenset( { "access_token", - "api_key", - "assertion", - "auth_token", - "authorization", "awsaccesskeyid", - "client_assertion", - "code", - "credential", "googleaccessid", - "id_token", - "key", "password", - "refresh_token", - "sas", - "security_token", "sig", "signature", - "x_amz_credential", - "x_amz_security_token", - "x_amz_signature", - "x_goog_credential", - "x_goog_security_token", - "x_goog_signature", - "x_ms_sas_token", + "token", + "x-amz-credential", + "x-amz-security-token", + "x-amz-signature", + "x-goog-credential", + "x-goog-security-token", + "x-goog-signature", } ) +_URL_SCHEME = re.compile(r"^(?:https?:[/\\]*|[a-z][a-z0-9+.-]*://)", re.IGNORECASE) -def _saved_storage_option_value(key: str, value: object) -> object: - """Keep recognized settings and strip credentials from URL values.""" - if key not in _SAVED_STORAGE_OPTION_VALUES: - return None - if key not in _URL_STORAGE_OPTION_KEYS or value is None: - return value +def _has_url_credentials(value: object, *, endpoint: bool = False) -> bool: + """Check only for password-bearing userinfo and known credential query keys.""" if not isinstance(value, str): - return None + return False - has_scheme = bool( - re.match( - r"^(?:[a-z][a-z0-9+.-]*://|https?:|socks[45][ah]?:)", value, re.IGNORECASE - ) - ) - has_authority = value.startswith("//") - proxy_without_scheme = ( - key in _PROXY_URL_OPTION_KEYS and not has_scheme and not has_authority + address, _, query = value.lstrip().partition("#")[0].partition("?") + scheme = _URL_SCHEME.match(address) + if scheme is None and not endpoint: + return False # A local storage path can contain literal URL punctuation. + + if scheme is not None: + address = address[scheme.end() :] + elif address.startswith("//"): + address = address[2:] + authority = address.partition("/")[0].partition("\\")[0] + userinfo, at, _ = authority.rpartition("@") + return bool(at and ":" in userinfo) or any( + unquote_plus(field.partition("=")[0]).lower() in _CREDENTIAL_QUERY_KEYS + for field in query.split("&") ) - expects_host = has_scheme or has_authority or key not in _RELATIVE_URL_OPTION_KEYS - try: - url = urlsplit(f"//{value}" if proxy_without_scheme else value) - # Accessing the port validates its syntax and range. - _ = url.port - if re.search(r"[\x00-\x20\x7f\\]", value) or ( - expects_host and url.scheme != "file" and not url.hostname - ): - return None - except ValueError: - return None - # Preserve the original escaping and order of public query parameters. - query = "&".join( - field - for field in url.query.split("&") - if unquote_plus(field.partition("=")[0]).lower().replace("-", "_") - not in _CREDENTIAL_URL_QUERY_KEYS - ) - host = url.netloc.rsplit("@", 1)[-1] - if host == url.netloc and query == url.query and not url.fragment: - return value - saved = urlunsplit((url.scheme, host, url.path, query, "")) - return saved.removeprefix("//") if proxy_without_scheme else saved class DeltaTableDatabase: @@ -2140,9 +1988,6 @@ def __init__( self._root_uri, self._storage_options = parse_base_path( base_path, storage_options ) - self._redacted_storage_option_names: frozenset[str] = ( - _root._redacted_storage_option_names if _root is not None else frozenset() - ) self._is_cloud: bool = is_cloud_uri(self._root_uri) self._path_prefix = _path_prefix self._root = _root @@ -3875,33 +3720,37 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: "max_hierarchy_depth": self.max_hierarchy_depth, "allow_schema_evolution": self.allow_schema_evolution, } - if self._storage_options or self._redacted_storage_option_names: - options = ( - dict.fromkeys(self._redacted_storage_option_names) - | self._storage_options - ) - config["storage_options"] = dict(sorted(options.items())) + if self._storage_options: + config["storage_options"] = self._storage_options return self.config_for_resave(config) @classmethod def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: - """Apply the storage-option policy to a config, even if it failed to rebuild.""" - if "storage_options" not in config: - return config - options: object = config["storage_options"] + """Apply the same save policy to live and retained Delta configurations.""" + root_uri: object = config.get("root_uri", config.get("base_path")) + if _has_url_credentials(root_uri): + raise ValueError( + "Cannot save Delta root_uri with embedded credentials. " + "Supply credentials through the environment or dedicated storage options." + ) + + options: object = config.get("storage_options") if isinstance(options, dict): - options = cast("dict[str, object]", options) - for name, value in options.items(): + saved: dict[str, object] = {} + for name, value in cast("dict[str, object]", options).items(): key = name.lower() - saved = _saved_storage_option_value(key, value) - if saved is not value: - if saved is None and key in _URL_STORAGE_OPTION_KEYS: - logger.warning( - "Omitted malformed Delta storage option URL for %s", name - ) - options[name] = saved - else: - config["storage_options"] = None + if key in _CREDENTIAL_STORAGE_OPTION_KEYS: + continue + if key in _URL_STORAGE_OPTION_KEYS and _has_url_credentials( + value, endpoint=True + ): + raise ValueError( + f"Cannot save Delta storage option {name!r} with embedded " + "credentials. Supply credentials through the environment or " + "dedicated storage options." + ) + saved[name] = value + config = {**config, "storage_options": saved} return config @classmethod @@ -3924,7 +3773,7 @@ def from_config(cls, config: dict[str, Any]) -> "DeltaTableDatabase": root_uri = config["base_path"] _path_prefix = () options: dict[str, str | None] = config.get("storage_options") or {} - database = cls( + return cls( base_path=root_uri, storage_options={ name: value for name, value in options.items() if value is not None @@ -3935,10 +3784,6 @@ def from_config(cls, config: dict[str, Any]) -> "DeltaTableDatabase": allow_schema_evolution=config.get("allow_schema_evolution", True), _path_prefix=_path_prefix, ) - database._redacted_storage_option_names = frozenset( - name for name, value in options.items() if value is None - ) - return database @property def keeps_field_metadata(self) -> bool: diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 92b7af7e0..544255413 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -22,7 +22,6 @@ from collections.abc import Iterator from contextlib import contextmanager from typing import TYPE_CHECKING, Any, cast -from urllib.parse import unquote import pyarrow as pa @@ -395,99 +394,35 @@ def _parse_dsn(dsn: str) -> list[psycopg.pq.ConninfoOption]: raise ProgrammingError("Invalid PostgreSQL connection string.") -# Secret parameters through libpq 18. Saving must also work with older libpq -# versions that reject newer non-secret options, or without psycopg installed. _DSN_SECRET_KEYS = frozenset({"password", "sslpassword", "oauth_client_secret"}) -_CONNINFO_OPTION = re.compile( - r""" - \s*(?: - (?P[a-zA-Z_][a-zA-Z_0-9-]*)\s*=\s* - (?: - '(?:[^'\\]|\\.)*' # Single-quoted value. - | (?!')(?:[^\s\\]|\\(?:.|\Z))*(?=\s|\Z) # Unquoted value. - ) - | \Z - ) - """, - re.ASCII | re.DOTALL | re.VERBOSE, -) -_MALFORMED_URI_ESCAPE = re.compile(r"%(?:00|(?![0-9a-fA-F]{2}))") - - -def _redact_conninfo(dsn: str) -> str | None: - """Remove secret keyword/value options, or return None on invalid syntax.""" - parts: list[str] = [] - offset = kept_from = 0 - while offset < len(dsn): - option = _CONNINFO_OPTION.match(dsn, offset) - if option is None: - return None - offset = option.end() - key = option["key"] - if key is not None and key.lower() in _DSN_SECRET_KEYS: - parts.append(dsn[kept_from : option.start("key")]) - kept_from = offset - parts.append(dsn[kept_from:]) - return "".join(parts) - - -def _redact_dsn_uri(dsn: str) -> str | None: - """Remove secrets from URI user info and query fields, preserving their encoding.""" - if _MALFORMED_URI_ESCAPE.search(dsn): - return None - scheme, separator, location = dsn.partition("://") - # Like libpq, look for the first @ before the first slash. A raw question - # mark in user info does not start the query. - userinfo, at, _ = location.partition("/")[0].partition("@") - prefix = scheme + separator - if at: - prefix += userinfo.partition(":")[0] + at - location = location[len(userinfo) + 1 :] - address, question, query = location.partition("?") - fields = query.removesuffix("&").split("&") if query else [] - public_fields: list[str] = [] - for field in fields: - name, equals, value = field.partition("=") - if not equals or "=" in value: - return None - # libpq trims raw whitespace before decoding URI query parameter names. - if unquote(name.strip(" \t\n\r\v\f")).lower() not in _DSN_SECRET_KEYS: - public_fields.append(field) - if len(public_fields) == len(fields): - return prefix + address + question + query - if public_fields: - trailing_separator = "&" if query.endswith("&") else "" - return ( - prefix + address + question + "&".join(public_fields) + trailing_separator - ) - return prefix + address - - -def _dsn_for_save(dsn: str) -> str | None: - """Remove connection secrets without validating options against installed libpq.""" - redacted = None - if "\0" not in dsn: - if dsn.startswith(("postgresql://", "postgres://")): - redacted = _redact_dsn_uri(dsn) - else: - redacted = _redact_conninfo(dsn) - if redacted is not None: - return redacted - - # If token boundaries are unclear, omit a potentially secret DSN without - # logging its text. Keep malformed strings that show no sign of credentials. - decoded = unquote(dsn).lower() - before_at, at, _ = decoded.partition("@") - if ( - "password" not in decoded - and "oauth_client_secret" not in decoded - and not (at and ":" in before_at) - ): - return dsn - logger.warning( - "Omitting malformed PostgreSQL connection string that may contain credentials." + + +def _dsn_for_save(dsn: object) -> str: + """Use psycopg to parse and serialize settings without secret parameters.""" + try: + from psycopg import Error + from psycopg.conninfo import conninfo_to_dict, make_conninfo + except ImportError: + pass + else: + if isinstance(dsn, str) and "\0" not in dsn: + try: + options = conninfo_to_dict(dsn) + return make_conninfo( + **{ + key: value + for key, value in options.items() + if key not in _DSN_SECRET_KEYS + } + ) + except (Error, UnicodeError): + pass + + raise ValueError( + "Cannot save PostgreSQL dsn without parsing it with psycopg. " + "Install psycopg with a compatible libpq or provide a valid dsn. " + "Supply credentials through the environment or a password file." ) - return None def _psycopg_server(dsn: str) -> tuple[str, str]: @@ -1156,13 +1091,7 @@ def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: """Make a legacy config safe to retain when its connection could not open.""" if "dsn" not in config: return config - dsn: object = config["dsn"] - saved_dsn = _dsn_for_save(dsn) if isinstance(dsn, str) else None - if saved_dsn is None: - del config["dsn"] - elif saved_dsn != dsn: - config["dsn"] = saved_dsn - return config + return {**config, "dsn": _dsn_for_save(config["dsn"])} @classmethod def from_config(cls, config: dict[str, Any]) -> PostgreSQLConnector: diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index 55776e391..ba036b00a 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -62,9 +62,7 @@ def test_saved_job_reopens_s3_tables_with_environment_credentials( rows = loaded.get_record_by_id(("table",), b"id") assert rows is not None assert rows.select(["x", "y"]) == data - assert loaded.to_config()["storage_options"] == options | dict.fromkeys( - credential_keys - ) + assert loaded.to_config()["storage_options"] == options # --------------------------------------------------------------------------- diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index 67035d778..bb6a479c3 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -199,41 +199,26 @@ def test_isinstance_dbconnector_protocol(self) -> None: class TestConfig: @pytest.mark.parametrize( - ("dsn", "saved_dsn"), + "dsn", [ - ( - "postgresql://u%3Aser:s%40fe@localhost:5432/mydb?" - "application_name=my%20app&%73slpassword=ssl-marker&password =query%26secret" - "&passfile=%2Ftmp%2Ftest.pgpass", - "postgresql://u%3Aser@localhost:5432/mydb?" - "application_name=my%20app&passfile=%2Ftmp%2Ftest.pgpass", - ), - ( - " sslpassword=ssl\\ marker dbname = mydb password='s\\' afe' port=5432 " - "passfile=/tmp/test.pgpass user=user host=localhost ", - " dbname = mydb port=5432 passfile=/tmp/test.pgpass " - "user=user host=localhost ", - ), - ("postgres://user:@localhost?password=", "postgres://user@localhost"), - ( - "postgres://localhost/mydb?application_name=my%20app", - "postgres://localhost/mydb?application_name=my%20app", - ), - ( - " host = localhost application_name='password=public label' ", - " host = localhost application_name='password=public label' ", - ), + "postgresql://u%3Aser:s%40fe@localhost:5432/mydb?" + "application_name=my%20app&%73slpassword=ssl-marker&password =query%26secret" + "&passfile=%2Ftmp%2Ftest.pgpass", + " sslpassword=ssl\\ marker dbname = mydb password='s\\' afe' port=5432 " + "passfile=/tmp/test.pgpass user=user host=localhost ", + "postgres://user:@localhost?password=", + "postgres://localhost/mydb?application_name=my%20app", + " host = localhost application_name='password=public label' ", ], ) - def test_to_config(self, dsn: str, saved_dsn: str) -> None: + def test_to_config(self, dsn: str) -> None: with patch("psycopg.connect") as mock_connect: mock_connect.return_value = MagicMock() connector = PostgreSQLConnector(dsn) config = connector.to_config() assert config["connector_type"] == "postgresql" - assert config["dsn"] == saved_dsn options = conninfo_to_dict(dsn) - assert conninfo_to_dict(saved_dsn) == { + assert conninfo_to_dict(config["dsn"]) == { key: value for key, value in options.items() if key not in {"password", "sslpassword"} @@ -246,26 +231,6 @@ def test_to_config(self, dsn: str, saved_dsn: str) -> None: connector._conn = None rebuilt._conn = None - @pytest.mark.parametrize( - ("dsn", "keep"), - [ - ("host=localhost application_name='broken", True), - ("host=localhost password='fixture-secret", False), - ("postgresq://user:fixture-secret@localhost/db", False), - ("postgres://localhost/db?broken&%70assword=fixture-secret", False), - ], - ) - def test_config_for_resave_handles_malformed_dsn( - self, dsn: str, keep: bool, caplog: pytest.LogCaptureFixture - ) -> None: - saved = PostgreSQLConnector.config_for_resave({"dsn": dsn}) - if keep: - assert saved["dsn"] == dsn - else: - assert "dsn" not in saved - assert "malformed PostgreSQL connection string" in caplog.text - assert "fixture-secret" not in caplog.text - @pytest.mark.skipif(psycopg.pq.version() < 180000, reason="libpq 18 adds OAuth") def test_to_config_omits_oauth_client_secret(self) -> None: dsn = "host=localhost oauth_client_id=client oauth_client_secret=oauth-marker" diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index f3039e274..43ad10750 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -25,10 +25,8 @@ DeltaTableDatabase, PostgreSQLConnector, ) -from orcapod.databases import postgresql_connector from orcapod.databases.delta_lake_databases import ( - _SAVED_STORAGE_OPTION_VALUES, - _URL_STORAGE_OPTION_KEYS, + _CREDENTIAL_STORAGE_OPTION_KEYS, ) from orcapod.databases.storage_utils import parse_base_path from orcapod.errors import InconsistentSourceError @@ -57,7 +55,6 @@ "AWS_SESSION_TOKEN": "synthetic-session-token", "AZURE_STORAGE_SAS_KEY": "synthetic-sas", "GOOGLE_SERVICE_ACCOUNT_KEY": "synthetic-service-account", - "unknown": "synthetic-unknown", } @@ -130,27 +127,25 @@ def test_delta_job_and_cached_source( UPath("s3://test-bucket/data", **cast("dict[str, Any]", upath_options)) ) public = {"AWS_ENDPOINT_URL": PUBLIC_OPTIONS["AWS_ENDPOINT_URL"]} - private = {key: None for key in list(PRIVATE_OPTIONS)[:3]} else: options = PUBLIC_OPTIONS | PRIVATE_OPTIONS if reverse: options = dict(reversed(options.items())) database = DeltaTableDatabase(tmp_path / "delta", storage_options=options) public = PUBLIC_OPTIONS - private = dict.fromkeys(PRIVATE_OPTIONS) path = tmp_path / "job.json" bindings = _save(path, _arrow_source(), database) - assert bindings["database"]["storage_options"] == public | private + assert bindings["database"]["storage_options"] == public loaded_database = PipelineJob.load(path).database assert isinstance(loaded_database, DeltaTableDatabase) - assert loaded_database.to_config()["storage_options"] == public | private + assert loaded_database.to_config()["storage_options"] == public assert PipelineJob.load(path, database=database).database is database bindings = _save(path, CachedSource(_arrow_source(), cache_database=database)) (cached,) = bindings["sources"].values() - assert cached["cache_database"]["storage_options"] == public | private + assert cached["cache_database"]["storage_options"] == public @pytest.mark.parametrize("reverse", [False, True]) @@ -243,7 +238,7 @@ def test_delta_cloud_options_reach_backend_after_round_trip( reverse: bool, ) -> None: path = tmp_path / "job.json" - private = dict.fromkeys((*private_keys, "unknown_option"), SECRET) + private = dict.fromkeys(private_keys, SECRET) options = public | private if reverse: options = dict(reversed(options.items())) @@ -259,9 +254,7 @@ def test_delta_cloud_options_reach_backend_after_round_trip( open_table.assert_called_once_with(f"{uri}/table", storage_options=public) raw = path.read_text() assert SECRET not in raw - assert json.loads(raw)["bindings"]["database"]["storage_options"] == ( - public | dict.fromkeys(private) - ) + assert json.loads(raw)["bindings"]["database"]["storage_options"] == public def test_delta_azure_round_trip_uses_environment_access_key( @@ -293,25 +286,30 @@ def open_table(table_uri: str, storage_options: dict[str, str]) -> None: open_delta.assert_called_once() +@pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize( "uri", ["s3://fixtures/data", "az://fixtures/data", "gs://fixtures/data"] ) -@pytest.mark.parametrize( - "key", sorted(_SAVED_STORAGE_OPTION_VALUES - _URL_STORAGE_OPTION_KEYS) -) -def test_delta_non_url_options_preserve_text( - tmp_path: Path, uri: str, key: str +def test_delta_omits_every_listed_credential_option( + tmp_path: Path, caplog: pytest.LogCaptureFixture, uri: str, reverse: bool ) -> None: - value = "fixture-loader/1.0 (+https://example.test/project?sig=example; ops@example.test)" - public = {key: value} + private = { + key.upper(): f"{SECRET}-{index}" + for index, key in enumerate(sorted(_CREDENTIAL_STORAGE_OPTION_KEYS)) + } + public = { + "unknown_option": " literal value ", + "user_agent": "fixture-loader/1.0 (+https://example.test/project?sig=example)", + "region": "", + } + options = public | private + if reverse: + options = dict(reversed(options.items())) path = tmp_path / "job.json" - bindings = _save( - path, _arrow_source(), DeltaTableDatabase(uri, public | PRIVATE_OPTIONS) - ) - assert bindings["database"]["storage_options"] == public | dict.fromkeys( - PRIVATE_OPTIONS - ) - assert SECRET not in path.read_text() + saved = _save(path, _arrow_source(), DeltaTableDatabase(uri, options)) + assert saved["database"]["storage_options"] == public + output = path.read_text() + caplog.text + assert all(secret not in output for secret in private.values()) loaded = PipelineJob.load(path).database assert isinstance(loaded, DeltaTableDatabase) with patch("deltalake.DeltaTable", side_effect=TableNotFoundError) as open_table: @@ -320,50 +318,30 @@ def test_delta_non_url_options_preserve_text( @pytest.mark.parametrize("reverse", [False, True]) -def test_delta_saved_urls_strip_credentials_and_keep_routing( - tmp_path: Path, caplog: pytest.LogCaptureFixture, reverse: bool +@pytest.mark.parametrize( + "endpoint", + [ + " http://localhost/explicit ", + "http:/localhost/explicit", + "https://[broken", + "https://example.test:8443/account?route=a%20b#fragment", + "proxy.example.test:3128", + ], +) +def test_delta_azure_endpoint_passes_through_verbatim( + tmp_path: Path, endpoint: str, reverse: bool ) -> None: uri = "az://fixtures/data" public = { "azure_storage_account_name": "fixtureaccount", - "azure_storage_endpoint": "https://storage.example.test:8443/account?route=a%20b", - "azure_identity_endpoint": "https://identity.example.test/tenant", - "azure_proxy_url": "proxy.example.test:3128", - } - options = public | { - "azure_storage_endpoint": ( - f"https://fixture-user:{SECRET}@storage.example.test:8443/account" - "?route=a%20b&%53IG=synthetic-sas-signature" - ), - "azure_identity_endpoint": ( - "https://identity.example.test/tenant?X-Amz-Signature=synthetic-signature" - "&X-Goog-Credential=synthetic-credential&ACCESS_TOKEN=synthetic-token" - ), - "azure_proxy_url": f"fixture-proxy-user:{SECRET}@proxy.example.test:3128", - "azure_authority_host": f"https://[broken-{SECRET}", + "azure_storage_endpoint": endpoint, + "azure_allow_http": "true", } if reverse: - options = dict(reversed(options.items())) + public = dict(reversed(public.items())) path = tmp_path / "job.json" - bindings = _save(path, _arrow_source(), DeltaTableDatabase(uri, options)) - raw = path.read_text() - for credential in ( - "fixture-user", - "fixture-proxy-user", - "synthetic-sas-signature", - "synthetic-signature", - "synthetic-credential", - "synthetic-token", - ): - assert credential not in raw - assert bindings["database"]["storage_options"] == public | { - "azure_authority_host": None, - } - assert ( - "Omitted malformed Delta storage option URL for azure_authority_host" - in caplog.text - ) - assert SECRET not in caplog.text + saved = _save(path, _arrow_source(), DeltaTableDatabase(uri, public)) + assert saved["database"]["storage_options"] == public loaded = PipelineJob.load(path).database assert isinstance(loaded, DeltaTableDatabase) with patch("deltalake.DeltaTable", side_effect=TableNotFoundError) as open_table: @@ -371,6 +349,55 @@ def test_delta_saved_urls_strip_credentials_and_keep_routing( open_table.assert_called_once_with(f"{uri}/table", storage_options=public) +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize( + ("name", "value"), + [ + ("root_uri", f"abfs://fixtures:{SECRET}@fixture.dfs.core.windows.net/data"), + ("root_uri", f"az://fixtures/data?sig={SECRET}"), + ("azure_storage_endpoint", f"https://fixture:{SECRET}@example.test"), + ("azure_storage_endpoint", f" http:/fixture:{SECRET}@example.test"), + ("azure_storage_endpoint", f"http:fixture:{SECRET}@example.test"), + ("azure_storage_endpoint", f"https://example.test?%53IG={SECRET}"), + ("AWS_ENDPOINT_URL", f"https://example.test?X-Amz-Signature={SECRET}"), + ("aws_endpoint_url_sts", f"https://example.test?X-Amz-Credential={SECRET}"), + ("google_base_url", f"https://example.test?X-Goog-Signature={SECRET}"), + ("azure_proxy_url", f"fixture:{SECRET}@proxy.example.test:3128"), + ("aws_container_credentials_relative_uri", f"/metadata?token={SECRET}"), + ], +) +def test_delta_refuses_urls_with_credentials( + tmp_path: Path, + caplog: pytest.LogCaptureFixture, + name: str, + value: str, + reverse: bool, +) -> None: + options = PUBLIC_OPTIONS | PRIVATE_OPTIONS + uri = "az://fixtures/data" + if name == "root_uri": + uri = value + else: + options[name] = value + if reverse: + options = dict(reversed(options.items())) + path = tmp_path / "job.json" + with pytest.raises(ValueError, match=name) as failure: + _save(path, _arrow_source(), DeltaTableDatabase(uri, options)) + assert not path.exists() + assert SECRET not in str(failure.value) + caplog.text + + +def test_delta_preserves_abfs_container_and_public_query(tmp_path: Path) -> None: + uri = "abfs://fixtures@fixture.dfs.core.windows.net/data?route=a%20b" + path = tmp_path / "job.json" + saved = _save(path, _arrow_source(), DeltaTableDatabase(uri)) + assert saved["database"]["root_uri"] == uri + loaded = PipelineJob.load(path).database + assert isinstance(loaded, DeltaTableDatabase) + assert loaded.to_config()["root_uri"] == uri + + @pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize( ("arn_key", "session_key", "token_file_key"), @@ -403,7 +430,7 @@ def test_delta_aws_role_settings_reach_backend_after_round_trip( options = dict(reversed(options.items())) path = tmp_path / "job.json" bindings = _save(path, _arrow_source(), DeltaTableDatabase(uri, options)) - assert bindings["database"]["storage_options"] == public | dict.fromkeys(private) + assert bindings["database"]["storage_options"] == public loaded = PipelineJob.load(path).database assert isinstance(loaded, DeltaTableDatabase) with patch("deltalake.DeltaTable", side_effect=TableNotFoundError) as open_table: @@ -413,7 +440,7 @@ def test_delta_aws_role_settings_reach_backend_after_round_trip( @pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize("public", [{}, PUBLIC_OPTIONS]) -def test_delta_resave_keeps_redacted_option_names( +def test_delta_resave_keeps_credential_options_omitted( tmp_path: Path, reverse: bool, public: dict[str, str] ) -> None: uri = "s3://fixtures/data" @@ -431,14 +458,14 @@ def test_delta_resave_keeps_redacted_option_names( ) loaded.save(path) resaved = json.loads(path.read_text())["bindings"]["database"] - assert json.dumps(resaved["storage_options"]) == json.dumps( - initial["database"]["storage_options"] + assert ( + resaved.get("storage_options", {}) + == initial["database"].get("storage_options", {}) + == public ) scoped = _save(path, _arrow_source(), loaded.database.at("scope", "nested")) - assert scoped["database"]["storage_options"] == public | dict.fromkeys( - PRIVATE_OPTIONS - ) + assert scoped["database"].get("storage_options", {}) == public @pytest.mark.usefixtures("postgres") @@ -513,7 +540,7 @@ def test_legacy_delta_options_load_and_are_scrubbed_on_resave( assert secret not in raw expected = { **data["bindings"][slot], - "storage_options": PUBLIC_OPTIONS | dict.fromkeys(PRIVATE_OPTIONS), + "storage_options": PUBLIC_OPTIONS, } assert json.dumps(json.loads(raw)["bindings"][slot]) == json.dumps(expected) @@ -541,7 +568,7 @@ def test_cached_source_fallback_scrubs_a_legacy_dsn( @pytest.mark.parametrize("binding", ["postgresql", "delta", "nested"]) -def test_resaving_clean_retained_blocks_preserves_saved_bytes( +def test_resaving_clean_retained_blocks_preserves_settings( tmp_path: Path, postgres: MagicMock, binding: str ) -> None: path = tmp_path / "original.json" @@ -582,50 +609,32 @@ def test_resaving_clean_retained_blocks_preserves_saved_bytes( target = tmp_path / "resaved.json" loaded.save(target) field = "database" if binding == "delta" else "sources" - assert json.dumps(json.loads(target.read_text())["bindings"][field], indent=2) == ( - json.dumps(bindings[field], indent=2) - ) - - -@pytest.mark.parametrize( - ("legacy_dsn", "saved_dsn"), - [ - pytest.param(CLEAN_DSN, CLEAN_DSN, id="clean-uri"), - pytest.param( - " host = localhost application_name='password=public label' user=user", - " host = localhost application_name='password=public label' user=user", - id="clean-conninfo", - ), - pytest.param( - "postgres://u%3As:secret%2Fword@localhost:5432/mydb?" - "application_name=app%20name&%70assword=query-secret&" - "%73slpassword=ssl-secret&connect_timeout=3", - "postgres://u%3As@localhost:5432/mydb?" - "application_name=app%20name&connect_timeout=3", - id="credential-uri", - ), - pytest.param( - "host=localhost password = 'secret\\' word' " - "application_name='password=public label' sslpassword=ssl\\ secret " - "user=user password=''oauth_client_secret='oauth marker'", - "host=localhost application_name='password=public label' user=user ", - id="credential-conninfo", - ), - ], -) -def test_resaving_without_postgresql_extra_keeps_rebuildable_dsn( + saved = json.loads(target.read_text())["bindings"] + if binding == "postgresql": + (config,) = saved["sources"].values() + assert conninfo_to_dict(config["dsn"]) == conninfo_to_dict(CLEAN_DSN) + source_config["dsn"] = config["dsn"] + elif binding == "nested": + (config,) = saved["sources"].values() + dsn = config["inner_source"]["origin"]["dsn"] + assert conninfo_to_dict(dsn) == conninfo_to_dict(CLEAN_DSN) + source_config["inner_source"]["origin"]["dsn"] = dsn + assert json.dumps(saved[field], indent=2) == json.dumps(bindings[field], indent=2) + + +@pytest.mark.parametrize("dsn", [CLEAN_DSN, _dsn()]) +def test_resaving_without_postgresql_extra_refuses( tmp_path: Path, postgres: MagicMock, monkeypatch: pytest.MonkeyPatch, - legacy_dsn: str, - saved_dsn: str, + caplog: pytest.LogCaptureFixture, + dsn: str, ) -> None: path = tmp_path / "original.json" - source = PostgreSQLTableSource(CLEAN_DSN, "records", tag_only_columns=True) - _ = _save(path, source) + _ = _save(path, PostgreSQLTableSource(CLEAN_DSN, "records", tag_only_columns=True)) data = json.loads(path.read_text()) (slot,) = data["bindings"]["sources"] - data["bindings"]["sources"][slot]["dsn"] = legacy_dsn + data["bindings"]["sources"][slot]["dsn"] = dsn _ = path.write_text(json.dumps(data)) original_import = builtins.__import__ @@ -640,89 +649,72 @@ def without_psycopg( raise ModuleNotFoundError(name=name) return original_import(name, globals, locals, fromlist, level) + monkeypatch.setattr(builtins, "__import__", without_psycopg) + loaded = PipelineJob.load(path) + assert loaded.unbound_sources == [slot] target = tmp_path / "resaved.json" - with monkeypatch.context() as scoped: - scoped.setattr(builtins, "__import__", without_psycopg) - loaded = PipelineJob.load(path) - assert loaded.unbound_sources == [slot] + with pytest.raises(ValueError, match="dsn.*psycopg") as failure: loaded.save(target) - - actual = json.loads(target.read_text())["bindings"]["sources"][slot]["dsn"] - assert actual == saved_dsn - restored = PipelineJob.load(target) - assert list(restored.sources) == [slot] - postgres.assert_called_with(saved_dsn, autocommit=False) + assert not target.exists() + assert PASSWORD not in str(failure.value) + caplog.text @pytest.mark.parametrize( - ("dsn", "saved_dsn"), - [ - pytest.param( - " host = localhost sslmode=require sslnegotiation=direct ", - " host = localhost sslmode=require sslnegotiation=direct ", - id="clean-conninfo", - ), - pytest.param( - "postgresql://u%3As@localhost/mydb?sslmode=require&sslnegotiation=direct", - "postgresql://u%3As@localhost/mydb?sslmode=require&sslnegotiation=direct", - id="clean-uri", - ), - pytest.param( - "host=localhost password='secret\\' word' sslmode=require sslnegotiation=direct", - "host=localhost sslmode=require sslnegotiation=direct", - id="credential-conninfo", - ), - pytest.param( - "postgresql://u%3As:secret%2Fword@localhost/mydb?" - "sslmode=require&%70assword=query-secret&sslnegotiation=direct", - "postgresql://u%3As@localhost/mydb?sslmode=require&sslnegotiation=direct", - id="credential-uri", - ), - ], + "dsn", ["host=localhost password='broken " + PASSWORD, _dsn() + "&unknown=1"] ) -def test_resaving_with_older_libpq_keeps_rebuildable_dsn( - tmp_path: Path, - postgres: MagicMock, - monkeypatch: pytest.MonkeyPatch, - dsn: str, - saved_dsn: str, +def test_resaving_invalid_postgresql_dsn_refuses( + tmp_path: Path, postgres: MagicMock, caplog: pytest.LogCaptureFixture, dsn: str ) -> None: - original_parse = postgresql_connector._parse_dsn - - def modern_parse(conninfo: str) -> list[psycopg.pq.ConninfoOption]: - # Allow the newer option even on test installations with older libpq. - compatible = conninfo.replace("&sslnegotiation=direct", "").replace( - " sslnegotiation=direct", "" - ) - return original_parse(compatible) - - def older_parse(conninfo: str) -> list[psycopg.pq.ConninfoOption]: - if "sslnegotiation=direct" in conninfo: - raise psycopg.ProgrammingError("Invalid PostgreSQL connection string.") - return original_parse(conninfo) - - monkeypatch.setattr(postgresql_connector, "_parse_dsn", modern_parse) path = tmp_path / "original.json" - source = PostgreSQLTableSource(CLEAN_DSN, "records", tag_only_columns=True) - _ = _save(path, source) + _ = _save(path, PostgreSQLTableSource(CLEAN_DSN, "records", tag_only_columns=True)) data = json.loads(path.read_text()) (slot,) = data["bindings"]["sources"] data["bindings"]["sources"][slot]["dsn"] = dsn _ = path.write_text(json.dumps(data)) - + loaded = PipelineJob.load(path) + assert loaded.unbound_sources == [slot] target = tmp_path / "resaved.json" - with monkeypatch.context() as scoped: - scoped.setattr(postgresql_connector, "_parse_dsn", older_parse) - loaded = PipelineJob.load(path) - assert loaded.unbound_sources == [slot] + with pytest.raises(ValueError, match="dsn") as failure: loaded.save(target) + assert not target.exists() + assert failure.value.__context__ is None + assert PASSWORD not in str(failure.value) + caplog.text - assert ( - json.loads(target.read_text())["bindings"]["sources"][slot]["dsn"] == saved_dsn + +@pytest.mark.parametrize("reverse", [False, True]) +def test_postgresql_job_save_uses_psycopg_conninfo( + tmp_path: Path, postgres: MagicMock, caplog: pytest.LogCaptureFixture, reverse: bool +) -> None: + options = [ + "host=localhost", + f"password='{PASSWORD}'", + "application_name='public label'", + f"sslpassword={SSL_PASSWORD}", + "dbname=mydb", + ] + oauth_secret = "synthetic-oauth-secret" + if psycopg.pq.version() >= 180000: + options.append(f"oauth_client_secret={oauth_secret}") + if reverse: + options.reverse() + dsn = " ".join(options) + source = PostgreSQLTableSource(dsn, "records", tag_only_columns=True) + path = tmp_path / "job.json" + with patch("psycopg.conninfo.conninfo_to_dict", wraps=conninfo_to_dict) as parse: + bindings = _save(path, source) + parse.assert_any_call(dsn) + (saved,) = bindings["sources"].values() + assert conninfo_to_dict(saved["dsn"]) == { + "host": "localhost", + "application_name": "public label", + "dbname": "mydb", + } + assert PipelineJob.load(path).sources + postgres.assert_called_with(saved["dsn"], autocommit=False) + output = path.read_text() + caplog.text + assert all( + secret not in output for secret in (PASSWORD, SSL_PASSWORD, oauth_secret) ) - restored = PipelineJob.load(target) - assert list(restored.sources) == [slot] - postgres.assert_called_with(saved_dsn, autocommit=False) @pytest.mark.parametrize("wrapper", ["table", "generic", "derived", "cached", "delta"]) From b438fc6b417f9acbe853d852ddfb5669a0d92a9a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:53:05 -0800 Subject: [PATCH 10/20] fix(storage): type psycopg conninfo serialization --- src/orcapod/databases/postgresql_connector.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 544255413..171e39783 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -409,11 +409,12 @@ def _dsn_for_save(dsn: object) -> str: try: options = conninfo_to_dict(dsn) return make_conninfo( + "", **{ key: value for key, value in options.items() if key not in _DSN_SECRET_KEYS - } + }, ) except (Error, UnicodeError): pass From 5a27254bc3215f167c5f0db81b12ef7a059c8ae7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 19:38:20 -0800 Subject: [PATCH 11/20] fix(delta): parse URL credentials before saving --- docs/dev/design_issues/ITL-1394-JB1.md | 8 +++-- src/orcapod/databases/delta_lake_databases.py | 33 +++++++------------ .../loaded_job/test_saved_credentials.py | 15 +++++++-- 3 files changed, 29 insertions(+), 27 deletions(-) diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index 311549f53..27cff7857 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -10,9 +10,11 @@ PostgreSQL connector and table source configs can contain passwords in connectio strings. Saving a job exposes those values in plain text, including in wrapped configs. **Fix:** Delta omits known credential options, preserves other values verbatim, -and refuses a root or endpoint URL with an embedded password or known credential -query parameter. The PostgreSQL connector parses and serializes connection strings -with psycopg, omitting `password`, `sslpassword`, and `oauth_client_secret`. It +and refuses a root or endpoint URL with a non-empty password or known credential +query value. Detection follows Python's URL parser and conservatively refuses +unparseable values with userinfo or credential query markers. The PostgreSQL +connector parses and serializes connection strings with psycopg, omitting +`password`, `sslpassword`, and `oauth_client_secret`. It refuses to save a connection string that psycopg cannot parse. Older files still load their recorded values. Subsequent saves apply the same storage rules to retained configs, including nested bindings. Unknown config types are retained diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 816fe62f0..b1655736f 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -13,7 +13,7 @@ from pathlib import Path from time import sleep from typing import TYPE_CHECKING, Any, BinaryIO, Literal, cast -from urllib.parse import unquote_plus +from urllib.parse import parse_qsl, unquote_plus, urlsplit import polars as pl import pyarrow as pa @@ -1923,28 +1923,21 @@ class _CommittedSnapshot: "x-goog-signature", } ) -_URL_SCHEME = re.compile(r"^(?:https?:[/\\]*|[a-z][a-z0-9+.-]*://)", re.IGNORECASE) -def _has_url_credentials(value: object, *, endpoint: bool = False) -> bool: - """Check only for password-bearing userinfo and known credential query keys.""" +def _has_url_credentials(value: object) -> bool: + """Detect non-empty URL credentials and refuse unparseable URLs with credential markers.""" if not isinstance(value, str): return False - address, _, query = value.lstrip().partition("#")[0].partition("?") - scheme = _URL_SCHEME.match(address) - if scheme is None and not endpoint: - return False # A local storage path can contain literal URL punctuation. - - if scheme is not None: - address = address[scheme.end() :] - elif address.startswith("//"): - address = address[2:] - authority = address.partition("/")[0].partition("\\")[0] - userinfo, at, _ = authority.rpartition("@") - return bool(at and ":" in userinfo) or any( - unquote_plus(field.partition("=")[0]).lower() in _CREDENTIAL_QUERY_KEYS - for field in query.split("&") + try: + parsed = urlsplit(value) + except ValueError: + decoded = unquote_plus(value).lower() + return "@" in value or any(key in decoded for key in _CREDENTIAL_QUERY_KEYS) + + return bool(parsed.password) or any( + key.lower() in _CREDENTIAL_QUERY_KEYS for key, _ in parse_qsl(parsed.query) ) @@ -3741,9 +3734,7 @@ def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: key = name.lower() if key in _CREDENTIAL_STORAGE_OPTION_KEYS: continue - if key in _URL_STORAGE_OPTION_KEYS and _has_url_credentials( - value, endpoint=True - ): + if key in _URL_STORAGE_OPTION_KEYS and _has_url_credentials(value): raise ValueError( f"Cannot save Delta storage option {name!r} with embedded " "credentials. Supply credentials through the environment or " diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index 43ad10750..c7bffb2bd 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -324,7 +324,12 @@ def test_delta_omits_every_listed_credential_option( " http://localhost/explicit ", "http:/localhost/explicit", "https://[broken", + "https://user@127.0.0.1/", + "https://user:@127.0.0.1/", + "https://[::1]:8443/account", + "https://example.test/account/user@domain", "https://example.test:8443/account?route=a%20b#fragment", + "https://example.test/account?sig=&X-Amz-Signature", "proxy.example.test:3128", ], ) @@ -356,13 +361,17 @@ def test_delta_azure_endpoint_passes_through_verbatim( ("root_uri", f"abfs://fixtures:{SECRET}@fixture.dfs.core.windows.net/data"), ("root_uri", f"az://fixtures/data?sig={SECRET}"), ("azure_storage_endpoint", f"https://fixture:{SECRET}@example.test"), - ("azure_storage_endpoint", f" http:/fixture:{SECRET}@example.test"), - ("azure_storage_endpoint", f"http:fixture:{SECRET}@example.test"), + ("azure_storage_endpoint", f"ht\ttps://fixture:{SECRET}@127.0.0.1/"), + ("azure_storage_endpoint", f"https:\n//fixture:{SECRET}@127.0.0.1/"), + ("azure_storage_endpoint", f" https://fixture:{SECRET}@127.0.0.1/"), + ("azure_storage_endpoint", f"HTTPS://fixture:{SECRET}@[::1]/"), + ("azure_storage_endpoint", f"https://fixture:{SECRET}@[broken"), + ("azure_storage_endpoint", f"https://[broken?%53IG={SECRET}"), ("azure_storage_endpoint", f"https://example.test?%53IG={SECRET}"), ("AWS_ENDPOINT_URL", f"https://example.test?X-Amz-Signature={SECRET}"), ("aws_endpoint_url_sts", f"https://example.test?X-Amz-Credential={SECRET}"), ("google_base_url", f"https://example.test?X-Goog-Signature={SECRET}"), - ("azure_proxy_url", f"fixture:{SECRET}@proxy.example.test:3128"), + ("azure_proxy_url", f"//fixture:{SECRET}@proxy.example.test:3128"), ("aws_container_credentials_relative_uri", f"/metadata?token={SECRET}"), ], ) From 07375149de8fd99a8abfa450f83ee5234f0b3e69 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 20:07:40 -0800 Subject: [PATCH 12/20] fix(delta): preserve local storage roots when saving jobs --- changelog.d/ITL-1394.md | 4 +- docs/concepts/pipeline-job.md | 3 ++ docs/dev/design_issues/ITL-1394-JB1.md | 7 +-- src/orcapod/databases/delta_lake_databases.py | 18 ++++++-- .../loaded_job/test_saved_credentials.py | 44 +++++++++++++++++++ 5 files changed, 68 insertions(+), 8 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index 6b230d83b..c733610cf 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -14,8 +14,8 @@ - Delta databases, PostgreSQL connectors and the sources that wrap them keep credentials out of newly saved job files. Earlier files still load with their recorded settings. -- Saved Delta databases retain other option values verbatim, including endpoints, - regions, and AWS role identifiers. +- Saved Delta databases retain local roots and other option values verbatim, including + endpoints, regions, and AWS role identifiers. - Resaving a legacy job applies the same credential rules to retained source and database configurations, including nested storage wrappers. PostgreSQL uses psycopg to serialize the remaining connection settings. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index d06a9e58e..975fb4bf8 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -551,6 +551,9 @@ Keep credentials in the backend's dedicated credential options or environment. S refuses a Delta storage root, endpoint or proxy URL with an embedded password or a known credential query parameter, such as a SAS signature. To save the job, remove the embedded credential from the URL and supply it separately. +A Delta storage root is checked for embedded credentials only if it parses as a URL +with a scheme other than `file` and a network location, and local paths including +relative paths, Windows drive paths and `file:` URLs are saved verbatim. PostgreSQL uses psycopg to parse the connection string, omit secret parameters and serialize the remaining settings, including any password-file path. Saving requires diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index 27cff7857..337369a4e 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -10,9 +10,10 @@ PostgreSQL connector and table source configs can contain passwords in connectio strings. Saving a job exposes those values in plain text, including in wrapped configs. **Fix:** Delta omits known credential options, preserves other values verbatim, -and refuses a root or endpoint URL with a non-empty password or known credential -query value. Detection follows Python's URL parser and conservatively refuses -unparseable values with userinfo or credential query markers. The PostgreSQL +and refuses remote roots and endpoint URLs with a non-empty password or known +credential query value. A remote root parses with a scheme other than `file` and a +network location, excluding Windows drive paths. Detection conservatively refuses +unparseable endpoint values with userinfo or credential query markers. The PostgreSQL connector parses and serializes connection strings with psycopg, omitting `password`, `sslpassword`, and `oauth_client_secret`. It refuses to save a connection string that psycopg cannot parse. Older files still diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index b1655736f..c23ee8003 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1925,17 +1925,29 @@ class _CommittedSnapshot: ) -def _has_url_credentials(value: object) -> bool: - """Detect non-empty URL credentials and refuse unparseable URLs with credential markers.""" +def _has_url_credentials(value: object, *, storage_root: bool = False) -> bool: + """Detect embedded credentials in Delta URL values. + + Check a storage root only when ``urlsplit`` finds a scheme other than + ``file`` and a network location, with Windows drive paths treated as local. + """ if not isinstance(value, str): return False try: parsed = urlsplit(value) except ValueError: + if storage_root: + return False decoded = unquote_plus(value).lower() return "@" in value or any(key in decoded for key in _CREDENTIAL_QUERY_KEYS) + # A one-letter scheme can be a Windows drive, even in a path like C://dir. + if storage_root and ( + len(parsed.scheme) <= 1 or parsed.scheme == "file" or not parsed.netloc + ): + return False + return bool(parsed.password) or any( key.lower() in _CREDENTIAL_QUERY_KEYS for key, _ in parse_qsl(parsed.query) ) @@ -3721,7 +3733,7 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: """Apply the same save policy to live and retained Delta configurations.""" root_uri: object = config.get("root_uri", config.get("base_path")) - if _has_url_credentials(root_uri): + if _has_url_credentials(root_uri, storage_root=True): raise ValueError( "Cannot save Delta root_uri with embedded credentials. " "Supply credentials through the environment or dedicated storage options." diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index c7bffb2bd..15d33df21 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -397,6 +397,50 @@ def test_delta_refuses_urls_with_credentials( assert SECRET not in str(failure.value) + caplog.text +@pytest.mark.parametrize( + "name", ["cache?sig=weekly", "cache?token=demo", "logs@host:1"] +) +def test_delta_preserves_local_directory_and_reads_saved_table( + tmp_path: Path, name: str +) -> None: + root = tmp_path / name + database = DeltaTableDatabase(root) + payload = pa.table({"x": [1], "y": [2]}) + database.add_record(("table",), b"id", payload, flush=True) + + path = tmp_path / "job.json" + saved = _save(path, _arrow_source(), database) + assert saved["database"]["root_uri"] == str(root) + loaded = PipelineJob.load(path).database + assert isinstance(loaded, DeltaTableDatabase) + assert loaded.to_config()["root_uri"] == str(root) + record = loaded.get_record_by_id(("table",), b"id") + assert record is not None + assert record.select(payload.column_names) == payload + + +@pytest.mark.parametrize( + "root", + [ + "relative/logs@host:1?sig=weekly", + "file:///dir/x?sig=1", + "file://localhost/dir/x?sig=1", + r"C:\dir\x?sig=1", + "C://dir/x?sig=1", + ], +) +def test_delta_preserves_local_root_spelling( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, root: str +) -> None: + monkeypatch.chdir(tmp_path) + path = tmp_path / "job.json" + saved = _save(path, _arrow_source(), DeltaTableDatabase(root)) + assert saved["database"]["root_uri"] == root + loaded = PipelineJob.load(path).database + assert isinstance(loaded, DeltaTableDatabase) + assert loaded.to_config()["root_uri"] == root + + def test_delta_preserves_abfs_container_and_public_query(tmp_path: Path) -> None: uri = "abfs://fixtures@fixture.dfs.core.windows.net/data?route=a%20b" path = tmp_path / "job.json" From 06e387cfa20b32843a49560fd6f5e5962ca1ddd2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 21:27:19 -0800 Subject: [PATCH 13/20] fix(storage): preserve values outside credential option keys --- changelog.d/ITL-1394.md | 32 ++-- docs/concepts/pipeline-job.md | 26 ++- docs/dev/design_issues/ITL-1394-JB1.md | 19 +- src/orcapod/databases/delta_lake_databases.py | 110 +---------- src/orcapod/databases/postgresql_connector.py | 42 ++-- .../test_postgresql_connector.py | 7 +- .../loaded_job/test_saved_credentials.py | 180 ++++++++---------- 7 files changed, 151 insertions(+), 265 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index c733610cf..390e685be 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -1,21 +1,27 @@ ### Breaking changes and migration - Saved job files omit known Delta credential options and secret PostgreSQL connection - parameters. Provide credentials through the storage backend's environment or credential - provider, pass the configured database to `PipelineJob.load()`, or bind a source that - could not be rebuilt with `job.bind(sources=...)`. -- Saving now refuses Delta URLs with embedded credentials, including URLs that - previously saved with those fields removed. Remove the credential from the URL - and supply it through the environment or a dedicated storage option. -- Saving PostgreSQL bindings requires psycopg and a libpq version that understands - the connection string. Install a compatible version or supply a valid connection string. + parameters that psycopg parses. Provide credentials through the storage backend's + environment or credential provider, pass the configured database to + `PipelineJob.load()`, or bind a source that could not be rebuilt with + `job.bind(sources=...)`. ### Fixed -- Delta databases, PostgreSQL connectors and the sources that wrap them keep credentials - out of newly saved job files. Earlier files still load with their recorded settings. -- Saved Delta databases retain local roots and other option values verbatim, including - endpoints, regions, and AWS role identifiers. +- Delta databases, PostgreSQL connectors and their source wrappers apply the storage + backend's credential-key list when saving jobs. Earlier files still load with their + recorded settings. +- Saved Delta databases retain all other values verbatim, including roots, endpoints, + regions, and AWS role identifiers. - Resaving a legacy job applies the same credential rules to retained source and database configurations, including nested storage wrappers. PostgreSQL uses - psycopg to serialize the remaining connection settings. + psycopg to serialize the remaining connection settings after omitting secret keywords. + +### Known limitations + +- A credential embedded in a URL or path value is saved as given (ITL-1708). Pass + credentials through the dedicated options or the environment. + Save a job backed by `DeltaTableDatabase("az://fixtures/data?sig=example")` to see + `?sig=example` in its saved `root_uri`. +- PostgreSQL connection strings are saved as given when psycopg is unavailable + or cannot parse them. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 975fb4bf8..144cf50cd 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -546,20 +546,18 @@ the **Nodes** table below the picture for each node's columns and status. ## Saving and loading `job.save(path)` writes the graph, database locations and source settings to a JSON file. -Delta omits its known credential options and saves all other option values verbatim. -Keep credentials in the backend's dedicated credential options or environment. Saving -refuses a Delta storage root, endpoint or proxy URL with an embedded password or a -known credential query parameter, such as a SAS signature. To save the job, remove the -embedded credential from the URL and supply it separately. -A Delta storage root is checked for embedded credentials only if it parses as a URL -with a scheme other than `file` and a network location, and local paths including -relative paths, Windows drive paths and `file:` URLs are saved verbatim. - -PostgreSQL uses psycopg to parse the connection string, omit secret parameters and -serialize the remaining settings, including any password-file path. Saving requires -psycopg with a libpq version that understands the connection string. A user-written -`PollingSource` implementer is responsible for keeping credentials out of its -`to_config()` return value. +Delta omits its listed credential option keys and saves all other values verbatim. +For PostgreSQL, when psycopg parses the connection string and finds `password`, +`sslpassword`, or `oauth_client_secret`, it serializes the remaining settings. This +includes omitting a URI password that psycopg returns as the `password` keyword. +If psycopg is unavailable, cannot parse the string, or finds no secret keywords, +the connection string is saved as given. A user-written `PollingSource` implementer +is responsible for keeping credentials out of its `to_config()` return value. + +**Known limitation (ITL-1708).** A credential embedded in a URL or path value is saved +as given. Pass credentials through the dedicated options or the environment. +Save a job backed by `DeltaTableDatabase("az://fixtures/data?sig=example")` to see +`?sig=example` in the saved `root_uri`. `PipelineJob.load(path)` reads the job back, for example in a later Python session. Supply omitted credentials again through the backend's environment or its usual diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index 337369a4e..51a2976c9 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -9,14 +9,11 @@ Delta database configs can contain credentials supplied directly or through a UP PostgreSQL connector and table source configs can contain passwords in connection strings. Saving a job exposes those values in plain text, including in wrapped configs. -**Fix:** Delta omits known credential options, preserves other values verbatim, -and refuses remote roots and endpoint URLs with a non-empty password or known -credential query value. A remote root parses with a scheme other than `file` and a -network location, excluding Windows drive paths. Detection conservatively refuses -unparseable endpoint values with userinfo or credential query markers. The PostgreSQL -connector parses and serializes connection strings with psycopg, omitting -`password`, `sslpassword`, and `oauth_client_secret`. It -refuses to save a connection string that psycopg cannot parse. Older files still -load their recorded values. Subsequent saves apply the same storage rules to -retained configs, including nested bindings. Unknown config types are retained -as saved and trigger a credential warning. +**Fix:** Delta omits known credential option keys and preserves other values +verbatim. The PostgreSQL connector uses psycopg to omit `password`, `sslpassword`, +and `oauth_client_secret` and serialize the remaining settings when any of those +keys are parsed. Otherwise the connection string is saved verbatim. Older files +still load their recorded values. Subsequent saves apply the same storage rules +to retained configs, including nested bindings. Unknown config types are retained +as saved and trigger a credential warning. Credentials embedded in Delta URL or +path values are saved as given (ITL-1708). diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c23ee8003..5c4690eb5 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -13,7 +13,6 @@ from pathlib import Path from time import sleep from typing import TYPE_CHECKING, Any, BinaryIO, Literal, cast -from urllib.parse import parse_qsl, unquote_plus, urlsplit import polars as pl import pyarrow as pa @@ -1873,85 +1872,6 @@ class _CommittedSnapshot: } ) -# URL-valued endpoints and proxies may embed credentials in their authority or query. -_URL_STORAGE_OPTION_KEYS = ( - {prefix + "proxy_url" for prefix in ("", "aws_", "azure_", "google_")} - | { - prefix + key - for prefix in ("", "aws_") - for key in ( - "container_credentials_full_uri", - "container_credentials_relative_uri", - "endpoint", - "endpoint_url", - "endpoint_url_sts", - "metadata_endpoint", - ) - } - | { - "aws_endpoint_url_s3", - "azure_storage_endpoint", - "azure_endpoint", - "azure_storage_authority_host", - "azure_authority_host", - "authority_host", - "azure_msi_endpoint", - "azure_identity_endpoint", - "identity_endpoint", - "msi_endpoint", - "azure_fabric_token_service_url", - "fabric_token_service_url", - "google_base_url", - "base_url", - } -) - -_CREDENTIAL_QUERY_KEYS = frozenset( - { - "access_token", - "awsaccesskeyid", - "googleaccessid", - "password", - "sig", - "signature", - "token", - "x-amz-credential", - "x-amz-security-token", - "x-amz-signature", - "x-goog-credential", - "x-goog-security-token", - "x-goog-signature", - } -) - - -def _has_url_credentials(value: object, *, storage_root: bool = False) -> bool: - """Detect embedded credentials in Delta URL values. - - Check a storage root only when ``urlsplit`` finds a scheme other than - ``file`` and a network location, with Windows drive paths treated as local. - """ - if not isinstance(value, str): - return False - - try: - parsed = urlsplit(value) - except ValueError: - if storage_root: - return False - decoded = unquote_plus(value).lower() - return "@" in value or any(key in decoded for key in _CREDENTIAL_QUERY_KEYS) - - # A one-letter scheme can be a Windows drive, even in a path like C://dir. - if storage_root and ( - len(parsed.scheme) <= 1 or parsed.scheme == "file" or not parsed.netloc - ): - return False - - return bool(parsed.password) or any( - key.lower() in _CREDENTIAL_QUERY_KEYS for key, _ in parse_qsl(parsed.query) - ) - class DeltaTableDatabase: """ @@ -3731,29 +3651,17 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: @classmethod def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: - """Apply the same save policy to live and retained Delta configurations.""" - root_uri: object = config.get("root_uri", config.get("base_path")) - if _has_url_credentials(root_uri, storage_root=True): - raise ValueError( - "Cannot save Delta root_uri with embedded credentials. " - "Supply credentials through the environment or dedicated storage options." - ) - + """Omit dedicated credential options from live and retained configurations.""" options: object = config.get("storage_options") if isinstance(options, dict): - saved: dict[str, object] = {} - for name, value in cast("dict[str, object]", options).items(): - key = name.lower() - if key in _CREDENTIAL_STORAGE_OPTION_KEYS: - continue - if key in _URL_STORAGE_OPTION_KEYS and _has_url_credentials(value): - raise ValueError( - f"Cannot save Delta storage option {name!r} with embedded " - "credentials. Supply credentials through the environment or " - "dedicated storage options." - ) - saved[name] = value - config = {**config, "storage_options": saved} + config = { + **config, + "storage_options": { + name: value + for name, value in cast("dict[str, object]", options).items() + if name.lower() not in _CREDENTIAL_STORAGE_OPTION_KEYS + }, + } return config @classmethod diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 171e39783..2681c44e7 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -397,32 +397,25 @@ def _parse_dsn(dsn: str) -> list[psycopg.pq.ConninfoOption]: _DSN_SECRET_KEYS = frozenset({"password", "sslpassword", "oauth_client_secret"}) -def _dsn_for_save(dsn: object) -> str: - """Use psycopg to parse and serialize settings without secret parameters.""" +def _dsn_for_save(dsn: str) -> str: + """Omit secret parameters when psycopg can parse the full string.""" + # libpq stops at a NUL, so parsing it would lose the rest of the string. + if "\0" in dsn: + return dsn try: from psycopg import Error from psycopg.conninfo import conninfo_to_dict, make_conninfo except ImportError: - pass - else: - if isinstance(dsn, str) and "\0" not in dsn: - try: - options = conninfo_to_dict(dsn) - return make_conninfo( - "", - **{ - key: value - for key, value in options.items() - if key not in _DSN_SECRET_KEYS - }, - ) - except (Error, UnicodeError): - pass + return dsn - raise ValueError( - "Cannot save PostgreSQL dsn without parsing it with psycopg. " - "Install psycopg with a compatible libpq or provide a valid dsn. " - "Supply credentials through the environment or a password file." + try: + options = conninfo_to_dict(dsn) + except (Error, UnicodeError): + return dsn + if _DSN_SECRET_KEYS.isdisjoint(options): + return dsn + return make_conninfo( + **{key: value for key, value in options.items() if key not in _DSN_SECRET_KEYS} ) @@ -1089,10 +1082,11 @@ def to_config(self) -> dict[str, Any]: @classmethod def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: - """Make a legacy config safe to retain when its connection could not open.""" - if "dsn" not in config: + """Apply the connection string save policy to a retained config.""" + dsn: object = config.get("dsn") + if not isinstance(dsn, str): return config - return {**config, "dsn": _dsn_for_save(config["dsn"])} + return {**config, "dsn": _dsn_for_save(dsn)} @classmethod def from_config(cls, config: dict[str, Any]) -> PostgreSQLConnector: diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index bb6a479c3..b752f817e 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -11,7 +11,7 @@ import psycopg import pyarrow as pa import pytest -from psycopg.conninfo import conninfo_to_dict +from psycopg.conninfo import conninfo_to_dict, make_conninfo from orcapod.databases.postgresql_connector import ( PostgreSQLConnector, @@ -218,11 +218,14 @@ def test_to_config(self, dsn: str) -> None: config = connector.to_config() assert config["connector_type"] == "postgresql" options = conninfo_to_dict(dsn) - assert conninfo_to_dict(config["dsn"]) == { + public = { key: value for key, value in options.items() if key not in {"password", "sslpassword"} } + assert config["dsn"] == ( + make_conninfo(**public) if public != options else dsn + ) mock_connect.assert_called_once_with(dsn, autocommit=False) mock_connect.reset_mock() rebuilt = PostgreSQLConnector.from_config(config) diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index 15d33df21..3b51f064d 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -4,6 +4,7 @@ import builtins import json +import logging from collections.abc import Iterator, Mapping, Sequence from pathlib import Path from typing import Any, cast @@ -293,8 +294,9 @@ def open_table(table_uri: str, storage_options: dict[str, str]) -> None: def test_delta_omits_every_listed_credential_option( tmp_path: Path, caplog: pytest.LogCaptureFixture, uri: str, reverse: bool ) -> None: + caplog.set_level(logging.DEBUG, logger="orcapod") private = { - key.upper(): f"{SECRET}-{index}" + (key.upper() if index % 2 else key.title()): f"{SECRET}-{index}" for index, key in enumerate(sorted(_CREDENTIAL_STORAGE_OPTION_KEYS)) } public = { @@ -308,18 +310,18 @@ def test_delta_omits_every_listed_credential_option( path = tmp_path / "job.json" saved = _save(path, _arrow_source(), DeltaTableDatabase(uri, options)) assert saved["database"]["storage_options"] == public - output = path.read_text() + caplog.text - assert all(secret not in output for secret in private.values()) loaded = PipelineJob.load(path).database assert isinstance(loaded, DeltaTableDatabase) with patch("deltalake.DeltaTable", side_effect=TableNotFoundError) as open_table: assert not loaded.table_exists(("table",)) open_table.assert_called_once_with(f"{uri}/table", storage_options=public) + output = path.read_text() + caplog.text + assert all(secret not in output for secret in private.values()) -@pytest.mark.parametrize("reverse", [False, True]) +# On main, saving and loading a Delta binding preserves these strings as supplied. @pytest.mark.parametrize( - "endpoint", + "value", [ " http://localhost/explicit ", "http:/localhost/explicit", @@ -331,70 +333,76 @@ def test_delta_omits_every_listed_credential_option( "https://example.test:8443/account?route=a%20b#fragment", "https://example.test/account?sig=&X-Amz-Signature", "proxy.example.test:3128", + "abfs://fixtures:example-password@fixture.dfs.core.windows.net/data", + "abfs://fixtures@fixture.dfs.core.windows.net/data?route=a%20b", + "az://fixtures/data?sig=example-signature", + "https://user:example-password@example.test/", + "ht\ttps://user:example-password@127.0.0.1/", + "https:\n//user:example-password@127.0.0.1/", + " https://user:example-password@127.0.0.1/", + "HTTPS://user:example-password@[::1]/", + "https://user:example-password@[broken", + "https://[broken?%53IG=example-signature", + "https://example.test?%53IG=example-signature", + "https://example.test?X-Amz-Signature=example-signature", + "https://example.test?X-Amz-Credential=example-credential", + "https://example.test?X-Goog-Signature=example-signature", + "//user:example-password@proxy.example.test:3128", + "/metadata?token=example-token", + "relative/cache?sig=weekly", + "file:///dir/x?sig=1", + "file://localhost/dir/x?sig=1", + r"C:\dir\x?sig=1", + "C://dir/x?sig=1", ], ) -def test_delta_azure_endpoint_passes_through_verbatim( - tmp_path: Path, endpoint: str, reverse: bool -) -> None: - uri = "az://fixtures/data" - public = { - "azure_storage_account_name": "fixtureaccount", - "azure_storage_endpoint": endpoint, - "azure_allow_http": "true", +def test_delta_saves_options_verbatim_as_on_main(tmp_path: Path, value: str) -> None: + options = { + "AWS_ENDPOINT_URL": value, + "aws_endpoint_url_sts": value, + "aws_container_credentials_relative_uri": value, + "azure_storage_endpoint": value, + "azure_proxy_url": value, + "google_base_url": value, + "unlisted_option": value, } - if reverse: - public = dict(reversed(public.items())) + uri = "az://fixtures/data" path = tmp_path / "job.json" - saved = _save(path, _arrow_source(), DeltaTableDatabase(uri, public)) - assert saved["database"]["storage_options"] == public - loaded = PipelineJob.load(path).database - assert isinstance(loaded, DeltaTableDatabase) + saved = _save(path, _arrow_source(), DeltaTableDatabase(uri, options))["database"] + assert saved["storage_options"] == options + + loaded = PipelineJob.load(path) + assert isinstance(loaded.database, DeltaTableDatabase) with patch("deltalake.DeltaTable", side_effect=TableNotFoundError) as open_table: - assert not loaded.table_exists(("table",)) - open_table.assert_called_once_with(f"{uri}/table", storage_options=public) + assert not loaded.database.table_exists(("table",)) + open_table.assert_called_once_with(f"{uri}/table", storage_options=options) + loaded.save(path) + assert json.loads(path.read_text())["bindings"]["database"] == saved -@pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize( - ("name", "value"), + "root", [ - ("root_uri", f"abfs://fixtures:{SECRET}@fixture.dfs.core.windows.net/data"), - ("root_uri", f"az://fixtures/data?sig={SECRET}"), - ("azure_storage_endpoint", f"https://fixture:{SECRET}@example.test"), - ("azure_storage_endpoint", f"ht\ttps://fixture:{SECRET}@127.0.0.1/"), - ("azure_storage_endpoint", f"https:\n//fixture:{SECRET}@127.0.0.1/"), - ("azure_storage_endpoint", f" https://fixture:{SECRET}@127.0.0.1/"), - ("azure_storage_endpoint", f"HTTPS://fixture:{SECRET}@[::1]/"), - ("azure_storage_endpoint", f"https://fixture:{SECRET}@[broken"), - ("azure_storage_endpoint", f"https://[broken?%53IG={SECRET}"), - ("azure_storage_endpoint", f"https://example.test?%53IG={SECRET}"), - ("AWS_ENDPOINT_URL", f"https://example.test?X-Amz-Signature={SECRET}"), - ("aws_endpoint_url_sts", f"https://example.test?X-Amz-Credential={SECRET}"), - ("google_base_url", f"https://example.test?X-Goog-Signature={SECRET}"), - ("azure_proxy_url", f"//fixture:{SECRET}@proxy.example.test:3128"), - ("aws_container_credentials_relative_uri", f"/metadata?token={SECRET}"), + "abfs://fixtures:example-password@fixture.dfs.core.windows.net/data", + "abfs://fixtures@fixture.dfs.core.windows.net/data?route=a%20b", + "az://fixtures/data?sig=example-signature", + "relative/logs@host:1?sig=weekly", + "file:///dir/x?sig=1", + "file://localhost/dir/x?sig=1", + r"C:\dir\x?sig=1", + "C://dir/x?sig=1", ], ) -def test_delta_refuses_urls_with_credentials( - tmp_path: Path, - caplog: pytest.LogCaptureFixture, - name: str, - value: str, - reverse: bool, +def test_delta_saves_roots_verbatim_as_on_main( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, root: str ) -> None: - options = PUBLIC_OPTIONS | PRIVATE_OPTIONS - uri = "az://fixtures/data" - if name == "root_uri": - uri = value - else: - options[name] = value - if reverse: - options = dict(reversed(options.items())) + monkeypatch.chdir(tmp_path) path = tmp_path / "job.json" - with pytest.raises(ValueError, match=name) as failure: - _save(path, _arrow_source(), DeltaTableDatabase(uri, options)) - assert not path.exists() - assert SECRET not in str(failure.value) + caplog.text + saved = _save(path, _arrow_source(), DeltaTableDatabase(root))["database"] + assert saved["root_uri"] == root + loaded = PipelineJob.load(path) + loaded.save(path) + assert json.loads(path.read_text())["bindings"]["database"] == saved @pytest.mark.parametrize( @@ -419,38 +427,6 @@ def test_delta_preserves_local_directory_and_reads_saved_table( assert record.select(payload.column_names) == payload -@pytest.mark.parametrize( - "root", - [ - "relative/logs@host:1?sig=weekly", - "file:///dir/x?sig=1", - "file://localhost/dir/x?sig=1", - r"C:\dir\x?sig=1", - "C://dir/x?sig=1", - ], -) -def test_delta_preserves_local_root_spelling( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, root: str -) -> None: - monkeypatch.chdir(tmp_path) - path = tmp_path / "job.json" - saved = _save(path, _arrow_source(), DeltaTableDatabase(root)) - assert saved["database"]["root_uri"] == root - loaded = PipelineJob.load(path).database - assert isinstance(loaded, DeltaTableDatabase) - assert loaded.to_config()["root_uri"] == root - - -def test_delta_preserves_abfs_container_and_public_query(tmp_path: Path) -> None: - uri = "abfs://fixtures@fixture.dfs.core.windows.net/data?route=a%20b" - path = tmp_path / "job.json" - saved = _save(path, _arrow_source(), DeltaTableDatabase(uri)) - assert saved["database"]["root_uri"] == uri - loaded = PipelineJob.load(path).database - assert isinstance(loaded, DeltaTableDatabase) - assert loaded.to_config()["root_uri"] == uri - - @pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize( ("arn_key", "session_key", "token_file_key"), @@ -676,7 +652,7 @@ def test_resaving_clean_retained_blocks_preserves_settings( @pytest.mark.parametrize("dsn", [CLEAN_DSN, _dsn()]) -def test_resaving_without_postgresql_extra_refuses( +def test_resaving_without_postgresql_extra_preserves_dsn( tmp_path: Path, postgres: MagicMock, monkeypatch: pytest.MonkeyPatch, @@ -706,16 +682,20 @@ def without_psycopg( loaded = PipelineJob.load(path) assert loaded.unbound_sources == [slot] target = tmp_path / "resaved.json" - with pytest.raises(ValueError, match="dsn.*psycopg") as failure: - loaded.save(target) - assert not target.exists() - assert PASSWORD not in str(failure.value) + caplog.text + loaded.save(target) + assert json.loads(target.read_text())["bindings"]["sources"][slot]["dsn"] == dsn + assert PASSWORD not in caplog.text @pytest.mark.parametrize( - "dsn", ["host=localhost password='broken " + PASSWORD, _dsn() + "&unknown=1"] + "dsn", + [ + "host=localhost password='broken " + PASSWORD, + _dsn() + "&unknown=1", + "host=localhost\x00 password=" + PASSWORD, + ], ) -def test_resaving_invalid_postgresql_dsn_refuses( +def test_resaving_invalid_postgresql_dsn_preserves_dsn( tmp_path: Path, postgres: MagicMock, caplog: pytest.LogCaptureFixture, dsn: str ) -> None: path = tmp_path / "original.json" @@ -724,20 +704,20 @@ def test_resaving_invalid_postgresql_dsn_refuses( (slot,) = data["bindings"]["sources"] data["bindings"]["sources"][slot]["dsn"] = dsn _ = path.write_text(json.dumps(data)) + postgres.side_effect = RuntimeError("connection unavailable") loaded = PipelineJob.load(path) assert loaded.unbound_sources == [slot] target = tmp_path / "resaved.json" - with pytest.raises(ValueError, match="dsn") as failure: - loaded.save(target) - assert not target.exists() - assert failure.value.__context__ is None - assert PASSWORD not in str(failure.value) + caplog.text + loaded.save(target) + assert json.loads(target.read_text())["bindings"]["sources"][slot]["dsn"] == dsn + assert PASSWORD not in caplog.text @pytest.mark.parametrize("reverse", [False, True]) def test_postgresql_job_save_uses_psycopg_conninfo( tmp_path: Path, postgres: MagicMock, caplog: pytest.LogCaptureFixture, reverse: bool ) -> None: + caplog.set_level(logging.DEBUG, logger="orcapod") options = [ "host=localhost", f"password='{PASSWORD}'", From c52ba1093ce2c7d0dba6fc410b48043f918e6ab5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 21:28:07 -0800 Subject: [PATCH 14/20] fix(postgresql): pass the base conninfo explicitly --- src/orcapod/databases/postgresql_connector.py | 3 ++- tests/test_databases/test_postgresql_connector.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 2681c44e7..3d34b122e 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -415,7 +415,8 @@ def _dsn_for_save(dsn: str) -> str: if _DSN_SECRET_KEYS.isdisjoint(options): return dsn return make_conninfo( - **{key: value for key, value in options.items() if key not in _DSN_SECRET_KEYS} + "", + **{key: value for key, value in options.items() if key not in _DSN_SECRET_KEYS}, ) diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index b752f817e..a3ccaba8f 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -224,7 +224,7 @@ def test_to_config(self, dsn: str) -> None: if key not in {"password", "sslpassword"} } assert config["dsn"] == ( - make_conninfo(**public) if public != options else dsn + make_conninfo("", **public) if public != options else dsn ) mock_connect.assert_called_once_with(dsn, autocommit=False) mock_connect.reset_mock() From 8db606735f6cecca07ce603bf48425a0b67be6fb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 22:11:22 -0800 Subject: [PATCH 15/20] fix(delta): omit credential aliases from saved jobs --- changelog.d/ITL-1394.md | 4 +- docs/dev/design_issues/ITL-1394-JB1.md | 5 +- src/orcapod/databases/delta_lake_databases.py | 62 ++++++++++++++- .../test_delta_table_database_s3.py | 45 +++++++++++ .../loaded_job/test_saved_credentials.py | 79 +++++++++++++++++-- 5 files changed, 185 insertions(+), 10 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index 390e685be..cc52ec3c4 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -9,8 +9,8 @@ ### Fixed - Delta databases, PostgreSQL connectors and their source wrappers apply the storage - backend's credential-key list when saving jobs. Earlier files still load with their - recorded settings. + backend's credential-key list when saving jobs, including OpenDAL and Unity Catalog + aliases for Delta. Earlier files still load with their recorded settings. - Saved Delta databases retain all other values verbatim, including roots, endpoints, regions, and AWS role identifiers. - Resaving a legacy job applies the same credential rules to retained source diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index 51a2976c9..7b02e391d 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -9,8 +9,9 @@ Delta database configs can contain credentials supplied directly or through a UP PostgreSQL connector and table source configs can contain passwords in connection strings. Saving a job exposes those values in plain text, including in wrapped configs. -**Fix:** Delta omits known credential option keys and preserves other values -verbatim. The PostgreSQL connector uses psycopg to omit `password`, `sslpassword`, +**Fix:** Delta omits known credential option keys, including OpenDAL and Unity +Catalog aliases, and preserves other values verbatim. The PostgreSQL connector +uses psycopg to omit `password`, `sslpassword`, and `oauth_client_secret` and serialize the remaining settings when any of those keys are parsed. Otherwise the connection string is saved verbatim. Older files still load their recorded values. Subsequent saves apply the same storage rules diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 5c4690eb5..637a6ff4a 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1820,11 +1820,19 @@ class _CommittedSnapshot: dataset_filesystem: "pa_fs.FileSystem | None" = None -# Option keys that carry credentials or point to credential material. +# Credential keys and their exact aliases. Native spellings come from object_store +# 0.13.2's aws/azure/gcp builder FromStr tables and deltalake 1.6.6's AWS option +# constants and UnityCatalogConfigKey parser. For OpenDAL, deltalake's +# crates/opendal/src/config.rs strips "opendal." and forwards the remainder to the +# services enabled in python/Cargo.toml. Their OpenDAL 0.56.0 config.rs fields and +# serde aliases supply the prefixed spellings below. Keep the existing AWS web +# identity file locators and identifiers such as role ARNs and GCS metadata +# service-account names. The Python wheel exposes no option-key catalog. _CREDENTIAL_STORAGE_OPTION_KEYS = frozenset( { "access_key", "access_key_id", + "access_token", "account_key", "application_credentials", "aws_access_key_id", @@ -1851,6 +1859,10 @@ class _CommittedSnapshot: "certificate_password", "client_secret", "container_authorization_token_file", + "databricks_access_token", + "databricks_client_secret", + "databricks_federated_token_file", + "databricks_token", "external_id", "fabric_session_token", "federated_token_file", @@ -1860,6 +1872,51 @@ class _CommittedSnapshot: "google_service_account_key", "google_service_account_path", "master_key", + "opendal.access_key", + "opendal.access_key_id", + "opendal.access_key_secret", + "opendal.account_key", + "opendal.application_key", + "opendal.application_key_id", + "opendal.aws_access_key_id", + "opendal.aws_secret_access_key", + "opendal.aws_session_token", + "opendal.aws_sse_customer_key_base64", + "opendal.aws_token", + "opendal.azure_storage_access_key", + "opendal.azure_storage_account_key", + "opendal.azure_storage_master_key", + "opendal.azure_storage_sas_key", + "opendal.azure_storage_sas_token", + "opendal.client_secret", + "opendal.credential", + "opendal.credential_path", + "opendal.delegation", + "opendal.encryption_key", + "opendal.external_id", + "opendal.google_application_credentials", + "opendal.google_service_account_key", + "opendal.key", + "opendal.master_key", + "opendal.oidc_token_file", + "opendal.password", + "opendal.sas_key", + "opendal.sas_token", + "opendal.secret_access_key", + "opendal.secret_id", + "opendal.secret_key", + "opendal.security_token", + "opendal.server_side_encryption_customer_key", + "opendal.service_account_key", + "opendal.session_token", + "opendal.temp_url_key", + "opendal.token", + "opendal.tos_access_key_id", + "opendal.tos_secret_access_key", + "opendal.tos_security_token", + "opendal.volcengine_access_key_id", + "opendal.volcengine_secret_access_key", + "opendal.volcengine_session_token", "sas_key", "sas_token", "secret_access_key", @@ -1869,6 +1926,9 @@ class _CommittedSnapshot: "session_token", "sse_customer_key_base64", "token", + "unity_access_token", + "unity_client_secret", + "unity_federated_token_file", } ) diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index ba036b00a..26769e047 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -65,6 +65,51 @@ def test_saved_job_reopens_s3_tables_with_environment_credentials( assert loaded.to_config()["storage_options"] == options +def test_saved_job_omits_opendal_s3_credentials( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + s3_base_uri: str, + s3_storage_options: dict[str, str], +) -> None: + """Write through OpenDAL and reopen the job with its configured database.""" + monkeypatch.chdir(tmp_path) + for key in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN"): + monkeypatch.delenv(key, raising=False) + public_options = { + "opendal.bucket": s3_base_uri.split("/")[2], + "opendal.endpoint": s3_storage_options["AWS_ENDPOINT_URL"], + "opendal.region": s3_storage_options["AWS_REGION"], + } + credentials = { + "opendal.access_key_id": s3_storage_options["AWS_ACCESS_KEY_ID"], + "opendal.secret_access_key": s3_storage_options["AWS_SECRET_ACCESS_KEY"], + } + database = DeltaTableDatabase( + f"opendal+{s3_base_uri}", storage_options=public_options | credentials + ) + data = pa.table({"x": [1]}) + database.add_record(("table",), b"id", data, flush=True) + path = tmp_path / "job.json" + with PipelineJob(database=database) as job: + source = ArrowTableSource( + pa.table({"t": [1], "x": [1]}), + source_id="data", + tag_columns="t", + tag_only_columns=True, + ) + _ = source.select_data_columns("x", label="selected") + job.save(path) + + assert json.loads(path.read_text())["bindings"]["database"]["storage_options"] == ( + public_options + ) + loaded = PipelineJob.load(path, database=database).database + assert isinstance(loaded, DeltaTableDatabase) + rows = loaded.get_record_by_id(("table",), b"id") + assert rows is not None + assert rows.select(["x"]) == data + + # --------------------------------------------------------------------------- # Core S3 operations # --------------------------------------------------------------------------- diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index 3b51f064d..74395be6d 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -26,9 +26,6 @@ DeltaTableDatabase, PostgreSQLConnector, ) -from orcapod.databases.delta_lake_databases import ( - _CREDENTIAL_STORAGE_OPTION_KEYS, -) from orcapod.databases.storage_utils import parse_base_path from orcapod.errors import InconsistentSourceError from orcapod.protocols.database_protocols import ArrowDatabaseProtocol @@ -291,18 +288,90 @@ def open_table(table_uri: str, storage_options: dict[str, str]) -> None: @pytest.mark.parametrize( "uri", ["s3://fixtures/data", "az://fixtures/data", "gs://fixtures/data"] ) -def test_delta_omits_every_listed_credential_option( +def test_delta_omits_credential_options_from_upstream_parsers( tmp_path: Path, caplog: pytest.LogCaptureFixture, uri: str, reverse: bool ) -> None: + # The deltalake 1.6.6 wheel has no Python API listing backend option names. + # Pin the expected keys independently of Orcapod's filter. Recheck the + # FromStr parsers in object_store 0.13.2 (aws/azure/gcp src/*/builder.rs) + # and delta-rs (crates/catalog-unity/src/lib.rs) on dependency upgrades. + native_keys = """ + access_key_id aws_access_key_id secret_access_key aws_secret_access_key + token session_token aws_token aws_session_token + aws_container_authorization_token_file container_authorization_token_file + sse_customer_key_base64 aws_sse_customer_key_base64 + access_key account_key master_key azure_storage_access_key + azure_storage_account_key azure_storage_master_key + sas_key sas_token azure_storage_sas_key azure_storage_sas_token + bearer_token azure_storage_token + client_secret azure_client_secret azure_storage_client_secret + federated_token_file azure_federated_token_file + fabric_session_token azure_fabric_session_token + service_account service_account_path google_service_account + google_service_account_path service_account_key google_service_account_key + application_credentials google_application_credentials + access_token unity_access_token databricks_access_token databricks_token + unity_client_secret databricks_client_secret + unity_federated_token_file databricks_federated_token_file + """.split() + retained_omissions = """ + aws_access_key_id_dynamodb aws_secret_access_key_dynamodb + aws_session_token_dynamodb aws_external_id external_id + certificate_password google_bearer_token + """.split() + # delta-rs python/Cargo.toml selects these OpenDAL 0.56.0 services. + # Each opendal-service-/src/config.rs declares fields and aliases. + opendal_keys = { + "s3": """ + access_key_id aws_access_key_id secret_access_key aws_secret_access_key + session_token aws_session_token aws_token token external_id + server_side_encryption_customer_key aws_sse_customer_key_base64 + """, + "azblob": """ + account_key access_key master_key azure_storage_account_key + azure_storage_access_key azure_storage_master_key encryption_key + sas_token sas_key azure_storage_sas_key azure_storage_sas_token + """, + "azdls": "account_key client_secret sas_token", + "gcs": """ + credential google_service_account_key service_account_key + credential_path google_application_credentials token + """, + "oss": "access_key_id access_key_secret security_token oidc_token_file", + "obs": "access_key_id secret_access_key", + "cos": "secret_id secret_key", + "tos": """ + access_key_id tos_access_key_id volcengine_access_key_id + secret_access_key tos_secret_access_key volcengine_secret_access_key + security_token tos_security_token volcengine_session_token + """, + "b2": "application_key_id application_key", + "swift": "token temp_url_key", + "webhdfs": "delegation", + "webdav": "password token", + "ftp": "password", + "sftp": "key", + "hf": "token", + } + expected_keys = set(native_keys + retained_omissions) + expected_keys.update( + f"opendal.{key}" for keys in opendal_keys.values() for key in keys.split() + ) caplog.set_level(logging.DEBUG, logger="orcapod") private = { (key.upper() if index % 2 else key.title()): f"{SECRET}-{index}" - for index, key in enumerate(sorted(_CREDENTIAL_STORAGE_OPTION_KEYS)) + for index, key in enumerate(sorted(expected_keys)) } public = { "unknown_option": " literal value ", "user_agent": "fixture-loader/1.0 (+https://example.test/project?sig=example)", "region": "", + "opendal.endpoint": "https://example.test/one?sig=example", + "opendal.region": " literal region ", + "opendal.role_arn": "arn:aws:iam::123456789012:role/fixture", + "opendal.service_account": "fixture@example.test", + "opendal.server_side_encryption_aws_kms_key_id": "alias/test-key", + "opendal.unknown_token_option": "literal value", } options = public | private if reverse: From 113e8c407acd631c590b0ca2dc49b93218f4cab8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 22:12:07 -0800 Subject: [PATCH 16/20] test(delta): type the pinned credential key set --- tests/test_pipeline/loaded_job/test_saved_credentials.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index 74395be6d..558a0a6b4 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -353,7 +353,7 @@ def test_delta_omits_credential_options_from_upstream_parsers( "sftp": "key", "hf": "token", } - expected_keys = set(native_keys + retained_omissions) + expected_keys: set[str] = set(native_keys + retained_omissions) expected_keys.update( f"opendal.{key}" for keys in opendal_keys.values() for key in keys.split() ) From 46dd14839ea0c2f4c55e554f5f73ab57db856a04 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 22:55:51 -0800 Subject: [PATCH 17/20] fix(delta): preserve credential file locators and role identifiers --- changelog.d/ITL-1394.md | 8 +- docs/concepts/pipeline-job.md | 4 +- docs/dev/design_issues/ITL-1394-JB1.md | 5 +- src/orcapod/databases/delta_lake_databases.py | 26 +---- .../loaded_job/test_saved_credentials.py | 94 ++++++++++++++----- 5 files changed, 87 insertions(+), 50 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index cc52ec3c4..21801f3ef 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -1,8 +1,8 @@ ### Breaking changes and migration -- Saved job files omit known Delta credential options and secret PostgreSQL connection - parameters that psycopg parses. Provide credentials through the storage backend's - environment or credential provider, pass the configured database to +- Saved job files omit known Delta options carrying secret values and PostgreSQL connection + secrets that psycopg parses. Provide omitted credentials through the storage + backend's environment or credential provider, pass the configured database to `PipelineJob.load()`, or bind a source that could not be rebuilt with `job.bind(sources=...)`. @@ -12,7 +12,7 @@ backend's credential-key list when saving jobs, including OpenDAL and Unity Catalog aliases for Delta. Earlier files still load with their recorded settings. - Saved Delta databases retain all other values verbatim, including roots, endpoints, - regions, and AWS role identifiers. + regions, credential-file paths, and AWS role identifiers. - Resaving a legacy job applies the same credential rules to retained source and database configurations, including nested storage wrappers. PostgreSQL uses psycopg to serialize the remaining connection settings after omitting secret keywords. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 144cf50cd..c292c6319 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -546,7 +546,9 @@ the **Nodes** table below the picture for each node's columns and status. ## Saving and loading `job.save(path)` writes the graph, database locations and source settings to a JSON file. -Delta omits its listed credential option keys and saves all other values verbatim. +Delta omits recognized options that carry secret values, such as access keys, +tokens, and inline service-account keys. It saves all other values verbatim, +including credential-file paths, role ARNs, and AWS external IDs. For PostgreSQL, when psycopg parses the connection string and finds `password`, `sslpassword`, or `oauth_client_secret`, it serializes the remaining settings. This includes omitting a URI password that psycopg returns as the `password` keyword. diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index 7b02e391d..64ccea9e7 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -9,8 +9,9 @@ Delta database configs can contain credentials supplied directly or through a UP PostgreSQL connector and table source configs can contain passwords in connection strings. Saving a job exposes those values in plain text, including in wrapped configs. -**Fix:** Delta omits known credential option keys, including OpenDAL and Unity -Catalog aliases, and preserves other values verbatim. The PostgreSQL connector +**Fix:** Delta omits options whose values carry secret material, including OpenDAL +and Unity Catalog aliases. It preserves credential-file locators, role identifiers +including AWS external IDs, and other settings verbatim. The PostgreSQL connector uses psycopg to omit `password`, `sslpassword`, and `oauth_client_secret` and serialize the remaining settings when any of those keys are parsed. Otherwise the connection string is saved verbatim. Older files diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 637a6ff4a..853dea020 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1825,20 +1825,18 @@ class _CommittedSnapshot: # constants and UnityCatalogConfigKey parser. For OpenDAL, deltalake's # crates/opendal/src/config.rs strips "opendal." and forwards the remainder to the # services enabled in python/Cargo.toml. Their OpenDAL 0.56.0 config.rs fields and -# serde aliases supply the prefixed spellings below. Keep the existing AWS web -# identity file locators and identifiers such as role ARNs and GCS metadata -# service-account names. The Python wheel exposes no option-key catalog. +# serde aliases supply the prefixed spellings below. Include a key only when +# its value is itself secret material (including access-key credentials and +# inline service-account keys). Preserve file locators, role identifiers +# including AWS external IDs, and other non-secret configuration verbatim. _CREDENTIAL_STORAGE_OPTION_KEYS = frozenset( { "access_key", "access_key_id", "access_token", "account_key", - "application_credentials", "aws_access_key_id", "aws_access_key_id_dynamodb", - "aws_container_authorization_token_file", - "aws_external_id", "aws_secret_access_key", "aws_secret_access_key_dynamodb", "aws_session_token", @@ -1847,7 +1845,6 @@ class _CommittedSnapshot: "aws_token", "azure_client_secret", "azure_fabric_session_token", - "azure_federated_token_file", "azure_storage_access_key", "azure_storage_account_key", "azure_storage_client_secret", @@ -1858,19 +1855,12 @@ class _CommittedSnapshot: "bearer_token", "certificate_password", "client_secret", - "container_authorization_token_file", "databricks_access_token", "databricks_client_secret", - "databricks_federated_token_file", "databricks_token", - "external_id", "fabric_session_token", - "federated_token_file", - "google_application_credentials", "google_bearer_token", - "google_service_account", "google_service_account_key", - "google_service_account_path", "master_key", "opendal.access_key", "opendal.access_key_id", @@ -1890,15 +1880,10 @@ class _CommittedSnapshot: "opendal.azure_storage_sas_token", "opendal.client_secret", "opendal.credential", - "opendal.credential_path", "opendal.delegation", "opendal.encryption_key", - "opendal.external_id", - "opendal.google_application_credentials", "opendal.google_service_account_key", - "opendal.key", "opendal.master_key", - "opendal.oidc_token_file", "opendal.password", "opendal.sas_key", "opendal.sas_token", @@ -1920,15 +1905,12 @@ class _CommittedSnapshot: "sas_key", "sas_token", "secret_access_key", - "service_account", "service_account_key", - "service_account_path", "session_token", "sse_customer_key_base64", "token", "unity_access_token", "unity_client_secret", - "unity_federated_token_file", } ) diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index 558a0a6b4..833b19db1 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -172,7 +172,6 @@ def test_delta_job_and_cached_source( "sas_token", "bearer_token", "azure_client_secret", - "federated_token_file", "azure_fabric_session_token", ), id="azure", @@ -189,11 +188,7 @@ def test_delta_job_and_cached_source( "google_proxy_url": "http://proxy.example.test:8080", }, ( - "google_service_account", - "service_account_path", - "google_service_account_path", "google_service_account_key", - "application_credentials", "google_bearer_token", "certificate_password", ), @@ -221,7 +216,6 @@ def test_delta_job_and_cached_source( "access_key_id", "secret_access_key", "aws_token", - "container_authorization_token_file", "aws_sse_customer_key_base64", ), id="s3", @@ -298,25 +292,20 @@ def test_delta_omits_credential_options_from_upstream_parsers( native_keys = """ access_key_id aws_access_key_id secret_access_key aws_secret_access_key token session_token aws_token aws_session_token - aws_container_authorization_token_file container_authorization_token_file sse_customer_key_base64 aws_sse_customer_key_base64 access_key account_key master_key azure_storage_access_key azure_storage_account_key azure_storage_master_key sas_key sas_token azure_storage_sas_key azure_storage_sas_token bearer_token azure_storage_token client_secret azure_client_secret azure_storage_client_secret - federated_token_file azure_federated_token_file fabric_session_token azure_fabric_session_token - service_account service_account_path google_service_account - google_service_account_path service_account_key google_service_account_key - application_credentials google_application_credentials + service_account_key google_service_account_key access_token unity_access_token databricks_access_token databricks_token unity_client_secret databricks_client_secret - unity_federated_token_file databricks_federated_token_file """.split() - retained_omissions = """ + legacy_secret_keys = """ aws_access_key_id_dynamodb aws_secret_access_key_dynamodb - aws_session_token_dynamodb aws_external_id external_id + aws_session_token_dynamodb certificate_password google_bearer_token """.split() # delta-rs python/Cargo.toml selects these OpenDAL 0.56.0 services. @@ -324,7 +313,7 @@ def test_delta_omits_credential_options_from_upstream_parsers( opendal_keys = { "s3": """ access_key_id aws_access_key_id secret_access_key aws_secret_access_key - session_token aws_session_token aws_token token external_id + session_token aws_session_token aws_token token server_side_encryption_customer_key aws_sse_customer_key_base64 """, "azblob": """ @@ -334,10 +323,9 @@ def test_delta_omits_credential_options_from_upstream_parsers( """, "azdls": "account_key client_secret sas_token", "gcs": """ - credential google_service_account_key service_account_key - credential_path google_application_credentials token + credential google_service_account_key service_account_key token """, - "oss": "access_key_id access_key_secret security_token oidc_token_file", + "oss": "access_key_id access_key_secret security_token", "obs": "access_key_id secret_access_key", "cos": "secret_id secret_key", "tos": """ @@ -350,10 +338,9 @@ def test_delta_omits_credential_options_from_upstream_parsers( "webhdfs": "delegation", "webdav": "password token", "ftp": "password", - "sftp": "key", "hf": "token", } - expected_keys: set[str] = set(native_keys + retained_omissions) + expected_keys: set[str] = set(native_keys + legacy_secret_keys) expected_keys.update( f"opendal.{key}" for keys in opendal_keys.values() for key in keys.split() ) @@ -388,6 +375,71 @@ def test_delta_omits_credential_options_from_upstream_parsers( assert all(secret not in output for secret in private.values()) +@pytest.mark.parametrize( + ("uri", "locator_keys", "role_keys"), + [ + ( + "gs://fixtures/data", + "google_service_account google_service_account_path service_account " + "service_account_path google_application_credentials application_credentials", + "", + ), + ( + "opendal+gcs://fixtures/data", + "opendal.credential_path opendal.google_application_credentials", + "", + ), + ("opendal+sftp://localhost/data", "opendal.key", ""), + ( + "opendal+oss://fixtures/data", + "opendal.oidc_token_file", + "opendal.role_arn opendal.oidc_provider_arn", + ), + ( + "az://fixtures/data", + "azure_federated_token_file federated_token_file", + "", + ), + ( + "uc://catalog/schema/fixture", + "unity_federated_token_file databricks_federated_token_file", + "", + ), + ( + "s3://fixtures/data", + "aws_container_authorization_token_file container_authorization_token_file " + "aws_web_identity_token_file web_identity_token_file", + "aws_external_id external_id aws_role_arn role_arn " + "aws_iam_role_arn aws_s3_assume_role_arn", + ), + ( + "opendal+s3://fixtures/data", + "", + "opendal.external_id opendal.role_arn opendal.role_session_name", + ), + ], +) +def test_delta_preserves_credential_locators_and_role_options( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + uri: str, + locator_keys: str, + role_keys: str, +) -> None: + monkeypatch.chdir(tmp_path) + # Use distinct strings to catch dropped aliases, normalization, and rewrites. + options = { + key.title(): f" ./fixtures/λ/{key}.json " for key in locator_keys.split() + } | {key.upper(): f" arn:example:fixture:λ/{key} " for key in role_keys.split()} + path = tmp_path / "job.json" + saved = _save(path, _arrow_source(), DeltaTableDatabase(uri, options)) + job = PipelineJob.load(path) + resaved_path = tmp_path / "resaved.json" + job.save(resaved_path) + assert saved["database"]["storage_options"] == options + assert resaved_path.read_bytes() == path.read_bytes() + + # On main, saving and loading a Delta binding preserves these strings as supplied. @pytest.mark.parametrize( "value", @@ -522,7 +574,7 @@ def test_delta_aws_role_settings_reach_backend_after_round_trip( token_file_key: str(tmp_path / "web-identity.jwt"), "AWS_REGION": "us-east-1", } - private = {"AWS_EXTERNAL_ID": SECRET, "AWS_SECRET_ACCESS_KEY": SECRET} + private = {"AWS_SECRET_ACCESS_KEY": SECRET} options = public | private if reverse: options = dict(reversed(options.items())) From e8d024d069b79a9a0da1163700e75990a22fca75 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 23:44:05 -0800 Subject: [PATCH 18/20] fix(delta): preserve credential identifiers in saved jobs --- changelog.d/ITL-1394.md | 6 +- docs/concepts/pipeline-job.md | 7 +- docs/dev/design_issues/ITL-1394-JB1.md | 7 +- src/orcapod/databases/delta_lake_databases.py | 15 +--- .../test_delta_table_database_s3.py | 30 +++++-- .../loaded_job/test_saved_credentials.py | 87 ++++++++++++++++--- 6 files changed, 111 insertions(+), 41 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index 21801f3ef..496b9b744 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -11,8 +11,10 @@ - Delta databases, PostgreSQL connectors and their source wrappers apply the storage backend's credential-key list when saving jobs, including OpenDAL and Unity Catalog aliases for Delta. Earlier files still load with their recorded settings. -- Saved Delta databases retain all other values verbatim, including roots, endpoints, - regions, credential-file paths, and AWS role identifiers. +- Saved Delta databases keep access-key IDs verbatim and omit the secret half of + each recognized access-key pair. They also retain account names, client and tenant + IDs, usernames, roots, endpoints, regions, credential-file paths, and AWS role + identifiers. - Resaving a legacy job applies the same credential rules to retained source and database configurations, including nested storage wrappers. PostgreSQL uses psycopg to serialize the remaining connection settings after omitting secret keywords. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 161494f05..b63c9a30a 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -557,9 +557,10 @@ the **Nodes** table below the picture for each node's columns and status. ## Saving and loading `job.save(path)` writes the graph, database locations and source settings to a JSON file. -Delta omits recognized options that carry secret values, such as access keys, -tokens, and inline service-account keys. It saves all other values verbatim, -including credential-file paths, role ARNs, and AWS external IDs. +For an access-key pair, Delta saves the access-key ID and omits the secret access key. +It also omits other recognized secret values, such as tokens and inline service-account +keys. It saves all other values verbatim, including account names, client and tenant +IDs, usernames, credential-file paths, role ARNs, and AWS external IDs. For PostgreSQL, when psycopg parses the connection string and finds `password`, `sslpassword`, or `oauth_client_secret`, it serializes the remaining settings. This includes omitting a URI password that psycopg returns as the `password` keyword. diff --git a/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md index 64ccea9e7..5f862dfa3 100644 --- a/docs/dev/design_issues/ITL-1394-JB1.md +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -10,9 +10,10 @@ PostgreSQL connector and table source configs can contain passwords in connectio strings. Saving a job exposes those values in plain text, including in wrapped configs. **Fix:** Delta omits options whose values carry secret material, including OpenDAL -and Unity Catalog aliases. It preserves credential-file locators, role identifiers -including AWS external IDs, and other settings verbatim. The PostgreSQL connector -uses psycopg to omit `password`, `sslpassword`, +and Unity Catalog aliases. It saves access-key IDs verbatim and omits the secret +half of each recognized pair. It also preserves credential-file locators, role +identifiers including AWS external IDs, and other settings verbatim. The PostgreSQL +connector uses psycopg to omit `password`, `sslpassword`, and `oauth_client_secret` and serialize the remaining settings when any of those keys are parsed. Otherwise the connection string is saved verbatim. Older files still load their recorded values. Subsequent saves apply the same storage rules diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 6a77c1e83..610d75342 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1831,17 +1831,14 @@ class _CommittedSnapshot: # crates/opendal/src/config.rs strips "opendal." and forwards the remainder to the # services enabled in python/Cargo.toml. Their OpenDAL 0.56.0 config.rs fields and # serde aliases supply the prefixed spellings below. Include a key only when -# its value is itself secret material (including access-key credentials and -# inline service-account keys). Preserve file locators, role identifiers -# including AWS external IDs, and other non-secret configuration verbatim. +# its value carries secret material, such as the signing half of an access-key +# pair or an inline service-account key. Preserve identifiers such as access-key +# IDs and role ARNs, file locators, and other non-secret values verbatim. _CREDENTIAL_STORAGE_OPTION_KEYS = frozenset( { "access_key", - "access_key_id", "access_token", "account_key", - "aws_access_key_id", - "aws_access_key_id_dynamodb", "aws_secret_access_key", "aws_secret_access_key_dynamodb", "aws_session_token", @@ -1868,12 +1865,9 @@ class _CommittedSnapshot: "google_service_account_key", "master_key", "opendal.access_key", - "opendal.access_key_id", "opendal.access_key_secret", "opendal.account_key", "opendal.application_key", - "opendal.application_key_id", - "opendal.aws_access_key_id", "opendal.aws_secret_access_key", "opendal.aws_session_token", "opendal.aws_sse_customer_key_base64", @@ -1893,7 +1887,6 @@ class _CommittedSnapshot: "opendal.sas_key", "opendal.sas_token", "opendal.secret_access_key", - "opendal.secret_id", "opendal.secret_key", "opendal.security_token", "opendal.server_side_encryption_customer_key", @@ -1901,10 +1894,8 @@ class _CommittedSnapshot: "opendal.session_token", "opendal.temp_url_key", "opendal.token", - "opendal.tos_access_key_id", "opendal.tos_secret_access_key", "opendal.tos_security_token", - "opendal.volcengine_access_key_id", "opendal.volcengine_secret_access_key", "opendal.volcengine_session_token", "sas_key", diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index 26769e047..ab611913f 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -29,17 +29,30 @@ pytestmark = pytest.mark.s3 +@pytest.mark.parametrize( + "configured_id_key", [None, "aws_access_key_id", "AcCeSs_KeY_Id"] +) def test_saved_job_reopens_s3_tables_with_environment_credentials( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, s3_base_uri: str, s3_storage_options: dict[str, str], + configured_id_key: str | None, ) -> None: options = { **s3_storage_options, "AWS_ENDPOINT_URL_STS": "https://sts.example.test", "AWS_VIRTUAL_HOSTED_STYLE_REQUEST": "false", } + access_key_id = options.pop("AWS_ACCESS_KEY_ID") + secret_access_key = options.pop("AWS_SECRET_ACCESS_KEY") + monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", secret_access_key) + if configured_id_key is None: + monkeypatch.setenv("AWS_ACCESS_KEY_ID", access_key_id) + else: + for key in ("AWS_ACCESS_KEY_ID", "ACCESS_KEY_ID"): + monkeypatch.delenv(key, raising=False) + options[configured_id_key] = access_key_id database = DeltaTableDatabase(s3_base_uri, storage_options=options) data = pa.table({"x": [1], "y": [2]}) database.add_record(("table",), b"id", data, flush=True) @@ -54,18 +67,18 @@ def test_saved_job_reopens_s3_tables_with_environment_credentials( _ = source.select_data_columns(["x", "y"], label="selected") job.save(path) - credential_keys = ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY") - for key in credential_keys: - monkeypatch.setenv(key, options.pop(key)) loaded = PipelineJob.load(path).database assert isinstance(loaded, DeltaTableDatabase) rows = loaded.get_record_by_id(("table",), b"id") assert rows is not None assert rows.select(["x", "y"]) == data + assert json.loads(path.read_text())["bindings"]["database"]["storage_options"] == ( + options + ) assert loaded.to_config()["storage_options"] == options -def test_saved_job_omits_opendal_s3_credentials( +def test_saved_job_keeps_opendal_s3_key_id_and_omits_secret( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, s3_base_uri: str, @@ -76,16 +89,15 @@ def test_saved_job_omits_opendal_s3_credentials( for key in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN"): monkeypatch.delenv(key, raising=False) public_options = { + "opendal.access_key_id": s3_storage_options["AWS_ACCESS_KEY_ID"], "opendal.bucket": s3_base_uri.split("/")[2], "opendal.endpoint": s3_storage_options["AWS_ENDPOINT_URL"], "opendal.region": s3_storage_options["AWS_REGION"], } - credentials = { - "opendal.access_key_id": s3_storage_options["AWS_ACCESS_KEY_ID"], - "opendal.secret_access_key": s3_storage_options["AWS_SECRET_ACCESS_KEY"], - } database = DeltaTableDatabase( - f"opendal+{s3_base_uri}", storage_options=public_options | credentials + f"opendal+{s3_base_uri}", + storage_options=public_options + | {"opendal.secret_access_key": s3_storage_options["AWS_SECRET_ACCESS_KEY"]}, ) data = pa.table({"x": [1]}) database.add_record(("table",), b"id", data, flush=True) diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index 833b19db1..99cac904c 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -41,6 +41,7 @@ SSL_PASSWORD = "synthetic-ssl-password" CLEAN_DSN = "postgresql://user@localhost:5432/mydb?application_name=app%20name" PUBLIC_OPTIONS = { + "AWS_ACCESS_KEY_ID": "synthetic-access-key-id", "AWS_REGION": "us-east-1", "aws_DEFAULT_region": "us-east-2", "AWS_ENDPOINT_URL": "https://storage.example.test", @@ -48,7 +49,6 @@ "AWS_VIRTUAL_HOSTED_STYLE_REQUEST": "true", } PRIVATE_OPTIONS = { - "AWS_ACCESS_KEY_ID": "synthetic-access-key", "AWS_SECRET_ACCESS_KEY": SECRET, "AWS_SESSION_TOKEN": "synthetic-session-token", "AZURE_STORAGE_SAS_KEY": "synthetic-sas", @@ -114,7 +114,7 @@ def test_delta_job_and_cached_source( ) -> None: if via_upath: upath_options = { - "key": PRIVATE_OPTIONS["AWS_ACCESS_KEY_ID"], + "key": PUBLIC_OPTIONS["AWS_ACCESS_KEY_ID"], "secret": SECRET, "token": PRIVATE_OPTIONS["AWS_SESSION_TOKEN"], "client_kwargs": {"endpoint_url": PUBLIC_OPTIONS["AWS_ENDPOINT_URL"]}, @@ -124,7 +124,10 @@ def test_delta_job_and_cached_source( database = DeltaTableDatabase( UPath("s3://test-bucket/data", **cast("dict[str, Any]", upath_options)) ) - public = {"AWS_ENDPOINT_URL": PUBLIC_OPTIONS["AWS_ENDPOINT_URL"]} + public = { + key: PUBLIC_OPTIONS[key] + for key in ("AWS_ACCESS_KEY_ID", "AWS_ENDPOINT_URL") + } else: options = PUBLIC_OPTIONS | PRIVATE_OPTIONS if reverse: @@ -211,9 +214,9 @@ def test_delta_job_and_cached_source( "aws_skip_signature": "false", "aws_sse_kms_key_id": "alias/test-key", "aws_connect_timeout": "5s", + "access_key_id": "fixture-key-id", }, ( - "access_key_id", "secret_access_key", "aws_token", "aws_sse_customer_key_base64", @@ -290,7 +293,7 @@ def test_delta_omits_credential_options_from_upstream_parsers( # FromStr parsers in object_store 0.13.2 (aws/azure/gcp src/*/builder.rs) # and delta-rs (crates/catalog-unity/src/lib.rs) on dependency upgrades. native_keys = """ - access_key_id aws_access_key_id secret_access_key aws_secret_access_key + secret_access_key aws_secret_access_key token session_token aws_token aws_session_token sse_customer_key_base64 aws_sse_customer_key_base64 access_key account_key master_key azure_storage_access_key @@ -304,7 +307,7 @@ def test_delta_omits_credential_options_from_upstream_parsers( unity_client_secret databricks_client_secret """.split() legacy_secret_keys = """ - aws_access_key_id_dynamodb aws_secret_access_key_dynamodb + aws_secret_access_key_dynamodb aws_session_token_dynamodb certificate_password google_bearer_token """.split() @@ -312,7 +315,7 @@ def test_delta_omits_credential_options_from_upstream_parsers( # Each opendal-service-/src/config.rs declares fields and aliases. opendal_keys = { "s3": """ - access_key_id aws_access_key_id secret_access_key aws_secret_access_key + secret_access_key aws_secret_access_key session_token aws_session_token aws_token token server_side_encryption_customer_key aws_sse_customer_key_base64 """, @@ -325,15 +328,14 @@ def test_delta_omits_credential_options_from_upstream_parsers( "gcs": """ credential google_service_account_key service_account_key token """, - "oss": "access_key_id access_key_secret security_token", - "obs": "access_key_id secret_access_key", - "cos": "secret_id secret_key", + "oss": "access_key_secret security_token", + "obs": "secret_access_key", + "cos": "secret_key", "tos": """ - access_key_id tos_access_key_id volcengine_access_key_id secret_access_key tos_secret_access_key volcengine_secret_access_key security_token tos_security_token volcengine_session_token """, - "b2": "application_key_id application_key", + "b2": "application_key", "swift": "token temp_url_key", "webhdfs": "delegation", "webdav": "password token", @@ -440,6 +442,67 @@ def test_delta_preserves_credential_locators_and_role_options( assert resaved_path.read_bytes() == path.read_bytes() +@pytest.mark.parametrize( + ("uri", "keys"), + [ + ( + "s3://fixtures/data", + "access_key_id aws_access_key_id aws_access_key_id_dynamodb", + ), + ( + "az://fixtures/data", + "account_name azure_storage_account_name client_id azure_client_id " + "azure_storage_client_id tenant_id azure_tenant_id azure_storage_tenant_id " + "authority_id azure_authority_id azure_storage_authority_id " + "azure_object_id object_id azure_msi_resource_id msi_resource_id", + ), + ( + "uc://catalog/schema/fixture", + "client_id unity_client_id databricks_client_id", + ), + ( + "opendal+s3://fixtures/data", + "opendal.access_key_id opendal.aws_access_key_id", + ), + ( + "opendal+tos://fixtures/data", + "opendal.access_key_id opendal.tos_access_key_id opendal.volcengine_access_key_id", + ), + ("opendal+b2://fixtures/data", "opendal.application_key_id"), + ("opendal+cos://fixtures/data", "opendal.secret_id"), + ( + "opendal+azblob://fixtures/data", + "opendal.account_name opendal.azure_storage_account_name", + ), + ( + "opendal+azdls://fixtures/data", + "opendal.account_name opendal.client_id opendal.tenant_id", + ), + ("opendal+webhdfs://fixtures/data", "opendal.user_name"), + ("opendal+webdav://fixtures/data", "opendal.username"), + ("opendal+ftp://fixtures/data", "opendal.user"), + ("opendal+sftp://localhost/data", "opendal.user"), + ], +) +def test_delta_preserves_identifiers_as_on_main( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, uri: str, keys: str +) -> None: + monkeypatch.chdir(tmp_path) + options = { + spelling: f" fixture-λ/{spelling} " + for key in keys.split() + for spelling in (key, key.upper(), key.title()) + } + path = tmp_path / "job.json" + saved = _save(path, _arrow_source(), DeltaTableDatabase(uri, options)) + assert saved["database"]["storage_options"] == options + + job = PipelineJob.load(path) + resaved_path = tmp_path / "resaved.json" + job.save(resaved_path) + assert resaved_path.read_bytes() == path.read_bytes() + + # On main, saving and loading a Delta binding preserves these strings as supplied. @pytest.mark.parametrize( "value", From 8697058b2fc978a8f51801133240b7af591ba237 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 01:13:39 -0800 Subject: [PATCH 19/20] test(storage): skip Windows-invalid Delta roots on Windows --- .../loaded_job/test_saved_credentials.py | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index 99cac904c..649722657 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -5,6 +5,7 @@ import builtins import json import logging +import sys from collections.abc import Iterator, Mapping, Sequence from pathlib import Path from typing import Any, cast @@ -55,6 +56,10 @@ "GOOGLE_SERVICE_ACCOUNT_KEY": "synthetic-service-account", } +_POSIX_LOCAL_NAME = pytest.mark.skipif( + sys.platform == "win32", reason="Windows cannot create these local path names" +) + def _dsn(password: str = PASSWORD) -> str: return ( @@ -570,11 +575,11 @@ def test_delta_saves_options_verbatim_as_on_main(tmp_path: Path, value: str) -> "abfs://fixtures:example-password@fixture.dfs.core.windows.net/data", "abfs://fixtures@fixture.dfs.core.windows.net/data?route=a%20b", "az://fixtures/data?sig=example-signature", - "relative/logs@host:1?sig=weekly", - "file:///dir/x?sig=1", - "file://localhost/dir/x?sig=1", - r"C:\dir\x?sig=1", - "C://dir/x?sig=1", + pytest.param("relative/logs@host:1?sig=weekly", marks=_POSIX_LOCAL_NAME), + pytest.param("file:///dir/x?sig=1", marks=_POSIX_LOCAL_NAME), + pytest.param("file://localhost/dir/x?sig=1", marks=_POSIX_LOCAL_NAME), + pytest.param(r"C:\dir\x?sig=1", marks=_POSIX_LOCAL_NAME), + pytest.param("C://dir/x?sig=1", marks=_POSIX_LOCAL_NAME), ], ) def test_delta_saves_roots_verbatim_as_on_main( @@ -590,7 +595,12 @@ def test_delta_saves_roots_verbatim_as_on_main( @pytest.mark.parametrize( - "name", ["cache?sig=weekly", "cache?token=demo", "logs@host:1"] + "name", + [ + pytest.param("cache?sig=weekly", marks=_POSIX_LOCAL_NAME), + pytest.param("cache?token=demo", marks=_POSIX_LOCAL_NAME), + pytest.param("logs@host:1", marks=_POSIX_LOCAL_NAME), + ], ) def test_delta_preserves_local_directory_and_reads_saved_table( tmp_path: Path, name: str From 665fa5e3c47084cd5e00174a016482ec4ca124c9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 02:12:54 -0800 Subject: [PATCH 20/20] docs(storage): clarify saved credential behavior --- changelog.d/ITL-1394.md | 4 +++ docs/concepts/pipeline-job.md | 30 +++++++++++++++---- src/orcapod/databases/delta_lake_databases.py | 8 ++++- src/orcapod/databases/postgresql_connector.py | 8 ++++- .../loaded_job/test_saved_credentials.py | 9 ------ 5 files changed, 43 insertions(+), 16 deletions(-) diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md index 496b9b744..e932a4f1a 100644 --- a/changelog.d/ITL-1394.md +++ b/changelog.d/ITL-1394.md @@ -5,6 +5,10 @@ backend's environment or credential provider, pass the configured database to `PipelineJob.load()`, or bind a source that could not be rebuilt with `job.bind(sources=...)`. +- When a reloaded S3 Delta database has a saved access-key ID and no matching + secret in its storage options, `list_table_paths()` raises + `TableListingNotSupportedError` with a missing-secret cause, so pass a database + configured with both credential options to `PipelineJob.load()`. ### Fixed diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index b63c9a30a..677cfaa2a 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -558,9 +558,10 @@ the **Nodes** table below the picture for each node's columns and status. `job.save(path)` writes the graph, database locations and source settings to a JSON file. For an access-key pair, Delta saves the access-key ID and omits the secret access key. -It also omits other recognized secret values, such as tokens and inline service-account -keys. It saves all other values verbatim, including account names, client and tenant -IDs, usernames, credential-file paths, role ARNs, and AWS external IDs. +It also omits the other secret values listed in +[Delta storage options omitted on save](#delta-storage-options-omitted-on-save). +It saves all other values verbatim, including account names, client and tenant IDs, +usernames, credential-file paths, role ARNs, and AWS external IDs. For PostgreSQL, when psycopg parses the connection string and finds `password`, `sslpassword`, or `oauth_client_secret`, it serializes the remaining settings. This includes omitting a URI password that psycopg returns as the `password` keyword. @@ -578,8 +579,11 @@ Supply omitted credentials again through the backend's environment or its usual credential provider, such as a PostgreSQL password file. Supply a database explicitly with `PipelineJob.load(path, database=...)` or `PipelineJob.load(path, result_database=...)` when it needs explicit credentials or has -moved. For a connector database (SQLite, PostgreSQL, SpiralDB), always pass the database -built over your connector. If a source cannot be rebuilt, bind it after loading with +moved. When a reloaded S3 Delta database has a saved access-key ID and no matching secret +in its storage options, `list_table_paths()` raises `TableListingNotSupportedError` with +a missing-secret cause, so pass a database configured with both credential options to +`PipelineJob.load()`. For a connector database (SQLite, PostgreSQL, SpiralDB), always +pass the database built over your connector. If a source cannot be rebuilt, bind it after loading with `job.bind(sources={...})`. Saving a loaded job writes the bound database's settings when available and otherwise keeps the recorded settings. @@ -636,6 +640,22 @@ inputs that is not known to be commutative (`MergeJoin`, `SemiJoin`, or an opera cannot be rebuilt in this process); build the job from its code and save it again. A file whose multi-input operators are all commutative (`Join`, `Rejoin`) loads as before. +### Delta storage options omitted on save + +Delta matches these option names case-insensitively. + +| Options | Names omitted | +| --- | --- | +| AWS | `aws_secret_access_key`, `aws_secret_access_key_dynamodb`, `aws_session_token`, `aws_session_token_dynamodb`, `aws_sse_customer_key_base64`, `aws_token` | +| Azure | `azure_client_secret`, `azure_fabric_session_token`, `azure_storage_access_key`, `azure_storage_account_key`, `azure_storage_client_secret`, `azure_storage_master_key`, `azure_storage_sas_key`, `azure_storage_sas_token`, `azure_storage_token` | +| Google Cloud | `google_bearer_token`, `google_service_account_key` | +| Databricks and Unity Catalog | `databricks_access_token`, `databricks_client_secret`, `databricks_token`, `unity_access_token`, `unity_client_secret` | +| Unprefixed names | `access_key`, `access_token`, `account_key`, `bearer_token`, `certificate_password`, `client_secret`, `fabric_session_token`, `master_key`, `sas_key`, `sas_token`, `secret_access_key`, `service_account_key`, `session_token`, `sse_customer_key_base64`, `token` | +| OpenDAL AWS and S3 options | `opendal.aws_secret_access_key`, `opendal.aws_session_token`, `opendal.aws_sse_customer_key_base64`, `opendal.aws_token`, `opendal.server_side_encryption_customer_key` | +| OpenDAL Azure options | `opendal.azure_storage_access_key`, `opendal.azure_storage_account_key`, `opendal.azure_storage_master_key`, `opendal.azure_storage_sas_key`, `opendal.azure_storage_sas_token` | +| OpenDAL Google Cloud and TOS options | `opendal.google_service_account_key`, `opendal.tos_secret_access_key`, `opendal.tos_security_token`, `opendal.volcengine_secret_access_key`, `opendal.volcengine_session_token` | +| Other OpenDAL names | `opendal.access_key`, `opendal.access_key_secret`, `opendal.account_key`, `opendal.application_key`, `opendal.client_secret`, `opendal.credential`, `opendal.delegation`, `opendal.encryption_key`, `opendal.master_key`, `opendal.password`, `opendal.sas_key`, `opendal.sas_token`, `opendal.secret_access_key`, `opendal.secret_key`, `opendal.security_token`, `opendal.service_account_key`, `opendal.session_token`, `opendal.temp_url_key`, `opendal.token` | + ## How it connects to other concepts - A job records applications of [Function Pods](function-pods.md) and diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 610d75342..4783b24bb 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -3691,7 +3691,13 @@ def get_records_by_ids( ) def to_config(self, db_registry: Any = None) -> dict[str, Any]: - """Serialize database configuration with credential values omitted.""" + """Serialize the database with listed secret storage options omitted. + + Option names are matched case-insensitively against the table in + `docs/concepts/pipeline-job.md` (Delta storage options omitted on save). + The root URI and all other option values are saved verbatim, including + any credentials embedded in URL or path values. + """ config: dict[str, Any] = { "type": "delta_table", "root_uri": self._root_uri, # renamed from "base_path" diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 210469270..0e87ee159 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -1105,7 +1105,13 @@ def __exit__(self, *args: Any) -> None: # ── Serialization ───────────────────────────────────────────────────────── def to_config(self) -> dict[str, Any]: - """Serialize libpq connection settings with secret parameters omitted.""" + """Serialize libpq connection settings. + + When psycopg parses the full DSN and finds a top-level `password`, + `sslpassword`, or `oauth_client_secret`, serialize the remaining settings. + Save the original DSN verbatim if psycopg is unavailable, the full DSN + cannot be parsed, or none of those parameters is present. + """ return self.config_for_resave( {"connector_type": "postgresql", "dsn": self._dsn} ) diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py index 649722657..b3a3a0bc0 100644 --- a/tests/test_pipeline/loaded_job/test_saved_credentials.py +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -833,15 +833,6 @@ def test_resaving_clean_retained_blocks_preserves_settings( loaded.save(target) field = "database" if binding == "delta" else "sources" saved = json.loads(target.read_text())["bindings"] - if binding == "postgresql": - (config,) = saved["sources"].values() - assert conninfo_to_dict(config["dsn"]) == conninfo_to_dict(CLEAN_DSN) - source_config["dsn"] = config["dsn"] - elif binding == "nested": - (config,) = saved["sources"].values() - dsn = config["inner_source"]["origin"]["dsn"] - assert conninfo_to_dict(dsn) == conninfo_to_dict(CLEAN_DSN) - source_config["inner_source"]["origin"]["dsn"] = dsn assert json.dumps(saved[field], indent=2) == json.dumps(bindings[field], indent=2)