diff --git a/.github/quality.yml b/.github/quality.yml index 2549116c..0a817644 100644 --- a/.github/quality.yml +++ b/.github/quality.yml @@ -41,8 +41,9 @@ classes: - "content/*" - "public/*" - "ops/*" # the hosted scheduler's cron jobs - # Run by every production deploy (vercel-build) or by the gateway image build. - - "scripts/vercel-maybe-migrate.ts" + # Run by every production deploy (vercel-build), by the schema release job or by the gateway image build. + - "scripts/wait-for-schema-release.ts" + - "scripts/schema-release-plan.sh" - "scripts/migrate.ts" - "scripts/*.sql" # the database grants migrate.ts applies - "scripts/verify-exomem-gateway-bundle.mjs" @@ -54,6 +55,7 @@ classes: - "scripts/strict-generation-visibility-cutover.ts" - "scripts/generate-jwt-keypair.ts" # `--commit` inserts the public key into signing_keys - ".github/workflows/publish-exomem-gateway.yml" # builds and publishes the gateway image + - ".github/workflows/migrate-database.yml" # applies the schema release to production - "instrumentation.ts" - "next.config.ts" - "tailwind.config.ts" diff --git a/.github/workflows/migrate-database.yml b/.github/workflows/migrate-database.yml new file mode 100644 index 00000000..99d124e7 --- /dev/null +++ b/.github/workflows/migrate-database.yml @@ -0,0 +1,75 @@ +# Applies the database migrations and the grants script for the tip of `main`, +# then records the tip's schema release. The production build waits for that +# row (scripts/wait-for-schema-release.ts) and runs no migration itself. +# +# Every run releases the tip of `main` as it stands when the run starts, whatever +# commit started it. The group below keeps one waiting run, so a restart of an +# old run can replace the waiting run of a newer push. That run then releases the +# newer tip and loses nothing. Only the step that applies reads the tip again, and +# it applies nothing when `main` moved during the install: the push that moved it +# started a run of its own. This rule needs a run for every push to `main`, so +# the `push` trigger has no path filter. +# +# This is the only workflow that names the protected environment, and it starts +# only on a push to `main` or by hand. The environment accepts only `main` and +# holds the schema-owner connection string. +name: migrate-database + +on: + push: + branches: [main] + workflow_dispatch: + inputs: + dry_run: + description: List the pending migrations and change nothing + type: boolean + default: true + +permissions: + contents: read + +# One run applies at a time, and a running job is never cancelled: a cancelled +# migration would leave a half-applied step for the next run to find. A dry run +# changes nothing, so it takes a group of its own and never displaces a waiting +# run. +concurrency: + group: ${{ inputs.dry_run && format('schema-dry-run-{0}', github.run_id) || 'schema-release' }} + cancel-in-progress: false + +jobs: + migrate: + runs-on: ubuntu-latest + timeout-minutes: 30 + environment: production-schema + steps: + # The tip, not the commit that started the run. + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + with: + ref: main + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 24 + # No package install script runs in a job that holds the schema owner's credential. + - run: npm ci --ignore-scripts + # Reads git only. It runs after the install and just before the migration, so it + # sees the tip as late as it can. + - id: plan + run: scripts/schema-release-plan.sh >> "$GITHUB_OUTPUT" + # The only step that receives the secret. + - name: Migrate + env: + DATABASE_MIGRATION_URL: ${{ secrets.DATABASE_MIGRATION_URL }} + DRY_RUN: ${{ inputs.dry_run }} + APPLY: ${{ steps.plan.outputs.apply }} + TIP: ${{ steps.plan.outputs.tip }} + SUPERSEDED: ${{ steps.plan.outputs.superseded }} + run: | + if [ "$DRY_RUN" = "true" ]; then + node_modules/.bin/tsx scripts/migrate.ts --dry + elif [ "$APPLY" = "true" ]; then + node_modules/.bin/tsx scripts/migrate.ts --commit "$TIP" --superseded "$SUPERSEDED" + else + echo "::notice::main moved to $TIP while this job installed. The run for that push applies it." + fi diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index db0081cc..84f48ee2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -37,16 +37,19 @@ jobs: - id: install run: npm ci - run: npm test + # The PostgreSQL steps run one file at a time: the suites create the same login roles, and + # roles, their passwords and their grants belong to the cluster, so two files cannot share it. - name: Exomem shared PostgreSQL authority (OAuth, capacity, billing, sessions, migrations) env: EXOMEM_TEST_DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/substrate_test CONFIRM_ENDSTATE_CLOUD_RELEASE_A: "yes" run: >- - node --import tsx --experimental-test-module-mocks --test + node --import tsx --experimental-test-module-mocks --test --test-concurrency=1 src/lib/exomem-hosted/__tests__/oauth-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/capacity-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/migration-upgrade.integration.test.ts src/lib/exomem-hosted/__tests__/migration-runner.integration.test.ts + src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/postgres.integration.test.ts src/lib/exomem-hosted/__tests__/alert-receiver-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/access-recovery.test.ts @@ -55,7 +58,7 @@ jobs: EXOMEM_TEST_DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/substrate_test CONFIRM_ENDSTATE_CLOUD_RELEASE_A: "yes" run: >- - node --import tsx --experimental-test-module-mocks --test + node --import tsx --experimental-test-module-mocks --test --test-concurrency=1 src/lib/hosted-backup/__tests__/version-commit-postgres.integration.test.ts src/lib/db/__tests__/pg-sql-driver.integration.test.ts - name: Exomem Cloud control plane PostgreSQL authority (schema, grants, admission, OAuth, Home channel, exports, lifecycle, deletion, release) @@ -63,9 +66,11 @@ jobs: EXOMEM_TEST_DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/substrate_test CONFIRM_ENDSTATE_CLOUD_RELEASE_A: "yes" run: >- - node --import tsx --experimental-test-module-mocks --test + node --import tsx --experimental-test-module-mocks --test --test-concurrency=1 src/lib/exomem-hosted/__tests__/cloud-cells-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts + src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts + src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/cloud-access-log-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/cloud-imports-postgres.integration.test.ts src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts diff --git a/README.md b/README.md index 9e8f2c5d..173c2bcf 100644 --- a/README.md +++ b/README.md @@ -124,14 +124,17 @@ For a new blog post, do nothing extra — drop a `.md` file in `content/blog/` w The substrate also serves as the auth issuer + metadata store + presigned-URL minter for **Endstate Hosted Backup v2**. Protocol locked in [`hosted-backup-contract.md`](./hosted-backup-contract.md) (OIDC discovery, EdDSA JWTs, Argon2id-derived `serverPassword + masterKey` split, R2 storage with 5-version retention). -**Migrations.** +**Local migrations.** Set `LOCAL_DATABASE_URL` to a disposable database before running these commands. ```bash -npm run migrate # apply pending migrations from migrations/*.sql -npm run migrate:dry # list pending migrations without applying +env -u DATABASE_MIGRATION_URL DATABASE_URL="${LOCAL_DATABASE_URL:?}" npm run migrate:dry +env -u DATABASE_MIGRATION_URL DATABASE_URL="${LOCAL_DATABASE_URL:?}" npm run migrate ``` -The runner auto-creates a `schema_migrations` tracking table on first invocation. +The runner prefers `DATABASE_MIGRATION_URL` when both variables are set. The local commands clear it for each invocation. Applying migrations creates the tracking table if needed. The dry run only lists pending migrations. + +In production, a protected GitHub job (`.github/workflows/migrate-database.yml`) applies the migrations and the grants script for each commit that lands on `main`. +It then records the commit's schema release. The production build reads its schema release and never migrates. [`docs/runbooks/production-keys-and-storage.md`](./docs/runbooks/production-keys-and-storage.md) describes the job and the manual run. **JWT signing key.** Generate the active EdDSA keypair (and optionally insert the public-key row into `signing_keys`): diff --git a/docs/runbooks/exomem-cloud-operations.md b/docs/runbooks/exomem-cloud-operations.md index 5c16f8b1..ebdfc40d 100644 --- a/docs/runbooks/exomem-cloud-operations.md +++ b/docs/runbooks/exomem-cloud-operations.md @@ -770,6 +770,476 @@ ticket, screenshot, test fixture or log. To rotate it, replace the value and redeploy before the provider verifies it. To remove it, delete the variable, redeploy, and confirm that the route returns `404`. +## Identity lock and issuance log + +Migrations `0101` and `0102` lock the rows that decide which tenant a credential reaches. They also record each +credential that the web app issues. This section says what the lock refuses and which statement the schema owner runs in an emergency. +It also says how to read the log and how download tickets use the database. The design is the OpenSpec change +`lock-cloud-identity-rows-and-record-issuance`. Its section "What the claim does not cover" lists the limits of the +claim, and those limits belong beside every statement of it. + +Four database roles appear here. `substrate_owner` owns the schema and runs the migrations. `substrate_app` is the web +app's role. `exomem_gateway` and `exomem_cellctl` are the gateway's and the controller's roles. `substrate_audit` reads +the log and nothing else. + +### What the lock refuses + +The grants script and the guards work together. The grants script takes rights from `substrate_app` on every run. A guard is a trigger that refuses a statement unless the schema owner runs it. +It still holds when a grants script gives too much. A guard raises `EXOMEM_ROW_LOCKED: on is refused` with SQLSTATE `42501`. An error +that reads `permission denied` comes from the grants script, not from a guard. + +| Table | Refused to the web app's role | Update guard | Delete and truncate guards | +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------------- | +| `exomem_oauth_grants` | A change to any column except `scopes`, `refresh_allowed`, `authorization_transaction_id`, `updated_at`, `revoked_at` and `client_context_override`; a delete | `exomem_oauth_grants_identity_lock` | `exomem_oauth_grants_delete_lock`, `exomem_oauth_grants_truncate_lock` | +| `exomem_oauth_token_families` | A change to any column except `revoked_at` and `revoked_reason` | `exomem_oauth_token_families_identity_lock` | none: deletes stay | +| `exomem_oauth_access_tokens` | A change to any column except `revoked_at` | `exomem_oauth_access_tokens_identity_lock` | none: deletes stay | +| `exomem_oauth_refresh_tokens` | A change to any column except `consumed_at` | `exomem_oauth_refresh_tokens_identity_lock` | none: deletes stay | +| `exomem_cloud_service_credentials` | A change to any column except `revoked_at` and `revoked_by_principal_digest`; a delete | `exomem_cloud_service_credentials_identity_lock` | `exomem_cloud_service_credentials_delete_lock`, `..._truncate_lock` | +| `exomem_oauth_clients` | A change to `id` or `client_id`; a delete | `exomem_oauth_clients_identity_lock` | `exomem_oauth_clients_delete_lock`, `exomem_oauth_clients_truncate_lock` | +| `exomem_tenants` | A change to `owner_user_id`; a delete | `exomem_tenants_identity_lock` | `exomem_tenants_delete_lock`, `exomem_tenants_truncate_lock` | +| `exomem_cloud_cells` | A change to `cell_id` or `tenant_id`; a delete | `exomem_cloud_cells_identity_lock` | `exomem_cloud_cells_delete_lock`, `exomem_cloud_cells_truncate_lock` | +| `exomem_users` | A delete | none | `exomem_users_delete_lock`, `exomem_users_truncate_lock` | +| `exomem_marketplace_reviewer_credentials` | A delete | none | `exomem_marketplace_reviewer_credentials_delete_lock`, `..._truncate_lock` | + +Four more rules hold on the same terms: + +- A revocation or consumption time that is already set cannot change. A statement that keeps the value succeeds. +- `schema_releases` and `exomem_cloud_issuance_log` refuse every insert, update, delete and truncate. + Only the schema owner and the routines that run as the schema owner may write them. The guards are `schema_releases_owner_only`, + `exomem_cloud_issuance_log_owner_only` and the matching `..._owner_only_truncate` triggers. +- A row in `exomem_cloud_download_tickets` cannot change. The guard is `exomem_cloud_download_tickets_update_lock`. +- A truncate that cascades from another table meets the same guards. + +The schema owner is exempt, because it can drop any guard. The lock is stated against the select, insert, update, +delete and truncate rights. It does not hold against a role that holds the trigger right, or a create right on the +database or on a schema. The checks below read those rights. + +### Emergency statements + +Run each statement as the schema owner, in `psql`, and write down its time and text. Read the error first, to see which +statement fits. + +- `permission denied for table` or `for column`: the grants script withheld a right. Use statement 1. +- `EXOMEM_ROW_LOCKED`: a guard refused a flow. Use statement 2. +- A credential insert fails, and the error names `exomem_record_issuance` or the log: the recording failed. Use + statement 3. + +| No | Statement | What it suspends | Undo | +| --- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------- | +| 1 | `GRANT UPDATE () ON
TO substrate_app;` | Only the missing right on that column. The guard still refuses a fixed column. The grant lasts until the next run of the grants script, which is the next merge. | `REVOKE UPDATE () ON
FROM substrate_app;` | +| 2 | `ALTER TABLE
DISABLE TRIGGER ;` | That guard, for every role, on that table. The table's protection then rests on rights alone, and the grants script does not re-enable the trigger. A migration does not either. | `ALTER TABLE
ENABLE TRIGGER ;` | +| 3 | `ALTER TABLE
DISABLE TRIGGER
_issuance_record;` | The claim that the database records each credential, for that credential kind. A credential that the web app creates while the trigger is off has no record. The check "credential rows without a record" lists each one afterwards. | `ALTER TABLE
ENABLE TRIGGER
_issuance_record;` | + +The recording triggers are `exomem_oauth_token_families_issuance_record`, `exomem_oauth_access_tokens_issuance_record`, +`exomem_oauth_refresh_tokens_issuance_record`, `exomem_cloud_service_credentials_issuance_record` and +`exomem_cloud_download_tickets_issuance_record`. Each one sits on the table that its name gives. + +Four more triggers end a record when its credential is revoked or its row is deleted: `exomem_cloud_service_credentials_issuance_end_revoke` +and `exomem_cloud_service_credentials_issuance_end_delete` on `exomem_cloud_service_credentials`, and +`exomem_oauth_token_families_issuance_end_revoke` and `exomem_oauth_token_families_issuance_end_delete` on +`exomem_oauth_token_families`. While they are off, a service credential's record stays open and the prune never deletes it. +A token family's record then keeps its expiry. + +Two triggers on `exomem_cloud_cells`, `exomem_cloud_cells_service_credentials_end_update` and +`exomem_cloud_cells_service_credentials_end_delete`, revoke a tenant's service credentials when its cell is deleted. While they are off, +a deleted account's service credentials stay live in the database, and the gateway still refuses them, because it serves only a tenant that has a cell +that is not deleted. Revoke each one through the operator API afterwards. + +One trigger on `exomem_cloud_service_credentials`, `exomem_cloud_service_credentials_live_cell`, refuses a new service credential for a tenant +that has no cell that is not deleted, and locks that cell's row while the credential is inserted. While it is off, a request that overlaps a cell's +deletion can commit after the deletion's trigger ran, and its credential stays live for the tenant's next cell. After it is on again, revoke through +the operator API each live service credential of a tenant that has no cell that is not deleted. + +A hand-typed grant or a disabled trigger is an emergency state, not a fix. After either statement: + +1. Open a commit that changes the grants script or the guard so that the flow works under the lock. +2. Merge it. The migration job applies the grants script. +3. Run the undo of the statement, if the grants script has not already done so. +4. Run the catalog check "triggers that are missing or disabled" below. The expected result is no rows. +5. For statement 3, run the check "credential rows without a record" over the period of the outage. + +### The issuance log + +`exomem_cloud_issuance_log` holds one record for each credential that the web app inserts. +The credential is a token family, an access token, a refresh token, a service credential or a download ticket. A record holds identifiers only. +These are the credential's `id` and kind, its grant, token family, client, tenant and user, and its expiry. +A record also holds its own time and the database role that wrote it. It holds no token, digest, secret, path or address. A record that the migration wrote for an older +row has `backfilled` set. Its `recorded_at` is the migration's time. The migration writes no record for a row whose end is more than 90 days old, because the prune +would delete the record at once. + +The recording fails closed. A credential insert fails when its record cannot be written. The web app's role cannot read, +write or alter the log. The reconcile job calls `exomem_prune_issuance_log()` once a run. The function deletes at most +10,000 records whose credential expired, or ended, more than 90 days ago. A service credential has no expiry. Its +record stays open while the credential is live, and the prune never deletes it. When the credential is revoked, or its +row is deleted, the record's end becomes the database clock's time, and the prune deletes it 90 days later. A token +family's record ends the same way when the family is revoked or deleted, if that is before its expiry. The +session policy sets a token family's expiry, `EXOMEM_OAUTH_SESSION_MAX_DAYS` after sign-in (365 days by default, at most 730), and a refresh +token's expiry, `EXOMEM_OAUTH_REFRESH_IDLE_DAYS` (30 days by default, at most 90). The database bounds no expiry, so a role that +writes a far expiry only lengthens retention. A database trigger revokes a tenant's service credentials when its cell is deleted, whichever release or job deletes it. The migration +also revoked once the credentials of every account that an earlier release had deleted. After the deletion, a +token family's record and a service credential's record last 90 days, and an access token's or a refresh token's record lasts +until 90 days after its own expiry. The longest +window after deletion is the refresh idle bound plus 90 days: 120 days by default, 180 at most. Only the schema owner deletes a record. The job's response reports the deleted counts as `issuancePruned.records` and +`issuancePruned.tickets`. A value of `null` means that part failed, and the log line `exomem-issuance: log retention +failed` names it. A failed part makes the job answer `503`, and the answer still carries `issuancePruned`. The prune runs +whatever the other lanes do. + +#### Read it as the audit role + +Connect as `substrate_audit` for these checks. It can read the issuance log, +the identifier and creation time of each credential, and each tenant's +identifier and owner. Run the credential check on demand. It reads pages from the five +credential tables. Save the two checkpoints separately and only after their +queries succeed. + +##### Credential rows without an issuance record + +1. Read the migration time as the schema owner: + `SELECT applied_at FROM schema_migrations WHERE version = '0102_exomem_issuance_log_and_download_tickets.sql';`. + Use it as `install`. For the first sweep, use the same value as `checked_through`. +2. Read the settled time as the audit role: `SELECT clock_timestamp() - interval '1 hour';`. Use it as the fixed `credential_target`. +3. If the target is no later than `checked_through`, let the next check cover new time. For a live mint check, use the tenant's log page below. +4. For each row in the table, set `kind` and `credential_table` in psql. Start with `after_id` empty and `page` set to `10000` or a smaller positive number. + + | `kind` | `credential_table` | + | --- | --- | + | `token_family` | `exomem_oauth_token_families` | + | `access_token` | `exomem_oauth_access_tokens` | + | `refresh_token` | `exomem_oauth_refresh_tokens` | + | `service_credential` | `exomem_cloud_service_credentials` | + | `download_ticket` | `exomem_cloud_download_tickets` | + +5. Run this query. It reads a page by credential identifier before filtering by time, so each pass checks only that page. + + ```sql + WITH floor AS ( + SELECT greatest(:'install'::timestamptz, now() - interval '2160 hours') AS start_at + ), credentials AS MATERIALIZED ( + SELECT id, created_at FROM :"credential_table" + WHERE id >= coalesce(nullif(:'after_id', '')::uuid, '00000000-0000-0000-0000-000000000000'::uuid) + AND id IS DISTINCT FROM nullif(:'after_id', '')::uuid + ORDER BY id LIMIT :'page'::integer + ), bounds AS ( + SELECT greatest(start_at, :'checked_through'::timestamptz - interval '1 hour') AS lo, + :'credential_target'::timestamptz AS hi, + start_at + FROM floor + ) + SELECT (SELECT id FROM credentials ORDER BY id DESC LIMIT 1) AS next_id, + bounds.start_at > greatest(:'install'::timestamptz, :'checked_through'::timestamptz) AS retention_gap, + missing.id, missing.created_at + FROM bounds + LEFT JOIN LATERAL ( + SELECT credential.id, credential.created_at + FROM credentials AS credential + LEFT JOIN LATERAL ( + SELECT true AS present + FROM exomem_cloud_issuance_log AS record + WHERE record.credential_kind = :'kind' AND record.credential_id = credential.id + AND record.recorded_at >= credential.created_at + LIMIT 1 + ) AS matching ON true + WHERE credential.created_at >= bounds.lo AND credential.created_at < bounds.hi + AND matching.present IS NULL + ) AS missing ON true; + ``` + +6. Investigate rows with a credential identifier. Without a finding, the query returns one row with empty credential fields. +7. If `retention_gap` is true, record the skipped period as unverified. Older credentials can have pruned records. +8. Set `after_id` to `next_id` after a successful query. Repeat until `next_id` is empty, then move to the next credential kind. +9. After all five kinds finish, save `credential_target` as `checked_through`. + +The time window includes the lower edge and leaves the upper edge to the +next sweep. The one-hour delay lets a transaction with the database's +creation time finish before the sweep reads its identifier range. A longer +open transaction or an explicitly backdated credential can fall outside +that coverage. The next sweep repeats the last hour. The credential and its +log record use the same snapshot in every page. An earlier issuance with the +same identifier cannot satisfy the check. A reuse with the same creation +time can match the old record. For older work, use the tenant's log page. + +##### Recorded issuances + +1. Start psql with `ON_ERROR_STOP` set. Set `prev_id`, `prior_before`, and `prior_after` from the last successful pass. For the first pass, use `0` and two `-infinity` timestamps. +2. Set `id_target` to `0` at the start of a sweep. Set `page` to `100000`, or a smaller positive number. +3. Run this block in one transaction. It reads one new page and replays recent records through the previous stop. + + ```sql + BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY; + SELECT statement_timestamp() AS sample_before, + clock_timestamp() AS sample_after, + coalesce((SELECT max(id) FROM exomem_cloud_issuance_log), 0) AS newest \gset + SELECT greatest(:'prev_id'::bigint, coalesce(nullif(:'id_target'::bigint, 0), :newest)) AS target \gset + SELECT least(:target, :'prev_id'::bigint + :'page'::bigint) AS hi \gset + + WITH records AS MATERIALIZED ( + SELECT id, credential_kind, tenant_id, user_id, database_role, backfilled + FROM exomem_cloud_issuance_log + WHERE id > :'prev_id'::bigint AND id <= :hi + UNION ALL + SELECT id, credential_kind, tenant_id, user_id, database_role, backfilled + FROM exomem_cloud_issuance_log + WHERE NOT backfilled AND id <= :'prev_id'::bigint + AND recorded_at >= :'prior_before'::timestamptz - interval '1 hour' + AND recorded_at <= :'prior_after'::timestamptz + ) + SELECT 'other database role' AS finding, id, credential_kind, tenant_id, user_id + FROM records WHERE NOT backfilled AND database_role <> 'substrate_app' + UNION ALL + SELECT 'user differs from tenant owner', record.id, record.credential_kind, + record.tenant_id, record.user_id + FROM records AS record + JOIN exomem_tenants AS tenant ON tenant.id = record.tenant_id + WHERE record.user_id <> tenant.owner_user_id; + COMMIT; + \echo prev_id=:hi prior_before=:sample_before prior_after=:sample_after id_target=:target + ``` + +4. Investigate each returned finding. If a repeat shows the same identifier and finding, treat it as one finding. +5. Save all four values printed by the successful block. Keep `id_target` fixed until `prev_id` reaches it. + +A new sweep captures the current greatest identifier. Later writes do not +move that sweep's target. A pruned stop does not change the numeric cursor. +The recorded time comes from the transaction's start, so it can differ from +identifier order. The replay uses the prior snapshot's time window and the +index on recorded time. With transactions open for at most one hour, a +record that committed after the previous snapshot can appear in the replay +even if its identifier is already behind the stop. Backfilled records were +written in a single transaction. The new pages cover them. + +Read one tenant's records, newest first, a page at a time. Use it for an +incident, and for an owner who asks who held access. For the first page, use +the current greatest log identifier plus one as `before`. For the next +page, use the lowest identifier from the previous page. + +```sql +SELECT id, recorded_at, credential_kind, credential_id, grant_id, family_id, client_id, expires_at +FROM exomem_cloud_issuance_log +WHERE tenant_id = :'tenant_id'::uuid AND id < :'before'::bigint +ORDER BY id DESC LIMIT 50; +``` + +#### Catalog checks + +These five checks read the catalog and the grants. Run them with the range checks, and after every migration. Each one +is a finding when it returns a row. Run them as `substrate_audit`: they need no other right. + +Triggers of this change that are missing or disabled. A row with a `NULL` state is missing. A state other than `O` is +disabled. + +```sql +SELECT expected.table_name, expected.trigger_name, trigger.tgenabled AS state +FROM (VALUES + ('exomem_oauth_grants', 'exomem_oauth_grants_identity_lock'), + ('exomem_oauth_token_families', 'exomem_oauth_token_families_identity_lock'), + ('exomem_oauth_access_tokens', 'exomem_oauth_access_tokens_identity_lock'), + ('exomem_oauth_refresh_tokens', 'exomem_oauth_refresh_tokens_identity_lock'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_identity_lock'), + ('exomem_oauth_clients', 'exomem_oauth_clients_identity_lock'), + ('exomem_tenants', 'exomem_tenants_identity_lock'), + ('exomem_cloud_cells', 'exomem_cloud_cells_identity_lock'), + ('exomem_oauth_grants', 'exomem_oauth_grants_delete_lock'), + ('exomem_oauth_grants', 'exomem_oauth_grants_truncate_lock'), + ('exomem_oauth_clients', 'exomem_oauth_clients_delete_lock'), + ('exomem_oauth_clients', 'exomem_oauth_clients_truncate_lock'), + ('exomem_tenants', 'exomem_tenants_delete_lock'), + ('exomem_tenants', 'exomem_tenants_truncate_lock'), + ('exomem_users', 'exomem_users_delete_lock'), + ('exomem_users', 'exomem_users_truncate_lock'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_delete_lock'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_truncate_lock'), + ('exomem_marketplace_reviewer_credentials', 'exomem_marketplace_reviewer_credentials_delete_lock'), + ('exomem_marketplace_reviewer_credentials', 'exomem_marketplace_reviewer_credentials_truncate_lock'), + ('exomem_cloud_cells', 'exomem_cloud_cells_delete_lock'), + ('exomem_cloud_cells', 'exomem_cloud_cells_truncate_lock'), + ('exomem_cloud_cells', 'exomem_cloud_cells_service_credentials_end_update'), + ('exomem_cloud_cells', 'exomem_cloud_cells_service_credentials_end_delete'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_live_cell'), + ('schema_releases', 'schema_releases_owner_only'), + ('schema_releases', 'schema_releases_owner_only_truncate'), + ('exomem_cloud_issuance_log', 'exomem_cloud_issuance_log_owner_only'), + ('exomem_cloud_issuance_log', 'exomem_cloud_issuance_log_owner_only_truncate'), + ('exomem_cloud_download_tickets', 'exomem_cloud_download_tickets_update_lock'), + ('exomem_oauth_token_families', 'exomem_oauth_token_families_issuance_record'), + ('exomem_oauth_token_families', 'exomem_oauth_token_families_issuance_end_revoke'), + ('exomem_oauth_token_families', 'exomem_oauth_token_families_issuance_end_delete'), + ('exomem_oauth_access_tokens', 'exomem_oauth_access_tokens_issuance_record'), + ('exomem_oauth_refresh_tokens', 'exomem_oauth_refresh_tokens_issuance_record'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_issuance_record'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_issuance_end_revoke'), + ('exomem_cloud_service_credentials', 'exomem_cloud_service_credentials_issuance_end_delete'), + ('exomem_cloud_download_tickets', 'exomem_cloud_download_tickets_issuance_record') +) AS expected(table_name, trigger_name) +LEFT JOIN pg_trigger AS trigger + ON trigger.tgname = expected.trigger_name AND trigger.tgrelid = to_regclass(expected.table_name) +WHERE trigger.tgenabled IS DISTINCT FROM 'O'; +``` + +Roles other than the table's owner that hold the trigger right on a table in the schema. A role with that right can run +its own code as the schema owner, and no guard holds against it. Revoke the right with `REVOKE TRIGGER ON
FROM +`. The grants script revokes it on every run. + +```sql +SELECT class.oid::regclass AS table_name, + CASE WHEN privilege.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(privilege.grantee) END AS holder +FROM pg_class AS class +JOIN pg_namespace AS namespace ON namespace.oid = class.relnamespace AND namespace.nspname = current_schema() +CROSS JOIN LATERAL aclexplode(class.relacl) AS privilege +WHERE class.relkind IN ('r', 'p') AND privilege.privilege_type = 'TRIGGER' AND privilege.grantee <> class.relowner; +``` + +Roles that the web app's role is a member of. A membership can carry any right. The expected result is no rows. + +```sql +SELECT pg_get_userbyid(roleid) AS member_of +FROM pg_auth_members WHERE member = 'substrate_app'::regrole; +``` + +Rights of the web app's role beyond what the grants script gives it. The grants script of an earlier release gives the +role select, insert, update and delete on every table. It runs again when a build of an earlier commit applies it: the +production build that was in flight at the merge, or a redeploy of an earlier commit. A dry run of the migration job +applies no grants. Each row is a right that the role must not hold, whether it holds the right itself or through `PUBLIC` +or a membership: + +- any right on the log, at table level or on a column: select, insert, update, delete, truncate or references. The trigger right has its own check above; +- any right on the sequence that numbers the log's records; +- insert, update or delete on `schema_releases`, where the role keeps select; +- update of a ticket row, where the role keeps select, insert and delete; +- delete on a table whose rows the role never deletes; +- a table-wide update on a table that carries column rights only: grants, token families, access tokens, refresh + tokens, service credentials, clients and tenants (design D2). + +The expected result is no rows. A single column grant on a locked column is not listed, because the guard refuses the +change anyway. That includes the emergency statement 1. + +```sql +SELECT forbidden.table_name, forbidden.privilege +FROM (VALUES + ('exomem_cloud_issuance_log', 'SELECT'), ('exomem_cloud_issuance_log', 'INSERT'), + ('exomem_cloud_issuance_log', 'UPDATE'), ('exomem_cloud_issuance_log', 'DELETE'), + ('exomem_cloud_issuance_log', 'TRUNCATE'), ('exomem_cloud_issuance_log', 'REFERENCES'), + ('schema_releases', 'INSERT'), ('schema_releases', 'UPDATE'), ('schema_releases', 'DELETE'), + ('exomem_cloud_download_tickets', 'UPDATE') +) AS forbidden(table_name, privilege) +WHERE CASE + WHEN forbidden.privilege IN ('DELETE', 'TRUNCATE') + THEN has_table_privilege('substrate_app', to_regclass(forbidden.table_name), forbidden.privilege) + ELSE has_any_column_privilege('substrate_app', to_regclass(forbidden.table_name), forbidden.privilege) +END +UNION ALL +SELECT 'exomem_cloud_issuance_log_id_seq', privilege.name +FROM (VALUES ('USAGE'), ('SELECT'), ('UPDATE')) AS privilege(name) +WHERE has_sequence_privilege('substrate_app', pg_get_serial_sequence('exomem_cloud_issuance_log', 'id'), privilege.name) +UNION ALL +SELECT forbidden.table_name, forbidden.privilege +FROM (VALUES + ('exomem_oauth_grants', 'UPDATE'), ('exomem_oauth_token_families', 'UPDATE'), + ('exomem_oauth_access_tokens', 'UPDATE'), ('exomem_oauth_refresh_tokens', 'UPDATE'), + ('exomem_cloud_service_credentials', 'UPDATE'), ('exomem_oauth_clients', 'UPDATE'), + ('exomem_tenants', 'UPDATE'), + ('exomem_oauth_grants', 'DELETE'), ('exomem_oauth_clients', 'DELETE'), ('exomem_tenants', 'DELETE'), + ('exomem_users', 'DELETE'), ('exomem_cloud_service_credentials', 'DELETE'), + ('exomem_marketplace_reviewer_credentials', 'DELETE'), ('exomem_cloud_cells', 'DELETE') +) AS forbidden(table_name, privilege) +WHERE has_table_privilege('substrate_app', to_regclass(forbidden.table_name), forbidden.privilege) +ORDER BY 1, 2; +``` + +If a row appears: + +1. Open the "Actions" tab of the repository and select the workflow `migrate-database`. +2. Select "Run workflow" for `main`, clear "List the pending migrations and change nothing", and run it. +3. Wait for the green run. Its grants script takes back each right that the role holds by its own grant. +4. Run the check again. The expected result is no rows. +5. If a row remains, wait for any running build of an earlier commit to end. Then run the job and the check again. +6. If a row still remains, the right comes through `PUBLIC` or a membership. Revoke it from that holder. +7. Run the check again. The expected result is no rows. + +Create rights and schemas. A role that can create a schema can run its code as the schema owner, with no trigger right. +The first query lists each role that holds a create right on the database, or on a schema outside `pg_catalog` and `information_schema`. +It counts a right held directly or through a membership. +It leaves out a superuser, the schema owner and `pg_database_owner`. +The second lists each schema that another role owns. Revoke each right, and drop each schema that a role created. + +```sql +SELECT 'database' AS target, role.rolname AS holder +FROM pg_roles AS role +WHERE has_database_privilege(role.oid, current_database(), 'CREATE') + AND NOT role.rolsuper AND role.rolname NOT IN ('substrate_owner', 'pg_database_owner') +UNION ALL +SELECT namespace.nspname, role.rolname +FROM pg_namespace AS namespace +CROSS JOIN pg_roles AS role +WHERE namespace.nspname NOT IN ('pg_catalog', 'information_schema') + AND namespace.nspname NOT LIKE 'pg\_toast%' AND namespace.nspname NOT LIKE 'pg\_temp\_%' + AND has_schema_privilege(role.oid, namespace.oid, 'CREATE') + AND NOT role.rolsuper AND role.oid <> namespace.nspowner + AND role.rolname NOT IN ('substrate_owner', 'pg_database_owner'); + +SELECT namespace.nspname, pg_get_userbyid(namespace.nspowner) AS owner +FROM pg_namespace AS namespace +WHERE namespace.nspname NOT LIKE 'pg\_temp\_%' AND namespace.nspname NOT LIKE 'pg\_toast\_temp\_%' + AND namespace.nspowner <> 10 + AND pg_get_userbyid(namespace.nspowner) NOT IN ('substrate_owner', 'pg_database_owner'); +``` + +#### Size and retention + +Compare the log's size with the estimated record count. The count comes from +the planner and lags until the next analyse. + +```sql +SELECT pg_size_pretty(pg_total_relation_size('exomem_cloud_issuance_log')) AS size, + (SELECT reltuples::bigint FROM pg_class WHERE oid = 'exomem_cloud_issuance_log'::regclass) AS estimated_records; +``` + +Read how far the prune is behind. The count stops at 100,001, so the read stays short when the prune has failed for +long. A result of 100,001 means at least ten runs of backlog. Check the reconcile job's `issuancePruned.records`, and +the log line `exomem-issuance: log retention failed`. + +```sql +SELECT count(*) AS past_retention +FROM (SELECT 1 FROM exomem_cloud_issuance_log + WHERE expires_at < now() - interval '2160 hours' LIMIT 100001) AS stale; +``` + +A log that holds twice the size that the count of live credentials predicts needs a look at the prune first. The +retention period is a constant inside the function, so a change needs a migration. + +### Download ticket rows + +A download ticket is a signed message that names a token family, a grant, a path digest and an expiry. The web app stores one row in `exomem_cloud_download_tickets` before it redirects to the ticket's address. +The insert uses `ON CONFLICT DO NOTHING` on the key `(family_id, path_sha256, expires_at)`. Two tickets with the same three values share one row and +one record. The gateway serves a ticket only when that row exists and has not expired. The gateway checks it inside the +statement that finds the ticket's login, so a download makes no extra database round trip. + +- A ticket that has no row, or whose path, token family or expiry differs from the row, gets `401 DOWNLOAD_TICKET_INVALID` + from the gateway. The owner asks for the download again. +- The web app's role may select, insert and delete ticket rows. The gateway's role reads `family_id`, `path_sha256` and + `expires_at`. No role can update a row. +- A ticket authorises a download for at most one day. Expired rows stay in the table until cleanup. +- The reconcile job deletes up to 1000 expired rows a run through the index on `expires_at`. +- The row table has no foreign key and holds no grant. The recording trigger reads the grant, the tenant and the user + through the token family. An insert for a family that does not exist fails, because the recording fails closed. A role + that can insert a row can name another tenant's family, and the gateway then admits the ticket. The issuance log + records that insert, like every credential. + +#### Deploy and rollback order + +A ticket signed by a web release that stores no row is refused by a gateway that requires one. The two releases +therefore move in a fixed order. + +1. Merge the change. The migration job creates the ticket table. The web release then stores a row for each ticket. +2. Wait at least one day. That is the longest lifetime of a ticket, so every ticket in use has its row. +3. Roll the gateway release that requires ticket rows. The expected result is that downloads keep working. + +To roll back, reverse the order: + +1. Roll the gateway back to its previous image first. That image ignores ticket rows. +2. Roll the web app back past this change only after the gateway has rolled back. + +A gateway that requires rows and a web release from before this change refuse every download until one of them moves. + ## External scheduler Vercel Hobby rejects cron expressions that run more than once per day, so the diff --git a/docs/runbooks/exomem-cloud-service-credentials.md b/docs/runbooks/exomem-cloud-service-credentials.md index ea088dc8..fe7870de 100644 --- a/docs/runbooks/exomem-cloud-service-credentials.md +++ b/docs/runbooks/exomem-cloud-service-credentials.md @@ -44,7 +44,10 @@ tenant is `deletion_pending` or `deleted`, its owner has an account block, it has no non-deleted cell, or it is a marketplace-reviewer tenant — reviewer credentials carry their own expiry contract a long-lived secret would sidestep. A 409 `SERVICE_CREDENTIAL_LIMIT` means the tenant and principal -already hold two live credentials; revoke one before issuing another. +already hold two live credentials; revoke one before issuing another. A 503 +`SERVICE_CREDENTIAL_RETRY` with a `Retry-After` header means the database failed +the request to break a lock cycle with a lifecycle sweep of the same tenant. +Nothing was stored, so send the request again after the header's seconds. The 201 response is the only place the secret ever appears: `secret`, `credentialId`, `tenantId`, `principal`, `cellId`, `cloudMcpUrl`. It is sent diff --git a/docs/runbooks/production-keys-and-storage.md b/docs/runbooks/production-keys-and-storage.md index c3660344..ba03d7c8 100644 --- a/docs/runbooks/production-keys-and-storage.md +++ b/docs/runbooks/production-keys-and-storage.md @@ -172,23 +172,56 @@ Each of these has bitten us in production at least once during hosted-backup rol **4. Asymmetric handling between paired endpoints.** When two endpoints implement opposite halves of the same protocol contract (upload mints URL → download fetches URL; encrypt → decrypt; write → read), an invariant on one side has to be honored on the other. Drift is invisible in unit tests that exercise each half in isolation. The hosted-backup contract uses `chunkIndex = -1` as the sentinel for the manifest blob in **both** the upload-URL response (`POST /api/backups/:id/versions`) and the download-URL request (`POST /api/backups/:id/versions/:vid/download-urls`); the upload side was correct from PR #2, but the download side validated all requested indices against the chunks table — where `-1` is by definition absent — and threw `NOT_FOUND` before ever reaching the manifest case. **When you find a sentinel value or magic-number convention in code, grep the codebase for every other place that value could appear and verify the symmetry.** Add an end-to-end test that round-trips through both endpoints with the sentinel. *(First seen: PR #7, `POST .../download-urls` with `chunkIndices: [-1]` returned `NOT_FOUND`, blocking the engine smoke test's pull half on a real prod backup `9e6f8cc9-…`/`910f3c00-…`. Push had worked because that path mints the manifest URL itself; download couldn't fetch what push had written.)* -**5. Migrations auto-run on Vercel *production* deploys via `vercel-build`** (since 2026-05-27). `package.json`'s `vercel-build` script chains `scripts/vercel-maybe-migrate.ts` before `next build`. The migrate step checks `VERCEL_ENV` and only runs against the production database when `VERCEL_ENV === 'production'` — preview and development builds skip it. A failing migration aborts the build and the previous deploy stays live. +**5. A protected GitHub job applies the migrations. The Vercel build never does.** The workflow `.github/workflows/migrate-database.yml` runs the job `migrate`. It starts on every push to `main` and by hand. It runs in the protected environment `production-schema`, whose branch rule accepts only `main`. That environment holds the schema-owner connection string as the secret `DATABASE_MIGRATION_URL`. No Vercel environment holds it. -**Implications:** +Whatever commit started a run, the job checks out the tip of `main` as it stands when the run starts, then does three things in order: -- **Adding a migration: just merge.** When you add `migrations/00XX_*.sql` and a PR that depends on the schema in the same merge, the Vercel deploy of `main` applies the migration before serving traffic. No manual step needed for the happy path. -- **Manual override:** set `SKIP_VERCEL_MIGRATE=1` in Vercel project env to disable temporarily (e.g. during incident response where a migration is hot-failing and you need the previous code path back up faster than a revert). Unset it once recovered. -- **Manual application is still possible** for one-off backfills or pre-merge dry-runs: +1. It applies the pending migrations, then `scripts/exomem-cloud-grants.sql`. +2. It records a schema release for the tip in `schema_releases`, with status `released`. +3. It records each earlier commit of the tip's history that has no row as `superseded`. - ```bash - vercel env pull .env.production.local --environment=production - npx tsx --env-file=.env.production.local scripts/migrate.ts --dry # confirm pending - npx tsx --env-file=.env.production.local scripts/migrate.ts # apply - rm .env.production.local # wipe local credentials - ``` +Just before step 1, the job reads the tip once more. When `main` moved during the install, it applies nothing, and the run that the new push started applies the new tip. The concurrency group lets one run proceed at a time and never cancels a running one. It keeps only the newest waiting run, so a restart of an old run can replace the waiting run of a newer push. That run releases the newer tip. -- **Preview deploys** still skip migrations entirely. If you need to test a migration's effect on a preview env, point that preview's `DATABASE_URL` at a separate, disposable database and apply via the manual `tsx --env-file=...` form above. +**The build.** `package.json`'s `vercel-build` script runs `scripts/wait-for-schema-release.ts` before `next build`. A production build reads the row for its own commit through the web app's database role: + +- `released`: the build continues. When a newer release exists, the log says so. +- `superseded`: the build fails at once. A newer commit carries the schema release. +- No row, no table, or a refused select: the build polls every 10 seconds for up to 15 minutes, then fails. The merge commit's build starts before the job has created the table. + +A production build that carries no commit identifier fails. A failed build leaves the previous deployment serving. Preview and development builds neither migrate nor wait. + +**A job that fails.** Each migration runs in one transaction with a lock timeout of five seconds. A migration that meets its lock timeout, or a deadlock with a flow that writes in another order, fails the job and records no release. Nothing stays half applied, and the build fails after its wait. + +1. Open the failed run in the repository's "Actions" tab. +2. Select "Re-run failed jobs". The job takes the tip of `main` again, whatever commit the failed run was for. +3. Wait for the job to end. The expected result is a green run and a `released` row for the tip of `main`. +4. If the merge commit's production build already failed, open it in Vercel and select "Redeploy". The expected result is a build that reads the `released` row and deploys. + +Step 4 is needed because nothing rebuilds a build that failed after its 15-minute wait. + +If the job fails twice at the same migration, read its log for the lock that timed out. +Find the long transaction that holds that lock before you start the job again. + +**A manual run.** Use it when the runner cannot reach the database or GitHub Actions is down. It needs your own copy of the schema-owner connection string from your secret store, and the full hash of the commit to apply. + +1. Check out the tip of `main` in a clean working tree: `git fetch origin main && git checkout --detach origin/main`. +2. Read the hash of that commit: `git rev-parse HEAD`. Use the full 40 characters below. +3. Install the dependencies without install scripts: `npm ci --ignore-scripts`. +4. Hold the connection string in this shell only: `read -rs DATABASE_MIGRATION_URL && export DATABASE_MIGRATION_URL`. Paste it, then press Enter. +5. List the pending migrations: `npx tsx scripts/migrate.ts --dry`. The expected result is the list, and `[migrate] --dry: not applying`. +6. Print the superseded commits: `scripts/schema-release-plan.sh`. The expected result is `apply=true`, `tip=` with the hash from step 2, and a `superseded=` list. +7. Apply and record: `npx tsx scripts/migrate.ts --commit --superseded `. The expected result is `[migrate] applying grants ... ok`, then `[migrate] recorded release ` and the count of superseded commits. +8. Clear the credential: `unset DATABASE_MIGRATION_URL`. + +Never write the connection string to a file, a Vercel variable or a shell history line. The build of a waiting merge commit continues within 10 seconds of step 7. + +**An incident that needs a build now.** Set `SKIP_SCHEMA_RELEASE_WAIT=1` in the Vercel Production environment to ship one build without the wait. The log of that build says that it skipped the check. The build then runs against whatever schema exists, so use it only when you know that the schema is compatible. Unset the variable once the incident ends. + +**Promotion, rollback and uploaded deployments** run no build, so none of them checks the schema release. `vercel-deployments.md` says what to check by hand. + +**Preview deploys.** To test a migration on a preview, point that preview's `DATABASE_URL` at a separate, disposable database. Apply the migrations with `scripts/migrate.ts` and that database's own connection string. Never point a preview at a database that holds production data. *(First seen: v2.0.0 cutover, migration `0011_recovery_tokens_used.sql` was caught pre-merge by manual review during the substrate→engine handoff. Repeated 2026-05-27 with `0015_account_sessions.sql` — engine v2.4.0 and gui-v2.7.0 / v2.8.0 all shipped before the migration was applied, and the new `/account/start` route 500'd at production until the manual migration ran. That incident motivated wiring the auto-migration into `vercel-build`.)* +*(The protected migration job replaces that auto-migration. It still applies migrations on every merge, and it takes the schema-owner credential out of the build.)* ### Verify the bypass is wired (substrate-side, no engine needed) diff --git a/docs/runbooks/vercel-deployments.md b/docs/runbooks/vercel-deployments.md index 3c171640..889c1972 100644 --- a/docs/runbooks/vercel-deployments.md +++ b/docs/runbooks/vercel-deployments.md @@ -15,4 +15,38 @@ delete existing deployments or reduce retained storage by itself. Inventory old deployments separately, preserve production/current aliases and rollback targets, and remove only confirmed unused previews. +## Production builds and the schema release + +A production build never migrates the database. The protected job `migrate` applies the migrations and the grants script for the tip of `main`, then records a schema release for that commit. The build script `scripts/wait-for-schema-release.ts` reads the row for the build's commit and continues only on `released`. `production-keys-and-storage.md` describes the job, the wait and the manual run. + +The check runs in every production build that the platform makes from source: a push, a redeploy and a deploy hook. It does not run in these cases, because none of them runs the build script: + +- **Promotion** of an existing deployment to production. +- **Instant rollback** to an earlier deployment. +- **A deployment that was built elsewhere and uploaded** with the Vercel CLI. + +Each of the three serves code without a check of the schema. The schema may be older or newer than that code. A deployment whose migrations have not run can fail on a table or column that does not exist. Before you promote, roll back, or upload a deployment, follow these steps: + +1. Read the commit hash of the deployment that you plan to serve. +2. As the schema owner, run the query below. It returns the row of that commit and the newest `released` row. + + ```sql + SELECT 'candidate' AS which, commit_sha, status FROM schema_releases WHERE commit_sha = '' + UNION ALL + (SELECT 'newest', commit_sha, status FROM schema_releases WHERE status = 'released' ORDER BY recorded_at DESC LIMIT 1); + ``` + +3. In a checkout of the repository, run `git merge-base --is-ancestor ` and note its exit status. +4. If the exit status is not 0 and the row of the commit is not `released`, do not serve the deployment. Its migrations may not have run. +5. In that case, run the `migrate-database` workflow for `main` and wait for the green run. Then repeat from step 2. +6. If the exit status is 0 and the commit is not the newest `released` commit, run `git log --oneline ..`. +7. Serve the deployment only when no listed commit adds a migration that breaks the older code. +8. In every other case, serve the deployment. + +The expected result is a decision that you can name: the schema is at least as new as the code and no later migration breaks it, or you run the migration job first. + +When migration 0102 is in force and the previous web release is serving, pause service credential issuance. This applies during the first rollout and after an instant rollback. The previous release can return HTTP 500 when the new guard refuses a request. Resume issuance when the new release serves. + +To ship one production build while the job cannot run, set `SKIP_SCHEMA_RELEASE_WAIT=1` in the Production environment, and unset it afterwards. + Reference: [Vercel Git configuration](https://vercel.com/docs/project-configuration/git-configuration). diff --git a/migrations/0101_exomem_identity_lock_and_schema_releases.sql b/migrations/0101_exomem_identity_lock_and_schema_releases.sql new file mode 100644 index 00000000..1be500ff --- /dev/null +++ b/migrations/0101_exomem_identity_lock_and_schema_releases.sql @@ -0,0 +1,299 @@ +-- Schema releases and the identity lock (lock-cloud-identity-rows-and-record-issuance, +-- D2, D5, D9). This migration changes only the catalog: it adds one table and +-- the guard triggers, and pins the search path of the functions that run as the +-- schema owner for another role. + +-- A write to any table below waits behind this transaction until it commits. +-- The timeout bounds each wait, not the migration: when a lock stays busy, +-- the migration fails, the job fails, and the operator starts the job again. +-- One statement takes every lock in the order that admission and revocation +-- already write these tables (users, tenants, then grants, token families, +-- tokens); cell deletion writes them in another order, so a deadlock can fail +-- the migration the same way. SHARE ROW EXCLUSIVE is the mode that CREATE +-- TRIGGER takes. +SET LOCAL lock_timeout = '5s'; + +LOCK TABLE + exomem_users, + exomem_tenants, + exomem_cloud_cells, + exomem_marketplace_reviewer_credentials, + exomem_oauth_clients, + exomem_oauth_grants, + exomem_oauth_token_families, + exomem_oauth_refresh_tokens, + exomem_oauth_access_tokens, + exomem_cloud_service_credentials + IN SHARE ROW EXCLUSIVE MODE; + +-- Pin the search path of every function that the database can run as the +-- schema owner for another role (design D2, "The create right"). A role that +-- can create a schema defines an operator there and puts that schema first on +-- its own path, and a trigger function that names an operator without a schema +-- then runs the role's operator as the schema owner. The set is read from the +-- catalog: the schema owner's trigger functions and SECURITY DEFINER functions +-- in this schema, and each SQL or PL/pgSQL function that a constraint, a column +-- default or an index calls. A function that belongs to an extension, and a C or +-- internal function, is out of the set: the first is not the schema owner's to +-- alter, and the second looks up no names. A function that one of them calls +-- runs under its caller's path. +-- +-- The health proof qualifies every name with its schema, so it gets only +-- pg_catalog and pg_temp. Every other function names schema objects without a +-- schema, so it gets pg_catalog, then every schema of this migration's own path, +-- then pg_temp. A schema that another role owns must never enter a pin: that role +-- could define an operator there. The schema owner, the bootstrap superuser +-- (always role 10) and pg_database_owner are the trusted owners. When the path +-- holds a schema that any other role owns, the migration raises an error that +-- names each such schema and its owner, and the transaction rolls back, so the +-- old schema keeps serving. The operator pays one failed migration job, until +-- the schema's owner is fixed or the schema leaves the migration role's path. +DO $migration$ +DECLARE + target_schema text := current_schema(); + schema_owner oid := (SELECT oid FROM pg_roles WHERE rolname = current_user); + trusted_owners oid[] := ARRAY[ + schema_owner, 10::oid, (SELECT oid FROM pg_roles WHERE rolname = 'pg_database_owner') + ]; + path_schemas text; + untrusted_schemas text; + routine record; +BEGIN + SELECT string_agg(quote_ident(path.name), ', ' ORDER BY path.position), + string_agg( + quote_ident(path.name) || ' (owned by ' || quote_ident(pg_get_userbyid(namespace.nspowner)) || ')', + ', ' ORDER BY path.position + ) FILTER (WHERE namespace.nspowner <> ALL (trusted_owners)) + INTO path_schemas, untrusted_schemas + FROM unnest(current_schemas(false)) WITH ORDINALITY AS path(name, position) + JOIN pg_namespace AS namespace ON namespace.nspname = path.name; + IF untrusted_schemas IS NOT NULL THEN + RAISE EXCEPTION 'The migration path holds schemas that another role owns: %. Change the owner of each schema, or take it off the path of the migration role, and run the migration again.', + untrusted_schemas; + END IF; + + FOR routine IN + SELECT proc.proname, pg_get_function_identity_arguments(proc.oid) AS arguments + FROM pg_proc AS proc + JOIN pg_language AS language ON language.oid = proc.prolang + WHERE proc.pronamespace = target_schema::regnamespace + AND proc.proowner = schema_owner + AND language.lanname NOT IN ('c', 'internal') + AND NOT EXISTS ( + SELECT 1 FROM pg_depend AS membership + WHERE membership.classid = 'pg_proc'::regclass AND membership.objid = proc.oid + AND membership.deptype = 'e' + ) + AND ( + proc.prorettype = 'trigger'::regtype + OR proc.prosecdef + OR EXISTS ( + SELECT 1 FROM pg_depend AS caller + LEFT JOIN pg_class AS caller_index + ON caller.classid = 'pg_class'::regclass AND caller_index.oid = caller.objid + WHERE caller.refclassid = 'pg_proc'::regclass AND caller.refobjid = proc.oid + AND ( + caller.classid IN ('pg_constraint'::regclass, 'pg_attrdef'::regclass) + OR caller_index.relkind IN ('i', 'I') + ) + ) + ) + LOOP + EXECUTE format( + 'ALTER FUNCTION %I.%I(%s) SET search_path = %s', + target_schema, routine.proname, routine.arguments, + CASE + WHEN routine.proname = 'exomem_record_memory_health_proof' THEN 'pg_catalog, pg_temp' + ELSE 'pg_catalog, ' || coalesce(path_schemas || ', ', '') || 'pg_temp' + END + ); + END LOOP; +END; +$migration$; + +-- The guard. Every trigger of this lock calls it. It refuses the statement +-- unless the role that runs it owns the table. It is not SECURITY DEFINER, +-- because it must see who the caller is. The pinned path keeps a temporary +-- table from taking the place of pg_class, and the body names nothing else. +CREATE FUNCTION exomem_refuse_unless_schema_owner() RETURNS trigger +LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp +AS $body$ +BEGIN + IF current_user IS DISTINCT FROM ( + SELECT pg_catalog.pg_get_userbyid(relowner) FROM pg_catalog.pg_class WHERE oid = TG_RELID + ) THEN + RAISE EXCEPTION 'EXOMEM_ROW_LOCKED: % on % is refused', TG_OP, TG_TABLE_NAME + USING ERRCODE = '42501'; + END IF; + RETURN NULL; +END; +$body$; + +REVOKE ALL ON FUNCTION exomem_refuse_unless_schema_owner() FROM PUBLIC; + +-- One row for each commit whose schema the release job applied or overtook. +-- The job inserts a row once and never updates it. +CREATE TABLE schema_releases ( + commit_sha text PRIMARY KEY CHECK (commit_sha ~ '^[0-9a-f]{40}$'), + -- A closed set that the release pipeline fixes, not data. + status text NOT NULL CHECK (status IN ('released', 'superseded')), + -- When the row was written: the release time of a released commit. + recorded_at timestamptz NOT NULL DEFAULT now() +); + +-- The build's wait script reads the newest released commit on every poll, so +-- the read walks this index and scans no rows. +CREATE INDEX schema_releases_newest_released_idx + ON schema_releases (recorded_at DESC) WHERE status = 'released'; + +CREATE TRIGGER schema_releases_owner_only + AFTER INSERT OR UPDATE OR DELETE ON schema_releases + FOR EACH ROW EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); +CREATE TRIGGER schema_releases_owner_only_truncate + BEFORE TRUNCATE ON schema_releases + FOR EACH STATEMENT EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +-- Default privileges would give the web app's role every right on the new +-- table. Take back each right that any other role holds on it, in the +-- transaction that creates it. The grants script then gives select back. +DO $migration$ +DECLARE + holder record; +BEGIN + FOR holder IN + SELECT DISTINCT acl.grantee + FROM pg_class AS relation, aclexplode(relation.relacl) AS acl + WHERE relation.oid = to_regclass('schema_releases') AND acl.grantee <> relation.relowner + LOOP + EXECUTE format( + 'REVOKE ALL ON schema_releases FROM %s', + CASE WHEN holder.grantee = 0 THEN 'PUBLIC' ELSE quote_ident(pg_get_userbyid(holder.grantee)) END + ); + END LOOP; +END; +$migration$; + +-- The lock (design D2). Each guard is an AFTER row trigger, so it judges the +-- stored row and the role that ran the statement, whatever a BEFORE trigger did +-- and whichever role a foreign-key action ran as. A WHEN clause on an update +-- guard lists the columns that must not change; no function runs for an update +-- that leaves them alone, such as the Home mint's upsert that changes only +-- updated_at. The grants script gives the web app's role update on the +-- complement of each list. A test asserts that every column of a column-locked +-- table is in exactly one of the two lists, so a new column forces a decision. +-- A one-way column is refused once it holds a value: it changes only from empty. + +CREATE TRIGGER exomem_oauth_grants_identity_lock + AFTER UPDATE ON exomem_oauth_grants + FOR EACH ROW WHEN ( + OLD.id IS DISTINCT FROM NEW.id OR OLD.user_id IS DISTINCT FROM NEW.user_id + OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id OR OLD.client_id IS DISTINCT FROM NEW.client_id + OR OLD.resource IS DISTINCT FROM NEW.resource OR OLD.created_at IS DISTINCT FROM NEW.created_at + OR OLD.reviewer_credential_id IS DISTINCT FROM NEW.reviewer_credential_id + OR OLD.candidate_id IS DISTINCT FROM NEW.candidate_id + OR OLD.assignment_id IS DISTINCT FROM NEW.assignment_id + OR OLD.assignment_generation IS DISTINCT FROM NEW.assignment_generation + OR OLD.staged_client_release_id IS DISTINCT FROM NEW.staged_client_release_id + OR (OLD.revoked_at IS NOT NULL AND NEW.revoked_at IS DISTINCT FROM OLD.revoked_at) + ) EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +CREATE TRIGGER exomem_oauth_token_families_identity_lock + AFTER UPDATE ON exomem_oauth_token_families + FOR EACH ROW WHEN ( + OLD.id IS DISTINCT FROM NEW.id OR OLD.grant_id IS DISTINCT FROM NEW.grant_id + OR OLD.client_id IS DISTINCT FROM NEW.client_id OR OLD.expires_at IS DISTINCT FROM NEW.expires_at + OR OLD.created_at IS DISTINCT FROM NEW.created_at + OR OLD.candidate_id IS DISTINCT FROM NEW.candidate_id + OR OLD.assignment_id IS DISTINCT FROM NEW.assignment_id + OR OLD.assignment_generation IS DISTINCT FROM NEW.assignment_generation + OR OLD.staged_client_release_id IS DISTINCT FROM NEW.staged_client_release_id + OR OLD.reviewer_credential_id IS DISTINCT FROM NEW.reviewer_credential_id + OR (OLD.revoked_at IS NOT NULL AND NEW.revoked_at IS DISTINCT FROM OLD.revoked_at) + ) EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +CREATE TRIGGER exomem_oauth_access_tokens_identity_lock + AFTER UPDATE ON exomem_oauth_access_tokens + FOR EACH ROW WHEN ( + OLD.id IS DISTINCT FROM NEW.id OR OLD.access_digest IS DISTINCT FROM NEW.access_digest + OR OLD.grant_id IS DISTINCT FROM NEW.grant_id OR OLD.family_id IS DISTINCT FROM NEW.family_id + OR OLD.client_id IS DISTINCT FROM NEW.client_id OR OLD.resource IS DISTINCT FROM NEW.resource + OR OLD.scopes IS DISTINCT FROM NEW.scopes OR OLD.expires_at IS DISTINCT FROM NEW.expires_at + OR OLD.created_at IS DISTINCT FROM NEW.created_at + OR OLD.candidate_id IS DISTINCT FROM NEW.candidate_id + OR OLD.assignment_id IS DISTINCT FROM NEW.assignment_id + OR OLD.assignment_generation IS DISTINCT FROM NEW.assignment_generation + OR OLD.staged_client_release_id IS DISTINCT FROM NEW.staged_client_release_id + OR OLD.reviewer_credential_id IS DISTINCT FROM NEW.reviewer_credential_id + OR (OLD.revoked_at IS NOT NULL AND NEW.revoked_at IS DISTINCT FROM OLD.revoked_at) + ) EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +CREATE TRIGGER exomem_oauth_refresh_tokens_identity_lock + AFTER UPDATE ON exomem_oauth_refresh_tokens + FOR EACH ROW WHEN ( + OLD.id IS DISTINCT FROM NEW.id OR OLD.refresh_digest IS DISTINCT FROM NEW.refresh_digest + OR OLD.family_id IS DISTINCT FROM NEW.family_id + OR OLD.parent_refresh_token_id IS DISTINCT FROM NEW.parent_refresh_token_id + OR OLD.expires_at IS DISTINCT FROM NEW.expires_at OR OLD.created_at IS DISTINCT FROM NEW.created_at + OR OLD.candidate_id IS DISTINCT FROM NEW.candidate_id + OR OLD.assignment_id IS DISTINCT FROM NEW.assignment_id + OR OLD.assignment_generation IS DISTINCT FROM NEW.assignment_generation + OR OLD.staged_client_release_id IS DISTINCT FROM NEW.staged_client_release_id + OR OLD.oauth_client_id IS DISTINCT FROM NEW.oauth_client_id + OR OLD.reviewer_credential_id IS DISTINCT FROM NEW.reviewer_credential_id + OR (OLD.consumed_at IS NOT NULL AND NEW.consumed_at IS DISTINCT FROM OLD.consumed_at) + ) EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +CREATE TRIGGER exomem_cloud_service_credentials_identity_lock + AFTER UPDATE ON exomem_cloud_service_credentials + FOR EACH ROW WHEN ( + OLD.id IS DISTINCT FROM NEW.id OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id + OR OLD.principal IS DISTINCT FROM NEW.principal + OR OLD.secret_digest IS DISTINCT FROM NEW.secret_digest + OR OLD.created_by_principal_digest IS DISTINCT FROM NEW.created_by_principal_digest + OR OLD.created_at IS DISTINCT FROM NEW.created_at + OR (OLD.revoked_at IS NOT NULL AND NEW.revoked_at IS DISTINCT FROM OLD.revoked_at) + OR (OLD.revoked_by_principal_digest IS NOT NULL + AND NEW.revoked_by_principal_digest IS DISTINCT FROM OLD.revoked_by_principal_digest) + ) EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +-- Clients, tenants and cells stay updatable except for the one identity column or two. +CREATE TRIGGER exomem_oauth_clients_identity_lock + AFTER UPDATE ON exomem_oauth_clients + FOR EACH ROW WHEN (OLD.id IS DISTINCT FROM NEW.id OR OLD.client_id IS DISTINCT FROM NEW.client_id) + EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +CREATE TRIGGER exomem_tenants_identity_lock + AFTER UPDATE ON exomem_tenants + FOR EACH ROW WHEN (OLD.owner_user_id IS DISTINCT FROM NEW.owner_user_id) + EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +-- The gateway reaches a cell through cell.tenant_id, so a cell row that moves to another +-- tenant sends that tenant's traffic to this cell. cell_id names the cell that cellctl runs. +CREATE TRIGGER exomem_cloud_cells_identity_lock + AFTER UPDATE ON exomem_cloud_cells + FOR EACH ROW WHEN (OLD.cell_id IS DISTINCT FROM NEW.cell_id OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id) + EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +-- No code deletes a grant, client, tenant, user, service credential, reviewer +-- credential or cell row: a cell ends as desired_state 'deleted', and no role +-- holds delete on cells. A truncate that cascades from another table fires the same guard. +DO $migration$ +DECLARE + locked_table text; +BEGIN + FOREACH locked_table IN ARRAY ARRAY[ + 'exomem_oauth_grants', 'exomem_oauth_clients', 'exomem_tenants', 'exomem_users', + 'exomem_cloud_service_credentials', 'exomem_marketplace_reviewer_credentials', + 'exomem_cloud_cells' + ] LOOP + EXECUTE format( + 'CREATE TRIGGER %I AFTER DELETE ON %I FOR EACH ROW EXECUTE FUNCTION exomem_refuse_unless_schema_owner()', + locked_table || '_delete_lock', locked_table + ); + EXECUTE format( + 'CREATE TRIGGER %I BEFORE TRUNCATE ON %I FOR EACH STATEMENT EXECUTE FUNCTION exomem_refuse_unless_schema_owner()', + locked_table || '_truncate_lock', locked_table + ); + END LOOP; +END; +$migration$; diff --git a/migrations/0102_exomem_issuance_log_and_download_tickets.sql b/migrations/0102_exomem_issuance_log_and_download_tickets.sql new file mode 100644 index 00000000..ee68f05a --- /dev/null +++ b/migrations/0102_exomem_issuance_log_and_download_tickets.sql @@ -0,0 +1,457 @@ +-- The issuance log and the download ticket rows (lock-cloud-identity-rows-and-record-issuance, +-- D5, D6, D8). Every credential insert writes one log record in its own +-- transaction, and a record that cannot be written fails the insert. + +-- A write to a table below waits behind this transaction until it commits, +-- which is after the records for the existing rows are written. The timeout +-- bounds each wait, not the migration: when a lock stays busy, the migration +-- fails, the job fails, and the operator starts the job again. One statement +-- takes the locks in the order that the flows already write these tables: a +-- cell, then token families, then tokens. SHARE ROW EXCLUSIVE is the mode that +-- CREATE TRIGGER takes. The download ticket table is created below, so no other +-- session can see it before the commit and it needs no lock. +SET LOCAL lock_timeout = '5s'; + +LOCK TABLE + exomem_cloud_cells, + exomem_oauth_token_families, + exomem_oauth_refresh_tokens, + exomem_oauth_access_tokens, + exomem_cloud_service_credentials + IN SHARE ROW EXCLUSIVE MODE; + +-- One record for each credential insert. Identifiers only: no token, digest, +-- secret, principal, path or address. No foreign keys, so a record outlives its +-- credential row and the insert stays cheap. +CREATE TABLE exomem_cloud_issuance_log ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + -- The database clock when the record was written. A backfilled record holds + -- the migration's time, not the issuance time. + recorded_at timestamptz NOT NULL DEFAULT now(), + -- One kind for each table that has a recording trigger: a closed set that this + -- schema fixes, not data. + credential_kind text NOT NULL CHECK (credential_kind IN ( + 'access_token', 'refresh_token', 'token_family', 'service_credential', 'download_ticket' + )), + credential_id uuid NOT NULL, + grant_id uuid, + family_id uuid, + client_id uuid, + tenant_id uuid NOT NULL, + user_id uuid NOT NULL, + -- When the credential stops being usable, so the prune keeps the record until + -- 90 days after. A token family, an access token, a refresh token and a download + -- ticket take their expiry. A token family that is revoked or deleted before it + -- expires moves to the database clock's time. A service credential has no + -- expiry: its record takes the time the credential ends, by the database clock, + -- when it is revoked or its row is deleted. Empty while that credential is + -- live, and the prune never deletes an empty one. + expires_at timestamptz, + -- The role that connected (session_user), not the owner that the recording + -- function runs as. + database_role text NOT NULL, + backfilled boolean NOT NULL DEFAULT false +); + +-- The prune reads by expiry, and one tenant's records list newest first. +CREATE INDEX exomem_cloud_issuance_log_expires_idx ON exomem_cloud_issuance_log (expires_at); +CREATE INDEX exomem_cloud_issuance_log_tenant_idx ON exomem_cloud_issuance_log (tenant_id, id); +-- Credential checks and service credential or family end events use the same +-- lookup. The time index lets a later audit find recent commits below a saved ID. +CREATE INDEX exomem_cloud_issuance_log_credential_idx + ON exomem_cloud_issuance_log (credential_kind, credential_id, recorded_at); +CREATE INDEX exomem_cloud_issuance_log_replay_idx + ON exomem_cloud_issuance_log (recorded_at, id) WHERE NOT backfilled; + +-- The log refuses every writer that is not the schema owner, whatever rights +-- the writer holds. The recording and prune functions run as the schema owner. +CREATE TRIGGER exomem_cloud_issuance_log_owner_only + AFTER INSERT OR UPDATE OR DELETE ON exomem_cloud_issuance_log + FOR EACH ROW EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); +CREATE TRIGGER exomem_cloud_issuance_log_owner_only_truncate + BEFORE TRUNCATE ON exomem_cloud_issuance_log + FOR EACH STATEMENT EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +-- A download ticket is a signed message, and no row backed it. The web app now +-- stores one row for each ticket, and the gateway requires it. Cleanup deletes +-- expired rows. The gateway joins the token family when it uses the ticket. +-- The recording function reads the grant, tenant and user through the family. +-- Those lookups need only the family ID, so the row needs no foreign key or grant. +CREATE TABLE exomem_cloud_download_tickets ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + family_id uuid NOT NULL, + -- The ticket's claim: a SHA-256 of the path, in lower-case hexadecimal. + path_sha256 text NOT NULL CHECK (path_sha256 ~ '^[0-9a-f]{64}$'), + expires_at timestamptz NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + -- Two tickets with these three values carry the same authority and share one row. + UNIQUE (family_id, path_sha256, expires_at) +); +CREATE INDEX exomem_cloud_download_tickets_expiry_idx ON exomem_cloud_download_tickets (expires_at); + +-- A ticket row never changes, so every update is refused unless the schema owner runs it. +CREATE TRIGGER exomem_cloud_download_tickets_update_lock + AFTER UPDATE ON exomem_cloud_download_tickets + FOR EACH ROW EXECUTE FUNCTION exomem_refuse_unless_schema_owner(); + +-- Default privileges would give the web app's role every right on the two new +-- tables. Take back each right that any other role holds on them, in the +-- transaction that creates them. The grants script then gives back what each +-- role needs. +DO $migration$ +DECLARE + new_table text; + holder record; +BEGIN + FOREACH new_table IN ARRAY ARRAY['exomem_cloud_issuance_log', 'exomem_cloud_download_tickets'] LOOP + FOR holder IN + SELECT DISTINCT acl.grantee + FROM pg_class AS relation, aclexplode(relation.relacl) AS acl + WHERE relation.oid = to_regclass(new_table) AND acl.grantee <> relation.relowner + LOOP + EXECUTE format( + 'REVOKE ALL ON %I FROM %s', + new_table, + CASE WHEN holder.grantee = 0 THEN 'PUBLIC' ELSE quote_ident(pg_get_userbyid(holder.grantee)) END + ); + END LOOP; + END LOOP; +END; +$migration$; + +-- The recording function and the prune function run as the schema owner, +-- because they write a table on which their callers hold nothing. Each pins +-- `search_path = pg_catalog, pg_temp` and names every object with its schema, +-- and the migration creates each through current_schema(), so a temporary +-- table cannot take the place of the grant table or the log. +DO $migration$ +DECLARE + target_schema text := current_schema(); +BEGIN + -- TG_ARGV[0] is the credential kind. The function reads only what the row does + -- not name: a refresh token's or a download ticket's grant through its token + -- family, a tenant and a user through the grant, a service credential's owner + -- through its tenant. Any missing row raises, so the credential insert fails closed. + EXECUTE format($definition$ + CREATE FUNCTION %1$I.exomem_record_issuance() RETURNS trigger + LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp + AS $body$ + DECLARE + kind text := TG_ARGV[0]; + the_grant uuid; + the_family uuid; + the_client uuid; + the_tenant uuid; + the_user uuid; + the_expiry timestamptz; + BEGIN + -- The end of a credential: the revocation or the delete of its row. The record + -- takes the database clock's statement time, not the row's revoked_at, which the + -- web app's role writes and could set in the past to bring the prune forward. + -- The statement time, not now(), so that retention runs from the revoking or + -- deleting statement and not from the start of a long transaction. A revocation + -- is one-way, so it cannot end a live credential's record early. A record keeps + -- an end that is already in the past. + IF TG_OP <> 'INSERT' THEN + IF kind = 'service_credential' THEN + UPDATE %1$I.exomem_cloud_issuance_log AS record + SET expires_at = pg_catalog.statement_timestamp() + WHERE record.credential_kind = 'service_credential' + AND record.credential_id = OLD.id AND record.expires_at IS NULL; + ELSIF kind = 'token_family' THEN + UPDATE %1$I.exomem_cloud_issuance_log AS record + SET expires_at = pg_catalog.statement_timestamp() + WHERE record.credential_kind = 'token_family' + AND record.credential_id = OLD.id AND record.expires_at > pg_catalog.statement_timestamp(); + END IF; + RETURN NULL; + END IF; + + -- A row inserted already revoked ends at its insert, by the same rule as a + -- revocation: the schema accepts such a row, and the web app's role can insert it. + -- Without this, a service credential's record would stay open and the prune + -- would never select it, and a family's would keep its future expiry. An access + -- token also has a revocation column, but its record always takes its expiry, + -- on a revocation as well, so it needs no case here. + IF kind = 'token_family' THEN + the_grant := NEW.grant_id; the_family := NEW.id; + the_client := NEW.client_id; the_expiry := NEW.expires_at; + IF NEW.revoked_at IS NOT NULL THEN + the_expiry := least(NEW.expires_at, pg_catalog.statement_timestamp()); + END IF; + ELSIF kind = 'access_token' THEN + the_grant := NEW.grant_id; the_family := NEW.family_id; + the_client := NEW.client_id; the_expiry := NEW.expires_at; + ELSIF kind IN ('refresh_token', 'download_ticket') THEN + SELECT family.grant_id, family.client_id INTO the_grant, the_client + FROM %1$I.exomem_oauth_token_families AS family WHERE family.id = NEW.family_id; + the_family := NEW.family_id; the_expiry := NEW.expires_at; + IF kind = 'download_ticket' THEN + -- The expiry index bounds each mint to 32 candidates before locking, + -- so a locked backlog cannot make a request walk the expired table. + WITH candidates AS MATERIALIZED ( + SELECT candidate.id, candidate.expires_at + FROM %1$I.exomem_cloud_download_tickets AS candidate + WHERE candidate.expires_at <= pg_catalog.statement_timestamp() + AND candidate.id <> NEW.id + ORDER BY candidate.expires_at + LIMIT 32 + ) + DELETE FROM %1$I.exomem_cloud_download_tickets AS expired + WHERE expired.id = ( + SELECT lock_target.id + FROM candidates + JOIN %1$I.exomem_cloud_download_tickets AS lock_target ON lock_target.id = candidates.id + ORDER BY candidates.expires_at + LIMIT 1 + FOR UPDATE OF lock_target SKIP LOCKED + ); + END IF; + ELSIF kind = 'service_credential' THEN + the_tenant := NEW.tenant_id; + IF NEW.revoked_at IS NOT NULL THEN + the_expiry := pg_catalog.statement_timestamp(); + END IF; + END IF; + + IF kind = 'service_credential' THEN + SELECT tenant.owner_user_id INTO the_user + FROM %1$I.exomem_tenants AS tenant WHERE tenant.id = the_tenant; + ELSE + SELECT grant_row.tenant_id, grant_row.user_id, coalesce(the_client, grant_row.client_id) + INTO the_tenant, the_user, the_client + FROM %1$I.exomem_oauth_grants AS grant_row WHERE grant_row.id = the_grant; + END IF; + IF the_user IS NULL THEN + RAISE EXCEPTION 'EXOMEM_ISSUANCE_UNRECORDED: no account for this credential' + USING ERRCODE = '23503'; + END IF; + + INSERT INTO %1$I.exomem_cloud_issuance_log ( + credential_kind, credential_id, grant_id, family_id, client_id, + tenant_id, user_id, expires_at, database_role + ) VALUES ( + kind, NEW.id, the_grant, the_family, the_client, + the_tenant, the_user, the_expiry, session_user + ); + RETURN NULL; + END; + $body$; + $definition$, target_schema); + + -- A record is kept until 90 days after its credential expires, or ends: a token + -- family that is revoked or deleted, and a service credential. The 90 days is a + -- constant here, not a setting: changing it takes a migration. A record of a live + -- service credential never matches. One call deletes at most 10000 records, so + -- the reconcile job's call stays short. + EXECUTE format($definition$ + CREATE FUNCTION %1$I.exomem_prune_issuance_log() RETURNS integer + LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp + AS $body$ + DECLARE + deleted integer; + BEGIN + DELETE FROM %1$I.exomem_cloud_issuance_log AS record + USING ( + SELECT stale.id FROM %1$I.exomem_cloud_issuance_log AS stale + WHERE stale.expires_at < pg_catalog.now() - interval '2160 hours' + ORDER BY stale.expires_at + LIMIT 10000 + ) AS doomed + WHERE record.id = doomed.id; + GET DIAGNOSTICS deleted = ROW_COUNT; + RETURN deleted; + END; + $body$; + $definition$, target_schema); + + -- A tenant's service credentials end when its cell does. A credential belongs to + -- the tenant, not to one cell, so a live one would serve the tenant's next cell + -- after re-admission, and its record would stay open and never be pruned. This + -- function runs as the role that changes the cell, not as the schema owner. Only + -- the web app's role changes a cell's desired state, and it holds update on the + -- revocation column, so the function needs no owner rights. It sets the + -- revocation time from the statement's clock and leaves the revoking principal + -- empty, because no operator revoked the credential. The existing trigger on the + -- credential table then ends its record. It names the tenant only, because one + -- index allows a single non-deleted cell for each tenant, so no other live cell + -- remains when a cell becomes deleted. It pins its path for the same reason as + -- the functions above. + EXECUTE format($definition$ + CREATE FUNCTION %1$I.exomem_revoke_service_credentials_of_cell() RETURNS trigger + LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp + AS $body$ + BEGIN + -- The revocation must see credentials that committed while deletion + -- waited for the cell lock. The web transaction already uses read + -- committed. Refuse a stale snapshot before deleting or revoking. + IF pg_catalog.current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Cell deletion must use READ COMMITTED to revoke service credentials' + USING ERRCODE = '0A000'; + END IF; + UPDATE %1$I.exomem_cloud_service_credentials AS credential + SET revoked_at = pg_catalog.statement_timestamp() + WHERE credential.tenant_id = OLD.tenant_id AND credential.revoked_at IS NULL; + RETURN NULL; + END; + $body$; + $definition$, target_schema); + + -- A service credential needs a live cell when it is inserted, and the check + -- locks that cell's row. Without the lock, a credential could commit just after + -- the trigger above ran for a deletion that the credential's transaction had not + -- seen, and it would stay live for the tenant's next cell. The share lock makes + -- a deletion wait for the insert, and the trigger above then revokes the + -- committed credential. An insert that waits for a deletion finds no live cell + -- when the deletion commits, and is refused. It runs with its caller's rights, + -- which are the web app's role's: select on the cell's columns and update on the + -- columns that the share lock needs. It pins its path like the functions above. + EXECUTE format($definition$ + CREATE FUNCTION %1$I.exomem_require_live_cell_for_service_credential() RETURNS trigger + LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp + AS $body$ + BEGIN + PERFORM 1 FROM %1$I.exomem_cloud_cells AS cell + WHERE cell.tenant_id = NEW.tenant_id AND cell.desired_state <> 'deleted' + FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'EXOMEM_SERVICE_CREDENTIAL_NO_LIVE_CELL: the tenant has no cell that is not deleted' + USING ERRCODE = '23503', CONSTRAINT = 'exomem_cloud_service_credentials_live_cell'; + END IF; + RETURN NEW; + END; + $body$; + $definition$, target_schema); + + -- PostgreSQL gives PUBLIC execute on every new function. With it, any role + -- could attach the recording function to a trigger on its own table and + -- append records for rows that never existed. The grants script gives the web + -- app's role execute on the prune function only. The cell trigger's function is + -- closed the same way, though it runs with its caller's rights and can write + -- nothing that its caller cannot. + EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_record_issuance() FROM PUBLIC', target_schema); + EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_prune_issuance_log() FROM PUBLIC', target_schema); + EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_revoke_service_credentials_of_cell() FROM PUBLIC', target_schema); + EXECUTE format('REVOKE ALL ON FUNCTION %I.exomem_require_live_cell_for_service_credential() FROM PUBLIC', target_schema); +END; +$migration$; + +-- One AFTER INSERT row trigger on each credential table. PostgreSQL checks the +-- execute right when a trigger is created, not when it fires, so no role but +-- the schema owner can attach the function. +CREATE TRIGGER exomem_oauth_token_families_issuance_record + AFTER INSERT ON exomem_oauth_token_families + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('token_family'); +CREATE TRIGGER exomem_oauth_access_tokens_issuance_record + AFTER INSERT ON exomem_oauth_access_tokens + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('access_token'); +CREATE TRIGGER exomem_oauth_refresh_tokens_issuance_record + AFTER INSERT ON exomem_oauth_refresh_tokens + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('refresh_token'); +CREATE TRIGGER exomem_cloud_service_credentials_issuance_record + AFTER INSERT ON exomem_cloud_service_credentials + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('service_credential'); +-- The same function ends the record when the credential ends. A WHEN clause +-- cannot read NEW in a delete trigger, so a revocation and a delete get one trigger each. +-- A delete that the account's deletion cascades to fires the delete trigger too. +CREATE TRIGGER exomem_oauth_token_families_issuance_end_revoke + AFTER UPDATE ON exomem_oauth_token_families + FOR EACH ROW WHEN (OLD.revoked_at IS NULL AND NEW.revoked_at IS NOT NULL) + EXECUTE FUNCTION exomem_record_issuance('token_family'); +CREATE TRIGGER exomem_oauth_token_families_issuance_end_delete + AFTER DELETE ON exomem_oauth_token_families + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('token_family'); +CREATE TRIGGER exomem_cloud_service_credentials_issuance_end_revoke + AFTER UPDATE ON exomem_cloud_service_credentials + FOR EACH ROW WHEN (OLD.revoked_at IS NULL AND NEW.revoked_at IS NOT NULL) + EXECUTE FUNCTION exomem_record_issuance('service_credential'); +CREATE TRIGGER exomem_cloud_service_credentials_issuance_end_delete + AFTER DELETE ON exomem_cloud_service_credentials + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('service_credential'); +CREATE TRIGGER exomem_cloud_download_tickets_issuance_record + AFTER INSERT ON exomem_cloud_download_tickets + FOR EACH ROW EXECUTE FUNCTION exomem_record_issuance('download_ticket'); + +-- A cell that becomes deleted, by update or by a delete of a live row, revokes the +-- tenant's service credentials in the same statement, whichever release runs it. +-- The delete trigger covers the schema owner, the only role that can delete a cell +-- row. Deleting a row that is already deleted changes nothing for the tenant. +CREATE TRIGGER exomem_cloud_cells_service_credentials_end_update + AFTER UPDATE ON exomem_cloud_cells + FOR EACH ROW WHEN (OLD.desired_state IS DISTINCT FROM 'deleted' AND NEW.desired_state = 'deleted') + EXECUTE FUNCTION exomem_revoke_service_credentials_of_cell(); +CREATE TRIGGER exomem_cloud_cells_service_credentials_end_delete + AFTER DELETE ON exomem_cloud_cells + FOR EACH ROW WHEN (OLD.desired_state IS DISTINCT FROM 'deleted') + EXECUTE FUNCTION exomem_revoke_service_credentials_of_cell(); + +-- A service credential is inserted only for a tenant with a live cell, and the +-- insert locks that cell's row (the function's comment says why). +CREATE TRIGGER exomem_cloud_service_credentials_live_cell + BEFORE INSERT ON exomem_cloud_service_credentials + FOR EACH ROW EXECUTE FUNCTION exomem_require_live_cell_for_service_credential(); + +-- One-time revoke. A service credential of a tenant with no cell other than deleted +-- ones is not served, so it ends now, whichever release deleted the cell. The +-- revocation time is the migration's time, and the revoking principal stays empty. +-- It runs before the backfill, which then writes each ended credential's record +-- with that time. +UPDATE exomem_cloud_service_credentials AS credential +SET revoked_at = pg_catalog.now() +WHERE credential.revoked_at IS NULL + AND NOT EXISTS ( + SELECT 1 FROM exomem_cloud_cells AS cell + WHERE cell.tenant_id = credential.tenant_id AND cell.desired_state <> 'deleted' + ); + +-- One backfilled record for each credential row that exists, except a row whose +-- record the prune would delete at once: its end is more than 90 days old, which is +-- the prune function's constant. Each record takes the end that the recording +-- function would write. It runs after the triggers exist and inside the transaction +-- that holds the locks, so no row can land between the two steps without a record. +-- The ticket table is new and empty. +INSERT INTO exomem_cloud_issuance_log ( + credential_kind, credential_id, grant_id, family_id, client_id, + tenant_id, user_id, expires_at, database_role, backfilled +) +-- A family that is revoked already ends at the migration's time, unless it expired earlier. +SELECT 'token_family', family.id, family.grant_id, family.id, family.client_id, + grant_row.tenant_id, grant_row.user_id, family_end.at, current_user, true +FROM exomem_oauth_token_families AS family +JOIN exomem_oauth_grants AS grant_row ON grant_row.id = family.grant_id +CROSS JOIN LATERAL ( + SELECT CASE WHEN family.revoked_at IS NOT NULL + THEN least(family.expires_at, pg_catalog.now()) ELSE family.expires_at END AS at +) AS family_end +WHERE family_end.at >= pg_catalog.now() - interval '2160 hours'; + +INSERT INTO exomem_cloud_issuance_log ( + credential_kind, credential_id, grant_id, family_id, client_id, + tenant_id, user_id, expires_at, database_role, backfilled +) +SELECT 'access_token', token.id, token.grant_id, token.family_id, token.client_id, + grant_row.tenant_id, grant_row.user_id, token.expires_at, current_user, true +FROM exomem_oauth_access_tokens AS token +JOIN exomem_oauth_grants AS grant_row ON grant_row.id = token.grant_id +WHERE token.expires_at >= pg_catalog.now() - interval '2160 hours'; + +INSERT INTO exomem_cloud_issuance_log ( + credential_kind, credential_id, grant_id, family_id, client_id, + tenant_id, user_id, expires_at, database_role, backfilled +) +SELECT 'refresh_token', token.id, family.grant_id, token.family_id, family.client_id, + grant_row.tenant_id, grant_row.user_id, token.expires_at, current_user, true +FROM exomem_oauth_refresh_tokens AS token +JOIN exomem_oauth_token_families AS family ON family.id = token.family_id +JOIN exomem_oauth_grants AS grant_row ON grant_row.id = family.grant_id +WHERE token.expires_at >= pg_catalog.now() - interval '2160 hours'; + +-- A credential that is revoked already ends at the migration's time, like every +-- backfilled time, so the prune keeps its record 90 days from the migration. +INSERT INTO exomem_cloud_issuance_log ( + credential_kind, credential_id, tenant_id, user_id, expires_at, database_role, backfilled +) +SELECT 'service_credential', credential.id, credential.tenant_id, tenant.owner_user_id, + CASE WHEN credential.revoked_at IS NOT NULL THEN pg_catalog.now() END, current_user, true +FROM exomem_cloud_service_credentials AS credential +JOIN exomem_tenants AS tenant ON tenant.id = credential.tenant_id; diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md index 4e0ecc5e..1c95da37 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/design.md @@ -22,8 +22,8 @@ Load target: `openspec/project.md` records 10,000 tenants. Neither `docs/runbook **Goals** -- The database records every credential that the web app issues for a cell, and the web app's role cannot alter the record. -- The web app's role cannot change an existing credential row's identity, cannot revive a revoked credential, and cannot delete an identity row. +- The database records every credential that the gateway admits from the web app (the five kinds in D1), and the web app's role cannot alter the record. +- On the column-locked tables, the web app's role cannot change an existing credential row's identity or revive a revoked credential. It cannot delete an identity row. - These controls hold whatever select, insert, update, delete and truncate rights a grants script gives the web app's role. - No web deployment environment holds a credential that can remove those controls. - Every flow that exists today keeps working, on the release that serves during a deploy too. @@ -51,7 +51,7 @@ The stated problem was OAuth tokens. The gateway admits five kinds of credential A lock on access tokens alone would leave three silent paths. The web app's role could insert a service credential for any tenant. It could rewrite a service credential's digest or tenant. It could sign a download ticket against any live Home token family, with no insert at all. The lock and the log therefore cover all five kinds, and D8 gives the download ticket a row. -A refresh token never reaches the gateway. It is recorded and locked anyway, because the claim says "every credential" and the cost is one record for each rotation. +A refresh token never reaches the gateway, but the web app exchanges it for an access token that the gateway admits. The claim lists it, and the cost is one record for each rotation. ### D2. Column rights deny the web app's role; guards hold when the rights fail @@ -66,6 +66,7 @@ The grants script gives the web app's role these rights on every run: | `exomem_cloud_service_credentials` | `revoked_at`, `revoked_by_principal_digest` | both | removed | | `exomem_oauth_clients` | every column except `id` and `client_id` | none | removed | | `exomem_tenants` | every column except `owner_user_id` | none | removed | +| `exomem_cloud_cells` | `desired_state`, `desired_image`, `storage_gib`, `cancellation_notice_sent_at`, `deletion_grant`; the grants script already gives exactly these | none | never held | | `exomem_users` | every column | none | removed | | `exomem_marketplace_reviewer_credentials` | every column | none | removed | @@ -77,9 +78,9 @@ Column rights are the first control, because the database enforces them before a **Guards.** A guard is a trigger that refuses a statement unless the schema owner runs it. Guards do not depend on the grants script. They do three jobs: -- **Fixed columns.** On a column-locked table, a guard refuses a change to any fixed column. On clients and tenants, it refuses a change to the columns that the table above excepts. +- **Fixed columns.** On a column-locked table, a guard refuses a change to any fixed column. On clients and tenants, it refuses a change to the columns that the table above excepts. On cells, it refuses a change to `cell_id` or `tenant_id`, because the gateway reaches a cell through its tenant. - **One-way columns.** A guard refuses a change to a revocation or consumption value that is already set. Every revocation statement today either keeps the old value or filters on an empty one. -- **Deletes.** On every table whose delete the table above removes, a guard refuses a delete and a truncate. A truncate that cascades from another table meets the same guard. +- **Deletes.** On every table whose delete the table above removes or never held, a guard refuses a delete and a truncate. No flow deletes a cell row: a cell ends as `desired_state = 'deleted'`, and no role holds delete on cells. A truncate that cascades from another table meets the same guard. Every guard calls one function, built this way: @@ -121,7 +122,7 @@ An event trigger that refuses `CREATE TRIGGER` to other roles would hold without - The first migration pins `search_path` on every function that the database can run as the schema owner for another role. These are the schema owner's trigger functions and `SECURITY DEFINER` functions in the schema, and each SQL or PL/pgSQL function in the schema that a constraint, a column default or an index calls. The set holds only functions that the schema owner owns and that belong to no extension: a C or internal function looks up no names, and the schema owner cannot alter an extension's functions. A function that one of them calls runs under its caller's path. - A function that qualifies every name gets `pg_catalog, pg_temp`. That covers the health proof and every function of this change. - - Every other one gets `pg_catalog`, then those schemas of the migration's own path that the schema owner, the bootstrap superuser or `pg_database_owner` owns, then `pg_temp`. On PostgreSQL 15 and later `public` belongs to `pg_database_owner`, which stands for the database's owner. A schema that another role created therefore never enters a pin. Its body names schema objects without a schema, and one calls `pgcrypto` in `public`. Production's path is `public`; a test's is its own schema, then `public`. Each body therefore resolves as it does today, except that a temporary table can no longer shadow a table. + - Every other one gets `pg_catalog`, then every schema of the migration's own path, then `pg_temp`. Each of these bodies names schema objects without a schema, and one calls `pgcrypto` in `public`. Production's path is `public`; a test's is its own schema, then `public`. Each body therefore resolves as it does today, except that a temporary table can no longer shadow a table. A schema that another role owns would put that role's operators into a pin. The migration therefore checks each schema of its path first. The schema owner, the bootstrap superuser or `pg_database_owner` must own it. On PostgreSQL 15 and later `public` belongs to `pg_database_owner`, which stands for the database's owner. When the check fires wrongly, because the owner of a schema on the path is harmless, the migration raises an error that names each such schema and its owner, and it rolls back. The old schema keeps serving. The operator pays one failed migration job, until the schema's owner is changed or the schema leaves the migration role's path. - A test reads the catalog: each of those functions pins a path that starts with `pg_catalog` and ends with `pg_temp`. When the test fires wrongly, a migration that adds such a function fails CI until its author adds one `SET` clause. The author pays, and nothing reaches production. - The pinned path never names a schema that the role created, so the pin alone closes that route. It cannot close the route through a schema that the path names. The create right on the database also lets a role create a schema named after the schema owner, which the default path `"$user", public` searches first in the owner's own sessions. The rollout and the runbook's checks therefore read that no role other than a superuser, the schema owner or `pg_database_owner` holds a create right on the database or on a schema outside `pg_catalog` and `information_schema`, directly or through a membership, and list each schema that another role owns. Superusers hold every right, and each schema's owner holds the create right on it, so the read leaves those out. @@ -162,17 +163,19 @@ The existing test suites set up fixtures as the role that owns the schema, so th Two existing options were checked first. `exomem_audit_events` exists and has no writer. It describes operations, with an outcome and size buckets, and has no column for a credential, grant, token family or user. Its two indexes would also add work to every token insert. The `pgaudit` extension writes statements to the server's log file. That needs server-level installation, and a reader cannot query the file beside the rows it describes. A table with a trigger is the smaller mechanism. +A third option was weighed and rejected for this change: recording at the gateway on each admission, a use log. It puts a write and a de-duplication on the gateway's hot path for every request. The issuance log and the ticket-row requirement already close the paths that this change targets. A use log is a later step for limit 9, which says that the log does not record use. + One table, `exomem_cloud_issuance_log`, holds one record for each credential insert: | Column | Meaning | |---|---| | `id` | identity column, in insert order | -| `recorded_at` | the database clock when the record was written | +| `recorded_at` | the time the transaction started | | `credential_kind` | `access_token`, `refresh_token`, `token_family`, `service_credential` or `download_ticket` | | `credential_id` | the credential row's identifier | | `grant_id`, `family_id`, `client_id` | as the credential row names them, or read through its token family | | `tenant_id`, `user_id` | read from the grant, or from the service credential's own tenant | -| `expires_at` | the credential's expiry, or empty when it has none | +| `expires_at` | the credential's expiry. A service credential has none: its record stays empty while the credential is live, and takes the database clock's time when the credential ends (D6) | | `database_role` | the role that connected (`session_user`) | | `backfilled` | true only for a record that the migration wrote for an older row | @@ -189,31 +192,41 @@ Other points: - **No foreign keys.** A record outlives its credential row, and the insert stays cheap. - **Identifiers only.** The log holds no token, digest, secret, principal, path or address. It fits the content-free telemetry requirement of the OAuth spec. - **Tenant and user are copied.** The copy costs one primary-key read of a row that the same transaction has just touched. D12 uses it to read one tenant's records. -- **Existing rows.** The migration writes one record for each credential row that already exists. Those records are marked `backfilled`. Their `recorded_at` is the migration's time, not the issuance time, and their database role is the schema owner. +- **Existing rows.** The migration writes a record for each credential row whose record the prune would keep: the end that the recording function would write is empty, or is at most 90 days before the migration. A token that expired longer ago gets no record, because the prune would delete it at once, and a large old table would only lengthen the lock. Those records are marked `backfilled`. Their `recorded_at` is the migration's time, not the issuance time, and their database role is the schema owner. - **Order inside the migration.** The migration creates each recording trigger first and writes the older rows' records afterwards, in the same transaction. Creating the trigger locks the table against writes until the commit. No row can then land between the two steps without a record. **What the migrations lock.** Creating a trigger locks its table against inserts, updates and deletes until the commit. Reads continue, the gateway's lookups included. The change ships two migrations, so that the longer one locks fewer tables: -- The first adds `schema_releases` and the guards, and pins the functions' paths. It locks users, tenants, reviewer credentials, clients, grants, token families, refresh tokens, access tokens and service credentials. It changes only the catalog, so it commits soon after it holds the last lock. -- The second adds the log, the ticket table, the recording triggers and the records for existing rows. It locks token families, refresh tokens, access tokens and service credentials until it has written those records. Code exchange, refresh, the Home mint, token revocation, service credential requests and the maintenance wait for it. Its length grows with the count of live credential rows. -- Each migration takes all its locks first, with one `LOCK TABLE` statement in the mode that creating a trigger takes. PostgreSQL takes them one at a time, in the order listed above. Admission writes users before tenants, and every revocation and issuance writes grants, then token families, then tokens, in that order. Two flows write in another order: cell deletion writes the OAuth tables, then tenants, then users, and deletion finish writes tenants before users. Either can deadlock with the first migration, and PostgreSQL then fails one of the two transactions. The reconcile job runs both flows every minute (`ops/exomem-hosted-schedules.json`), so a failed deletion step runs again a minute later. A deadlock fails the migration's job like a lock timeout does, and the operator starts the job again. +- The first adds `schema_releases` and the guards, and pins the functions' paths. It locks users, tenants, cells, reviewer credentials, clients, grants, token families, refresh tokens, access tokens and service credentials. It changes only the catalog, so it commits soon after it holds the last lock. +- The second adds the log, the ticket table, the recording triggers, the cell trigger of D6 and the records for existing rows. It locks cells, token families, refresh tokens, access tokens and service credentials until it has written those records. Code exchange, refresh, the Home mint, token revocation, service credential requests, cell changes and the maintenance wait for it. Its length grows with the rows that its backfill reads, which are the full token family, access token, refresh token and service credential tables, because no expiry index covers every retained row: the refresh token index covers only unconsumed rows. The rows that it writes add to that. The migration runs once, against today's data, so task 7.4's query counts the rows that each read scans, and the window and the go/no-go use that count. +- Each migration takes all its locks first, with one `LOCK TABLE` statement in the mode that creating a trigger takes. PostgreSQL takes them one at a time, in the order listed above, and the second migration takes cells first: a cell's change writes the service credentials after it, through the trigger of D6. Admission writes users before tenants, and every revocation and issuance writes grants, then token families, then tokens, in that order. Three flows write in another order: cell deletion writes the OAuth tables, then tenants, then users, deletion finish writes tenants before users, and the lifecycle sweep writes a cell before its tenant. Any of them can deadlock with the first migration, and PostgreSQL then fails one of the two transactions. The reconcile job runs both flows every minute (`ops/exomem-hosted-schedules.json`), so a failed deletion step runs again a minute later. A deadlock fails the migration's job like a lock timeout does, and the operator starts the job again. A service credential request locks the tenant, then the cell through D6's trigger. That is the order of deletion finish, which waits for the request on the tenant, and the reverse of the lifecycle sweep. If the sweep and a request for the same tenant overlap, they can deadlock, and PostgreSQL fails one of them. The sweep runs again a minute later. A request that PostgreSQL fails answers 503 `SERVICE_CREDENTIAL_RETRY` with `Retry-After: 3`, and the operator sends it again. - Each migration sets a lock timeout of five seconds. Without one, its lock request would wait behind any long transaction, and every later write would wait behind the request. The timeout bounds each wait, not the migration. While the migration waits for one lock, it holds every lock that it took before, and new writes to the table it waits for queue behind its request. In the worst case, a write to users waits through all nine waits of the first migration, about 45 seconds, before that migration commits or fails. When a wait times out, the migration fails, the job fails, and a later run tries again. - If the second migration fails, the guards are in force without the log. No flow depends on the log, and a later run adds it. The recording fails closed: when the record cannot be written, the credential insert fails. This prevents a credential that exists with no record, which is the claim itself. When it fires wrongly, sign-in and Home fail for every user until the schema owner disables the trigger with one statement. The proof in `tasks.md` runs every flow through the trigger before release, and the runbook names that statement. -### D6. Records are kept until 90 days after the credential expires +### D6. Records are kept until 90 days after the credential expires or ends + +The cutoff uses 90 elapsed days. A session's time zone does not change it. + +A record is deleted once its credential expired, or ended, more than 90 days ago. A token family and a service credential end when they are revoked or their row is deleted. The session policy sets the expiry: a token family lasts `EXOMEM_OAUTH_SESSION_MAX_DAYS` from sign-in, 365 days by default and at most 730 (`src/lib/exomem-hosted/oauth-session-policy.ts`). A refresh token lasts `EXOMEM_OAUTH_REFRESH_IDLE_DAYS`, 30 days by default and at most 90, and never past its family's expiry. An access token lasts one hour, also never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. + +A service credential has no expiry. Its record has no end while the credential is live, and the prune never deletes it. When the credential is revoked, or its row is deleted, the recording function sets the record's end to the database clock's time. It runs from an update trigger on the revocation time and a delete trigger, and it sets a record's end once. The prune then deletes the record 90 days later. The function reads the clock, not the row's `revoked_at`. The web app's role writes that column, and a past time would bring the prune forward and erase the record of a credential that the role issued. The audit's credential index finds the record by kind and identifier. For a revoked credential that exists when the migration runs, the record's end is the migration's time. -A record is deleted once its credential expired more than 90 days ago. A record with no expiry, which is a service credential's, is never deleted. A token family lives up to its session maximum, 365 days by default, so its record lives longer than that. +A token family's record holds the family's expiry from the insert. The same recording function moves it to the database clock's time when the family is revoked or its row is deleted, if that is earlier. An update trigger on the revocation time and a delete trigger run it, and a delete that an account's deletion cascades to runs it too. The function reads the clock, not the row's `revoked_at`, for the same reason as above. A revocation is one-way, and a revoked family cannot be used, so the web app's role cannot end a live family's record early. The same credential index finds the family's record. For a family that is revoked when the migration runs, the record's end is the migration's time, unless the family expired earlier. An access token's and a refresh token's record do not end early. Each keeps its own expiry. + +A cell's deletion revokes its tenant's service credentials, in the database. An `AFTER UPDATE` row trigger on the cells table fires when a cell's desired state becomes `deleted`, and an `AFTER DELETE` trigger fires when a row that is not yet deleted goes. Both set `revoked_at` to the database clock on the tenant's unrevoked service credentials and leave the revoking principal empty, because no operator revoked them. The recording function's trigger then ends each record. The database does this, not the web app's code, so the release that serves during a build, and an instant rollback to the release before this one, still end the credentials: no flow's SQL changes. A credential belongs to the tenant, so a live one would otherwise serve the tenant's next cell after re-admission, and its record would stay open and never be pruned. The trigger function runs with its caller's rights, not the schema owner's. Only the web app's role sets a cell's desired state, and it already holds update on the revocation column, so no grant changes. The gateway's role reads cells only, and the controller's role writes observed columns only, so neither fires it. The schema owner is the only role that can delete a cell row, so the delete trigger covers it. The trigger does not check for another live cell, because one index allows a single cell that is not deleted for each tenant. A second update, or a delete of a row that is already deleted, changes nothing. A `BEFORE INSERT` row trigger on the service credentials table closes the opposite order. Without it, a credential that commits just after the deletion's trigger ran would stay live and serve the tenant's next cell. The trigger reads the tenant's cell that is not deleted with `FOR SHARE`, and refuses the insert when none exists, with SQLSTATE `23503` and the constraint name `exomem_cloud_service_credentials_live_cell`. A deletion that starts after the insert waits for the inserting transaction to commit, and the deletion's own trigger then revokes the new credential. An insert that waits for a deletion finds the updated row, finds no live cell when the deletion commits, and is refused. The service credential request answers that refusal as `SERVICE_CREDENTIAL_TENANT_INELIGIBLE` (409), the answer for any tenant without a live cell. This trigger function also runs with its caller's rights. The web app's role is the only role that inserts credentials. It holds select on the cell and update on the columns that the share lock needs, so no grant changes. Both triggers take the cell's lock before the credential: the insert locks the cell's row before its own row exists, and the cell trigger writes the credentials after the cell row, as D5's order requires. Afterwards, a token family's record and a service credential's record last 90 days. The migration also revokes once, at its own time, every unrevoked service credential of a tenant that has no cell other than deleted ones, so the credentials of accounts that a release before this one deleted end too. No record stays open after that. An access token's record lasts until 90 days after its own expiry, which is an hour at most from its issue. A refresh token's record lasts until 90 days after its own expiry, which is the idle window at most from its issue: 30 days by default, at most 90. The longest window after deletion is therefore the refresh token's idle bound plus 90 days, which is 120 days by default and 180 at most. A download ticket's record lasts a day plus 90 days at most. The expiry is safe to key on. It is set at insert and is a fixed column afterwards. A credential cannot be used after its expiry, so no usable credential loses its record early. -A prune function deletes the records. The schema owner owns it, and it is `SECURITY DEFINER` with the same `search_path` rule as the recording function. Only the web app's role holds its execute right. Each call deletes at most 10,000 records. The reconcile job calls it once a run, beside the OAuth maintenance. At one run a minute it can delete 14.4 million records a day. D7 estimates 1.5 million new records a day at the load target. A backlog from a week without the job clears in about a day. +A prune function deletes the records. The schema owner owns it, and it is `SECURITY DEFINER` with the same `search_path` rule as the recording function. Of the roles granted the right to execute it, only the web app's role is one. Each call deletes at most 10,000 records. The reconcile job calls it once a run as a lane of its own, beside the OAuth maintenance. Another lane's failure does not stop it. A part of it that fails is reported as `null` and fails the job's response with `503`, which carries the counts. At one run a minute it can delete 14.4 million records a day. D7 estimates 1.5 million new records a day at the load target. A backlog from a week without the job clears in about a day. The web app's role may call the function at any time, and it still deletes only records past their retention. The 90 days is a constant inside the function, not a setting: changing it needs a migration, which is a public commit. A btree index on `expires_at` serves the prune. The alternatives were worse. A partitioned log would make every token insert depend on partition upkeep. A block-range index would go stale as long-lived token family records pin old ranges. +Only a read-committed transaction may delete a live cell or set it to deleted. After waiting for issuance's cell lock, the revocation must see the newly committed credential. The web transaction already uses read committed. The database refuses a fixed-snapshot deletion rather than leave a credential live. + ### D7. Cost on the hot path, at the load target A Home tool call runs about seven statements today. One checks the cell before the transaction. Inside it come the client lookup, the retirement of a stale grant, the grant upsert, the token family lookup, the delete of expired tokens and the token insert. A new token family adds one insert. @@ -221,7 +234,7 @@ A Home tool call runs about seven statements today. One checks the cell before t This change adds work in two places. The token insert gains: - one read of the grant by primary key; -- one log insert with three index entries (`id`, `expires_at`, and `tenant_id` with `id`); +- one log insert with five index entries. The identity lookup and late-commit replay share the live insert; - one call of the log's guard. Each update of a column-locked table gains the evaluation of its guard's `WHEN` clause, which calls no function. @@ -235,30 +248,31 @@ Volume, from constants in the code and one assumption: - A refresh token expires after its idle window, 30 days by default, so its record lives up to 120 days. - Assumption, not a recorded figure: each of 10,000 tenants keeps Home visible for one hour a day and runs two apps for eight hours. -That gives about 1.5 million records a day: 1.2 million from Home and 0.3 million from apps. About 142 million sit inside the retention. A record with its three index entries takes roughly 250 bytes, so the log holds about 35 GB at the load target. Home's two-minute tokens are about three quarters of it. The row size is an estimate from the column list. Nothing here is measured, and the proof reports the measured size of a record. +Use that traffic mix and the retention periods to size the representative +dataset. Measure storage with the audit indexes before rollout. The log also costs outside the request: -- Each record is written once and deleted once. At the load target that is about three million row changes a day in the write-ahead log. +- Each record is written once and deleted once. Both writes contribute to the write-ahead log. - Each base backup grows by the log's size, and a restore takes longer in proportion. Proof, on a disposable PostgreSQL: -- **Instrument.** `pgbench` runs the Home mint transaction's statements as a custom script, over generated data for 10,000 tenants. The same script runs with and without this change's triggers, five runs each, on the same machine and data. -- **Size.** The log holds 10 million generated records. That is enough, because every insert lands at the right edge of an index, or at the right edge of one tenant's range. The pages that an insert touches stay in memory at any log size. -- **Result.** The PR reports the median and the 95th percentile of the transaction's latency for both arms, and the write-ahead-log bytes for each mint. The median must rise by less than one millisecond. -- **Plans.** `EXPLAIN (ANALYZE, BUFFERS)` of one prune call shows that it reads only the records it deletes. The same output for each read of D12 shows an index range and no full scan. +- **Instrument.** `pgbench` runs the Home mint transaction's statements as a custom script, over generated data for 10,000 tenants. The same script runs with and without this change's triggers, five runs each, on the same machine and data. The script and the generator are not in this repository. They are kept with the private record of the run, together with its outputs, so a later change to the triggers or the guards reruns the proof with the same instrument. +- **Size.** The instrument holds 10 million generated records. Its results describe that sample and the tested client count. Latency at the projected log size and concurrency remains unverified. The expiry index also holds credentials with different lifetimes and records whose expiry can change. +- **Result.** The run's outputs are kept as a private record outside this repository, and task 5.8 states the outcome and the commit that the run measured. The median must rise by less than one millisecond. +- **Plans.** Run `EXPLAIN (ANALYZE, BUFFERS)` on one prune and on each current D12 query. The prune should read only the records it deletes. Each D12 read must use a bounded range or lookup on the log. The credential check pages through the source tables by primary key, then probes the log's credential index for eligible rows. ### D8. A download ticket gets a stored row A download ticket is a signed message that names a token family, a grant and a path digest. The web app signs it with a key that the gateway shares. No row backs it. A compromised web app could sign a ticket against any tenant's live Home token family and leave no trace. -The web app now stores one row for each ticket in `exomem_cloud_download_tickets`: an identifier, the token family, the grant, the path digest and the expiry. A recording trigger writes the issuance record. +The web app now stores one row for each ticket in `exomem_cloud_download_tickets`: an identifier, the token family, the path digest and the expiry. A recording trigger writes the issuance record. - **Key.** A unique key covers the token family, the path digest and the expiry. The web app inserts with `ON CONFLICT DO NOTHING`. Two tickets with the same three values carry the same authority and share one row and one record. - **Rights.** The web app's role holds select, insert and delete. The gateway's role holds select. A guard refuses every update unless the schema owner runs it. -- **No foreign key.** A row lives at most one day, and the gateway joins the token family when the ticket is used. The recording function reads the row's grant, so an insert that names no real grant fails. -- **Prune.** The scheduled maintenance deletes a bounded batch of expired rows, through an index on the expiry. +- **No foreign key, and no grant column.** A signed ticket can authorize a download for at most one day, and the gateway joins the token family when the ticket is used. The row names no grant, because nothing reads one: the gateway's lookup requires the ticket's token family to carry the grant that the signed ticket names. The recording function reads the grant, the tenant and the user through the family. An insert for a family that does not exist fails, because the recording fails closed. A role that can insert can name another tenant's family with that family's real grant, and the gateway then admits the ticket. That is issuance, which the log records and this change does not prevent (limit 1). +- **Prune.** A new ticket looks up a bounded set of expired rows through the expiry index before trying any locks. It retires one available row and skips the cleanup if every candidate is locked. The scheduled job drains idle backlog and rows skipped during contention. If the recorder is disabled for emergency repairs, only the scheduled cleanup runs. An expired ticket cannot authorize a download while its row awaits deletion. The gateway checks the signature as today and then requires the matching unexpired row. The check is one more condition in the statement that already resolves the ticket's login. A media request therefore makes no extra round trip, and each byte-range request costs one more index probe. A test counts the statements of a download request before and after. @@ -279,13 +293,14 @@ The download ticket's own requirements live in the active change `add-cloud-medi A new workflow runs on every push to `main` and by hand. It runs in a protected environment whose branch rule accepts only `main`. The schema-owner connection string is that environment's secret. The job: -1. Checks that its commit is the tip of `main`. If it is not, the job applies nothing. It records the commit as superseded, unless the commit already has a row. -2. Runs `scripts/migrate.ts`, which applies the pending migrations and then the grants script. -3. Records a schema release for its commit. It records as superseded each commit between the previous schema release and its own that has no row. +1. Checks out the tip of `main` as it stands when the run starts, whatever commit started the run, and installs its dependencies. +2. Reads the tip once more, after the install and just before it applies. If `main` moved in between, the job applies nothing: the push that moved it started a run of its own, which applies the new tip. +3. Runs `scripts/migrate.ts`, which applies the pending migrations and then the grants script. +4. Records a schema release for the tip. It records as superseded the tip's first-parent ancestors, up to 100, that have no row. An ancestor that already has a row keeps it. A gap longer than 100 commits leaves its oldest commits without a row, and a build of one of them fails after its wait. `schema_releases` holds one row for each commit, with a status of `released` or `superseded`. A row is written once and never changes: the job inserts and never updates. A restarted run of a released commit therefore leaves it released. A guard refuses every write to the table unless the schema owner runs it, and the web app's role holds select only. -A concurrency group lets one run proceed at a time and keeps only the newest waiting run. A dry run stays outside the group. It changes nothing, and inside the group it would displace the waiting run. The tip check stops a restarted old run from applying an older grants script. +A concurrency group lets one run proceed at a time and keeps only the newest waiting run. A restart of an old run can therefore replace the waiting run of a newer push. That is safe because every run releases the tip, not its own commit: the replacing run releases the newer commit, and a build of that commit finds its row. A dry run stays outside the group. It changes nothing, and inside the group it would displace the waiting run. Releasing the tip stops a restarted old run from applying an older grants script. The rule needs a run for every push to `main`, so the trigger has no path filter, and a test holds that. The group's `queue: max` setting would keep every waiting run in order, but a burst of pushes would then run one install after another before the newest tip, and a full queue cancels the newest run. The single waiting slot with a tip that each run resolves loses no push and runs fewer installs. `scripts/migrate.ts` records a schema release only when its caller names a commit, as a full 40-character hash. The workflow names its own. A local run, the test job and the end-to-end job name none and record nothing. An operator's run by hand names the commit it applies. @@ -296,7 +311,7 @@ A concurrency group lets one run proceed at a time and keeps only the newest wai - Every action is pinned to a commit, not to a tag. - The environment has no required reviewer. The operator already authorises each merge, and a second click would add a wait without a second person. -Who starts a run does not matter. A run can only apply the tip of `main`: the branch rule refuses other branches, and the tip check refuses older commits. What matters is which code a run executes, and who can change the rules. A test holds the first rule below, and the rollout reads the others: +Who starts a run does not matter. A run can only apply the tip of `main`: the branch rule refuses other branches, and the job checks out the tip whatever commit started it. What matters is which code a run executes, and who can change the rules. A test holds the first rule below, and the rollout reads the others: - **Only this workflow names the environment, and it starts only on a push to `main` or by hand.** A run that starts on `pull_request_target` or `workflow_run` carries `main` as its ref, so the branch rule accepts it. Such a run can check out a pull request's code. No workflow does so today, and a test that reads the workflow files keeps it so. When that test fires wrongly, a new workflow that needs the environment or another event fails CI until the test names it. Its author pays one reviewed edit. - **The ruleset on `main` names no bypass actor.** A bypass actor could push a commit that the merge queue never checked, and the job would run it with the credential. @@ -316,7 +331,7 @@ The previous deployment keeps serving after a failed build, as it does today. A **What the check proves.** It proves that the schema is at least as new as the build. It does not prove that the schema is not newer. A rebuild of an older released commit passes, and its log says that a newer schema release exists. D10's rule covers one release back; an older rebuild is the operator's decision. -The check runs in every production build on the platform: a push, a redeploy and a deploy hook. It does not run for a deployment that was built elsewhere and uploaded, for a promotion, or for an instant rollback. None of those runs the build script. Each needs the platform's deploy credential or the operator's dashboard. +The check runs in every production build on the platform: a push, a redeploy and a deploy hook. It does not run for a deployment that was built elsewhere and uploaded, for a promotion, or for an instant rollback. None of those runs the build script. Each needs the platform's deploy credential or the operator's dashboard. The runbook therefore asks the operator, before such a deployment serves, for a schema release of its commit or of a newer one, and for the compatibility check when the commit is older than the newest release. Alternatives: @@ -333,7 +348,9 @@ The order for each commit is: migrations, grants, schema release, build, serve. The release that is already serving meets the new schema and the new grants during the build. It also meets them after an instant rollback. So each migration and each grants change stays compatible with the previous release. That is today's unwritten rule, and it is now a requirement. -This change obeys it. The lock changes no statement, so the previous release runs under the new rights and guards. The proof runs the flows as the web app's role for that reason. The recording triggers are invisible to callers. The ticket table exists before the web app writes to it, and the gateway requires it last. +The previous release runs under the new rights and guards. The proof runs the existing flows as the web app's role. The ticket table exists before the web app writes to it, and the gateway requires it last. + +Service credential issuance is an operator action. Migration 0102 can refuse an ineligible cell or detect the lock conflict described in D5. The previous release can report either as HTTP 500. The new release reports the ineligible cell as 409 and the lock conflict as a retryable 503. Keep issuance paused while the previous release serves against 0102, during both rollout and instant rollback. ### D11. The schema-owner credential is removed, then rotated @@ -343,11 +360,11 @@ Preview and development environments must hold no credential for the production ### D12. Reading the log -A log that nobody can read cheaply proves nothing. Two readers exist, and each one reads a bounded range. +A log that nobody can read cheaply proves nothing. Two readers exist, and each one reads a bounded range of the log. **The audit role.** A new role, `substrate_audit`, reads the log without the schema-owner credential. It holds select on the log and on the columns that its checks compare, and no other right. The grants script grants this when the role exists, as it does for the gateway's role. The operator creates the role in the rollout. -**The runbook's checks.** Each check that reads records takes a range of record identifiers and reads only that range, through the primary key. The checks are: +**The runbook's checks.** Each log read uses a bounded range or an indexed lookup. The checks are: - credential rows created in the period that have no record; - records in the range whose database role is not the web app's role and that are not backfilled; @@ -355,36 +372,39 @@ A log that nobody can read cheaply proves nothing. Two readers exist, and each o - triggers of this change that are missing or disabled; - roles other than the owner that hold the trigger right on a table in the schema; - roles that the web app's role is a member of; +- rights that the web app's role holds on the log, `schema_releases`, ticket rows and, table-wide, the locked tables beyond what the grants script gives it; - create rights that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and schemas that a role other than the schema owner, the bootstrap superuser or `pg_database_owner` owns. -The first check reads the credential tables' rows of the same period. Those tables hold live rows only, so that read is bounded by the count of live credentials. The last four read the catalog. +**Credential coverage.** The on-demand check reads one primary-key page from one credential table at a time. It applies the time window after taking the page, so a quiet interval does not make PostgreSQL scan past the page. A sweep checks rows with creation times at least an hour old. That closed cohort lets the primary-key cursor advance without a long-lived database snapshot. A transaction open for more than an hour or an explicitly backdated credential can fall outside this check. The next sweep repeats the last hour. The log lookup excludes records older than the credential. Reuse with the same creation time cannot be distinguished. The audit role's grants stay narrow. The owner reads the migration time once; the check clips its lower edge to that time and the retention floor and reports an unverified gap if retention overtook the checkpoint. -**Late commits.** PostgreSQL assigns a record's identifier at insert, not at commit. A record can therefore commit after a check has read past its identifier. Each run starts one hour of records before the point where the previous run stopped, so the next run reads such a record. It finds that start by walking back through the primary key, so the read stays bounded. A record whose transaction stayed open for longer than that hour is missed by the range checks. The read of one tenant's records still returns it. +**Recorded issuances.** The recorded-issuance checks use a separate numeric checkpoint and a fixed greatest identifier for the sweep. Each pass reads one new page through the primary key. It also checks identifiers at or below the checkpoint whose transaction-start time falls within the previous snapshot's replay window. The replay uses the partial time index and excludes the backfill. The backfill committed together and is covered by the new pages. Identifier order need not match transaction-start order. An uncommitted record therefore stays eligible for the next replay even if a later identifier has an earlier timestamp. The replay covers transactions open for up to one hour. Longer transactions can fall outside it. A checkpoint advances only after the queries succeed. **One tenant's records.** An index on `tenant_id` with `id` lists one tenant's issuances, newest first, a page at a time. That is the read for an incident and for an owner who asks who held access. Without the index, it would scan the whole log. ## What the claim does not cover -The claim is: the database records every credential that the account service issues for a cell, in a log that the account service cannot alter. These limits belong beside it wherever it is published. +The claim is: the database records every credential that the gateway admits from the account service, in a log that the account service cannot alter. Those credentials are OAuth access and refresh tokens, token families, service credentials and download tickets. These limits belong beside it wherever it is published. 1. **Issuance itself, and moving an app.** The account service signs users in. It can sign in as any account and issue a credential. It can also hand a connected app a credential for another tenant: at the app's next refresh, or at once by replacing the app's token row (D3). The log records each such insert. It cannot tell one from the owner's own action, and the record does not name the app's owner. -2. **Operation grants.** The account service signs export, import and deletion grants. Each is stored in its own row, not in this log. An export's grant is written once and the web app's role cannot change it. An import's and a deletion's grant is a column that the web app's role can update. +2. **Operation grants.** The account service signs export, import and deletion grants. The log does not record them. The web app's role can insert an export row with its grant. It cannot delete that row, and it holds no update right on the grant column. It can update an import's grant column. It can write a cell's deletion grant once: the trigger of migration 0084 refuses to replace or clear a stored deletion grant. 3. **Content that passes through the web app.** Home's viewer reads memory through the web app. The web app sees what an owner views there. 4. **Cell images.** The account service's operator interface sets the image that a cell runs. 5. **What a grant allows.** The account service can change a grant's scopes. It can change an app's stored attributes, such as its name, its redirect addresses and whether it is enabled. The grant's tenant, user and app stay fixed. 6. **Suspension and blocks.** The account service sets a tenant's status and can add or remove an account block. 7. **The schema owner, the trigger right and the create right.** Whoever holds the schema-owner credential, administers the database server, or lands a commit on `main` can change the lock and the log. So can a role that holds the trigger right on a table in the schema, or a create right on the database or on a schema (D2). So can an administrator of the repository: they can edit the protected environment or the ruleset and run code with the schema-owner credential without landing a commit. The rollout turns off the administrators' bypass of the environment's rules, which narrows that path but does not remove it. Each change through `main` is a public commit. -8. **Old records.** A record is deleted 90 days after its credential expires. +8. **Retention.** The log keeps a record until 90 days after its credential expires. A token family's record ends earlier when the family is revoked or its row is deleted. A service credential, which has no expiry, ends the same way. The session policy sets a token family's expiry: 365 days from sign-in by default, at most 730. It sets a refresh token's expiry from its idle window, 30 days by default, at most 90, never past its family's expiry. The database bounds no expiry, so a role that writes a far expiry only lengthens retention. Deleting an account's cell revokes its service credentials in the database, so after the deletion a token family's record and a service credential's record last 90 days. The migration revokes the credentials of accounts that were deleted before it, so no record stays open. An access token's record and a refresh token's record last until 90 days after its own expiry. The longest window after deletion is the refresh token's idle bound plus 90 days: 120 days by default, 180 at most. No flow but the schema owner deletes a record, and deleting an account does not. 9. **Use, revocation and deletion.** The log records issuance only. It does not say when a credential was used, revoked or deleted. 10. **The gateway's own keys.** The gateway signs cell tokens and upload capsules with its own keys. In this repository only gateway code loads them. Other services may hold them, and this change does not record what they sign. The rollout checks that no web deployment environment holds those keys. 11. **Credentials that the web app admits itself.** The web app issues and checks its own browser sessions. It does the same for the possession grants and sessions of the access record (`exomem_cloud_access_grants`, `exomem_cloud_access_sessions`). The gateway admits none of them, and the log records none. +12. **Reviewer credentials.** The web app's role keeps update rights on every column of `exomem_marketplace_reviewer_credentials`. An existing guard fixes only its lineage columns: kind, candidate, assignment, assignment generation, staged client release and OAuth client. The role can therefore clear a reviewer credential's revocation time and revive it. The gateway then admits that credential's unrevoked families and tokens again. Their records exist from their inserts. +13. **Detection is manual.** The operator runs the runbook's checks on demand. Nothing schedules them yet. The first check reads the five credential tables in full, because none has an index on `created_at`. Detecting a disabled recording trigger, a grant mismatch or a credential without a record is therefore best-effort until a scheduled job runs the checks. That job needs an index on `created_at` or a different first query, which is a later step. ## Risks / Trade-offs - **A flow that the inventory missed changes a fixed column.** → It fails in production from the merge, because the lock has no switch. The proof runs every flow in the inventory as the web app's role. The schema owner's emergency statement restores the flow, and a commit makes the fix durable. - **The recording trigger fails in production.** → Every token insert fails. The proof runs each insert path through the trigger, and the runbook names the statement that disables it. Disabling it suspends the claim, and the runbook says so. -- **The second migration blocks writes to four tables while it writes the older rows' records.** → Token issue, refresh, the Home mint and revocation wait for that transaction (D5). Its length grows with the count of live credential rows. The rollout reads that count before the merge. -- **A migration meets its lock timeout or a deadlock.** → The job fails and records no schema release, so the build does not deploy. The operator starts the job again. +- **The second migration blocks writes to five tables while it writes the older rows' records.** → Token issue, refresh, the Home mint, revocation and cell changes wait for that transaction (D5). Its length grows with the rows that its backfill reads. The rollout reads that count before the merge, with the query of task 7.4. +- **A migration meets its lock timeout or a deadlock.** → The job fails and records no schema release, so the build does not deploy. The operator starts the job again. If the production build already failed after its 15-minute wait, the operator redeploys it once the job is green, because nothing rebuilds it. - **A hand-typed grant gives a role the trigger right.** → The lock does not hold against that role until the grants script runs again. The runbook's checks list the grant. - **A hand-typed grant gives a role other than the owner a create right.** → The role may then reach code that runs as the schema owner (D2). The grants script does not revoke the right. The runbook's checks list the right and any schema the role created, and the operator revokes the right and drops the schema. - **The migration job cannot reach the database, or the CI service is down.** → Builds fail after the wait and the previous deployment serves. The operator runs `scripts/migrate.ts` by hand with the credential from the operator's secret store, which also records the schema release. @@ -393,6 +413,7 @@ The claim is: the database records every credential that the account service iss - **The gateway release rolls too early.** → A ticket signed before the web release is refused for the rest of its life. The owner asks for the download again. The task states the wait. - **Each deploy waits for the migration job.** → A deploy takes longer by the job's run time. The job installs dependencies and connects once. - **The schema owner's exemption hides a broken flow in ordinary tests.** → Most suites run as the role that owns the schema, so a guard never refuses them. Only the suites that connect as the web app's role prove the flows. +- **Nothing runs the D12 checks.** → The operator runs the runbook's checks on demand. Nothing schedules them yet, so detecting a disabled recording trigger, a grant mismatch or a credential without a record is best-effort until a scheduled job runs them. The first check reads the credential tables in full, so that job needs an index on `created_at` or a different first query. It is a later step. ## Migration Plan @@ -401,7 +422,7 @@ The claim is: the database records every credential that the account service iss 1. Before the merge, the operator creates the protected environment and its secret, and creates the audit role. The operator confirms that the job's runner can reach the migration address, and reads the repository settings and the database facts that the lock depends on. 2. The operator approves the merge. The job applies the migrations and the grants. The lock and the log are in force from that moment, and the web app starts to store ticket rows. 3. The operator reads the log and runs the flows once against production. -4. The operator removes the schema-owner credential from every web deployment environment, rotates it, and checks the preview and development variables. +4. The operator removes the schema-owner credential from every web deployment environment, rotates it, and checks the preview and development variables. The operator then starts the migration job once more, not as a dry run, and reads the rights of the web app's role. 5. The operator rolls the gateway release that requires ticket rows, at least one day after step 2. 6. The evidence goes to the owner of the privacy page text. @@ -409,7 +430,7 @@ Rollback: - **A flow fails under the lock.** The schema owner runs the emergency statement from the runbook. A commit then fixes the grants script or the guard. - **A revert before step 4.** The revert restores the build-time migration, and its build applies the earlier grants script. The web app's role regains update and delete on every table, the new ones included. It gains no trigger right, because that script grants none. The guards still refuse a change to a fixed or one-way column and a delete of an identity row. They also refuse every write to the log and to `schema_releases`, and every update of a ticket row. The migrations' tables and triggers stay. -- **A rebuild of an earlier commit between steps 2 and 4.** It applies the earlier grants script in the same way. The next run of the migration job restores the rights. Step 4 follows step 2 closely for that reason. +- **The earlier grants script returns between steps 2 and 4.** Two builds can apply it. The first is the in-flight production build of the commit before this change: it waits on the migration job's advisory lock, then applies the earlier grants script after the job's own. The second is a redeploy of an earlier commit. Each leaves the web app's role with the wide state, the log included. A dry run applies no grants. The non-dry run in step 4 (task 7.7) restores the narrow rights, and the runbook's check of the role's rights lists any that remain. Step 4 follows step 2 closely for that reason. - **After step 4.** The earlier build script cannot migrate. With no schema-owner connection string, it falls back to the web app's connection string, which holds no right on `schema_migrations`, and the build fails. A revert of this change is then a fix forward through the migration job. A promotion of an existing deployment still works, because it runs no build. - **The gateway.** Roll the gateway back to its previous image before the web app goes back past this change (D8). @@ -417,5 +438,5 @@ Rollback: Each question has a default that this design already uses. -1. **Retention.** The design keeps a record until 90 days after its credential expires. A longer period keeps evidence for longer. It also keeps a finer record of when each account was active, and costs storage in proportion. Home's two-minute tokens are about three quarters of the log, so their retention decides its size. The period becomes part of the public claim. +1. **Retention.** The design keeps a record until 90 days after its credential expires or, for a service credential, ends. A longer period keeps evidence for longer. It also keeps a finer record of when each account was active, and costs storage in proportion. The period becomes part of the public claim. If size is the concern, the larger lever is the Home mint on every 30-second poll. The non-goals leave that mint out of this change, and a later change can take it. Cutting retention is not the cheaper fix: it removes evidence for every kind of credential, while changing the mint rate shrinks only Home's records. 2. **The migration job's runner.** A hosted runner may not reach the migration address. The choice is then a runner inside the database's network, or opening the address to hosted runners. The first keeps the address closed. It adds a machine to maintain, and a runner group that only this workflow may use. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md index 368ef051..0623a9c6 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/proposal.md @@ -1,14 +1,14 @@ ## Why -Substrate's web app signs users in and issues the credentials that the Exomem Cloud gateway admits. The grants script (`scripts/exomem-cloud-grants.sql`) gives its database role update and delete rights on every table in the schema, OAuth rows included. With them it can re-point a grant to another tenant or overwrite a token's digest with no insert. Nothing records an issuance. The build script (`vercel-build` in `package.json`) runs migrations with the schema-owner connection string, so the build's environment must hold that credential, and a compromised build could also remove any database control. So the privacy page can claim nothing about the account service. This change makes one claim true. The database records every credential that the account service issues for a cell, in a log that the account service cannot alter. The account service also cannot change a credential row's identity or revive a revoked credential. Replacing a credential takes an insert, which the log records. +Substrate's web app signs users in and issues the credentials that the Exomem Cloud gateway admits. The grants script (`scripts/exomem-cloud-grants.sql`) gives its database role update and delete rights on every table in the schema, OAuth rows included. With them it can re-point a grant to another tenant or overwrite a token's digest with no insert. Nothing records an issuance. The build script (`vercel-build` in `package.json`) runs migrations with the schema-owner connection string, so the build's environment must hold that credential, and a compromised build could also remove any database control. So the privacy page can claim nothing about the account service. This change makes one claim true. The database records every credential that the gateway admits from the account service, in a log that the account service cannot alter. Those credentials are OAuth access and refresh tokens, token families, service credentials and download tickets. Export, import and deletion grants are outside the log. On the column-locked tables, the account service also cannot change a credential row's identity or revive a revoked credential. Reviewer credentials stay writable by the web app's role (design limit 12). Replacing a credential takes an insert, which the log records. ## What Changes - **Schema releases leave the web build.** A continuous-integration job in a protected environment applies migrations and the grants script for the tip of `main`. It then records a schema release for that commit, and records each overtaken commit as superseded. The production build runs no migration. It waits for its commit's schema release and fails at once when its commit is superseded. The schema-owner credential leaves every web deployment environment, and the operator rotates it. **BREAKING** for the operator: `SKIP_VERCEL_MIGRATE` and the migration procedure that pulls production variables from the web deployment go away. -- **Identity lock.** Guard triggers refuse every change to an identity field of a grant, token family, access token, refresh token, client or service credential. They also refuse a change to a tenant's owner. A revocation time and a consumption time change only from empty to a time. Guards refuse a delete of a grant, client, tenant, user, service credential or reviewer credential. Each guard holds for every role except the schema owner, whatever select, insert, update, delete and truncate rights that role holds. A guard checks the stored row, so no trigger that runs before it can slip a change past. The web app's database role also keeps update rights only on the columns its flows change. +- **Identity lock.** Guard triggers refuse every change to an identity field of a grant, token family, access token, refresh token, client or service credential. They also refuse a change to a tenant's owner and to a cell's identifier or tenant. A revocation time and a consumption time change only from empty to a time. Guards refuse a delete of a grant, client, tenant, user, cell, service credential or reviewer credential. Each guard holds for every role except the schema owner, whatever select, insert, update, delete and truncate rights that role holds. A guard checks the stored row, so no trigger that runs before it can slip a change past. On the five column-locked tables that the grants script narrows (grants, token families, access tokens, refresh tokens and service credentials), the web app's database role also keeps update rights only on the columns its flows change. - **The trigger right stays with the schema owner.** A role that holds the trigger right on a table can run its own code as the schema owner, and no guard holds against that. The grants script therefore revokes that right on every table in the schema from every other role, on every run. `PUBLIC` holds no execute right on the functions that this change adds. Every function that the database can run as the schema owner for another role pins its search path, so a role's own operator cannot run in place of the built-in one. - **No switch.** The lock and the log are in force once the migrations apply. Relaxing either one takes a migration or a grants change, which is a reviewed commit. -- **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential expires. +- **Issuance log.** An owner-owned trigger writes one record for every access token, refresh token, token family, service credential and download ticket row, in the inserting transaction. The log refuses every write that the schema owner does not run. A read-only audit role reads it in bounded ranges. A record is kept until 90 days after its credential stops being usable. That is its expiry or, for a token family and a service credential, the time it is revoked or its row is deleted, if that comes first. A service credential has no expiry. The session policy sets a token family's expiry (365 days from sign-in by default, at most 730) and a refresh token's expiry (30 days idle by default, at most 90, never past its family's expiry). The database bounds no expiry, so a role that writes a far expiry only lengthens retention. A database trigger on the cells table revokes a tenant's service credentials when its cell is deleted, so after the deletion a token family's record and a service credential's record last 90 days. The migration revokes once the service credentials of accounts that a release before this one deleted, so no record stays open. It writes records only for rows that the prune would keep. An access token's record and a refresh token's record last until 90 days after its own expiry. The longest window after deletion is the refresh token's idle bound plus 90 days: 120 days by default, 180 at most. No flow but the schema owner deletes a record. - **Download tickets get a stored row.** A download ticket is a credential that the web app signs with a key it holds. Today no row backs it. The web app now stores one row for each ticket, and the gateway refuses a ticket without its row. - **Proof as the real roles.** Tests on a disposable PostgreSQL run every legitimate flow as the web app's role. They run each attack as that role twice: with the new rights, and with select, insert, update, delete and truncate on every table. @@ -28,12 +28,12 @@ The account service stays the sign-in provider, so it can still issue a credenti ## Impact -- **Database:** two migrations. The first adds the schema release table and the guards, and pins the search path of the functions that run as the schema owner. The second adds the issuance log, the recording triggers and the download ticket table. It blocks writes to the token and service credential tables while it records existing rows. Each sets a lock timeout. `scripts/exomem-cloud-grants.sql` gains the lock's rights, the trigger and execute revokes, and the audit role's rights. No new grants file. +- **Database:** two migrations. The first adds the schema release table and the guards, and pins the search path of the functions that run as the schema owner. The second adds the issuance log, the recording triggers, the download ticket table a trigger on cells that revokes a deleted tenant's service credentials, and a trigger on service credentials that refuses a new one for a tenant without a live cell. It blocks writes to the cell, token and service credential tables while it records existing rows. Each sets a lock timeout. `scripts/exomem-cloud-grants.sql` gains the lock's rights, the trigger and execute revokes, and the audit role's rights. No new grants file. - **Deployment:** a new workflow under `.github/workflows/`, `scripts/migrate.ts`, the `vercel-build` script and the script it calls. Each deploy waits for the migration job before it builds. -- **Web app:** the download handler stores a ticket row, and the reconcile job prunes ticket rows and issuance records. No other flow changes its SQL. +- **Web app:** the download handler stores a ticket row, and the reconcile job prunes ticket rows and issuance records. The prune is a lane beside the job's other lanes, so another lane's failure does not stop it, and its own failure fails the job's response. No other flow changes its SQL. - **Gateway:** one release that requires the ticket row. It rolls at least one maximum ticket lifetime after the web release, and it rolls back before the web app does. - **Other changes:** the gateway requirement stands beside the download-ticket requirements of the active change `add-cloud-media-access`. Archive that change first; `tasks.md` holds the step. - **Tests:** `cloud-grants-postgres.integration.test.ts` changes its assertion that the web app's role holds every right on every non-Cloud table. A fixture step that the lock refuses moves to the role that owns the schema. - **Runbooks:** `docs/runbooks/production-keys-and-storage.md`, `docs/runbooks/exomem-cloud-operations.md`, `docs/runbooks/vercel-deployments.md` and the README's migration section. - **Operator steps:** the protected environment and its secret, the audit role, the settings and database checks, and the merge that applies the lock and the log. Then removing and rotating the schema-owner credential, and rolling the gateway. `tasks.md` lists each one. -- **Storage and privacy:** the issuance log is a new retained record, and each backup grows by its size. It shows when each account's apps and Home were active, by opaque identifier, for the retention period. The privacy page must say so when it states the claim. +- **Storage and privacy:** the issuance log is a new retained record, and each backup grows by its size. It shows when each account's apps and Home were active, by opaque identifier, for the retention period above. The privacy page must say so when it states the claim. diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md index 9c04b3ff..274e6c20 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-cloud-service-credentials/spec.md @@ -35,3 +35,52 @@ This requirement binds every role except the schema owner. The database SHALL re - **WHEN** any role inserts a service credential row - **THEN** the issuance log gains one record that names the row and its tenant - **AND** the record holds neither the principal nor the secret digest + +### Requirement: Deleting a tenant's cell revokes its service credentials + +A database trigger SHALL revoke every unrevoked service credential of a tenant when its cell becomes deleted or a cell not yet deleted is deleted, at the database clock's time with no revoking principal. The migration SHALL do the same for each tenant with only deleted cells. No other tenant's credential SHALL change. The credential's issuance record SHALL then end. A second trigger SHALL refuse a new credential for a tenant with no cell that is not deleted, and lock that cell's row. + +#### Scenario: A transaction with a fixed snapshot deletes a cell + +- **WHEN** a transaction running outside read committed tries to delete a live cell or set it to deleted +- **THEN** the database refuses the deletion and the cell and its credentials keep their state + +#### Scenario: An account's deletion finishes + +- **WHEN** an owner confirms the account's deletion and the finish scrubs the tenant +- **THEN** each of the tenant's service credentials is revoked, with the database clock's time and no revoking principal +- **AND** each credential's issuance record has an end +- **AND** another tenant's service credential stays live and its record stays open + +#### Scenario: A release that does not revoke the credentials deletes the cell + +- **WHEN** the web app's role sets a tenant's cell to deleted by any statement +- **THEN** each of the tenant's unrevoked service credentials is revoked, with the database clock's time and no revoking principal + +#### Scenario: The cell is deleted again + +- **WHEN** the web app's role sets a cell that is already deleted to deleted again +- **THEN** no revocation time changes + +#### Scenario: A credential is inserted for a tenant whose only cell is deleted + +- **WHEN** a service credential is inserted for a tenant that has no cell other than deleted ones +- **THEN** the insert is refused and no credential row is stored +- **AND** the service credential request answers `SERVICE_CREDENTIAL_TENANT_INELIGIBLE` + +#### Scenario: A deletion starts while a credential insert is open + +- **WHEN** a transaction has inserted a service credential and another transaction sets the tenant's cell to deleted before the first commits +- **THEN** the deletion waits for the insert to commit +- **AND** the credential is then revoked with the database clock's time and its record has an end + +#### Scenario: A credential insert waits for a deletion + +- **WHEN** a service credential insert waits for a transaction that sets the tenant's cell to deleted, and that transaction commits +- **THEN** the insert is refused and no credential row is stored + +#### Scenario: A tenant that an earlier release deleted + +- **WHEN** the migration runs and a tenant has no cell other than deleted ones +- **THEN** each of its unrevoked service credentials is revoked, with the migration's time and no revoking principal +- **AND** the credentials of a tenant that has a live cell stay live diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-gateway/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-gateway/spec.md index 745594b9..0f42e754 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-gateway/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-gateway/spec.md @@ -2,7 +2,7 @@ ### Requirement: The gateway admits a download ticket only with its stored row -The web app SHALL store one row for each download ticket that it signs. The row SHALL name the ticket's token family, grant, path digest and expiry. The gateway SHALL refuse a ticket that has no matching unexpired row, whatever its signature says. The database SHALL refuse every update of a ticket row that the schema owner does not run. Every ticket row insert SHALL write an issuance record. +The web app SHALL store one row for each download ticket that it signs. The row SHALL name the ticket's token family, path digest and expiry. The gateway SHALL refuse a ticket that has no matching unexpired row, whatever its signature says. The database SHALL refuse every update of a ticket row that the schema owner does not run. Every ticket row insert SHALL write an issuance record. #### Scenario: A signed ticket has no row @@ -34,7 +34,7 @@ The web app SHALL store one row for each download ticket that it signs. The row #### Scenario: A ticket row is inserted - **WHEN** the web app stores a ticket row -- **THEN** the issuance log gains one record that names the row, its grant, token family, tenant, user and expiry +- **THEN** the issuance log gains one record that names the row, its token family, and the grant, tenant, user and expiry that follow from that family - **AND** the record holds no path and no path digest #### Scenario: The row check adds no round trip diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md index afc52705..8481f39d 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/exomem-hosted-mcp-oauth/spec.md @@ -2,7 +2,12 @@ ### Requirement: OAuth identity fields are unchangeable once written -This requirement binds every role except the schema owner. The database SHALL refuse every change to an identity field of an OAuth grant, token family, access token, refresh token or client, and to a tenant's owner. It SHALL let a revocation time and a consumption time change only from empty to a time. It SHALL refuse a delete of a grant, client, tenant, user or reviewer credential. Each refusal SHALL hold whatever select, insert, update, delete and truncate rights the role holds. +The database SHALL refuse a change to an identity field of a grant, token family, access token, refresh token or client, a tenant's owner, and a cell's identifier or tenant, and a delete of a grant, client, tenant, user, reviewer credential or cell. A grant, token family, access token or refresh token SHALL change its revocation or consumption time only from empty. Each refusal SHALL bind all roles but the schema owner, whatever rights they hold. Design limits 5, 7 and 12 list exceptions. + +#### Scenario: A cell is re-pointed + +- **WHEN** the web app's role changes a cell's tenant or identifier, or deletes a cell row +- **THEN** the database refuses the statement and the cell row is unchanged #### Scenario: A grant is re-pointed @@ -96,7 +101,7 @@ This requirement binds every role except the schema owner. The database SHALL re ### Requirement: The web app's database role holds only the OAuth rights its flows need -The web app's database role SHALL hold update rights only on the columns its flows change. It SHALL hold no delete right on grants, clients, tenants, users or reviewer credentials. The grants script SHALL apply these rights on every run, and a second run SHALL change nothing. The gateway's and the controller's rights on these tables SHALL stay as they were. +On the grants, token families, access tokens, refresh tokens and service credentials tables, the web app's database role SHALL hold update rights only on the columns its flows change. It SHALL hold no delete right on grants, clients, tenants, users or reviewer credentials. The grants script SHALL apply these rights on every run, and a second run SHALL change nothing. The gateway's and the controller's rights on these tables SHALL stay as they were. #### Scenario: The rights are exact @@ -132,7 +137,7 @@ The web app's database role SHALL hold update rights only on the columns its flo ### Requirement: Only the schema owner can attach a trigger or call the recording routine -The grants script SHALL revoke the trigger right on every table in the schema from every role except the table's owner, on every run. Every non-extension SQL or PL/pgSQL function that runs as the schema owner for another role SHALL pin a search path naming only schemas owned by the schema owner, the bootstrap superuser or the database's owner. `PUBLIC` SHALL not execute the guard, recording or prune routine. Only the web app's role SHALL execute the prune routine. +The grants script SHALL revoke the trigger right on every table in the schema from every role except the table's owner, on every run. Every non-extension SQL or PL/pgSQL function that runs as the schema owner for another role SHALL pin a search path naming only schemas owned by the schema owner, the bootstrap superuser or the database's owner. `PUBLIC` SHALL not execute the guard, recording or prune routine. Only the web app's role SHALL be granted the prune routine. #### Scenario: A role was given the trigger right by hand @@ -164,7 +169,7 @@ The grants script SHALL revoke the trigger right on every table in the schema fr ### Requirement: Every issued credential is recorded -The database SHALL write one issuance record for every access token, refresh token, token family, service credential and download ticket row. It SHALL write the record in the transaction that inserts the row. A credential row SHALL NOT be inserted without its record. No role except the schema owner SHALL be able to stop the recording. +The database SHALL write one issuance record for every access token, refresh token, token family, service credential and download ticket row. It SHALL write the record in the transaction that inserts the row. A credential row SHALL NOT be inserted without its record. Whatever select, insert, update, delete and truncate rights a role holds, no role except the schema owner SHALL be able to stop the recording. Design limit 7 lists what else can. #### Scenario: Home mints an access token @@ -212,9 +217,14 @@ The database SHALL write one issuance record for every access token, refresh tok #### Scenario: Credentials that predate the log - **WHEN** the migration that creates the log runs -- **THEN** it writes one record for each credential row that already exists, after the recording triggers exist and in the same transaction +- **THEN** it writes one record for each credential row that already exists and whose record the prune routine would keep, after the recording triggers exist and in the same transaction - **AND** each of those records is marked as backfilled, carries the migration's time and names the schema owner as its database role +#### Scenario: Credentials that ended long before the log + +- **WHEN** the migration runs and a token row expired more than 90 days earlier +- **THEN** it writes no record for that row + ### Requirement: The issuance log accepts writes from the schema owner only The issuance log SHALL refuse every insert, update, delete and truncate that the schema owner does not run. That SHALL hold whatever select, insert, update, delete and truncate rights the acting role holds. Apart from the schema owner, only the recording routine and the prune routine SHALL write the log. The web app's, the gateway's and the controller's database roles SHALL hold no right on it. @@ -236,7 +246,7 @@ The issuance log SHALL refuse every insert, update, delete and truncate that the ### Requirement: Issuance records outlive their credentials and stay cheap to write -An issuance record SHALL be kept until at least 90 days after its credential expires, and a record whose credential has no expiry SHALL be kept. Only the prune routine SHALL delete records, in bounded batches from the scheduled maintenance. Recording SHALL add less than one millisecond to the median latency of the Home mint transaction at the 10,000-tenant load target. +An issuance record SHALL be kept until at least 90 days after its credential expires. A token family's record SHALL end when the family is revoked or its row is deleted, if that is earlier. A service credential has no expiry, so its record SHALL end the same way. Only the prune routine SHALL delete records, in bounded batches from the scheduled maintenance. Recording SHALL add less than one millisecond to the median latency of the Home mint transaction at the 10,000-tenant load target. #### Scenario: The scheduled maintenance prunes the log @@ -244,16 +254,39 @@ An issuance record SHALL be kept until at least 90 days after its credential exp - **THEN** the prune routine deletes at most 10,000 records whose credential expired more than 90 days ago - **AND** the job reports how many records it deleted +#### Scenario: Another lane of the reconcile job fails + +- **WHEN** another lane of the reconcile job fails +- **THEN** the prune routine still runs +- **AND** the job's response reports its counts, or `null` for a part that failed, and a failed part fails the response + #### Scenario: The web app's role calls the prune routine early - **WHEN** the web app's role calls the prune routine any number of times - **THEN** no record inside its retention is deleted -#### Scenario: A credential without an expiry +#### Scenario: A live service credential -- **WHEN** a service credential has no expiry +- **WHEN** a service credential is live - **THEN** the prune routine never deletes its record +#### Scenario: A service credential ends + +- **WHEN** the web app's role revokes a service credential, with any revocation time, or the schema owner deletes its row, or a tenant's cell deletion revokes it +- **THEN** the record's end is the database clock's time at that statement +- **AND** the prune routine deletes the record only after 90 days from then + +#### Scenario: A token family ends before it expires + +- **WHEN** the web app's role revokes a token family, with any revocation time, or deletes its row, or an account's deletion cascades to it +- **THEN** the record's end is the database clock's time at that statement +- **AND** the prune routine deletes the record only after 90 days from then + +#### Scenario: A live token family + +- **WHEN** a token family is neither revoked nor deleted +- **THEN** its record's end stays the family's expiry + #### Scenario: The Home mint at the load target - **WHEN** the same Home mint transaction runs with and without the guards and the recording, on the same machine and on data generated for the load target @@ -267,7 +300,7 @@ An issuance record SHALL be kept until at least 90 days after its credential exp ### Requirement: The issuance log is read in bounded ranges, without the schema-owner credential -A read-only audit role SHALL hold select on the issuance log and on the columns that its checks compare, and no other right. Each documented check SHALL read a bounded range of records. A reader SHALL be able to list one tenant's records a page at a time through an index. +A read-only audit role SHALL hold select on the issuance log and on the columns that its checks compare, and no other right. Each documented read of the log SHALL use an indexed lookup or read a bounded range. The on-demand credential check SHALL page through each source table by its primary key. A reader SHALL be able to list one tenant's records a page at a time through an index. #### Scenario: The audit role reads the log @@ -278,12 +311,23 @@ A read-only audit role SHALL hold select on the issuance log and on the columns #### Scenario: A check reads a range - **WHEN** the operator runs a documented check over a range of record identifiers -- **THEN** the check reads that range through the primary key and no other record +- **THEN** the check reads one new page through the primary key and replays recent records through the previous stop using the time index +- **AND** each successful page advances toward the sweep's fixed target even if new log rows arrive or the saved stop is pruned + +#### Scenario: The credential check lists only credentials that must have a record + +- **WHEN** the operator runs the check for credential rows without a record +- **THEN** it looks up the credential kind and identifier for credentials created in the last 90 days and from the second migration onward +- **AND** a record from before a credential's creation cannot cover a later reuse of its identifier +- **AND** a credential older than 90 days is not listed, because the prune may have deleted its record, and that includes a live service credential +- **AND** the fixed upper time edge is no later than one hour before the sweep starts +- **AND** the next sweep includes the upper time edge +- **AND** a missing credential is listed even if pruning removed the closest issuance records or the log is empty #### Scenario: A record commits late -- **WHEN** a record commits after a run of the checks has read past its identifier, less than one hour late -- **THEN** the next run reads that record, because each run starts one hour of records before the point where the previous run stopped +- **WHEN** a record in a transaction open for up to one hour commits after a check has read past its identifier +- **THEN** the next check reads that record using the previous snapshot's time window even when record time and identifier order differ #### Scenario: The checks name what they find @@ -292,6 +336,7 @@ A read-only audit role SHALL hold select on the issuance log and on the columns - **AND** they list records whose database role is not the web app's role, except backfilled records - **AND** they list each role other than the owner that holds the trigger right on a table in the schema - **AND** they list each role that the web app's role is a member of +- **AND** they list each right that the web app's role holds on the log, `schema_releases`, ticket rows and, table-wide, the locked tables beyond what the grants script gives it - **AND** they list each create right that a role other than a superuser, the schema owner or `pg_database_owner` holds on the database or on a schema outside `pg_catalog` and `information_schema`, and each schema that another role owns #### Scenario: One tenant's records are listed diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md index cf7f0664..b624fdfe 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/specs/substrate-database-releases/spec.md @@ -2,7 +2,7 @@ ### Requirement: Production migrations run from a protected job outside the web deployment -Production migrations and the grants script SHALL run from a continuous-integration job in a protected environment that accepts only the default branch. That environment SHALL be the only automated holder of the schema-owner credential. The job SHALL apply only the tip of the default branch, one run at a time. It SHALL record a schema release for its commit only after the migrations and the grants script succeed. +Production migrations and the grants script SHALL run from a continuous-integration job in a protected environment that accepts only the default branch. That environment SHALL be the only automated holder of the schema-owner credential. The job SHALL apply only the tip of the default branch, one run at a time, whatever commit started the run. It SHALL record a schema release for that tip only after the migrations and the grants script succeed. #### Scenario: A commit lands on the default branch @@ -22,13 +22,19 @@ Production migrations and the grants script SHALL run from a continuous-integrat #### Scenario: A run starts for a commit that is no longer the tip - **WHEN** a run starts, or someone restarts one, and its commit is no longer the tip of the default branch -- **THEN** the job applies nothing -- **AND** it records that commit as superseded, unless the commit already has a row +- **THEN** the job applies the tip of the default branch as it stands when the run starts, and records that tip as released +- **AND** it records the tip's first-parent ancestors, up to 100, that have no row as superseded -#### Scenario: A released commit's run is restarted +#### Scenario: A restarted run replaces the waiting run of a newer push -- **WHEN** someone restarts the run of a commit that is recorded as released and is no longer the tip -- **THEN** the job applies nothing and the commit stays released +- **WHEN** someone restarts the run of an older commit while the run of a newer push waits, and the restarted run replaces the waiting one +- **THEN** the restarted run releases the newer tip, and no push stays without a release + +#### Scenario: The default branch moves while the job installs + +- **WHEN** a push lands after the job started and before it applies +- **THEN** the job reads the tip once more just before it applies, finds that it moved, and applies nothing +- **AND** the run that the push started applies the new tip #### Scenario: A recorded commit never changes @@ -39,12 +45,12 @@ Production migrations and the grants script SHALL run from a continuous-integrat - **WHEN** a second commit lands while the job runs for the first - **THEN** the runs do not overlap, and the later commit's run applies last -- **AND** that run records as superseded each commit between the previous schema release and its own that has no row +- **AND** that run records as superseded the tip's first-parent ancestors, up to 100, that have no row #### Scenario: The operator runs the job by hand - **WHEN** the operator starts the job for the default branch as a dry run -- **THEN** the job lists the pending migrations and changes nothing +- **THEN** the job lists the pending migrations of the tip and changes nothing, and it takes no migration lock and creates no table, so an empty database stays empty - **AND** it neither cancels nor replaces a run that applies migrations #### Scenario: A migration cannot take its lock @@ -96,7 +102,8 @@ A production build of the web app SHALL run no migration. It SHALL finish only a #### Scenario: The serving release meets the new schema - **WHEN** the job has applied a commit's migrations and grants, and that commit's build has not finished -- **THEN** every flow of the release that is still serving keeps working +- **THEN** existing user flows keep working under the new schema and grants +- **AND** during the migration that adds the service credential guard, the operator waits for the new web release before issuing service credentials #### Scenario: A preview or development build diff --git a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md index b0b5f8b1..9d96aea8 100644 --- a/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md +++ b/openspec/changes/lock-cloud-identity-rows-and-record-issuance/tasks.md @@ -1,13 +1,13 @@ Groups 1 to 6 are one implementation PR. Group 7 is the live rollout, and every step in it is the operator's. The change ships two migrations, which take the -next free numbers: 0100 and 0101 at the time of writing. The first holds +next free numbers: 0101 and 0102 at the time of writing. The first holds `schema_releases` and the guards. The second holds the log, the ticket table, the recording triggers and the records for existing rows (D5). `design.md` names each decision as D1 to D12. ## 1. Schema release pipeline (D9, D10) -- [ ] 1.1 In the first migration, set a lock timeout of five seconds for the +- [x] 1.1 In the first migration, set a lock timeout of five seconds for the transaction, then take D5's locks in D5's order with one `LOCK TABLE` statement. Create `schema_releases` (commit, status, release time) with a guard that refuses every write unless the schema owner runs it. Revoke every @@ -15,29 +15,35 @@ names each decision as D1 to D12. give the web app's role select on it and nothing else. Verify: as the web app's role, a select succeeds. An insert, update, delete and truncate are refused, also when the role holds those rights on the table. -- [ ] 1.2 In `scripts/migrate.ts`, accept a commit and a list of superseded +- [x] 1.2 In `scripts/migrate.ts`, accept a commit and a list of superseded commits, each as a full 40-character hash. With a commit, record its schema release after the grants script succeeds, and record each listed commit as - superseded. Record with an insert that leaves an existing row unchanged. Add - a mode that only records commits as superseded. Verify on a disposable - PostgreSQL: a successful run with a commit records the release. A failed - migration, a failed grants script, a dry run and a run with no commit record - none. A commit that already has a row keeps its status. A malformed commit - fails before the runner connects. -- [ ] 1.3 Add the migration workflow under `.github/workflows/`. It starts on a + superseded. Record with an insert that leaves an existing row unchanged. A dry + run takes no migration lock and creates no table, and an absent tracking + table counts as an empty applied set. Verify on a disposable PostgreSQL: a + successful run with a commit records the release. A failed migration, a + failed grants script, a dry run and a run with no commit record none. A + commit that already has a row keeps its status. A malformed commit fails + before the runner connects. A dry run on an empty schema leaves it empty, + while another session holds the migration lock. +- [x] 1.3 Add the migration workflow under `.github/workflows/`. It starts on a push to `main` and by hand, in the protected environment, with a dry-run input. It has a concurrency group that never cancels a running job, and a - dry run stays outside that group. It has the tip-of-`main` check. It lists - the superseded commits from the checkout's history. Only the migrate step + dry run stays outside that group. It checks out the tip of `main` whatever + commit started the run. After the install, and just before the migrate + step, it reads the tip again and applies nothing when `main` moved. It lists + the tip's superseded ancestors from the checkout's history. Only the migrate step receives the secret. Dependencies install with `npm ci --ignore-scripts`. Every action is pinned to a commit. Add a test that reads the workflow files: only this workflow names the protected environment, and it starts on - no other event. Verify: in a scratch clone, the tip check passes at the tip - and stops one commit behind it. After an install without scripts, a dry run + no other event, and with no path filter on the push. Verify: in a scratch + clone, the tip check applies at the tip and stops once `main` has moved on. + On a scratch remote, a run that an older commit started releases the newer + tip and records the older commit as superseded. After an install without scripts, a dry run of `scripts/migrate.ts` succeeds. The test fails when a second workflow names the environment. The reviewer reads the three hardening properties in the diff. -- [ ] 1.4 Replace `scripts/vercel-maybe-migrate.ts` with a script that reads +- [x] 1.4 Replace `scripts/vercel-maybe-migrate.ts` with a script that reads the build's schema release, and point `vercel-build` at it. Keep the control-plane key check. Verify: the script continues on `released`, fails at once on `superseded`, and fails after its bounded wait when no row @@ -48,77 +54,127 @@ names each decision as D1 to D12. ## 2. Identity lock (D2, D3, D4) -- [ ] 2.1 In the first migration, add the guard function and the triggers of +- [x] 2.1 In the first migration, add the guard function and the triggers of D2. Fixed and one-way columns get an `AFTER UPDATE` row trigger with a `WHEN` clause. Deletes get an `AFTER DELETE` row trigger and a `BEFORE TRUNCATE` - trigger. Build the guard function by D2's rules and revoke its execute right - from `PUBLIC`. Change no rule of the three guards that exist today. Verify: + trigger. Guard `exomem_cloud_cells` as well: an `AFTER UPDATE` row trigger on + `cell_id` and `tenant_id`, and the delete and truncate triggers. Build the + guard function by D2's rules and revoke its execute right from `PUBLIC`. + Change no rule of the three guards that exist today. Verify: tasks 5.1 and 5.2. -- [ ] 2.2 In `scripts/exomem-cloud-grants.sql`, add the lock's section after the +- [x] 2.2 In `scripts/exomem-cloud-grants.sql`, add the lock's section after the schema-wide grant. It revokes update and delete on the D2 tables from the web app's role. It then grants the D2 rights, each guarded on its table and column existing. It revokes the trigger right on every table in the schema from `PUBLIC` and from every role that is not the table's owner. Update the script's header, which names the exceptions to the schema-wide grant. Verify: task 5.6. -- [ ] 2.3 In `cloud-grants-postgres.integration.test.ts`, change the assertion +- [x] 2.3 In `cloud-grants-postgres.integration.test.ts`, change the assertion that the web app's role holds every right on every non-Cloud table. It now names the tables this change takes out. Verify: the suite passes, and the assertion fails if the lock's section is removed from the grants script. -- [ ] 2.4 Move each fixture step that changes a fixed column or deletes an +- [x] 2.4 Move each fixture step that changes a fixed column or deletes an identity row as the web app's role to the role that owns the schema. Change no assertion. Verify: every existing PostgreSQL suite passes with the guards in place. -- [ ] 2.5 In the first migration, pin `search_path` on each function of D2's +- [x] 2.5 In the first migration, pin `search_path` on each function of D2's "The create right": the schema owner's trigger and `SECURITY DEFINER` functions in the schema, and each SQL or PL/pgSQL function in the schema that a constraint, a column default or an index calls; only functions that the schema owner owns and that belong to no extension. Read the set from the catalog. Give a function that qualifies every name `pg_catalog, pg_temp`. Give every other one - `pg_catalog`, then those schemas of `current_schemas(false)` that the schema - owner, the bootstrap superuser or `pg_database_owner` owns, then `pg_temp`. - Every function of this change pins its path at creation. Verify: task 5.6, - and every existing PostgreSQL suite passes with the pins in place. + `pg_catalog`, then every schema of `current_schemas(false)`, then `pg_temp`. + Raise an error that names each schema of that path which the schema owner, + the bootstrap superuser and `pg_database_owner` do not own, so the migration + fails and the old schema keeps serving. Every function of this change pins + its path at creation. Verify: task 5.6, a migration that fails on a schema + of another owner and applies on the same database without it, and every + existing PostgreSQL suite passes with the pins in place. ## 3. Issuance log (D5, D6, D12) -- [ ] 3.1 In the second migration, set a lock timeout of five seconds for the +- [x] 3.1 In the second migration, set a lock timeout of five seconds for the transaction, then take D5's locks in D5's order with one `LOCK TABLE` statement. Create `exomem_cloud_issuance_log` with its kind constraint, its - three indexes and its guard. Add the recording function and revoke its - execute right from `PUBLIC`. Add one - `AFTER INSERT` trigger on each of the five credential tables. Revoke every + five indexes and its guard. The audit uses the credential lookup and the + partial index for late-commit replay. Add the recording function and revoke its execute + right from `PUBLIC`. Add one `AFTER INSERT` trigger on each of the five + credential tables, and on the service credential and token family tables an + update trigger on the revocation time and a delete trigger that end the + record (D6). Revoke every right on the log in the same transaction. After the triggers exist, in the - same transaction, write one backfilled record for each credential row that - already exists. Verify: tasks 5.3 and 5.4. -- [ ] 3.2 Add the prune function with its batch of 10,000 records and its + same transaction, write one backfilled record for each credential row whose + record the prune would keep: its end is empty or at most 90 days old. Verify: + tasks 5.3 and 5.4. +- [x] 3.2 Add the prune function with its batch of 10,000 records and its 90-day constant. Revoke its execute right from `PUBLIC` and give it to the web app's role. Call it from the reconcile job beside the OAuth maintenance, and report the deleted count. Verify: a record inside its retention survives - any number of calls, a record past it is deleted, and a service credential's - record is never deleted. -- [ ] 3.3 In `scripts/exomem-cloud-grants.sql`, revoke every right on the log + any number of calls, and a record past it is deleted. A live service + credential's record is never deleted. A revoked credential's record, and a revoked + or deleted token family's, takes the database clock's time, whatever + revocation time the row names, and is deleted 90 days after. A live + family's record keeps its expiry. +- [x] 3.3 In `scripts/exomem-cloud-grants.sql`, revoke every right on the log from the web app's, the gateway's and the controller's roles on every run. Revoke execute on the guard, recording and prune functions from `PUBLIC`, and grant execute on the prune function to the web app's role. When the audit role exists, grant it select on the log and on the columns that the D12 checks compare. Verify: task 5.6. +- [x] 3.4 In the second migration, add a trigger function that runs with its + caller's rights and pins its search path. Attach it to `exomem_cloud_cells` + with an `AFTER UPDATE` row trigger that fires when the desired state becomes + `deleted`, and an `AFTER DELETE` row trigger on a row that is not yet + deleted. It sets `revoked_at` to the database clock on the tenant's + unrevoked service credentials and leaves the revoking principal empty (D6). + Take the cells lock first in D5's `LOCK TABLE`. After the triggers exist, + revoke once, at the migration's time, every unrevoked service credential of + a tenant that has no cell other than deleted ones, before the backfill. + Revoke the function's execute right from `PUBLIC` in the migration and in + the grants script. Verify: task 5.4's migration test, and the trigger tests + of the issuance log suite in both states of group 5. As the web app's role, + setting a cell to `deleted` ends the tenant's credentials and their records + at the database clock, and another tenant's stay live. A cell that only + stops changes nothing, and a second update changes nothing. A deletion at a fixed transaction snapshot is refused. A delete of a + live cell row by the schema owner ends them, and a delete of an old deleted + row beside a live cell does not. The migration ends the live credential of a + tenant that has only deleted cells and keeps that of a tenant with a live + cell. + +- [x] 3.5 In the second migration, add a `BEFORE INSERT` row trigger on + `exomem_cloud_service_credentials`. Its function runs with its caller's + rights and pins its search path. It reads the tenant's cell that is not + deleted with `FOR SHARE`, and raises SQLSTATE `23503` with the constraint + name `exomem_cloud_service_credentials_live_cell` when there is none. Revoke + the function's execute right from `PUBLIC` in the migration and in the grants + script. In the service credential request, answer that refusal as + `SERVICE_CREDENTIAL_TENANT_INELIGIBLE`. Answer a deadlock (SQLSTATE 40P01) + that the sweep's lock order can cause as 503 `SERVICE_CREDENTIAL_RETRY` with + `Retry-After: 3`, and not as a bare 500. Verify, in both states of group 5, + with a statement timeout on each connection: a credential for a tenant whose + only cell is deleted is refused. A deletion that starts while the insert is + open waits for the commit, and the credential then ends at the database + clock with its record. An insert that waits for an open deletion is refused + after the commit. The request's own test shows the 409 answer, and a unit + test shows the 503 answer for a thrown 40P01. Without + `FOR SHARE`, the two waiting tests fail. ## 4. Download ticket rows (D8) -- [ ] 4.1 In the second migration, create `exomem_cloud_download_tickets` with +- [x] 4.1 In the second migration, create `exomem_cloud_download_tickets` with its unique key, its expiry index, its update guard and its recording trigger. In the grants script, give the web app's role select, insert and - delete, and the gateway's role select. Verify: as the web app's role, an - update of a ticket row is refused, also after a grant of update on the - table. -- [ ] 4.2 In the download handler, store the ticket's row before the redirect + delete, and the gateway's role select. The row names no grant: the recording + trigger reads the grant, the tenant and the user through the token family. + Verify: as the web app's role, an update of a ticket row is refused, also + after a grant of update on the table. +- [x] 4.2 In the download handler, store the ticket's row before the redirect answer, with `ON CONFLICT DO NOTHING`. In the scheduled maintenance, delete a bounded batch of expired ticket rows. Verify: a download request leaves one row and one issuance record, a second ticket with the same token family, path and expiry adds neither, and a maintenance run removes an expired row. -- [ ] 4.3 In the gateway, require the matching unexpired row inside the +- [x] 4.3 In the gateway, require the matching unexpired row inside the statement that resolves the ticket's login. Verify: task 5.7. ## 5. Proof on a disposable PostgreSQL, as the real roles @@ -131,17 +187,18 @@ The wide state is select, insert, update, delete and truncate on every table in the schema, the log included. An earlier grants script gives the wide state without truncate. Neither state holds the trigger right. -- [ ] 5.1 Attacks as the web app's role, in both states. Re-point a grant's +- [x] 5.1 Attacks as the web app's role, in both states. Re-point a grant's tenant and user, by update and by a conflict action. Overwrite an access token's digest and a refresh token's digest. Extend an expiry. Change a reviewer reference. Clear a revocation time and a consumption time. Re-point a service credential's tenant and overwrite its digest. Change a tenant's - owner and a client's identifier. Delete and truncate grants, clients, - tenants, users, service credentials and reviewer credentials. Truncate a + owner and a client's identifier. Re-point a cell to another tenant and + rename a cell. Delete and truncate grants, clients, tenants, users, cells, + service credentials and reviewer credentials. Truncate a table that one of them references, with `CASCADE`. Create a trigger on a guarded table. Then create temporary tables that carry the names of the guarded tables, the log and the grant table, and run the list again. -- [ ] 5.2 The guards alone, with help that only the schema owner can give. +- [x] 5.2 The guards alone, with help that only the schema owner can give. The schema owner adds a `BEFORE` trigger that changes a grant's tenant: an update by the web app's role that names only `updated_at` is refused. The schema owner disables the delete guard on reviewer credentials. In the wide @@ -153,14 +210,14 @@ without truncate. Neither state holds the trigger right. token family that has tokens. A statement that keeps a revocation time that is already set succeeds. `EXPLAIN ANALYZE` of the Home mint's grant upsert lists no trigger of this change. -- [ ] 5.3 Every insert path writes its records, through the real functions. A +- [x] 5.3 Every insert path writes its records, through the real functions. A code exchange writes three. A refresh rotation writes two. A Home sign-in writes one for a new token family, and each Home mint writes one. A service credential and a download ticket write one each. A rolled-back transaction leaves none. A deleted and re-inserted token row has two. With temporary tables that carry the names of the log and the grant table, a token insert still records in the real log. -- [ ] 5.4 The log resists the web app's, the gateway's and the controller's +- [x] 5.4 The log resists the web app's, the gateway's and the controller's roles, in both states of group 5. Insert, update, delete and truncate on the log are refused. Dropping or disabling a recording trigger, creating a trigger on the log, replacing the recording function and setting @@ -169,8 +226,9 @@ without truncate. Neither state holds the trigger right. function. The trigger is refused and the log gains no record. After the schema owner renames the log table, a token insert fails and leaves no row. A migration run over existing credential rows writes one backfilled record - for each. -- [ ] 5.5 Every legitimate flow runs as the web app's role, on the rights of the + for each row whose record the prune would keep, and none for a token that + expired more than 90 days before. +- [x] 5.5 Every legitimate flow runs as the web app's role, on the rights of the new grants script: authorization and consent, invite admission, code exchange, refresh rotation, token revocation by the client, by the owner and by the operator, account revocation, reviewer credential issue and reviewer @@ -181,7 +239,7 @@ without truncate. Neither state holds the trigger right. download. The PR changes no existing statement of these flows. The same run therefore covers the release that serves during a deploy. The reviewer checks that against the diff. -- [ ] 5.6 Rights are exact. After the grants script, the web app's rights on +- [x] 5.6 Rights are exact. After the grants script, the web app's rights on the D2 tables equal the D2 table. Every column of a column-locked table is either changeable or in a guard's list, never both and never neither. A second run changes nothing. The gateway's and the controller's rights on @@ -191,45 +249,55 @@ without truncate. Neither state holds the trigger right. the trigger right on any table in the schema, also after a hand-typed grant and a second run. The schema's functions that run with their owner's rights are exactly the health proof, the recording function and the prune function. - `PUBLIC` holds execute on none of them, nor on the guard function. Only the - web app's role holds execute on the prune function. Each function in the set + `PUBLIC` holds execute on none of them, nor on the guard function. Of the + roles granted execute on the prune function, only the web app's role is one. + Each function in the set of task 2.5, read from the catalog, pins a `search_path` that starts with `pg_catalog` and ends with `pg_temp`, and names only schemas that the schema owner, the bootstrap superuser or `pg_database_owner` owns. -- [ ] 5.7 The gateway refuses a correctly signed ticket that has no row, and +- [x] 5.7 The gateway refuses a correctly signed ticket that has no row, and serves one that has its row. It refuses one whose path, token family or expiry differs from the stored row. A download request runs as many database - statements as it did before this change. -- [ ] 5.8 Cost at the load target (D7). Generate data for 10,000 tenants and a - log of 10 million records. With `pgbench`, run the Home mint transaction's + statements as it did before this change. One new ticket retires one expired row + and keeps both issuance records. Issuance succeeds without deleting a row + when the bounded set of expired candidates is locked. +- [ ] 5.8 Cost proof (D7). For comparison with the earlier sample, generate data + for 10,000 tenants and a log of 10 million records. With `pgbench`, run the Home mint transaction's statements with and without this change's triggers: five runs each, same machine, same data. Report the median and the 95th percentile of both arms, the write-ahead-log bytes for each mint, and the measured size of a record. Report `EXPLAIN (ANALYZE, BUFFERS)` of one prune call and of each D12 read. Pass: the median rises by less than one millisecond, the prune reads only - what it deletes, and no D12 read scans the whole log. Put the outputs in the - PR. -- [ ] 5.9 Add the new suites to the PostgreSQL integration list in + what it deletes, and no D12 read of the log scans the whole log. The credential check + reads a primary-key page from its source table before filtering by time. Keep the results as private evidence. The run at + `e8a7c3db` used the predecessor indexes and audit queries. The current + indexes change insert cost. Repeat the write proof with the same instrument + and run the current D12 queries on the generated log. The 10-million-record + run gives a sample result. Verify the budget at the projected load and + retained volume, or show that the sample covers the same index working set + and write conditions. +- [x] 5.9 Add the new suites to the PostgreSQL integration list in `.github/workflows/test.yml`. Verify: CI runs them. ## 6. Documentation -- [ ] 6.1 `docs/runbooks/production-keys-and-storage.md`: replace the +- [x] 6.1 `docs/runbooks/production-keys-and-storage.md`: replace the build-time migration section. Describe the migration job, the manual run with the operator's own copy of the credential and a named commit, and `SKIP_SCHEMA_RELEASE_WAIT`. Say that a migration that meets its lock timeout - or a deadlock fails the job, and that the operator starts the job again. Remove - `SKIP_VERCEL_MIGRATE` and the procedure that pulls production variables to a - local file. -- [ ] 6.2 `docs/runbooks/exomem-cloud-operations.md`: what the lock refuses, + or a deadlock fails the job, and that the operator starts the job again and + redeploys a production build that already failed. Remove `SKIP_VERCEL_MIGRATE` + and the procedure that pulls production variables to a local file. +- [x] 6.2 `docs/runbooks/exomem-cloud-operations.md`: what the lock refuses, and each emergency statement with what it suspends. The issuance log: the D12 checks as the audit role, with the hour that each run reads again, a - size check, and the statement that disables recording. The three catalog - checks of D12: the trigger right, the web app's role memberships, create - rights held by a role other than a superuser, the schema owner or - `pg_database_owner`, and schemas that another role owns. Ticket - rows. The deploy order and the rollback order of D8. -- [ ] 6.3 `docs/runbooks/vercel-deployments.md` and the README's migration + size check, and the statement that disables recording. The four catalog + checks of D12: the trigger right, the web app's role memberships, the web + app's rights beyond what the grants script gives it (with the steps that + restore them), create rights held by a role other than a superuser, the + schema owner or `pg_database_owner`, and schemas that another role owns. + Ticket rows. The deploy order and the rollback order of D8. +- [x] 6.3 `docs/runbooks/vercel-deployments.md` and the README's migration section: the production build reads its schema release and never migrates. Say beside promotion, rollback and uploaded deployments that none of them checks the schema release. @@ -273,27 +341,72 @@ and its date. and no right to set `session_replication_role`. No role but the owner holds the trigger right on any table in the schema. Production runs the same PostgreSQL major version as CI, so the foreign-key test of D2 holds there. - Read the count of live credential rows, which sets - how long the second migration blocks writes to the token and service - credential tables. Create the audit role. Evidence: the catalog queries' - outcome. Fix any failure before step 7.5. -- [ ] 7.5 Approve the merge of the implementation PR. The merge applies the + Read the count of rows that each of the second migration's backfill reads + scans, which are the full source tables: this migration runs once, against + today's data. That count sets how long the migration blocks writes to the + cell, token and service credential tables, and the go/no-go uses it. The + query also counts the rows that each backfill writes, by the backfill's own + predicate: a row counts when the end that its record would take is empty or + at most 90 days old. + + ```sql + SELECT 'token_families' AS source, count(*) AS rows_read, + count(*) FILTER (WHERE CASE WHEN family.revoked_at IS NOT NULL + THEN least(family.expires_at, now()) ELSE family.expires_at END + >= now() - interval '2160 hours') AS rows_written + FROM exomem_oauth_token_families AS family + UNION ALL SELECT 'access_tokens', count(*), + count(*) FILTER (WHERE expires_at >= now() - interval '2160 hours') + FROM exomem_oauth_access_tokens + UNION ALL SELECT 'refresh_tokens', count(*), + count(*) FILTER (WHERE expires_at >= now() - interval '2160 hours') + FROM exomem_oauth_refresh_tokens + UNION ALL SELECT 'service_credentials', count(*), count(*) + FROM exomem_cloud_service_credentials; + ``` + + Create the audit role as the schema owner or another role + that holds the role-creation right: `CREATE ROLE substrate_audit LOGIN + NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION;`, then set its password + with `\password substrate_audit` in `psql` and store it in the operator's + secret store. The role needs the connect right on the database, which + `PUBLIC` holds unless the operator revoked it. If the operator revoked it, + run `GRANT CONNECT ON DATABASE TO substrate_audit;`. The role + needs no other right and no membership in any role. The grants script gives + it the select on the log and on the columns that the D12 checks compare + when the merge's job runs. The catalog checks read `pg_catalog`, which + every role can read. Evidence: the catalog queries' outcome. Fix any + failure before step 7.5. +- [ ] 7.5 Pause operator service credential issuance until the new web release serves. + Approve the merge of the implementation PR. The merge applies the migrations to production. The lock and the log are in force from that moment, and the web app starts to store ticket rows. If a migration meets - its lock timeout or a deadlock, start the job again. Evidence: the job is green, the merge - commit has a schema release, and the production build read it and deployed. + its lock timeout or a deadlock, start the job again. If the production build + already failed, redeploy it after the job is green. Evidence: the job is + green, the merge commit has a schema release, and the production build read + it and deployed. - [ ] 7.6 Read the log and run the flows once. Sign in, connect an app, wait for one token refresh, open Home, download a file, disconnect the app, and - see one maintenance run succeed. Run the D12 checks as the audit role. - Evidence: the flows add records for the test account, and the checks list - nothing. Run no attack against production; task 5.1 is that proof. + see one maintenance run succeed. Run the D12 checks as the audit role, the + check of the web app's rights included. Read the install + time once, as the runbook says, and run both audit sweeps to their fixed + targets. Evidence: the flows add records for + the test account, and the checks list nothing. A row from the rights check + means that an earlier grants script ran after the job, and step 7.7 takes + the right back. Run no attack against production; task 5.1 is that proof. - [ ] 7.7 On the day of step 7.5, remove the schema-owner connection string and `SKIP_VERCEL_MIGRATE` from every web deployment environment. Then rotate the schema-owner credential and store the new value in the protected environment. Until this step, a rebuild of an earlier commit applies the - earlier grants script. Evidence: a listing of variable names shows no - schema-owner variable, a dry run of the job is green, and a connection with - the old credential is refused. + earlier grants script. So can the production build of the commit before this + change, if it was still in flight at step 7.5: it waits on the job's lock, + then applies that script after the job's own. When no build of an earlier + commit is still running, run the `migrate-database` workflow for `main` with + `dry_run` set to false. A dry run applies no grants. The job's grants script + restores the narrow rights. Then run the runbook's check of the web app's + rights as the audit role. Evidence: a listing of variable names shows no + schema-owner variable, the non-dry run is green, the rights check lists no + row, and a connection with the old credential is refused. - [ ] 7.8 Read the host and the database name of each preview and development database variable, without printing a secret. Replace and rotate any that names the production database. Check that no web deployment environment diff --git a/package.json b/package.json index fe3baf48..dda63f28 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "dev": "rm -rf .next && next dev --port 3000", "dev:next": "next dev", "build": "npm run check:exomem-theme && next build", - "vercel-build": "npm run check:exomem-theme && tsx scripts/vercel-maybe-migrate.ts && next build", + "vercel-build": "npm run check:exomem-theme && tsx scripts/wait-for-schema-release.ts && next build", "start": "next start", "gateway:start": "node dist/exomem-gateway/index.cjs", "gateway:typecheck": "tsc --noEmit", diff --git a/scripts/exomem-cloud-grants.sql b/scripts/exomem-cloud-grants.sql index cbac6e75..e44cd5e8 100644 --- a/scripts/exomem-cloud-grants.sql +++ b/scripts/exomem-cloud-grants.sql @@ -29,6 +29,15 @@ -- review finding 3) -- the gateway connects to Postgres directly with -- its own role and runs that lookup itself. -- +-- 4. The identity lock (section 1b below): the exceptions to the schema-wide +-- grant in 1. substrate_app loses delete on grants, clients, tenants, users, +-- service credentials and reviewer credentials, and update on every column +-- of token families, access tokens, refresh tokens, grants and service +-- credentials except the ones its flows change. It reads schema_releases +-- and writes nothing there. The script also revokes the trigger right on +-- every table in the schema from every role but the table's owner. The +-- guards in migration 0101 hold whatever this script grants. +-- -- Applied by the migration runner (scripts/migrate.ts) after every run -- -- including one against a migrationsDir that never creates the Cloud -- tables at all, as the runner's own generic-runner tests do -- and by the @@ -50,6 +59,11 @@ DECLARE target_schema text := current_schema(); cloud_role text; oauth_table text; + lock_table text; + lock_columns text[]; + lock_column_list text; + lock_holder record; + lock_role text; BEGIN -- 1. Schema-wide substrate_app DML, plus default privileges for whatever a -- later migration creates. Guarded on substrate_app existing so a database @@ -89,6 +103,198 @@ BEGIN ); END IF; + -- 1b. Identity lock, issuance log and download tickets (lock-cloud-identity-rows-and-record-issuance). + -- Each part takes rights back from the schema-wide grant above, so it + -- runs after it. Guards in the migrations hold whatever this section + -- gives; the rights are the first control and the guards the second. + -- + -- schema_releases: the web app's build reads its schema release and nothing + -- else touches the table from the web deployment. The migration job writes + -- it as the schema owner. + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_app') + AND to_regclass('schema_releases') IS NOT NULL THEN + REVOKE ALL ON schema_releases FROM substrate_app; + GRANT SELECT ON schema_releases TO substrate_app; + END IF; + + -- Identity lock (design D2). The web app's role loses delete on the tables + -- whose rows it never deletes, and update on every column of the five + -- column-locked tables that its flows do not change. Insert stays whole-table: + -- an insert is the recorded operation. Each right is granted only when its + -- table and column exist, because a partial upgrade runs this script too. The + -- migration's guards hold when these rights are wrong, and a test asserts that + -- each column of a column-locked table is either in a list here or in its + -- guard's list, never both and never neither. + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_app') THEN + FOREACH lock_table IN ARRAY ARRAY[ + 'exomem_oauth_grants', 'exomem_oauth_clients', 'exomem_tenants', 'exomem_users', + 'exomem_cloud_service_credentials', 'exomem_marketplace_reviewer_credentials' + ] LOOP + IF to_regclass(lock_table) IS NOT NULL THEN + EXECUTE format('REVOKE DELETE ON %I FROM substrate_app', lock_table); + END IF; + END LOOP; + + -- Column-locked tables: the changeable columns only. + FOR lock_table, lock_columns IN + SELECT * FROM (VALUES + ('exomem_oauth_grants', ARRAY['scopes', 'refresh_allowed', 'authorization_transaction_id', + 'updated_at', 'revoked_at', 'client_context_override']), + ('exomem_oauth_token_families', ARRAY['revoked_at', 'revoked_reason']), + ('exomem_oauth_access_tokens', ARRAY['revoked_at']), + ('exomem_oauth_refresh_tokens', ARRAY['consumed_at']), + ('exomem_cloud_service_credentials', ARRAY['revoked_at', 'revoked_by_principal_digest']) + ) AS locked(table_name, column_names) + LOOP + IF to_regclass(lock_table) IS NOT NULL THEN + EXECUTE format('REVOKE UPDATE ON %I FROM substrate_app', lock_table); + SELECT string_agg(quote_ident(column_name), ', ') INTO lock_column_list + FROM information_schema.columns + WHERE table_schema = target_schema AND table_name = lock_table + AND column_name = ANY (lock_columns); + IF lock_column_list IS NOT NULL THEN + EXECUTE format('GRANT UPDATE (%s) ON %I TO substrate_app', lock_column_list, lock_table); + END IF; + END IF; + END LOOP; + + -- Clients and tenants: every column except the identity columns. + FOR lock_table, lock_columns IN + SELECT * FROM (VALUES + ('exomem_oauth_clients', ARRAY['id', 'client_id']), + ('exomem_tenants', ARRAY['owner_user_id']) + ) AS locked(table_name, column_names) + LOOP + IF to_regclass(lock_table) IS NOT NULL THEN + EXECUTE format('REVOKE UPDATE ON %I FROM substrate_app', lock_table); + SELECT string_agg(quote_ident(column_name), ', ') INTO lock_column_list + FROM information_schema.columns + WHERE table_schema = target_schema AND table_name = lock_table + AND column_name <> ALL (lock_columns); + IF lock_column_list IS NOT NULL THEN + EXECUTE format('GRANT UPDATE (%s) ON %I TO substrate_app', lock_column_list, lock_table); + END IF; + END IF; + END LOOP; + END IF; + + -- Issuance log (design D5, D6, D12). The web app's, the gateway's and the + -- controller's roles hold nothing on the log or on the sequence that numbers + -- its records. The guard refuses their writes whatever they hold, and the + -- recording and prune functions write as the schema owner. The audit role + -- reads the log and the columns that its checks compare, and nothing else. + IF to_regclass('exomem_cloud_issuance_log') IS NOT NULL THEN + REVOKE ALL ON exomem_cloud_issuance_log FROM PUBLIC; + FOREACH lock_role IN ARRAY ARRAY['substrate_app', 'exomem_gateway', 'exomem_cellctl', 'substrate_audit'] LOOP + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = lock_role) THEN + EXECUTE format('REVOKE ALL ON exomem_cloud_issuance_log FROM %I', lock_role); + EXECUTE format( + 'REVOKE ALL ON SEQUENCE %s FROM %I', + pg_get_serial_sequence('exomem_cloud_issuance_log', 'id'), lock_role + ); + END IF; + END LOOP; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_audit') THEN + GRANT SELECT ON exomem_cloud_issuance_log TO substrate_audit; + -- The columns that the runbook's checks compare with the log: each credential + -- table's identifier and creation time, and the tenant's owner. + FOREACH lock_table IN ARRAY ARRAY[ + 'exomem_oauth_token_families', 'exomem_oauth_access_tokens', 'exomem_oauth_refresh_tokens', + 'exomem_cloud_service_credentials', 'exomem_cloud_download_tickets' + ] LOOP + IF to_regclass(lock_table) IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON %I FROM substrate_audit', lock_table); + EXECUTE format('GRANT SELECT (id, created_at) ON %I TO substrate_audit', lock_table); + END IF; + END LOOP; + IF to_regclass('exomem_tenants') IS NOT NULL THEN + REVOKE ALL ON exomem_tenants FROM substrate_audit; + GRANT SELECT (id, owner_user_id) ON exomem_tenants TO substrate_audit; + END IF; + END IF; + END IF; + + -- Download ticket rows (design D8): the web app stores and prunes them, the + -- gateway reads the three columns that it matches a ticket by, and no update + -- is granted. The migration's guard refuses an update whatever is granted. + IF to_regclass('exomem_cloud_download_tickets') IS NOT NULL THEN + REVOKE ALL ON exomem_cloud_download_tickets FROM PUBLIC; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_app') THEN + REVOKE ALL ON exomem_cloud_download_tickets FROM substrate_app; + GRANT SELECT, INSERT, DELETE ON exomem_cloud_download_tickets TO substrate_app; + END IF; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'exomem_gateway') THEN + REVOKE ALL ON exomem_cloud_download_tickets FROM exomem_gateway; + GRANT SELECT (family_id, path_sha256, expires_at) ON exomem_cloud_download_tickets TO exomem_gateway; + END IF; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'exomem_cellctl') THEN + REVOKE ALL ON exomem_cloud_download_tickets FROM exomem_cellctl; + END IF; + END IF; + + -- PostgreSQL gives PUBLIC execute on every new function. The guard, the + -- recording function and the two cell-related trigger functions need no + -- grant: PostgreSQL checks the right when a trigger is created, not when it + -- fires, and only the schema owner creates these triggers. Only the web app's + -- role may call the prune function, and the reconcile job does so. + IF to_regprocedure('exomem_refuse_unless_schema_owner()') IS NOT NULL THEN + REVOKE ALL ON FUNCTION exomem_refuse_unless_schema_owner() FROM PUBLIC; + END IF; + IF to_regprocedure('exomem_record_issuance()') IS NOT NULL THEN + REVOKE ALL ON FUNCTION exomem_record_issuance() FROM PUBLIC; + END IF; + IF to_regprocedure('exomem_revoke_service_credentials_of_cell()') IS NOT NULL THEN + REVOKE ALL ON FUNCTION exomem_revoke_service_credentials_of_cell() FROM PUBLIC; + END IF; + IF to_regprocedure('exomem_require_live_cell_for_service_credential()') IS NOT NULL THEN + REVOKE ALL ON FUNCTION exomem_require_live_cell_for_service_credential() FROM PUBLIC; + END IF; + IF to_regprocedure('exomem_prune_issuance_log()') IS NOT NULL THEN + REVOKE ALL ON FUNCTION exomem_prune_issuance_log() FROM PUBLIC; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'substrate_app') THEN + GRANT EXECUTE ON FUNCTION exomem_prune_issuance_log() TO substrate_app; + END IF; + END IF; + FOREACH lock_role IN ARRAY ARRAY['substrate_app', 'exomem_gateway', 'exomem_cellctl', 'substrate_audit'] LOOP + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = lock_role) THEN + IF to_regprocedure('exomem_refuse_unless_schema_owner()') IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON FUNCTION exomem_refuse_unless_schema_owner() FROM %I', lock_role); + END IF; + IF to_regprocedure('exomem_record_issuance()') IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON FUNCTION exomem_record_issuance() FROM %I', lock_role); + END IF; + IF to_regprocedure('exomem_revoke_service_credentials_of_cell()') IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON FUNCTION exomem_revoke_service_credentials_of_cell() FROM %I', lock_role); + END IF; + IF to_regprocedure('exomem_require_live_cell_for_service_credential()') IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON FUNCTION exomem_require_live_cell_for_service_credential() FROM %I', lock_role); + END IF; + IF lock_role <> 'substrate_app' AND to_regprocedure('exomem_prune_issuance_log()') IS NOT NULL THEN + EXECUTE format('REVOKE ALL ON FUNCTION exomem_prune_issuance_log() FROM %I', lock_role); + END IF; + END IF; + END LOOP; + + -- The trigger right stays with the table's owner. A role that holds it on one + -- table can run its own code as the schema owner, and no guard holds against + -- that. Take it from PUBLIC and from every other role, on every table of the + -- schema, on every run. No flow creates a trigger; a tool that needs the right + -- fails until a reviewed change names it. + FOR lock_holder IN + SELECT DISTINCT relation.oid::regclass::text AS table_name, acl.grantee + FROM pg_class AS relation, aclexplode(relation.relacl) AS acl + WHERE relation.relnamespace = target_schema::regnamespace + AND relation.relkind IN ('r', 'p') + AND acl.privilege_type = 'TRIGGER' + AND acl.grantee <> relation.relowner + LOOP + EXECUTE format( + 'REVOKE TRIGGER ON %s FROM %s', + lock_holder.table_name, + CASE WHEN lock_holder.grantee = 0 THEN 'PUBLIC' ELSE quote_ident(pg_get_userbyid(lock_holder.grantee)) END + ); + END LOOP; + -- 2. C1-C1d, C5 and C6 are the exceptions to the schema-wide grant above: revoke -- whatever it (and PUBLIC) just gave every role on these four tables, then -- apply the exact C1 privilege table below. A rerun of this whole script diff --git a/scripts/migrate.ts b/scripts/migrate.ts index b951055e..bf8cba6a 100644 --- a/scripts/migrate.ts +++ b/scripts/migrate.ts @@ -12,9 +12,19 @@ * statement applied successfully and the row was inserted, or the run aborts * and the file is left to be retried. * + * A caller that names a commit (`--commit `) also records that commit's + * schema release once the migrations and the grants script have succeeded, and + * records each commit of `--superseded ` as superseded. A run that + * names no commit records nothing. + * + * A dry run only reads. It takes no migration lock and creates no table, so it + * lists every migration as pending on a database that has none applied, and + * leaves that database empty. + * * Usage: * tsx scripts/migrate.ts # apply pending migrations * tsx scripts/migrate.ts --dry # list pending migrations without applying + * tsx scripts/migrate.ts --commit [--superseded ] */ import { existsSync, readFileSync, readdirSync } from "node:fs"; @@ -24,12 +34,21 @@ import { Client, type ClientBase } from "pg"; const DEFAULT_MIGRATIONS_DIR = resolve(process.cwd(), "migrations"); const DEFAULT_GRANTS_FILE = resolve(process.cwd(), "scripts/exomem-cloud-grants.sql"); -const MIGRATION_LOCK_NAMESPACE = 0x45584f4d; // "EXOM" -const MIGRATION_LOCK_ID = 0x454d; // "EM" +export const MIGRATION_LOCK_NAMESPACE = 0x45584f4d; // "EXOM" +export const MIGRATION_LOCK_ID = 0x454d; // "EM" const RELEASE_A_MIGRATION = "0040_backup_version_commit.sql"; type Sql = Pick; +// The format of a git commit hash is fixed by git, so a pattern checks it. +const FULL_COMMIT_HASH = /^[0-9a-f]{40}$/; + +export function assertCommitHash(value: string, label: string): void { + if (!FULL_COMMIT_HASH.test(value)) { + throw new Error(`${label} must be a full 40-character commit hash`); + } +} + /** * `DATABASE_MIGRATION_URL`, when set, names PgBouncer's session-mode alias * (design D7): the schema-owning connection this runner holds a session-level @@ -75,6 +94,10 @@ async function ensureTrackingTable(sql: Sql): Promise { } async function getAppliedVersions(sql: Sql): Promise> { + // A dry run reaches here without the tracking table on a database that no + // migration has touched: nothing is applied there. + const present = await sql.query("SELECT to_regclass('schema_migrations') IS NOT NULL AS present"); + if (!(present.rows[0] as { present: boolean }).present) return new Set(); const { rows } = await sql.query<{ version: string }>("SELECT version FROM schema_migrations"); return new Set((rows as Array<{ version: string }>).map((r) => r.version)); } @@ -166,13 +189,61 @@ async function applyFile(sql: Sql, migrationsDir: string, filename: string): Pro } } +/** + * Writes the schema release of `commit` and each superseded commit, in one + * transaction. A commit that already has a row keeps it, so a restarted run + * of a released commit leaves it released. The table is the schema owner's + * to write (migration 0101's guard). + */ +async function recordSchemaReleases( + sql: Sql, + commit: string | undefined, + superseded: readonly string[] +): Promise { + if ((await sql.query("SELECT to_regclass('schema_releases') AS name")).rows[0]?.name === null) { + // A commit from before migration 0101 has no table to record in. + console.log("[migrate] schema_releases does not exist yet; nothing to record"); + return; + } + await sql.query("BEGIN"); + try { + if (commit !== undefined) { + await sql.query( + "INSERT INTO schema_releases (commit_sha, status) VALUES ($1, 'released') ON CONFLICT (commit_sha) DO NOTHING", + [commit] + ); + } + if (superseded.length > 0) { + await sql.query( + "INSERT INTO schema_releases (commit_sha, status) SELECT sha, 'superseded' FROM unnest($1::text[]) AS sha ON CONFLICT (commit_sha) DO NOTHING", + [superseded] + ); + } + await sql.query("COMMIT"); + } catch (error) { + await sql.query("ROLLBACK"); + throw error; + } + console.log( + `[migrate] recorded ${commit === undefined ? "no release" : `release ${commit}`} and ${superseded.length} superseded commit${superseded.length === 1 ? "" : "s"}` + ); +} + +/** Reads `--name value` or `--name=value`; undefined when the flag is absent. */ +function flagValue(argv: readonly string[], name: string): string | undefined { + const index = argv.findIndex((argument) => argument === name || argument.startsWith(`${name}=`)); + if (index < 0) return undefined; + const argument = argv[index]!; + const value = argument.includes("=") ? argument.slice(name.length + 1) : argv[index + 1]; + if (!value) throw new Error(`${name} needs a value`); + return value; +} + /** * Apply all pending migrations (or list them, if `dry: true`). * - * Exported so `scripts/vercel-maybe-migrate.ts` can call the same code path - * during Vercel production builds without spawning a child process. Throws on - * any migration failure so callers can decide whether to abort the build / - * non-zero exit / etc. + * Exported so tests call the same code path as the release job. Throws on any + * migration failure so callers can decide on a non-zero exit. */ export async function applyMigrations( opts: { @@ -180,26 +251,37 @@ export async function applyMigrations( databaseUrl?: string; migrationsDir?: string; grantsFile?: string; + /** Records this commit's schema release after the grants script succeeds. */ + commit?: string; + /** Commits that a newer schema release overtook; recorded as superseded. */ + supersededCommits?: readonly string[]; } = {} ): Promise { const { dry = false, migrationsDir = DEFAULT_MIGRATIONS_DIR, grantsFile = DEFAULT_GRANTS_FILE, + supersededCommits = [], } = opts; + // A malformed commit fails before the runner connects. + if (opts.commit !== undefined) assertCommitHash(opts.commit, "commit"); + for (const commit of supersededCommits) assertCommitHash(commit, "superseded commit"); const client = getClient(opts.databaseUrl); await client.connect(); let locked = false; try { // A session lock is held on this dedicated connection across the applied // version recheck and every per-file transaction. A crashed runner drops - // the connection and releases it automatically. - await client.query("SELECT pg_advisory_lock($1, $2)", [ - MIGRATION_LOCK_NAMESPACE, - MIGRATION_LOCK_ID, - ]); - locked = true; - await ensureTrackingTable(client); + // the connection and releases it automatically. A dry run writes nothing, + // so it needs neither the lock nor the tracking table. + if (!dry) { + await client.query("SELECT pg_advisory_lock($1, $2)", [ + MIGRATION_LOCK_NAMESPACE, + MIGRATION_LOCK_ID, + ]); + locked = true; + await ensureTrackingTable(client); + } const applied = await getAppliedVersions(client); const all = listMigrationFiles(migrationsDir); const pending = all.filter((name) => !applied.has(name)); @@ -260,6 +342,10 @@ export async function applyMigrations( console.log("FAIL"); throw new Error(`grants failed: ${err instanceof Error ? err.message : String(err)}`); } + // Only a run whose migrations and grants both succeeded reaches this line. + if (opts.commit !== undefined) { + await recordSchemaReleases(client, opts.commit, supersededCommits); + } } } finally { if (locked) { @@ -271,11 +357,18 @@ export async function applyMigrations( } } -// CLI entry point. Only runs when invoked directly (`tsx scripts/migrate.ts`) -// — not when imported as a module by `vercel-maybe-migrate.ts`. Standard ESM -// idiom: compare process.argv[1] against the file path of this module. +// CLI entry point. Only runs when invoked directly (`tsx scripts/migrate.ts`), +// not when a test imports the module. Standard ESM idiom: compare +// process.argv[1] against the file path of this module. if (process.argv[1] === fileURLToPath(import.meta.url)) { - applyMigrations({ dry: process.argv.includes("--dry") }).catch((err) => { + const argv = process.argv.slice(2); + (async () => { + await applyMigrations({ + dry: argv.includes("--dry"), + commit: flagValue(argv, "--commit"), + supersededCommits: flagValue(argv, "--superseded")?.split(",").filter(Boolean), + }); + })().catch((err) => { console.error("[migrate] runner error:", err); process.exit(1); }); diff --git a/scripts/schema-release-plan.sh b/scripts/schema-release-plan.sh new file mode 100755 index 00000000..9522b00e --- /dev/null +++ b/scripts/schema-release-plan.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# Decides what the schema release job applies. The job checks out the tip of the +# default branch when it starts, whatever commit started the run, installs its +# dependencies, then runs this script just before it applies. Prints three lines +# for the job's step output: +# tip= the tip of the default branch now +# apply=true|false whether the checked-out commit is that tip +# superseded= the tip's recent first-parent ancestors +# +# The migration runner records each listed commit that has no row as superseded, +# so every commit that the previous schema release left behind gets a row, +# including one whose own run the concurrency group replaced. A commit that +# already has a row keeps it. +# +# apply=false means the default branch moved while the job installed: the job holds +# the old tip's code, and the push that moved it started a run of its own, which +# applies the new tip. +# +# Usage: scripts/schema-release-plan.sh [remote] [branch] +set -euo pipefail + +remote="${1:-origin}" +branch="${2:-main}" +# A bound on the history, not data: a gap longer than this leaves its oldest +# commits without a row, and a build of one of them fails after its wait. +history_limit=100 + +git fetch --quiet --no-tags "$remote" "$branch" +tip="$(git rev-parse FETCH_HEAD)" + +echo "tip=$tip" +if [ "$tip" = "$(git rev-parse HEAD)" ]; then + echo "apply=true" +else + echo "apply=false" +fi +echo "superseded=$(git rev-list --first-parent --max-count="$history_limit" "$tip^" 2>/dev/null | paste -sd, -)" diff --git a/scripts/vercel-maybe-migrate.ts b/scripts/vercel-maybe-migrate.ts deleted file mode 100644 index 31c9c5c2..00000000 --- a/scripts/vercel-maybe-migrate.ts +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Conditional production migration step for Vercel builds. - * - * Vercel runs `npm run vercel-build` (when present in package.json) on every - * deploy. We chain this script in front of `next build` so production deploys - * apply any pending migrations against the production database, while preview - * and development deploys skip migration entirely — preview builds must never - * touch the production schema. - * - * Failure mode: a failing migration aborts the build with a non-zero exit - * code, which Vercel surfaces as a failed deploy. The previous deploy stays - * live. This is the desired behavior — better to fail loudly than ship code - * that 500s on the first request to touch a missing table (the gui-v2.8.0 / - * migration 0015 incident, 2026-05-27). - * - * Manual override: set `SKIP_VERCEL_MIGRATE=1` in Vercel project env to - * temporarily disable. Use sparingly — the whole point of this script is to - * keep the schema and the deployed code in lockstep. The override skips the - * migrations only: a production deploy still needs a valid control-plane key. - */ - -import { applyMigrations } from './migrate'; -import { controlPlaneKeyFromEnv } from '../src/lib/exomem-hosted/security'; - -const env = process.env.VERCEL_ENV ?? 'unset'; -const skip = process.env.SKIP_VERCEL_MIGRATE === '1'; - -/** - * The Paddle webhook seals the payment-failed email, and the start, sign-in - * and OAuth routes seal or key their state, with EXOMEM_CONTROL_PLANE_KEY. - * Without a valid key each of them fails on every request, and Paddle only - * retries its webhook. Refusing the production deploy costs one blocked - * deploy (the previous one stays live) until the operator sets the key. - */ -function assertControlPlaneKey(): void { - try { - controlPlaneKeyFromEnv(); - } catch { - throw new Error('EXOMEM_CONTROL_PLANE_KEY is missing or not 32 bytes of base64url'); - } -} - -async function main() { - if (env === 'production') assertControlPlaneKey(); - if (skip) { - console.log('[vercel-maybe-migrate] SKIP_VERCEL_MIGRATE=1 — skipping'); - return; - } - if (env !== 'production') { - console.log(`[vercel-maybe-migrate] VERCEL_ENV=${env} — skipping (production-only)`); - return; - } - console.log('[vercel-maybe-migrate] VERCEL_ENV=production — applying pending migrations'); - await applyMigrations({ dry: false }); -} - -main().catch((err) => { - console.error('[vercel-maybe-migrate] failed:', err); - process.exit(1); -}); diff --git a/scripts/wait-for-schema-release.ts b/scripts/wait-for-schema-release.ts new file mode 100644 index 00000000..679cb628 --- /dev/null +++ b/scripts/wait-for-schema-release.ts @@ -0,0 +1,164 @@ +/** + * Production build gate for Vercel (`vercel-build`). + * + * A production build runs no migration. The release job in the protected + * environment applies the migrations and the grants script for the tip of the + * default branch, then records a schema release for that commit in + * `schema_releases`. This script reads that row with the web app's own role and + * lets the build continue only once the row for the build's commit says + * `released`: + * + * - `released`: continue. When a newer release exists, the log says so. + * - `superseded`: fail at once. A newer commit carries the schema release. + * - no row, no table, or a select the role may not run yet: keep waiting up to + * 15 minutes, then fail. The merge commit's build starts before the job has + * created the table or given the select right. + * + * Preview and development builds neither migrate nor wait. The control-plane + * key check stays for production. `SKIP_SCHEMA_RELEASE_WAIT=1` lets the + * operator ship one build without the wait during an incident. The previous + * deployment keeps serving after a failed build. + */ + +import { fileURLToPath } from "node:url"; +import { Client } from "pg"; +import { controlPlaneKeyFromEnv } from "../src/lib/exomem-hosted/security"; +import { assertCommitHash } from "./migrate"; + +const WAIT_MS = 15 * 60 * 1000; +const POLL_MS = 10_000; +const TAG = "[wait-for-schema-release]"; + +type SchemaReleaseRead = { + /** The status of the build's own commit, or null when it has no row. */ + status: string | null; + /** The newest released commit, or null when none exists. */ + newestReleased: string | null; +}; + +type Dependencies = { + read: (commit: string) => Promise; + sleep: (ms: number) => Promise; + now: () => number; + log: (line: string) => void; + waitMs?: number; + pollMs?: number; +}; + +/** + * The web app's role may lack the select right, or the table may not exist, + * until the release job for this very commit has run. Both mean "not yet". + */ +const NOT_READABLE_YET = new Set(["42P01", "42501"]); + +async function waitForSchemaRelease(commit: string, deps: Dependencies): Promise { + const { read, sleep, now, log, waitMs = WAIT_MS, pollMs = POLL_MS } = deps; + const deadline = now() + waitMs; + let lastReason = "no schema release row yet"; + for (;;) { + let row: SchemaReleaseRead | null = null; + try { + row = await read(commit); + } catch (error) { + const code = String((error as { code?: unknown }).code ?? "no code"); + lastReason = NOT_READABLE_YET.has(code) + ? `schema_releases is not readable yet (${code})` + : `schema release read failed (${code})`; + } + if (row?.status === "released") { + if (row.newestReleased !== null && row.newestReleased !== commit) { + log( + `${TAG} a newer schema release exists (${row.newestReleased}); this commit's schema is older` + ); + } + log(`${TAG} schema release for ${commit} exists`); + return; + } + if (row?.status === "superseded") { + throw new Error(`commit ${commit} is superseded: a newer commit carries the schema release`); + } + if (row) lastReason = "no schema release row yet"; + if (now() + pollMs > deadline) { + throw new Error( + `no schema release for ${commit} within ${Math.round(waitMs / 60_000)} minutes: ${lastReason}` + ); + } + log(`${TAG} waiting for the schema release of ${commit}: ${lastReason}`); + await sleep(pollMs); + } +} + +async function readFromDatabase(commit: string): Promise { + const url = process.env.DATABASE_URL; + if (!url) throw new Error("DATABASE_URL is not set"); + const client = new Client({ + connectionString: url, + connectionTimeoutMillis: 10_000, + query_timeout: 10_000, + }); + await client.connect(); + try { + const { rows } = await client.query<{ status: string | null; newest_released: string | null }>( + // The newest released commit is read only once the build's own release exists: a poll + // that finds none pays one primary key lookup. The index on released rows serves the rest. + `SELECT own.status, + CASE WHEN own.status = 'released' THEN + (SELECT commit_sha FROM schema_releases WHERE status = 'released' + ORDER BY recorded_at DESC LIMIT 1) + END AS newest_released + FROM (SELECT $1::text AS commit_sha) AS wanted + LEFT JOIN schema_releases AS own ON own.commit_sha = wanted.commit_sha`, + [commit] + ); + return { status: rows[0]?.status ?? null, newestReleased: rows[0]?.newest_released ?? null }; + } finally { + await client.end().catch(() => undefined); + } +} + +/** + * The Paddle webhook seals the payment-failed email, and the start, sign-in + * and OAuth routes seal or key their state, with EXOMEM_CONTROL_PLANE_KEY. + * Without a valid key each of them fails on every request, and Paddle only + * retries its webhook. Refusing the production deploy costs one blocked + * deploy (the previous one stays live) until the operator sets the key. + */ +function assertControlPlaneKey(): void { + try { + controlPlaneKeyFromEnv(); + } catch { + throw new Error("EXOMEM_CONTROL_PLANE_KEY is missing or not 32 bytes of base64url"); + } +} + +export async function checkSchemaRelease( + env: Record, + deps: Dependencies +): Promise { + const environment = env.VERCEL_ENV ?? "unset"; + if (environment !== "production") { + deps.log(`${TAG} VERCEL_ENV=${environment}: skipping (production only)`); + return; + } + assertControlPlaneKey(); + if (env.SKIP_SCHEMA_RELEASE_WAIT === "1") { + deps.log(`${TAG} SKIP_SCHEMA_RELEASE_WAIT=1: skipping the schema release check`); + return; + } + const commit = env.VERCEL_GIT_COMMIT_SHA; + if (!commit) throw new Error("a production build carries no commit (VERCEL_GIT_COMMIT_SHA)"); + assertCommitHash(commit, "VERCEL_GIT_COMMIT_SHA"); + await waitForSchemaRelease(commit, deps); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + checkSchemaRelease(process.env, { + read: readFromDatabase, + sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), + now: () => Date.now(), + log: (line) => console.log(line), + }).catch((err) => { + console.error(`${TAG} failed:`, err instanceof Error ? err.message : err); + process.exit(1); + }); +} diff --git a/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts b/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts index 9c5983f6..c85bffde 100644 --- a/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts +++ b/src/app/api/cron/exomem-reconcile/__tests__/route.test.ts @@ -20,6 +20,11 @@ let contactCalls = 0; let contactShouldFail = false; let accessLogIsEnabled = false; let accessLogPruneCalls = 0; +let issuancePruneCalls = 0; +let issuancePruneResult: { records: number | null; tickets: number | null } = { + records: 5, + tickets: 2, +}; before(() => { mock.module("@/lib/exomem-hosted/cloud-admission", { @@ -98,6 +103,14 @@ before(() => { }, }, }); + mock.module("@/lib/exomem-hosted/issuance-maintenance", { + namedExports: { + pruneIssuanceState: async () => { + issuancePruneCalls += 1; + return issuancePruneResult; + }, + }, + }); mock.module("@/lib/exomem-hosted/email-change", { namedExports: { pruneExpiredExomemEmailChanges: async () => 2 }, }); @@ -151,6 +164,8 @@ afterEach(() => { contactShouldFail = false; accessLogIsEnabled = false; accessLogPruneCalls = 0; + issuancePruneCalls = 0; + issuancePruneResult = { records: 5, tickets: 2 }; if (ORIGINAL_SCHEDULER_SECRET === undefined) delete process.env.EXOMEM_HOSTED_SCHEDULER_SECRET; else process.env.EXOMEM_HOSTED_SCHEDULER_SECRET = ORIGINAL_SCHEDULER_SECRET; }); @@ -233,6 +248,7 @@ describe("GET /api/cron/exomem-reconcile", () => { }, emailChangesPruned: 2, accessLogAuthPruned: null, + issuancePruned: { records: 5, tickets: 2 }, }); }); @@ -301,9 +317,35 @@ describe("GET /api/cron/exomem-reconcile", () => { assert.deepEqual(JSON.parse(text), { success: false, error: { code: "CONTROL_PLANE_UNAVAILABLE", retryable: true }, + issuancePruned: { records: 5, tickets: 2 }, }); }); + // Retention of the issuance log must not wait on a provider outage in another lane, + // and the response must say what the prune did either way. + it("still prunes the issuance log when another lane fails, and reports the counts", async () => { + process.env.EXOMEM_HOSTED_SCHEDULER_SECRET = "cron-secret"; + paddleShouldFail = true; + const { GET } = await import("../route"); + const response = await GET(request("cron-secret")); + assert.equal(response.status, 503); + assert.equal(issuancePruneCalls, 1); + const body = (await response.json()) as { issuancePruned: unknown }; + assert.deepEqual(body.issuancePruned, { records: 5, tickets: 2 }); + }); + + it("reports a failed issuance prune as a failed lane, with null for the part that failed", async () => { + process.env.EXOMEM_HOSTED_SCHEDULER_SECRET = "cron-secret"; + issuancePruneResult = { records: null, tickets: 2 }; + const { GET } = await import("../route"); + const response = await GET(request("cron-secret")); + assert.equal(response.status, 503); + assert.equal(paddleRunCalls, 1, "the other lanes still ran"); + assert.equal(cloudReconcileCalls, 1); + const body = (await response.json()) as { issuancePruned: unknown }; + assert.deepEqual(body.issuancePruned, { records: null, tickets: 2 }); + }); + // A sweep that stops reclaiming client slots must not stay silent (the // partitions would fill again) or keep billing and Cloud work from running. it("still runs billing and Cloud work when the OAuth lane fails, then reports the failure", async () => { diff --git a/src/app/api/cron/exomem-reconcile/route.ts b/src/app/api/cron/exomem-reconcile/route.ts index 8147848f..abd7ee12 100644 --- a/src/app/api/cron/exomem-reconcile/route.ts +++ b/src/app/api/cron/exomem-reconcile/route.ts @@ -8,6 +8,10 @@ import { retryPendingCloudCancellationNotices } from "@/lib/exomem-hosted/cloud- import { runBoundedCloudDeletionFinish } from "@/lib/exomem-hosted/cloud-deletion-finish"; import { runBoundedPaddleReceiptContacts } from "@/lib/exomem-hosted/paddle-receipt-contact"; import { pruneExpiredExomemEmailChanges } from "@/lib/exomem-hosted/email-change"; +import { + pruneIssuanceState, + type IssuancePruneResult, +} from "@/lib/exomem-hosted/issuance-maintenance"; import { pruneExpiredOAuthState } from "@/lib/exomem-hosted/oauth-store"; import { promoteWaitlistedPeople, @@ -123,23 +127,43 @@ export async function GET(request: NextRequest): Promise { { status: 401, headers: { "cache-control": "no-store" } } ); } + // Set once the issuance lane has run, so the failure response can report it too. + let issuancePruned: IssuancePruneResult | null = null; try { // The OAuth lane deletes expired codes and tokens and gives back the slots - // of clients that can no longer be used (reclaim-oauth-client-slots). It is - // bounded per run and runs beside the other lanes, so a failure in any one - // still lets the others finish this tick before the route reports it. - const [paddleResult, cloudResult, oauthResult, contactsResult, changesResult, accessLogResult] = - await Promise.allSettled([ - runBoundedPaddleReconcile({ - maxSubscriptions: 5, - timeBudgetMs: 8_000, - }), - runCloudLane(), - pruneExpiredOAuthState(), - runBoundedPaddleReceiptContacts({ maxContacts: 5, timeBudgetMs: 8_000 }), - pruneExpiredExomemEmailChanges(), - accessLogEnabled() ? pruneAccessLogAuth() : Promise.resolve(null), - ]); + // of clients that can no longer be used (reclaim-oauth-client-slots). The + // issuance lane prunes the issuance log and the download ticket rows. Both + // are bounded per run and run beside the other lanes, so a failure in any + // one still lets the others finish this tick before the route reports it. + const [ + paddleResult, + cloudResult, + oauthResult, + contactsResult, + changesResult, + accessLogResult, + issuanceResult, + ] = await Promise.allSettled([ + runBoundedPaddleReconcile({ + maxSubscriptions: 5, + timeBudgetMs: 8_000, + }), + runCloudLane(), + pruneExpiredOAuthState(), + runBoundedPaddleReceiptContacts({ maxContacts: 5, timeBudgetMs: 8_000 }), + pruneExpiredExomemEmailChanges(), + accessLogEnabled() ? pruneAccessLogAuth() : Promise.resolve(null), + pruneIssuanceState(), + ]); + // The prune logs and reports a failed part as null. A failed part counts as a failed lane, + // so the log's retention never stops without the route saying so. + if (issuanceResult.status === "rejected") + console.error("exomem-issuance: retention lane failed"); + issuancePruned = + issuanceResult.status === "fulfilled" + ? issuanceResult.value + : { records: null, tickets: null }; + const issuanceFailed = issuancePruned.records === null || issuancePruned.tickets === null; if (oauthResult.status === "rejected") { console.error("exomem-oauth: expired state and client retirement lane failed"); } @@ -152,7 +176,8 @@ export async function GET(request: NextRequest): Promise { changesResult.status === "rejected" || paddleResult.status === "rejected" || cloudResult.status === "rejected" || - oauthResult.status === "rejected" + oauthResult.status === "rejected" || + issuanceFailed ) { throw new Error("EXOMEM_RECONCILIATION_LANE_FAILED"); } @@ -174,6 +199,7 @@ export async function GET(request: NextRequest): Promise { receiptContacts: contactsResult.value, emailChangesPruned: changesResult.value, accessLogAuthPruned: accessLogResult.value, + issuancePruned, oauth: { disabledCimd: oauthResult.value.disabledCimd, retiredAutoRegistered: oauthResult.value.retired.autoRegistered, @@ -192,6 +218,9 @@ export async function GET(request: NextRequest): Promise { { success: false, error: { code: "CONTROL_PLANE_UNAVAILABLE", retryable: true }, + // The counts, or null for a failed part, whichever lane failed. Absent only when the + // failure came before the issuance lane ran. + ...(issuancePruned ? { issuancePruned } : {}), }, { status: 503, headers: { "cache-control": "no-store" } } ); diff --git a/src/app/api/exomem/admin/service-credentials/__tests__/route.test.ts b/src/app/api/exomem/admin/service-credentials/__tests__/route.test.ts index 8b9274b9..5b88eaae 100644 --- a/src/app/api/exomem/admin/service-credentials/__tests__/route.test.ts +++ b/src/app/api/exomem/admin/service-credentials/__tests__/route.test.ts @@ -10,6 +10,7 @@ let issued: Record | null = null; let revokeCalls = 0; let nextRevokeResult = true; let nextList: unknown[] | null = []; +let nextIssueError: Error | null = null; before(() => { process.env.EXOMEM_ADMIN_TOKEN = ADMIN_TOKEN; @@ -17,6 +18,7 @@ before(() => { namedExports: { issueCloudServiceCredentialAtomic: async (input: Record) => { issued = input; + if (nextIssueError) throw nextIssueError; return { credentialId: CREDENTIAL_ID, tenantId: TENANT_ID, @@ -58,6 +60,7 @@ beforeEach(() => { revokeCalls = 0; nextRevokeResult = true; nextList = []; + nextIssueError = null; }); function request( @@ -110,6 +113,23 @@ describe("Exomem operator service credentials", () => { assert.equal(issued?.principal, "service:creator-platform"); }); + it("answers a retryable error with 503 and a Retry-After header, never a bare 500", async () => { + const { exomemErrors } = await import("@/lib/exomem-hosted/errors"); + nextIssueError = exomemErrors.serviceCredentialRetry(); + const { POST } = await import("../route"); + const response = await POST( + request("POST", { + authorization: `Bearer ${ADMIN_TOKEN}`, + body: { tenantId: TENANT_ID, principal: "service:creator-platform" }, + }) + ); + assert.equal(response.status, 503); + assert.equal(response.headers.get("retry-after"), "3"); + const body = (await response.json()) as { error: { code: string; retryable: boolean } }; + assert.equal(body.error.code, "SERVICE_CREDENTIAL_RETRY"); + assert.equal(body.error.retryable, true); + }); + it("enforces the service: principal format", async () => { const { POST } = await import("../route"); for (const principal of [ diff --git a/src/exomem-gateway/__tests__/cloud-download.test.ts b/src/exomem-gateway/__tests__/cloud-download.test.ts index dc79ca9b..6864936b 100644 --- a/src/exomem-gateway/__tests__/cloud-download.test.ts +++ b/src/exomem-gateway/__tests__/cloud-download.test.ts @@ -392,6 +392,29 @@ describe("Cloud download ticket at the gateway", () => { ); }); + it("looks the login up by the ticket's own path digest and expiry, so a ticket without its stored row finds none", async () => { + const now = Math.floor(Date.now() / 1000); + let selector: unknown; + const response = await handleCloudDownloadRequest( + ticketRequest(ticket({ now })), + ticketDeps({ + findLogin: async (looked) => { + selector = looked; + return null; + }, + }) + ); + assert.equal(response.status, 401); + assert.deepEqual(selector, { + familyId: CLAIMS.familyId, + grantId: CLAIMS.grantId, + ticket: { + pathSha256: createHash("sha256").update(PATH, "utf8").digest("hex"), + expiresAt: now + downloadTicketLifetimeSeconds(), + }, + }); + }); + it("refuses a ticket that is expired, for another path, forged or the wrong shape before any lookup or cell contact", async () => { const issuedLongAgo = Math.floor(Date.now() / 1000) - downloadTicketLifetimeSeconds() - 5; const cases: Array<[string, Request]> = [ diff --git a/src/exomem-gateway/cloud-handler.ts b/src/exomem-gateway/cloud-handler.ts index 2083c40a..7d9be993 100644 --- a/src/exomem-gateway/cloud-handler.ts +++ b/src/exomem-gateway/cloud-handler.ts @@ -57,6 +57,7 @@ import { REQUIRED_CLOUD_SCOPES, type ActiveCloudOAuthAccessToken, type ActiveCloudOAuthLogin, + type CloudDownloadTicketRow, } from "../lib/exomem-hosted/cloud-oauth"; import { findCloudServiceCredential, @@ -1118,7 +1119,12 @@ async function serveTicketDownload( cellId: claims.cellId, // Its own identity, so a long download never spends the Home channel's MCP bucket or slots. identityKey: `${claims.tenantId}:media-download`, - selector: { familyId: claims.familyId, grantId: claims.grantId }, + selector: { + familyId: claims.familyId, + grantId: claims.grantId, + // The login lookup also requires the ticket's stored row. + ticket: { pathSha256: claims.pathSha256, expiresAt: claims.expiresAt }, + }, // Only the app mints a ticket, and only from the owner's first-party login // of this tenant and cell. Anything else is refused whatever its MAC says. accepts: (login) => @@ -1135,7 +1141,7 @@ async function serveTicketDownload( type DownloadCaller = { cellId: string; identityKey: string; - selector: { familyId: string; grantId: string }; + selector: { familyId: string; grantId: string; ticket?: CloudDownloadTicketRow }; /** Whether the login, as it is now, is the one this credential may use. */ accepts(login: ActiveCloudOAuthLogin): boolean; refuse(): Response; diff --git a/src/lib/exomem-hosted/__tests__/account-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/account-postgres.integration.test.ts index 5f71f0fb..1ab5c270 100644 --- a/src/lib/exomem-hosted/__tests__/account-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/account-postgres.integration.test.ts @@ -25,6 +25,7 @@ import { loadExomemPaddleConfig } from "../paddle-config"; import { createSqlExomemPaddleEventStore } from "../paddle-event-store"; import { reconcileExomemPaddleSubscription } from "../paddle-reconciliation"; import { dispatchVerifiedExomemPaddleEvent } from "../paddle-webhook"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // The lifecycle emails this suite's facts enqueue carry an encrypted payload. @@ -44,6 +45,8 @@ const WEBHOOK_ENVIRONMENT = { PADDLE_WEBHOOK_SECRET: "pdl_ntfset_example", }; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool; let pool: Pool; let schema: string; let migrationsBefore: string; @@ -63,7 +66,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function interactiveTransaction(work: (tx: ExomemSql) => Promise): Promise { - const client = await pool.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN"); const result = await work(taggedSql(client)); @@ -195,7 +198,7 @@ function subscriptionEvent( async function dispatch(event: Record) { return dispatchVerifiedExomemPaddleEvent(event, { env: WEBHOOK_ENVIRONMENT, - store: createSqlExomemPaddleEventStore(taggedSql(pool)), + store: createSqlExomemPaddleEventStore(taggedSql(flowPool!)), // The Cloud cell hook is not under test; these tenants have no cell. cloudHook: async () => undefined, }); @@ -213,7 +216,7 @@ async function reconcile(tenant: PaddleTenant, event: Record) { PADDLE_API_KEY: "pdl_sdbx_apikey_example", EXOMEM_PADDLE_PRODUCT_ID: "pro_exomem_example", }), - store: createSqlExomemPaddleEventStore(taggedSql(pool)), + store: createSqlExomemPaddleEventStore(taggedSql(flowPool!)), transport: async () => Response.json({ data }), } ); @@ -274,13 +277,16 @@ describe("Exomem account facts on PostgreSQL", { skip: !databaseUrl }, () => { legacyPastDueWithoutReceipt = await insertPaddleTenant("past_due", "users"); await applyMigrations({ databaseUrl: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + // After the upgrade under test: the flow pool applies every migration to give its role rights. + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(interactiveTransaction); }); after(async () => { __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (migrationsBefore) rmSync(migrationsBefore, { recursive: true, force: true }); if (schema) { diff --git a/src/lib/exomem-hosted/__tests__/app-signout-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/app-signout-postgres.integration.test.ts index 211b8d32..14c77f24 100644 --- a/src/lib/exomem-hosted/__tests__/app-signout-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/app-signout-postgres.integration.test.ts @@ -9,6 +9,7 @@ import { drainExomemEmailOutbox } from "../email-outbox"; import { setOperationalEventSinkForTests } from "../observability"; import { pruneExpiredOAuthState } from "../oauth-store"; import { disconnectOwnerApp, listOwnerApps } from "../owner-apps"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // The app sign-out notice and Home's reachability state against real @@ -18,6 +19,8 @@ import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; const CLOUD_RESOURCE = "https://cloud.example.test/mcp/v1"; const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool | undefined; let pool: Pool | undefined; let schema: string | undefined; @@ -41,7 +44,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function interactiveTransaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -212,7 +215,8 @@ describe("Exomem app sign-out notice PostgreSQL integration", { skip: !databaseU await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(interactiveTransaction); }); @@ -220,6 +224,7 @@ describe("Exomem app sign-out notice PostgreSQL integration", { skip: !databaseU __setExomemSqlForTests(null); __setExomemTransactionForTests(null); setOperationalEventSinkForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-admission-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-admission-postgres.integration.test.ts index 95a33445..6d9c3b9d 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-admission-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-admission-postgres.integration.test.ts @@ -21,6 +21,7 @@ import { tokenDigest } from "../security"; import { setMonthlyUpdateEmail } from "../whats-new-digest/setting"; import type { PaddleTransport } from "../paddle-billing"; import type { ExomemPaddleConfig } from "../paddle-config"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // Task 3.3/3.4: Cloud admission (design D1) against real PostgreSQL. @@ -46,6 +47,8 @@ const FAKE_PADDLE_CONFIG: ExomemPaddleConfig = { }; const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool | undefined; let pool: Pool | undefined; let schema: string | undefined; @@ -61,7 +64,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function interactiveTransaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -226,13 +229,15 @@ describe("Exomem Cloud admission PostgreSQL integration", { skip: !databaseUrl } await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(interactiveTransaction); }); after(async () => { __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts index b7abe1c0..e1b53dbc 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-deletion-finish-postgres.integration.test.ts @@ -31,6 +31,7 @@ import { issueOAuthTokensFromCodeAtomic } from "../oauth-store"; import type { PaddleTransport } from "../paddle-billing"; import type { ExomemPaddleConfig } from "../paddle-config"; import { generateExternalToken, tokenDigest } from "../security"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // The lifecycle emails this suite's facts enqueue carry an encrypted payload. @@ -44,6 +45,8 @@ process.env.EXOMEM_CONTROL_PLANE_KEY ??= randomBytes(32).toString("base64url"); // D4's receipt fails the test. const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool | undefined; let pool: Pool | undefined; let schema: string | undefined; @@ -84,7 +87,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function interactiveTransaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -115,6 +118,7 @@ async function resetFleet(): Promise { "exomem_exports", "exomem_entitlements", "exomem_cloud_cells", + "exomem_cloud_service_credentials", "exomem_oauth_account_blocks", "exomem_tenants", "exomem_users", @@ -581,11 +585,14 @@ async function tenantFootprint(tenantId: string): Promise /** * D4's receipt, exactly: nothing else may remain for the tenant, except email - * 07's row, which keeps its address only until 30 days after it settles. + * 07's row, which keeps its address only until 30 days after it settles. The + * issuance log keeps one identifier-only record for each credential row the + * tenant held: a token family, an access token and each refresh token. */ function d4Receipt(input: { cells?: number; refreshTokens?: number } = {}): Record { return { exomem_cloud_cells: input.cells ?? 1, + exomem_cloud_issuance_log: 2 + (input.refreshTokens ?? 0), exomem_email_outbox: 1, exomem_entitlements: 1, exomem_oauth_access_tokens: 1, @@ -711,13 +718,15 @@ describe("Exomem Cloud deletion finish PostgreSQL integration", { skip: !databas await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(interactiveTransaction); }); after(async () => { __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); @@ -1522,6 +1531,73 @@ describe("Exomem Cloud deletion finish PostgreSQL integration", { skip: !databas await assertFinishedReceipt(tenant, { sourceState: "complimentary_active" }); }); + it("revokes a deleted account's service credentials, ends their issuance records, and leaves another tenant's credential live", async () => { + await resetFleet(); + const gone = await admitCloudTenant({ source: "complimentary" }); + const kept = await admitCloudTenant({ source: "complimentary" }); + const addCredential = async (tenantId: string, principal: string) => + ( + await pool!.query<{ id: string }>( + `INSERT INTO exomem_cloud_service_credentials + (tenant_id, principal, secret_digest, created_by_principal_digest) + VALUES ($1, $2, $3, $4) RETURNING id`, + [tenantId, principal, randomBytes(32), randomBytes(32)] + ) + ).rows[0]!.id; + const goneCredentials = [ + await addCredential(gone.tenantId, "service:creator-platform"), + await addCredential(gone.tenantId, "service:other-product"), + ]; + const keptCredential = await addCredential(kept.tenantId, "service:creator-platform"); + // The record ends at the database clock when the credential does, and stays open while it lives. + const state = async (ids: string[]) => + ( + await pool!.query( + `SELECT credential.revoked_at IS NOT NULL AS revoked, + credential.revoked_at <= now() AS revoked_at_clock, + credential.revoked_by_principal_digest IS NULL AS no_operator, + record.expires_at IS NULL AS record_open, + coalesce(record.expires_at > now() - interval '1 minute' AND record.expires_at <= now(), false) AS record_ended_now + FROM exomem_cloud_service_credentials AS credential + JOIN exomem_cloud_issuance_log AS record + ON record.credential_kind = 'service_credential' AND record.credential_id = credential.id + WHERE credential.id = ANY($1::uuid[]) ORDER BY credential.id`, + [ids] + ) + ).rows; + const live = { revoked: false, record_open: true, record_ended_now: false }; + const ended = { revoked: true, record_open: false, record_ended_now: true }; + const pick = (rows: Array>, shape: Record) => + rows.map((row) => Object.fromEntries(Object.keys(shape).map((key) => [key, row[key]]))); + assert.deepEqual(pick(await state([...goneCredentials, keptCredential]), live), [ + live, + live, + live, + ]); + + const fake = fakePaddle(); + let atFinish: Array> = []; + await confirmCloudDeletion(gone, async (tenantId) => { + // The confirmation's reconcile set the cell to deleted, and the database ended the credentials with it. + atFinish = await state(goneCredentials); + return finishCloudAccountDeletion(tenantId, withPaddle(fake)); + }); + assert.equal(await tenantStatus(gone.tenantId), "deleted"); + assert.deepEqual(pick(atFinish, ended), [ended, ended], "revoked when the cell was deleted"); + const afterFinish = await state(goneCredentials); + assert.deepEqual(pick(afterFinish, ended), [ended, ended]); + assert.ok( + afterFinish.every((row) => row.revoked_at_clock && row.no_operator), + "revoked at the database clock, by no operator" + ); + assert.deepEqual( + pick(await state([keptCredential]), live), + [live], + "another tenant's credential stays live" + ); + assert.notEqual(await tenantStatus(kept.tenantId), "deleted"); + }); + it("finishes a never-paid awaiting_checkout tenant, with no references, without any Paddle call", async () => { await resetFleet(); const tenant = await admitCloudTenant({ source: "paddle" }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-download-ticket.test.ts b/src/lib/exomem-hosted/__tests__/cloud-download-ticket.test.ts index 44f7ba86..4bea46db 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-download-ticket.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-download-ticket.test.ts @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; import { describe, it } from "node:test"; import { downloadTicketLifetimeSeconds, @@ -14,6 +15,7 @@ const LOGIN = { grantId: "33333333-3333-4333-8333-333333333333", }; const PATH = "Recordings/standup.mp4"; +const PATH_SHA256 = createHash("sha256").update(PATH, "utf8").digest("hex"); const NOW = 1_800_000_000; const FIFTEEN_MINUTES = 15 * 60; const ONE_HOUR = 60 * 60; @@ -23,15 +25,19 @@ function ticket(options: Parameters[2] = { now: NOW } } describe("download ticket", () => { - it("names the login it was minted for", () => { - assert.deepEqual(verifyDownloadTicket(ticket(), PATH, KEY, { now: NOW }), LOGIN); + it("names the login it was minted for, and the digest and expiry that its row is keyed by", () => { + assert.deepEqual(verifyDownloadTicket(ticket(), PATH, KEY, { now: NOW }), { + ...LOGIN, + pathSha256: PATH_SHA256, + expiresAt: NOW + FIFTEEN_MINUTES, + }); }); it("lives fifteen minutes unless configured, so a ticket in an address is a short bearer", () => { assert.equal(downloadTicketLifetimeSeconds({}), FIFTEEN_MINUTES); - assert.deepEqual( - verifyDownloadTicket(ticket(), PATH, KEY, { now: NOW + FIFTEEN_MINUTES - 1 }), - LOGIN + assert.equal( + verifyDownloadTicket(ticket(), PATH, KEY, { now: NOW + FIFTEEN_MINUTES - 1 })?.familyId, + LOGIN.familyId ); assert.equal(verifyDownloadTicket(ticket(), PATH, KEY, { now: NOW + FIFTEEN_MINUTES }), null); }); @@ -41,9 +47,9 @@ describe("download ticket", () => { assert.equal(downloadTicketLifetimeSeconds(env), ONE_HOUR); const longer = ticket({ now: NOW, lifetimeSeconds: ONE_HOUR }); const gateway = { lifetimeSeconds: ONE_HOUR }; - assert.deepEqual( - verifyDownloadTicket(longer, PATH, KEY, { now: NOW + ONE_HOUR - 1, ...gateway }), - LOGIN + assert.equal( + verifyDownloadTicket(longer, PATH, KEY, { now: NOW + ONE_HOUR - 1, ...gateway })?.familyId, + LOGIN.familyId ); assert.equal( verifyDownloadTicket(longer, PATH, KEY, { now: NOW + ONE_HOUR, ...gateway }), diff --git a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts index ee231fb0..3ac7e3a4 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-grants-postgres.integration.test.ts @@ -16,7 +16,9 @@ import { __setExomemSqlForTests, __setExomemTransactionForTests, type ExomemSql import { digestSecret, generateExternalToken } from "../security"; import { loadOpenServiceNotices } from "../service-notice-header"; import { assertCellAcceptsGrant } from "./cell-grant-rules"; +import { seedWorld } from "./identity-lock-fixture"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; +import { TEST_ROLE_PASSWORD } from "./test-role-password"; // D7 (reopened task 3.2): scripts/exomem-cloud-grants.sql is the single // implementation of both (1) schema-wide substrate_app DML plus default @@ -32,7 +34,7 @@ import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; process.env.EXOMEM_CONTROL_PLANE_KEY ??= randomBytes(32).toString("base64url"); const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; -const TEST_PASSWORD = "exomem-cloud-grants-test"; +const TEST_PASSWORD = TEST_ROLE_PASSWORD; const CLOUD_ROLES = ["substrate_app", "exomem_cellctl", "exomem_gateway"] as const; const C1_TABLES = [ "exomem_cloud_cells", @@ -53,6 +55,23 @@ const ACCESS_AUTH_TABLES = [ "exomem_cloud_access_challenges", ] as const; const CLOUD_RESOURCE = "https://cloud.example.test/mcp/v1"; +// The identity lock takes rights from these tables; each entry is what substrate_app holds on +// the table itself. A column grant is not a table right, so a column-locked table shows no update. +const NO_RIGHTS = { select: false, insert: false, update: false, delete: false }; +const LOCKED_TABLE_RIGHTS = { + exomem_oauth_grants: { select: true, insert: true, update: false, delete: false }, + exomem_oauth_token_families: { select: true, insert: true, update: false, delete: true }, + exomem_oauth_access_tokens: { select: true, insert: true, update: false, delete: true }, + exomem_oauth_refresh_tokens: { select: true, insert: true, update: false, delete: true }, + exomem_cloud_service_credentials: { select: true, insert: true, update: false, delete: false }, + exomem_oauth_clients: { select: true, insert: true, update: false, delete: false }, + exomem_tenants: { select: true, insert: true, update: false, delete: false }, + exomem_users: { select: true, insert: true, update: true, delete: false }, + exomem_marketplace_reviewer_credentials: { select: true, insert: true, update: true, delete: false }, + schema_releases: { ...NO_RIGHTS, select: true }, + exomem_cloud_issuance_log: NO_RIGHTS, + exomem_cloud_download_tickets: { select: true, insert: true, update: false, delete: true }, +} as const; let adminPool: Pool | undefined; let ownerPool: Pool | undefined; @@ -204,6 +223,8 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( } await applyMigrations({ databaseUrl: ownerUrl, migrationsDir: migrationRoot }); for (const role of CLOUD_ROLES) await ensureRole(role); + // The audit role reads the issuance log; the grants script gives it its reads only when it exists. + await ensureRole("substrate_audit"); await adminPool.query(`GRANT USAGE ON SCHEMA "${schema}" TO ${CLOUD_ROLES.join(", ")}`); // Grants must also work before any of migration 0079's columns exist. await applyMigrations({ databaseUrl: ownerUrl, migrationsDir: migrationRoot }); @@ -236,7 +257,8 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( name !== "schema_migrations" && name !== "exomem_cloud_image_history" && name !== "exomem_cloud_imports" && - name !== "exomem_cloud_exports" + name !== "exomem_cloud_exports" && + !(name in LOCKED_TABLE_RIGHTS) ); assert.ok(nonCloudTables.length > 10, "sanity: the schema of record has plenty of non-Cloud tables"); const privileges = await tablePrivileges("substrate_app", nonCloudTables); @@ -248,6 +270,11 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( assert.ok(grant.delete, `substrate_app should DELETE on ${name}`); } + const lockedPrivileges = await tablePrivileges("substrate_app", Object.keys(LOCKED_TABLE_RIGHTS)); + for (const [name, expected] of Object.entries(LOCKED_TABLE_RIGHTS)) { + assert.deepEqual(lockedPrivileges[name], expected, `substrate_app's rights on ${name}`); + } + // One real INSERT/DELETE round trip, not just has_table_privilege: a // simple table with no NOT NULL foreign keys. const host = `grant-roundtrip-${randomUUID()}.example.test`; @@ -1762,4 +1789,325 @@ describe("Exomem Cloud grants PostgreSQL integration", { skip: !databaseUrl }, ( __setExomemTransactionForTests(null); } }); + + // Task 5.6: rights are exact. Each assertion names the attacker that a wrong right or a missing pin lets in. + + /** What substrate_app may update on each column-locked table (design D2), typed here so that a wider grant fails. */ + const APP_UPDATABLE_COLUMNS: Record = { + exomem_oauth_grants: [ + "scopes", "refresh_allowed", "authorization_transaction_id", "updated_at", "revoked_at", + "client_context_override", + ], + exomem_oauth_token_families: ["revoked_at", "revoked_reason"], + exomem_oauth_access_tokens: ["revoked_at"], + exomem_oauth_refresh_tokens: ["consumed_at"], + exomem_cloud_service_credentials: ["revoked_at", "revoked_by_principal_digest"], + }; + // A one-way column is changeable and also in its guard's list: the guard refuses a change once it holds a value. + const ONE_WAY_COLUMNS: Record = { + exomem_oauth_grants: ["revoked_at"], + exomem_oauth_token_families: ["revoked_at"], + exomem_oauth_access_tokens: ["revoked_at"], + exomem_oauth_refresh_tokens: ["consumed_at"], + exomem_cloud_service_credentials: ["revoked_at", "revoked_by_principal_digest"], + }; + // Clients and tenants stay updatable except for these identity columns. + const IDENTITY_COLUMNS: Record = { + exomem_oauth_clients: ["id", "client_id"], + exomem_tenants: ["owner_user_id"], + }; + + async function columnsOf(table: string): Promise { + const { rows } = await ownerPool!.query<{ attname: string }>( + `SELECT attname FROM pg_attribute + WHERE attrelid = to_regclass($1) AND attnum > 0 AND NOT attisdropped ORDER BY attname`, + [table] + ); + return rows.map((row) => row.attname); + } + + /** The columns that a table's update guards read, from the dependencies PostgreSQL records for a WHEN clause. */ + async function guardedColumns(table: string): Promise { + const { rows } = await ownerPool!.query<{ attname: string }>( + `SELECT DISTINCT attribute.attname + FROM pg_trigger AS trigger + JOIN pg_depend AS dependency + ON dependency.classid = 'pg_trigger'::regclass AND dependency.objid = trigger.oid + AND dependency.refclassid = 'pg_class'::regclass AND dependency.refobjid = trigger.tgrelid + AND dependency.refobjsubid > 0 + JOIN pg_attribute AS attribute + ON attribute.attrelid = dependency.refobjid AND attribute.attnum = dependency.refobjsubid + WHERE trigger.tgrelid = to_regclass($1) AND NOT trigger.tgisinternal + AND trigger.tgfoid = to_regproc('exomem_refuse_unless_schema_owner') + AND trigger.tgtype & 16 = 16 + ORDER BY attribute.attname`, + [table] + ); + return rows.map((row) => row.attname); + } + + async function updatableByApp(table: string, columns: readonly string[]): Promise { + const { rows } = await ownerPool!.query<{ attname: string }>( + `SELECT column_name AS attname FROM unnest($2::text[]) AS column_name + WHERE has_column_privilege('substrate_app', $1, column_name, 'UPDATE') ORDER BY column_name`, + [table, columns] + ); + return rows.map((row) => row.attname); + } + + it("lets the web app's role update only the changeable columns of each locked table, and puts every column in a guard's list or the role's, never neither", async () => { + const tables = [...Object.keys(APP_UPDATABLE_COLUMNS), ...Object.keys(IDENTITY_COLUMNS)]; + for (const table of tables) { + const columns = await columnsOf(table); + const changeable = await updatableByApp(table, columns); + const guarded = await guardedColumns(table); + const expectedChangeable = + table in APP_UPDATABLE_COLUMNS + ? [...APP_UPDATABLE_COLUMNS[table]!].sort() + : columns.filter((column) => !IDENTITY_COLUMNS[table]!.includes(column)); + assert.deepEqual(changeable, expectedChangeable, `${table}: columns that substrate_app may update`); + assert.deepEqual( + columns.filter((column) => !changeable.includes(column) && !guarded.includes(column)), + [], + `${table}: a column in neither list` + ); + assert.deepEqual( + changeable.filter((column) => guarded.includes(column)), + [...(ONE_WAY_COLUMNS[table] ?? [])].sort(), + `${table}: a column in both lists is a one-way column` + ); + } + }); + + it("gives the gateway only column reads and the controller nothing on the locked tables, the log and the ticket rows", async () => { + const tables = Object.keys(LOCKED_TABLE_RIGHTS); + const holds = async (role: string) => + ( + await ownerPool!.query<{ relname: string; scope: string; privilege_type: string }>( + `SELECT c.relname, 'table' AS scope, acl.privilege_type + FROM pg_class AS c, aclexplode(c.relacl) AS acl + WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ANY($1) AND acl.grantee = $2::regrole + UNION ALL + SELECT c.relname, a.attname, acl.privilege_type + FROM pg_attribute AS a JOIN pg_class AS c ON c.oid = a.attrelid, aclexplode(a.attacl) AS acl + WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ANY($1) + AND a.attnum > 0 AND acl.grantee = $2::regrole + ORDER BY 1, 2, 3`, + [tables, role] + ) + ).rows; + assert.deepEqual(await holds("exomem_cellctl"), [], "the controller holds nothing on these tables"); + const gateway = await holds("exomem_gateway"); + assert.deepEqual( + gateway.filter((held) => held.scope === "table" || held.privilege_type !== "SELECT"), + [], + "the gateway holds column reads only" + ); + assert.deepEqual( + gateway.filter((held) => held.relname === "exomem_cloud_download_tickets").map((held) => held.scope), + ["expires_at", "family_id", "path_sha256"], + "the gateway matches a ticket by these three columns" + ); + assert.deepEqual( + gateway.filter((held) => ["exomem_cloud_issuance_log", "schema_releases"].includes(held.relname)), + [], + "the gateway reads neither the log nor the schema releases" + ); + }); + + it("gives the audit role select on the log and the compared columns, and nothing else", async () => { + const audit = await ownerPool!.query<{ relname: string; scope: string; privilege_type: string }>( + `SELECT c.relname, 'table' AS scope, acl.privilege_type + FROM pg_class AS c, aclexplode(c.relacl) AS acl + WHERE c.relnamespace = current_schema()::regnamespace AND acl.grantee = 'substrate_audit'::regrole + UNION ALL + SELECT c.relname, a.attname, acl.privilege_type + FROM pg_attribute AS a JOIN pg_class AS c ON c.oid = a.attrelid, aclexplode(a.attacl) AS acl + WHERE c.relnamespace = current_schema()::regnamespace AND a.attnum > 0 AND acl.grantee = 'substrate_audit'::regrole + ORDER BY 1, 2, 3` + ); + const compared = [ + "exomem_cloud_download_tickets", "exomem_cloud_service_credentials", "exomem_oauth_access_tokens", + "exomem_oauth_refresh_tokens", "exomem_oauth_token_families", + ].flatMap((relname) => ["created_at", "id"].map((scope) => ({ relname, scope, privilege_type: "SELECT" }))); + const expected = [ + { relname: "exomem_cloud_issuance_log", scope: "table", privilege_type: "SELECT" }, + ...compared, + { relname: "exomem_tenants", scope: "id", privilege_type: "SELECT" }, + { relname: "exomem_tenants", scope: "owner_user_id", privilege_type: "SELECT" }, + ].sort((a, b) => (a.relname + a.scope).localeCompare(b.relname + b.scope)); + assert.deepEqual( + audit.rows.sort((a, b) => (a.relname + a.scope).localeCompare(b.relname + b.scope)), + expected + ); + }); + + it("leaves a column added after the grants script unwritable for the web app's role, also after a second run", async () => { + const tables = Object.keys(APP_UPDATABLE_COLUMNS); + for (const table of tables) await ownerPool!.query(`ALTER TABLE ${table} ADD COLUMN grants_probe integer`); + try { + await applyMigrations({ databaseUrl: roleUrl(databaseUrl!, "substrate_owner") }); + for (const table of tables) { + await assert.rejects( + appPool!.query(`UPDATE ${table} SET grants_probe = 1 WHERE false`), + (error: Error & { code?: string }) => error.code === "42501", + table + ); + } + } finally { + for (const table of tables) await ownerPool!.query(`ALTER TABLE ${table} DROP COLUMN grants_probe`); + } + }); + + it("leaves the trigger right with each table's owner, also after a hand-typed grant and a second run", async () => { + const holders = async () => + ( + await ownerPool!.query<{ relname: string; grantee: string }>( + `SELECT c.relname, CASE acl.grantee WHEN 0 THEN 'PUBLIC' ELSE pg_get_userbyid(acl.grantee)::text END AS grantee + FROM pg_class AS c, aclexplode(c.relacl) AS acl + WHERE c.relnamespace = current_schema()::regnamespace AND c.relkind IN ('r', 'p') + AND acl.privilege_type = 'TRIGGER' AND acl.grantee <> c.relowner + ORDER BY 1, 2` + ) + ).rows; + assert.deepEqual(await holders(), [], "no role but the owner holds the trigger right"); + await adminPool!.query( + `GRANT TRIGGER ON "${schema}".exomem_tenants, "${schema}".exomem_cloud_issuance_log TO substrate_app, exomem_gateway, PUBLIC` + ); + assert.equal((await holders()).length > 0, true, "the hand-typed grant took effect"); + await applyMigrations({ databaseUrl: roleUrl(databaseUrl!, "substrate_owner") }); + assert.deepEqual(await holders(), [], "a grants run takes the right back"); + }); + + it("runs with owner rights in exactly three functions, and lets only the web app's role call the prune", async () => { + const definers = await ownerPool!.query<{ proname: string }>( + `SELECT proname FROM pg_proc WHERE pronamespace = current_schema()::regnamespace AND prosecdef ORDER BY proname` + ); + assert.deepEqual( + definers.rows.map((row) => row.proname), + ["exomem_prune_issuance_log", "exomem_record_issuance", "exomem_record_memory_health_proof"] + ); + const executors = await ownerPool!.query<{ proname: string; grantee: string }>( + `SELECT proc.proname, CASE acl.grantee WHEN 0 THEN 'PUBLIC' ELSE pg_get_userbyid(acl.grantee)::text END AS grantee + FROM pg_proc AS proc, aclexplode(coalesce(proc.proacl, acldefault('f', proc.proowner))) AS acl + WHERE proc.pronamespace = current_schema()::regnamespace AND acl.privilege_type = 'EXECUTE' + AND proc.proname = ANY($1) AND acl.grantee <> proc.proowner + ORDER BY 1, 2`, + [[ + "exomem_prune_issuance_log", "exomem_record_issuance", "exomem_record_memory_health_proof", + "exomem_refuse_unless_schema_owner", + ]] + ); + assert.equal( + executors.rows.some((row) => row.grantee === "PUBLIC"), + false, + "PUBLIC executes none of them, nor the guard function" + ); + assert.deepEqual( + executors.rows.filter((row) => row.proname === "exomem_prune_issuance_log"), + [{ proname: "exomem_prune_issuance_log", grantee: "substrate_app" }] + ); + assert.deepEqual( + executors.rows.filter((row) => ["exomem_record_issuance", "exomem_refuse_unless_schema_owner"].includes(row.proname)), + [], + "no role but the owner executes the recording function or the guard function" + ); + }); + + it("pins a search path on each function that runs as the schema owner for another role, naming only schemas that a trusted role owns", async () => { + // The set of task 2.5, read from the catalog the way the migration reads it. + const pinned = await ownerPool!.query<{ proname: string; pin: string | null; untrusted: string[] }>( + `SELECT proc.proname, + (SELECT substr(setting, length('search_path=') + 1) FROM unnest(proc.proconfig) AS setting + WHERE setting LIKE 'search_path=%') AS pin, + ARRAY( + SELECT namespace.nspname::text FROM unnest( + string_to_array(replace((SELECT substr(setting, length('search_path=') + 1) + FROM unnest(proc.proconfig) AS setting WHERE setting LIKE 'search_path=%'), '"', ''), ', ') + ) AS schema_name + JOIN pg_namespace AS namespace ON namespace.nspname = schema_name + WHERE namespace.nspowner NOT IN (proc.proowner, 10, 'pg_database_owner'::regrole) + ) AS untrusted + FROM pg_proc AS proc + JOIN pg_language AS language ON language.oid = proc.prolang + WHERE proc.pronamespace = current_schema()::regnamespace + AND proc.proowner = 'substrate_owner'::regrole + AND language.lanname NOT IN ('c', 'internal') + AND NOT EXISTS ( + SELECT 1 FROM pg_depend AS membership + WHERE membership.classid = 'pg_proc'::regclass AND membership.objid = proc.oid AND membership.deptype = 'e' + ) + AND ( + proc.prorettype = 'trigger'::regtype OR proc.prosecdef + OR EXISTS ( + SELECT 1 FROM pg_depend AS caller + LEFT JOIN pg_class AS caller_index + ON caller.classid = 'pg_class'::regclass AND caller_index.oid = caller.objid + WHERE caller.refclassid = 'pg_proc'::regclass AND caller.refobjid = proc.oid + AND (caller.classid IN ('pg_constraint'::regclass, 'pg_attrdef'::regclass) + OR caller_index.relkind IN ('i', 'I')) + ) + ) + ORDER BY proc.proname` + ); + assert.ok(pinned.rows.length >= 4, "sanity: the set holds the guard, the recording function, the prune and more"); + for (const row of pinned.rows) { + const path = (row.pin ?? "").replaceAll('"', "").split(", "); + assert.equal(path[0], "pg_catalog", `${row.proname} starts its search path with pg_catalog`); + assert.equal(path.at(-1), "pg_temp", `${row.proname} ends its search path with pg_temp`); + assert.deepEqual(row.untrusted, [], `${row.proname} names a schema that an untrusted role owns`); + } + for (const name of ["exomem_refuse_unless_schema_owner", "exomem_record_issuance", "exomem_prune_issuance_log"]) { + assert.ok(pinned.rows.some((row) => row.proname === name), `${name} is in the set`); + } + }); + + it("keeps an operator that a role defines in a schema it owns from changing what a pinned function does", async () => { + // The grants-suite owner cannot create a schema for another role, so the superuser does. Production + // gives the web app's role no create right; this is the state that a stray create right would give. + const attackSchema = `operator_attack_${randomUUID().replaceAll("-", "").slice(0, 12)}`; + await adminPool!.query(`CREATE SCHEMA "${attackSchema}" AUTHORIZATION substrate_app`); + await ownerPool!.query( + `CREATE FUNCTION exomem_operator_probe(a varchar, b varchar) RETURNS boolean + LANGUAGE sql AS 'SELECT a = b'` + ); + const attacker = await appPool!.connect(); + try { + await attacker.query( + `CREATE FUNCTION "${attackSchema}".hijacked(varchar, varchar) RETURNS boolean + LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'operator hijacked'; END $$` + ); + await attacker.query( + `CREATE OPERATOR "${attackSchema}".= (LEFTARG = varchar, RIGHTARG = varchar, FUNCTION = "${attackSchema}".hijacked)` + ); + await attacker.query(`SET search_path = "${attackSchema}", "${schema}", public`); + // The control: a function with no pin takes the caller's path, so the attack works on this server. + await assert.rejects( + attacker.query(`SELECT "${schema}".exomem_operator_probe('a', 'a')`), + /operator hijacked/ + ); + await ownerPool!.query("ALTER FUNCTION exomem_operator_probe(varchar, varchar) SET search_path = pg_catalog, pg_temp"); + const pinnedProbe = await attacker.query(`SELECT "${schema}".exomem_operator_probe('a', 'a') AS equal`); + assert.equal(pinnedProbe.rows[0].equal, true, "the same function with a pin ignores the operator"); + + // The real recording function runs in that session, and its record is written. + const world = await seedWorld(ownerPool!); + const inserted = await attacker.query<{ id: string }>( + `INSERT INTO "${schema}".exomem_oauth_access_tokens + (access_digest, grant_id, family_id, client_id, resource, scopes, expires_at) + VALUES ($1, $2, $3, $4, 'https://gateway.example.test/mcp', ARRAY['mcp:read'], now() + interval '1 hour') + RETURNING id`, + [randomBytes(32), world.grantId, world.familyId, world.clientId] + ); + const recorded = await ownerPool!.query( + "SELECT count(*)::int AS count FROM exomem_cloud_issuance_log WHERE credential_id = $1", + [inserted.rows[0]!.id] + ); + assert.equal(recorded.rows[0].count, 1); + } finally { + attacker.release(); + await adminPool!.query(`DROP SCHEMA "${attackSchema}" CASCADE`); + await ownerPool!.query("DROP FUNCTION exomem_operator_probe(varchar, varchar)"); + } + }); }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts index 809dc4ad..99243148 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-home-postgres.integration.test.ts @@ -21,6 +21,7 @@ import { getOwnerCloudHomeStatus } from "../cloud-status"; import { __setExomemSqlForTests, __setExomemTransactionForTests, type ExomemSql } from "../db"; import { revokeOAuthAccountForOwnerTenantAtomic } from "../oauth-store"; import { digestSecret, generateExternalToken } from "../security"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; import { handleCloudStorage } from "../cloud-storage"; import { loadExomemPaddleConfig } from "../paddle-config"; @@ -47,6 +48,8 @@ const LEVELS = { coding: { level: "balanced", source: "default" }, conversation: { level: "balanced", source: "default" }, }; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool; let pool: Pool; let schema: string; @@ -458,9 +461,10 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database scoped.searchParams.set("options", `-c search_path=${schema},public`); await applyMigrations({ databaseUrl: scoped.toString() }); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(async (work) => { - const client = await pool.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN"); const result = await work(taggedSql(client)); @@ -478,6 +482,7 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database after(async () => { __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); await pool?.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); @@ -542,7 +547,7 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database }, { env: f.env, - store: createSqlExomemPaddleEventStore(taggedSql(pool)), + store: createSqlExomemPaddleEventStore(taggedSql(flowPool!)), cloudHook: async () => {}, } ); @@ -706,6 +711,29 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database assert.equal(rows[0].admission_mode, "first_party"); }); + it("records the Home family once and the access token of each mint", async () => { + const alice = await owner(); + const cell = fakeCell(() => ({ revision: "r1", levels: LEVELS })); + const recorded = async () => + ( + await pool.query( + `SELECT credential_kind, count(*)::int AS count FROM exomem_cloud_issuance_log + WHERE tenant_id = $1 AND user_id = $2 GROUP BY credential_kind ORDER BY credential_kind`, + [alice.tenantId, alice.userId] + ) + ).rows; + assert.equal((await getLevels(alice, cell.fetchCell)).status, 200); + assert.deepEqual(await recorded(), [ + { credential_kind: "access_token", count: 1 }, + { credential_kind: "token_family", count: 1 }, + ]); + assert.equal((await getLevels(alice, cell.fetchCell)).status, 200); + assert.deepEqual(await recorded(), [ + { credential_kind: "access_token", count: 2 }, + { credential_kind: "token_family", count: 1 }, + ]); + }); + it("lets the gateway refuse a Home token minted before an account block or a started deletion", async () => { const blocked = await owner(); const deleting = await owner(); @@ -873,7 +901,7 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database // The session lookup refuses a blocked account, so the block lands in // the window after the session and cell checks, before the mint. __setExomemSqlForTests(async (strings, ...values) => { - const result = await taggedSql(pool)(strings, ...values); + const result = await taggedSql(flowPool!)(strings, ...values); if (strings.join("").includes("exomem-cloud:home-serving-cell")) { await revokeOAuthAccountForOwnerTenantAtomic({ ownerUserId: alice.userId, @@ -891,7 +919,7 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database reason: "ACCOUNT_ACCESS_CLOSED", }); } finally { - __setExomemSqlForTests(taggedSql(pool)); + __setExomemSqlForTests(taggedSql(flowPool!)); } const minted = await pool.query( `SELECT count(*)::integer AS tokens FROM exomem_oauth_access_tokens AS token @@ -907,7 +935,7 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database // The deletion commits after the session and cell checks, before the // mint, as one transaction: the tenant and its cell change together. __setExomemSqlForTests(async (strings, ...values) => { - const result = await taggedSql(pool)(strings, ...values); + const result = await taggedSql(flowPool!)(strings, ...values); if (strings.join("").includes("exomem-cloud:home-serving-cell")) { const deletion = await pool.connect(); try { @@ -936,7 +964,7 @@ describe("Cloud Home channel and exports PostgreSQL boundary", { skip: !database reason: "ACCOUNT_ACCESS_CLOSED", }); } finally { - __setExomemSqlForTests(taggedSql(pool)); + __setExomemSqlForTests(taggedSql(flowPool!)); } assert.equal(cell.calls.length, 0); }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts new file mode 100644 index 00000000..bb77aa9d --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/cloud-identity-lock-postgres.integration.test.ts @@ -0,0 +1,698 @@ +import assert from "node:assert/strict"; +import { randomBytes, randomUUID } from "node:crypto"; +import { after, before, describe, it } from "node:test"; +import type { Pool, PoolClient } from "pg"; +import { applyMigrations } from "../../../../scripts/migrate"; +import { + createLockFixture, + randomCellId, + seedClient, + seedWorld, + tableSnapshot, + type LockFixture, + type LockState, + type World, +} from "./identity-lock-fixture"; + +// The identity lock (design D2) against the web app's own database role. Each attack runs twice: +// in the narrow state, which is what the grants script gives, and in the wide state, where the +// role also holds select, insert, update, delete and truncate on every table. In the wide state +// only the guards stand, so each refusal there names the guard. + +const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +const LOCKED = "EXOMEM_ROW_LOCKED"; + +type Attack = { + name: string; + /** The table whose rows must be unchanged afterwards. */ + table: string; + text: string; + params?: unknown[]; + /** A guard refuses it in the wide state; otherwise a missing right does, in both states. */ + guard?: boolean; +}; + +type Victims = { + grantId: string; + clientId: string; + tenantId: string; + userId: string; + serviceCredentialId: string; + reviewerCredentialId: string; + ticketId: string; + /** A cell row of the first world's tenant that nothing else references. */ + cellId: string; +}; + +/** Rows that nothing references, so a refusal can only come from the lock and not from a foreign key. */ +async function seedVictims(fx: LockFixture, world: World): Promise { + const id = async (text: string, values: unknown[] = []) => + (await fx.owner.query<{ id: string }>(text, values)).rows[0]!.id; + const grantId = await id( + `INSERT INTO exomem_oauth_grants (user_id, tenant_id, client_id, resource, scopes) + VALUES ($1, $2, $3, $4, ARRAY['mcp:read']) RETURNING id`, + [world.userId, world.tenantId, world.clientId, `https://victim.example.test/${randomUUID()}`] + ); + const clientId = await seedClient(fx.owner); + const lonelyUserId = await id("INSERT INTO exomem_users (email) VALUES ($1) RETURNING id", [ + `victim-${randomUUID()}@example.test`, + ]); + const reviewerOwnerId = await id("INSERT INTO exomem_users (email) VALUES ($1) RETURNING id", [ + `victim-${randomUUID()}@example.test`, + ]); + const ownerOfVictimTenant = await id( + "INSERT INTO exomem_users (email) VALUES ($1) RETURNING id", + [`victim-${randomUUID()}@example.test`] + ); + const tenantId = await id("INSERT INTO exomem_tenants (owner_user_id) VALUES ($1) RETURNING id", [ + ownerOfVictimTenant, + ]); + const serviceCredentialId = await id( + `INSERT INTO exomem_cloud_service_credentials (tenant_id, principal, secret_digest, created_by_principal_digest) + VALUES ($1, $2, $3, $4) RETURNING id`, + [world.tenantId, `service:t${randomBytes(6).toString("hex")}`, randomBytes(32), randomBytes(32)] + ); + const reviewerTenant = await id( + "INSERT INTO exomem_tenants (owner_user_id, marketplace_reviewer_purpose) VALUES ($1, true) RETURNING id", + [reviewerOwnerId] + ); + const reviewerCredentialId = await id( + `INSERT INTO exomem_marketplace_reviewer_credentials ( + provider, username_digest, password_hash, owner_user_id, tenant_id, fixture_version, + fixture_payload_digest, created_by_principal_digest, expires_at + ) VALUES ('openai', $1, '$argon2id$test', $2, $3, 'sample-v1', $4, $5, now() + interval '1 day') + RETURNING id`, + [randomBytes(32), reviewerOwnerId, reviewerTenant, "a".repeat(64), randomBytes(32)] + ); + const ticketId = await id( + `INSERT INTO exomem_cloud_download_tickets (family_id, path_sha256, expires_at) + VALUES ($1, $2, now() + interval '15 minutes') RETURNING id`, + [world.familyId, "0".repeat(64)] + ); + const cellId = world.cellId; + return { + grantId, + clientId, + tenantId, + userId: lonelyUserId, + serviceCredentialId, + reviewerCredentialId, + ticketId, + cellId, + }; +} + +function attackList(fx: LockFixture, a: World, b: World, v: Victims): Attack[] { + const q = fx.q; + const grants = q("exomem_oauth_grants"); + const families = q("exomem_oauth_token_families"); + const access = q("exomem_oauth_access_tokens"); + const refresh = q("exomem_oauth_refresh_tokens"); + const credentials = q("exomem_cloud_service_credentials"); + const clients = q("exomem_oauth_clients"); + const tenants = q("exomem_tenants"); + const users = q("exomem_users"); + const reviewers = q("exomem_marketplace_reviewer_credentials"); + const tickets = q("exomem_cloud_download_tickets"); + const cells = q("exomem_cloud_cells"); + const attacks: Attack[] = [ + { + name: "re-point a grant's tenant and user by update", + table: grants, + text: `UPDATE ${grants} SET tenant_id = $2, user_id = $3 WHERE id = $1`, + params: [a.grantId, b.tenantId, b.userId], + guard: true, + }, + { + name: "re-point a grant's tenant and user by a conflict action", + table: grants, + text: `INSERT INTO ${grants} (id, user_id, tenant_id, client_id, resource, scopes) + VALUES ($1, $2, $3, $4, 'https://other.example.test/mcp', ARRAY['mcp:read']) + ON CONFLICT (id) DO UPDATE SET tenant_id = EXCLUDED.tenant_id, user_id = EXCLUDED.user_id`, + params: [a.grantId, b.userId, b.tenantId, a.clientId], + guard: true, + }, + { + name: "overwrite an access token's digest", + table: access, + text: `UPDATE ${access} SET access_digest = $2 WHERE id = $1`, + params: [a.accessTokenId, randomBytes(32)], + guard: true, + }, + { + name: "overwrite a refresh token's digest", + table: refresh, + text: `UPDATE ${refresh} SET refresh_digest = $2 WHERE id = $1`, + params: [a.refreshTokenId, randomBytes(32)], + guard: true, + }, + { + name: "extend an access token's expiry", + table: access, + text: `UPDATE ${access} SET expires_at = expires_at + interval '30 days' WHERE id = $1`, + params: [a.accessTokenId], + guard: true, + }, + { + name: "extend a token family's expiry", + table: families, + text: `UPDATE ${families} SET expires_at = expires_at + interval '30 days' WHERE id = $1`, + params: [a.familyId], + guard: true, + }, + { + name: "extend a refresh token's expiry", + table: refresh, + text: `UPDATE ${refresh} SET expires_at = expires_at + interval '30 days' WHERE id = $1`, + params: [a.refreshTokenId], + guard: true, + }, + { + name: "change a grant's reviewer reference", + table: grants, + text: `UPDATE ${grants} SET reviewer_credential_id = $2 WHERE id = $1`, + params: [a.grantId, v.reviewerCredentialId], + guard: true, + }, + { + name: "clear a grant's revocation time", + table: grants, + text: `UPDATE ${grants} SET revoked_at = NULL WHERE id = $1`, + params: [a.spent.grantId], + guard: true, + }, + { + name: "clear a token family's revocation time", + table: families, + text: `UPDATE ${families} SET revoked_at = NULL WHERE id = $1`, + params: [a.spent.familyId], + guard: true, + }, + { + name: "clear an access token's revocation time", + table: access, + text: `UPDATE ${access} SET revoked_at = NULL WHERE id = $1`, + params: [a.spent.accessTokenId], + guard: true, + }, + { + name: "clear a refresh token's consumption time", + table: refresh, + text: `UPDATE ${refresh} SET consumed_at = NULL WHERE id = $1`, + params: [a.spent.refreshTokenId], + guard: true, + }, + { + name: "clear a service credential's revocation time", + table: credentials, + text: `UPDATE ${credentials} SET revoked_at = NULL WHERE id = $1`, + params: [a.spent.serviceCredentialId], + guard: true, + }, + { + name: "re-point a service credential's tenant", + table: credentials, + text: `UPDATE ${credentials} SET tenant_id = $2 WHERE id = $1`, + params: [a.serviceCredentialId, b.tenantId], + guard: true, + }, + { + name: "overwrite a service credential's digest", + table: credentials, + text: `UPDATE ${credentials} SET secret_digest = $2 WHERE id = $1`, + params: [a.serviceCredentialId, randomBytes(32)], + guard: true, + }, + { + name: "change a tenant's owner", + table: tenants, + text: `UPDATE ${tenants} SET owner_user_id = $2 WHERE id = $1`, + // The owner column is unique, so the new owner must be a user that owns no tenant. + params: [a.tenantId, v.userId], + guard: true, + }, + { + name: "change a client's identifier", + table: clients, + text: `UPDATE ${clients} SET client_id = 'https://attacker.example.test/client.json' WHERE id = $1`, + params: [a.clientId], + guard: true, + }, + { + // The gateway reaches a cell through its tenant. The victim tenant has no cell, so no unique index answers first. + name: "re-point a cell to another tenant", + table: cells, + text: `UPDATE ${cells} SET tenant_id = $2 WHERE cell_id = $1`, + params: [v.cellId, v.tenantId], + guard: true, + }, + { + name: "rename a cell", + table: cells, + text: `UPDATE ${cells} SET cell_id = $2 WHERE cell_id = $1`, + params: [v.cellId, randomCellId()], + guard: true, + }, + { + name: "update a download ticket row", + table: tickets, + text: `UPDATE ${tickets} SET expires_at = expires_at + interval '30 days' WHERE id = $1`, + params: [v.ticketId], + guard: true, + }, + ]; + const deletions: Array<[string, string, string]> = [ + ["grant", grants, v.grantId], + ["client", clients, v.clientId], + ["tenant", tenants, v.tenantId], + ["user", users, v.userId], + ["service credential", credentials, v.serviceCredentialId], + ["reviewer credential", reviewers, v.reviewerCredentialId], + ]; + for (const [label, table, id] of deletions) { + attacks.push({ + name: `delete a ${label}`, + table, + text: `DELETE FROM ${table} WHERE id = $1`, + params: [id], + guard: true, + }); + attacks.push({ + // PostgreSQL refuses a plain truncate of a referenced table, for every role, before any trigger runs. + name: `truncate the ${label} table with CASCADE`, + table, + text: `TRUNCATE ${table} CASCADE`, + guard: true, + }); + } + // A cell row ends as desired_state 'deleted'; no flow deletes the row. + attacks.push({ + name: "delete a cell", + table: cells, + text: `DELETE FROM ${cells} WHERE cell_id = $1`, + params: [v.cellId], + guard: true, + }); + attacks.push({ + name: "truncate the cell table with CASCADE", + table: cells, + text: `TRUNCATE ${cells} CASCADE`, + guard: true, + }); + // A cascade from a table that a guarded table references reaches the guarded table's truncate guard. + for (const referenced of [ + "exomem_oauth_authorization_transactions", + "exomem_agent_contract_candidates", + ]) { + attacks.push({ + name: `truncate ${referenced} with CASCADE`, + table: grants, + text: `TRUNCATE ${q(referenced)} CASCADE`, + guard: true, + }); + } + attacks.push({ + name: "create a trigger on a guarded table", + table: grants, + text: `CREATE TRIGGER app_probe AFTER INSERT ON ${grants} + FOR EACH ROW EXECUTE FUNCTION ${q("exomem_refuse_unless_schema_owner")}()`, + }); + return attacks; +} + +async function refusal( + pool: Pool | PoolClient, + attack: Attack +): Promise<{ code?: string; message: string }> { + try { + await pool.query(attack.text, attack.params); + } catch (error) { + return { code: (error as { code?: string }).code, message: (error as Error).message }; + } + return assert.fail(`${attack.name}: the statement succeeded`); +} + +const TABLES_UNDER_ATTACK = [ + "exomem_oauth_grants", + "exomem_oauth_token_families", + "exomem_oauth_access_tokens", + "exomem_oauth_refresh_tokens", + "exomem_cloud_service_credentials", + "exomem_oauth_clients", + "exomem_tenants", + "exomem_users", + "exomem_marketplace_reviewer_credentials", + "exomem_cloud_download_tickets", + "exomem_cloud_cells", +]; + +const STATES: LockState[] = ["narrow", "wide"]; + +for (const state of STATES) { + describe( + `The identity lock against the web app's role, ${state} rights`, + { skip: !databaseUrl }, + () => { + let fx: LockFixture; + let a: World; + let b: World; + let victims: Victims; + + before(async () => { + fx = await createLockFixture(state); + a = await seedWorld(fx.owner); + b = await seedWorld(fx.owner); + victims = await seedVictims(fx, a); + }); + + after(async () => { + await fx?.close(); + }); + + async function everyTable(): Promise { + return Promise.all( + TABLES_UNDER_ATTACK.map((table) => tableSnapshot(fx.owner, fx.q(table))) + ); + } + + async function runAttacks(session: Pool | PoolClient): Promise { + const before = await everyTable(); + for (const attack of attackList(fx, a, b, victims)) { + const result = await refusal(session, attack); + assert.equal(result.code, "42501", `${attack.name}: ${result.message}`); + // With every right in hand, only a guard stops the statement, and it says so. + if (state === "wide" && attack.guard) + assert.match(result.message, new RegExp(LOCKED), `${attack.name}: ${result.message}`); + } + assert.deepEqual(await everyTable(), before, "no refused statement changed a row"); + } + + it("refuses every change of an identity field, every delete and every truncate", async () => { + await runAttacks(fx.app); + }); + + it("refuses the same list in a session whose temporary tables carry the guarded names", async () => { + const client = await fx.app.connect(); + try { + // A temporary table found first in the search path stands in for the real one. The log + // and the grant table are what the recording function reads and writes; pg_class is what the + // guard reads to learn the table's owner. + // The role cannot read the log, so the stand-in names its columns itself. + await client.query( + "CREATE TEMP TABLE exomem_cloud_issuance_log (id bigint, credential_kind text, tenant_id uuid, user_id uuid)" + ); + await client.query( + `CREATE TEMP TABLE exomem_oauth_grants (LIKE ${fx.q("exomem_oauth_grants")})` + ); + await client.query("CREATE TEMP TABLE pg_class (oid oid, relowner oid)"); + await client.query( + `INSERT INTO pg_temp.pg_class + SELECT c.oid, (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = current_user) + FROM pg_catalog.pg_class AS c` + ); + await runAttacks(client); + } finally { + client.release(); + } + }); + + it("lets the schema owner make each of the changes", async () => { + const client = await fx.owner.connect(); + try { + for (const attack of attackList(fx, a, b, victims)) { + if (attack.name === "create a trigger on a guarded table") continue; + await client.query("BEGIN"); + try { + await client.query(attack.text, attack.params); + } catch (error) { + assert.fail(`${attack.name}: the owner was refused: ${(error as Error).message}`); + } finally { + await client.query("ROLLBACK"); + } + } + } finally { + client.release(); + } + }); + + it("keeps the three older guards in force for the schema owner, whose own changes the new guards allow", async () => { + // Each older guard is a BEFORE trigger that binds every role. Each statement below changes a lineage or + // purpose column on a row that is no candidate's, which the new guards let the owner do. + const refusals: Array<[string, string, unknown[], RegExp]> = [ + [ + "candidate lineage", + `UPDATE ${fx.q("exomem_oauth_grants")} SET candidate_id = gen_random_uuid() WHERE id = $1`, + [a.grantId], + /candidate OAuth lineage is immutable/, + ], + [ + "reviewer purpose", + `UPDATE ${fx.q("exomem_tenants")} SET marketplace_reviewer_purpose = true WHERE id = $1`, + [a.tenantId], + /marketplace reviewer purpose is immutable/, + ], + [ + "reviewer credential lineage", + `UPDATE ${fx.q("exomem_marketplace_reviewer_credentials")} SET assignment_generation = 1 WHERE id = $1`, + [victims.reviewerCredentialId], + /reviewer credential lineage is immutable/, + ], + ]; + for (const [guard, text, params, message] of refusals) { + await assert.rejects(fx.owner.query(text, params), message, guard); + } + }); + + it("refuses a change that a trigger of the owner's slips in, because the guard reads the stored row", async () => { + // A BEFORE trigger runs as the invoking role and can rewrite the row after the statement's + // column rights were checked. The update below names only updated_at. + await fx.owner.query( + `CREATE FUNCTION ${fx.q("test_retarget_grant")}() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN NEW.tenant_id := '${b.tenantId}'::uuid; RETURN NEW; END $$` + ); + await fx.owner.query( + `GRANT EXECUTE ON FUNCTION ${fx.q("test_retarget_grant")}() TO substrate_app` + ); + await fx.owner.query( + `CREATE TRIGGER aaa_retarget BEFORE UPDATE ON ${fx.q("exomem_oauth_grants")} + FOR EACH ROW EXECUTE FUNCTION ${fx.q("test_retarget_grant")}()` + ); + try { + const before = await tableSnapshot(fx.owner, fx.q("exomem_oauth_grants")); + await assert.rejects( + fx.app.query( + `UPDATE ${fx.q("exomem_oauth_grants")} SET updated_at = now() WHERE id = $1`, + [a.grantId] + ), + (error: Error) => error.message.includes(LOCKED) + ); + assert.equal(await tableSnapshot(fx.owner, fx.q("exomem_oauth_grants")), before); + } finally { + await fx.owner.query(`DROP TRIGGER aaa_retarget ON ${fx.q("exomem_oauth_grants")}`); + await fx.owner.query(`DROP FUNCTION ${fx.q("test_retarget_grant")}()`); + } + }); + + // In the narrow state the role holds no delete right on reviewer credentials, so no action runs. + it( + "keeps the grant's guard in force when the foreign-key action runs, not only the table's own delete guard", + { skip: state === "narrow" }, + async () => { + // A foreign-key action runs as the table owner, but the grant's guard is queued and fires as + // the role that ran the statement. The reviewer credential's own delete guard is off, so the + // grant's guard alone must refuse. + const credential = victims.reviewerCredentialId; + await fx.owner.query( + `UPDATE ${fx.q("exomem_oauth_grants")} SET reviewer_credential_id = $2 WHERE id = $1`, + [victims.grantId, credential] + ); + await fx.owner.query( + `ALTER TABLE ${fx.q("exomem_marketplace_reviewer_credentials")} + DISABLE TRIGGER exomem_marketplace_reviewer_credentials_delete_lock` + ); + try { + await assert.rejects( + fx.app.query( + `DELETE FROM ${fx.q("exomem_marketplace_reviewer_credentials")} WHERE id = $1`, + [credential] + ), + (error: Error) => + error.message.includes(LOCKED) && error.message.includes("exomem_oauth_grants") + ); + const kept = await fx.owner.query( + `SELECT (SELECT count(*) FROM ${fx.q("exomem_marketplace_reviewer_credentials")} WHERE id = $1)::int AS credentials, + (SELECT reviewer_credential_id FROM ${fx.q("exomem_oauth_grants")} WHERE id = $2) AS reference`, + [credential, victims.grantId] + ); + assert.deepEqual(kept.rows[0], { credentials: 1, reference: credential }); + } finally { + await fx.owner.query( + `ALTER TABLE ${fx.q("exomem_marketplace_reviewer_credentials")} + ENABLE TRIGGER exomem_marketplace_reviewer_credentials_delete_lock` + ); + await fx.owner.query( + `UPDATE ${fx.q("exomem_oauth_grants")} SET reviewer_credential_id = NULL WHERE id = $1`, + [victims.grantId] + ); + } + } + ); + + // In the narrow state the role holds no update right on a cell's tenant, so the grants script refuses first. + it( + "moves a cell to another tenant only when its guard is off, and the gateway then finds it under that tenant", + { skip: state === "narrow" }, + async () => { + const cells = fx.q("exomem_cloud_cells"); + const move = `UPDATE ${cells} SET tenant_id = $2 WHERE cell_id = $1`; + await assert.rejects( + fx.app.query(move, [victims.cellId, victims.tenantId]), + (error: Error) => error.message.includes(LOCKED) + ); + const guard = "exomem_cloud_cells_identity_lock"; + await fx.owner.query(`ALTER TABLE ${cells} DISABLE TRIGGER ${guard}`); + try { + await fx.app.query(move, [victims.cellId, victims.tenantId]); + const found = await fx.gateway.query<{ cell_id: string }>( + `SELECT cell_id FROM ${cells} WHERE tenant_id = $1 AND desired_state <> 'deleted'`, + [victims.tenantId] + ); + assert.deepEqual( + found.rows, + [{ cell_id: victims.cellId }], + "the control move reached the gateway's lookup" + ); + } finally { + await fx.owner.query(`ALTER TABLE ${cells} ENABLE TRIGGER ${guard}`); + await fx.owner.query(`UPDATE ${cells} SET tenant_id = $2 WHERE cell_id = $1`, [ + victims.cellId, + a.tenantId, + ]); + } + } + ); + + it("still lets the legitimate foreign-key actions run: a deleted transaction that a grant names, and a family with tokens", async () => { + const world = await seedWorld(fx.owner); + const transaction = await fx.owner.query<{ id: string }>( + `INSERT INTO exomem_oauth_authorization_transactions ( + transaction_digest, client_id, redirect_uri, resource, requested_scopes, state_digest, + pkce_challenge, expires_at, state_envelope, form_nonce_digest, continuation_binding + ) VALUES ($1, $2, 'https://client.example.test/callback', 'https://gateway.example.test/mcp', + ARRAY['mcp:read'], $3, 'challenge', now() + interval '10 minutes', '{}'::jsonb, $4, $5) + RETURNING id`, + [randomBytes(32), world.clientId, randomBytes(32), randomBytes(32), randomBytes(32)] + ); + await fx.owner.query( + `UPDATE exomem_oauth_grants SET authorization_transaction_id = $2 WHERE id = $1`, + [world.grantId, transaction.rows[0]!.id] + ); + await fx.app.query(`DELETE FROM exomem_oauth_authorization_transactions WHERE id = $1`, [ + transaction.rows[0]!.id, + ]); + const grant = await fx.owner.query( + "SELECT authorization_transaction_id FROM exomem_oauth_grants WHERE id = $1", + [world.grantId] + ); + assert.equal(grant.rows[0]!.authorization_transaction_id, null); + + await fx.app.query(`DELETE FROM exomem_oauth_token_families WHERE id = $1`, [ + world.familyId, + ]); + const tokens = await fx.owner.query( + `SELECT (SELECT count(*) FROM exomem_oauth_access_tokens WHERE family_id = $1)::int AS access, + (SELECT count(*) FROM exomem_oauth_refresh_tokens WHERE family_id = $1)::int AS refresh`, + [world.familyId] + ); + assert.deepEqual(tokens.rows[0], { access: 0, refresh: 0 }); + }); + + it("lets an update keep a revocation time that is already set, and change what the flows change", async () => { + await fx.app.query(`UPDATE exomem_oauth_grants SET revoked_at = revoked_at WHERE id = $1`, [ + a.spent.grantId, + ]); + await fx.app.query( + `UPDATE exomem_oauth_grants SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL`, + [b.grantId] + ); + const revoked = await fx.owner.query( + "SELECT revoked_at IS NOT NULL AS revoked FROM exomem_oauth_grants WHERE id = $1", + [b.grantId] + ); + assert.equal(revoked.rows[0]!.revoked, true); + }); + + it("runs the Home mint's grant upsert without firing a trigger of this change", async () => { + const grant = await fx.owner.query<{ resource: string }>( + "SELECT resource FROM exomem_oauth_grants WHERE id = $1", + [a.grantId] + ); + const client = await fx.app.connect(); + try { + await client.query("BEGIN"); + const plan = await client.query<{ "QUERY PLAN": string }>( + `EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF) + INSERT INTO exomem_oauth_grants (user_id, tenant_id, client_id, resource, scopes, refresh_allowed) + VALUES ($1, $2, $3, $4, ARRAY['mcp:read'], false) + ON CONFLICT (user_id, tenant_id, client_id, resource) WHERE revoked_at IS NULL + DO UPDATE SET updated_at = now()`, + [a.userId, a.tenantId, a.clientId, grant.rows[0]!.resource] + ); + const text = plan.rows.map((row) => row["QUERY PLAN"]).join("\n"); + assert.match(text, /Conflict Resolution: UPDATE/, "the upsert took its update branch"); + assert.doesNotMatch( + text, + /Trigger \S*(identity_lock|delete_lock|truncate_lock|issuance_record|update_lock)/, + "no trigger of this change ran for the upsert" + ); + } finally { + await client.query("ROLLBACK"); + client.release(); + } + }); + } + ); +} + +describe("The migration that pins search paths", { skip: !databaseUrl }, () => { + let fx: LockFixture; + const NO_GRANTS = "/nonexistent/exomem-cloud-grants.sql"; + + before(async () => { + fx = await createLockFixture("narrow", { migrate: false }); + }); + + after(async () => { + await fx?.close(); + }); + + it("fails and applies nothing when the path holds a schema that another role owns, and names it with its owner", async () => { + const rogue = `rogue_${randomUUID().replaceAll("-", "")}`; + await fx.admin.query(`CREATE SCHEMA "${rogue}" AUTHORIZATION substrate_app`); + // PostgreSQL leaves a schema off a role's effective path unless the role holds usage on it, + // so the owner of the schema grants it, as an attacker would to make the schema resolve. + await fx.admin.query(`GRANT USAGE ON SCHEMA "${rogue}" TO substrate_owner`); + try { + const url = new URL(fx.roleUrl("substrate_owner")); + url.searchParams.set("options", `-c search_path=${fx.schema},${rogue},public`); + await assert.rejects( + applyMigrations({ databaseUrl: url.toString(), grantsFile: NO_GRANTS }), + (error: Error) => + error.message.includes(rogue) && error.message.includes("owned by substrate_app") + ); + const tables = await fx.owner.query<{ releases: string | null }>( + "SELECT to_regclass('schema_releases') AS releases" + ); + assert.equal(tables.rows[0]!.releases, null, "the migration rolled back"); + + // Control: the same database migrates once the schema is off the path. + await applyMigrations({ databaseUrl: fx.roleUrl("substrate_owner"), grantsFile: NO_GRANTS }); + const applied = await fx.owner.query<{ releases: string | null }>( + "SELECT to_regclass('schema_releases') AS releases" + ); + assert.notEqual(applied.rows[0]!.releases, null); + } finally { + await fx.admin.query(`DROP SCHEMA IF EXISTS "${rogue}" CASCADE`); + } + }); +}); diff --git a/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts new file mode 100644 index 00000000..50113843 --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/cloud-issuance-log-postgres.integration.test.ts @@ -0,0 +1,1059 @@ +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import { cp, mkdtemp, readdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, before, describe, it } from "node:test"; +import type { Pool } from "pg"; +import { applyMigrations } from "../../../../scripts/migrate"; +import { __setExomemSqlForTests, type ExomemSql } from "../db"; +import { pruneIssuanceState } from "../issuance-maintenance"; +import { + createLockFixture, + randomCellId, + seedWorld, + tableSnapshot, + waitForWaiter, + type LockFixture, + type LockState, + type World, +} from "./identity-lock-fixture"; + +// The issuance log (design D3) as the real roles. Each state is the same as in the lock suite: +// narrow is what the grants script gives, wide adds every right on every table. + +const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +const LOCKED = "EXOMEM_ROW_LOCKED"; +const STATES: LockState[] = ["narrow", "wide"]; + +function tagged(pool: Pool): ExomemSql { + return async (strings, ...values) => { + let text = strings[0]!; + for (let index = 0; index < values.length; index += 1) { + text += `$${index + 1}${strings[index + 1]}`; + } + const result = await pool.query(text, values); + return { rows: result.rows as Array>, rowCount: result.rowCount ?? 0 }; + }; +} + +for (const state of STATES) { + describe( + `The issuance log against the service roles, ${state} rights`, + { skip: !databaseUrl }, + () => { + let fx: LockFixture; + let world: World; + + before(async () => { + fx = await createLockFixture(state); + world = await seedWorld(fx.owner); + }); + + after(async () => { + await fx?.close(); + }); + + const log = () => fx.q("exomem_cloud_issuance_log"); + const accessInsert = (digest: Buffer) => ({ + text: `INSERT INTO ${fx.q("exomem_oauth_access_tokens")} + (access_digest, grant_id, family_id, client_id, resource, scopes, expires_at) + VALUES ($1, $2, $3, $4, 'https://gateway.example.test/mcp', ARRAY['mcp:read'], + now() + interval '1 hour') RETURNING id`, + params: [digest, world.grantId, world.familyId, world.clientId], + }); + const recordsFor = async (credentialId: string) => + ( + await fx.owner.query( + `SELECT credential_kind, tenant_id, user_id, grant_id, family_id, client_id, database_role, backfilled + FROM ${log()} WHERE credential_id = $1`, + [credentialId] + ) + ).rows; + + it("writes one record for a credential that the web app's role inserts, naming the role that connected", async () => { + const digest = randomBytes(32); + const insert = accessInsert(digest); + const { rows } = await fx.app.query(insert.text, insert.params); + assert.deepEqual(await recordsFor(rows[0].id), [ + { + credential_kind: "access_token", + tenant_id: world.tenantId, + user_id: world.userId, + grant_id: world.grantId, + family_id: world.familyId, + client_id: world.clientId, + database_role: "substrate_app", + backfilled: false, + }, + ]); + }); + + it("writes no record for a transaction that rolls back, and two for a row that is deleted and inserted again", async () => { + const countRecords = async () => + Number((await fx.owner.query(`SELECT count(*) FROM ${log()}`)).rows[0].count); + const recordsBefore = await countRecords(); + const client = await fx.app.connect(); + try { + await client.query("BEGIN"); + const insert = accessInsert(randomBytes(32)); + await client.query(insert.text, insert.params); + await client.query("ROLLBACK"); + } finally { + client.release(); + } + assert.equal(await countRecords(), recordsBefore); + + const digest = randomBytes(32); + const first = accessInsert(digest); + const one = await fx.app.query(first.text, first.params); + await fx.app.query(`DELETE FROM ${fx.q("exomem_oauth_access_tokens")} WHERE id = $1`, [ + one.rows[0].id, + ]); + const two = await fx.app.query(first.text, first.params); + assert.notEqual(one.rows[0].id, two.rows[0].id); + assert.equal( + await countRecords(), + recordsBefore + 2, + "each insert is a record; the delete removes none" + ); + }); + + it("still records in the real log when temporary tables carry the names of the log and the grant table", async () => { + const client = await fx.app.connect(); + try { + // The role cannot read the log, so the stand-in names its columns itself. + await client.query( + `CREATE TEMP TABLE exomem_cloud_issuance_log ( + credential_kind text, credential_id uuid, grant_id uuid, family_id uuid, client_id uuid, + tenant_id uuid, user_id uuid, expires_at timestamptz, database_role text, + id bigint, recorded_at timestamptz, backfilled boolean)` + ); + await client.query( + `CREATE TEMP TABLE exomem_oauth_grants (LIKE ${fx.q("exomem_oauth_grants")})` + ); + await client.query(`CREATE TEMP TABLE exomem_tenants (LIKE ${fx.q("exomem_tenants")})`); + const insert = accessInsert(randomBytes(32)); + const { rows } = await client.query(insert.text, insert.params); + const real = await recordsFor(rows[0].id); + assert.equal(real.length, 1, "the record is in the real log"); + assert.equal(real[0].user_id, world.userId, "its account comes from the real grant"); + const shadow = await client.query( + "SELECT count(*)::int AS count FROM pg_temp.exomem_cloud_issuance_log" + ); + assert.equal(shadow.rows[0].count, 0, "the temporary table holds nothing"); + } finally { + client.release(); + } + }); + + it("refuses an insert, update, delete or truncate on the log from the web app, the gateway and the controller", async () => { + const before = await tableSnapshot(fx.owner, log()); + for (const [role, pool] of [ + ["substrate_app", fx.app], + ["exomem_gateway", fx.gateway], + ["exomem_cellctl", fx.cellctl], + ] as const) { + const statements = [ + `INSERT INTO ${log()} (credential_kind, credential_id, tenant_id, user_id, database_role) + VALUES ('access_token', gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'forged')`, + `UPDATE ${log()} SET tenant_id = gen_random_uuid()`, + `DELETE FROM ${log()}`, + `TRUNCATE ${log()}`, + ]; + for (const statement of statements) { + await assert.rejects(pool.query(statement), (error: Error & { code?: string }) => { + assert.equal(error.code, "42501", `${role}: ${statement}: ${error.message}`); + if (state === "wide" && role === "substrate_app") + assert.match(error.message, new RegExp(LOCKED), `${role}: ${error.message}`); + return true; + }); + } + } + assert.equal(await tableSnapshot(fx.owner, log()), before); + }); + + it("refuses to drop or disable a recording trigger, to add a trigger on the log, to replace the function and to switch off triggers", async () => { + const before = await tableSnapshot(fx.owner, log()); + for (const pool of [fx.app, fx.gateway, fx.cellctl]) { + for (const statement of [ + `DROP TRIGGER exomem_oauth_access_tokens_issuance_record ON ${fx.q("exomem_oauth_access_tokens")}`, + `ALTER TABLE ${fx.q("exomem_oauth_access_tokens")} DISABLE TRIGGER exomem_oauth_access_tokens_issuance_record`, + `ALTER TABLE ${fx.q("exomem_oauth_access_tokens")} DISABLE TRIGGER ALL`, + `CREATE TRIGGER probe AFTER INSERT ON ${log()} FOR EACH ROW EXECUTE FUNCTION ${fx.q("exomem_refuse_unless_schema_owner")}()`, + `CREATE OR REPLACE FUNCTION ${fx.q("exomem_record_issuance")}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NULL; END $$`, + "SET session_replication_role = replica", + ]) { + await assert.rejects(pool.query(statement), (error: Error & { code?: string }) => { + assert.equal(error.code, "42501", `${statement}: ${error.message}`); + return true; + }); + } + } + assert.equal(await tableSnapshot(fx.owner, log()), before); + }); + + it("refuses every service role, and the audit role, a trigger on its own table that runs the recording function", async () => { + const before = await tableSnapshot(fx.owner, log()); + for (const pool of [fx.app, fx.gateway, fx.cellctl, fx.audit]) { + const client = await pool.connect(); + try { + await client.query( + "CREATE TEMP TABLE forged (id uuid, grant_id uuid, family_id uuid, client_id uuid, expires_at timestamptz)" + ); + await assert.rejects( + client.query( + `CREATE TRIGGER forge AFTER INSERT ON forged FOR EACH ROW + EXECUTE FUNCTION ${fx.q("exomem_record_issuance")}('access_token')` + ), + (error: Error & { code?: string }) => error.code === "42501" + ); + } finally { + client.release(); + } + } + assert.equal(await tableSnapshot(fx.owner, log()), before, "the log gained no record"); + }); + + it("fails a credential insert, and leaves no row, when the log cannot take its record", async () => { + await fx.owner.query(`ALTER TABLE ${log()} RENAME TO exomem_cloud_issuance_log_moved`); + try { + const insert = accessInsert(randomBytes(32)); + const digest = insert.params[0] as Buffer; + await assert.rejects(fx.app.query(insert.text, insert.params)); + const kept = await fx.owner.query( + `SELECT count(*)::int AS count FROM ${fx.q("exomem_oauth_access_tokens")} WHERE access_digest = $1`, + [digest] + ); + assert.equal(kept.rows[0].count, 0); + } finally { + await fx.owner.query( + `ALTER TABLE ${fx.q("exomem_cloud_issuance_log_moved")} RENAME TO exomem_cloud_issuance_log` + ); + } + }); + + it("lets only the web app's role run the prune, and the prune deletes only records that expired 90 days ago", async () => { + for (const pool of [fx.gateway, fx.cellctl, fx.audit]) { + await assert.rejects( + pool.query(`SELECT ${fx.q("exomem_prune_issuance_log")}()`), + (error: Error & { code?: string }) => error.code === "42501" + ); + } + const stale = async (expiresAt: string | null) => + ( + await fx.owner.query<{ id: string }>( + `INSERT INTO ${log()} (credential_kind, credential_id, tenant_id, user_id, expires_at, database_role) + VALUES ('access_token', gen_random_uuid(), $1, $2, ${expiresAt ?? "NULL"}, 'substrate_owner') RETURNING id`, + [world.tenantId, world.userId] + ) + ).rows[0]!.id; + const old = await stale("now() - interval '91 days'"); + const recent = await stale("now() - interval '89 days'"); + const none = await stale(null); + const deleted = await fx.app.query( + `SELECT ${fx.q("exomem_prune_issuance_log")}() AS deleted` + ); + assert.equal(deleted.rows[0].deleted >= 1, true); + const left = await fx.owner.query<{ id: string }>( + `SELECT id FROM ${log()} WHERE id = ANY($1::bigint[]) ORDER BY id`, + [[old, recent, none]] + ); + assert.deepEqual( + left.rows.map((row) => row.id), + [recent, none].sort((x, y) => Number(x) - Number(y)), + "the record that expired 91 days ago is gone; a recent one and one without an expiry stay" + ); + }); + + // A service credential has no expiry, so its record takes the time the credential ends. + const serviceCredentials = () => fx.q("exomem_cloud_service_credentials"); + const addServiceCredential = async () => + ( + await fx.owner.query<{ id: string }>( + `INSERT INTO ${serviceCredentials()} + (tenant_id, principal, secret_digest, created_by_principal_digest) + VALUES ($1, $2, $3, $4) RETURNING id`, + [ + world.tenantId, + `service:t${randomBytes(6).toString("hex")}`, + randomBytes(32), + randomBytes(32), + ] + ) + ).rows[0]!.id; + const recordEnd = async (credentialId: string) => + ( + await fx.owner.query<{ open: boolean; at_now: boolean }>( + `SELECT expires_at IS NULL AS open, + coalesce(expires_at > now() - interval '1 minute' AND expires_at <= now(), false) AS at_now + FROM ${log()} WHERE credential_kind = 'service_credential' AND credential_id = $1`, + [credentialId] + ) + ).rows[0]; + + it("ends a service credential's record at the database clock when the web app's role revokes it, whatever revoked_at says", async () => { + const live = await addServiceCredential(); + const revoked = await addServiceCredential(); + assert.deepEqual(await recordEnd(live), { open: true, at_now: false }); + await fx.app.query( + `UPDATE ${serviceCredentials()} + SET revoked_at = now() - interval '200 days', revoked_by_principal_digest = $2 WHERE id = $1`, + [revoked, randomBytes(32)] + ); + assert.deepEqual( + await recordEnd(revoked), + { open: false, at_now: true }, + "a backdated revoked_at does not bring the prune forward" + ); + assert.deepEqual( + await recordEnd(live), + { open: true, at_now: false }, + "a live one stays open" + ); + }); + + it("ends a service credential's record when the schema owner deletes its row", async () => { + const credential = await addServiceCredential(); + await fx.owner.query(`DELETE FROM ${serviceCredentials()} WHERE id = $1`, [credential]); + assert.deepEqual(await recordEnd(credential), { open: false, at_now: true }); + }); + + it("prunes a revoked service credential's record 90 days after the revocation, and keeps a live one's", async () => { + const live = await addServiceCredential(); + const revoked = await addServiceCredential(); + await fx.app.query( + `UPDATE ${serviceCredentials()} SET revoked_at = now(), revoked_by_principal_digest = $2 WHERE id = $1`, + [revoked, randomBytes(32)] + ); + const pruneAsApp = () => + fx.app.query(`SELECT ${fx.q("exomem_prune_issuance_log")}() AS deleted`); + const kept = async () => + ( + await fx.owner.query<{ credential_id: string }>( + `SELECT credential_id FROM ${log()} WHERE credential_id = ANY($1::uuid[])`, + [[live, revoked]] + ) + ).rows + .map((row) => row.credential_id) + .sort(); + await pruneAsApp(); + assert.deepEqual(await kept(), [live, revoked].sort(), "90 days have not passed"); + // The test cannot wait 90 days, so the owner moves the recorded end back. + await fx.owner.query( + `UPDATE ${log()} SET expires_at = now() - interval '91 days' + WHERE credential_kind = 'service_credential' AND credential_id = $1`, + [revoked] + ); + await pruneAsApp(); + assert.deepEqual( + await kept(), + [live], + "the revoked one's record is gone; the live one's stays" + ); + }); + + // A cell that ends revokes the tenant's service credentials in the same statement, so a + // release that does not know the rule, or a rollback, still ends them. Only the web app's role + // sets a cell's desired state, so these run as it. + const cells = () => fx.q("exomem_cloud_cells"); + const credentialState = async (credentialId: string) => + ( + await fx.owner.query<{ + revoked: boolean; + at_clock: boolean; + no_operator: boolean; + at: string | null; + }>( + `SELECT revoked_at IS NOT NULL AS revoked, coalesce(revoked_at <= now(), false) AS at_clock, + revoked_by_principal_digest IS NULL AS no_operator, revoked_at::text AS at + FROM ${serviceCredentials()} WHERE id = $1`, + [credentialId] + ) + ).rows[0]!; + + it("revokes a tenant's live service credentials at the database clock, and ends their records, when the web app's role sets its cell to deleted", async () => { + const gone = await seedWorld(fx.owner); + const kept = await seedWorld(fx.owner); + const goneCell = gone.cellId; + const spentBefore = await credentialState(gone.spent.serviceCredentialId); + assert.deepEqual(await recordEnd(gone.serviceCredentialId), { open: true, at_now: false }); + + await fx.app.query(`UPDATE ${cells()} SET desired_state = 'stopped' WHERE cell_id = $1`, [ + goneCell, + ]); + assert.equal( + (await credentialState(gone.serviceCredentialId)).revoked, + false, + "a cell that only stops keeps its tenant's credentials" + ); + + await fx.app.query(`UPDATE ${cells()} SET desired_state = 'deleted' WHERE cell_id = $1`, [ + goneCell, + ]); + const revoked = await credentialState(gone.serviceCredentialId); + assert.deepEqual( + { + revoked: revoked.revoked, + at_clock: revoked.at_clock, + no_operator: revoked.no_operator, + }, + { revoked: true, at_clock: true, no_operator: true } + ); + assert.deepEqual(await recordEnd(gone.serviceCredentialId), { open: false, at_now: true }); + assert.deepEqual( + await credentialState(gone.spent.serviceCredentialId), + spentBefore, + "a credential that was already revoked keeps its time and its revoking principal" + ); + assert.equal((await credentialState(kept.serviceCredentialId)).revoked, false); + assert.deepEqual(await recordEnd(kept.serviceCredentialId), { open: true, at_now: false }); + + await fx.app.query(`UPDATE ${cells()} SET desired_state = 'deleted' WHERE cell_id = $1`, [ + goneCell, + ]); + assert.deepEqual( + await credentialState(gone.serviceCredentialId), + revoked, + "a second update changes nothing" + ); + }); + + it("leaves a re-admitted tenant's credentials alone when its old deleted cell row goes, and revokes them when the schema owner deletes its live cell row", async () => { + const world = await seedWorld(fx.owner); + const oldCell = randomCellId(); + await fx.owner.query( + `INSERT INTO ${cells()} (cell_id, tenant_id, desired_state) VALUES ($1, $2, 'deleted')`, + [oldCell, world.tenantId] + ); + const liveCell = world.cellId; + await fx.owner.query(`DELETE FROM ${cells()} WHERE cell_id = $1`, [oldCell]); + assert.equal((await credentialState(world.serviceCredentialId)).revoked, false); + await fx.owner.query(`DELETE FROM ${cells()} WHERE cell_id = $1`, [liveCell]); + assert.equal((await credentialState(world.serviceCredentialId)).revoked, true); + assert.deepEqual(await recordEnd(world.serviceCredentialId), { open: false, at_now: true }); + }); + + it("refuses cell deletion in a transaction with a fixed snapshot", async () => { + const world = await seedWorld(fx.owner); + const transaction = await fx.app.connect(); + try { + await transaction.query("BEGIN ISOLATION LEVEL REPEATABLE READ"); + await assert.rejects( + transaction.query(`UPDATE ${cells()} SET desired_state = 'deleted' WHERE cell_id = $1`, [ + world.cellId, + ]), + { code: "0A000", message: /must use READ COMMITTED/ } + ); + } finally { + await transaction.query("ROLLBACK"); + transaction.release(); + } + assert.equal((await credentialState(world.serviceCredentialId)).revoked, false); + const state = await fx.owner.query(`SELECT desired_state FROM ${cells()} WHERE cell_id = $1`, [ + world.cellId, + ]); + assert.equal(state.rows[0]?.desired_state, "running"); + }); + + // A service credential is inserted only for a tenant with a live cell, and the insert locks + // that cell's row. These run as the web app's role, which mints credentials. Each connection + // has a statement timeout, so a lock that waits for the wrong thing fails the test. + const NO_LIVE_CELL = { + code: "23503", + constraint: "exomem_cloud_service_credentials_live_cell", + }; + const mintSql = () => `INSERT INTO ${serviceCredentials()} + (tenant_id, principal, secret_digest, created_by_principal_digest) + VALUES ($1, $2, $3, $4) RETURNING id`; + const mintValues = (tenantId: string) => [ + tenantId, + `service:t${randomBytes(6).toString("hex")}`, + randomBytes(32), + randomBytes(32), + ]; + const credentialCount = async (tenantId: string) => + ( + await fx.owner.query<{ count: number }>( + `SELECT count(*)::integer AS count FROM ${serviceCredentials()} WHERE tenant_id = $1`, + [tenantId] + ) + ).rows[0]!.count; + const sessions = async () => { + const [mint, deletion] = [await fx.app.connect(), await fx.app.connect()]; + for (const session of [mint, deletion]) + await session.query("SET statement_timeout = 10000"); + return { + mint, + deletion, + // The pool destroys a connection that carries a changed setting and maybe an open transaction. + close: () => { + mint.release(true); + deletion.release(true); + }, + }; + }; + // The caller keeps the promise to await it later, and a rejection that comes first is not "unhandled". + const pending = (promise: Promise): Promise => { + promise.catch(() => undefined); + return promise; + }; + + it("refuses a service credential for a tenant whose only cell is deleted", async () => { + const gone = await seedWorld(fx.owner); + await fx.app.query(`UPDATE ${cells()} SET desired_state = 'deleted' WHERE cell_id = $1`, [ + gone.cellId, + ]); + const before = await credentialCount(gone.tenantId); + await assert.rejects(fx.app.query(mintSql(), mintValues(gone.tenantId)), NO_LIVE_CELL); + assert.equal(await credentialCount(gone.tenantId), before); + }); + + it("revokes a credential that is inserted while a deletion of its tenant's cell waits for the insert", async () => { + const target = await seedWorld(fx.owner); + const { mint, deletion, close } = await sessions(); + try { + await mint.query("BEGIN"); + const minted = await mint.query<{ id: string }>(mintSql(), mintValues(target.tenantId)); + const deleting = pending( + deletion.query(`UPDATE ${cells()} SET desired_state = 'deleted' WHERE cell_id = $1`, [ + target.cellId, + ]) + ); + await waitForWaiter(fx.owner, mint); + await mint.query("COMMIT"); + await deleting; + const id = minted.rows[0]!.id; + const state = await credentialState(id); + assert.deepEqual( + { revoked: state.revoked, at_clock: state.at_clock, no_operator: state.no_operator }, + { revoked: true, at_clock: true, no_operator: true } + ); + assert.deepEqual(await recordEnd(id), { open: false, at_now: true }); + } finally { + close(); + } + }); + + it("refuses a credential that waits for a deletion of its tenant's cell, once the deletion commits", async () => { + const target = await seedWorld(fx.owner); + const { mint, deletion, close } = await sessions(); + try { + await deletion.query("BEGIN"); + await deletion.query( + `UPDATE ${cells()} SET desired_state = 'deleted' WHERE cell_id = $1`, + [target.cellId] + ); + const before = await credentialCount(target.tenantId); + const minting = pending(mint.query(mintSql(), mintValues(target.tenantId))); + await waitForWaiter(fx.owner, deletion); + await deletion.query("COMMIT"); + await assert.rejects(minting, NO_LIVE_CELL); + assert.equal(await credentialCount(target.tenantId), before); + } finally { + close(); + } + }); + + // A token family's record holds the family's expiry. A revocation or a delete before then + // moves it to the database clock's time, so the prune keeps it 90 days from the end. + const families = () => fx.q("exomem_oauth_token_families"); + const addFamily = async (grantId = world.grantId) => + ( + await fx.owner.query<{ id: string }>( + `INSERT INTO ${families()} (grant_id, client_id, expires_at) + VALUES ($1, $2, now() + interval '300 days') RETURNING id`, + [grantId, world.clientId] + ) + ).rows[0]!.id; + const familyEnd = async (familyId: string) => + ( + await fx.owner.query<{ at_expiry: boolean; at_now: boolean }>( + `SELECT expires_at > now() + interval '299 days' AS at_expiry, + coalesce(expires_at > now() - interval '1 minute' AND expires_at <= now(), false) AS at_now + FROM ${log()} WHERE credential_kind = 'token_family' AND credential_id = $1`, + [familyId] + ) + ).rows[0]; + + it("ends a token family's record at the database clock when the web app's role revokes it, whatever revoked_at says", async () => { + const live = await addFamily(); + const revoked = await addFamily(); + assert.deepEqual(await familyEnd(live), { at_expiry: true, at_now: false }); + await fx.app.query( + `UPDATE ${families()} SET revoked_at = now() - interval '200 days' WHERE id = $1`, + [revoked] + ); + assert.deepEqual( + await familyEnd(revoked), + { at_expiry: false, at_now: true }, + "a backdated revoked_at does not bring the prune forward" + ); + assert.deepEqual( + await familyEnd(live), + { at_expiry: true, at_now: false }, + "a live family's record keeps its expiry" + ); + }); + + it("ends a record at the revoking statement, not at the start of a transaction that stayed open", async () => { + const credential = await addServiceCredential(); + const family = await addFamily(); + const client = await fx.app.connect(); + let before: Date; + try { + await client.query("BEGIN"); + // The transaction clock stays at BEGIN while the statement clock moves on. + before = ( + await client.query<{ before: Date }>( + "SELECT pg_sleep(1.2), clock_timestamp() AS before" + ) + ).rows[0]!.before; + await client.query( + `UPDATE ${serviceCredentials()} SET revoked_at = now(), revoked_by_principal_digest = $2 WHERE id = $1`, + [credential, randomBytes(32)] + ); + await client.query(`UPDATE ${families()} SET revoked_at = now() WHERE id = $1`, [family]); + await client.query("COMMIT"); + } finally { + client.release(); + } + const { rows } = await fx.owner.query<{ credential_kind: string; expires_at: Date }>( + `SELECT credential_kind, expires_at FROM ${log()} + WHERE credential_id = ANY($1::uuid[]) AND credential_kind IN ('service_credential', 'token_family')`, + [[credential, family]] + ); + assert.equal(rows.length, 2); + for (const row of rows) { + assert.ok( + row.expires_at >= before!, + `the ${row.credential_kind} record ends at the revoking statement` + ); + } + }); + + it("ends a record at its insert when the web app's role inserts a service credential or a token family already revoked", async () => { + // The schema accepts such a row. Without an end, the credential's record would stay + // open for ever and the family's would keep its future expiry, and the prune would + // select neither. + const credential = ( + await fx.app.query<{ id: string }>( + `INSERT INTO ${serviceCredentials()} + (tenant_id, principal, secret_digest, created_by_principal_digest, revoked_at, revoked_by_principal_digest) + VALUES ($1, $2, $3, $4, now() - interval '200 days', $5) RETURNING id`, + [ + world.tenantId, + `service:t${randomBytes(6).toString("hex")}`, + randomBytes(32), + randomBytes(32), + randomBytes(32), + ] + ) + ).rows[0]!.id; + assert.deepEqual(await recordEnd(credential), { open: false, at_now: true }); + + const family = ( + await fx.app.query<{ id: string }>( + `INSERT INTO ${families()} (grant_id, client_id, expires_at, revoked_at) + VALUES ($1, $2, now() + interval '300 days', now() - interval '200 days') RETURNING id`, + [world.grantId, world.clientId] + ) + ).rows[0]!.id; + assert.deepEqual(await familyEnd(family), { at_expiry: false, at_now: true }); + }); + + it("ends a token family's record when the web app's role deletes the family, and when a deleted grant cascades to it", async () => { + const deleted = await addFamily(); + await fx.app.query(`DELETE FROM ${families()} WHERE id = $1`, [deleted]); + assert.deepEqual(await familyEnd(deleted), { at_expiry: false, at_now: true }); + + // Account deletion removes a grant, and the family goes with it. + const grant = ( + await fx.owner.query<{ id: string }>( + `INSERT INTO ${fx.q("exomem_oauth_grants")} (user_id, tenant_id, client_id, resource, scopes) + VALUES ($1, $2, $3, $4, ARRAY['mcp:read']) RETURNING id`, + [ + world.userId, + world.tenantId, + world.clientId, + `https://gateway.example.test/mcp/${randomBytes(6).toString("hex")}`, + ] + ) + ).rows[0]!.id; + const cascaded = await addFamily(grant); + await fx.owner.query(`DELETE FROM ${fx.q("exomem_oauth_grants")} WHERE id = $1`, [grant]); + assert.deepEqual(await familyEnd(cascaded), { at_expiry: false, at_now: true }); + }); + + it("prunes a revoked token family's record 90 days after the revocation, and keeps a live family's", async () => { + const live = await addFamily(); + const revoked = await addFamily(); + await fx.app.query(`UPDATE ${families()} SET revoked_at = now() WHERE id = $1`, [revoked]); + const pruneAsApp = () => + fx.app.query(`SELECT ${fx.q("exomem_prune_issuance_log")}() AS deleted`); + const kept = async () => + ( + await fx.owner.query<{ credential_id: string }>( + `SELECT credential_id FROM ${log()} WHERE credential_id = ANY($1::uuid[])`, + [[live, revoked]] + ) + ).rows + .map((row) => row.credential_id) + .sort(); + await pruneAsApp(); + assert.deepEqual(await kept(), [live, revoked].sort(), "90 days have not passed"); + // The test cannot wait 90 days, so the owner moves the recorded end back. + await fx.owner.query( + `UPDATE ${log()} SET expires_at = now() - interval '91 days' + WHERE credential_kind = 'token_family' AND credential_id = $1`, + [revoked] + ); + await pruneAsApp(); + assert.deepEqual( + await kept(), + [live], + "the revoked family's record is gone; the live one stays" + ); + }); + + it("lets the maintenance run, as the web app's role, remove an expired download ticket row", async () => { + const ticket = async (expires: string) => + ( + await fx.owner.query<{ id: string }>( + `INSERT INTO ${fx.q("exomem_cloud_download_tickets")} (family_id, path_sha256, expires_at, created_at) + VALUES ($1, $2, now() + ${expires}, now() - interval '2 hours') RETURNING id`, + [world.familyId, randomBytes(32).toString("hex")] + ) + ).rows[0]!.id; + const live = await ticket("interval '10 minutes'"); + const expired = await ticket("interval '-1 hour'"); + __setExomemSqlForTests(tagged(fx.app)); + try { + const result = await pruneIssuanceState(); + assert.equal(typeof result.records, "number"); + assert.ok((result.tickets ?? 0) >= 1); + } finally { + __setExomemSqlForTests(null); + } + const rows = await fx.owner.query<{ id: string }>( + `SELECT id FROM ${fx.q("exomem_cloud_download_tickets")} WHERE id = ANY($1::uuid[])`, + [[expired, live]] + ); + assert.deepEqual( + rows.rows.map((row) => row.id), + [live] + ); + }); + + it("removes one expired ticket on issuance and keeps both issuance records", async () => { + const tickets = fx.q("exomem_cloud_download_tickets"); + const expired = await fx.app.query<{ id: string }>( + `INSERT INTO ${tickets} (family_id, path_sha256, expires_at) + VALUES ($1, $2, now() - interval '1 minute') RETURNING id`, + [world.familyId, randomBytes(32).toString("hex")] + ); + const live = await fx.app.query<{ id: string }>( + `INSERT INTO ${tickets} (family_id, path_sha256, expires_at) + VALUES ($1, $2, now() + interval '10 minutes') RETURNING id`, + [world.familyId, randomBytes(32).toString("hex")] + ); + const ids = [expired.rows[0]!.id, live.rows[0]!.id]; + const retained = await fx.app.query<{ id: string }>( + `SELECT id FROM ${tickets} WHERE id = ANY($1::uuid[])`, + [ids] + ); + assert.deepEqual(retained.rows.map((row) => row.id), [live.rows[0]!.id]); + const recorded = await fx.owner.query<{ credential_id: string }>( + `SELECT credential_id FROM ${log()} WHERE credential_id = ANY($1::uuid[])`, + [ids] + ); + assert.deepEqual(recorded.rows.map((row) => row.credential_id).sort(), ids.sort()); + }); + + it("issues the ticket when all cleanup candidates are locked", async () => { + const tickets = fx.q("exomem_cloud_download_tickets"); + const seeded = await fx.owner.query<{ id: string }>( + `INSERT INTO ${tickets} (family_id, path_sha256, expires_at) + SELECT $1, encode(public.gen_random_bytes(32), 'hex'), now() + n * interval '1 minute' + FROM generate_series(1, 33) AS n RETURNING id`, + [world.familyId] + ); + const ids = seeded.rows.map((row) => row.id); + await fx.owner.query( + `UPDATE ${tickets} SET expires_at = expires_at - interval '1 hour' WHERE id = ANY($1::uuid[])`, + [ids] + ); + const locks = await fx.owner.connect(); + try { + await locks.query("BEGIN"); + await locks.query( + `SELECT id FROM ${tickets} WHERE id = ANY($1::uuid[]) + ORDER BY expires_at LIMIT 32 FOR UPDATE`, + [ids] + ); + const issued = await fx.app.query<{ id: string }>( + `INSERT INTO ${tickets} (family_id, path_sha256, expires_at) + VALUES ($1, $2, now() + interval '10 minutes') RETURNING id`, + [world.familyId, randomBytes(32).toString("hex")] + ); + assert.ok(issued.rows[0]?.id); + const remaining = await fx.app.query( + `SELECT id FROM ${tickets} WHERE id = ANY($1::uuid[])`, + [ids] + ); + assert.equal(remaining.rows.length, ids.length); + } finally { + await locks.query("ROLLBACK"); + locks.release(); + } + }); + } + ); +} + +describe("The migration that adds the log", { skip: !databaseUrl }, () => { + let fx: LockFixture; + let migrationRoot: string; + const NO_GRANTS = "/nonexistent/exomem-cloud-grants.sql"; + + type Seeded = { + live: World; + deleted: World; + deletedSpentRevokedAt: string; + stale: World; + staleOld: { familyId: string; accessTokenId: string; refreshTokenId: string }; + staleRecent: { familyId: string; accessTokenId: string; refreshTokenId: string }; + }; + let seeded: Seeded; + + // A family with an access token and a refresh token, all of which expired the given number of days ago. + const seedExpiredChain = async (world: World, daysAgo: number) => { + const id = async (text: string, values: unknown[]): Promise => + (await fx.owner.query<{ id: string }>(text, values)).rows[0]!.id; + const familyId = await id( + `INSERT INTO exomem_oauth_token_families (grant_id, client_id, created_at, expires_at) + VALUES ($1, $2, now() - make_interval(days => $3 + 1), now() - make_interval(days => $3)) + RETURNING id`, + [world.grantId, world.clientId, daysAgo] + ); + const accessTokenId = await id( + `INSERT INTO exomem_oauth_access_tokens + (access_digest, grant_id, family_id, client_id, resource, scopes, created_at, expires_at) + VALUES ($1, $2, $3, $4, 'https://example.test/mcp', ARRAY['mcp:read'], + now() - make_interval(days => $5 + 1), now() - make_interval(days => $5)) + RETURNING id`, + [randomBytes(32), world.grantId, familyId, world.clientId, daysAgo] + ); + const refreshTokenId = await id( + `INSERT INTO exomem_oauth_refresh_tokens (refresh_digest, family_id, created_at, expires_at) + VALUES ($1, $2, now() - make_interval(days => $3 + 1), now() - make_interval(days => $3)) + RETURNING id`, + [randomBytes(32), familyId, daysAgo] + ); + return { familyId, accessTokenId, refreshTokenId }; + }; + + before(async () => { + fx = await createLockFixture("narrow", { migrate: false }); + migrationRoot = await mkdtemp(join(tmpdir(), "issuance-log-upgrade-")); + for (const name of await readdir("migrations")) { + if (name.endsWith(".sql") && name < "0102") + await cp(join("migrations", name), join(migrationRoot, name)); + } + // Earlier releases left default privileges that give the web app's role every right on a + // table a migration creates; the new tables must not inherit them. + await fx.admin.query( + `ALTER DEFAULT PRIVILEGES FOR ROLE substrate_owner IN SCHEMA "${fx.schema}" + GRANT ALL ON TABLES TO substrate_app` + ); + await applyMigrations({ + databaseUrl: fx.roleUrl("substrate_owner"), + migrationsDir: migrationRoot, + grantsFile: NO_GRANTS, + }); + // A tenant whose cell is live, with an older cell that was deleted and then re-admitted. + const live = await seedWorld(fx.owner); + await fx.owner.query( + "INSERT INTO exomem_cloud_cells (cell_id, tenant_id, desired_state) VALUES ($1, $2, 'deleted')", + [randomCellId(), live.tenantId] + ); + // A tenant that a release before this one deleted: only a deleted cell, and a credential left live. + const deleted = await seedWorld(fx.owner); + await fx.owner.query( + "UPDATE exomem_cloud_cells SET desired_state = 'deleted' WHERE cell_id = $1", + [deleted.cellId] + ); + const deletedSpentRevokedAt = ( + await fx.owner.query<{ at: string }>( + "SELECT revoked_at::text AS at FROM exomem_cloud_service_credentials WHERE id = $1", + [deleted.spent.serviceCredentialId] + ) + ).rows[0]!.at; + // A tenant with credentials that expired 100 days ago, which the prune would delete at once, and + // credentials that expired 10 days ago, which it keeps. + const stale = await seedWorld(fx.owner); + const staleOld = await seedExpiredChain(stale, 100); + const staleRecent = await seedExpiredChain(stale, 10); + seeded = { live, deleted, deletedSpentRevokedAt, stale, staleOld, staleRecent }; + await applyMigrations({ databaseUrl: fx.roleUrl("substrate_owner"), grantsFile: NO_GRANTS }); + }); + + after(async () => { + await rm(migrationRoot, { recursive: true, force: true }); + await fx?.close(); + }); + + it("writes one backfilled record for each credential row that existed, and gives the web app's role no right on the new tables", async () => { + const world = seeded.live; + + const counts = await fx.owner.query<{ + credential_kind: string; + count: number; + backfilled: boolean; + }>( + `SELECT credential_kind, count(*)::int AS count, bool_and(backfilled) AS backfilled + FROM exomem_cloud_issuance_log WHERE tenant_id = $1 GROUP BY credential_kind ORDER BY credential_kind`, + [world.tenantId] + ); + assert.deepEqual(counts.rows, [ + { credential_kind: "access_token", count: 2, backfilled: true }, + { credential_kind: "refresh_token", count: 2, backfilled: true }, + { credential_kind: "service_credential", count: 2, backfilled: true }, + { credential_kind: "token_family", count: 2, backfilled: true }, + ]); + const ends = await fx.owner.query( + `SELECT count(*) FILTER (WHERE expires_at IS NULL)::int AS open, + count(*) FILTER (WHERE expires_at IS NOT NULL)::int AS ended + FROM exomem_cloud_issuance_log WHERE tenant_id = $1 AND credential_kind = 'service_credential'`, + [world.tenantId] + ); + assert.deepEqual( + ends.rows, + [{ open: 1, ended: 1 }], + "the revoked service credential's backfilled record has an end, the live one's has none" + ); + const familyEnds = await fx.owner.query( + `SELECT family.revoked_at IS NOT NULL AS revoked, + record.expires_at <= now() AS ended + FROM exomem_cloud_issuance_log AS record + JOIN exomem_oauth_token_families AS family ON family.id = record.credential_id + WHERE record.tenant_id = $1 AND record.credential_kind = 'token_family' + ORDER BY revoked`, + [world.tenantId] + ); + assert.deepEqual( + familyEnds.rows, + [ + { revoked: false, ended: false }, + { revoked: true, ended: true }, + ], + "the revoked family's backfilled record has an end, the live family's keeps its expiry" + ); + const role = await fx.owner.query( + "SELECT DISTINCT database_role FROM exomem_cloud_issuance_log WHERE tenant_id = $1", + [world.tenantId] + ); + assert.deepEqual( + role.rows, + [{ database_role: "substrate_owner" }], + "a backfilled record names the migrating role" + ); + + // has_table_privilege with a list answers true when the role holds any one of the rights. + const held = await fx.owner.query<{ log: boolean; tickets: boolean; sequence: boolean }>( + `SELECT has_table_privilege('substrate_app', 'exomem_cloud_issuance_log', + 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER') AS log, + has_table_privilege('substrate_app', 'exomem_cloud_download_tickets', + 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER') AS tickets, + has_sequence_privilege('substrate_app', pg_get_serial_sequence('exomem_cloud_issuance_log', 'id'), + 'USAGE, SELECT, UPDATE') AS sequence` + ); + assert.deepEqual( + held.rows[0], + { log: false, tickets: false, sequence: false }, + "no right at all until the grants script runs" + ); + }); + + it("revokes, at the migration's time and with no revoking principal, the live service credentials of a tenant that has only deleted cells, and leaves a live tenant's alone", async () => { + const state = async (credentialId: string) => + ( + await fx.owner.query<{ + revoked: boolean; + no_operator: boolean; + at_migration: boolean; + record_end_matches: boolean; + }>( + `SELECT credential.revoked_at IS NOT NULL AS revoked, + credential.revoked_by_principal_digest IS NULL AS no_operator, + credential.revoked_at = record.recorded_at AS at_migration, + record.expires_at IS NOT DISTINCT FROM credential.revoked_at AS record_end_matches + FROM exomem_cloud_service_credentials AS credential + JOIN exomem_cloud_issuance_log AS record + ON record.credential_kind = 'service_credential' AND record.credential_id = credential.id + WHERE credential.id = $1`, + [credentialId] + ) + ).rows[0]!; + const ended = await state(seeded.deleted.serviceCredentialId); + assert.equal(ended.revoked, true, "the deleted tenant's credential ends"); + assert.equal(ended.no_operator, true, "no operator revoked it"); + assert.equal( + ended.at_migration, + true, + "it ends at the migration's time, which stamps the record" + ); + assert.equal(ended.record_end_matches, true, "its record ends at the same time"); + assert.equal( + (await state(seeded.live.serviceCredentialId)).revoked, + false, + "a tenant with a live cell keeps its credential, whatever deleted cell it had before" + ); + const spent = await fx.owner.query<{ at: string; operator: boolean }>( + `SELECT revoked_at::text AS at, revoked_by_principal_digest IS NOT NULL AS operator + FROM exomem_cloud_service_credentials WHERE id = $1`, + [seeded.deleted.spent.serviceCredentialId] + ); + assert.deepEqual( + spent.rows, + [{ at: seeded.deletedSpentRevokedAt, operator: true }], + "a credential that was revoked before keeps its time and its operator" + ); + }); + + it("writes no record for a credential whose record the prune would delete at once, and one for each that is live or ended within 90 days", async () => { + const recorded = async (kind: string, credentialId: string) => + ( + await fx.owner.query( + "SELECT 1 FROM exomem_cloud_issuance_log WHERE credential_kind = $1 AND credential_id = $2", + [kind, credentialId] + ) + ).rowCount; + for (const [label, rows, count] of [ + ["expired 100 days ago", seeded.staleOld, 0], + ["expired 10 days ago", seeded.staleRecent, 1], + ] as const) { + assert.equal(await recorded("token_family", rows.familyId), count, `family ${label}`); + assert.equal( + await recorded("access_token", rows.accessTokenId), + count, + `access token ${label}` + ); + assert.equal( + await recorded("refresh_token", rows.refreshTokenId), + count, + `refresh token ${label}` + ); + } + assert.equal( + await recorded("token_family", seeded.stale.familyId), + 1, + "a live family has a record" + ); + assert.equal( + await recorded("service_credential", seeded.stale.spent.serviceCredentialId), + 1, + "a service credential revoked before the migration ends at the migration's time, so its record is kept" + ); + }); +}); diff --git a/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts index 6dc94e36..063b90f0 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-media-download-postgres.integration.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { generateKeyPairSync, randomBytes, randomUUID } from "node:crypto"; +import { createHash, generateKeyPairSync, randomBytes, randomUUID } from "node:crypto"; import { after, before, describe, it } from "node:test"; import { Pool, type PoolClient } from "pg"; import { applyMigrations } from "../../../../scripts/migrate"; @@ -11,11 +11,14 @@ import type { ExomemCloudConfig } from "../cloud-config"; import { handleCloudMediaDownloadRequest } from "../cloud-media-download"; import { __setExomemSqlForTests, __setExomemTransactionForTests, type ExomemSql } from "../db"; import { digestSecret, generateExternalToken } from "../security"; +import { gatewayPool, productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // add-cloud-media-access: the signed-in download link against real PostgreSQL. The browser // session, the ticket and the gateway's login lookup all run for real; only the cell's -// bytes are substituted, at the gateway's `fetchCell` boundary. +// bytes are substituted, at the gateway's `fetchCell` boundary. Production runs the link as the +// web app's role and the gateway as its own narrower role, on the rights of the grants script, so +// each runs as that role here. The suite's own pool is a superuser that only seeds and asserts. process.env.EXOMEM_CONTROL_PLANE_KEY ??= randomBytes(32).toString("base64url"); @@ -27,6 +30,12 @@ const { privateKey } = generateKeyPairSync("ed25519"); const PATH = "Recordings/standup.mp4"; const BYTES = Buffer.from("0123456789"); let pool: Pool; +/** The web app's role: the link handler stores each ticket's row as this role. */ +let appPool: Pool; +/** The gateway's role: the login lookup that requires the row runs as this role. */ +let gatewayRolePool: Pool; +/** The statement handle that the gateway's lookup uses; a case swaps in a counting wrapper. */ +let gatewaySql: ExomemSql; let schema: string; type Owner = { userId: string; tenantId: string; cellId: string; cookie: string }; @@ -123,13 +132,19 @@ function gateway(cells: Owner[]) { }, }); }) as unknown as typeof fetch; - const follow = (location: string, headers: Record = {}) => - handleCloudDownloadRequest(new Request(location, { headers }), { - config, - fetchCell, - upstream: testUpstream(), - takeRateLimit: async () => true, - }); + const follow = async (location: string, headers: Record = {}) => { + __setExomemSqlForTests(gatewaySql); + try { + return await handleCloudDownloadRequest(new Request(location, { headers }), { + config, + fetchCell, + upstream: testUpstream(), + takeRateLimit: async () => true, + }); + } finally { + __setExomemSqlForTests(taggedSql(appPool)); + } + }; return { reached, follow }; } @@ -144,9 +159,12 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, scoped.searchParams.set("options", `-c search_path=${schema},public`); await applyMigrations({ databaseUrl: scoped.toString() }); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + appPool = await productionPool(scoped.toString(), schema); + gatewayRolePool = await gatewayPool(scoped.toString(), schema); + gatewaySql = taggedSql(gatewayRolePool); + __setExomemSqlForTests(taggedSql(appPool)); __setExomemTransactionForTests(async (work) => { - const client = await pool.connect(); + const client = await appPool.connect(); try { await client.query("BEGIN"); const result = await work(taggedSql(client)); @@ -165,6 +183,8 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, __setExomemSqlForTests(null); __setExomemTransactionForTests(null); await pool?.end(); + await appPool?.end(); + await gatewayRolePool?.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); await admin.query(`DROP SCHEMA "${schema}" CASCADE`); @@ -315,6 +335,103 @@ describe("Signed-in media download PostgreSQL boundary", { skip: !databaseUrl }, assert.equal(reached.length, served, "neither refused ticket reached a cell"); }); + it("stores one row for each ticket, by its path digest and expiry, before the redirect", async () => { + const a = await owner(); + const expiries = new Set(); + for (let attempt = 0; attempt < 3; attempt += 1) { + const claims = claimsOf((await link(a)).headers.get("location")!); + expiries.add(claims.exp); + const stored = await pool.query( + "SELECT path_sha256, extract(epoch FROM expires_at)::bigint AS exp FROM exomem_cloud_download_tickets WHERE family_id = $1 AND expires_at = to_timestamp($2)", + [claims.family_id, claims.exp] + ); + assert.equal(stored.rowCount, 1, "the row that the gateway looks up exists"); + assert.equal(stored.rows[0].path_sha256, createHash("sha256").update(PATH).digest("hex")); + } + const all = await pool.query( + "SELECT count(*)::int AS count FROM exomem_cloud_download_tickets t JOIN exomem_oauth_token_families f ON f.id = t.family_id JOIN exomem_oauth_grants g ON g.id = f.grant_id WHERE g.tenant_id = $1", + [a.tenantId] + ); + assert.equal(all.rows[0].count, expiries.size, "one row for each distinct expiry"); + const recorded = await pool.query( + "SELECT count(*)::int AS count FROM exomem_cloud_issuance_log WHERE tenant_id = $1 AND credential_kind = 'download_ticket'", + [a.tenantId] + ); + assert.equal(recorded.rows[0].count, expiries.size, "one issuance record for each stored row"); + }); + + it("serves a correctly signed ticket only with its stored row, and the check rides inside the login lookup", async () => { + const a = await owner(); + const b = await owner(); + const { reached, follow } = gateway([a, b]); + const location = (await link(a)).headers.get("location")!; + const claims = claimsOf(location); + const otherLocation = (await link(b)).headers.get("location")!; + const ticketRow = (family: string) => + pool.query( + "SELECT id, path_sha256, expires_at FROM exomem_cloud_download_tickets WHERE family_id = $1", + [family] + ); + const [row] = (await ticketRow(claims.family_id)).rows; + const other = (await ticketRow(claimsOf(otherLocation).family_id)).rows[0]; + + // Count the statements that the gateway runs for one download. + const statements: string[] = []; + const asGateway = gatewaySql; + gatewaySql = async (strings, ...values) => { + statements.push(strings.join("?")); + return asGateway(strings, ...values); + }; + try { + assert.equal((await follow(location, { range: "bytes=0-1" })).status, 206); + } finally { + gatewaySql = asGateway; + } + const lookups = statements.filter((text) => text.includes("exomem_cloud_download_tickets")); + assert.equal(lookups.length, 1, "no statement is added: the ticket row is checked in place"); + assert.ok(lookups[0].includes("exomem_oauth_access_tokens"), "inside the login lookup"); + + // Each key of the stored row decides: a row that differs in one is no row for this ticket. + const reset = () => + pool.query( + "UPDATE exomem_cloud_download_tickets SET family_id = $2, path_sha256 = $3, expires_at = $4 WHERE id = $1", + [row.id, claims.family_id, row.path_sha256, row.expires_at] + ); + const variants: Array<[string, string, unknown[]]> = [ + ["no row", "DELETE FROM exomem_cloud_download_tickets WHERE id = $1", []], + [ + "another path", + "UPDATE exomem_cloud_download_tickets SET path_sha256 = $2 WHERE id = $1", + ["0".repeat(64)], + ], + [ + "another expiry", + "UPDATE exomem_cloud_download_tickets SET expires_at = expires_at + interval '1 second' WHERE id = $1", + [], + ], + [ + "another family", + "UPDATE exomem_cloud_download_tickets SET family_id = $2 WHERE id = $1", + [claimsOf(otherLocation).family_id], + ], + ]; + // The other owner's row may carry this ticket's path and expiry; the move below needs its place. + await pool.query("DELETE FROM exomem_cloud_download_tickets WHERE id = $1", [other.id]); + const served = reached.length; + for (const [name, text, extra] of variants) { + await pool.query(text, [row.id, ...extra]); + assert.equal((await follow(location)).status, 401, `${name}: refused`); + if (name === "no row") { + await pool.query( + "INSERT INTO exomem_cloud_download_tickets (id, family_id, path_sha256, expires_at) VALUES ($1, $2, $3, $4)", + [row.id, claims.family_id, row.path_sha256, row.expires_at] + ); + } else await reset(); + } + assert.equal(reached.length, served, "no refused ticket reached a cell"); + assert.equal((await follow(location)).status, 200, "the restored row serves again"); + }); + it("answers 503 and mints nothing for a stopped cell", async () => { const stopped = await owner("stopped"); const response = await link(stopped); diff --git a/src/lib/exomem-hosted/__tests__/cloud-reviewer-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-reviewer-postgres.integration.test.ts index 7af1cf77..8335e4e0 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-reviewer-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-reviewer-postgres.integration.test.ts @@ -4,6 +4,7 @@ import { after, before, describe, it } from "node:test"; import { Pool, type PoolClient } from "pg"; import { applyMigrations } from "../../../../scripts/migrate"; import { __setExomemSqlForTests, __setExomemTransactionForTests, type ExomemSql } from "../db"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; import { randomCloudCellId } from "../cloud-admission"; import { @@ -30,6 +31,8 @@ import { const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; const CLOUD_RESOURCE = "https://cloud.example.test/mcp/v1"; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool; let pool: Pool; let schema: string; let statementBarrier: ((text: string) => Promise) | null = null; @@ -52,7 +55,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function transaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -225,7 +228,8 @@ describe("Cloud reviewer PostgreSQL authority", { skip: !databaseUrl }, () => { await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(transaction); }); after(async () => { @@ -236,6 +240,7 @@ describe("Cloud reviewer PostgreSQL authority", { skip: !databaseUrl }, () => { } __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); diff --git a/src/lib/exomem-hosted/__tests__/cloud-service-credentials-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/cloud-service-credentials-postgres.integration.test.ts index 65e139b2..a5d5d361 100644 --- a/src/lib/exomem-hosted/__tests__/cloud-service-credentials-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/cloud-service-credentials-postgres.integration.test.ts @@ -19,6 +19,8 @@ import { } from "../db"; import { digestSecret } from "../security"; import { SERVICE_CREDENTIAL_PREFIX } from "../service-credential-format"; +import { productionPool } from "./flow-pool"; +import { waitForWaiter } from "./identity-lock-fixture"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // add-cloud-service-credentials (D1-D5): the service credential store and the @@ -29,6 +31,8 @@ import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; const CLOUD_RESOURCE = "https://cloud.example.test/mcp/v1"; const OPERATOR_DIGEST = digestSecret("operator-test-principal"); const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool | undefined; let pool: Pool | undefined; let schema: string | undefined; @@ -44,7 +48,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function transaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -98,13 +102,15 @@ describe("Exomem Cloud service credentials PostgreSQL integration", { skip: !dat await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(transaction); }); after(async () => { __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); @@ -149,6 +155,21 @@ describe("Exomem Cloud service credentials PostgreSQL integration", { skip: !dat assert.equal(access.firstParty, false); }); + it("records the issue of a service credential against its tenant's owner, without the secret", async () => { + const { tenantId, ownerUserId } = await newTenantWithCell(); + const issued = await issue(tenantId); + const { rows } = await pool!.query( + "SELECT to_jsonb(log) AS record FROM exomem_cloud_issuance_log AS log WHERE tenant_id = $1", + [tenantId] + ); + assert.equal(rows.length, 1); + assert.equal(rows[0].record.credential_kind, "service_credential"); + assert.equal(rows[0].record.credential_id, issued.credentialId); + assert.equal(rows[0].record.user_id, ownerUserId); + assert.equal(rows[0].record.expires_at, null, "a service credential has no expiry"); + assert.equal(JSON.stringify(rows[0].record).includes(issued.secret), false); + }); + it("refuses a malformed principal before any row exists", async () => { const { tenantId } = await newTenantWithCell(); for (const principal of ["creator-platform", "service:", "service:Upper", "service:a_b"]) { @@ -326,6 +347,31 @@ describe("Exomem Cloud service credentials PostgreSQL integration", { skip: !dat }); }); + it("answers a request whose tenant's cell is deleted while it waits as ineligible, and stores nothing", async () => { + const target = await newTenantWithCell(); + const deletion = await pool!.connect(); + try { + await deletion.query("BEGIN"); + await deletion.query( + "UPDATE exomem_cloud_cells SET desired_state = 'deleted' WHERE cell_id = $1", + [target.cellId] + ); + // The lookup still reads the cell as live, so the insert's lock on that cell is what waits. + const issuing = issue(target.tenantId); + issuing.catch(() => undefined); + await waitForWaiter(pool!, deletion); + await deletion.query("COMMIT"); + await assert.rejects(issuing, { code: "SERVICE_CREDENTIAL_TENANT_INELIGIBLE" }); + const { rows } = await pool!.query( + "SELECT count(*)::integer AS count FROM exomem_cloud_service_credentials WHERE tenant_id = $1", + [target.tenantId] + ); + assert.equal(rows[0]!.count, 0); + } finally { + deletion.release(true); + } + }); + it("refuses issuance for a marketplace-reviewer tenant (review R2)", async () => { // Reviewer credentials carry their own expiry contract; a long-lived // service credential would sidestep it, so issuance is refused outright. diff --git a/src/lib/exomem-hosted/__tests__/cloud-service-credentials.test.ts b/src/lib/exomem-hosted/__tests__/cloud-service-credentials.test.ts new file mode 100644 index 00000000..1eff50e6 --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/cloud-service-credentials.test.ts @@ -0,0 +1,31 @@ +import assert from "node:assert/strict"; +import { after, before, describe, it } from "node:test"; +import { issueCloudServiceCredentialAtomic } from "../cloud-service-credentials"; +import { __setExomemTransactionForTests } from "../db"; +import { digestSecret } from "../security"; + +// A request whose transaction PostgreSQL fails to break a lock cycle gets a retryable answer, +// not an unnamed 500 (design D5). The cycle itself needs two transactions and is not reproduced. + +describe("Exomem Cloud service credential issuance, lock cycle", () => { + before(() => { + __setExomemTransactionForTests(async () => { + throw Object.assign(new Error("deadlock detected"), { code: "40P01" }); + }); + }); + + after(() => { + __setExomemTransactionForTests(null); + }); + + it("answers a deadlock that PostgreSQL detects as a retryable 503", async () => { + await assert.rejects( + issueCloudServiceCredentialAtomic({ + tenantId: "018f2d91-7c42-7000-8000-000000000012", + principal: "service:creator-platform", + operatorPrincipalDigest: digestSecret("operator-test-principal"), + }), + { code: "SERVICE_CREDENTIAL_RETRY", status: 503, retryable: true, retryAfterMs: 3000 } + ); + }); +}); diff --git a/src/lib/exomem-hosted/__tests__/consent-apps-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/consent-apps-postgres.integration.test.ts index bc6054b2..7c3dbe3c 100644 --- a/src/lib/exomem-hosted/__tests__/consent-apps-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/consent-apps-postgres.integration.test.ts @@ -23,6 +23,7 @@ import { } from "../oauth-store"; import { disconnectOwnerApp, listOwnerApps, setOwnerAppContext } from "../owner-apps"; import { digestSecret, generateExternalToken, tokenDigest } from "../security"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; // Consent outcomes and connected apps (launch-exomem-cloud-web, B and C) @@ -32,6 +33,8 @@ import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; const CLOUD_RESOURCE = "https://cloud.example.test/mcp/v1"; const ORIGIN = "https://exomem.example.test"; const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool | undefined; let pool: Pool | undefined; let schema: string | undefined; @@ -54,7 +57,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function interactiveTransaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -310,7 +313,8 @@ describe( await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema!); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(interactiveTransaction); }); @@ -318,6 +322,7 @@ describe( __setExomemSqlForTests(null); __setExomemTransactionForTests(null); setOperationalEventSinkForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); diff --git a/src/lib/exomem-hosted/__tests__/flow-pool.ts b/src/lib/exomem-hosted/__tests__/flow-pool.ts new file mode 100644 index 00000000..ab064a55 --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/flow-pool.ts @@ -0,0 +1,52 @@ +import { Pool } from "pg"; +import { applyMigrations } from "../../../../scripts/migrate"; +import { TEST_ROLE_PASSWORD } from "./test-role-password"; + +// Production runs the web app's flows as its own database role, on the rights of +// scripts/exomem-cloud-grants.sql. A suite's own pool is the schema owner, which holds every right, +// so a flow that needs a right the grants script withholds passes there and fails in production. +// A suite hands its production code this pool instead, and keeps seeding and asserting on its own pool. +// The gateway reads the same tables as its own narrower role, so it has a pool of its own. +const FLOW_ROLE = "substrate_app"; +const GATEWAY_ROLE = "exomem_gateway"; +const FLOW_PASSWORD = TEST_ROLE_PASSWORD; + +/** The web app role's login on the suite's schema, with the grants script applied for it. */ +export function productionPool(scopedUrl: string, schema: string): Promise { + return rolePool(FLOW_ROLE, scopedUrl, schema); +} + +/** The gateway role's login on the suite's schema, with the grants script applied for it. */ +export function gatewayPool(scopedUrl: string, schema: string): Promise { + return rolePool(GATEWAY_ROLE, scopedUrl, schema); +} + +async function rolePool(role: string, scopedUrl: string, schema: string): Promise { + const admin = new Pool({ connectionString: process.env.EXOMEM_TEST_DATABASE_URL }); + try { + await admin.query( + `DO $$ + BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${role}') THEN + CREATE ROLE ${role} LOGIN PASSWORD '${FLOW_PASSWORD}'; + ELSE + ALTER ROLE ${role} WITH LOGIN PASSWORD '${FLOW_PASSWORD}'; + END IF; + END + $$;` + ); + await admin.query(`GRANT USAGE ON SCHEMA "${schema}" TO ${role}`); + } finally { + await admin.end(); + } + // The role exists now, so the grants script gives it its rights. + await applyMigrations({ databaseUrl: scopedUrl }); + const url = new URL(scopedUrl); + url.username = role; + url.password = FLOW_PASSWORD; + const pool = new Pool({ connectionString: url.toString() }); + // A pool that quietly ran as another role would turn this proof into a pass on every right. + const { rows } = await pool.query<{ role: string }>("SELECT current_user AS role"); + if (rows[0]?.role !== role) throw new Error(`${role} pool runs as ${rows[0]?.role}`); + return pool; +} diff --git a/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts b/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts new file mode 100644 index 00000000..d8e528ff --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/identity-lock-fixture.ts @@ -0,0 +1,261 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { Pool, type PoolClient } from "pg"; +import { applyMigrations } from "../../../../scripts/migrate"; +import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; +import { TEST_ROLE_PASSWORD } from "./test-role-password"; + +// The identity lock and the issuance log are proven as the real roles, not as a superuser that +// holds every right. A schema owned by substrate_owner takes the migrations and the grants script, +// as production does; substrate_app, exomem_gateway, exomem_cellctl and substrate_audit are plain +// login roles with no other privilege. + +const FIXTURE_ROLES = [ + "substrate_app", + "exomem_cellctl", + "exomem_gateway", + "substrate_audit", +] as const; +export type LockState = "narrow" | "wide"; + +const PASSWORD = TEST_ROLE_PASSWORD; + +export type LockFixture = { + schema: string; + /** The schema owner, which runs the migrations and holds every right. */ + owner: Pool; + app: Pool; + gateway: Pool; + cellctl: Pool; + audit: Pool; + admin: Pool; + /** `"".`, so a statement reaches the real table whatever a session's temporary tables hold. */ + q(name: string): string; + roleUrl(role: string): string; + close(): Promise; +}; + +async function ensureRole(admin: Pool, name: string): Promise { + await admin.query( + `DO $$ + BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${name}') THEN + CREATE ROLE ${name} LOGIN PASSWORD '${PASSWORD}'; + ELSE + ALTER ROLE ${name} WITH LOGIN PASSWORD '${PASSWORD}'; + END IF; + END + $$;` + ); +} + +/** + * A migrated schema in one of two rights states. The narrow state is what the grants script gives. + * The wide state adds select, insert, update, delete and truncate on every table, the log included, + * for the three service roles: the rights an earlier grants script gave, and more. + */ +export async function createLockFixture( + state: LockState, + options: { migrate?: boolean } = {} +): Promise { + const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL!; + const schema = `lock_it_${state}_${randomUUID().replaceAll("-", "")}`; + await ensureExomemPostgresTestExtensions(databaseUrl); + const admin = new Pool({ connectionString: databaseUrl }); + for (const role of ["substrate_owner", ...FIXTURE_ROLES]) await ensureRole(admin, role); + await admin.query(`CREATE SCHEMA "${schema}" AUTHORIZATION substrate_owner`); + await admin.query(`GRANT USAGE ON SCHEMA "${schema}" TO ${FIXTURE_ROLES.join(", ")}`); + + const roleUrl = (role: string): string => { + const url = new URL(databaseUrl); + url.username = role; + url.password = PASSWORD; + url.searchParams.set("options", `-c search_path=${schema},public`); + return url.toString(); + }; + if (options.migrate !== false) { + await applyMigrations({ databaseUrl: roleUrl("substrate_owner") }); + if (state === "wide") { + await admin.query( + `GRANT SELECT, INSERT, UPDATE, DELETE, TRUNCATE ON ALL TABLES IN SCHEMA "${schema}" + TO substrate_app, exomem_gateway, exomem_cellctl` + ); + } + } + const pools: Pool[] = [admin]; + const pool = (role: string): Pool => { + const created = new Pool({ connectionString: roleUrl(role), max: 4 }); + pools.push(created); + return created; + }; + return { + schema, + owner: pool("substrate_owner"), + app: pool("substrate_app"), + gateway: pool("exomem_gateway"), + cellctl: pool("exomem_cellctl"), + audit: pool("substrate_audit"), + admin, + q: (name) => `"${schema}".${name}`, + roleUrl, + async close() { + // Drop first: an open pool of a role keeps no lock on the schema. + await admin.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); + for (const created of pools) await created.end(); + }, + }; +} + +export type World = { + userId: string; + tenantId: string; + /** The tenant's one live cell. A service credential can be inserted only for a tenant that has one. */ + cellId: string; + clientId: string; + grantId: string; + familyId: string; + accessTokenId: string; + accessDigest: Buffer; + refreshTokenId: string; + refreshDigest: Buffer; + serviceCredentialId: string; + /** The same rows, spent: revoked, consumed. A guard keeps each of those times. */ + spent: { + grantId: string; + familyId: string; + accessTokenId: string; + refreshTokenId: string; + serviceCredentialId: string; + }; +}; + +const RESOURCE = "https://gateway.example.test/mcp"; + +/** A pinned client row; its redirect list and digest satisfy the table's checks. */ +export async function seedClient(owner: Pool): Promise { + const redirectUris = JSON.stringify(["https://client.example.test/callback"]); + const { rows } = await owner.query<{ id: string }>( + `INSERT INTO exomem_oauth_clients ( + client_id, admission_mode, enabled, redirect_uris, redirect_uris_digest, + client_platform, oauth_client_config_sha256 + ) VALUES ($1, 'pinned', true, $2::jsonb, digest(convert_to($2::jsonb::text, 'utf8'), 'sha256'), + 'claude', $3) RETURNING id`, + [`https://client.example.test/${randomUUID()}.json`, redirectUris, "f".repeat(64)] + ); + return rows[0]!.id; +} + +/** One tenant with a live chain of credentials and a spent chain, written as the schema owner. */ +export async function seedWorld(owner: Pool): Promise { + const id = async (text: string, values: unknown[] = []): Promise => + (await owner.query<{ id: string }>(text, values)).rows[0]!.id; + const userId = await id("INSERT INTO exomem_users (email) VALUES ($1) RETURNING id", [ + `lock-${randomUUID()}@example.test`, + ]); + const tenantId = await id("INSERT INTO exomem_tenants (owner_user_id) VALUES ($1) RETURNING id", [ + userId, + ]); + const cellId = await seedCell(owner, tenantId); + const clientId = await seedClient(owner); + const chain = async (spent: boolean) => { + const revokedAt = spent ? "now()" : "NULL"; + const grant = await id( + `INSERT INTO exomem_oauth_grants (user_id, tenant_id, client_id, resource, scopes, revoked_at) + VALUES ($1, $2, $3, $4, ARRAY['mcp:read'], ${revokedAt}) RETURNING id`, + [userId, tenantId, clientId, `${RESOURCE}/${randomUUID()}`] + ); + const family = await id( + `INSERT INTO exomem_oauth_token_families (grant_id, client_id, expires_at, revoked_at) + VALUES ($1, $2, now() + interval '1 day', ${revokedAt}) RETURNING id`, + [grant, clientId] + ); + const accessDigest = randomBytes(32); + const access = await id( + `INSERT INTO exomem_oauth_access_tokens + (access_digest, grant_id, family_id, client_id, resource, scopes, expires_at, revoked_at) + VALUES ($1, $2, $3, $4, $5, ARRAY['mcp:read'], now() + interval '1 hour', ${revokedAt}) + RETURNING id`, + [accessDigest, grant, family, clientId, RESOURCE] + ); + const refreshDigest = randomBytes(32); + const refresh = await id( + `INSERT INTO exomem_oauth_refresh_tokens (refresh_digest, family_id, expires_at, consumed_at) + VALUES ($1, $2, now() + interval '1 day', ${revokedAt}) RETURNING id`, + [refreshDigest, family] + ); + const credential = await id( + `INSERT INTO exomem_cloud_service_credentials + (tenant_id, principal, secret_digest, created_by_principal_digest, revoked_at, revoked_by_principal_digest) + VALUES ($1, $2, $3, $4, ${revokedAt}, ${spent ? "$4" : "NULL"}) RETURNING id`, + [tenantId, `service:t${randomBytes(6).toString("hex")}`, randomBytes(32), randomBytes(32)] + ); + return { grant, family, access, accessDigest, refresh, refreshDigest, credential }; + }; + const live = await chain(false); + const spent = await chain(true); + return { + userId, + tenantId, + cellId, + clientId, + grantId: live.grant, + familyId: live.family, + accessTokenId: live.access, + accessDigest: live.accessDigest, + refreshTokenId: live.refresh, + refreshDigest: live.refreshDigest, + serviceCredentialId: live.credential, + spent: { + grantId: spent.grant, + familyId: spent.family, + accessTokenId: spent.access, + refreshTokenId: spent.refresh, + serviceCredentialId: spent.credential, + }, + }; +} + +const CELL_ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567"; + +/** A cell id as the table's check requires: sixteen characters of lower-case base32. */ +export function randomCellId(): string { + return Array.from(randomBytes(16), (byte) => CELL_ID_ALPHABET[byte % 32]).join(""); +} + +/** A running cell row for a tenant, written as the schema owner. Returns its cell id. */ +async function seedCell(owner: Pool, tenantId: string): Promise { + const cellId = randomCellId(); + await owner.query( + "INSERT INTO exomem_cloud_cells (cell_id, tenant_id, desired_state) VALUES ($1, $2, 'running')", + [cellId, tenantId] + ); + return cellId; +} + +/** + * Waits until another session waits for the open transaction on `holder`. The wait is the proof + * that a lock is held: a statement that never waits fails here, and a statement that is stuck + * fails on the caller's statement timeout, so a wrong lock never shows as a pass or a hang. + */ +export async function waitForWaiter(observer: Pool, holder: PoolClient): Promise { + const { rows } = await holder.query<{ xid: string }>( + "SELECT pg_current_xact_id()::xid::text AS xid" + ); + for (let attempt = 0; attempt < 100; attempt += 1) { + const waiting = await observer.query( + `SELECT 1 FROM pg_locks + WHERE locktype = 'transactionid' AND NOT granted AND transactionid = $1::xid`, + [rows[0]!.xid] + ); + if (waiting.rows.length > 0) return; + await new Promise((resolve) => setTimeout(resolve, 50)); + } + throw new Error("no statement waited for the open transaction"); +} + +/** Every row of a table as JSON, to compare before and after a refused statement. */ +export async function tableSnapshot(owner: Pool, table: string): Promise { + const { rows } = await owner.query<{ snapshot: string }>( + `SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text), '[]'::jsonb)::text AS snapshot FROM ${table} AS t` + ); + return rows[0]!.snapshot; +} diff --git a/src/lib/exomem-hosted/__tests__/migration-runner.integration.test.ts b/src/lib/exomem-hosted/__tests__/migration-runner.integration.test.ts index ed50d80e..871c575c 100644 --- a/src/lib/exomem-hosted/__tests__/migration-runner.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/migration-runner.integration.test.ts @@ -4,7 +4,11 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, it } from "node:test"; import { Client } from "pg"; -import { applyMigrations } from "../../../../scripts/migrate"; +import { + applyMigrations, + MIGRATION_LOCK_ID, + MIGRATION_LOCK_NAMESPACE, +} from "../../../../scripts/migrate"; const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL ?? process.env.DATABASE_URL; @@ -81,4 +85,51 @@ describe("migration runner PostgreSQL integration", { skip: !databaseUrl }, () = rmSync(directory, { recursive: true, force: true }); } }); + + it("lists pending migrations in a dry run without creating a table or waiting for the migration lock", async () => { + const schema = `migration_dry_${process.pid}_${Date.now()}`; + const admin = new Client({ connectionString: databaseUrl }); + const holder = new Client({ connectionString: databaseUrl }); + const directory = mkdtempSync(join(tmpdir(), "exomem-migrations-")); + await admin.connect(); + await holder.connect(); + try { + await admin.query(`CREATE SCHEMA "${schema}"`); + writeFileSync( + join(directory, "0001_dry_probe.sql"), + "CREATE TABLE dry_probe (id integer);\n", + "utf8" + ); + const scopedUrl = new URL(databaseUrl!); + scopedUrl.searchParams.set("options", `-c search_path=${schema}`); + // Another runner holds the migration lock for the whole dry run. + await holder.query("SELECT pg_advisory_lock($1, $2)", [ + MIGRATION_LOCK_NAMESPACE, + MIGRATION_LOCK_ID, + ]); + + const finished = applyMigrations({ + databaseUrl: scopedUrl.toString(), + migrationsDir: directory, + dry: true, + }).then(() => "done"); + const timeout = new Promise((resolve) => setTimeout(() => resolve("waiting"), 5_000)); + assert.equal(await Promise.race([finished, timeout]), "done"); + + const tables = await admin.query( + "SELECT table_name FROM information_schema.tables WHERE table_schema = $1", + [schema] + ); + assert.deepEqual(tables.rows, [], "the dry run left the empty schema empty"); + } finally { + await holder.query("SELECT pg_advisory_unlock($1, $2)", [ + MIGRATION_LOCK_NAMESPACE, + MIGRATION_LOCK_ID, + ]); + await holder.end(); + await admin.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); + await admin.end(); + rmSync(directory, { recursive: true, force: true }); + } + }); }); diff --git a/src/lib/exomem-hosted/__tests__/oauth-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/oauth-postgres.integration.test.ts index 65af59c1..a10f576e 100644 --- a/src/lib/exomem-hosted/__tests__/oauth-postgres.integration.test.ts +++ b/src/lib/exomem-hosted/__tests__/oauth-postgres.integration.test.ts @@ -5,6 +5,7 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { Pool, type PoolClient } from "pg"; import { applyMigrations } from "../../../../scripts/migrate"; +import { productionPool } from "./flow-pool"; import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; import { admitFirstCloudOAuthInviteAtomic, randomCloudCellId } from "../cloud-admission"; import { findCloudOAuthAccessToken, resolveApprovedCloudOAuthClient } from "../cloud-oauth"; @@ -47,6 +48,8 @@ const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; const clientId = "https://client.example.test/metadata.json"; const resource = "https://gateway.example.test/mcp"; let pool: Pool | undefined; +// The pool that production code runs on: the suite's own, or the web app role's. +let flowPool: Pool | undefined; let schema: string | undefined; function digest(value: number): Buffer { @@ -67,7 +70,7 @@ function taggedSql(client: Pool | PoolClient): ExomemSql { } async function interactiveTransaction(callback: (tx: ExomemSql) => Promise): Promise { - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); @@ -235,7 +238,8 @@ describe("OAuth admission PostgreSQL integration", { skip: !databaseUrl, concurr await applyMigrations({ databaseUrl: scoped.toString() }); await admin.end(); pool = new Pool({ connectionString: scoped.toString() }); - __setExomemSqlForTests(taggedSql(pool)); + flowPool = await productionPool(scoped.toString(), schema); + __setExomemSqlForTests(taggedSql(flowPool)); __setExomemTransactionForTests(interactiveTransaction); await seedLiveCohort(); }); @@ -245,6 +249,7 @@ describe("OAuth admission PostgreSQL integration", { skip: !databaseUrl, concurr delete process.env.EXOMEM_CLOUD_MCP_PATH; __setExomemSqlForTests(null); __setExomemTransactionForTests(null); + await flowPool?.end(); if (pool) await pool.end(); if (schema) { const admin = new Pool({ connectionString: databaseUrl }); @@ -857,6 +862,50 @@ describe("OAuth admission PostgreSQL integration", { skip: !databaseUrl, concurr ); }); + it("records each credential that a code exchange and a refresh rotation write", async () => { + const internal = await seedClient(); + const fixture = await seedAuthorizationCode(internal, 160, true); + const recorded = async () => + ( + await pool!.query<{ credential_kind: string; count: number }>( + `SELECT credential_kind, count(*)::int AS count FROM exomem_cloud_issuance_log + WHERE tenant_id = $1 AND user_id = $2 GROUP BY credential_kind ORDER BY credential_kind`, + [fixture.tenantId, fixture.userId] + ) + ).rows; + assert.deepEqual(await recorded(), []); + const issued = await issueOAuthTokensFromCodeAtomic({ + codeDigest: fixture.codeDigest, + clientId, + redirectUri: "https://client.example.test/callback", + resource, + pkceChallenge: "challenge", + refreshDigest: digest(161), + accessDigest: digest(162), + accessExpiresAt: new Date(Date.now() + 60_000), + }); + assert.ok(issued); + assert.deepEqual(await recorded(), [ + { credential_kind: "access_token", count: 1 }, + { credential_kind: "refresh_token", count: 1 }, + { credential_kind: "token_family", count: 1 }, + ]); + const rotated = await rotateOAuthRefreshTokenAtomic({ + refreshDigest: digest(161), + replacementRefreshDigest: digest(163), + accessDigest: digest(164), + accessExpiresAt: new Date(Date.now() + 60_000), + clientId, + resource, + }); + assert.equal(rotated?.kind, "issued"); + assert.deepEqual(await recorded(), [ + { credential_kind: "access_token", count: 2 }, + { credential_kind: "refresh_token", count: 2 }, + { credential_kind: "token_family", count: 1 }, + ]); + }); + it("persists refresh material only for offline access and retains rotation lineage during GC", async () => { const internal = await seedClient(); const online = await seedAuthorizationCode(internal, 120, false); @@ -1622,7 +1671,7 @@ describe("OAuth admission PostgreSQL integration", { skip: !databaseUrl, concurr let transactions = 0; __setExomemTransactionForTests(async (callback) => { const holdsOpen = transactions++ === 0; - const client = await pool!.connect(); + const client = await flowPool!.connect(); try { await client.query("BEGIN ISOLATION LEVEL READ COMMITTED"); const result = await callback(taggedSql(client)); diff --git a/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts b/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts new file mode 100644 index 00000000..d99b1fc3 --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/schema-release-postgres.integration.test.ts @@ -0,0 +1,265 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { cp, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, before, describe, it } from "node:test"; +import { Pool } from "pg"; +import { applyMigrations } from "../../../../scripts/migrate"; +import { ensureExomemPostgresTestExtensions } from "./postgres-test-extensions"; +import { TEST_ROLE_PASSWORD } from "./test-role-password"; + +// Schema releases (design D9): the table the release job writes and the +// production build reads, and how the migration runner records into it. + +const databaseUrl = process.env.EXOMEM_TEST_DATABASE_URL; +const TEST_PASSWORD = TEST_ROLE_PASSWORD; +const FIRST = "1".repeat(40); +const SECOND = "2".repeat(40); +const THIRD = "3".repeat(40); + +let adminPool: Pool | undefined; +let ownerPool: Pool | undefined; +let appPool: Pool | undefined; +let schema: string | undefined; +let ownerUrl: string; + +function roleUrl(role: string): string { + const url = new URL(databaseUrl!); + url.username = role; + url.password = TEST_PASSWORD; + url.searchParams.set("options", `-c search_path=${schema},public`); + return url.toString(); +} + +async function ensureRole(name: string): Promise { + await adminPool!.query( + `DO $$ + BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${name}') THEN + CREATE ROLE ${name} LOGIN PASSWORD '${TEST_PASSWORD}'; + ELSE + ALTER ROLE ${name} WITH LOGIN PASSWORD '${TEST_PASSWORD}'; + END IF; + END + $$;` + ); +} + +async function releases(): Promise> { + const { rows } = await ownerPool!.query( + "SELECT commit_sha, status FROM schema_releases ORDER BY commit_sha" + ); + return rows; +} + +async function clearReleases(): Promise { + await ownerPool!.query("DELETE FROM schema_releases"); +} + +describe("schema releases PostgreSQL integration", { skip: !databaseUrl }, () => { + before(async () => { + schema = `schema_release_it_${randomUUID().replaceAll("-", "")}`; + await ensureExomemPostgresTestExtensions(databaseUrl!); + adminPool = new Pool({ connectionString: databaseUrl }); + await ensureRole("substrate_owner"); + await ensureRole("substrate_app"); + await adminPool.query(`CREATE SCHEMA "${schema}" AUTHORIZATION substrate_owner`); + await adminPool.query(`GRANT USAGE ON SCHEMA "${schema}" TO substrate_app`); + ownerUrl = roleUrl("substrate_owner"); + await applyMigrations({ databaseUrl: ownerUrl }); + ownerPool = new Pool({ connectionString: ownerUrl }); + appPool = new Pool({ connectionString: roleUrl("substrate_app") }); + }); + + after(async () => { + await appPool?.end(); + await ownerPool?.end(); + if (schema) await adminPool!.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); + await adminPool?.end(); + }); + + it("lets the web app's role read schema releases and refuses every write, also when it holds the rights", async () => { + await ownerPool!.query( + "INSERT INTO schema_releases (commit_sha, status) VALUES ($1, 'released')", + [FIRST] + ); + try { + const read = await appPool!.query( + "SELECT status FROM schema_releases WHERE commit_sha = $1", + [FIRST] + ); + assert.deepEqual(read.rows, [{ status: "released" }]); + + const writes = [ + `INSERT INTO schema_releases (commit_sha, status) VALUES ('${SECOND}', 'released')`, + `UPDATE schema_releases SET status = 'superseded' WHERE commit_sha = '${FIRST}'`, + "DELETE FROM schema_releases", + "TRUNCATE schema_releases", + ]; + for (const write of writes) { + await assert.rejects(appPool!.query(write), /permission denied/, write); + } + + // The guard holds when a grants script gives the rights anyway. + await ownerPool!.query( + "GRANT INSERT, UPDATE, DELETE, TRUNCATE ON schema_releases TO substrate_app" + ); + for (const write of writes) { + await assert.rejects(appPool!.query(write), /EXOMEM_ROW_LOCKED/, write); + } + assert.deepEqual(await releases(), [{ commit_sha: FIRST, status: "released" }]); + } finally { + await ownerPool!.query( + "REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON schema_releases FROM substrate_app" + ); + await clearReleases(); + } + }); + + it("records a release and its superseded commits only after migrations and grants succeed", async () => { + await applyMigrations({ + databaseUrl: ownerUrl, + commit: SECOND, + supersededCommits: [FIRST, SECOND], + }); + assert.deepEqual(await releases(), [ + { commit_sha: FIRST, status: "superseded" }, + { commit_sha: SECOND, status: "released" }, + ]); + }); + + it("records nothing for a dry run, a run with no commit, a failed migration or a failed grants script", async () => { + await clearReleases(); + await applyMigrations({ + databaseUrl: ownerUrl, + dry: true, + commit: FIRST, + supersededCommits: [SECOND], + }); + await applyMigrations({ databaseUrl: ownerUrl }); + + const migrations = await mkdtemp(join(tmpdir(), "schema-release-migrations-")); + const brokenGrants = join(migrations, "broken-grants.sql"); + try { + for (const name of await readdir("migrations")) + await cp(join("migrations", name), join(migrations, name)); + await writeFile(join(migrations, "9999_fails.sql"), "SELECT 1 / 0;\n"); + await assert.rejects( + applyMigrations({ + databaseUrl: ownerUrl, + migrationsDir: migrations, + commit: FIRST, + supersededCommits: [SECOND], + }), + /9999_fails/ + ); + await rm(join(migrations, "9999_fails.sql")); + + await writeFile(brokenGrants, "SELECT 1 / 0;\n"); + await assert.rejects( + applyMigrations({ + databaseUrl: ownerUrl, + grantsFile: brokenGrants, + commit: FIRST, + supersededCommits: [SECOND], + }), + /grants failed/ + ); + } finally { + await rm(migrations, { recursive: true, force: true }); + } + assert.deepEqual(await releases(), []); + }); + + it("keeps the status of a commit that already has a row", async () => { + await clearReleases(); + await applyMigrations({ databaseUrl: ownerUrl, commit: FIRST }); + await applyMigrations({ + databaseUrl: ownerUrl, + commit: SECOND, + supersededCommits: [FIRST, THIRD], + }); + await applyMigrations({ + databaseUrl: ownerUrl, + commit: THIRD, + supersededCommits: [SECOND], + }); + assert.deepEqual(await releases(), [ + { commit_sha: FIRST, status: "released" }, + { commit_sha: SECOND, status: "released" }, + { commit_sha: THIRD, status: "superseded" }, + ]); + }); + + it("releases the pushed tip, and marks the older commit superseded, when a run that an older commit started proceeds", async () => { + await clearReleases(); + const root = await mkdtemp(join(tmpdir(), "schema-release-remote-")); + try { + const origin = join(root, "origin"); + const checkout = join(root, "checkout"); + const git = (cwd: string, ...args: string[]) => + execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + execFileSync("git", ["init", "--quiet", "--initial-branch=main", origin]); + git(origin, "config", "user.email", "test@example.test"); + git(origin, "config", "user.name", "test"); + const push = async (name: string) => { + await writeFile(join(origin, name), name); + git(origin, "add", name); + git(origin, "commit", "--quiet", "-m", name); + return git(origin, "rev-parse", "HEAD"); + }; + const older = await push("older"); + const newer = await push("newer"); + // The job's checkout takes the tip of main, not the commit that started the run. + execFileSync("git", ["clone", "--quiet", "--branch", "main", origin, checkout]); + const plan = Object.fromEntries( + execFileSync(join(process.cwd(), "scripts/schema-release-plan.sh"), [], { + cwd: checkout, + encoding: "utf8", + }) + .trim() + .split("\n") + .map((line) => line.split("=") as [string, string]) + ); + assert.equal(plan.apply, "true"); + + await applyMigrations({ + databaseUrl: ownerUrl, + commit: plan.tip, + supersededCommits: plan.superseded!.split(","), + }); + assert.deepEqual( + await releases(), + [ + { commit_sha: older, status: "superseded" }, + { commit_sha: newer, status: "released" }, + ].sort((a, b) => a.commit_sha.localeCompare(b.commit_sha)) + ); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it("fails a malformed commit before it connects", async () => { + // Nothing listens on this address, so only the check before connecting can answer. + const unreachable = "postgresql://nobody:none@127.0.0.1:1/none"; + await assert.rejects( + applyMigrations({ databaseUrl: unreachable, commit: "abc123" }), + /40-character/ + ); + await assert.rejects( + applyMigrations({ + databaseUrl: unreachable, + commit: FIRST, + supersededCommits: [`${SECOND}x`], + }), + /40-character/ + ); + await assert.rejects( + applyMigrations({ databaseUrl: unreachable, commit: "A".repeat(40) }), + /40-character/ + ); + }); +}); diff --git a/src/lib/exomem-hosted/__tests__/schema-release.test.ts b/src/lib/exomem-hosted/__tests__/schema-release.test.ts new file mode 100644 index 00000000..3d0cad3c --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/schema-release.test.ts @@ -0,0 +1,243 @@ +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { afterEach, beforeEach, describe, it } from "node:test"; +import { parse } from "yaml"; +import { checkSchemaRelease } from "../../../../scripts/wait-for-schema-release"; + +// The production build's gate (scripts/wait-for-schema-release.ts), the release +// job's workflow file and its tip check. The database side runs in +// schema-release-postgres.integration.test.ts. + +const COMMIT = "a".repeat(40); +const NEWER = "b".repeat(40); +type Row = { status: string | null; newestReleased: string | null }; + +function productionEnv(extra: Record = {}) { + return { VERCEL_ENV: "production", VERCEL_GIT_COMMIT_SHA: COMMIT, ...extra }; +} + +/** A fake clock and database: each read returns the next scripted outcome. */ +function harness(outcomes: Array) { + let clock = 0; + const log: string[] = []; + const reads: number[] = []; + return { + log, + reads, + deps: { + read: async (): Promise => { + reads.push(clock); + const outcome = outcomes[Math.min(reads.length - 1, outcomes.length - 1)]!; + if ("code" in outcome) throw Object.assign(new Error("database"), { code: outcome.code }); + return outcome; + }, + sleep: async (ms: number) => { + clock += ms; + }, + now: () => clock, + log: (line: string) => log.push(line), + }, + }; +} + +describe("production build schema release gate", () => { + beforeEach(() => { + process.env.EXOMEM_CONTROL_PLANE_KEY = randomBytes(32).toString("base64url"); + }); + + it("continues on a released commit and says when a newer release exists", async () => { + const run = harness([{ status: "released", newestReleased: NEWER }]); + await checkSchemaRelease(productionEnv(), run.deps); + assert.equal(run.reads.length, 1); + assert.ok(run.log.some((line) => line.includes(`newer schema release exists (${NEWER})`))); + }); + + it("fails at once, without waiting, when its commit is superseded", async () => { + const run = harness([{ status: "superseded", newestReleased: NEWER }]); + await assert.rejects(checkSchemaRelease(productionEnv(), run.deps), /superseded/); + assert.equal(run.reads.length, 1); + }); + + it("fails after its bounded wait when no row appears", async () => { + const run = harness([{ status: null, newestReleased: null }]); + await assert.rejects(checkSchemaRelease(productionEnv(), run.deps), /within 15 minutes/); + assert.ok(run.reads.length > 10); + assert.ok(run.reads.at(-1)! <= 15 * 60 * 1000); + }); + + it("keeps waiting while the table is missing or the select is refused, then continues", async () => { + const run = harness([ + { code: "42P01" }, + { code: "42501" }, + { status: null, newestReleased: null }, + { status: "released", newestReleased: COMMIT }, + ]); + await checkSchemaRelease(productionEnv(), run.deps); + assert.equal(run.reads.length, 4); + }); + + it("fails a production build that carries no commit or a malformed one", async () => { + const run = harness([{ status: "released", newestReleased: COMMIT }]); + await assert.rejects( + checkSchemaRelease(productionEnv({ VERCEL_GIT_COMMIT_SHA: "" }), run.deps), + /no commit/ + ); + await assert.rejects( + checkSchemaRelease(productionEnv({ VERCEL_GIT_COMMIT_SHA: "abc123" }), run.deps), + /40-character/ + ); + assert.equal(run.reads.length, 0); + }); + + it("does nothing outside production, and logs a skip under the override", async () => { + const preview = harness([]); + await checkSchemaRelease({ VERCEL_ENV: "preview" }, preview.deps); + assert.equal(preview.reads.length, 0); + + const skipped = harness([]); + await checkSchemaRelease(productionEnv({ SKIP_SCHEMA_RELEASE_WAIT: "1" }), skipped.deps); + assert.equal(skipped.reads.length, 0); + assert.ok(skipped.log.some((line) => line.includes("SKIP_SCHEMA_RELEASE_WAIT"))); + }); + + it("still refuses a production build without the control-plane key", async () => { + delete process.env.EXOMEM_CONTROL_PLANE_KEY; + const run = harness([{ status: "released", newestReleased: COMMIT }]); + await assert.rejects(checkSchemaRelease(productionEnv(), run.deps), /EXOMEM_CONTROL_PLANE_KEY/); + await assert.rejects( + checkSchemaRelease(productionEnv({ SKIP_SCHEMA_RELEASE_WAIT: "1" }), run.deps), + /EXOMEM_CONTROL_PLANE_KEY/ + ); + }); +}); + +const WORKFLOWS = resolve(process.cwd(), ".github/workflows"); +const RELEASE_WORKFLOW = "migrate-database.yml"; +const SHA_PINNED_ACTION = /^[\w.-]+\/[\w.-]+@[0-9a-f]{40}$/; + +type Step = { + id?: string; + name?: string; + uses?: string; + run?: string; + with?: Record; + env?: Record; +}; +type Workflow = { + on: Record; + jobs: Record; +}; + +function readWorkflow(name: string): Workflow { + return parse(readFileSync(join(WORKFLOWS, name), "utf8")) as Workflow; +} + +describe("schema release workflow", () => { + const release = readWorkflow(RELEASE_WORKFLOW); + const environmentOf = (job: Workflow["jobs"][string]) => + typeof job.environment === "string" ? job.environment : job.environment?.name; + const environment = environmentOf(Object.values(release.jobs)[0]!)!; + + it("names the protected environment in no other workflow, and starts on no other event", () => { + assert.ok(environment, "the release job names its environment"); + for (const name of readdirSync(WORKFLOWS).filter((file) => /\.ya?ml$/.test(file))) { + if (name === RELEASE_WORKFLOW) continue; + assert.ok( + !readFileSync(join(WORKFLOWS, name), "utf8").includes(environment), + `${name} names the protected environment ${environment}` + ); + } + assert.deepEqual(Object.keys(release.on).sort(), ["push", "workflow_dispatch"]); + // No path filter: the job applies only the tip, so a push that started no run would never release. + assert.deepEqual(release.on.push, { branches: ["main"] }); + }); + + it("releases the tip of main whatever commit started the run, reading it again just before it applies", () => { + const steps = Object.values(release.jobs).flatMap((job) => job.steps); + const checkout = steps.find((step) => step.uses?.startsWith("actions/checkout@"))!; + assert.equal(checkout.with?.ref, "main"); + assert.ok( + !JSON.stringify(steps).includes("GITHUB_SHA") && + !JSON.stringify(steps).includes("github.sha"), + "no step names the commit that started the run" + ); + const order = (match: (step: Step) => boolean) => steps.findIndex(match); + const install = order((step) => step.run === "npm ci --ignore-scripts"); + const plan = order((step) => step.run?.includes("schema-release-plan.sh") ?? false); + const migrate = order((step) => step.run?.includes("scripts/migrate.ts") ?? false); + assert.ok( + install >= 0 && install < plan && plan < migrate, + "the tip is read after the install" + ); + }); + + it("keeps the credential to one step, installs without scripts and pins every action", () => { + const steps = Object.values(release.jobs).flatMap((job) => job.steps); + const withSecret = steps.filter((step) => JSON.stringify(step.env ?? {}).includes("secrets.")); + assert.equal(withSecret.length, 1); + assert.match(withSecret[0]!.run ?? "", /scripts\/migrate\.ts/); + assert.ok(steps.some((step) => step.run === "npm ci --ignore-scripts")); + assert.ok( + !steps.some( + (step) => + /\bnpm (ci|install)\b/.test(step.run ?? "") && + !(step.run ?? "").includes("--ignore-scripts") + ) + ); + for (const step of steps.filter((candidate) => candidate.uses)) { + assert.match(step.uses!, SHA_PINNED_ACTION); + } + }); +}); + +describe("schema release tip check", () => { + let directory: string; + const git = (cwd: string, ...args: string[]) => + execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + const plan = (cwd: string) => + Object.fromEntries( + execFileSync(join(process.cwd(), "scripts/schema-release-plan.sh"), [], { + cwd, + encoding: "utf8", + }) + .trim() + .split("\n") + .map((line) => line.split("=") as [string, string]) + ); + const commitFile = (repository: string, name: string) => { + writeFileSync(join(repository, name), name); + git(repository, "add", name); + git(repository, "commit", "--quiet", "-m", name); + return git(repository, "rev-parse", "HEAD"); + }; + + beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), "schema-release-plan-")); + }); + afterEach(() => rmSync(directory, { recursive: true, force: true })); + + it("applies the tip with its older commits, and applies nothing once main has moved on", () => { + const origin = join(directory, "origin"); + const clone = join(directory, "clone"); + execFileSync("git", ["init", "--quiet", "--initial-branch=main", origin]); + git(origin, "config", "user.email", "test@example.test"); + git(origin, "config", "user.name", "test"); + const commits = ["one", "two", "three"].map((name) => commitFile(origin, name)); + execFileSync("git", ["clone", "--quiet", origin, clone]); + + const atTip = plan(clone); + assert.equal(atTip.tip, commits[2]); + assert.equal(atTip.apply, "true"); + assert.deepEqual(atTip.superseded!.split(","), [commits[1], commits[0]]); + + // A push lands while the job installs: its code is no longer the tip's. + const pushed = commitFile(origin, "four"); + const moved = plan(clone); + assert.equal(moved.tip, pushed); + assert.equal(moved.apply, "false"); + }); +}); diff --git a/src/lib/exomem-hosted/__tests__/test-role-password.ts b/src/lib/exomem-hosted/__tests__/test-role-password.ts new file mode 100644 index 00000000..cdade039 --- /dev/null +++ b/src/lib/exomem-hosted/__tests__/test-role-password.ts @@ -0,0 +1,5 @@ +// The login roles that the PostgreSQL suites create (`substrate_app`, `exomem_gateway`, ...) belong +// to the whole cluster, not to a suite's schema. Every suite sets their password before it +// connects, so two suites that set different ones lock each other out. One password, set by each +// suite, keeps the logins valid whichever suite ran last. +export const TEST_ROLE_PASSWORD = "exomem-suite-role-test"; diff --git a/src/lib/exomem-hosted/cloud-download-ticket.ts b/src/lib/exomem-hosted/cloud-download-ticket.ts index 68d79362..6226caab 100644 --- a/src/lib/exomem-hosted/cloud-download-ticket.ts +++ b/src/lib/exomem-hosted/cloud-download-ticket.ts @@ -75,6 +75,16 @@ export type DownloadTicketClaims = { grantId: string; }; +/** + * What a verified ticket names beyond its login: the path digest and the expiry + * (in epoch seconds) that its stored row is keyed by. The app stores the row from + * this and the gateway looks it up by this. + */ +export type VerifiedDownloadTicket = DownloadTicketClaims & { + pathSha256: string; + expiresAt: number; +}; + function pathDigest(path: string): string { return createHash("sha256").update(path, "utf8").digest("hex"); } @@ -117,15 +127,15 @@ export function signDownloadTicket( /** * The claims of a ticket that is genuine, unexpired and minted for exactly * `path`; otherwise null, with no hint of which check failed. A ticket is - * only ever a pointer to a login: the caller must still resolve that login and - * compare its tenant and cell with these claims. + * only ever a pointer to a login: the caller must still resolve that login, + * compare its tenant and cell with these claims, and find the ticket's stored row. */ export function verifyDownloadTicket( ticket: string, path: string, key: Buffer, options: { now?: number; lifetimeSeconds?: number } = {} -): DownloadTicketClaims | null { +): VerifiedDownloadTicket | null { const now = options.now ?? nowSeconds(); const cap = options.lifetimeSeconds ?? downloadTicketLifetimeSeconds(); if (ticket.length === 0 || ticket.length > MAX_TICKET_CHARS) return null; @@ -158,5 +168,7 @@ export function verifyDownloadTicket( cellId: claims.cell_id, familyId: claims.family_id, grantId: claims.grant_id, + pathSha256: claims.path_sha256, + expiresAt: claims.exp, }; } diff --git a/src/lib/exomem-hosted/cloud-media-download.ts b/src/lib/exomem-hosted/cloud-media-download.ts index 4dc6a305..af153645 100644 --- a/src/lib/exomem-hosted/cloud-media-download.ts +++ b/src/lib/exomem-hosted/cloud-media-download.ts @@ -10,7 +10,12 @@ import { CLOUD_DOWNLOAD_PATH } from "../../exomem-gateway/cloud-origin"; import { controlPlaneKeyFromEnv } from "./security"; import { loadExomemCloudResource, type EnvironmentSource } from "./cloud-config"; -import { downloadTicketLifetimeSeconds, signDownloadTicket } from "./cloud-download-ticket"; +import { + downloadTicketLifetimeSeconds, + signDownloadTicket, + verifyDownloadTicket, +} from "./cloud-download-ticket"; +import { executeExomemSql as sql } from "./db"; import { openHomeLoginForTicket, servingCell } from "./cloud-home-mcp"; import { ExomemHostedError, exomemErrors } from "./errors"; import { PRIVATE_NO_STORE_HEADERS } from "./http"; @@ -108,6 +113,7 @@ export async function handleCloudMediaDownloadRequest( : unavailableCell(login.refused); } + const key = controlPlaneKeyFromEnv(); const ticket = signDownloadTicket( { tenantId: session.tenantId, @@ -116,9 +122,22 @@ export async function handleCloudMediaDownloadRequest( grantId: login.grantId, path, }, - controlPlaneKeyFromEnv(), + key, { lifetimeSeconds } ); + // The gateway serves a ticket only with its stored row, so the row exists before the + // redirect. Its key is read back from the signed ticket, so it is what the gateway looks up. + const signed = verifyDownloadTicket(ticket, path, key, { lifetimeSeconds }); + if (!signed) throw exomemErrors.invalidRequest(); + await sql` + /* exomem:store-download-ticket */ + INSERT INTO exomem_cloud_download_tickets (family_id, path_sha256, expires_at) + VALUES ( + ${signed.familyId}::uuid, ${signed.pathSha256}, + to_timestamp(${signed.expiresAt}::double precision) + ) + ON CONFLICT (family_id, path_sha256, expires_at) DO NOTHING + `; const location = new URL(CLOUD_DOWNLOAD_PATH, mcpUrl); location.search = new URLSearchParams({ path, ticket }).toString(); return new Response(null, { diff --git a/src/lib/exomem-hosted/cloud-oauth.ts b/src/lib/exomem-hosted/cloud-oauth.ts index a7288697..3e8c4dcf 100644 --- a/src/lib/exomem-hosted/cloud-oauth.ts +++ b/src/lib/exomem-hosted/cloud-oauth.ts @@ -120,7 +120,15 @@ export type ActiveCloudOAuthLogin = { export type ActiveCloudOAuthAccessToken = ActiveCloudOAuthLogin & { scopes: string[] }; -type CloudOAuthSelector = { accessDigest: Buffer } | { familyId: string; grantId: string }; +/** + * A download ticket's stored row, which the login lookup requires when the caller + * holds a ticket (D8). The key is the ticket's own path digest and expiry. + */ +export type CloudDownloadTicketRow = { pathSha256: string; expiresAt: number }; + +type CloudOAuthSelector = + | { accessDigest: Buffer } + | { familyId: string; grantId: string; ticket?: CloudDownloadTicketRow }; /** * Looks up a Cloud-resource access token for the gateway (D3 step 4). Joins @@ -160,7 +168,7 @@ export async function findCloudOAuthAccessToken( * token lookup above except the token row's own. */ export async function findCloudOAuthLogin( - login: { familyId: string; grantId: string }, + login: { familyId: string; grantId: string; ticket?: CloudDownloadTicketRow }, acceptedResources: readonly string[] ): Promise { const row = await findCloudOAuthAuthority(login, acceptedResources); @@ -198,6 +206,8 @@ async function findCloudOAuthAuthority( const accessDigest = "accessDigest" in selector ? selector.accessDigest : null; const familyId = "familyId" in selector ? selector.familyId : null; const grantId = "grantId" in selector ? selector.grantId : null; + const ticketPathSha256 = "ticket" in selector ? (selector.ticket?.pathSha256 ?? null) : null; + const ticketExpiresAt = "ticket" in selector ? (selector.ticket?.expiresAt ?? null) : null; const { rows } = await executeExomemSql` /* exomem-cloud:find-oauth-access-token */ WITH token AS ( @@ -268,6 +278,16 @@ async function findCloudOAuthAuthority( -- is the one definition of "tenant live, owner unblocked" that this -- lookup and the service credential lookup share. AND exomem_cloud_tenant_access_allowed(oauth_grant.tenant_id, oauth_grant.user_id) + -- A download ticket is served only with its stored row (D8). The row is + -- found by the family, path digest and expiry that the ticket carries, so + -- this adds one index probe and no round trip. No other caller passes a ticket. + AND (${ticketPathSha256}::text IS NULL OR EXISTS ( + SELECT 1 FROM exomem_cloud_download_tickets AS stored_ticket + WHERE stored_ticket.family_id = token.family_id + AND stored_ticket.path_sha256 = ${ticketPathSha256}::text + AND stored_ticket.expires_at = to_timestamp(${ticketExpiresAt}::double precision) + AND stored_ticket.expires_at > now() + )) LIMIT 1 `; return (rows[0] as CloudOAuthAuthorityRow | undefined) ?? null; diff --git a/src/lib/exomem-hosted/cloud-service-credentials.ts b/src/lib/exomem-hosted/cloud-service-credentials.ts index 8ce0cfed..f35c019a 100644 --- a/src/lib/exomem-hosted/cloud-service-credentials.ts +++ b/src/lib/exomem-hosted/cloud-service-credentials.ts @@ -24,6 +24,18 @@ import { SERVICE_CREDENTIAL_PRINCIPAL_FORMAT, } from "./service-credential-format"; +/** + * The name that migration 0102's insert trigger gives its refusal: the tenant's + * cell was deleted between this request's lookup and its insert (design D6). + */ +const NO_LIVE_CELL_CONSTRAINT = "exomem_cloud_service_credentials_live_cell"; + +/** + * PostgreSQL's code for a transaction that it failed to break a lock cycle (design D5). A + * serialization failure (40001) cannot reach this request: its transactions run at READ COMMITTED. + */ +const DEADLOCK_DETECTED = "40P01"; + /** Design D5: rotation without downtime is exactly two live credentials. */ const MAX_LIVE_CREDENTIALS_PER_PRINCIPAL = 2; @@ -134,6 +146,9 @@ export async function issueCloudServiceCredentialAtomic( if (Number(live.rows[0]?.count ?? 0) >= MAX_LIVE_CREDENTIALS_PER_PRINCIPAL) { throw exomemErrors.serviceCredentialLimit(); } + // The insert locks the cell's row, so a deletion that began after the lookup waits for + // this transaction; one that already ran makes the insert fail, and that failure + // gets the answer of a tenant with no live cell (design D6). const inserted = await tx` /* exomem-cloud:issue-service-credential */ INSERT INTO exomem_cloud_service_credentials ( @@ -142,7 +157,12 @@ export async function issueCloudServiceCredentialAtomic( ${row.id}::uuid, ${input.principal}, ${digestSecret(secret)}, ${input.operatorPrincipalDigest} ) RETURNING id - `; + `.catch((error: unknown) => { + if ((error as { constraint?: unknown } | null)?.constraint === NO_LIVE_CELL_CONSTRAINT) { + throw exomemErrors.serviceCredentialTenantIneligible(); + } + throw error; + }); return { credentialId: String(inserted.rows[0]!.id), tenantId: row.id, @@ -150,6 +170,14 @@ export async function issueCloudServiceCredentialAtomic( cellId: row.cell_id, secret, }; + }).catch((error: unknown) => { + // The sweep locks a cell before its tenant and this request locks the tenant first (design D5). + // The transaction rolled back whole and the secret was never stored, so the operator can + // send the request again, and the answer says so. + if ((error as { code?: unknown } | null)?.code === DEADLOCK_DETECTED) { + throw exomemErrors.serviceCredentialRetry(); + } + throw error; }); } diff --git a/src/lib/exomem-hosted/errors.ts b/src/lib/exomem-hosted/errors.ts index 88e5f2bd..836aed10 100644 --- a/src/lib/exomem-hosted/errors.ts +++ b/src/lib/exomem-hosted/errors.ts @@ -178,6 +178,17 @@ export const exomemErrors = { status: 409, message: "no eligible tenant matches this selector", }), + // The database failed this request's transaction to break a lock cycle (design D5). The + // transaction rolled back whole, so sending the request again is safe. + serviceCredentialRetry: () => + new ExomemHostedError({ + code: "SERVICE_CREDENTIAL_RETRY", + status: 503, + message: "the request met a concurrent change; send it again", + retryable: true, + retryAfterMs: 3000, + remediation: "retry_later", + }), } as const; export function safeErrorEnvelope(error: unknown, requestId?: string): ExomemHostedErrorEnvelope { diff --git a/src/lib/exomem-hosted/issuance-maintenance.ts b/src/lib/exomem-hosted/issuance-maintenance.ts new file mode 100644 index 00000000..5fd338b9 --- /dev/null +++ b/src/lib/exomem-hosted/issuance-maintenance.ts @@ -0,0 +1,42 @@ +import { executeExomemSql as sql } from "./db"; + +// The job drains idle backlog and rows that issuance skipped because of locks. +const TICKET_BATCH = 1000; + +export type IssuancePruneResult = { + /** Records the log's prune function deleted, or null when the call failed. */ + records: number | null; + /** Expired download ticket rows deleted, or null when the delete failed. */ + tickets: number | null; +}; + +/** + * Retention for the issuance log and the download ticket rows. The log's own + * prune function holds the 90-day rule and its batch size, and deletes as the + * schema owner, because the web app's role holds nothing on the log. Each part + * is isolated: a failed part is reported as null, never as zero. + */ +export async function pruneIssuanceState(): Promise { + let records: number | null = null; + try { + const { rows } = + await sql`/* exomem:prune-issuance-log */ SELECT exomem_prune_issuance_log() AS deleted`; + records = Number(rows[0]?.deleted); + } catch { + console.error("exomem-issuance: log retention failed"); + } + let tickets: number | null = null; + try { + const deleted = await sql` + /* exomem:prune-download-tickets */ + DELETE FROM exomem_cloud_download_tickets + WHERE id IN ( + SELECT id FROM exomem_cloud_download_tickets + WHERE expires_at <= now() ORDER BY expires_at LIMIT ${TICKET_BATCH} + )`; + tickets = deleted.rowCount ?? 0; + } catch { + console.error("exomem-issuance: download ticket retention failed"); + } + return { records, tickets }; +} diff --git a/src/lib/exomem-hosted/operator-observability.ts b/src/lib/exomem-hosted/operator-observability.ts index 5fdc3a68..18b98960 100644 --- a/src/lib/exomem-hosted/operator-observability.ts +++ b/src/lib/exomem-hosted/operator-observability.ts @@ -35,5 +35,10 @@ export function operatorControlErrorResponse(error: unknown, requestId: string) errorCode: reported instanceof ExomemHostedError ? reported.code : "INTERNAL_ERROR", variables, }); - return safeErrorResponse(reported, requestId); + const response = safeErrorResponse(reported, requestId); + // The header counts whole seconds. An error that names a delay sends it as the header too. + if (reported instanceof ExomemHostedError && reported.retryAfterMs) { + response.headers.set("retry-after", String(Math.ceil(reported.retryAfterMs / 1000))); + } + return response; }