Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, `<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(...), '<key>') }}"]`, 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 `<login>_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 `<schema>_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` |

Expand Down Expand Up @@ -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.
Expand Down
10 changes: 8 additions & 2 deletions dbt/macros/valxel.sql
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion dbt/profiles/profiles.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
6 changes: 3 additions & 3 deletions src/job/work.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
46 changes: 14 additions & 32 deletions src/transform/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
<login>_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
Expand All @@ -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:
Expand All @@ -48,49 +47,32 @@ 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


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

Expand All @@ -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)
Expand Down
38 changes: 27 additions & 11 deletions src/transform/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, <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)
Expand All @@ -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)


Expand Down Expand Up @@ -97,15 +108,15 @@ 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()
for col in expr.find_all(exp.Column):
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):
Expand All @@ -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 = (
Expand All @@ -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
Expand Down Expand Up @@ -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 = []
Expand Down Expand Up @@ -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:
Expand Down
5 changes: 5 additions & 0 deletions src/transform/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading
Loading