Metadata-Version: 2.4
Name: tarkin
Version: 0.4.2
Summary: Governance compiler for PostgreSQL
Author-email: Brent Pollard <brentjpollard@gmail.com>
License-Expression: Apache-2.0
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: typer<1.0,>=0.9
Requires-Dist: pydantic<3.0,>=2.0
Requires-Dist: sqlalchemy<3.0,>=2.0
Requires-Dist: psycopg[binary]<4.0,>=3.1
Requires-Dist: ruamel.yaml<1.0,>=0.18
Provides-Extra: test
Requires-Dist: pytest<9.0,>=8.0; extra == "test"
Requires-Dist: boto3>=1.26; extra == "test"
Provides-Extra: query
Requires-Dist: anthropic<1.0,>=0.25; extra == "query"
Requires-Dist: openai<2.0,>=1.0; extra == "query"
Provides-Extra: iam
Requires-Dist: boto3>=1.26; extra == "iam"
Dynamic: license-file

# Tarkin: govern your data

An open source governance compiler for PostgreSQL.

![Careful, Princess. Disclosing the Rebellion's location like that is strictly in violation of GDPR.](./tarkin.jpg)

## Why?

Data governance is tough. Regulations aren't made with implementation in mind, and data engineers often aren't the ones making those decisions anyway.

The result:
- A lot of ad-hoc work in triggers, functions, and manual grants
- Constant required fixes
- Limited documentation (or a ton of work to write it all)
Or, you take an off-the-shelf solution that's a complete black-box.

But it's not rocket science, just a lot of work. I made this to help. And also so that I don't have to write out column GRANTs ever again.

## How it works

By design, Tarkin is an open book: open source, fully accessible code, fully human-readable output. The point of data governance is to keep things secure, so having any aspect of the process live in a black-box is counterintuitive.

Tarkin is run through a Command Line Interface (CLI) tool built in Python with Typer. Some commands generate YAMLs for you to view and modify, or SQL scripts for you to validate, and others apply those scripts once you've decided they're ready. Nothing happens without your direct approval. And don't just take my word for it — check [the GitHub repo](https://github.com/BProgramming/tarkin) yourself.

## Reading the governance model

Once a database is attached, its governance model is readable through a set of `SECURITY DEFINER` functions in `__META__`, granted to `PUBLIC`. Authorization is enforced inside PostgreSQL against the calling role's grants and clearance — a client only ever receives what that role is entitled to, and Tarkin is not in a position to get that wrong.

```bash
tarkin discover --profile mydb                             # everything visible to your role
tarkin discover --profile mydb -obj retention -obj rls     # just the governance stuff
tarkin discover --profile mydb -obj columns -s analytics
tarkin discover --profile mydb -obj columns -s public -t patients
tarkin discover --profile mydb -obj erasure_counts --since 2026-01-01
```

Results are printed as JSON. Add `--output` to also write a timestamped JSON file.

The same functions are callable over any PostgreSQL connection, and a view flattens them into one row per column:

```sql
SELECT * FROM __META__.tarkin_governance;
SELECT __META__.get_columns('analytics');
SELECT __META__.get_rls_policies('analytics', 'events');
```

Available discovery functions: `get_schemas`, `get_tables`, `get_columns`, `get_roles`, `get_build`, `get_retention`, `get_erasures`, `get_erasure_counts`, and `get_rls_policies`. Filtering happens inside each function against `session_user` (the authenticated login role), so `__META__.tarkin_governance` needs no `security_invoker` and returns the right answer regardless of who owns it. `SELECT` on the view is granted to `PUBLIC`; what comes back is not.

This is how third-party tooling reads a Tarkin-governed database. An AI agent connected as a governed role can build a query against the model without Tarkin brokering the connection, without a service to deploy, and without a second set of credentials. `tarkin query` is one consumer of a surface that is already open to any client.

Descriptions written in the governance YAML are also applied to the database as `COMMENT ON` statements, so they show up in `\d+`, in ORMs, and in any tool that reads `pg_description`, not only through Tarkin. The `__META__` schema comment names the discovery functions, and each function carries a comment describing what it returns and how it is filtered — so a client reading `pg_description` finds the surface without knowing Tarkin exists. `tarkin inspect` reads existing comments back into the YAML, so an already-documented database keeps its documentation.

See [REFERENCE.md](REFERENCE.md) for the full function list and each one's visibility rule.

## Installation

```bash
pip install tarkin
pip install tarkin[query] # optional extension as of v0.2.0, required for 'tarkin query'
pip install tarkin[iam]   # optional extension as of v0.3.0, required for 'tarkin auth'
```

Or with uv: `uv add tarkin`, `uv add tarkin[query]`, `uv add tarkin[iam]`.

IAM/SSO authentication also requires the [AWS CLI](https://aws.amazon.com/cli/). Certificate-based authentication needs neither the extension nor the AWS CLI — those connections authenticate through your provider's own CLI (e.g. Okta), and Tarkin simply reads the certificate files already on disk.

Requires Python 3.11+ and PostgreSQL 14+, or PostgreSQL 16+ for MAINTAIN privileges.

## Quick start

```bash
# Authorize your database connection (for IAM credentials only)
tarkin auth --profile mydb

# Inspect a live database and generate a governance YAML
tarkin inspect --profile mydb

# Edit out/mydb_model.yaml to configure governance

# Compile and validate
tarkin validate out/mydb_model.yaml
tarkin build out/mydb_model.yaml --profile mydb

# Apply
tarkin attach --profile mydb

# Read the governance model back
tarkin discover --profile mydb

# Remove
tarkin detach --profile mydb --keep-versioning
```

Run `tarkin help` or `tarkin --help` for the full command reference.

## Upgrading an existing installation

A database keeps the `__META__` schema and generated SQL from the version it was attached under until you update it. After upgrading the package, run:

```bash
pip install --upgrade tarkin
tarkin update --profile mydb
tarkin migrate --force --profile mydb path/to/your.yaml
tarkin attach -b out/tarkin_migrate_TIMESTAMP.zip --profile mydb
```

Order matters: `update` adds the columns the new codegen expects before `migrate` regenerates against them.

- `tarkin update` converges the `__META__` tables and refreshes the discovery functions in place. Every patch is idempotent by contract, so it is safe to run any number of times, against a database attached under any prior version. It reports what it applied rather than what changed.
- `tarkin migrate --force` generates a migration artifact even when your governance model hasn't changed, converging the database on the installed version's codegen. That includes rebuilding every table's views, triggers, row-level security and view grants, so fixes to the generated view layer reach an existing database. As with any migration, it goes through the normal artifact flow rather than mutating the database directly, so you can read the generated SQL before you attach it.

> **Databases attached under v0.1.0 through v0.3.0 must be upgraded.** Those versions had two security bugs in the discovery surface, fixed in v0.4.0: `__META__` was missing `GRANT USAGE`, and the discovery functions filtered on `current_user` (the function owner, inside `SECURITY DEFINER`) instead of `session_user`. Only metadata was ever exposed, never data. See the [v0.4.0 release notes](https://github.com/BProgramming/tarkin/releases/tag/v0.4.0) for details.

## Credentials

Tarkin uses a `credentials.toml` file (default: `~/.tarkin/credentials.toml`) to store connection profiles. Three authentication methods are supported.
Note that `sslmode` defaults to `verify-full` for IAM and certificate profiles, and `prefer` for username/password profiles. It can be overridden explicitly if needed.

Supported methods:
**Username and password:**
```toml
[mydb]
host     = "localhost"
port     = 5432
database = "myapp"
username = "postgres"
password = "secret"
hmac_key = "your-strong-secret-key"    # Optional: HMAC key for HMAC256 column hashing
```

**AWS IAM / SSO:**
```toml
[mydb]
host        = "mydb.xxxx.us-east-1.rds.amazonaws.com"
port        = 5432
database    = "myapp"
username    = "db_user"
iam_auth    = true
aws_profile = "my-aws-profile"         # Optional: defaults to the AWS default profile
aws_region  = "us-east-1"
hmac_key    = "your-strong-secret-key" # Optional: HMAC key for HMAC256 column hashing
```

Run `tarkin auth --profile mydb` to authenticate before connecting. Use `--reauth`/`-r` on any command that connects to your database to be prompted to re-authorize via browser login if your SSO session has expired; Tarkin then retries. If an IAM connection fails and a `password` is also configured on the profile, Tarkin falls back to username and password.

**Certificate-based auth (e.g. Okta Privileged Access):**
```toml
[mydb]
host        = "mydb.example.com"
port        = 5432
database    = "myapp"
username    = "alice"                  # Must match the CN in your client certificate
sslcert     = "~/.okta/client.crt"
sslkey      = "~/.okta/client.key"
sslrootcert = "~/.okta/ca.crt"
hmac_key    = "your-strong-secret-key" # Optional: HMAC key for HMAC256 column hashing
```

### AI provider (for `tarkin query`)

`tarkin query` needs a single `[ai]` section in the same file:

```toml
[ai]
provider = "anthropic"
api_key  = "sk-ant-..."
model    = "claude-sonnet-4-6"
```

```toml
[ai]
provider = "openai"
api_key  = "sk-..."
model    = "gpt-4o"
```

```toml
[ai]
provider = "openai"                                    # Azure OpenAI
api_key  = "your-azure-key"
model    = "gpt-4o"
base_url = "https://your-instance.openai.azure.com/"
```

None of this is needed for agents or MCP clients that connect to the database directly — they can call the discovery functions with the role's own credentials.

## Writes and row-level security

Governed roles read and write through the views; they hold no privileges on the `tk_` shadow tables, which is what keeps them from skipping the masking. Each view has two `INSTEAD OF` triggers. The first runs as the caller: it fills defaults (so `DEFAULT current_user` records who wrote the row), enforces immutable columns, and checks row-level security. The second writes to the shadow table as its owner, touching only the columns the caller changed. If it can't find the row a write is aimed at, typically because the primary key is masked, it raises an error rather than reporting success.

Serial and identity columns work through the view: the owned sequence stays in the shadow schema with its table, and the owner-side trigger draws the next value, so `INSERT ... RETURNING id` reports it. Callers have no privileges on the sequence itself, so `currval()` and `lastval()` aren't available to them; use `RETURNING`.

Row-level security policies in the YAML are applied to the caller in the view layer, with PostgreSQL's semantics:

```yaml
rls_enabled: true
rls_policies:
  - roles: [analyst, support]
    using_expr: tenant_id = current_setting('app.tenant_id')::bigint
```

- `using_expr` filters what the caller can see, and which rows an `UPDATE` or `DELETE` can reach.
- `check_expr` (defaulting to `using_expr`) must hold for any row the caller inserts or updates, or the write fails with PostgreSQL's own RLS error.
- Policies are permissive: a row passes if any policy that applies to the caller admits it. Superusers and `BYPASSRLS` roles bypass them, as does the table owner unless `rls_force: true`.

The policies are also created on the shadow table, so `get_rls_policies` and `\d+` report them as they are. See [SECURITY.md](SECURITY.md) for how the enforcement works and its known limitations; in particular, write policies against unmasked columns.

## Versioning columns

When a column has `versioned: true`, Tarkin adds `__valid_from__` and `__valid_to__` columns to the shadow table to maintain a full history of changes. Both are exposed through the view, after the declared columns, so every row says which version it is. The view shows every version; the `_current` view variant (e.g. `users_current`) is created automatically and filters to live records (`__valid_to__ = 'infinity'`).

Writes through the view act on the current version:
- `UPDATE` closes the current version (`__valid_to__ = now()`) and inserts the new one. A statement that also matches historical versions of the record leaves them alone, so one update writes one version.
- `DELETE` closes the current version. History is never deleted through the view; erasure and retention handle that.
- `INSERT` uses `now()` and `'infinity'` unless you supply the versioning columns yourself, for example to backfill history.
- Changing a version's own `__valid_from__` or `__valid_to__` in an `UPDATE` edits that version in place instead of versioning it. That's an escape hatch for fixing history, and it's yours to use carefully; the partial unique index still stops two versions of a record being live at once.

Because a versioned table keeps historical rows that reuse the same key values, its original single-row primary key is replaced with a partial unique index covering only the live row (`__valid_to__ = 'infinity'`). As a consequence, **a versioned table cannot be the target of a foreign key**; `tarkin validate` rejects any configuration that does this.

On `tarkin migrate`, if a change removes versioning from the last versioned column in a table:
- With `--drop-versioning`/`-d`: only current records (`__valid_to__ = 'infinity'`) are retained and the versioning columns are dropped. **This operation is destructive and irreversible.**
- Without it, the migration fails with an error rather than leaving orphaned versioning columns behind.

There is no keep option on migrate. If you want to keep the history, leave at least one column in the table versioned — Tarkin won't create data it doesn't govern, since that data would be out of reach of erasure and retention.

On `tarkin detach`:
- With `--keep-versioning`: the `__valid_from__` and `__valid_to__` columns are retained in the restored table, along with all historical records. This is the safe default when history is valuable.
- With `--drop-versioning`: only current records (`__valid_to__ = 'infinity'`) are retained and the versioning columns are dropped. **This operation is destructive and irreversible.**

The versioning index (`idx_<table>_current`) is dropped when `--drop-versioning` is used, and retained otherwise.

## Retention columns

When a table has `retention_days` set, Tarkin adds `__expires_at__` and `__erase_on_expiry__` columns to the shadow table to support time-based data expiry. These columns are intentionally **not exposed through the public-facing view** — the view layer presents only the declared columns.

`__expires_at__` is a `timestamptz` column with a default of `now() + interval '<retention_days> days'`, computed at INSERT time. `__erase_on_expiry__` is a `bool` column defaulting to `true`. A partial index on `__expires_at__ WHERE __erase_on_expiry__ = true` is created to keep the scheduled sweep performant.

Setting `__erase_on_expiry__ = false` on any individual row exempts it from scheduled deletion — this is the mechanism for legal holds when a record must be retained beyond its normal expiry.

When `retention_schedule` is configured on the database, Tarkin registers a pg_cron job named `tarkin_retention_<database>` that calls `__META__.tarkin_erase_expired_records()` on the configured cron schedule. That function sweeps all tables registered in `__META__.tarkin_retention`, finds rows where `__expires_at__ <= now() AND __erase_on_expiry__ = true`, and applies the table's `erase_strategy` (`delete`, `nullify`, or `obfuscate`). Each sweep is logged to `__META__.tarkin_erasures` with `was_scheduled = true`, and is readable through `get_erasures` and `get_erasure_counts`.

On `tarkin detach`:
- The pg_cron job is unscheduled (guarded by a check that pg_cron is installed, since it may have been removed independently)
- The partial index `idx_<table>_expires_at` is dropped
- The `__expires_at__` and `__erase_on_expiry__` columns are dropped from the shadow table before the schema rename

Unlike versioning, there is no keep/drop flag — retention columns are always removed on detach. Any records that had not yet expired are restored to the table without expiry metadata, and the operator is responsible for any cleanup.

## Security

See [SECURITY.md](SECURITY.md) for:
- Release integrity and SBOM verification
- The discovery function surface and what it deliberately withholds
- HMAC key management and rotation
- Shadow schema model and detach guarantees
- Column masking security notes (xxhash vs SHA vs HMAC)
- Sensitive column enforcement
- pgaudit configuration and restoration
- Known limitations

## Reference

See [REFERENCE.md](REFERENCE.md) for an overview of all available CLI commands, and the [releases page](https://github.com/BProgramming/tarkin/releases) for per-version changes.

## License

Apache 2.0. See [LICENSE](LICENSE).
