Files
0pt/src/services/source-rate-policy-service.ts
T
Simon AxelssonandClaude Sonnet 5 dc6aaa0e10
CI (SIAX Cloud) / quality (push) Successful in 51s
Security Scan (SIAX Cloud) / security (push) Successful in 26s
CI (SIAX Cloud) / security (push) Successful in 28s
CI (SIAX Cloud) / integration (push) Successful in 1m1s
CI (SIAX Cloud) / integration (pull_request) Successful in 30s
CI (SIAX Cloud) / security (pull_request) Successful in 24s
CI (SIAX Cloud) / quality (pull_request) Successful in 48s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 22s
fix(data-os): P014 — close tenant-isolation + idempotency gaps, execute real restore drill
Tenant isolation (security-critical): every app/api/0pt/** route reading
tenant_id from client-controlled query/body never cross-checked it against
the token middleware.ts already verified (x-0pt-verified-tenant). Adds a
shared assertTenantMatchesVerified guard and wires it into all 20+ affected
routes. Also closes two full-leak-by-omission bugs found in this pass
(documents/capture and lakehouse/mappings GETs returned every tenant's rows
when tenant_id was simply omitted) and two "no tenant check at all" reads
(rate-policies/[id], lakehouse/mappings/[id]) reachable by ID alone.

Duplicate-delivery idempotency (correctness-critical): POST /api/orders now
honors Idempotency-Key (sql/006, replay-or-409-on-conflict, Postgres +
in-memory); the Python orchestrator's POST /orders/{id}/run — the actual
delivery trigger — is now idempotent under an asyncio lock, closing a real
concurrent-request race, not just the sequential-retry case.

Engine-duplication resolution: adaptive_router.py's docstring wrongly
invited a bypass ("see b0ts for scraping") contradicting the product's own
compliance stance; corrected, and given real (additive, not escalating)
block-signal tracking so a rate-limited/blocked source is excluded from the
plan instead of hammered. Also fixes a previously-undiscovered production
bug: the Python engine's only call into the TS quality bridge
(X-Internal-Token) was unconditionally 401'd by middleware.ts, which never
checked that credential — the advisory quality bridge was unreachable in any
environment enforcing auth.

Restore drill: executed for real against throwaway Docker Postgres
containers (not simulated). Found and fixed two real blockers along the way:
sql/004 referenced opt_datasets, which no migration ever created (chain was
never actually runnable end to end); lib/db.ts hardcoded ssl:"require",
making any non-TLS Postgres (incl. compose.dev.yaml's own local-dev
container) unreachable. After both fixes: full migration chain applies
cleanly, pg_dump/pg_restore round-trip is byte-identical (row counts +
content checksums), and real application code (lib/orders-store.ts,
SourceRegistryService's Postgres repository) reads the restored data back
correctly, including cross-tenant isolation still holding.

82 new tests (55 TS + 27 Python), all passing; full existing suite (291 TS +
55 Python) still green; typecheck clean on every changed/added file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-03 12:00:43 +02:00

157 lines
6.1 KiB
TypeScript

import type {
SourceRatePolicy,
SourceRatePolicyStatus,
CreateSourceRatePolicyInput,
} from "../types/source-rate-policy";
import { createAud0Client, type Aud0Client } from "../clients/aud0-client";
import { SourceService } from "./source-service";
interface SourceRatePolicyRecord {
source_rate_policy_id: string;
tenant_id: string;
project_id: string;
source_id: string;
rate_limit_per_minute: number;
crawl_budget: number;
compliance_notes: string | null;
domain: string | null;
robots_ok: boolean | null;
access: string | null;
status: string;
correlation_id: string | null;
created_at: string;
updated_at: string | null;
created_by: string | null;
}
/**
* Owns 0pt.source_rate_policy.schema.v1 -- the genuine ownership repair:
* source/crawl-domain rate limiting is 0pt's own compliance policy, moved
* OUT of N0D's ComputePolicy.sourceRatePolicy (deprecated there per
* ADR-0030's audit). See docs/ICEBERG_WRITE_BOUNDARY.md.
*/
export class SourceRatePolicyService {
private policies: Map<string, SourceRatePolicyRecord> = new Map();
private aud0: Aud0Client;
private sourceService: SourceService;
constructor(opts?: { aud0BaseUrl?: string; sourceService?: SourceService }) {
this.aud0 = createAud0Client(opts?.aud0BaseUrl);
this.sourceService = opts?.sourceService ?? new SourceService({ aud0BaseUrl: opts?.aud0BaseUrl });
}
async createSourceRatePolicy(input: CreateSourceRatePolicyInput): Promise<SourceRatePolicy> {
if (this.policies.has(input.source_rate_policy_id)) {
throw new Error(`Source rate policy ${input.source_rate_policy_id} already exists`);
}
if (input.rate_limit_per_minute <= 0) {
throw new Error("rate_limit_per_minute must be > 0");
}
if (input.crawl_budget <= 0) {
throw new Error("crawl_budget must be > 0");
}
// Verify the source exists -- a rate policy with no source is meaningless.
try {
await this.sourceService.getSource(input.source_id);
} catch {
throw new Error(`Source ${input.source_id} not found`);
}
const now = new Date().toISOString();
const record: SourceRatePolicyRecord = {
source_rate_policy_id: input.source_rate_policy_id,
tenant_id: input.tenant_id,
project_id: input.project_id,
source_id: input.source_id,
rate_limit_per_minute: input.rate_limit_per_minute,
crawl_budget: input.crawl_budget,
compliance_notes: input.compliance_notes ?? null,
domain: input.domain ?? null,
robots_ok: input.robots_ok ?? null,
access: input.access ?? null,
status: input.status ?? "active",
correlation_id: input.correlation_id ?? null,
created_at: now,
updated_at: null,
created_by: input.created_by ?? null,
};
this.policies.set(input.source_rate_policy_id, record);
// 0pt.source_rate_policy_created -- docs/11-lakehouse-write-plan.md event list,
// docs/ICEBERG_WRITE_BOUNDARY.md. Gives AUD0/CL0UD an evented trail of 0pt's
// crawl-compliance posture without polling 0pt's DB.
await this.aud0.ingestEvent({
event_id: `evt_0pt_source_rate_policy_created_${input.source_rate_policy_id}`,
event_type: "0pt.source_rate_policy_created",
tenant_id: input.tenant_id,
project_id: input.project_id,
actor_id: input.created_by ?? "system",
app_id: "0pt",
capability_id: "0pt.create_source_rate_policy",
resource_type: "source_rate_policy",
resource_id: input.source_rate_policy_id,
risk_level: "L2",
payload: {
source_id: input.source_id,
rate_limit_per_minute: input.rate_limit_per_minute,
crawl_budget: input.crawl_budget,
},
created_at: now,
correlation_id: input.correlation_id ?? "",
});
return this.toPolicy(record);
}
// P014: `tenantId` is optional so existing internal callers that already
// resolved a policy from a tenant-scoped list (or are trusted, in-process
// callers) are unaffected — but the HTTP route now always passes it, which
// closes a real gap: this lookup used to be reachable by rate-policy ID
// alone with NO tenant check anywhere, so any authenticated caller could
// read another tenant's crawl-budget/rate-limit/compliance-notes record
// just by guessing or enumerating IDs. A mismatched tenantId is reported
// identically to "not found" (no existence oracle), matching the
// convention SourceRegistryService.assertSourceTenant already established.
async getSourceRatePolicy(sourceRatePolicyId: string, tenantId?: string): Promise<SourceRatePolicy> {
const record = this.policies.get(sourceRatePolicyId);
if (!record || (tenantId && record.tenant_id !== tenantId)) {
throw new Error(`Source rate policy ${sourceRatePolicyId} not found`);
}
return this.toPolicy(record);
}
async listSourceRatePolicies(filter?: {
tenant_id?: string;
project_id?: string;
source_id?: string;
status?: SourceRatePolicyStatus;
}): Promise<SourceRatePolicy[]> {
let results = Array.from(this.policies.values());
if (filter?.tenant_id) results = results.filter((r) => r.tenant_id === filter.tenant_id);
if (filter?.project_id) results = results.filter((r) => r.project_id === filter.project_id);
if (filter?.source_id) results = results.filter((r) => r.source_id === filter.source_id);
if (filter?.status) results = results.filter((r) => r.status === filter.status);
return results.map((r) => this.toPolicy(r));
}
private toPolicy(r: SourceRatePolicyRecord): SourceRatePolicy {
return {
source_rate_policy_id: r.source_rate_policy_id,
tenant_id: r.tenant_id,
project_id: r.project_id,
source_id: r.source_id,
rate_limit_per_minute: r.rate_limit_per_minute,
crawl_budget: r.crawl_budget,
compliance_notes: r.compliance_notes ?? undefined,
domain: r.domain ?? undefined,
robots_ok: r.robots_ok ?? undefined,
access: (r.access as SourceRatePolicy["access"]) ?? undefined,
status: r.status as SourceRatePolicyStatus,
correlation_id: r.correlation_id ?? undefined,
created_at: r.created_at,
updated_at: r.updated_at ?? undefined,
created_by: r.created_by ?? undefined,
};
}
}