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
79 changes: 79 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,85 @@ is written. You need a Databricks profile that reaches your account console (`da
its workspaces and their metastores. To include bucket versioning, you also need an AWS profile that
can read the S3 buckets behind the storage roots. The audit writes its files to `audit/`.

## Audit without Claude Code

The audit needs no language model. It is one command you can run yourself.

You need [uv](https://docs.astral.sh/uv/), a written platform set (`platform/adr-set.yaml` in your
ADR monorepo), and the profiles listed under [Use](#use). Clone the last release:

```sh
git clone --branch release git@github.com:Cloudamite/databricks-wizard.git
```

**Once: say which workspaces are your estate.** The audit reads this from `audit/live.yaml` in your
monorepo. Run the audit command below before the file exists. It writes `audit/live.yaml` for you to
fill in, then stops without auditing. The file has an entry for each environment your platform set
records, and lists your account's workspaces in a comment:

```yaml
schema_version: 1
name: platform
# The account's workspaces:
# acme-dev
# acme-prod
# acme-sandbox
# other-team
workspaces:
- name: # <fill here the name of the workspace for dev>
environment: dev
- name: # <fill here the name of the workspace for prod>
environment: prod
```

Fill in each `name` from the list. Add an entry with only a `name` for each other workspace of your
estate that holds no environment:

```yaml
workspaces:
- name: acme-dev
environment: dev
- name: acme-prod
environment: prod
- name: acme-sandbox
```

If your platform set shares one workspace between environments, the file has a single entry with no
`environment` instead. If the command cannot list your workspaces, the comment says why, and you
type the names yourself. The audit refuses the file until every `name` is filled in.

Commit `audit/live.yaml`. Every later audit reuses it.

**Each time: run the audit** from the monorepo:

```sh
uv run --project <clone>/scripts --locked --group audit <clone>/scripts/audit_live.py \
--databricks-profile <profile> --aws-profile <profile>
```

If you cannot read the buckets behind the storage roots (Databricks manages them, or they are in
another AWS account), pass `--no-storage` in place of `--aws-profile`. Bucket versioning is then
reported as unevaluated.

The command reads the account with read calls only, then measures what it read. It prints a report
for people to read and writes the structured one to `audit/audit.json`. What it read is kept in
`audit/snapshot.json`.

| Exit | Meaning |
|---|---|
| `0` | no deviations |
| `1` | deviations found |
| `2` | could not run, and nothing was measured. The message says why |

It refuses before reading the account if `audit/live.yaml` is malformed, or if a workspace's
environment is not one your platform set records. A workspace name the account does not have stops
the read, naming it. A workspace you left out is listed in the report, but not measured.

A report of 0 deviations does not mean the account conforms. Read all four counts: deviations,
unevaluated, conformant and not enforced. A high unevaluated count means little was measured. The
report also names the principal it read as. Anything that principal cannot see is missing from the
snapshot, so it is not measured.

## What it decides

- **`platform-core`**, the lakehouse foundations: how workspaces and catalogs are isolated, which
Expand Down
37 changes: 16 additions & 21 deletions SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,8 +339,9 @@ audit writes goes in `<repo>/audit/`:
The snapshot holds no credential, but it names the team's workspaces, catalogs and schemas. Whether
to commit the snapshot and the report is the team's call.

The audit is four steps, each a command. The first only sets up the second: the reader is the one
that reaches the network with the team's credentials, and the audit itself reads files only.
The audit is three steps. The first two settle what to read and as whom; the third is one command,
`audit_live.py`, which reads the account with the team's credentials and then measures what it read,
from files only. A team without Claude runs the same command (the README says how).

### 1. Say which workspaces are the estate

Expand Down Expand Up @@ -409,41 +410,35 @@ reported unevaluated until they audit again with a profile that reaches the buck
for them, and never fall back to it after a failed read. The principal needs
`s3:GetBucketVersioning` and `s3:GetLifecycleConfiguration` on each bucket.

### 3. Read the account
### 3. Read and measure the account

Say before running it that it reads the account and the buckets, as the two profiles, with read
calls only.
calls only, and then measures what it read. Run it from `<repo>`:

```bash
uv run --project <skill>/scripts --locked --group audit <skill>/scripts/snapshot.py \
--declaration <repo>/audit/live.yaml --out <repo>/audit/snapshot.json \
cd <repo> && uv run --project <skill>/scripts --locked --group audit <skill>/scripts/audit_live.py \
--databricks-profile <profile> (--aws-profile <profile> | --no-storage)
```

`--no-storage` only when the team picked "I can't read the buckets", and then no `--aws-profile`.
It reads `platform/adr-set.yaml` and `audit/live.yaml`, and writes `audit/snapshot.json` and
`audit/audit.json`.

| Code | Meaning | What to do |
|---|---|---|
| `0` | every declared workspace and every bucket was read, and the snapshot written | go on to step 4 |
| `2` | could not run, and **nothing was written** | **stop.** Show stderr. It names every workspace or bucket not read, with the reason, and the profile used |

| `0` | read and measured: no deviation | report the result |
| `1` | read and measured: deviations found — a measurement, not an error | report the result |
| `2` | could not run, and **nothing was measured** | **stop.** Show stderr |

Exit `2` comes before the read when the files are wrong: no declaration, a defective one, a
defective set, or a workspace labelled with an environment the set does not record — the label is
the team's to correct. It comes after the read starts when the account or a bucket could not be
read: stderr names every workspace or bucket not read, with the reason, and the profile used.
There is no partial snapshot. A declared workspace the account does not list usually means the
profile reaches another account; one it lists but cannot read means the principal lacks access.
Either way the remedy is the configuration, not the declaration. A bucket the AWS profile cannot
read is the team's to fix, or to answer with "I can't read the buckets" — theirs to choose.

### 4. Audit the snapshot

```bash
uv run --project <skill>/scripts --locked <skill>/scripts/audit.py \
--set <repo>/platform/adr-set.yaml --declaration <repo>/audit/live.yaml \
--snapshot <repo>/audit/snapshot.json --report <repo>/audit/audit.json
```

Exit `0` no deviation, `1` deviations found — a measurement, not an error — and `2` could not run,
with no report written. A snapshot taken against a different declaration is refused with `2`,
naming the difference: read the account again.

### Reporting the result

The audit writes the structured report and prints a rendering written for a reader. **Prefer the
Expand Down
41 changes: 30 additions & 11 deletions scripts/audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
from wizard.divergence import LIVE # noqa: E402
from wizard.live.report import report # noqa: E402
from wizard.live.storage import unread_buckets # noqa: E402
from wizard.naming import refuse_unrecorded # noqa: E402
from wizard.rendering import render # noqa: E402
from wizard.report import render_human # noqa: E402
from wizard.validity import CannotRun # noqa: E402
Expand All @@ -71,27 +72,45 @@ def main(argv=None):
try:
audited = audit(args.set_path, args.declaration, args.snapshot)
write(args.report, json.dumps(audited, indent=2, ensure_ascii=False) + "\n")
except Defective as exc:
print(f"cannot audit: the {ARTEFACTS[exc.artefact]} is defective", file=sys.stderr)
print(render_human(exc.artefact, exc.failures), file=sys.stderr)
return CANNOT_RUN
except CannotRun as exc:
print(f"cannot run: {exc}", file=sys.stderr)
except REFUSALS as exc:
refuse(exc)
return CANNOT_RUN

print(render(audited))
return DEVIATIONS_FOUND if audited["counts"]["deviations"] else NO_DEVIATION


# What the audit refuses with, and how it says so, wherever it is run from
# (`audit_live.py` too).
REFUSALS = (Defective, CannotRun)


def refuse(exc):
if isinstance(exc, Defective):
print(f"cannot audit: the {ARTEFACTS[exc.artefact]} is defective", file=sys.stderr)
print(render_human(exc.artefact, exc.failures), file=sys.stderr)
else:
print(f"cannot run: {exc}", file=sys.stderr)


def checked(set_path, declaration_path):
"""`(declaration, set document)`, or a refusal: what the audit refuses from
the files alone, before any snapshot. The declaration first, then the set,
then the labels the declaration gives."""
declaration = live_declaration.read(declaration_path)
document = validated(adr_set, "adr-set", set_path)
refuse_unrecorded(document, [workspace.get("environment")
for workspace in declaration["workspaces"]])
return declaration, document


def audit(set_path, declaration_path, snapshot_path):
"""The report of one audit, or a refusal before anything is measured.

The declaration first, then the set, then
the snapshot and whether it describes the declaration: one run reports one
thing, the earliest wrong.
The files first (`checked`), then the snapshot and whether it describes the
declaration: one run reports one thing, the earliest wrong.
"""
declaration = live_declaration.read(declaration_path)
document = validated(adr_set, "adr-set", set_path)
declaration, document = checked(set_path, declaration_path)
snapshot = read_snapshot(snapshot_path)
found = mismatches(snapshot, declaration)
if found:
Expand Down
166 changes: 166 additions & 0 deletions scripts/audit_live.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
#!/usr/bin/env python3
"""Audit the live account in one command: read it, then measure what was read.

cd <ADR monorepo>
uv run --project <skill>/scripts --locked --group audit <skill>/scripts/audit_live.py \\
--databricks-profile NAME (--aws-profile NAME | --no-storage) \\
[--set PATH] [--declaration PATH] [--snapshot PATH] [--report PATH]

It runs `snapshot.py` and then `audit.py`, and adds nothing to either: the
snapshot, the report, what is printed and the exit code are theirs. What the
files alone refuse — a defective declaration, a defective set, a label the set
does not record — is refused before the account is read, since the audit would
refuse it after the read anyway. A read that fails measures nothing. Where there
is no declaration, one is written for the team to fill in, and nothing is read
but the account's list of workspaces.

The files are where the published skill keeps them, relative to the directory it
is run from, unless named:

--set platform/adr-set.yaml
--declaration audit/live.yaml
--snapshot audit/snapshot.json
--report audit/audit.json

The profiles are never defaulted: a profile is who reads the account.

Exit codes, as the audit's:

0 no deviation was found
1 one or more were — a measurement, not a build verdict
2 could not run, and nothing was measured
"""

import argparse
import os
import sys
from pathlib import Path

import audit
import live
import snapshot
from wizard import adr_set, profiles
from wizard.analysis import validated
from wizard.files import write
from wizard.naming import set_environments
from wizard.validity import CannotRun, Refused

CANNOT_RUN = 2

DEFAULTS = {
"set_path": "platform/adr-set.yaml",
"declaration": "audit/live.yaml",
"snapshot": "audit/snapshot.json",
"report": "audit/audit.json",
}


def main(argv=None):
parser = argparse.ArgumentParser(
prog="audit_live.py",
description="Read the live account, then measure it against the ADR set.",
)
parser.add_argument("--set", dest="set_path", default=DEFAULTS["set_path"], metavar="PATH",
help=f"the ADR set to measure against (default {DEFAULTS['set_path']})")
for name, what in (("declaration", "the live estate declaration"),
("snapshot", "where the snapshot is written"),
("report", "where the structured report is written")):
parser.add_argument(f"--{name}", default=DEFAULTS[name], metavar="PATH",
help=f"{what} (default {DEFAULTS[name]})")
profiles.add_arguments(parser, ("databricks",))
storage = parser.add_mutually_exclusive_group()
storage.add_argument("--aws-profile", metavar="NAME",
help="the AWS configuration profile to read the buckets through; a "
"profile, never a credential")
storage.add_argument("--no-storage", action="store_true",
help="read no bucket: PRE-001 is then reported unevaluated")
args = parser.parse_args(argv)

if not os.path.lexists(args.declaration):
return no_declaration(args)
try:
audit.checked(args.set_path, args.declaration)
except audit.REFUSALS as exc:
audit.refuse(exc)
return CANNOT_RUN

read = snapshot.main(["--declaration", args.declaration, "--out", args.snapshot,
*_given("--databricks-profile", args.databricks_profile),
*_given("--aws-profile", args.aws_profile),
*(["--no-storage"] if args.no_storage else [])])
if read != 0:
return read
return audit.main(["--set", args.set_path, "--declaration", args.declaration,
"--snapshot", args.snapshot, "--report", args.report])


def no_declaration(args):
"""Exit 2, measuring nothing, with a declaration written at `args.declaration`
for the team to fill in: the set's entries with their names empty, and the
account's workspaces, or why they could not be listed, in a comment."""
try:
document = validated(adr_set, "adr-set", args.set_path)
except audit.REFUSALS as exc:
audit.refuse(exc)
return CANNOT_RUN
names, why = [], "no --databricks-profile was given to list them with"
if args.databricks_profile is not None:
try:
names = [workspace["name"]
for workspace in live.workspaces(args.databricks_profile)["workspaces"]]
why = "the account lists no workspace"
except (CannotRun, Refused) as exc:
why = str(exc)
out = Path(args.declaration)
out.parent.mkdir(parents=True, exist_ok=True)
write(out, declaration_text(Path(args.set_path).resolve().parent.name,
names or None, why, topology_entries(document)))
print(f"cannot run: no live estate declaration at {out}, so one was written there.\n"
"Fill in the workspace names and run the audit again.", file=sys.stderr)
return CANNOT_RUN


# DEC-001a's options under which every environment shares a workspace.
SHARED_TOPOLOGIES = ("unit", "single")


def topology_entries(document):
"""The environment of each workspace a declaration of the set needs, `None`
for one that holds none: one per environment the set records, unless its
DEC-001a shares a workspace between environments, or it records none. Only an
adopted entry can have a shared option chosen: a declined one's is `declined`."""
for adr in document.get("adrs") or ():
if adr.get("corpus_entry") == "DEC-001a":
chosen = [option.get("key") for option in adr.get("options") or ()
if option.get("status") == "chosen"]
if chosen and chosen[0] in SHARED_TOPOLOGIES:
return [None]
return set_environments(document) or [None]


def declaration_text(name, workspaces, why, environments):
"""A declaration to fill in: the account's `workspaces` in a comment, or `why`
there are none, and an entry with an empty name for each of `environments`.
Text, since YAML's writer writes no comments; workspace names are only ever in
comments."""
if workspaces:
listing = ["# The account's workspaces:", *(f"# {each}" for each in workspaces)]
else:
listing = ["# The account's workspaces could not be listed:",
*(f"# {line}" for line in why.splitlines())]
lines = ["schema_version: 1", f"name: {name}", *listing, "workspaces:"]
for environment in environments:
if environment is None:
lines.append(" - name: # <fill here the name of a workspace of the estate>")
else:
lines += [f" - name: # <fill here the name of the workspace for {environment}>",
f" environment: {environment}"]
return "\n".join(lines) + "\n"


def _given(flag, value):
return [flag, value] if value is not None else []


if __name__ == "__main__":
raise SystemExit(main())
Loading
Loading