From c43ef538ac248e76e0b9d41a43335948e4d2b558 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 17:21:36 -0600 Subject: [PATCH] Sign in with the transform's own login; make its helper schema itself (CP-127) The platform now makes the login (platform-resources postgres-login): column SELECT on what its contracts give it, CREATE on the database, ADMIN on _break_glass. Nothing here needs owner rights or creates roles. - Settings take the login's bound outputs (TRANSFORM_PG_HOST, _PORT, _DATABASE, _USER, _PASSWORD, TRANSFORM_TOKENIZE_KEY); a URL still works for local runs. - tokenize, generalize_year and the break-glass record live in _fn, made by the run itself. tokenize is HMAC-SHA256 on built-in sha256 (no pgcrypto); same tokens as before. - The data-class check counts only the transform's own helpers. - Break-glass uses _break_glass; transform-admin setup and grants are gone (the platform's job now). - The Postgres tests run every transform as a login with only those grants. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FsRHvp6Xroi64RED1Rqpyq --- README.md | 14 ++-- dbt/macros/valxel.sql | 10 ++- dbt/profiles/profiles.yml | 2 +- src/job/work.py | 6 +- src/transform/admin.py | 46 ++++------ src/transform/classes.py | 38 ++++++--- src/transform/config.py | 5 ++ src/transform/pg.py | 167 +++++++++++++++++++++++-------------- src/transform/run.py | 45 ++++++++-- tests/test_classes.py | 21 +++-- tests/test_config.py | 27 ++++++ tests/test_transform_pg.py | 72 ++++++++++++---- 12 files changed, 300 insertions(+), 153 deletions(-) diff --git a/README.md b/README.md index ae1db35..a45f842 100644 --- a/README.md +++ b/README.md @@ -50,11 +50,11 @@ The example models build two marts over reporting's synthetic `notes` table: | --- | --- | --- | | Data classes through SQL | Every output column is traced through the SQL to the source columns it's made from (sqlglot). Its declared class must be at least the highest among them, unless the path goes through `valxel_tokenize`, `valxel_generalize_year`, or a `count`/`sum`/`avg` in a model with `valxel_min_group(11)` or more. `secret` never de-identifies; `min`/`max` don't de-identify. An undeclared column, `select *` or a declared column that isn't in the SQL fails too. | `src/transform/classes.py`, `transform-check` | | Control totals | `valxel_control_total`: a measure on the model against the same, or another, measure on what it's built from, within a tolerance (`compare: equal` or `at_most`). Blocking. | `dbt/macros/valxel.sql` | -| Tokens | `valxel.tokenize`: HMAC-SHA256 with the session's key, from the transform's mounted secret through libpq's `PGOPTIONS`, so the key is never in SQL, dbt's logs or artifacts. A session without a key of 32+ characters fails instead of producing guessable tokens. | `src/transform/pg.py` | +| Tokens | `valxel_tokenize`: HMAC-SHA256 (on Postgres's built-in sha256, no extension) with the session's key, the login's own, through libpq's `PGOPTIONS`, so the key is never in SQL, dbt's logs or artifacts. A session without a key of 32+ characters fails instead of producing guessable tokens. The functions live in the transform's own helper schema, `_fn`; the data-class check counts only those. | `src/transform/pg.py` | | Deletions | Reporting deletes a raw row on a `.deleted` event. Full rebuilds follow it. An incremental model removes what's gone with `post_hook=["{{ valxel_deletions(source(...), '') }}"]`, quoted so it renders at run time; `transform-check` fails an unquoted one. A test deletes a source row and proves it's gone from every mart that carries its key. | `dbt/macros/valxel.sql`, `tests/test_transform_pg.py` | -| Least privilege | `transform-admin grants` renders the transform login's grants from the approved sources: select on those raw tables, create for its own schemas, nothing else. The platform applies them. | `src/transform/pg.py` | +| Least privilege | The transform signs in with a login of its own, never the database owner's: platform-resources' `postgres-login`, made when it deploys from the contracts it reads. SELECT on exactly those columns, CREATE on the database for its own schemas, ADMIN on `_break_glass`; no superuser, createrole or createdb. It makes its helper, build and published schemas itself. | `src/transform/pg.py` | | Only writer | The transform login owns the published schema. Report logins (`reporting_reader`) read marts only, with row security by tenant through `reporting_tenants()`. Views run with the reader's rights (`security_invoker`). Staging and intermediate models, which still hold raw columns, aren't readable. | `src/transform/pg.py` | -| Break-glass | `transform-admin break-glass --login L --minutes N --reason "..."`: write on the marts for at most 240 minutes, recorded in `valxel.break_glass`, revoked by the first run after it ends (audited). | `src/transform/admin.py` | +| Break-glass | `transform-admin break-glass --login L --minutes N --reason "..."`: write on the marts for at most 240 minutes, recorded in `_fn.break_glass`, revoked by the first run after it ends (audited). | `src/transform/admin.py` | | Query audit | The platform's Postgres runs pgaudit on the reporting store's database; its logs go to the product's audit topic. Not in this repo. | platform | | Evidence | Manifest, run results, data-class report and summary per run. | `src/transform/run.py` | @@ -108,12 +108,12 @@ and G4 checks it. | `JOB_COHORTS_SLOW_MS` | `5000` | An item slower than this counts as slow in its flag cohort | | `SENTRY_DSN`, `SENTRY_RELEASE` | none | Error reports (GlitchTip takes the same DSN) | | `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_SERVICE_NAME` | none | Where traces go; unset, traces are made but not exported | - -| `TRANSFORM_DATABASE_URL_FILE` | `/var/run/secrets/valxel/transform-database-url` | The warehouse connection as the transform's login, a mounted file (`TRANSFORM_DATABASE_URL` for local runs only) | -| `TRANSFORM_TOKENIZE_KEY_FILE` | `/var/run/secrets/valxel/transform-tokenize-key` | `valxel.tokenize`'s key, 32+ characters, a mounted file (`TRANSFORM_TOKENIZE_KEY` for local runs only) | +| `TRANSFORM_PG_HOST`, `_PORT`, `_DATABASE`, `_USER`, `_PASSWORD` | none, `5432` | The transform's own login (postgres-login's outputs, bound in workload.yaml; the password from its Secret). `TRANSFORM_PG_SSLMODE` defaults to `require` | +| `TRANSFORM_TOKENIZE_KEY` | none | The tokenize key, 32+ characters: the login's own, bound from its Secret (or a mounted file at `TRANSFORM_TOKENIZE_KEY_FILE`) | +| `TRANSFORM_DATABASE_URL` | none | Local runs only, instead of the parts (or a mounted file at `TRANSFORM_DATABASE_URL_FILE`) | | `TRANSFORM_EVIDENCE_DIR` | none | Where each run's evidence is kept | | `TRANSFORM_VERSION` | none | The deployed commit, in the evidence (the Valxel SDLC sets it) | -| `TRANSFORM_SEED_SYNTHETIC` | `false` | CI and local only: set up the warehouse and seed synthetic raw tables first; refused unless `JOB_ENVIRONMENT` is `ci` or `dev` | +| `TRANSFORM_SEED_SYNTHETIC` | `false` | CI and local only: make the roles environments have and seed synthetic raw tables first; refused unless `JOB_ENVIRONMENT` is `ci` or `dev` | Without `JOB_DATABASE_URL`, runs keep no history, so missed and overlapping runs can't be detected. That's fine for a local try, but not for an environment. diff --git a/dbt/macros/valxel.sql b/dbt/macros/valxel.sql index e498bd2..93c8342 100644 --- a/dbt/macros/valxel.sql +++ b/dbt/macros/valxel.sql @@ -1,16 +1,22 @@ {# The template's macros. transform-check knows each one: what it compiles to is how the data-class check sees a column de-identified. Don't redefine them in models. #} +{# The transform's helper schema (transform.yaml's schema + _fn), which its own login makes at the + start of every run; the runner sets it. #} +{% macro valxel_helpers() -%} + {{ adapter.quote(env_var('TRANSFORM_HELPER_SCHEMA', 'transform_fn')) }} +{%- endmacro %} + {# A keyed token of a value (HMAC-SHA256 with the session's key): the same input gives the same token, so marts still join on it, but the value can't be read back without the key. De-identifies. #} {% macro valxel_tokenize(column) -%} - valxel.tokenize(({{ column }})::text) + {{ valxel_helpers() }}.tokenize(({{ column }})::text) {%- endmacro %} {# A date or time cut to its year (HIPAA safe harbor keeps the year): de-identifies. Any finer cut keeps the column's class; use date_trunc for that. #} {% macro valxel_generalize_year(column) -%} - valxel.generalize_year(({{ column }})::timestamptz) + {{ valxel_helpers() }}.generalize_year(({{ column }})::timestamptz) {%- endmacro %} {# The group-size floor for an aggregate mart: groups smaller than this are left out, so a count or diff --git a/dbt/profiles/profiles.yml b/dbt/profiles/profiles.yml index 55a9282..6cf7605 100644 --- a/dbt/profiles/profiles.yml +++ b/dbt/profiles/profiles.yml @@ -14,5 +14,5 @@ transform: schema: "{{ env_var('TRANSFORM_BUILD_SCHEMA', 'transform_build') }}" sslmode: "{{ env_var('TRANSFORM_PG_SSLMODE', 'prefer') }}" threads: 4 - # valxel.tokenize's key reaches each session through libpq's PGOPTIONS, which the runner sets + # The tokenize key reaches each session through libpq's PGOPTIONS, which the runner sets # from the mounted secret: never in SQL, this file, logs or artifacts. diff --git a/src/job/work.py b/src/job/work.py index 245abe2..13ab48e 100644 --- a/src/job/work.py +++ b/src/job/work.py @@ -46,12 +46,12 @@ def _seed(settings: Any, environment: str) -> None: from transform import pg, seed from transform.config import load - from transform.run import TransformError, _secret + from transform.run import TransformError, database_url if environment not in SEED_ENVIRONMENTS: raise TransformError(f"TRANSFORM_SEED_SYNTHETIC replaces raw tables: refused in {environment}") cfg = load(Path(settings.config_path)) - url = _secret(settings.database_url, settings.database_url_file, "database URL") + url = database_url(settings) with psycopg.connect(url, autocommit=True) as conn: - pg.setup(conn) + pg.dev_setup(conn) seed.seed(conn, Path(settings.project_dir), Path("contracts"), cfg.source_schema) diff --git a/src/transform/admin.py b/src/transform/admin.py index 8a5a4c1..e828a38 100644 --- a/src/transform/admin.py +++ b/src/transform/admin.py @@ -3,17 +3,16 @@ transform-check build every model on the database TRANSFORM_DATABASE_URL names (a local or CI Postgres) and run the data-class check; prints the report and exits 1 on a problem. The PR check runs it. -transform-admin setup the valxel schema (tokenize, generalize_year), the break-glass - table and roles: run once by the platform as the database owner -transform-admin grants --login L --database D - print the grants for the transform's login, from the approved - sources: the platform applies them transform-admin break-glass --login L --minutes N --reason "..." write access to the published marts for a person, for at most N minutes (up to 240); recorded, revoked by the next run after - it ends -transform-dev a local run end to end: setup, raw tables seeded from the - contracts, a run, the data-class report + it ends. Runs as the transform's login, which administers + _break_glass. +transform-dev a local run end to end: the roles environments have, raw tables + seeded from the contracts, a run, the data-class report + +The transform's login and what it may read are the platform's (platform-resources postgres-login, +made when the transform deploys, from the contracts it reads); the login makes its own schemas. """ from __future__ import annotations @@ -30,13 +29,13 @@ from . import classes, pg, seed from .config import load -from .run import Settings, TransformError, _secret, dbt, dbt_env, transform +from .run import Settings, TransformError, _secret, database_url, dbt, dbt_env, transform MAX_BREAK_GLASS_MINUTES = 240 def _url(settings: Settings) -> str: - return _secret(settings.database_url, settings.database_url_file, "database URL") + return database_url(settings) def check_main(argv: list[str] | None = None) -> int: @@ -48,11 +47,12 @@ def check_main(argv: list[str] | None = None) -> int: with tempfile.TemporaryDirectory(prefix="transform-check-") as tmp: target = Path(tmp) with psycopg.connect(url, autocommit=True) as conn: + pg.helpers(conn, cfg) pg.prepare(conn, cfg, []) if not dbt(Path(settings.project_dir).resolve(), target, ["compile"], env): print("the dbt project doesn't compile", file=sys.stderr) return 1 - report = classes.check(json.loads((target / "manifest.json").read_text())) + report = classes.check(json.loads((target / "manifest.json").read_text()), cfg.helper_schema) print(classes.render(report)) return 0 if report.ok else 1 @@ -60,37 +60,19 @@ def check_main(argv: list[str] | None = None) -> int: def admin_main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="transform-admin", description=__doc__) sub = parser.add_subparsers(dest="command", required=True) - sub.add_parser("setup") - g = sub.add_parser("grants") - g.add_argument("--login", required=True) - g.add_argument("--database", required=True) b = sub.add_parser("break-glass") b.add_argument("--login", required=True) b.add_argument("--minutes", type=int, required=True) b.add_argument("--reason", required=True) args = parser.parse_args(argv) settings = Settings() - if args.command == "grants": - cfg = load(Path(settings.config_path)) - with tempfile.TemporaryDirectory(prefix="transform-grants-") as tmp: - env = {"TRANSFORM_SOURCE_SCHEMA": cfg.source_schema, "TRANSFORM_BUILD_SCHEMA": cfg.build_schema} - if not dbt(Path(settings.project_dir).resolve(), Path(tmp), ["parse"], env): - print("the dbt project doesn't parse", file=sys.stderr) - return 1 - manifest = json.loads((Path(tmp) / "manifest.json").read_text()) - for stmt in pg.grants(cfg, manifest, args.login, args.database): - print(f"{stmt};") - return 0 + cfg = load(Path(settings.config_path)) with psycopg.connect(_url(settings), autocommit=True) as conn: - if args.command == "setup": - pg.setup(conn) - print("valxel schema, break-glass table and roles in place") - return 0 if not 1 <= args.minutes <= MAX_BREAK_GLASS_MINUTES or len(args.reason.strip()) < 10: print(f"break-glass: 1-{MAX_BREAK_GLASS_MINUTES} minutes and a reason of a few words", file=sys.stderr) return 2 until = datetime.now(UTC) + timedelta(minutes=args.minutes) - pg.break_glass_grant(conn, args.login, until, args.reason.strip()) + pg.break_glass_grant(conn, cfg, args.login, until, args.reason.strip()) print(f"{args.login} may write the published marts until {until.isoformat()}; recorded") return 0 @@ -104,7 +86,7 @@ def dev_main(argv: list[str] | None = None) -> int: cfg = load(Path(settings.config_path)) url = _url(settings) with psycopg.connect(url, autocommit=True) as conn: - pg.setup(conn) + pg.dev_setup(conn) seeded = seed.seed(conn, Path(settings.project_dir), Path("contracts"), cfg.source_schema, rows=args.rows) print(f"seeded {', '.join(f'{t} ({n} rows)' for t, n in seeded.items())}") end = datetime.now(UTC) diff --git a/src/transform/classes.py b/src/transform/classes.py index 4eb39e0..2a6394c 100644 --- a/src/transform/classes.py +++ b/src/transform/classes.py @@ -7,6 +7,8 @@ class among them (none < pii < financial < phi < secret), except along a path th valxel_tokenize(col) a keyed token: what it wraps counts as none valxel_generalize_year(col) a date cut to its year: what it wraps counts as none + (both compile to the transform's own helper schema, _fn: a + function of the same name anywhere else doesn't de-identify) count/sum/avg in a model with valxel_min_group(n), n at least MIN_GROUP: what's aggregated counts as none (group-by columns keep their class; min and max don't de-identify, they return a value as it is) @@ -33,7 +35,16 @@ class among them (none < pii < financial < phi < secret), except along a path th CLASSES = ("none", "pii", "financial", "phi", "secret") RANK = {c: i for i, c in enumerate(CLASSES)} MIN_GROUP = 11 # the smallest group an aggregate of personal data may show (decided Nov 24 for PHI) -DEIDENTIFY = {"valxel.tokenize", "valxel.generalize_year"} +HELPERS = "transform_fn" # the default helper schema: transform.yaml's schema + _fn (Config.helper_schema) +FUNCTIONS = ("tokenize", "generalize_year") # the de-identifications, in the transform's helper schema + + +def deidentify(helpers: str) -> frozenset[str]: + """The de-identification functions by qualified name: only the transform's own, never a + function of the same name in another schema.""" + return frozenset(f"{helpers}.{f}".lower() for f in FUNCTIONS) + + AGGREGATES = (exp.Count, exp.Sum, exp.Avg) @@ -97,7 +108,7 @@ def _func_name(node: exp.Expression) -> str: return "" -def _shielded(expr: exp.Expression, aggregate_ok: bool) -> set[str]: +def _shielded(expr: exp.Expression, aggregate_ok: bool, deid: frozenset[str]) -> set[str]: """Column names in `expr` that are referenced only inside a de-identification.""" inside: set[str] = set() outside: set[str] = set() @@ -105,7 +116,7 @@ def _shielded(expr: exp.Expression, aggregate_ok: bool) -> set[str]: safe = False parent = col.parent while isinstance(parent, exp.Expression) and parent is not expr.parent: - if _func_name(parent) in DEIDENTIFY: + if _func_name(parent) in deid: safe = True break if aggregate_ok and isinstance(parent, AGGREGATES): @@ -116,12 +127,14 @@ def _shielded(expr: exp.Expression, aggregate_ok: bool) -> set[str]: return inside - outside -def _leaves(node: Node, shielded: bool, out: list[tuple[str, bool]], aggregate_floor: int) -> None: +def _leaves( + node: Node, shielded: bool, out: list[tuple[str, bool]], aggregate_floor: int, deid: frozenset[str] +) -> None: expr = node.expression projection = expr.this if isinstance(expr, exp.Alias) else expr select = expr.find_ancestor(exp.Select) if isinstance(expr, exp.Expression) else None agg_ok = aggregate_floor >= MIN_GROUP or (select is not None and _min_group(select) >= MIN_GROUP) - safe_cols = _shielded(projection, agg_ok) if isinstance(projection, exp.Expression) else set() + safe_cols = _shielded(projection, agg_ok, deid) if isinstance(projection, exp.Expression) else set() if not node.downstream: source = node.source table = ( @@ -133,11 +146,13 @@ def _leaves(node: Node, shielded: bool, out: list[tuple[str, bool]], aggregate_f return for child in node.downstream: col = child.name.rsplit(".", 1)[-1].lower() - _leaves(child, shielded or col in safe_cols, out, 0) + _leaves(child, shielded or col in safe_cols, out, 0, deid) -def check(manifest: dict[str, Any]) -> Report: - """Check every model in a compiled dbt manifest.""" +def check(manifest: dict[str, Any], helpers: str = HELPERS) -> Report: + """Check every model in a compiled dbt manifest. `helpers`: the transform's helper schema, where + its de-identification functions are.""" + deid = deidentify(helpers) report = Report() known: dict[str, dict[str, str]] = {} # relation -> column -> class schema: dict[str, Any] = {} # catalog -> schema -> table -> column -> type, as sqlglot takes it @@ -177,7 +192,8 @@ def check(manifest: dict[str, Any]) -> Report: leaves: list[tuple[str, bool]] = [] try: root = lineage(col, sql, schema=schema, dialect="postgres") - _leaves(root, False, leaves, _min_group(parsed) if isinstance(parsed, exp.Select) else 0) + floor = _min_group(parsed) if isinstance(parsed, exp.Select) else 0 + _leaves(root, False, leaves, floor, deid) except Exception as e: # noqa: BLE001 - reported as a problem, never skipped entry.problem = f"{name}.{col}: couldn't trace its inputs ({type(e).__name__}: {e})" leaves = [] @@ -243,8 +259,8 @@ def visit(uid: str) -> None: return done -def check_file(path: Path) -> Report: - return check(json.loads(path.read_text())) +def check_file(path: Path, helpers: str = HELPERS) -> Report: + return check(json.loads(path.read_text()), helpers) def render(report: Report) -> str: diff --git a/src/transform/config.py b/src/transform/config.py index fdb7912..628dbe7 100644 --- a/src/transform/config.py +++ b/src/transform/config.py @@ -40,6 +40,11 @@ def build_schema(self) -> str: def old_schema(self) -> str: return f"{self.schema}_old" + @property + def helper_schema(self) -> str: + """The transform's functions and break-glass record, made by its own login.""" + return f"{self.schema}_fn" + def parse(raw: Any) -> Config: if not isinstance(raw, dict): diff --git a/src/transform/pg.py b/src/transform/pg.py index 9b09b5a..d1b90e8 100644 --- a/src/transform/pg.py +++ b/src/transform/pg.py @@ -11,6 +11,11 @@ transform's login owns and writes the schema; people read through reporting_reader, and write only through break-glass, which is time-boxed and audited. +The transform signs in with a login of its own (platform-resources postgres-login): SELECT on the +source columns its contracts give it, CREATE on the database, and ADMIN on _break_glass. It +makes everything else itself, with no owner rights: its helper schema (helpers), the build +schema and the published one. + Every statement is composed with psycopg's sql module: names come from the approved transform.yaml and dbt's manifest and are quoted as identifiers; values are bound parameters. """ @@ -27,35 +32,61 @@ from .config import Config -READER = "reporting_reader" # the report logins' role, from template-reporting -BREAK_GLASS = "transform_break_glass" +READER = "reporting_reader" # the report logins' role, made by template-reporting (deployed first) MIN_KEY = 32 - -SETUP = [ - "create extension if not exists pgcrypto", - "create schema if not exists valxel", - # A keyed token. The key is the session's (PGOPTIONS, from the transform's mounted secret): a - # session without one, or with a short one, fails instead of producing guessable tokens. - f"""create or replace function valxel.tokenize(v text) returns text language plpgsql stable - set search_path = pg_catalog, public as $$ - declare k text := current_setting('valxel.tokenize_key', true); +FUNCTIONS = ("tokenize", "generalize_year") # in the transform's helper schema (Config.helper_schema) + + +def break_glass_role(login: str) -> str: + """The NOLOGIN role the platform makes beside the transform's login (platform-resources + postgres-login, breakGlass): the login administers it, so it grants and revokes it itself.""" + return f"{login}_break_glass" + + +def helper_sql(helpers: str) -> list[sql.Composed]: + """The transform's helper schema, made by its own login (it has CREATE on the database, nothing + more): the de-identification functions and the break-glass record. Idempotent; run every time. + + The token is HMAC-SHA256 with the session's key (PGOPTIONS, from the login's secret), written on + Postgres's built-in sha256 so it needs no extension. A session without a key, or with a short one, + fails instead of producing guessable tokens.""" + h = sql.Identifier(helpers) + return [ + sql.SQL("create schema if not exists {}").format(h), + sql.SQL( + """create or replace function {}.tokenize(v text) returns text language plpgsql stable + set search_path = pg_catalog as $$ + declare + ks text := current_setting('valxel.tokenize_key', true); + k bytea; ipad bytea; opad bytea; begin if v is null then return null; end if; - if k is null or length(k) < {MIN_KEY} then - raise exception 'valxel.tokenize: no key of at least {MIN_KEY} characters for this session'; + if ks is null or length(ks) < {} then + raise exception 'tokenize: no key of at least {} characters for this session'; end if; - return encode(hmac(v, k, 'sha256'), 'hex'); - end $$""", - """create or replace function valxel.generalize_year(t timestamptz) returns int language sql immutable - set search_path = pg_catalog as $$ select extract(year from t)::int $$""", - "grant usage on schema valxel to public", - """create table if not exists valxel.break_glass ( + k := convert_to(ks, 'UTF8'); + if length(k) > 64 then k := sha256(k); end if; + k := k || decode(repeat('00', 64 - length(k)), 'hex'); + ipad := k; opad := k; + for i in 0..63 loop + ipad := set_byte(ipad, i, get_byte(k, i) # 54); + opad := set_byte(opad, i, get_byte(k, i) # 92); + end loop; + return encode(sha256(opad || sha256(ipad || convert_to(v, 'UTF8'))), 'hex'); + end $$""" + ).format(h, sql.SQL(str(MIN_KEY)), sql.SQL(str(MIN_KEY))), + sql.SQL( + """create or replace function {}.generalize_year(t timestamptz) returns int language sql immutable + set search_path = pg_catalog as $$ select extract(year from t)::int $$""" + ).format(h), + sql.SQL( + """create table if not exists {}.break_glass ( login text not null, granted_at timestamptz not null default now(), until timestamptz not null, - reason text not null, revoked_at timestamptz)""", - "revoke all on valxel.break_glass from public", - f"do $$ begin create role {BREAK_GLASS} nologin; exception when duplicate_object then null; end $$", - f"do $$ begin create role {READER} nologin; exception when duplicate_object then null; end $$", -] + reason text not null, revoked_at timestamptz)""" + ).format(h), + sql.SQL("revoke all on schema {} from public").format(h), + sql.SQL("revoke all on {}.break_glass from public").format(h), + ] def execute(cur: psycopg.Cursor[Any], stmt: sql.SQL | sql.Composed | str, params: list[Any] | None = None) -> None: @@ -143,12 +174,15 @@ def expire(conn: psycopg.Connection[Any], cfg: Config, existing: Iterable[str]) return out -def reader_grants(cfg: Config, built: list[Model]) -> list[sql.Composed]: - """What readers and break-glass may do in the published schema: re-applied at every swap.""" - live = sql.Identifier(cfg.schema) +def reader_grants(cfg: Config, built: list[Model], break_glass: str) -> list[sql.Composed]: + """What readers and break-glass may do in the published schema: re-applied at every swap. Readers + also use the helper schema: a mart view that generalizes a year runs with their rights.""" + live, helpers = sql.Identifier(cfg.schema), sql.Identifier(cfg.helper_schema) + who = sql.SQL("{}, {}").format(sql.Identifier(READER), sql.Identifier(break_glass)) out: list[sql.Composed] = [ sql.SQL("revoke all on schema {} from public").format(live), - sql.SQL("grant usage on schema {} to {}, {}").format(live, sql.Identifier(READER), sql.Identifier(BREAK_GLASS)), + sql.SQL("grant usage on schema {} to {}").format(live, who), + sql.SQL("grant usage on schema {} to {}").format(helpers, who), ] for m in built: t = sql.SQL("{}.{}").format(live, sql.Identifier(m.name)) @@ -160,7 +194,7 @@ def reader_grants(cfg: Config, built: list[Model]) -> list[sql.Composed]: out.append(sql.SQL("grant select on {} to {}").format(t, sql.Identifier(READER))) if m.materialized != "view": out.append( - sql.SQL("grant select, insert, update, delete on {} to {}").format(t, sql.Identifier(BREAK_GLASS)) + sql.SQL("grant select, insert, update, delete on {} to {}").format(t, sql.Identifier(break_glass)) ) if m.tenant and m.materialized != "view": out += [ @@ -171,13 +205,13 @@ def reader_grants(cfg: Config, built: list[Model]) -> list[sql.Composed]: ).format(t, sql.Identifier(READER), sql.Identifier(m.tenant)), sql.SQL("drop policy if exists break_glass on {}").format(t), sql.SQL("create policy break_glass on {} for all to {} using (true)").format( - t, sql.Identifier(BREAK_GLASS) + t, sql.Identifier(break_glass) ), ] return out -def publish(conn: psycopg.Connection[Any], cfg: Config, built: list[Model]) -> None: +def publish(conn: psycopg.Connection[Any], cfg: Config, built: list[Model], break_glass: str) -> None: """Swap the build schema in, in one transaction, with readers' grants re-applied.""" with conn.transaction(), conn.cursor() as cur: live, build, old = (sql.Identifier(s) for s in (cfg.schema, cfg.build_schema, cfg.old_schema)) @@ -185,7 +219,7 @@ def publish(conn: psycopg.Connection[Any], cfg: Config, built: list[Model]) -> N if _exists(cur, cfg.schema): execute(cur, sql.SQL("alter schema {} rename to {}").format(live, old)) execute(cur, sql.SQL("alter schema {} rename to {}").format(build, live)) - for stmt in reader_grants(cfg, built): + for stmt in reader_grants(cfg, built, break_glass): execute(cur, stmt) execute(cur, sql.SQL("drop schema if exists {} cascade").format(old)) @@ -202,53 +236,60 @@ def counts(conn: psycopg.Connection[Any], schema: str, built: list[Model]) -> di return out -def grants(cfg: Config, manifest: dict[str, Any], login: str, database: str) -> list[str]: - """`transform-admin grants`: what the platform applies for this transform's login, rendered - from the approved sources: read only the raw tables it declares, own and write only its schemas.""" - who = sql.Identifier(login) - stmts: list[sql.Composable] = [sql.SQL(s) for s in SETUP] - stmts += [ - # create: the run makes its build schema; it owns that schema and the published one, nothing else. - sql.SQL("grant create on database {} to {}").format(sql.Identifier(database), who), - sql.SQL("grant usage on schema valxel to {}").format(who), - ] - for schema in sorted({s for s, _ in sources(manifest)}): - stmts.append(sql.SQL("grant usage on schema {} to {}").format(sql.Identifier(schema), who)) - for schema, table in sources(manifest): - stmts.append(sql.SQL("grant select on {}.{} to {}").format(sql.Identifier(schema), sql.Identifier(table), who)) - stmts += [ - sql.SQL("grant {} to {} with admin option").format(sql.Identifier(BREAK_GLASS), who), - sql.SQL("grant select, insert, update on valxel.break_glass to {}").format(who), - ] - return [s.as_string(None) for s in stmts] +def login(conn: psycopg.Connection[Any]) -> str: + with conn.cursor() as cur: + execute(cur, "select current_user") + row = cur.fetchone() + return str(row[0]) if row else "" -def setup(conn: psycopg.Connection[Any]) -> None: +def helpers(conn: psycopg.Connection[Any], cfg: Config) -> None: + """The helper schema, as the transform's own login: at the start of every run.""" with conn.transaction(), conn.cursor() as cur: - for stmt in SETUP: + for stmt in helper_sql(cfg.helper_schema): execute(cur, stmt) -def break_glass_grant(conn: psycopg.Connection[Any], login: str, until: datetime, reason: str) -> None: +def dev_setup(conn: psycopg.Connection[Any]) -> None: + """CI and local only, on a database whose login may create roles: the roles the platform and + template-reporting make in environments (reporting_reader, _break_glass).""" + me = login(conn) + with conn.transaction(), conn.cursor() as cur: + for role in (READER, break_glass_role(me)): + execute(cur, "select 1 from pg_roles where rolname = %s", [role]) + if not cur.fetchone(): + execute(cur, sql.SQL("create role {} nologin").format(sql.Identifier(role))) + + +def break_glass_grant(conn: psycopg.Connection[Any], cfg: Config, person: str, until: datetime, reason: str) -> None: + helpers(conn, cfg) + role = break_glass_role(login(conn)) with conn.transaction(), conn.cursor() as cur: execute( - cur, "insert into valxel.break_glass (login, until, reason) values (%s, %s, %s)", [login, until, reason] + cur, + sql.SQL("insert into {}.break_glass (login, until, reason) values (%s, %s, %s)").format( + sql.Identifier(cfg.helper_schema) + ), + [person, until, reason], ) - execute(cur, sql.SQL("grant {} to {}").format(sql.Identifier(BREAK_GLASS), sql.Identifier(login))) + execute(cur, sql.SQL("grant {} to {}").format(sql.Identifier(role), sql.Identifier(person))) -def break_glass_expire(conn: psycopg.Connection[Any]) -> list[str]: +def break_glass_expire(conn: psycopg.Connection[Any], cfg: Config) -> list[str]: """Revoke every break-glass grant past its time; returns the logins revoked.""" revoked = [] + role = break_glass_role(login(conn)) with conn.transaction(), conn.cursor() as cur: execute( cur, - "update valxel.break_glass set revoked_at = now() where revoked_at is null and until <= now()" - " returning login", + sql.SQL( + "update {}.break_glass set revoked_at = now() where revoked_at is null and until <= now()" + " returning login" + ).format(sql.Identifier(cfg.helper_schema)), ) - for (login,) in cur.fetchall(): - execute(cur, "select 1 from pg_roles where rolname = %s", [login]) + for (person,) in cur.fetchall(): + execute(cur, "select 1 from pg_roles where rolname = %s", [person]) if cur.fetchone(): - execute(cur, sql.SQL("revoke {} from {}").format(sql.Identifier(BREAK_GLASS), sql.Identifier(login))) - revoked.append(str(login)) + execute(cur, sql.SQL("revoke {} from {}").format(sql.Identifier(role), sql.Identifier(person))) + revoked.append(str(person)) return revoked diff --git a/src/transform/run.py b/src/transform/run.py index 1454545..ea508f7 100644 --- a/src/transform/run.py +++ b/src/transform/run.py @@ -32,7 +32,7 @@ from typing import Any import psycopg -from psycopg.conninfo import conninfo_to_dict +from psycopg.conninfo import conninfo_to_dict, make_conninfo from pydantic_settings import BaseSettings, SettingsConfigDict from . import classes, pg @@ -47,12 +47,20 @@ class Settings(BaseSettings): config_path: str = "transform.yaml" project_dir: str = "dbt" - # The warehouse connection, as the transform's own login. A mounted file in environments; the - # variable only for local runs (transform-dev). + # The warehouse connection, as the transform's own login (platform-resources postgres-login). In + # environments the login's outputs reach the pod as TRANSFORM_PG_HOST, _PORT, _DATABASE, _USER + # and _PASSWORD (workload.yaml binds them; the password from its Secret). Otherwise a URL: the + # variable for local runs (transform-dev), or a mounted file. + pg_host: str = "" + pg_port: int = 5432 + pg_database: str = "" + pg_user: str = "" + pg_password: str = "" + pg_sslmode: str = "require" database_url: str = "" database_url_file: str = "/var/run/secrets/valxel/transform-database-url" - # valxel.tokenize's key (at least 32 characters). A mounted file; never an environment variable - # outside local runs. + # The tokenize key (at least 32 characters): the login's own, bound from its Secret as + # TRANSFORM_TOKENIZE_KEY, or a mounted file. tokenize_key: str = "" tokenize_key_file: str = "/var/run/secrets/valxel/transform-tokenize-key" evidence_dir: str = "" # where each run's evidence is kept (a mounted volume); unset: not kept @@ -75,6 +83,22 @@ def _secret(value: str, path: str, what: str) -> str: raise TransformError(f"no {what}: mount it at {path}") from e +def database_url(settings: Settings) -> str: + """The transform's own login: the bound parts when there are any, else a URL.""" + if settings.pg_host: + if not (settings.pg_user and settings.pg_password and settings.pg_database): + raise TransformError("TRANSFORM_PG_HOST is set: TRANSFORM_PG_USER, _PASSWORD and _DATABASE are needed too") + return make_conninfo( + host=settings.pg_host, + port=settings.pg_port, + dbname=settings.pg_database, + user=settings.pg_user, + password=settings.pg_password, + sslmode=settings.pg_sslmode, + ) + return _secret(settings.database_url, settings.database_url_file, "database URL") + + def dbt_env(url: str, cfg: Config, key: str) -> dict[str, str]: """What dbt's profile reads (dbt/profiles/profiles.yml). The password and the key reach dbt only through DBT_ENV_SECRET_ and libpq's PGOPTIONS, which dbt keeps out of its logs and artifacts.""" @@ -91,6 +115,7 @@ def dbt_env(url: str, cfg: Config, key: str) -> dict[str, str]: "DBT_ENV_SECRET_PG_PASSWORD": str(info.get("password") or ""), "TRANSFORM_BUILD_SCHEMA": cfg.build_schema, "TRANSFORM_SOURCE_SCHEMA": cfg.source_schema, + "TRANSFORM_HELPER_SCHEMA": cfg.helper_schema, "PGOPTIONS": f"-c valxel.tokenize_key={key}", "DBT_SEND_ANONYMOUS_USAGE_STATS": "false", # nothing leaves for dbt Labs; nothing written beside the profile } @@ -159,7 +184,7 @@ def transform( ) -> dict[str, Any]: """One run; returns the summary (also logged and kept as evidence). Raises TransformError.""" cfg = load(Path(settings.config_path)) - url = _secret(settings.database_url, settings.database_url_file, "database URL") + url = database_url(settings) key = _secret(settings.tokenize_key, settings.tokenize_key_file, "tokenize key") env = dbt_env(url, cfg, key) project = Path(settings.project_dir).resolve() @@ -174,7 +199,9 @@ def transform( } with tempfile.TemporaryDirectory(prefix="transform-") as tmp, psycopg.connect(url, autocommit=True) as conn: target = Path(tmp) / "target" - for login in pg.break_glass_expire(conn): + pg.helpers(conn, cfg) + break_glass = pg.break_glass_role(pg.login(conn)) + for login in pg.break_glass_expire(conn, cfg): log.warning("break-glass access for %s expired and was revoked", login) if audit: audit("transform.break_glass.revoked", resource=("db_login", [login]), details={}) @@ -188,7 +215,7 @@ def transform( built_ok = dbt(project, target, ["build", "--vars", vars_], env) manifest = json.loads((target / "manifest.json").read_text()) summary["tests"] = _results(target / "run_results.json") - report = classes.check(manifest) + report = classes.check(manifest, cfg.helper_schema) summary["classes"] = {"ok": report.ok, "problems": report.problems} (target / "classes.json").write_text(json.dumps(report.as_dict(), indent=2)) built = pg.models(manifest) @@ -203,7 +230,7 @@ def transform( summary["expired"] = pg.expire(conn, cfg, [m.name for m in built]) summary["rows"] = pg.counts(conn, cfg.build_schema, built) if not dry_run: - pg.publish(conn, cfg, built) + pg.publish(conn, cfg, built, break_glass) summary["published"] = True if audit: audit( diff --git a/tests/test_classes.py b/tests/test_classes.py index 4ddfd73..1e8e37a 100644 --- a/tests/test_classes.py +++ b/tests/test_classes.py @@ -60,8 +60,8 @@ def test_declaring_higher_than_the_data_is_allowed(): @pytest.mark.parametrize( "expr", [ - "valxel.tokenize((patient_id)::text)", - "valxel.generalize_year((signed_at)::timestamptz)", + "transform_fn.tokenize((patient_id)::text)", + "transform_fn.generalize_year((signed_at)::timestamptz)", ], ) def test_the_template_de_identifications_lower_the_class(expr): @@ -74,19 +74,19 @@ def test_a_finer_cut_or_another_function_does_not_de_identify(): def test_only_what_the_de_identification_wraps_is_lowered(): - sql = f"select valxel.tokenize((patient_id)::text) || signed_at::text as x from {SRC}" + sql = f"select transform_fn.tokenize((patient_id)::text) || signed_at::text as x from {SRC}" [found] = problems(sql, {"x": "none"}) assert "signed_at (phi)" in found and "patient_id (phi, de-identified)" in found def test_a_column_used_both_inside_and_outside_a_de_identification_keeps_its_class(): - sql = f"select valxel.tokenize((patient_id)::text) || patient_id as x from {SRC}" + sql = f"select transform_fn.tokenize((patient_id)::text) || patient_id as x from {SRC}" assert problems(sql, {"x": "none"}) def test_secret_never_de_identifies(): - assert problems(f"select valxel.tokenize((ssn)::text) as t from {SRC}", {"t": "none"}) - assert problems(f"select valxel.tokenize((ssn)::text) as t from {SRC}", {"t": "secret"}) == [] + assert problems(f"select transform_fn.tokenize((ssn)::text) as t from {SRC}", {"t": "none"}) + assert problems(f"select transform_fn.tokenize((ssn)::text) as t from {SRC}", {"t": "secret"}) == [] AGG = "select clinic_id, count(distinct patient_id) as patients, sum(amount) as total from {src} group by 1 {having}" @@ -145,7 +145,7 @@ def test_a_source_column_without_a_class_fails(): def test_the_report_names_each_columns_inputs(): - report = check(manifest(f"select valxel.tokenize((patient_id)::text) as t from {SRC}", {"t": "none"})) + report = check(manifest(f"select transform_fn.tokenize((patient_id)::text) as t from {SRC}", {"t": "none"})) assert report.ok and report.as_dict()["columns"] == [ { "model": "mart", @@ -169,3 +169,10 @@ def test_a_deletions_hook_rendered_at_parse_time_is_caught(): "post-hook": [{"sql": f"delete from {me} as t where not exists (select 1 from {SRC} as s where s.k = t.k)"}] } assert check(m).ok + + +def test_only_the_transforms_own_helpers_de_identify(): + assert problems(f"select other.tokenize((patient_id)::text) as t from {SRC}", {"t": "none"}) + assert problems(f"select tokenize((patient_id)::text) as t from {SRC}", {"t": "none"}) + found = check(manifest(f"select emr_fn.tokenize((patient_id)::text) as t from {SRC}", {"t": "none"}), "emr_fn") + assert found.problems == [] diff --git a/tests/test_config.py b/tests/test_config.py index e6787a4..770d918 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -40,3 +40,30 @@ def test_not_yaml_or_not_a_mapping(): parse("a: [") with pytest.raises(ConfigError): parse("- a") + + +def test_the_transform_signs_in_with_its_logins_bound_outputs(): + from psycopg.conninfo import conninfo_to_dict + + from transform.run import Settings, TransformError, database_url + + url = database_url(Settings(pg_host="db.internal", pg_database="emr", pg_user="emr_transform", pg_password="pw")) + assert conninfo_to_dict(url) == { + "host": "db.internal", + "port": "5432", + "dbname": "emr", + "user": "emr_transform", + "password": "pw", + "sslmode": "require", + } + assert database_url(Settings(database_url="postgresql://x@y/z")) == "postgresql://x@y/z" + with pytest.raises(TransformError, match="_PASSWORD"): + database_url(Settings(pg_host="db.internal", pg_database="emr", pg_user="emr_transform")) + + +def test_the_helper_schema_is_the_transforms_own(): + from pathlib import Path + + from transform.config import load + + assert load(Path(__file__).resolve().parents[1] / "transform.yaml").helper_schema == "transform_fn" diff --git a/tests/test_transform_pg.py b/tests/test_transform_pg.py index f176317..856e94c 100644 --- a/tests/test_transform_pg.py +++ b/tests/test_transform_pg.py @@ -1,6 +1,10 @@ """The transform end to end on a real Postgres: set TRANSFORM_TEST_DATABASE_URL (a database these tests may reset; the login must be able to create roles). CI runs them against its Postgres service. +The fixture plays the platform: it makes the transform's own login with only what postgres-login +gives it (SELECT on the raw table, CONNECT and CREATE on the database, ADMIN on its break-glass role), +and every run signs in as that login, so nothing here works only because the tests are superuser. + The deletion test is generic: for every source with a key, it deletes one row from the raw table, runs again and proves the key is gone from every mart that carries it (traced by the data-class report's lineage), whatever models the product has written. @@ -24,6 +28,7 @@ URL = os.environ.get("TRANSFORM_TEST_DATABASE_URL", "") KEY = "k" * 40 +LOGIN, LOGIN_PW = "emr_transform", "transform-login-pw-123" ROOT = Path(__file__).resolve().parents[1] END = datetime(2026, 11, 25, tzinfo=UTC) WINDOW = (END - timedelta(days=1), END) @@ -42,6 +47,12 @@ def sql(*statements: str, url: str = URL) -> list[tuple]: return rows +def login_url() -> str: + from psycopg.conninfo import make_conninfo + + return make_conninfo(URL, user=LOGIN, password=LOGIN_PW) + + @pytest.fixture def warehouse(tmp_path): import psycopg @@ -50,28 +61,44 @@ def warehouse(tmp_path): "drop schema if exists transform cascade", "drop schema if exists transform_build cascade", "drop schema if exists transform_old cascade", + "drop schema if exists transform_fn cascade", "drop table if exists public.notes", "create table if not exists public._reporting_logins (login text, tenant text, primary key (login, tenant))", "create or replace function public.reporting_tenants() returns setof text language sql stable" " security definer set search_path = pg_catalog, public as" " $$ select tenant from public._reporting_logins where login = session_user $$", + "truncate public._reporting_logins", ) with psycopg.connect(URL, autocommit=True) as conn: - pg.setup(conn) seed.seed(conn, ROOT / "dbt", ROOT / "contracts", "public", rows=60) - sql("truncate valxel.break_glass", "truncate public._reporting_logins") for role in ("clinic_reader", "oncall_person"): sql( f"do $$ begin if exists (select 1 from pg_roles where rolname = '{role}') then" f" drop owned by {role}; drop role {role}; end if; end $$" ) + # What the platform makes (postgres-login) and template-reporting makes (reporting_reader). + for role, attrs in ( + (LOGIN, f"login password '{LOGIN_PW}'"), + (f"{LOGIN}_break_glass", "nologin"), + ("reporting_reader", "nologin"), + ): + sql( + f"do $$ begin if not exists (select 1 from pg_roles where rolname = '{role}') then" + f" create role {role} {attrs}; end if; end $$" + ) + sql( + f"do $$ begin execute format('grant connect, create on database %I to {LOGIN}', current_database()); end $$", + f"grant usage on schema public to {LOGIN}", + f"grant select on public.notes to {LOGIN}", + f"grant {LOGIN}_break_glass to {LOGIN} with admin option", + ) project = tmp_path / "dbt" shutil.copytree(ROOT / "dbt", project, ignore=shutil.ignore_patterns("target", "logs")) evidence = tmp_path / "evidence" settings = Settings( config_path=str(ROOT / "transform.yaml"), project_dir=str(project), - database_url=URL, + database_url=login_url(), tokenize_key=KEY, evidence_dir=str(evidence), version="abc123", @@ -122,7 +149,6 @@ def test_a_report_login_sees_only_its_tenants_marts_and_nothing_raw(warehouse): sql( "create role clinic_reader login password 'reader-pw-123'", "grant reporting_reader to clinic_reader", - "grant usage on schema valxel to clinic_reader", "insert into public._reporting_logins values ('clinic_reader', 'clinic_id-1') on conflict do nothing", ) from psycopg.conninfo import make_conninfo @@ -206,25 +232,35 @@ def test_break_glass_is_time_boxed_and_revoked_by_the_next_run(warehouse): run(warehouse) sql("create role oncall_person login") - with psycopg.connect(URL, autocommit=True) as conn: - pg.break_glass_grant(conn, "oncall_person", datetime.now(UTC) - timedelta(minutes=1), "fix a bad row in a mart") - assert sql("select pg_has_role('oncall_person', 'transform_break_glass', 'member')")[0][0] + cfg = load(ROOT / "transform.yaml") + with psycopg.connect(login_url(), autocommit=True) as conn: # the transform's own login grants it + pg.break_glass_grant(conn, cfg, "oncall_person", datetime.now(UTC) - timedelta(minutes=1), "fix a bad row") + member = f"select pg_has_role('oncall_person', '{LOGIN}_break_glass', 'member')" + assert sql(member)[0][0] audits = [] run(warehouse, audit=lambda a, **kw: audits.append((a, kw))) - assert not sql("select pg_has_role('oncall_person', 'transform_break_glass', 'member')")[0][0] + assert not sql(member)[0][0] assert ("transform.break_glass.revoked", {"resource": ("db_login", ["oncall_person"]), "details": {}}) in audits - assert sql("select revoked_at is not null from valxel.break_glass where login = 'oncall_person'") == [(True,)] + assert sql("select revoked_at is not null from transform_fn.break_glass where login = 'oncall_person'") == [(True,)] + +def test_tokens_need_the_sessions_key_and_are_hmac_sha256(warehouse): + import hashlib + import hmac -def test_tokens_need_the_sessions_key(warehouse): + run(warehouse) with pytest.raises(Exception, match="no key of at least 32 characters"): - sql("select valxel.tokenize('x')") + sql("select transform_fn.tokenize('x')") + for key in (KEY, "é" * 40, "x" * 100): # multi-byte, and longer than a block + [(token,)] = sql(f"set valxel.tokenize_key = '{key}'", "select transform_fn.tokenize('patient-ü-1')") + assert token == hmac.new(key.encode(), "patient-ü-1".encode(), hashlib.sha256).hexdigest() -def test_the_grants_name_only_the_declared_sources(): - cfg = load(ROOT / "transform.yaml") - manifest = {"sources": {"s": {"schema": "public", "identifier": "notes"}}} - stmts = pg.grants(cfg, manifest, "emr_transform", "emr") - assert 'grant select on "public"."notes" to "emr_transform"' in stmts - assert 'grant create on database "emr" to "emr_transform"' in stmts - assert not [s for s in stmts if "grant select on all" in s or ("insert" in s and "notes" in s)] +def test_the_login_owns_its_schemas_and_nothing_more(warehouse): + run(warehouse) + owners = dict(sql("select nspname, pg_get_userbyid(nspowner) from pg_namespace where nspname like 'transform%'")) + assert owners == {"transform": LOGIN, "transform_fn": LOGIN} + attrs = sql(f"select rolsuper, rolcreaterole, rolcreatedb from pg_roles where rolname = '{LOGIN}'") + assert attrs == [(False, False, False)] + with pytest.raises(Exception, match="permission denied"): + sql("insert into public.notes (note_id) values ('x')", url=login_url())