P014: close tenant-isolation + idempotency gaps, execute real restore drill #29
@@ -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";
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
+20
-4
@@ -6,10 +6,26 @@
|
||||
# not a copy of the full VPS stack (no NocoDB/Metabase/Caddy/worker here,
|
||||
# those are production concerns, not local dev needs).
|
||||
#
|
||||
# UNVERIFIED (2026-08-11): written and reviewed, but not smoke-tested end to
|
||||
# end in this pass -- no Docker daemon was available in the environment this
|
||||
# was authored in. Verify with `docker compose -f compose.dev.yaml up` before
|
||||
# relying on it.
|
||||
# VERIFIED (P014, 2026-09-03): this file's image/credentials/init-mount shape
|
||||
# was exercised for real (an equivalent standalone container -- this sandbox
|
||||
# had an unrelated service already bound to host port 5432, so the literal
|
||||
# `docker compose -f compose.dev.yaml up` command itself could not be run
|
||||
# here, but the identical image + `sql/*.sql` init sequence + connection
|
||||
# shape were run and verified end to end as part of P014's restore drill).
|
||||
# That drill surfaced and fixed the ACTUAL reason this was unverifiable
|
||||
# before: `lib/db.ts`'s `getSql()` hardcoded `ssl: "require"`, which this
|
||||
# plain-Postgres container can never satisfy (no TLS is configured here) --
|
||||
# every connection attempt failed before a single query ran. Fixed: `ssl` now
|
||||
# defaults to "require" (unchanged for every real deployment) but honors
|
||||
# `DATABASE_SSL=false` to opt out. To use this container from the app or a
|
||||
# script, set BOTH:
|
||||
# DATABASE_URL=postgresql://opt:opt-dev-only-not-a-secret@localhost:5432/opt
|
||||
# DATABASE_SSL=false
|
||||
# `sql/003_datasets.sql` (also added by P014, closing a separate gap where
|
||||
# `004_iceberg_write_boundary.sql` referenced a table no migration defined)
|
||||
# is picked up by the `docker-entrypoint-initdb.d` mount automatically --
|
||||
# Postgres runs `*.sql` in this directory in filename-sorted order, and the
|
||||
# zero-padded 00N prefixes already sort correctly.
|
||||
services:
|
||||
db:
|
||||
image: pgvector/pgvector:pg16
|
||||
|
||||
@@ -1,17 +1,76 @@
|
||||
# Runbook: Backup & Restore — 0pt
|
||||
|
||||
> Status 2026-08-10: **ingen databas i produktion** (`/api/health` →
|
||||
> `db: not_configured`); allt state är in-memory (försvinner vid kallstart).
|
||||
> Denna runbook beskriver läget idag + målbilden när Postgres provisioneras.
|
||||
> Status 2026-08-10 (still true as of this P014 pass, not independently
|
||||
> re-verified against a live deployment): **ingen databas i produktion**
|
||||
> (`/api/health` → `db: not_configured`); allt state är in-memory (försvinner
|
||||
> vid kallstart). Denna runbook beskriver läget idag + målbilden när Postgres
|
||||
> provisioneras. **Vad SOM ändrades i P014**: migreringskedjan
|
||||
> (`sql/001` → `006`) gick tidigare inte att köra alls end-to-end mot en
|
||||
> tom databas (se "P014 restore-övning" nedan) — det är nu fixat och
|
||||
> verifierat, oberoende av om produktion faktiskt har `DATABASE_URL` satt.
|
||||
|
||||
## Nuläge
|
||||
|
||||
- Ingen backup behövs/sker idag — det finns inget att backa upp (in-memory).
|
||||
- `sql/001_init.sql` är schemat (13 tabeller + pgvector/pgcrypto).
|
||||
- `sql/002_source_registry.sql` — Source Registry-tabellerna.
|
||||
- `sql/003_datasets.sql` (P014) — `opt_datasets`, tidigare saknad helt (se nedan).
|
||||
- `sql/004/005` är iceberg-bärande tabeller.
|
||||
- `sql/006_orders_idempotency.sql` (P014) — `orders.idempotency_key` + unikt index.
|
||||
- **Kända blockerare:** estate-som-helhet saknar offsite-backup (Hetzner
|
||||
Robot-creds). Denna repo kan inte lösa det enskilt.
|
||||
|
||||
## P014 restore-övning: EXEKVERAD 2026-09-03 (verklig, mätt, inte prosa)
|
||||
|
||||
Körd mot verklig, engångs, isolerad infrastruktur (Docker, `pgvector/pgvector:pg16`
|
||||
— samma image som `compose.dev.yaml`/`infra/docker-compose.yml`) — inte simulerad.
|
||||
Ingen produktionsdata, inga persistenta artefakter kvarlämnade.
|
||||
|
||||
**Steg 1 — upptäckt: migreringskedjan gick inte att köra.** Att faktiskt köra
|
||||
`sql/001` → `002` → `004` → `005` (den ordning `docs/03`/denna runbooks egna
|
||||
"Målbild" beskriver, och exakt vad en riktig restore-övning måste göra) mot en
|
||||
tom databas misslyckades: `004_iceberg_write_boundary.sql` refererar
|
||||
`opt_datasets`, en tabell ingen `sql/`-fil någonsin definierade. Filens egen
|
||||
kommentar hade redan flaggat detta ("Flagging, not fixing here... remains
|
||||
open") men ingen hade tidigare faktiskt kört kedjan för att bekräfta felet.
|
||||
**Fixat**: `sql/003_datasets.sql` tillagd (matchar
|
||||
`src/services/dataset-service.ts`s `DatasetRecord`-form exakt, inte en
|
||||
gissning) — kedjan `001→002→003→004→005→006` kör nu rent mot en tom databas.
|
||||
|
||||
**Steg 2 — upptäckt: `lib/db.ts` kunde aldrig ansluta till en icke-TLS
|
||||
Postgres.** `getSql()` hårdkodade `ssl: "require"` ovillkorligt — vilket gjorde
|
||||
att `compose.dev.yaml`s egen lokala Postgres-container (ingen TLS)
|
||||
ALDRIG hade kunnat nås via denna funktion, konsekvent med den filens egen
|
||||
"UNVERIFIED... not smoke-tested"-flagga. **Fixat**: `DATABASE_SSL=false` är
|
||||
nu ett explicit opt-out (standard oförändrad — `"require"` — för varje verklig
|
||||
driftsättning).
|
||||
|
||||
**Steg 3 — själva övningen, mätt:**
|
||||
|
||||
| Steg | Resultat |
|
||||
|---|---|
|
||||
| Käll-container (`p014-restore-source`, `pgvector/pgvector:pg16`, engångs) | frisk efter 1s |
|
||||
| Migreringar `001`→`006` applicerade | rent, 0 fel (efter fix ovan) |
|
||||
| Data seedad (verkliga tabellrader, inte platshållare) | 1 org, 2 orders (varav en med `idempotency_key`), 1 `opt_sources`-post + `rights`/`provenance`/`health`, 1 `opt_datasets`, 1 `opt_dataset_iceberg_mappings`, 1 `opt_source_rate_policies` |
|
||||
| `pg_dump -Fc` | 0,123 s, 48 835 bytes, sha256 loggad |
|
||||
| Frisk, TOM mål-container (`p014-restore-target`, separat engångsinstans) | frisk efter ~3s |
|
||||
| `pg_restore --no-owner --no-privileges` | 0,284 s, 0 fel |
|
||||
| Radantal källa vs. mål, samtliga 9 tabeller | **identiska** |
|
||||
| `md5`-checksumma på hela `orders`-tabellens innehåll (källa vs. mål) | **identisk** (`95f7d0f9…`) |
|
||||
| `md5`-checksumma på hela `opt_sources`-tabellens innehåll (källa vs. mål) | **identisk** (`b4612dbf…`) |
|
||||
| Verklig applikationskod mot den RESTORERADE databasen: `lib/orders-store.ts` (`getOrder`, `findOrderByIdempotencyKey`) | läser tillbaka exakt rätt `config`/`total_ore`/`est_confidence`/idempotency-nyckel |
|
||||
| Verklig applikationskod mot den RESTORERADE databasen: `SourceRegistryService` (riktigt Postgres-repository, `src/repositories/postgres-source-registry-repository.ts`) | `describeSource` returnerar korrekt `name`/`rights.license_id`/`provenance.method`/`health.status`; tvärtenant-isolering (`NOT_FOUND`, ingen existence-oracle) håller fortfarande mot den restorerade databasen |
|
||||
|
||||
Slutsats: en klon av denna schema+data-modell kan verkligen provisioneras,
|
||||
backas upp och återställas end-to-end idag — det kunde den INTE innan denna
|
||||
övning (migreringskedjan var trasig). Engångscontainrarna revs efter
|
||||
övningen; ingen data eller infrastruktur kvarlämnad.
|
||||
|
||||
**Kvarstående, inte löst av denna övning:** produktionens faktiska
|
||||
backup-schema/retention/offsite-kopia (se "Målbild" nedan — fortfarande
|
||||
målbild, inte verifierad mot en live driftsättning i denna pass) och
|
||||
Hetzner-blockeraren för estate-bred offsite-backup.
|
||||
|
||||
## Målbild (när `DATABASE_URL` satts)
|
||||
|
||||
### Daglig backup (P2-1 i BACKLOG)
|
||||
|
||||
@@ -13,11 +13,30 @@ export function hasDb(): boolean {
|
||||
return Boolean(dbUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* P014 fix: `ssl` used to be hardcoded to `"require"` unconditionally. That
|
||||
* is the right default for every REAL deployment target this app has
|
||||
* (Vercel Postgres, managed Postgres providers), but it made `compose.dev.yaml`'s
|
||||
* local Postgres container -- which speaks plain, non-TLS Postgres -- and
|
||||
* ANY other throwaway/local Postgres (e.g. a restore-drill target) silently
|
||||
* unreachable via this function, contradicting that file's own doc comment
|
||||
* ("local-only Postgres for developers who want real persistence") and its
|
||||
* own "UNVERIFIED... not smoke-tested end to end" caveat -- this is
|
||||
* precisely why it was never smoke-tested: it could not have worked.
|
||||
* `DATABASE_SSL` is opt-in-to-disable ONLY; absence (the default, matching
|
||||
* every existing deployment's actual env) keeps the exact prior behavior.
|
||||
*/
|
||||
export function sslMode(): "require" | false {
|
||||
const raw = process.env.DATABASE_SSL?.trim().toLowerCase();
|
||||
if (raw === "false" || raw === "disable" || raw === "off" || raw === "0") return false;
|
||||
return "require";
|
||||
}
|
||||
|
||||
export function getSql() {
|
||||
const url = dbUrl();
|
||||
if (!url) return null;
|
||||
if (!_sql) {
|
||||
_sql = postgres(url, { prepare: false, idle_timeout: 20, max: 5, ssl: "require" });
|
||||
_sql = postgres(url, { prepare: false, idle_timeout: 20, max: 5, ssl: sslMode() });
|
||||
}
|
||||
return _sql;
|
||||
}
|
||||
|
||||
+97
-12
@@ -29,6 +29,45 @@ export interface Order {
|
||||
|
||||
// Non-durable fallback used only until a database is provisioned.
|
||||
const mem = new Map<string, Order>();
|
||||
// idempotency_key -> order_id, mirroring the Postgres unique index added by
|
||||
// sql/006_orders_idempotency.sql for the in-memory fallback path.
|
||||
const memIdempotencyIndex = new Map<string, string>();
|
||||
|
||||
/**
|
||||
* Thrown by {@link createOrder} when a caller reuses an `Idempotency-Key`
|
||||
* for a semantically different request (different `flow` and/or `config`)
|
||||
* than the one that key was first used with. A route handler should map
|
||||
* this to HTTP 409 -- silently returning either order would be wrong (the
|
||||
* caller asked for the SAME operation to be safely retried, not for two
|
||||
* different operations to collapse into one).
|
||||
*/
|
||||
export class IdempotencyKeyConflictError extends Error {
|
||||
constructor(public readonly idempotencyKey: string) {
|
||||
super(`Idempotency-Key "${idempotencyKey}" was already used to create a different order (different flow/config)`);
|
||||
this.name = "IdempotencyKeyConflictError";
|
||||
}
|
||||
}
|
||||
|
||||
/** Postgres error code 23505 = unique_violation (postgres.js surfaces it as `.code`). */
|
||||
function isUniqueViolation(err: unknown): boolean {
|
||||
return typeof err === "object" && err !== null && (err as { code?: unknown }).code === "23505";
|
||||
}
|
||||
|
||||
function sameSubmission(a: Order, flow: string, config: OrderConfig): boolean {
|
||||
return a.flow === flow && JSON.stringify(a.config) === JSON.stringify(config);
|
||||
}
|
||||
|
||||
export async function findOrderByIdempotencyKey(key: string): Promise<Order | null> {
|
||||
const sql = getSql();
|
||||
if (sql) {
|
||||
const rows = await sql<Order[]>`
|
||||
SELECT order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
|
||||
FROM orders WHERE idempotency_key = ${key} LIMIT 1`;
|
||||
return rows[0] ? coerceOrder(rows[0]) : null;
|
||||
}
|
||||
const id = memIdempotencyIndex.get(key);
|
||||
return id ? mem.get(id) ?? null : null;
|
||||
}
|
||||
|
||||
// postgres.js (pinned v3.4.9) returns bigint (total_ore/deposit_ore/balance_ore)
|
||||
// and numeric (est_confidence) columns as strings by default, not JS numbers.
|
||||
@@ -58,21 +97,66 @@ function estimateFor(config: OrderConfig) {
|
||||
});
|
||||
}
|
||||
|
||||
export async function createOrder(flow: string, config: OrderConfig): Promise<Order> {
|
||||
export interface CreateOrderResult {
|
||||
order: Order;
|
||||
/** True when this call returned a PRE-EXISTING order (a safe retry under the same Idempotency-Key), not a newly created one. */
|
||||
replayed: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* P014: `idempotencyKey` is optional -- a caller that omits it (or the
|
||||
* pre-P014 call shape) behaves exactly as before, creating a fresh row every
|
||||
* call. When supplied (the `Idempotency-Key` header convention, see
|
||||
* sql/006_orders_idempotency.sql), a retry with the SAME key returns the
|
||||
* original order unchanged (`replayed: true`) instead of creating a
|
||||
* duplicate; a retry with the same key but a DIFFERENT flow/config throws
|
||||
* {@link IdempotencyKeyConflictError} rather than silently picking one.
|
||||
*
|
||||
* The Postgres path checks-then-inserts, which has a real (if narrow) race
|
||||
* window between two concurrent requests carrying the same fresh key -- the
|
||||
* UNIQUE INDEX from sql/006 is the actual source of truth, and a
|
||||
* unique-violation on INSERT is caught and re-resolved the same way a
|
||||
* pre-existing row would be, rather than surfacing a raw DB error.
|
||||
*/
|
||||
export async function createOrder(flow: string, config: OrderConfig, idempotencyKey?: string): Promise<CreateOrderResult> {
|
||||
const key = idempotencyKey?.trim() || undefined;
|
||||
if (key) {
|
||||
const existing = await findOrderByIdempotencyKey(key);
|
||||
if (existing) {
|
||||
if (sameSubmission(existing, flow, config)) return { order: existing, replayed: true };
|
||||
throw new IdempotencyKeyConflictError(key);
|
||||
}
|
||||
}
|
||||
|
||||
const est = estimateFor(config);
|
||||
const sql = getSql();
|
||||
if (sql) {
|
||||
const [row] = await sql<{ order_id: string; created_at: string }[]>`
|
||||
INSERT INTO orders (flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence)
|
||||
VALUES (${flow}, 'draft', ${sql.json(config as Parameters<typeof sql.json>[0])}, ${est.price * 100}, ${est.deposit * 100},
|
||||
${est.remainder * 100}, ${est.timelineDays}, ${est.estConfidence / 100})
|
||||
RETURNING order_id, created_at`;
|
||||
return {
|
||||
order_id: row.order_id, flow, status: "draft", config,
|
||||
total_ore: est.price * 100, deposit_ore: est.deposit * 100, balance_ore: est.remainder * 100,
|
||||
est_days: est.timelineDays, est_confidence: est.estConfidence / 100, created_at: row.created_at,
|
||||
};
|
||||
try {
|
||||
const [row] = await sql<{ order_id: string; created_at: string }[]>`
|
||||
INSERT INTO orders (flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, idempotency_key)
|
||||
VALUES (${flow}, 'draft', ${sql.json(config as Parameters<typeof sql.json>[0])}, ${est.price * 100}, ${est.deposit * 100},
|
||||
${est.remainder * 100}, ${est.timelineDays}, ${est.estConfidence / 100}, ${key ?? null})
|
||||
RETURNING order_id, created_at`;
|
||||
return {
|
||||
order: {
|
||||
order_id: row.order_id, flow, status: "draft", config,
|
||||
total_ore: est.price * 100, deposit_ore: est.deposit * 100, balance_ore: est.remainder * 100,
|
||||
est_days: est.timelineDays, est_confidence: est.estConfidence / 100, created_at: row.created_at,
|
||||
},
|
||||
replayed: false,
|
||||
};
|
||||
} catch (err) {
|
||||
if (key && isUniqueViolation(err)) {
|
||||
const raced = await findOrderByIdempotencyKey(key);
|
||||
if (raced) {
|
||||
if (sameSubmission(raced, flow, config)) return { order: raced, replayed: true };
|
||||
throw new IdempotencyKeyConflictError(key);
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const id = (globalThis.crypto?.randomUUID?.() ?? `SX-${Math.floor(1000 + Math.random() * 9000)}`);
|
||||
const order: Order = {
|
||||
order_id: id, flow, status: "draft", config,
|
||||
@@ -80,7 +164,8 @@ export async function createOrder(flow: string, config: OrderConfig): Promise<Or
|
||||
est_days: est.timelineDays, est_confidence: est.estConfidence / 100, created_at: new Date().toISOString(),
|
||||
};
|
||||
mem.set(id, order);
|
||||
return order;
|
||||
if (key) memIdempotencyIndex.set(key, id);
|
||||
return { order, replayed: false };
|
||||
}
|
||||
|
||||
export async function getOrder(id: string): Promise<Order | null> {
|
||||
|
||||
@@ -23,10 +23,25 @@
|
||||
* FIX (2026-08-31): matcher now covers BOTH /api/0pt (exact) and /api/0pt/:path*
|
||||
* to close the gap where a bare GET /api/0pt (no trailing path) was routed around
|
||||
* the middleware on Vercel's Edge runtime.
|
||||
*
|
||||
* FIX (P014): one route under this matcher, /api/0pt/quality/bridge-run, is
|
||||
* not called by a customer's Zitadel-authenticated session at all -- it is
|
||||
* called BY the Python engine (services/api/workers/quality_bridge.py) using
|
||||
* the pre-existing X-Internal-Token shared-secret convention, never a Bearer
|
||||
* token. Before this fix, that meant middleware always rejected the engine's
|
||||
* real call with 401 (see src/auth/internal-token.ts's doc comment for the
|
||||
* full story) -- the quality bridge was permanently unreachable in any
|
||||
* environment enforcing auth. INTERNAL_ONLY_ROUTES lets a request to that
|
||||
* ONE path through on a verified X-Internal-Token instead of a Bearer token;
|
||||
* every other /api/0pt/* route is untouched and still requires the normal
|
||||
* Zitadel flow below. A request to that route WITHOUT a valid internal token
|
||||
* still falls through to the ordinary Bearer check (e.g. an operator testing
|
||||
* it manually with their own token), it is not a blanket bypass.
|
||||
*/
|
||||
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { assertAuthConfigSafe, resolveAuthContext } from '@/src/auth/context';
|
||||
import { verifyInternalServiceToken } from '@/src/auth/internal-token';
|
||||
|
||||
// STARTUP GATE: fail to boot rather than serve /api/0pt/* openly in production.
|
||||
assertAuthConfigSafe();
|
||||
@@ -43,6 +58,9 @@ const EXEMPT_PATTERNS: RegExp[] = [
|
||||
/^\/api\/admin\/metrics(\/|$)/,
|
||||
];
|
||||
|
||||
/** The one 0pt route reached by a service (the Python engine), not a user session. */
|
||||
const INTERNAL_ONLY_ROUTES: RegExp[] = [/^\/api\/0pt\/quality\/bridge-run$/];
|
||||
|
||||
// Module-level diagnostics counter — first 5 auth requests in a process lifetime
|
||||
// log their outcome so the production auth gap (S1) can be traced to root cause.
|
||||
let _authDiagCount = 0;
|
||||
@@ -53,6 +71,16 @@ export async function middleware(req: NextRequest): Promise<NextResponse> {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
if (INTERNAL_ONLY_ROUTES.some((re) => re.test(path)) && verifyInternalServiceToken(req.headers)) {
|
||||
// Machine-to-machine call, verified via the shared X-Internal-Token
|
||||
// secret rather than a user's Bearer token. Deliberately does NOT set
|
||||
// x-0pt-verified-* headers -- there is no per-user principal here, and
|
||||
// the route requires+validates tenant_id from its own request body
|
||||
// (qualityBridgeRunSchema), which is the actual tenant the engine is
|
||||
// running the order for.
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
if (_authDiagCount < 5) {
|
||||
_authDiagCount += 1;
|
||||
const hasAuth = !!req.headers.get('authorization');
|
||||
|
||||
@@ -6,6 +6,7 @@ is the customer-facing edge; this service runs the actual pipeline.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
@@ -76,6 +77,21 @@ def compute_estimate(b: EstimateIn) -> dict[str, Any]:
|
||||
# ── in-memory store (swapped for asyncpg when DATABASE_URL is set) ───────────
|
||||
_ORDERS: dict[str, dict[str, Any]] = {}
|
||||
_JOBS: dict[str, dict[str, Any]] = {}
|
||||
# P014: one asyncio.Lock per order_id, held for the duration of a /run call.
|
||||
# Process-local only (matches the honest in-memory-store limitation this file
|
||||
# already documents), but closes the actual race a bare `if oid in _JOBS`
|
||||
# check would leave open: two /run requests for the same order_id arriving
|
||||
# back to back both await run_job() before either has stored a result, so a
|
||||
# read-then-write check alone would let both through. See `run()` below.
|
||||
_JOB_LOCKS: dict[str, asyncio.Lock] = {}
|
||||
|
||||
|
||||
def _lock_for(oid: str) -> asyncio.Lock:
|
||||
lock = _JOB_LOCKS.get(oid)
|
||||
if lock is None:
|
||||
lock = asyncio.Lock()
|
||||
_JOB_LOCKS[oid] = lock
|
||||
return lock
|
||||
|
||||
|
||||
class OrderIn(BaseModel):
|
||||
@@ -164,12 +180,31 @@ async def set_status(oid: str, body: StatusIn):
|
||||
|
||||
@app.post("/orders/{oid}/run")
|
||||
async def run(oid: str):
|
||||
"""
|
||||
P014: idempotent delivery. An order should be fulfilled/delivered ONCE.
|
||||
Before this fix, calling this endpoint twice for the same order_id (a
|
||||
retried request, a duplicate trigger, an operator double-click) re-ran
|
||||
the full compliant sourcing pipeline a second time and silently
|
||||
overwrote `_JOBS[oid]` with a second, independently-produced result --
|
||||
a genuinely different delivery (a second live fetch against upstream
|
||||
registries, a second QA pass with its own confidence draws), completely
|
||||
indistinguishable from the first at the API surface. This is the actual
|
||||
"duplicate delivery" gap P014's recon flagged as NOT MET: nothing
|
||||
downstream of order creation was idempotent at all. A job already
|
||||
recorded for this order_id is now returned unchanged; `run_job` is never
|
||||
invoked twice for the same order in this process's lifetime. The lock
|
||||
(see `_lock_for` above) closes the race between two requests arriving
|
||||
concurrently, not just sequential retries.
|
||||
"""
|
||||
o = _ORDERS.get(oid)
|
||||
if not o:
|
||||
raise HTTPException(404, "order saknas")
|
||||
o["status"] = "in_production"
|
||||
_JOBS[oid] = await run_job(oid, o["config"])
|
||||
o["status"] = "review"
|
||||
async with _lock_for(oid):
|
||||
if oid in _JOBS:
|
||||
return _JOBS[oid]
|
||||
o["status"] = "in_production"
|
||||
_JOBS[oid] = await run_job(oid, o["config"])
|
||||
o["status"] = "review"
|
||||
return _JOBS[oid]
|
||||
|
||||
|
||||
|
||||
@@ -49,6 +49,38 @@ CONNECTOR_VERSIONS: dict[str, str] = {
|
||||
|
||||
PRODUCER = "0pt-engine"
|
||||
|
||||
# P014: statuses a compliant source uses to signal "stop asking me this way"
|
||||
# (rate-limited, forbidden, or a legal/geo block) rather than "this record
|
||||
# doesn't exist". Collapsing these into an ordinary None (as every connector
|
||||
# did before this pass) is not itself a compliance violation -- nothing here
|
||||
# ever escalates to a bypass -- but it silently discarded a real signal:
|
||||
# adaptive_router.py had no way to know a source had just told it to back
|
||||
# off, so nothing could avoid hammering a rate-limited endpoint on the very
|
||||
# next record. See SourceBlockedError and adaptive_router.record_blocked.
|
||||
BLOCKED_STATUSES = frozenset({401, 403, 429, 451})
|
||||
|
||||
|
||||
class SourceBlockedError(Exception):
|
||||
"""
|
||||
Raised by a connector when the source responds with one of
|
||||
BLOCKED_STATUSES. This is informational, never an instruction to retry
|
||||
harder or escalate -- callers (pipeline.py's _fetch loop) catch it only
|
||||
to record the block via adaptive_router.record_blocked and move on to
|
||||
the next compliant source in the plan, exactly as they already would for
|
||||
a plain None. Compliance stance (CLAUDE.md §1) is unchanged: a block is
|
||||
always a stop signal for THAT source, never a cue to bypass it.
|
||||
"""
|
||||
|
||||
def __init__(self, source_id: str, status_code: int):
|
||||
self.source_id = source_id
|
||||
self.status_code = status_code
|
||||
super().__init__(f"{source_id} signaled a block (HTTP {status_code})")
|
||||
|
||||
|
||||
def _raise_if_blocked(source_id: str, response: httpx.Response) -> None:
|
||||
if response.status_code in BLOCKED_STATUSES:
|
||||
raise SourceBlockedError(source_id, response.status_code)
|
||||
|
||||
|
||||
def _client() -> httpx.AsyncClient:
|
||||
return httpx.AsyncClient(
|
||||
@@ -117,6 +149,7 @@ async def gleif_by_lei(lei: str) -> CompanyResult | None:
|
||||
url = f"https://api.gleif.org/api/v1/lei-records/{lei}"
|
||||
async with _client() as c:
|
||||
r = await c.get(url, headers={"Accept": "application/vnd.api+json"})
|
||||
_raise_if_blocked("gleif", r)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
a = (r.json().get("data") or {}).get("attributes") or {}
|
||||
@@ -142,6 +175,7 @@ async def brreg_by_orgnr(orgnr: str) -> CompanyResult | None:
|
||||
url = f"https://data.brreg.no/enhetsregisteret/api/enheter/{orgnr}"
|
||||
async with _client() as c:
|
||||
r = await c.get(url)
|
||||
_raise_if_blocked("brreg", r)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
d = r.json()
|
||||
@@ -170,6 +204,7 @@ async def companies_house_by_number(number: str) -> CompanyResult | None:
|
||||
url = f"https://api.company-information.service.gov.uk/company/{number}"
|
||||
async with _client() as c:
|
||||
r = await c.get(url, auth=(key, ""))
|
||||
_raise_if_blocked("companies_house", r)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
d = r.json()
|
||||
@@ -192,6 +227,7 @@ async def prh_by_businessid(business_id: str) -> CompanyResult | None:
|
||||
url = f"https://avoindata.prh.fi/opendata-ytj-api/v3/companies?businessId={business_id}"
|
||||
async with _client() as c:
|
||||
r = await c.get(url)
|
||||
_raise_if_blocked("prh", r)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
items = r.json().get("companies") or r.json().get("results") or []
|
||||
@@ -211,6 +247,7 @@ async def cvr_by_number(cvr: str) -> CompanyResult | None:
|
||||
url = f"https://cvrapi.dk/api?search={cvr}&country=dk"
|
||||
async with _client() as c:
|
||||
r = await c.get(url)
|
||||
_raise_if_blocked("cvr", r)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
d = r.json()
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
P014: adaptive_router.py previously had ZERO test coverage and a docstring
|
||||
("all methods, no compliance restrictions. See b0ts for scraping") that
|
||||
directly contradicted this product's own compliance stance and pointed at a
|
||||
forbidden, separate, non-compliant repo. This file tests the corrected
|
||||
version: plan_for_market's static per-market plan, and the new block-
|
||||
tracking (record_blocked/is_blocked/cooldown) that makes the engine actually
|
||||
back off a source that just told it to stop, instead of retrying it with no
|
||||
memory at all.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from workers.adaptive_router import AdaptiveRouter, MARKET_SOURCES, plan_for_market
|
||||
|
||||
|
||||
class TestPlanForMarket:
|
||||
def test_returns_the_full_static_plan_when_nothing_is_blocked(self):
|
||||
router = AdaptiveRouter()
|
||||
assert plan_for_market("GB", router=router) == MARKET_SOURCES["GB"]
|
||||
|
||||
def test_unknown_market_falls_back_to_gleif_only(self):
|
||||
router = AdaptiveRouter()
|
||||
assert plan_for_market("ZZ", router=router) == ["gleif"]
|
||||
|
||||
def test_defaults_to_the_process_wide_router_when_none_is_passed(self):
|
||||
# Just proves the call doesn't blow up and returns a real plan --
|
||||
# not asserting anything about global state here (other tests use
|
||||
# their own injected router precisely to avoid cross-test pollution
|
||||
# of the shared default_router).
|
||||
assert plan_for_market("FI") == MARKET_SOURCES["FI"]
|
||||
|
||||
|
||||
class TestBlockTracking:
|
||||
def test_a_freshly_blocked_source_is_excluded_from_the_plan(self):
|
||||
router = AdaptiveRouter()
|
||||
router.record_blocked("GB", "companies_house")
|
||||
plan = plan_for_market("GB", router=router)
|
||||
assert "companies_house" not in plan
|
||||
assert "gleif" in plan # only the blocked source is removed, not the whole market
|
||||
|
||||
def test_is_blocked_is_false_before_any_block_is_recorded(self):
|
||||
router = AdaptiveRouter()
|
||||
assert router.is_blocked("GB", "companies_house") is False
|
||||
|
||||
def test_blocking_is_scoped_per_market_not_global_to_the_source_id(self):
|
||||
# gleif appears in every market's plan -- blocking it for GB must not
|
||||
# silently remove it from FI/SE/etc too.
|
||||
router = AdaptiveRouter()
|
||||
router.record_blocked("GB", "gleif")
|
||||
assert "gleif" not in plan_for_market("GB", router=router)
|
||||
assert "gleif" in plan_for_market("FI", router=router)
|
||||
assert "gleif" in plan_for_market("SE", router=router)
|
||||
|
||||
def test_cooldown_expires_and_the_source_becomes_eligible_again(self):
|
||||
router = AdaptiveRouter(cooldown_seconds=60.0)
|
||||
router.record_blocked("GB", "companies_house", now=1000.0)
|
||||
assert router.is_blocked("GB", "companies_house", now=1030.0) is True # still within cooldown
|
||||
assert router.is_blocked("GB", "companies_house", now=1061.0) is False # cooldown elapsed
|
||||
# And the plan reflects that:
|
||||
assert "companies_house" in plan_for_market("GB", router=router)
|
||||
|
||||
def test_clear_forgets_every_recorded_block(self):
|
||||
router = AdaptiveRouter()
|
||||
router.record_blocked("GB", "companies_house")
|
||||
router.record_blocked("NO", "brreg")
|
||||
router.clear()
|
||||
assert plan_for_market("GB", router=router) == MARKET_SOURCES["GB"]
|
||||
assert plan_for_market("NO", router=router) == MARKET_SOURCES["NO"]
|
||||
|
||||
def test_two_router_instances_never_share_state(self):
|
||||
# Regression guard for a shared-mutable-default bug class: each
|
||||
# AdaptiveRouter() must own its own dict, not a class-level one.
|
||||
a = AdaptiveRouter()
|
||||
b = AdaptiveRouter()
|
||||
a.record_blocked("GB", "companies_house")
|
||||
assert a.is_blocked("GB", "companies_house") is True
|
||||
assert b.is_blocked("GB", "companies_house") is False
|
||||
@@ -0,0 +1,104 @@
|
||||
"""
|
||||
P014: every connector used by pipeline.py's adaptive plan (gleif, brreg,
|
||||
companies_house, prh, cvr) used to collapse EVERY non-200 response into a
|
||||
bare `None`, indistinguishable from "record genuinely doesn't exist". This
|
||||
tests that the block-status subset (401/403/429/451) now raises
|
||||
SourceBlockedError instead, while every other non-200 status (404, 500, ...)
|
||||
still returns None exactly as before -- this is an ADDITIVE signal, not a
|
||||
behavior change for the non-block case.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import respx
|
||||
|
||||
from sources.connectors import (
|
||||
SourceBlockedError,
|
||||
brreg_by_orgnr,
|
||||
companies_house_by_number,
|
||||
cvr_by_number,
|
||||
gleif_by_lei,
|
||||
prh_by_businessid,
|
||||
)
|
||||
|
||||
GLEIF_URL = "https://api.gleif.org/api/v1/lei-records/5493001KJTIIGC8Y1R12"
|
||||
BRREG_URL = "https://data.brreg.no/enhetsregisteret/api/enheter/923609016"
|
||||
COMPANIES_HOUSE_URL = "https://api.company-information.service.gov.uk/company/00000006"
|
||||
PRH_URL = "https://avoindata.prh.fi/opendata-ytj-api/v3/companies?businessId=2077474-0"
|
||||
CVR_URL = "https://cvrapi.dk/api?search=10150817&country=dk"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@respx.mock
|
||||
@pytest.mark.parametrize("status", [401, 403, 429, 451])
|
||||
async def test_gleif_raises_source_blocked_on_block_statuses(status):
|
||||
respx.get(GLEIF_URL).mock(return_value=httpx.Response(status, json={}))
|
||||
with pytest.raises(SourceBlockedError) as exc_info:
|
||||
await gleif_by_lei("5493001KJTIIGC8Y1R12")
|
||||
assert exc_info.value.source_id == "gleif"
|
||||
assert exc_info.value.status_code == status
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@respx.mock
|
||||
async def test_gleif_a_404_still_returns_none_not_blocked(monkeypatch):
|
||||
respx.get(GLEIF_URL).mock(return_value=httpx.Response(404, json={}))
|
||||
result = await gleif_by_lei("5493001KJTIIGC8Y1R12")
|
||||
assert result is None # unchanged pre-P014 behavior for a genuine "not found"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@respx.mock
|
||||
async def test_brreg_raises_source_blocked_on_429():
|
||||
respx.get(BRREG_URL).mock(return_value=httpx.Response(429, json={}))
|
||||
with pytest.raises(SourceBlockedError) as exc_info:
|
||||
await brreg_by_orgnr("923609016")
|
||||
assert exc_info.value.source_id == "brreg"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@respx.mock
|
||||
async def test_companies_house_raises_source_blocked_on_403(monkeypatch):
|
||||
monkeypatch.setenv("COMPANIES_HOUSE_API_KEY", "test-key")
|
||||
respx.get(COMPANIES_HOUSE_URL).mock(return_value=httpx.Response(403, json={}))
|
||||
with pytest.raises(SourceBlockedError) as exc_info:
|
||||
await companies_house_by_number("00000006")
|
||||
assert exc_info.value.source_id == "companies_house"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_companies_house_missing_key_still_delivers_honest_level_0_not_a_block():
|
||||
# No COMPANIES_HOUSE_API_KEY set -- this is a config gap, not a source
|
||||
# block, and must keep returning the honest "unavailable" result it
|
||||
# already did (never raise SourceBlockedError for a problem on OUR side).
|
||||
result = await companies_house_by_number("00000006")
|
||||
assert result is not None
|
||||
assert result.provenance[0].level == 0
|
||||
assert result.provenance[0].transform == "unavailable_no_key"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@respx.mock
|
||||
async def test_prh_raises_source_blocked_on_401():
|
||||
respx.get(PRH_URL).mock(return_value=httpx.Response(401, json={}))
|
||||
with pytest.raises(SourceBlockedError) as exc_info:
|
||||
await prh_by_businessid("2077474-0")
|
||||
assert exc_info.value.source_id == "prh"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@respx.mock
|
||||
async def test_cvr_raises_source_blocked_on_451():
|
||||
respx.get(CVR_URL).mock(return_value=httpx.Response(451, json={}))
|
||||
with pytest.raises(SourceBlockedError) as exc_info:
|
||||
await cvr_by_number("10150817")
|
||||
assert exc_info.value.source_id == "cvr"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@respx.mock
|
||||
async def test_cvr_a_500_still_returns_none_not_blocked():
|
||||
respx.get(CVR_URL).mock(return_value=httpx.Response(500, json={}))
|
||||
result = await cvr_by_number("10150817")
|
||||
assert result is None
|
||||
@@ -0,0 +1,112 @@
|
||||
"""
|
||||
P014: services/api/orchestrator/main.py had ZERO test coverage before this
|
||||
pass, and `POST /orders/{oid}/run` had no idempotency protection at all --
|
||||
calling it twice for the same order re-ran the full compliant sourcing
|
||||
pipeline a second time, silently overwriting `_JOBS[oid]` with a second,
|
||||
independently-produced delivery. This is the actual "duplicate delivery"
|
||||
gap P014's recon flagged NOT MET (nothing downstream of order creation was
|
||||
idempotent). These tests exercise the real ASGI app end to end (httpx
|
||||
ASGITransport, no mocked HTTP layer) and prove: a sequential retry returns
|
||||
the cached job without re-running the pipeline, a TRUE CONCURRENT race
|
||||
(two requests in flight at once) is also closed by the per-order asyncio
|
||||
lock, and an unknown order still 404s exactly as before.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from orchestrator.main import app
|
||||
|
||||
|
||||
def _fake_job_result(calls: list[str], order_id: str) -> dict:
|
||||
calls.append(order_id)
|
||||
return {
|
||||
"stage": "qa",
|
||||
"pct": 100,
|
||||
"state": "done",
|
||||
"metrics": {"rows": 1, "dropped_below_threshold": 0, "per_market": {"NO": 1}, "avg_confidence": 0.95},
|
||||
"records": [{"market": "NO", "name": "Test AS", "confidence": 0.95}],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sequential_retry_returns_cached_job_without_rerunning_pipeline(monkeypatch):
|
||||
calls: list[str] = []
|
||||
|
||||
async def fake_run_job(order_id: str, config: dict) -> dict:
|
||||
return _fake_job_result(calls, order_id)
|
||||
|
||||
monkeypatch.setattr("orchestrator.main.run_job", fake_run_job)
|
||||
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
created = await client.post("/orders", json={"flow": "custom", "config": {"markets": ["NO"]}})
|
||||
oid = created.json()["order_id"]
|
||||
|
||||
r1 = await client.post(f"/orders/{oid}/run")
|
||||
r2 = await client.post(f"/orders/{oid}/run")
|
||||
r3 = await client.post(f"/orders/{oid}/run")
|
||||
|
||||
assert r1.status_code == 200
|
||||
assert r1.json() == r2.json() == r3.json()
|
||||
assert calls == [oid] # run_job invoked exactly once across three /run calls
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_true_concurrent_race_still_invokes_run_job_exactly_once(monkeypatch):
|
||||
calls: list[str] = []
|
||||
|
||||
async def fake_run_job(order_id: str, config: dict) -> dict:
|
||||
# Widen the race window: both requests reach this await before
|
||||
# either has written to _JOBS, which is exactly the race a bare
|
||||
# `if oid in _JOBS` check (no lock) would lose.
|
||||
await asyncio.sleep(0.05)
|
||||
return _fake_job_result(calls, order_id)
|
||||
|
||||
monkeypatch.setattr("orchestrator.main.run_job", fake_run_job)
|
||||
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
created = await client.post("/orders", json={"flow": "custom", "config": {"markets": ["NO"]}})
|
||||
oid = created.json()["order_id"]
|
||||
|
||||
r1, r2 = await asyncio.gather(
|
||||
client.post(f"/orders/{oid}/run"),
|
||||
client.post(f"/orders/{oid}/run"),
|
||||
)
|
||||
|
||||
assert r1.status_code == 200 and r2.status_code == 200
|
||||
assert r1.json() == r2.json()
|
||||
assert calls == [oid] # THE regression this test guards: exactly one real pipeline run
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_on_unknown_order_still_404s():
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
res = await client.post("/orders/does-not-exist/run")
|
||||
assert res.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_different_orders_each_get_their_own_real_run(monkeypatch):
|
||||
calls: list[str] = []
|
||||
|
||||
async def fake_run_job(order_id: str, config: dict) -> dict:
|
||||
return _fake_job_result(calls, order_id)
|
||||
|
||||
monkeypatch.setattr("orchestrator.main.run_job", fake_run_job)
|
||||
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
o1 = (await client.post("/orders", json={"flow": "custom", "config": {"markets": ["NO"]}})).json()["order_id"]
|
||||
o2 = (await client.post("/orders", json={"flow": "custom", "config": {"markets": ["GB"]}})).json()["order_id"]
|
||||
|
||||
await client.post(f"/orders/{o1}/run")
|
||||
await client.post(f"/orders/{o2}/run")
|
||||
|
||||
# Idempotency is per-order, not global -- two distinct orders both really run.
|
||||
assert sorted(calls) == sorted([o1, o2])
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user