diff --git a/changelog.d/ITL-1394.md b/changelog.d/ITL-1394.md new file mode 100644 index 000000000..e932a4f1a --- /dev/null +++ b/changelog.d/ITL-1394.md @@ -0,0 +1,33 @@ +### Breaking changes and migration + +- 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=...)`. +- 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 + +- 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 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. + +### 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 58b9037d1..677cfaa2a 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -556,16 +556,38 @@ 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. +For an access-key pair, Delta saves the access-key ID and omits the secret access key. +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. +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 +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. 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. + +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. @@ -618,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/docs/dev/design_issues/ITL-1394-JB1.md b/docs/dev/design_issues/ITL-1394-JB1.md new file mode 100644 index 000000000..5f862dfa3 --- /dev/null +++ b/docs/dev/design_issues/ITL-1394-JB1.md @@ -0,0 +1,22 @@ +## `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 omits options whose values carry secret material, including OpenDAL +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 +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/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 5be483a96..e14373dfb 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 @@ -215,6 +215,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 d81050918..9853975ef 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -333,6 +333,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 dc5dee6f2..714eee8d0 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 @@ -433,6 +433,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 58acc1f17..d0fd966d7 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,15 @@ 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 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( diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 4384c8e57..db49e4690 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -353,8 +353,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 71ed8c774..127ad02b4 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1195,6 +1195,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 4e2fa16cc..4783b24bb 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1825,6 +1825,92 @@ class _CommittedSnapshot: dataset_filesystem: "pa_fs.FileSystem | None" = None +# 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. Include a key only when +# 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_token", + "account_key", + "aws_secret_access_key", + "aws_secret_access_key_dynamodb", + "aws_session_token", + "aws_session_token_dynamodb", + "aws_sse_customer_key_base64", + "aws_token", + "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", + "bearer_token", + "certificate_password", + "client_secret", + "databricks_access_token", + "databricks_client_secret", + "databricks_token", + "fabric_session_token", + "google_bearer_token", + "google_service_account_key", + "master_key", + "opendal.access_key", + "opendal.access_key_secret", + "opendal.account_key", + "opendal.application_key", + "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.delegation", + "opendal.encryption_key", + "opendal.google_service_account_key", + "opendal.master_key", + "opendal.password", + "opendal.sas_key", + "opendal.sas_token", + "opendal.secret_access_key", + "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_secret_access_key", + "opendal.tos_security_token", + "opendal.volcengine_secret_access_key", + "opendal.volcengine_session_token", + "sas_key", + "sas_token", + "secret_access_key", + "service_account_key", + "session_token", + "sse_customer_key_base64", + "token", + "unity_access_token", + "unity_client_secret", + } +) + + class DeltaTableDatabase: """ A Delta table database with clear insert vs update semantics. @@ -3605,7 +3691,13 @@ 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 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" @@ -3616,6 +3708,21 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: } 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]: + """Omit dedicated credential options from live and retained configurations.""" + options: object = config.get("storage_options") + if isinstance(options, dict): + 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 @@ -3637,9 +3744,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 32620eb99..0e87ee159 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -383,6 +383,43 @@ 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.") + + +_DSN_SECRET_KEYS = frozenset({"password", "sslpassword", "oauth_client_secret"}) + + +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: + return dsn + + 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}, + ) + + def _psycopg_server(dsn: str) -> tuple[str, str]: """Return the ``host`` and ``hostaddr`` psycopg reads for ``dsn``, now. @@ -390,9 +427,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 "") @@ -1066,11 +1105,24 @@ def __exit__(self, *args: Any) -> None: # ── Serialization ───────────────────────────────────────────────────────── def to_config(self) -> dict[str, Any]: - """Serialize connection configuration to a JSON-compatible dict.""" - return { - "connector_type": "postgresql", - "dsn": self._dsn, - } + """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} + ) + + @classmethod + def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: + """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(dsn)} @classmethod def from_config(cls, config: dict[str, Any]) -> PostgreSQLConnector: diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 632803444..af81177ee 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1999,7 +1999,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 @@ -2050,21 +2052,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, @@ -2299,7 +2306,9 @@ def load( failure: Exception | None = None source: cp.StreamProtocol | 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: # Reconstruction can pass the config to a custom source factory. diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index cb932041a..f774500d1 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -568,6 +568,71 @@ def saved_connector_kind(config: Any) -> str | None: return "unknown connector kind" +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 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], *, 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, + ConnectorArrowDatabase, + ) + + 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], *, 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.polling_source import PollingSource + + kind = config.get("source_type") + 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: """Reconstruct an operator instance from a config dict. 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_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index ba6a1a497..ab611913f 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,106 @@ import s3fs from upath import UPath +from orcapod import PipelineJob from orcapod.databases import DeltaTableDatabase +from orcapod.sources import ArrowTableSource 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) + path = tmp_path / "job.json" + with PipelineJob(database=database) as job: + source = ArrowTableSource( + pa.table({"t1": [1], "t2": [2], "x": [1], "y": [2]}), + source_id="data", + tag_columns=["t1", "t2"], + tag_only_columns=True, + ) + _ = source.select_data_columns(["x", "y"], label="selected") + job.save(path) + + 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_keeps_opendal_s3_key_id_and_omits_secret( + 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.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"], + } + database = DeltaTableDatabase( + 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) + 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_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index 900535e90..a3ccaba8f 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, make_conninfo from orcapod.databases.postgresql_connector import ( PostgreSQLConnector, @@ -197,26 +198,70 @@ def test_isinstance_dbconnector_protocol(self) -> None: class TestConfig: - def test_to_config(self) -> None: + @pytest.mark.parametrize( + "dsn", + [ + "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) -> 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" + options = conninfo_to_dict(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) + 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..b3a3a0bc0 --- /dev/null +++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py @@ -0,0 +1,1068 @@ +"""Storage bindings save connection settings without their credentials.""" + +from __future__ import annotations + +import builtins +import json +import logging +import sys +from collections.abc import Iterator, Mapping, Sequence +from pathlib import Path +from typing import Any, cast +from unittest.mock import MagicMock, patch + +import pyarrow as pa +import psycopg +import pytest +from deltalake.exceptions import TableNotFoundError +from deltalake.fs import DeltaStorageHandler +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" +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", + "allow_http": "false", + "AWS_VIRTUAL_HOSTED_STYLE_REQUEST": "true", +} +PRIVATE_OPTIONS = { + "AWS_SECRET_ACCESS_KEY": SECRET, + "AWS_SESSION_TOKEN": "synthetic-session-token", + "AZURE_STORAGE_SAS_KEY": "synthetic-sas", + "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 ( + 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": PUBLIC_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 = { + key: PUBLIC_OPTIONS[key] + for key in ("AWS_ACCESS_KEY_ID", "AWS_ENDPOINT_URL") + } + else: + options = PUBLIC_OPTIONS | PRIVATE_OPTIONS + if reverse: + options = dict(reversed(options.items())) + database = DeltaTableDatabase(tmp_path / "delta", storage_options=options) + public = PUBLIC_OPTIONS + + path = tmp_path / "job.json" + bindings = _save(path, _arrow_source(), database) + 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 + 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 + + +@pytest.mark.parametrize("reverse", [False, True]) +@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", + "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_key", + "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_web_identity_token_file": "/var/run/fixture/web-identity.jwt", + "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": "fixture-key-id", + }, + ( + "secret_access_key", + "aws_token", + "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, ...], + reverse: bool, +) -> None: + path = tmp_path / "job.json" + private = dict.fromkeys(private_keys, SECRET) + 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) + + 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 + + +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.parametrize("reverse", [False, True]) +@pytest.mark.parametrize( + "uri", ["s3://fixtures/data", "az://fixtures/data", "gs://fixtures/data"] +) +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 = """ + 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 + 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 + fabric_session_token azure_fabric_session_token + service_account_key google_service_account_key + access_token unity_access_token databricks_access_token databricks_token + unity_client_secret databricks_client_secret + """.split() + legacy_secret_keys = """ + aws_secret_access_key_dynamodb + aws_session_token_dynamodb + 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": """ + 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 + """, + "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 token + """, + "oss": "access_key_secret security_token", + "obs": "secret_access_key", + "cos": "secret_key", + "tos": """ + secret_access_key tos_secret_access_key volcengine_secret_access_key + security_token tos_security_token volcengine_session_token + """, + "b2": "application_key", + "swift": "token temp_url_key", + "webhdfs": "delegation", + "webdav": "password token", + "ftp": "password", + "hf": "token", + } + 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() + ) + 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(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: + options = dict(reversed(options.items())) + path = tmp_path / "job.json" + saved = _save(path, _arrow_source(), DeltaTableDatabase(uri, options)) + 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: + 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( + ("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() + + +@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", + [ + " 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", + "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_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, + } + uri = "az://fixtures/data" + path = tmp_path / "job.json" + 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.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( + "root", + [ + "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", + 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( + 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))["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( + "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 +) -> 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("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_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 + 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_credential_options_omitted( + 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 ( + resaved.get("storage_options", {}) + == initial["database"].get("storage_options", {}) + == public + ) + + scoped = _save(path, _arrow_source(), loaded.database.at("scope", "nested")) + assert scoped["database"].get("storage_options", {}) == public + + +@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() + for secret in PRIVATE_OPTIONS.values(): + assert secret not in raw + expected = { + **data["bindings"][slot], + "storage_options": PUBLIC_OPTIONS, + } + assert json.dumps(json.loads(raw)["bindings"][slot]) == json.dumps(expected) + + +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("binding", ["postgresql", "delta", "nested"]) +def test_resaving_clean_retained_blocks_preserves_settings( + 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" + saved = json.loads(target.read_text())["bindings"] + 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_preserves_dsn( + tmp_path: Path, + postgres: MagicMock, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + dsn: str, +) -> None: + path = tmp_path / "original.json" + _ = _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)) + 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) + + monkeypatch.setattr(builtins, "__import__", without_psycopg) + loaded = PipelineJob.load(path) + assert loaded.unbound_sources == [slot] + target = tmp_path / "resaved.json" + 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", + "host=localhost\x00 password=" + PASSWORD, + ], +) +def test_resaving_invalid_postgresql_dsn_preserves_dsn( + tmp_path: Path, postgres: MagicMock, caplog: pytest.LogCaptureFixture, dsn: str +) -> None: + path = tmp_path / "original.json" + _ = _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)) + postgres.side_effect = RuntimeError("connection unavailable") + loaded = PipelineJob.load(path) + assert loaded.unbound_sources == [slot] + target = tmp_path / "resaved.json" + 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}'", + "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) + ) + + +@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( + 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()