-
Notifications
You must be signed in to change notification settings - Fork 0
fix: harden durable job submission #20
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
EstandarMustaq
wants to merge
4
commits into
main
Choose a base branch
from
agent/rfc2-review-hardening
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
c447bfd
fix: harden durable job submission
EstandarMustaq 57c1d19
test: isolate durable job submissions
EstandarMustaq fb32270
fix: validate workbench OpenAPI references
EstandarMustaq 6772d4b
ci: align coordinated legacy connector branches
EstandarMustaq File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
104 changes: 104 additions & 0 deletions
104
prisma/migrations/20260718000100_durable_job_submission_receipts/migration.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| CREATE SCHEMA IF NOT EXISTS workbench; | ||
|
|
||
| DO $$ | ||
| BEGIN | ||
| IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'workbench_app') THEN | ||
| CREATE ROLE workbench_app NOLOGIN; | ||
| END IF; | ||
| IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'workbench_maintenance') THEN | ||
| CREATE ROLE workbench_maintenance NOLOGIN; | ||
| END IF; | ||
| ALTER ROLE workbench_app NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; | ||
| ALTER ROLE workbench_maintenance NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; | ||
| END | ||
| $$; | ||
|
|
||
| GRANT USAGE ON SCHEMA workbench TO workbench_app, workbench_maintenance; | ||
|
|
||
| CREATE TABLE workbench.job_submission_receipts ( | ||
| id text PRIMARY KEY, | ||
| "tenantId" text NOT NULL, | ||
| operation text NOT NULL CHECK (operation = 'create-job'), | ||
| "keyDigest" text NOT NULL CHECK ("keyDigest" ~ '^[a-f0-9]{64}$'), | ||
| "requestHash" text NOT NULL CHECK ("requestHash" ~ '^[a-f0-9]{64}$'), | ||
| "jobId" text NOT NULL, | ||
| "correlationId" text NOT NULL, | ||
| "actorId" text NOT NULL, | ||
| state text NOT NULL CHECK (state IN ('PENDING','COMPLETED')), | ||
| "httpStatus" integer CHECK ("httpStatus" BETWEEN 200 AND 299), | ||
| "responseBody" jsonb, | ||
| "completedAt" timestamp(3), | ||
| "expiresAt" timestamp(3) NOT NULL, | ||
| "createdAt" timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
| "updatedAt" timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
| UNIQUE ("tenantId", operation, "keyDigest"), | ||
| UNIQUE ("tenantId", "jobId"), | ||
| CHECK ( | ||
| (state = 'PENDING' AND "httpStatus" IS NULL AND "responseBody" IS NULL AND "completedAt" IS NULL) | ||
| OR | ||
| (state = 'COMPLETED' AND "httpStatus" IS NOT NULL AND "responseBody" IS NOT NULL AND "completedAt" IS NOT NULL) | ||
| ) | ||
| ); | ||
| CREATE INDEX job_submission_receipts_expires_idx ON workbench.job_submission_receipts("expiresAt"); | ||
| CREATE INDEX job_submission_receipts_tenant_created_idx ON workbench.job_submission_receipts("tenantId", "createdAt"); | ||
|
|
||
| CREATE OR REPLACE FUNCTION workbench.current_tenant_id() | ||
| RETURNS text LANGUAGE sql STABLE | ||
| AS $$ SELECT NULLIF(current_setting('app.current_tenant_id', true), '') $$; | ||
| REVOKE ALL ON FUNCTION workbench.current_tenant_id() FROM PUBLIC; | ||
| GRANT EXECUTE ON FUNCTION workbench.current_tenant_id() TO workbench_app; | ||
|
|
||
| ALTER TABLE workbench.job_submission_receipts ENABLE ROW LEVEL SECURITY; | ||
| ALTER TABLE workbench.job_submission_receipts FORCE ROW LEVEL SECURITY; | ||
| CREATE POLICY tenant_isolation ON workbench.job_submission_receipts TO workbench_app | ||
| USING ("tenantId" = workbench.current_tenant_id()) | ||
| WITH CHECK ("tenantId" = workbench.current_tenant_id()); | ||
| CREATE POLICY maintenance_access ON workbench.job_submission_receipts TO workbench_maintenance | ||
| USING (true) WITH CHECK (true); | ||
|
|
||
| GRANT SELECT, INSERT ON workbench.job_submission_receipts TO workbench_app; | ||
| GRANT UPDATE (state, "httpStatus", "responseBody", "completedAt", "updatedAt") | ||
| ON workbench.job_submission_receipts TO workbench_app; | ||
| GRANT SELECT, DELETE ON workbench.job_submission_receipts TO workbench_maintenance; | ||
|
|
||
| CREATE OR REPLACE FUNCTION workbench.delete_expired_job_submission_receipt( | ||
| tenant_id text, receipt_operation text, key_digest text | ||
| ) RETURNS integer | ||
| LANGUAGE plpgsql SECURITY DEFINER | ||
| SET search_path = pg_catalog, workbench | ||
| AS $$ | ||
| DECLARE deleted_count integer; | ||
| BEGIN | ||
| DELETE FROM workbench.job_submission_receipts | ||
| WHERE "tenantId" = tenant_id AND operation = receipt_operation | ||
| AND "keyDigest" = key_digest AND "expiresAt" <= now(); | ||
| GET DIAGNOSTICS deleted_count = ROW_COUNT; | ||
| RETURN deleted_count; | ||
| END | ||
| $$; | ||
|
|
||
| CREATE OR REPLACE FUNCTION workbench.cleanup_expired_job_submission_receipts(batch_limit integer) | ||
| RETURNS integer | ||
| LANGUAGE plpgsql SECURITY DEFINER | ||
| SET search_path = pg_catalog, workbench | ||
| AS $$ | ||
| DECLARE deleted_count integer; | ||
| BEGIN | ||
| WITH expired AS ( | ||
| SELECT id FROM workbench.job_submission_receipts | ||
| WHERE "expiresAt" <= now() ORDER BY "expiresAt" LIMIT batch_limit | ||
| FOR UPDATE SKIP LOCKED | ||
| ) | ||
| DELETE FROM workbench.job_submission_receipts receipt | ||
| USING expired WHERE receipt.id = expired.id; | ||
| GET DIAGNOSTICS deleted_count = ROW_COUNT; | ||
| RETURN deleted_count; | ||
| END | ||
| $$; | ||
|
|
||
| ALTER FUNCTION workbench.delete_expired_job_submission_receipt(text, text, text) OWNER TO workbench_maintenance; | ||
| ALTER FUNCTION workbench.cleanup_expired_job_submission_receipts(integer) OWNER TO workbench_maintenance; | ||
| REVOKE ALL ON FUNCTION workbench.delete_expired_job_submission_receipt(text, text, text) FROM PUBLIC; | ||
| REVOKE ALL ON FUNCTION workbench.cleanup_expired_job_submission_receipts(integer) FROM PUBLIC; | ||
| GRANT EXECUTE ON FUNCTION workbench.delete_expired_job_submission_receipt(text, text, text) TO workbench_app; | ||
| GRANT EXECUTE ON FUNCTION workbench.cleanup_expired_job_submission_receipts(integer) TO workbench_app; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| provider = "postgresql" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| datasource db { | ||
| provider = "postgresql" | ||
| url = env("DATABASE_URL") | ||
| } | ||
|
|
||
| model JobSubmissionReceipt { | ||
| id String @id | ||
| tenantId String | ||
| operation String | ||
| keyDigest String | ||
| requestHash String | ||
| jobId String | ||
| correlationId String | ||
| actorId String | ||
| state String | ||
| httpStatus Int? | ||
| responseBody Json? | ||
| completedAt DateTime? | ||
| expiresAt DateTime | ||
| createdAt DateTime @default(now()) | ||
| updatedAt DateTime @default(now()) @updatedAt | ||
|
|
||
| @@unique([tenantId, operation, keyDigest]) | ||
| @@unique([tenantId, jobId]) | ||
| @@index([expiresAt]) | ||
| @@index([tenantId, createdAt]) | ||
| @@map("job_submission_receipts") | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| #!/usr/bin/env node | ||
| import pg from 'pg'; | ||
|
|
||
| const databaseUrl = required('WORKBENCH_MIGRATION_DATABASE_URL'); | ||
| const password = required('WORKBENCH_DATABASE_ROLE_PASSWORD'); | ||
| if (password.length < 16 || password.startsWith('REPLACE_WITH_')) { | ||
| throw new Error('WORKBENCH_DATABASE_ROLE_PASSWORD must be a non-placeholder secret of at least 16 characters'); | ||
| } | ||
| const pool = new pg.Pool({ connectionString: withoutSchema(databaseUrl) }); | ||
| try { | ||
| await pool.query(`ALTER ROLE workbench_app WITH LOGIN PASSWORD '${password.replaceAll("'", "''")}'`); | ||
| const { rows } = await pool.query( | ||
| 'SELECT rolcanlogin, rolsuper, rolcreatedb, rolcreaterole, rolinherit, rolbypassrls FROM pg_roles WHERE rolname = $1', | ||
| ['workbench_app'], | ||
| ); | ||
| const role = rows[0]; | ||
| if (!role?.rolcanlogin || role.rolsuper || role.rolcreatedb || role.rolcreaterole || role.rolinherit || role.rolbypassrls) { | ||
| throw new Error('workbench_app role attributes do not satisfy the runtime policy'); | ||
| } | ||
| } finally { | ||
| await pool.end(); | ||
| } | ||
|
|
||
| function required(name) { | ||
| const value = process.env[name]?.trim(); | ||
| if (!value) throw new Error(`${name} is required`); | ||
| return value; | ||
| } | ||
|
|
||
| function withoutSchema(value) { | ||
| const url = new URL(value); | ||
| url.searchParams.delete('schema'); | ||
| return url.toString(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; | ||
| import { createHash, timingSafeEqual } from 'node:crypto'; | ||
| import { getRuntimeConfig } from '../utils/runtime-config'; | ||
|
|
||
| @Injectable() | ||
| export class MetricsTokenGuard implements CanActivate { | ||
| private readonly expected = getRuntimeConfig().metricsToken; | ||
|
|
||
| canActivate(context: ExecutionContext): boolean { | ||
| if (!this.expected) { | ||
| throw new UnauthorizedException('Metrics scrape token is not configured'); | ||
| } | ||
| const authorization = context.switchToHttp().getRequest().headers.authorization; | ||
| if (typeof authorization !== 'string' || !authorization.startsWith('Bearer ')) { | ||
| throw new UnauthorizedException('Metrics scrape token is required'); | ||
| } | ||
| const expectedDigest = createHash('sha256').update(this.expected).digest(); | ||
| const suppliedDigest = createHash('sha256').update(authorization.slice(7)).digest(); | ||
| if (!timingSafeEqual(expectedDigest, suppliedDigest)) { | ||
| throw new UnauthorizedException('Invalid metrics scrape token'); | ||
| } | ||
| return true; | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
With the new environment split,
.env.exampleno longer definesDATABASE_URLand instead documentsWORKBENCH_MIGRATION_DATABASE_URLfor privileged migrations, but this datasource still reads onlyDATABASE_URL. In deployments following the new contract,pnpm prisma:migratewill fail before creating the workbench schema/roles, or it will accidentally run with a runtime URL if an oldDATABASE_URLremains. Point the Prisma datasource/script atWORKBENCH_MIGRATION_DATABASE_URLor explicitly bridge it in the migrate command.Useful? React with 👍 / 👎.