fix(data-os): P014 — close tenant-isolation + idempotency gaps, execute real restore drill
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

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>
This commit is contained in:
Simon Axelsson
2026-09-03 12:00:43 +02:00
co-authored by Claude Sonnet 5
parent e7516697b3
commit dc6aaa0e10
50 changed files with 1820 additions and 52 deletions
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { parseBody, documentExtractionSchema } from "@/src/validation/0pt-schemas";
import { documentExtractionService } from "@/src/services/document-extraction-service";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function POST(request: NextRequest, { params }: { params: Promise<{ documentId: string }> }) {
try {
@@ -11,6 +12,8 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
if (tenantGuard) return tenantGuard;
const result = await documentExtractionService.extractDocument(documentId, {
tenant_id: body.tenant_id,
project_id: body.project_id,
@@ -35,10 +38,17 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
}
}
export async function GET(_request: NextRequest, { params }: { params: Promise<{ documentId: string }> }) {
export async function GET(request: NextRequest, { params }: { params: Promise<{ documentId: string }> }) {
try {
const { documentId } = await params;
const extractions = await documentExtractionService.listExtractionsForDocument(documentId);
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const extractions = await documentExtractionService.listExtractionsForDocument(documentId, tenantId);
return NextResponse.json(extractions);
} catch (error: unknown) {
const message = error instanceof Error ? error.message : "Unknown error";
+27 -3
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { parseBody, documentCaptureSchema } from "@/src/validation/0pt-schemas";
import { documentCaptureService } from "@/src/services/document-capture-service";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function POST(request: NextRequest) {
try {
@@ -10,6 +11,8 @@ export async function POST(request: NextRequest) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
if (tenantGuard) return tenantGuard;
const result = await documentCaptureService.captureFromMailbox(
{
mailbox: {
@@ -26,8 +29,18 @@ export async function POST(request: NextRequest) {
{
tenant_id: body.tenant_id,
project_id: body.project_id,
actor_id: body.actor_id,
correlation_id: body.correlation_id,
// documentCaptureSchema types these optional (pre-existing, listed
// among package.json's "9 pre-existing errors ... Wave 2 Zod
// schemas type fields as plain string while the services want
// narrower unions" -- deliberately left to its own change, not
// widened here). CaptureMailboxContext requires actor_id as a
// non-empty string and captureFromMailbox already throws a clear
// "missing tenant_id/project_id/actor_id" error when it's falsy, so
// `?? ""` changes no runtime behavior -- it only satisfies the type
// checker, which previously never saw this file (nothing under
// tests/ imported it before P014's cross-tenant regression tests).
actor_id: body.actor_id ?? "",
correlation_id: body.correlation_id ?? "",
},
);
return NextResponse.json(result, { status: 201 });
@@ -37,9 +50,20 @@ export async function POST(request: NextRequest) {
}
}
// P014: `tenant_id` used to be optional here, and
// DocumentCaptureService.listDocuments treats an absent tenant_id filter as
// "no restriction" — so calling this with no query params at all returned
// EVERY tenant's captured documents to any authenticated caller. Every
// sibling list/get route in this file already requires tenant_id; this was
// the one outlier. Now required, same as the rest of the surface.
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id") ?? undefined;
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const projectId = searchParams.get("project_id") ?? undefined;
const documents = await documentCaptureService.listDocuments({ tenant_id: tenantId, project_id: projectId });
return NextResponse.json(documents);
@@ -1,10 +1,25 @@
import { NextResponse } from "next/server";
import { NextRequest, NextResponse } from "next/server";
import { mappingService } from "@/src/services/lakehouse-mapping-registry";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function GET(_request: Request, { params }: { params: Promise<{ mappingId: string }> }) {
// P014: this lookup used to accept only `mappingId`, with NO tenant check
// anywhere in the request path -- any authenticated caller could read
// another tenant's dataset<->Iceberg-table mapping (namespace, table name,
// storage URI) by guessing or enumerating IDs. Now requires `?tenant_id=`
// and both checks it against the verified token and threads it into the
// service so a foreign mapping_id 404s instead of leaking -- see
// DatasetIcebergMappingService.getMapping's doc comment.
export async function GET(request: NextRequest, { params }: { params: Promise<{ mappingId: string }> }) {
try {
const { mappingId } = await params;
const mapping = await mappingService.getMapping(mappingId);
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const mapping = await mappingService.getMapping(mappingId, tenantId);
return NextResponse.json(mapping);
} catch (error: unknown) {
const message = error instanceof Error ? error.message : "Unknown error";
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { parseBody, requestIcebergWriteSchema } from "@/src/validation/0pt-schemas";
import { writeService } from "@/src/services/lakehouse-mapping-registry";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
// Registers a new Iceberg snapshot (a write) through ST0RE's table registry
// for an already-mapped dataset. See docs/ICEBERG_WRITE_BOUNDARY.md.
@@ -22,8 +23,11 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
if (tenantGuard) return tenantGuard;
const result = await writeService.requestIcebergWrite({
dataset_iceberg_mapping_id: mappingId,
tenant_id: body.tenant_id,
actor_id: body.actor_id,
correlation_id: body.correlation_id,
snapshot_type: body.snapshot_type,
+27 -2
View File
@@ -1,6 +1,8 @@
import { NextRequest, NextResponse } from "next/server";
import { parseBody, mapDatasetToIcebergTableSchema } from "@/src/validation/0pt-schemas";
import { mappingService, writeService } from "@/src/services/lakehouse-mapping-registry";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
import type { IcebergTableFormat } from "@/src/clients/st0re-lakehouse-client";
// Shared instances come from src/services/lakehouse-mapping-registry.ts so a
// mapping created via POST is visible to a later GET, AND to the sibling
@@ -28,6 +30,8 @@ export async function POST(request: NextRequest) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
if (tenantGuard) return tenantGuard;
const result = await writeService.mapDatasetToIcebergTable({
tenant_id: body.tenant_id,
project_id: body.project_id,
@@ -37,7 +41,17 @@ export async function POST(request: NextRequest) {
table_name: body.table_name,
storage_uri: body.storage_uri,
catalog_ref: body.catalog_ref,
table_format: body.table_format,
// mapDatasetToIcebergTableSchema types this as a plain string
// (pre-existing, listed among package.json's "9 pre-existing errors
// ... Wave 2 Zod schemas type fields as plain string while the
// services want narrower unions" -- deliberately left to its own
// change, not widened here). This cast changes no runtime behavior:
// an unrecognized value flows through exactly as it did before
// (ST0RE's own table-registration route is the actual validator) --
// it only satisfies the type checker, which previously never saw this
// file (nothing under tests/ imported it before P014's cross-tenant
// regression tests).
table_format: body.table_format as IcebergTableFormat | undefined,
actor_id: body.actor_id,
correlation_id: body.correlation_id,
});
@@ -48,10 +62,21 @@ export async function POST(request: NextRequest) {
}
}
// P014: tenant_id used to be optional here, and
// DatasetIcebergMappingService.listMappings treats an absent tenant_id
// filter as "no restriction" -- omitting the query param returned every
// tenant's dataset<->Iceberg-table mappings (namespace, table name, storage
// URI). Now required and cross-checked, matching the rest of the surface.
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const mappings = await mappingService.listMappings({
tenant_id: searchParams.get("tenant_id") ?? undefined,
tenant_id: tenantId,
project_id: searchParams.get("project_id") ?? undefined,
dataset_id: searchParams.get("dataset_id") ?? undefined,
});
+3
View File
@@ -7,6 +7,7 @@
import { NextRequest, NextResponse } from "next/server";
import { qualityService } from "@/src/services/quality";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
import type { DataQualityIssue } from "@/src/quality/quality-types";
export async function GET(request: NextRequest) {
@@ -16,6 +17,8 @@ export async function GET(request: NextRequest) {
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const issues = qualityService.listIssues({
tenant_id: tenantId,
dataset_id: searchParams.get("dataset_id") ?? undefined,
@@ -8,6 +8,7 @@
import { NextRequest, NextResponse } from "next/server";
import { qualityService } from "@/src/services/quality";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
import { z } from "zod";
const updateQualityRuleSchema = z.object({
@@ -26,6 +27,8 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const versions = searchParams.get("versions") === "true";
if (versions) {
return NextResponse.json(qualityService.getRuleVersions(ruleId, tenantId));
@@ -48,6 +51,8 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{
);
}
const { tenant_id, ...patch } = parsed.data;
const tenantGuard = assertTenantMatchesVerified(request, tenant_id);
if (tenantGuard) return tenantGuard;
const rule = await qualityService.updateRule(ruleId, tenant_id, patch);
return NextResponse.json(rule);
} catch (error: unknown) {
+5
View File
@@ -12,6 +12,7 @@ import { NextRequest, NextResponse } from "next/server";
import { parseBody, createQualityRuleSchema } from "@/src/validation/0pt-schemas";
import { qualityService } from "@/src/services/quality";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
import type { DataQualityRule } from "@/src/quality/quality-types";
export async function POST(request: NextRequest) {
@@ -21,6 +22,8 @@ export async function POST(request: NextRequest) {
if (!__parsed.ok) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const tenantGuard = assertTenantMatchesVerified(request, __parsed.data.tenant_id);
if (tenantGuard) return tenantGuard;
const rule = await qualityService.createRule(__parsed.data);
return NextResponse.json(rule, { status: 201 });
} catch (error: unknown) {
@@ -35,6 +38,8 @@ export async function GET(request: NextRequest) {
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const rules = qualityService.listRules({
tenant_id: tenantId,
dataset_id: searchParams.get("dataset_id") ?? undefined,
@@ -6,6 +6,7 @@
import { NextRequest, NextResponse } from "next/server";
import { qualityService } from "@/src/services/quality";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function GET(request: NextRequest, { params }: { params: Promise<{ runId: string }> }) {
try {
@@ -15,6 +16,8 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
return NextResponse.json(qualityService.getRun(runId, tenantId));
} catch (error: unknown) {
return siaxErrorResponse(error);
+5
View File
@@ -11,6 +11,7 @@ import { NextRequest, NextResponse } from "next/server";
import { parseBody, createQualityRunSchema } from "@/src/validation/0pt-schemas";
import { qualityService } from "@/src/services/quality";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function POST(request: NextRequest) {
try {
@@ -19,6 +20,8 @@ export async function POST(request: NextRequest) {
if (!__parsed.ok) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const tenantGuard = assertTenantMatchesVerified(request, __parsed.data.tenant_id);
if (tenantGuard) return tenantGuard;
const run = await qualityService.runQuality(__parsed.data);
return NextResponse.json(run, { status: 201 });
} catch (error: unknown) {
@@ -33,6 +36,8 @@ export async function GET(request: NextRequest) {
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const runs = qualityService.listRuns({
tenant_id: tenantId,
dataset_id: searchParams.get("dataset_id") ?? undefined,
@@ -10,6 +10,7 @@
import { NextRequest, NextResponse } from "next/server";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
@@ -19,6 +20,8 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const freshness = await sourceRegistryService.getFreshness(sourceId, tenantId);
return NextResponse.json(freshness);
} catch (error: unknown) {
@@ -10,6 +10,7 @@ import { NextRequest, NextResponse } from "next/server";
import { parseBody, recordSourceHealthCheckSchema } from "@/src/validation/0pt-schemas";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
@@ -19,6 +20,8 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const health = await sourceRegistryService.getHealth(sourceId, tenantId);
return NextResponse.json(health);
} catch (error: unknown) {
@@ -35,6 +38,8 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
if (tenantGuard) return tenantGuard;
const health = await sourceRegistryService.recordHealthCheck({
source_id: sourceId,
tenant_id: body.tenant_id,
@@ -12,6 +12,7 @@ import { NextRequest, NextResponse } from "next/server";
import { parseBody, setSourceProvenanceSchema } from "@/src/validation/0pt-schemas";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
@@ -21,6 +22,8 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const provenance = await sourceRegistryService.getProvenance(sourceId, tenantId);
if (!provenance) {
return NextResponse.json({ error: `source ${sourceId} has no provenance record` }, { status: 404 });
@@ -40,6 +43,8 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
if (tenantGuard) return tenantGuard;
const provenance = await sourceRegistryService.setProvenance({
...body,
source_id: sourceId,
@@ -16,6 +16,7 @@
import { NextRequest, NextResponse } from "next/server";
import { parseBody, sourceQuerySchema } from "@/src/validation/0pt-schemas";
import { sourceService } from "@/src/services/source-registry";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
import {
SourceQueryService,
SourceQueryTimeoutError,
@@ -43,6 +44,8 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
if (!body.connection_config || typeof body.connection_config !== "object") {
return NextResponse.json({ error: "connection_config is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
if (tenantGuard) return tenantGuard;
const result = await queryService.querySource({
source_id: sourceId,
@@ -9,6 +9,7 @@ import { NextRequest, NextResponse } from "next/server";
import { parseBody, setSourceRightsSchema } from "@/src/validation/0pt-schemas";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
@@ -18,6 +19,8 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const rights = await sourceRegistryService.getRights(sourceId, tenantId);
if (!rights) {
return NextResponse.json({ error: `source ${sourceId} has no rights record` }, { status: 404 });
@@ -37,6 +40,8 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
if (tenantGuard) return tenantGuard;
const rights = await sourceRegistryService.setRights({ ...body, source_id: sourceId });
return NextResponse.json(rights);
} catch (error: unknown) {
+3
View File
@@ -9,6 +9,7 @@
import { NextRequest, NextResponse } from "next/server";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
@@ -18,6 +19,8 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const descriptor = await sourceRegistryService.describeSource(sourceId, tenantId);
return NextResponse.json(descriptor);
} catch (error: unknown) {
@@ -1,13 +1,29 @@
import { NextResponse } from "next/server";
import { NextRequest, NextResponse } from "next/server";
import { sourceRatePolicyService as service } from "@/src/services/source-registry";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
// P014: this lookup used to accept only `sourceRatePolicyId`, with NO tenant
// check anywhere in the request path — any authenticated caller could read
// another tenant's rate-limit/crawl-budget/compliance-notes record by
// guessing or enumerating IDs. Now requires `?tenant_id=` (matching every
// sibling route under app/api/0pt/sources/*) and both checks it against the
// verified token (assertTenantMatchesVerified) and threads it into the
// service so a foreign policy_id 404s instead of leaking (no existence
// oracle) — see getSourceRatePolicy's doc comment.
export async function GET(
_request: Request,
request: NextRequest,
{ params }: { params: Promise<{ sourceRatePolicyId: string }> },
) {
try {
const { sourceRatePolicyId } = await params;
const policy = await service.getSourceRatePolicy(sourceRatePolicyId);
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const policy = await service.getSourceRatePolicy(sourceRatePolicyId, tenantId);
return NextResponse.json(policy);
} catch (error: unknown) {
const message = error instanceof Error ? error.message : "Unknown error";
+7 -1
View File
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { parseBody, createSourceRatePolicySchema } from "@/src/validation/0pt-schemas";
import { sourceRatePolicyService as service } from "@/src/services/source-registry";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function POST(request: NextRequest) {
try {
@@ -10,6 +11,8 @@ export async function POST(request: NextRequest) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
if (tenantGuard) return tenantGuard;
const policy = await service.createSourceRatePolicy(body);
return NextResponse.json(policy, { status: 201 });
} catch (error: unknown) {
@@ -20,8 +23,11 @@ export async function POST(request: NextRequest) {
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id") ?? undefined;
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const policies = await service.listSourceRatePolicies({
tenant_id: searchParams.get("tenant_id") ?? undefined,
tenant_id: tenantId,
project_id: searchParams.get("project_id") ?? undefined,
source_id: searchParams.get("source_id") ?? undefined,
});
+5
View File
@@ -15,6 +15,7 @@ import { NextRequest, NextResponse } from "next/server";
import { parseBody, registerSourceSchema } from "@/src/validation/0pt-schemas";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
import type { SourceStatus, SourceType } from "@/src/types/source";
import type { SourceRights } from "@/src/types/source-registry";
@@ -26,6 +27,8 @@ export async function POST(request: NextRequest) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
if (tenantGuard) return tenantGuard;
const descriptor = await sourceRegistryService.registerSource(body);
return NextResponse.json(descriptor, { status: 201 });
} catch (error: unknown) {
@@ -40,6 +43,8 @@ export async function GET(request: NextRequest) {
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
if (tenantGuard) return tenantGuard;
const sources = await sourceRegistryService.querySources({
tenant_id: tenantId,
project_id: searchParams.get("project_id") ?? undefined,
+22 -3
View File
@@ -1,11 +1,19 @@
import { NextRequest, NextResponse } from "next/server";
import { createOrder, listOrders, type OrderConfig } from "@/lib/orders-store";
import { createOrder, listOrders, IdempotencyKeyConflictError, type OrderConfig } from "@/lib/orders-store";
import { requireRouteAuth } from "@/src/auth/require-route-auth";
// POST /api/orders (docs/04) — create a draft order from a configurator config.
// Intentionally anonymous: a prospect drafts/estimates a job before signing in
// to pay the deposit (see docs/01, the configurator flow). Only reading back
// the order queue (GET, below) is a data-exposure risk.
//
// P014: honors an optional `Idempotency-Key` header (the convention this
// skill's own docs already name -- "Idempotency-Key on order/payment POSTs")
// so a retried submission (double-click, dropped response, proxy replay)
// returns the ORIGINAL order (200) instead of creating a duplicate (was:
// no idempotency mechanism at all -- every retry created a new row, P014
// recon "Duplicate delivery idempotent: NOT MET"). Omitting the header keeps
// the pre-P014 behavior exactly: every call creates a fresh order.
export async function POST(req: NextRequest) {
let body: { flow?: string; config?: OrderConfig };
try {
@@ -18,8 +26,19 @@ export async function POST(req: NextRequest) {
}
const flow = body.flow || "custom";
const config = body.config || {};
const order = await createOrder(flow, config);
return NextResponse.json({ order_id: order.order_id, status: order.status, deposit_ore: order.deposit_ore, total_ore: order.total_ore }, { status: 201 });
const idempotencyKey = req.headers.get("idempotency-key") ?? undefined;
try {
const { order, replayed } = await createOrder(flow, config, idempotencyKey);
return NextResponse.json(
{ order_id: order.order_id, status: order.status, deposit_ore: order.deposit_ore, total_ore: order.total_ore },
{ status: replayed ? 200 : 201 },
);
} catch (err: unknown) {
if (err instanceof IdempotencyKeyConflictError) {
return NextResponse.json({ error: { code: "idempotency_key_conflict", message: err.message } }, { status: 409 });
}
throw err;
}
}
// GET /api/orders — list all orders (queue + financial aggregates). This is