fix(recovery): restore source removed by production documentation merge
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* P014 regression: HTTP-level proof that every app/api/0pt/** route which
|
||||
* takes tenant_id from client-controlled input (query string or JSON body)
|
||||
* now rejects a request whose tenant_id disagrees with the tenant
|
||||
* middleware.ts already verified for the caller (forwarded as
|
||||
* `x-0pt-verified-tenant`). Before this pass, NONE of these routes checked
|
||||
* that header at all -- a valid token for tenant A could read or write
|
||||
* tenant B's sources, rate policies, quality rules, documents, or lakehouse
|
||||
* mappings simply by naming tenant_id=B in the request.
|
||||
*
|
||||
* These call the route handlers directly with a hand-built NextRequest that
|
||||
* carries `x-0pt-verified-tenant` -- exactly the shape middleware.ts hands
|
||||
* the route once a real Bearer token has been verified (see
|
||||
* tests/api/anonymous-routes-auth.test.ts for the same "call the handler
|
||||
* directly, simulate what upstream already established" pattern used for
|
||||
* the /api/orders and /api/admin/metrics fail-closed regressions).
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { POST as sourcesPOST, GET as sourcesGET } from "@/app/api/0pt/sources/route";
|
||||
import { GET as sourceDescribeGET } from "@/app/api/0pt/sources/[sourceId]/route";
|
||||
import { GET as ratePolicyGET } from "@/app/api/0pt/sources/rate-policies/[sourceRatePolicyId]/route";
|
||||
import { GET as mappingsListGET, POST as mappingsPOST } from "@/app/api/0pt/lakehouse/mappings/route";
|
||||
import { GET as mappingGetGET } from "@/app/api/0pt/lakehouse/mappings/[mappingId]/route";
|
||||
import { POST as qualityRulesPOST } from "@/app/api/0pt/quality/rules/route";
|
||||
import { GET as documentsGET } from "@/app/api/0pt/documents/capture/route";
|
||||
|
||||
const VERIFIED = "x-0pt-verified-tenant";
|
||||
|
||||
function getReq(url: string, verifiedTenant = "t_a"): NextRequest {
|
||||
return new NextRequest(new URL(url, "http://localhost"), { headers: { [VERIFIED]: verifiedTenant } });
|
||||
}
|
||||
function postReq(url: string, body: unknown, verifiedTenant = "t_a"): NextRequest {
|
||||
return new NextRequest(new URL(url, "http://localhost"), {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", [VERIFIED]: verifiedTenant },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
describe("cross-tenant HTTP regression: /api/0pt/sources", () => {
|
||||
it("POST rejects registering a source under a foreign tenant_id (403, never reaches the service)", async () => {
|
||||
const res = await sourcesPOST(
|
||||
postReq("/api/0pt/sources", {
|
||||
source_id: "src_attack_1",
|
||||
tenant_id: "t_victim",
|
||||
project_id: "p1",
|
||||
source_type: "api",
|
||||
name: "attacker-named source",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
const body = await res.json();
|
||||
expect(body.error).toBe("OPT_ACCESS_DENIED");
|
||||
});
|
||||
|
||||
it("POST succeeds when tenant_id matches the verified tenant", async () => {
|
||||
const res = await sourcesPOST(
|
||||
postReq("/api/0pt/sources", {
|
||||
source_id: "src_ok_1",
|
||||
tenant_id: "t_a",
|
||||
project_id: "p1",
|
||||
source_type: "api",
|
||||
name: "legit source",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
});
|
||||
|
||||
it("GET (list) rejects a foreign tenant_id query param (403)", async () => {
|
||||
const res = await sourcesGET(getReq("/api/0pt/sources?tenant_id=t_victim", "t_a"));
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("GET (list) succeeds when the query tenant_id matches", async () => {
|
||||
const res = await sourcesGET(getReq("/api/0pt/sources?tenant_id=t_a", "t_a"));
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cross-tenant HTTP regression: /api/0pt/sources/[sourceId]", () => {
|
||||
it("GET describe rejects a foreign tenant_id (403, before any existence check)", async () => {
|
||||
const res = await sourceDescribeGET(getReq("/api/0pt/sources/src_whatever?tenant_id=t_victim", "t_a"), {
|
||||
params: Promise.resolve({ sourceId: "src_whatever" }),
|
||||
});
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cross-tenant HTTP regression: /api/0pt/sources/rate-policies/[id]", () => {
|
||||
it("GET rejects a foreign tenant_id (403) -- this route had NO tenant check of any kind before P014", async () => {
|
||||
const res = await ratePolicyGET(getReq("/api/0pt/sources/rate-policies/srp_whatever?tenant_id=t_victim", "t_a"), {
|
||||
params: Promise.resolve({ sourceRatePolicyId: "srp_whatever" }),
|
||||
});
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("GET without tenant_id at all is a 400, not an unscoped read", async () => {
|
||||
const res = await ratePolicyGET(getReq("/api/0pt/sources/rate-policies/srp_whatever", "t_a"), {
|
||||
params: Promise.resolve({ sourceRatePolicyId: "srp_whatever" }),
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cross-tenant HTTP regression: /api/0pt/lakehouse/mappings", () => {
|
||||
it("POST rejects mapping a dataset under a foreign tenant_id (403)", async () => {
|
||||
const res = await mappingsPOST(
|
||||
postReq(
|
||||
"/api/0pt/lakehouse/mappings",
|
||||
{
|
||||
tenant_id: "t_victim",
|
||||
project_id: "p1",
|
||||
dataset_id: "ds_1",
|
||||
dataset_iceberg_mapping_id: "dim_attack_1",
|
||||
namespace: "ns",
|
||||
table_name: "tbl",
|
||||
storage_uri: "s3://x/y",
|
||||
catalog_ref: "cat",
|
||||
actor_id: "actor1",
|
||||
correlation_id: "corr1",
|
||||
},
|
||||
"t_a",
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("GET (list) requires tenant_id -- omitting it no longer returns every tenant's mappings (was: full leak)", async () => {
|
||||
const res = await mappingsListGET(getReq("/api/0pt/lakehouse/mappings", "t_a"));
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("GET (list) rejects a foreign tenant_id query param (403)", async () => {
|
||||
const res = await mappingsListGET(getReq("/api/0pt/lakehouse/mappings?tenant_id=t_victim", "t_a"));
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cross-tenant HTTP regression: /api/0pt/lakehouse/mappings/[mappingId]", () => {
|
||||
it("GET rejects a foreign tenant_id (403) -- this route had NO tenant check of any kind before P014", async () => {
|
||||
const res = await mappingGetGET(
|
||||
getReq("/api/0pt/lakehouse/mappings/dim_whatever?tenant_id=t_victim", "t_a"),
|
||||
{ params: Promise.resolve({ mappingId: "dim_whatever" }) },
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("GET without tenant_id at all is a 400, not an unscoped read", async () => {
|
||||
const res = await mappingGetGET(getReq("/api/0pt/lakehouse/mappings/dim_whatever", "t_a"), {
|
||||
params: Promise.resolve({ mappingId: "dim_whatever" }),
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cross-tenant HTTP regression: /api/0pt/quality/rules", () => {
|
||||
it("POST rejects creating a rule under a foreign tenant_id (403)", async () => {
|
||||
const res = await qualityRulesPOST(
|
||||
postReq(
|
||||
"/api/0pt/quality/rules",
|
||||
{
|
||||
rule_id: "rule_attack_1",
|
||||
tenant_id: "t_victim",
|
||||
project_id: "p1",
|
||||
dataset_id: "ds_1",
|
||||
name: "attacker rule",
|
||||
expectation: { expectation_type: "not_null", kwargs: { column: "name" } },
|
||||
},
|
||||
"t_a",
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cross-tenant HTTP regression: /api/0pt/documents/capture (GET)", () => {
|
||||
it("requires tenant_id -- omitting it no longer returns every tenant's captured documents (was: full leak)", async () => {
|
||||
const res = await documentsGET(getReq("/api/0pt/documents/capture", "t_a"));
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("rejects a foreign tenant_id query param (403)", async () => {
|
||||
const res = await documentsGET(getReq("/api/0pt/documents/capture?tenant_id=t_victim", "t_a"));
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("succeeds when the query tenant_id matches the verified tenant", async () => {
|
||||
const res = await documentsGET(getReq("/api/0pt/documents/capture?tenant_id=t_a", "t_a"));
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* HTTP-level tests for the P060/P067 routes added in this pass, in the same
|
||||
* shape as tests/api/0pt-cross-tenant-routes.test.ts: call the handler
|
||||
* directly with a hand-built NextRequest carrying `x-0pt-verified-tenant`,
|
||||
* which is exactly what middleware.ts forwards once a real Bearer token has
|
||||
* been verified.
|
||||
*
|
||||
* Two things are proved here that the service-level tests cannot:
|
||||
* - the new routes carry the SAME cross-tenant guard as the existing ones
|
||||
* (a new route with no guard would be the P014 hole reopened), and
|
||||
* - the activation gate is enforced at the HTTP boundary too — an
|
||||
* unclassified source gets 403, not a 200 with a quiet no-op.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { POST as sourcesPOST } from "@/app/api/0pt/sources/route";
|
||||
import { GET as classifyGET, POST as activatePOST } from "@/app/api/0pt/sources/[sourceId]/activate/route";
|
||||
import { PUT as authorizationPUT } from "@/app/api/0pt/sources/[sourceId]/authorization/route";
|
||||
import { PUT as schedulePUT } from "@/app/api/0pt/sources/[sourceId]/schedule/route";
|
||||
import { GET as lineageGET } from "@/app/api/0pt/lineage/route";
|
||||
|
||||
const VERIFIED = "x-0pt-verified-tenant";
|
||||
|
||||
function getReq(url: string, verifiedTenant = "t_a"): NextRequest {
|
||||
return new NextRequest(new URL(url, "http://localhost"), { headers: { [VERIFIED]: verifiedTenant } });
|
||||
}
|
||||
function bodyReq(url: string, method: "POST" | "PUT", body: unknown, verifiedTenant = "t_a"): NextRequest {
|
||||
return new NextRequest(new URL(url, "http://localhost"), {
|
||||
method,
|
||||
headers: { "content-type": "application/json", [VERIFIED]: verifiedTenant },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
const params = (sourceId: string) => ({ params: Promise.resolve({ sourceId }) });
|
||||
|
||||
describe("P060 routes — cross-tenant guard", () => {
|
||||
it("POST /activate rejects a foreign tenant_id (403)", async () => {
|
||||
const res = await activatePOST(
|
||||
bodyReq("/api/0pt/sources/src_x/activate", "POST", { tenant_id: "t_victim" }),
|
||||
params("src_x"),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
expect((await res.json()).error).toBe("OPT_ACCESS_DENIED");
|
||||
});
|
||||
|
||||
it("GET /activate (classification) rejects a foreign tenant_id (403)", async () => {
|
||||
const res = await classifyGET(
|
||||
getReq("/api/0pt/sources/src_x/activate?tenant_id=t_victim"),
|
||||
params("src_x"),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("PUT /authorization rejects a foreign tenant_id (403)", async () => {
|
||||
const res = await authorizationPUT(
|
||||
bodyReq("/api/0pt/sources/src_x/authorization", "PUT", {
|
||||
tenant_id: "t_victim",
|
||||
basis: "contract",
|
||||
granted_by: "usr_attacker",
|
||||
granted_at: "2026-09-04T00:00:00.000Z",
|
||||
}),
|
||||
params("src_x"),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("PUT /schedule rejects a foreign tenant_id (403)", async () => {
|
||||
const res = await schedulePUT(
|
||||
bodyReq("/api/0pt/sources/src_x/schedule", "PUT", { tenant_id: "t_victim", mode: "batch", enabled: true }),
|
||||
params("src_x"),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("GET /lineage rejects a foreign tenant_id (403)", async () => {
|
||||
const res = await lineageGET(getReq("/api/0pt/lineage?tenant_id=t_victim&output_name=0pt:dataset:ds_x"));
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("GET /lineage refuses an unfiltered dump (400)", async () => {
|
||||
const res = await lineageGET(getReq("/api/0pt/lineage?tenant_id=t_a"));
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("P060 routes — the activation gate over HTTP", () => {
|
||||
it("an unclassified source cannot be activated through the API", async () => {
|
||||
const created = await sourcesPOST(
|
||||
bodyReq("/api/0pt/sources", "POST", {
|
||||
source_id: "src_http_gate_1",
|
||||
tenant_id: "t_a",
|
||||
project_id: "p_a",
|
||||
source_type: "api",
|
||||
name: "Unclassified source",
|
||||
}),
|
||||
);
|
||||
expect(created.status).toBeLessThan(300);
|
||||
const body = await created.json();
|
||||
expect(body.source.status).toBe("pending");
|
||||
|
||||
const classification = await classifyGET(
|
||||
getReq("/api/0pt/sources/src_http_gate_1/activate?tenant_id=t_a"),
|
||||
params("src_http_gate_1"),
|
||||
);
|
||||
expect(classification.status).toBe(200);
|
||||
expect((await classification.json()).classified).toBe(false);
|
||||
|
||||
const activated = await activatePOST(
|
||||
bodyReq("/api/0pt/sources/src_http_gate_1/activate", "POST", { tenant_id: "t_a" }),
|
||||
params("src_http_gate_1"),
|
||||
);
|
||||
expect(activated.status).toBe(403);
|
||||
});
|
||||
|
||||
it("a classified source activates through the API", async () => {
|
||||
await sourcesPOST(
|
||||
bodyReq("/api/0pt/sources", "POST", {
|
||||
source_id: "src_http_gate_2",
|
||||
tenant_id: "t_a",
|
||||
project_id: "p_a",
|
||||
source_type: "api",
|
||||
name: "Classified source",
|
||||
owner_id: "usr_simon",
|
||||
rights: {
|
||||
license_id: "CC-BY-4.0",
|
||||
allowed_purposes: ["catalog"],
|
||||
pii_allowed: false,
|
||||
redistribution: "internal",
|
||||
verified_at: "2026-09-04",
|
||||
verified_by: "usr_simon",
|
||||
},
|
||||
provenance: { method: "official_api" },
|
||||
}),
|
||||
);
|
||||
const auth = await authorizationPUT(
|
||||
bodyReq("/api/0pt/sources/src_http_gate_2/authorization", "PUT", {
|
||||
tenant_id: "t_a",
|
||||
basis: "public_register",
|
||||
granted_by: "usr_simon",
|
||||
granted_at: "2026-09-01T00:00:00.000Z",
|
||||
}),
|
||||
params("src_http_gate_2"),
|
||||
);
|
||||
expect(auth.status).toBe(200);
|
||||
|
||||
const activated = await activatePOST(
|
||||
bodyReq("/api/0pt/sources/src_http_gate_2/activate", "POST", { tenant_id: "t_a", actor_id: "usr_simon" }),
|
||||
params("src_http_gate_2"),
|
||||
);
|
||||
expect(activated.status).toBe(200);
|
||||
expect((await activated.json()).status).toBe("active");
|
||||
});
|
||||
|
||||
it("a service identity cannot be recorded as the authorizing actor (400)", async () => {
|
||||
await sourcesPOST(
|
||||
bodyReq("/api/0pt/sources", "POST", {
|
||||
source_id: "src_http_gate_3",
|
||||
tenant_id: "t_a",
|
||||
project_id: "p_a",
|
||||
source_type: "api",
|
||||
name: "Self-authorizing source",
|
||||
}),
|
||||
);
|
||||
const res = await authorizationPUT(
|
||||
bodyReq("/api/0pt/sources/src_http_gate_3/authorization", "PUT", {
|
||||
tenant_id: "t_a",
|
||||
basis: "internal",
|
||||
granted_by: "svc_0pt",
|
||||
granted_at: "2026-09-01T00:00:00.000Z",
|
||||
}),
|
||||
params("src_http_gate_3"),
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Regression tests for the anonymous-access finding on `/api/orders` (GET)
|
||||
* and `/api/admin/metrics` (GET): a live compliance audit confirmed both
|
||||
* responded HTTP 200 with zero authentication (the order queue + financial
|
||||
* pipeline aggregates were readable by anyone). Both are outside
|
||||
* middleware.ts's matcher (`/api/0pt/:path*` only), so each handler now
|
||||
* calls `requireRouteAuth` (src/auth/require-route-auth.ts -> the same
|
||||
* fail-closed `resolveAuthContext`/Zitadel verifier `/api/0pt/*` relies on)
|
||||
* directly.
|
||||
*
|
||||
* No DATABASE_URL is set in this test env, so lib/orders-store.ts falls back
|
||||
* to its in-memory store -- these tests only exercise the auth gate, not
|
||||
* order persistence.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { NextRequest } from 'next/server';
|
||||
import { GET as ordersGET } from '@/app/api/orders/route';
|
||||
import { GET as orderGET } from '@/app/api/orders/[id]/route';
|
||||
import { GET as adminMetricsGET } from '@/app/api/admin/metrics/route';
|
||||
import { POST as depositPOST } from '@/app/api/payments/[order_id]/deposit/route';
|
||||
|
||||
function req(url: string, headers: Record<string, string> = {}): NextRequest {
|
||||
return new NextRequest(new URL(url, 'http://localhost'), { headers });
|
||||
}
|
||||
|
||||
describe('anonymous-access regression: /api/orders (GET) and /api/admin/metrics (GET)', () => {
|
||||
const saved = { auth: process.env.AUTH_ENFORCE, node: process.env.NODE_ENV };
|
||||
|
||||
beforeEach(() => {
|
||||
// Default posture: AUTH_ENFORCE unset => enforced (fail-closed), matching
|
||||
// production and matching how resolveAuthContext's own tests run.
|
||||
delete process.env.AUTH_ENFORCE;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (saved.auth === undefined) delete process.env.AUTH_ENFORCE;
|
||||
else process.env.AUTH_ENFORCE = saved.auth;
|
||||
if (saved.node === undefined) delete process.env.NODE_ENV;
|
||||
else process.env.NODE_ENV = saved.node;
|
||||
});
|
||||
|
||||
it('REGRESSION: GET /api/orders 401s with no Authorization header (was: 200 + full order list)', async () => {
|
||||
const res = await ordersGET(req('/api/orders'));
|
||||
expect(res.status).toBe(401);
|
||||
const body = await res.json();
|
||||
expect(body.error).toBe('OPT_UNAUTHENTICATED');
|
||||
});
|
||||
|
||||
it('GET /api/orders 401s on an invalid/unparseable bearer token', async () => {
|
||||
const res = await ordersGET(req('/api/orders', { authorization: 'Bearer not.a.real.jwt' }));
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('GET /api/orders/{id} rejects anonymous and spoofed-tenant reads before loading an order', async () => {
|
||||
const params = { params: Promise.resolve({ id: 'order-unknown' }) };
|
||||
expect((await orderGET(req('/api/orders/order-unknown'), params)).status).toBe(401);
|
||||
expect((await orderGET(req('/api/orders/order-unknown', {
|
||||
'x-0pt-verified-tenant': 'tenant_attacker',
|
||||
}), params)).status).toBe(401);
|
||||
});
|
||||
|
||||
it('deposit checkout rejects anonymous callers before checking Stripe credentials or order id', async () => {
|
||||
const request = req('/api/payments/order-unknown/deposit');
|
||||
const result = await depositPOST(request, { params: Promise.resolve({ order_id: 'order-unknown' }) });
|
||||
expect(result.status).toBe(401);
|
||||
});
|
||||
|
||||
it('REGRESSION: GET /api/admin/metrics 401s with no Authorization header (was: 200 + financial aggregates)', async () => {
|
||||
const res = await adminMetricsGET(req('/api/admin/metrics'));
|
||||
expect(res.status).toBe(401);
|
||||
const body = await res.json();
|
||||
expect(body.error).toBe('OPT_UNAUTHENTICATED');
|
||||
});
|
||||
|
||||
it('a bare X-Tenant-Id header alone (no bearer token) does not grant access to either route', async () => {
|
||||
// Guards against a shortcut implementation that trusts a client-supplied
|
||||
// tenant/verified header instead of re-verifying the token.
|
||||
const ordersRes = await ordersGET(req('/api/orders', { 'x-tenant-id': 'tenant_attacker' }));
|
||||
expect(ordersRes.status).toBe(401);
|
||||
|
||||
const metricsRes = await adminMetricsGET(req('/api/admin/metrics', { 'x-tenant-id': 'tenant_attacker' }));
|
||||
expect(metricsRes.status).toBe(401);
|
||||
});
|
||||
|
||||
it('a spoofed x-0pt-verified-tenant header alone does not grant access (never trusted directly)', async () => {
|
||||
// These routes sit outside middleware.ts's matcher, so nothing strips or
|
||||
// overwrites this header before the handler sees it -- proving the
|
||||
// handler re-verifies via the real JWT check rather than trusting it.
|
||||
const res = await ordersGET(req('/api/orders', { 'x-0pt-verified-tenant': 'tenant_attacker' }));
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('AUTH_ENFORCE=false cannot mint/read payable orders without a verified buyer', async () => {
|
||||
process.env.AUTH_ENFORCE = 'false';
|
||||
const ordersRes = await ordersGET(req('/api/orders'));
|
||||
expect(ordersRes.status).toBe(401);
|
||||
const metricsRes = await adminMetricsGET(req('/api/admin/metrics'));
|
||||
expect(metricsRes.status).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { NextRequest } from 'next/server';
|
||||
import { POST as capture } from '@/app/api/0pt/documents/capture/route';
|
||||
import { POST as extract } from '@/app/api/0pt/documents/[documentId]/extraction/route';
|
||||
import { documentCaptureService } from '@/src/services/document-capture-service';
|
||||
import { documentExtractionService } from '@/src/services/document-extraction-service';
|
||||
|
||||
function request(body: object) {
|
||||
return new NextRequest('http://localhost/api/0pt/documents', { method: 'POST',
|
||||
headers: { 'content-type': 'application/json', 'x-0pt-verified-tenant': 'tenant-a', 'x-0pt-verified-sub': 'user-a' },
|
||||
body: JSON.stringify(body) });
|
||||
}
|
||||
const base = { tenant_id: 'tenant-a', project_id: 'project-a', model_id: 'model-test' };
|
||||
const mailbox = { tenant_id: 'directory', client_id: 'test', client_secret: 'test', mailbox_address: 'test@example.test' };
|
||||
describe('document route verified actor', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
it('rejects forged body actors before either service is called', async () => {
|
||||
const captured = vi.spyOn(documentCaptureService, 'captureFromMailbox');
|
||||
const extracted = vi.spyOn(documentExtractionService, 'extractDocument');
|
||||
expect((await capture(request({ ...base, mailbox, actor_id: 'victim' }))).status).toBe(403);
|
||||
expect((await extract(request({ ...base, actor_id: 'victim' }), { params: Promise.resolve({ documentId: 'd' }) })).status).toBe(403);
|
||||
expect(captured).not.toHaveBeenCalled();
|
||||
expect(extracted).not.toHaveBeenCalled();
|
||||
});
|
||||
it('fills the actor from the verified subject when the body omits it', async () => {
|
||||
const captured = vi.spyOn(documentCaptureService, 'captureFromMailbox').mockResolvedValue({} as never);
|
||||
const extracted = vi.spyOn(documentExtractionService, 'extractDocument').mockResolvedValue({} as never);
|
||||
expect((await capture(request({ ...base, mailbox }))).status).toBe(201);
|
||||
expect((await extract(request(base), { params: Promise.resolve({ documentId: 'd' }) })).status).toBe(201);
|
||||
expect(captured.mock.calls[0]?.[1].actor_id).toBe('user-a');
|
||||
expect(extracted.mock.calls[0]?.[1].actor_id).toBe('user-a');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Route-level regression test for GET /api/health (BACKLOG P0-3): the old
|
||||
* handler hardcoded `ok: true` regardless of dependency state. These tests
|
||||
* cover the default (nothing configured) baseline against the real route
|
||||
* handler; per-dependency ok/error branching is covered at the unit level in
|
||||
* tests/lib/health-checks.test.ts (dependency-injected, no network/DB
|
||||
* needed).
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import { GET as healthGET } from "@/app/api/health/route";
|
||||
|
||||
describe("GET /api/health", () => {
|
||||
const savedEnv = {
|
||||
DATABASE_URL: process.env.DATABASE_URL,
|
||||
POSTGRES_URL: process.env.POSTGRES_URL,
|
||||
ENGINE_URL: process.env.ENGINE_URL,
|
||||
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
|
||||
REDIS_URL: process.env.REDIS_URL,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.DATABASE_URL;
|
||||
delete process.env.POSTGRES_URL;
|
||||
delete process.env.ENGINE_URL;
|
||||
delete process.env.STRIPE_SECRET_KEY;
|
||||
delete process.env.REDIS_URL;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const [k, v] of Object.entries(savedEnv)) {
|
||||
if (v === undefined) delete process.env[k];
|
||||
else process.env[k] = v;
|
||||
}
|
||||
});
|
||||
|
||||
it("REGRESSION: always returns HTTP 200 (liveness), but `ok` now reflects a real per-dependency check rather than a hardcoded true", async () => {
|
||||
const res = await healthGET();
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
// With nothing configured, nothing can be degraded -- ok:true here is
|
||||
// now an honest conclusion, not a hardcoded literal.
|
||||
expect(body.ok).toBe(true);
|
||||
expect(body.service).toBe("0pt-web");
|
||||
});
|
||||
|
||||
it("reports not_configured (not the old flat 'configured'/'not_configured' guess) for every unset dependency", async () => {
|
||||
const res = await healthGET();
|
||||
const body = await res.json();
|
||||
expect(body.db).toBe("not_configured");
|
||||
expect(body.engine).toBe("not_configured");
|
||||
expect(body.stripe).toBe("not_configured");
|
||||
expect(body.queue).toBe("not_configured");
|
||||
});
|
||||
|
||||
it("reports a configured but unreachable queue as error (never a fabricated ok)", async () => {
|
||||
process.env.REDIS_URL = "redis://127.0.0.1:1";
|
||||
const res = await healthGET();
|
||||
const body = await res.json();
|
||||
expect(body.queue).toBe("error");
|
||||
// Liveness stays 200; readiness is what fails closed on a broken dependency.
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("response includes a ts timestamp", async () => {
|
||||
const res = await healthGET();
|
||||
const body = await res.json();
|
||||
expect(new Date(body.ts).toString()).not.toBe("Invalid Date");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* DES1GN ADR D3 (§31): ImportDispatchPolicy — ren policy-funktion, testad per
|
||||
* kombination (format × bytes × rows, gränsvärden inkluderade), plus route-
|
||||
* kopplingen: rows > policy.maxRows -> 413 n0d_dispatch_required med hint
|
||||
* (descriptor-gate stängd), inline-taket oförändrat.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { IMPORT_DISPATCH_POLICY, evaluateImportDispatch } from "@/lib/import-dispatch-policy";
|
||||
|
||||
describe("evaluateImportDispatch — verdict per kombination", () => {
|
||||
it("gränsvärde maxInlineRows: exakt 500 rader -> inline", () => {
|
||||
expect(evaluateImportDispatch({ format: "csv", bytes: 100, rows: IMPORT_DISPATCH_POLICY.maxInlineRows })).toEqual({ verdict: "inline" });
|
||||
});
|
||||
|
||||
it("maxInlineRows < rows <= maxRows -> row_cap_exceeded (inline-taket, oförändrat)", () => {
|
||||
expect(evaluateImportDispatch({ format: "csv", bytes: 100, rows: IMPORT_DISPATCH_POLICY.maxInlineRows + 1 })).toEqual({
|
||||
verdict: "row_cap_exceeded",
|
||||
rows: 501,
|
||||
maxInlineRows: 500,
|
||||
});
|
||||
expect(evaluateImportDispatch({ format: "csv", bytes: 100, rows: IMPORT_DISPATCH_POLICY.maxRows }).verdict).toBe("row_cap_exceeded");
|
||||
});
|
||||
|
||||
it("rows > maxRows -> dispatch_n0d (D3-signalen)", () => {
|
||||
expect(evaluateImportDispatch({ format: "csv", bytes: 100, rows: IMPORT_DISPATCH_POLICY.maxRows + 1 })).toEqual({
|
||||
verdict: "dispatch_n0d",
|
||||
rows: 5001,
|
||||
maxRows: 5000,
|
||||
});
|
||||
});
|
||||
|
||||
it("bytes > maxBytes -> byte_cap_exceeded, oavsett rows", () => {
|
||||
expect(evaluateImportDispatch({ format: "csv", bytes: IMPORT_DISPATCH_POLICY.maxBytes + 1, rows: 1 }).verdict).toBe("byte_cap_exceeded");
|
||||
expect(evaluateImportDispatch({ format: "csv", bytes: IMPORT_DISPATCH_POLICY.maxBytes, rows: 1 }).verdict).toBe("inline");
|
||||
});
|
||||
|
||||
it("format utanför allowlist -> unsupported_format", () => {
|
||||
expect(evaluateImportDispatch({ format: "xlsx", bytes: 10, rows: 1 })).toEqual({ verdict: "unsupported_format", format: "xlsx" });
|
||||
});
|
||||
|
||||
it("precedens: format slår bytes, bytes slår rows", () => {
|
||||
expect(evaluateImportDispatch({ format: "json", bytes: 9e9, rows: 9e9 }).verdict).toBe("unsupported_format");
|
||||
expect(evaluateImportDispatch({ format: "csv", bytes: 9e9, rows: 9e9 }).verdict).toBe("byte_cap_exceeded");
|
||||
});
|
||||
});
|
||||
|
||||
describe("route-koppling: POST /api/orders/import respekterar policyn", () => {
|
||||
const { requireOrderOwnerMock, createOrderMock, ingestEventMock, mockOwner } = vi.hoisted(() => ({
|
||||
requireOrderOwnerMock: vi.fn(),
|
||||
createOrderMock: vi.fn(),
|
||||
ingestEventMock: vi.fn().mockResolvedValue({}),
|
||||
mockOwner: { owner: { tenantId: "tenant-test", subject: "buyer-test" } },
|
||||
}));
|
||||
const _unused = mockOwner;
|
||||
vi.mock("@/src/auth/require-order-owner", () => ({
|
||||
requireOrderOwner: (...args: unknown[]) => requireOrderOwnerMock(...args),
|
||||
}));
|
||||
vi.mock("@/lib/orders-store", () => ({ createOrder: (...args: unknown[]) => createOrderMock(...args) }));
|
||||
vi.mock("@/src/clients/aud0-client", () => ({ createAud0Client: () => ({ ingestEvent: ingestEventMock }) }));
|
||||
|
||||
let POST: typeof import("@/app/api/orders/import/route").POST;
|
||||
let MAX_IMPORT_ROWS: number;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
requireOrderOwnerMock.mockResolvedValue(mockOwner);
|
||||
({ POST, MAX_IMPORT_ROWS } = await import("@/app/api/orders/import/route"));
|
||||
});
|
||||
|
||||
function postReq(csv: string): NextRequest {
|
||||
return new NextRequest(new URL("/api/orders/import", "http://localhost"), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ mode: "validate", csv }),
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
const line = "custom,icp,Bolag,10,Engångs,SE";
|
||||
|
||||
it("exakt maxInlineRows rader -> 200 (inline-beteende oförändrat)", async () => {
|
||||
const csv = ["flow,service_type,type,volume,frequency,markets", ...Array.from({ length: MAX_IMPORT_ROWS }, () => line)].join("\n");
|
||||
const res = await POST(postReq(csv));
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("maxRows < rows -> 413 n0d_dispatch_required med UNVERIFIED-hint, ingen skrivning", async () => {
|
||||
const csv = ["flow,service_type,type,volume,frequency,markets", ...Array.from({ length: IMPORT_DISPATCH_POLICY.maxRows + 1 }, () => line)].join("\n");
|
||||
const res = await POST(postReq(csv));
|
||||
expect(res.status).toBe(413);
|
||||
const body = (await res.json()) as { error: { code: string; hint: { capability_id: string; job_type: string; status: string } } };
|
||||
expect(body.error.code).toBe("n0d_dispatch_required");
|
||||
expect(body.error.hint).toEqual({ capability_id: "0pt.import_execute", job_type: "0pt.import_execute_job", status: "UNVERIFIED" });
|
||||
expect(createOrderMock).not.toHaveBeenCalled();
|
||||
expect(ingestEventMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("CSV > maxBytes -> 413 csv_too_large", async () => {
|
||||
const csv = "flow,service_type,type,volume,frequency,markets\n" + "x".repeat(IMPORT_DISPATCH_POLICY.maxBytes);
|
||||
const res = await POST(postReq(csv));
|
||||
expect(res.status).toBe(413);
|
||||
const body = (await res.json()) as { error: { code: string } };
|
||||
expect(body.error.code).toBe("csv_too_large");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* 0pt#53: `getSqlForDurableStore` (lib/db.ts) throws
|
||||
* `SiaxError("DEPENDENCY_UNAVAILABLE")` (httpStatus 503, retryable) when a
|
||||
* money-bearing store would silently fall back to an in-memory Map in a
|
||||
* production runtime. The /api/0pt/* surface maps that error via
|
||||
* src/http/siax-error-response.ts; the SEVEN legacy routes outside the
|
||||
* middleware matcher (orders, orders/[id], subscriptions, payments/deposit,
|
||||
* payments/release, webhooks/stripe, admin/metrics) did NOT, so the documented
|
||||
* 503 leaked as Next's opaque 500 with no error body.
|
||||
*
|
||||
* These tests pin the mapping itself: `isSiaxError` accepts real SiaxErrors,
|
||||
* `siaxErrorResponseForLegacy` renders the pinned `.httpStatus` and the
|
||||
* structured `toJSON()` body (code + source + retryable, no internals), and
|
||||
* — most importantly — the DEPENDENCY_UNAVAILABLE code maps to 503 with
|
||||
* `retryable: true` so callers (Stripe retries, the UI) can distinguish a
|
||||
* transient store outage from a hard failure.
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { NextResponse } from "next/server";
|
||||
import { SiaxError } from "@/src/platform/errors";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "@/app/api/siax-error-mapping";
|
||||
|
||||
describe("0pt#53 legacy-route SiaxError mapping (app/api/siax-error-mapping.ts)", () => {
|
||||
it("isSiaxError: true for a real SiaxError, false for plain errors", () => {
|
||||
expect(isSiaxError(new SiaxError("DEPENDENCY_UNAVAILABLE", "0pt.orders", "x"))).toBe(true);
|
||||
expect(isSiaxError(new Error("plain"))).toBe(false);
|
||||
expect(isSiaxError(null)).toBe(false);
|
||||
expect(isSiaxError("nope")).toBe(false);
|
||||
});
|
||||
|
||||
it("DEPENDENCY_UNAVAILABLE maps to 503 with the structured, non-internal body", () => {
|
||||
const err = new SiaxError(
|
||||
"DEPENDENCY_UNAVAILABLE",
|
||||
"0pt.orders",
|
||||
'no database configured for persistent store "0pt.orders" in a production runtime',
|
||||
);
|
||||
expect(err.httpStatus).toBe(503);
|
||||
expect(err.retryable).toBe(true);
|
||||
|
||||
const res = siaxErrorResponseForLegacy(err) as NextResponse;
|
||||
expect(res.status).toBe(503);
|
||||
void res.json().then((body: Record<string, unknown>) => {
|
||||
expect(body.error).toBe("DEPENDENCY_UNAVAILABLE");
|
||||
expect(body.source).toBe("0pt.orders");
|
||||
expect(body.retryable).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("the store name travels in the body so the operator knows WHICH store failed", () => {
|
||||
const res = siaxErrorResponseForLegacy(
|
||||
new SiaxError("DEPENDENCY_UNAVAILABLE", "0pt.subscriptions", "no database"),
|
||||
);
|
||||
void res.json().then((body: Record<string, unknown>) => {
|
||||
expect(body.source).toBe("0pt.subscriptions");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,226 @@
|
||||
/**
|
||||
* Spår C — @siax/collaboration-kernelns första produktkonsument:
|
||||
* /api/admin/order-notes (persisted collaboration state på admin-orders).
|
||||
*
|
||||
* Mönstret följer tests/api/anonymous-routes-auth.test.ts +
|
||||
* orders-idempotency.test.ts: route-handlers anropas direkt med handbyggda
|
||||
* NextRequest. Ingen DATABASE_URL i test-miljön => lib/order-notes-store.ts
|
||||
* faller tillbaka på sin dokumenterade in-memory-store (production vägrar
|
||||
* den vägen via resolveStoreMode — se lib/db.ts).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
vi.mock("@/src/auth/require-route-auth", () => ({
|
||||
requireRouteAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/src/clients/aud0-client", () => ({
|
||||
createAud0Client: vi.fn(() => ({ ingestEvent: vi.fn().mockResolvedValue({}) })),
|
||||
}));
|
||||
|
||||
import { requireRouteAuth } from "@/src/auth/require-route-auth";
|
||||
import { createAud0Client } from "@/src/clients/aud0-client";
|
||||
import { GET, PATCH, POST } from "@/app/api/admin/order-notes/route";
|
||||
import { getOrder, createOrder } from "@/lib/orders-store";
|
||||
import {
|
||||
addNote,
|
||||
listNotes,
|
||||
resetOrderNotesMemoryForTests,
|
||||
} from "@/lib/order-notes-store";
|
||||
|
||||
const authed = { tenantId: "tenant-test", actorId: "admin-simon", requestId: "req-1" };
|
||||
|
||||
function mockAuth(ctx = authed) {
|
||||
vi.mocked(requireRouteAuth).mockResolvedValue({ ctx } as never);
|
||||
}
|
||||
|
||||
function req(
|
||||
url: string,
|
||||
init: { method?: string; headers?: Record<string, string>; body?: string } = {},
|
||||
): NextRequest {
|
||||
return new NextRequest(new URL(url, "http://localhost"), init);
|
||||
}
|
||||
|
||||
function jsonReq(url: string, body: unknown, method = "POST"): NextRequest {
|
||||
return req(url, {
|
||||
method,
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
let orderId: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.mocked(requireRouteAuth).mockReset();
|
||||
vi.mocked(createAud0Client).mockClear();
|
||||
resetOrderNotesMemoryForTests();
|
||||
mockAuth();
|
||||
const created = await createOrder("custom", {
|
||||
markets: ["SE"],
|
||||
type: "Bolag",
|
||||
volume: 10,
|
||||
});
|
||||
orderId = created.order.order_id;
|
||||
// Legacy anonymous draft får annoteras av admin — men en tenant-ägd order
|
||||
// behöver token-match. Skapa därför testordern anonym (tenant null) och
|
||||
// testa tenant-guarden separat med en ägd order.
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
resetOrderNotesMemoryForTests();
|
||||
});
|
||||
|
||||
describe("GET /api/admin/order-notes", () => {
|
||||
it("empty order -> 200 med tom lista (explicit empty behavior)", async () => {
|
||||
const res = await GET(req(`/api/admin/order-notes?order_id=${orderId}`));
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.notes).toEqual([]);
|
||||
});
|
||||
|
||||
it("saknad order_id -> 400; okänd order -> 404", async () => {
|
||||
expect((await GET(req("/api/admin/order-notes"))).status).toBe(400);
|
||||
expect((await GET(req("/api/admin/order-notes?order_id=nope"))).status).toBe(404);
|
||||
});
|
||||
|
||||
it("utan auth-svar från requireRouteAuth -> fail-closed (401), aldrig data", async () => {
|
||||
vi.mocked(requireRouteAuth).mockResolvedValueOnce({
|
||||
response: new NextResponse(null, { status: 401 }),
|
||||
} as never);
|
||||
const res = await GET(req(`/api/admin/order-notes?order_id=${orderId}`));
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST + GET happy path (kernel-semantik)", () => {
|
||||
it("201 skapar noten, GET listar deterministiskt (Lamport-ordning, inte insättningsordning)", async () => {
|
||||
const r1 = await POST(jsonReq("/api/admin/order-notes", { order_id: orderId, body: "Första" }));
|
||||
expect(r1.status).toBe(201);
|
||||
const first = await r1.json();
|
||||
expect(first.version).toBe(1);
|
||||
expect(first.clock).toBe(1);
|
||||
|
||||
const r2 = await POST(jsonReq("/api/admin/order-notes", { order_id: orderId, body: "Andra" }));
|
||||
expect(r2.status).toBe(201);
|
||||
|
||||
const list = await (await GET(req(`/api/admin/order-notes?order_id=${orderId}`))).json();
|
||||
expect(list.notes).toHaveLength(2);
|
||||
// kernel mergeOperationLog: stigande (clock, actorId, id)
|
||||
const clocks = list.notes.map((n: { clock: number }) => n.clock);
|
||||
expect([...clocks].sort((a: number, b: number) => a - b)).toEqual(clocks);
|
||||
expect(list.notes[0].body).toBe("Första");
|
||||
|
||||
// audit event emitterades via hostens AUD0-klient
|
||||
const ingest = vi.mocked(createAud0Client).mock.results.at(-1)?.value as {
|
||||
ingestEvent: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
expect(ingest.ingestEvent).toHaveBeenCalled();
|
||||
const evt = ingest.ingestEvent.mock.calls[0][0];
|
||||
expect(evt.capability_id).toBe("admin.order_notes");
|
||||
expect(evt.event_type).toBe("order_note.created");
|
||||
});
|
||||
|
||||
it("tom body -> 400 (server-authoritative validering)", async () => {
|
||||
const res = await POST(jsonReq("/api/admin/order-notes", { order_id: orderId, body: " " }));
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("tenant-guard: order tillhör annan tenant än token -> 403", async () => {
|
||||
const created = await createOrder("custom", { markets: ["SE"], volume: 5 }, undefined, {
|
||||
tenantId: "tenant-other",
|
||||
subject: "buyer-other",
|
||||
});
|
||||
const res = await POST(
|
||||
jsonReq("/api/admin/order-notes", { order_id: created.order.order_id, body: "hej" }),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
const body = await res.json();
|
||||
expect(body.error).toBe("OPT_ACCESS_DENIED");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PATCH — optimistisk samtidighet (conflict behavior)", () => {
|
||||
it("rätt version -> 200, version+1, klockan tickar (nextLamportClock)", async () => {
|
||||
const note = await addNote({ order_id: orderId, tenant_id: null, author_id: "a", body: "v1" });
|
||||
const res = await PATCH(
|
||||
jsonReq("/api/admin/order-notes", { note_id: note.note_id, body: "v2", version: 1 }, "PATCH"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const updated = await res.json();
|
||||
expect(updated.body).toBe("v2");
|
||||
expect(updated.version).toBe(2);
|
||||
expect(updated.clock).toBe(note.clock + 1);
|
||||
});
|
||||
|
||||
it("stale version -> 409 med aktuell version (multi-user semantics)", async () => {
|
||||
const note = await addNote({ order_id: orderId, tenant_id: null, author_id: "a", body: "v1" });
|
||||
await updateNoteViaApi(note.note_id, "v2 fran annan skribent"); // samtidig skribant -> v2
|
||||
const res = await PATCH(
|
||||
jsonReq("/api/admin/order-notes", { note_id: note.note_id, body: "v3 stale", version: 1 }, "PATCH"),
|
||||
);
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.error).toBe("version_conflict");
|
||||
expect(body.current_version).toBe(2);
|
||||
});
|
||||
|
||||
it("okänd note -> 404; ogiltig version -> 400", async () => {
|
||||
expect(
|
||||
(
|
||||
await PATCH(
|
||||
jsonReq(
|
||||
"/api/admin/order-notes",
|
||||
{ note_id: "note_nope", body: "x", version: 1 },
|
||||
"PATCH",
|
||||
),
|
||||
)
|
||||
).status,
|
||||
).toBe(404);
|
||||
const note = await addNote({ order_id: orderId, tenant_id: null, author_id: "a", body: "v1" });
|
||||
expect(
|
||||
(
|
||||
await PATCH(
|
||||
jsonReq(
|
||||
"/api/admin/order-notes",
|
||||
{ note_id: note.note_id, body: "x", version: 1.5 },
|
||||
"PATCH",
|
||||
),
|
||||
)
|
||||
).status,
|
||||
).toBe(400);
|
||||
});
|
||||
|
||||
it("PATCH utan auth -> 401 fail-closed", async () => {
|
||||
vi.mocked(requireRouteAuth).mockResolvedValueOnce({
|
||||
response: new NextResponse(null, { status: 401 }),
|
||||
} as never);
|
||||
const res = await PATCH(
|
||||
jsonReq("/api/admin/order-notes", { note_id: "x", body: "x", version: 1 }, "PATCH"),
|
||||
);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
async function updateNoteViaApi(noteId: string, body: string) {
|
||||
const res = await PATCH(jsonReq("/api/admin/order-notes", { note_id: noteId, body, version: 1 }, "PATCH"));
|
||||
expect(res.status).toBe(200);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
describe("kernel-återanvändning (capability, inte paket)", () => {
|
||||
it("listNotes är kernel-mergead: ordningen följer compareOperations (klocka -> actorId -> id), två listningar identiska", async () => {
|
||||
const a = await addNote({ order_id: orderId, tenant_id: null, author_id: "a", body: "A" });
|
||||
const b = await addNote({ order_id: orderId, tenant_id: null, author_id: "b", body: "B" });
|
||||
const first = await listNotes(orderId);
|
||||
const second = await listNotes(orderId);
|
||||
expect(second.map((n) => n.note_id)).toEqual(first.map((n) => n.note_id));
|
||||
// stigande klocka = deterministisk kernel-ordning, oberoende av minnes-mapens iteration
|
||||
expect(first.map((n) => n.clock)).toEqual([a.clock, b.clock].sort((x, y) => x - y));
|
||||
expect(first.map((n) => n.note_id)).toEqual([a.note_id, b.note_id]);
|
||||
});
|
||||
});
|
||||
|
||||
// getOrder används i routen (server-authoritative tenant-uppslag) — håll
|
||||
// importen levande så refaktorer inte tyst tappar guarden.
|
||||
void getOrder;
|
||||
@@ -0,0 +1,55 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
auth: vi.fn(),
|
||||
getOrder: vi.fn(),
|
||||
setStatusIfCurrent: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/src/auth/require-order-owner", () => ({ requireOrderOwner: mocks.auth }));
|
||||
vi.mock("@/lib/orders-store", () => ({
|
||||
getOwnedOrder: mocks.getOrder,
|
||||
setOwnedStatusIfCurrent: mocks.setStatusIfCurrent,
|
||||
}));
|
||||
|
||||
import { PATCH } from "@/app/api/orders/[id]/route";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.auth.mockReset().mockResolvedValue({ owner: { tenantId: "verified-tenant", subject: "buyer-1" } });
|
||||
mocks.getOrder.mockReset().mockResolvedValue({ order_id: "order-1", status: "draft" });
|
||||
mocks.setStatusIfCurrent.mockReset().mockResolvedValue({ order_id: "order-1", status: "accepted" });
|
||||
});
|
||||
|
||||
function request(status: string) {
|
||||
return new NextRequest("https://0pt.app/api/orders/order-1", {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ status }),
|
||||
});
|
||||
}
|
||||
|
||||
const ctx = { params: Promise.resolve({ id: "order-1" }) };
|
||||
|
||||
it("requires verified auth before changing an order", async () => {
|
||||
mocks.auth.mockResolvedValue({ response: NextResponse.json({ error: "unauthenticated" }, { status: 401 }) });
|
||||
expect((await PATCH(request("accepted"), ctx)).status).toBe(401);
|
||||
expect(mocks.getOrder).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects client writes to payment-confirmed states", async () => {
|
||||
expect((await PATCH(request("in_production"), ctx)).status).toBe(403);
|
||||
expect((await PATCH(request("delivered"), ctx)).status).toBe(403);
|
||||
expect(mocks.setStatusIfCurrent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cannot jump from draft directly to accepted", async () => {
|
||||
expect((await PATCH(request("accepted"), ctx)).status).toBe(409);
|
||||
expect(mocks.setStatusIfCurrent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses an atomic compare-and-set transition after review", async () => {
|
||||
mocks.getOrder.mockResolvedValue({ order_id: "order-1", status: "review" });
|
||||
expect((await PATCH(request("accepted"), ctx)).status).toBe(200);
|
||||
expect(mocks.getOrder).toHaveBeenCalledWith("order-1", "verified-tenant");
|
||||
expect(mocks.setStatusIfCurrent).toHaveBeenCalledWith("order-1", "verified-tenant", "review", "accepted");
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Våg 3.4 (DoD §56): unit tests for GET /api/orders/export — the first
|
||||
* adoption of the export kernel. Follows the suite pattern of calling the
|
||||
* route handler directly with a hand-built NextRequest and mocked auth/store.
|
||||
*/
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/src/auth/require-order-owner", () => ({
|
||||
requireOrderOwner: vi.fn().mockResolvedValue({ owner: { tenantId: "tenant-test", subject: "buyer-test" } }),
|
||||
}));
|
||||
vi.mock("@/lib/orders-store", () => ({
|
||||
listOwnedOrders: vi.fn().mockResolvedValue([
|
||||
{ order_id: "ord_1", flow: "custom", status: "draft", deposit_ore: 5000, total_ore: 10000 },
|
||||
{ order_id: 'ord,"2"', flow: "platform", status: "delivered", deposit_ore: 0, total_ore: 12345 },
|
||||
]),
|
||||
}));
|
||||
|
||||
import { GET as exportGET } from "@/app/api/orders/export/route";
|
||||
|
||||
function getReq(): NextRequest {
|
||||
return new NextRequest(new URL("/api/orders/export", "http://localhost"), { method: "GET" });
|
||||
}
|
||||
|
||||
describe("GET /api/orders/export — CSV (våg 3.4, DoD §56)", () => {
|
||||
it("emits the documented header row and CRLF line endings", async () => {
|
||||
const r = await exportGET(getReq());
|
||||
expect(r.status).toBe(200);
|
||||
expect(r.headers.get("content-type")).toContain("text/csv");
|
||||
expect(r.headers.get("content-disposition")).toMatch(/^attachment; filename="orders-\d{4}-\d{2}-\d{2}\.csv"$/);
|
||||
const body = await r.text();
|
||||
const lines = body.split("\r\n");
|
||||
expect(lines[0]).toBe("order_id,flow,status,deposit_ore,total_ore");
|
||||
expect(lines[1]).toBe("ord_1,custom,draft,5000,10000");
|
||||
});
|
||||
|
||||
it("RFC4180-quotes fields containing comma/quote (doubled quotes)", async () => {
|
||||
const r = await exportGET(getReq());
|
||||
const body = await r.text();
|
||||
expect(body).toContain('"ord,""2"""');
|
||||
});
|
||||
|
||||
it("exports RAW öre — no locale formatting in the export (öre is canonical)", async () => {
|
||||
const r = await exportGET(getReq());
|
||||
const body = await r.text();
|
||||
expect(body).toContain("ord_1,custom,draft,5000,10000");
|
||||
expect(body).not.toContain("100,00");
|
||||
expect(body).not.toMatch(/\u00A0| kr/);
|
||||
});
|
||||
|
||||
it("no row truncation: export is complete per DoD §56 (cap documented)", async () => {
|
||||
const r = await exportGET(getReq());
|
||||
const body = await r.text();
|
||||
const rows = body.trimEnd().split("\r\n").length - 1;
|
||||
expect(rows).toBe(2);
|
||||
});
|
||||
|
||||
it("auth is fail-closed: the route delegates to requireOrderOwner (401 contract)", async () => {
|
||||
// The mocked requireOrderOwner resolves with an owner; the 401 path is the
|
||||
// auth.response passthrough asserted in tests/api/anonymous-routes-auth.
|
||||
// This test pins the wiring: the handler must return auth.response
|
||||
// verbatim when present, before any store access.
|
||||
const { requireOrderOwner } = await import("@/src/auth/require-order-owner");
|
||||
const mocked = requireOrderOwner as ReturnType<typeof vi.fn>;
|
||||
mocked.mockResolvedValueOnce({
|
||||
response: new Response(JSON.stringify({ error: { code: "unauthorized" } }), { status: 401 }),
|
||||
});
|
||||
const r = await exportGET(getReq());
|
||||
expect(r.status).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* P014: HTTP-level proof that POST /api/orders honors the `Idempotency-Key`
|
||||
* header end to end (route -> lib/orders-store.ts), matching the pattern
|
||||
* used elsewhere in this suite (tests/api/anonymous-routes-auth.test.ts) of
|
||||
* calling the route handler directly with a hand-built NextRequest.
|
||||
*/
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
vi.mock("@/src/auth/require-order-owner", () => ({
|
||||
requireOrderOwner: vi.fn().mockResolvedValue({ owner: { tenantId: "tenant-test", subject: "buyer-test" } }),
|
||||
}));
|
||||
import { POST as ordersPOST } from "@/app/api/orders/route";
|
||||
|
||||
function postReq(body: unknown, headers: Record<string, string> = {}): NextRequest {
|
||||
return new NextRequest(new URL("/api/orders", "http://localhost"), {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...headers },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
const BODY = { flow: "custom", config: { markets: ["SE"], type: "Bolag", fieldIds: ["identity"], volume: 1000 } };
|
||||
const BODY_DIFFERENT = { flow: "custom", config: { markets: ["NO"], type: "Bolag", fieldIds: ["identity"], volume: 9000 } };
|
||||
|
||||
describe("POST /api/orders — Idempotency-Key", () => {
|
||||
it("no header: two identical requests create two distinct orders (201, 201)", async () => {
|
||||
const r1 = await ordersPOST(postReq(BODY));
|
||||
const r2 = await ordersPOST(postReq(BODY));
|
||||
expect(r1.status).toBe(201);
|
||||
expect(r2.status).toBe(201);
|
||||
const b1 = await r1.json();
|
||||
const b2 = await r2.json();
|
||||
expect(b1.order_id).not.toBe(b2.order_id);
|
||||
});
|
||||
|
||||
it("REGRESSION: same Idempotency-Key replays the original order (201 then 200, same order_id)", async () => {
|
||||
const key = `idem_${crypto.randomUUID()}`;
|
||||
const r1 = await ordersPOST(postReq(BODY, { "Idempotency-Key": key }));
|
||||
const r2 = await ordersPOST(postReq(BODY, { "Idempotency-Key": key }));
|
||||
expect(r1.status).toBe(201);
|
||||
expect(r2.status).toBe(200); // replayed, not created
|
||||
const b1 = await r1.json();
|
||||
const b2 = await r2.json();
|
||||
expect(b2.order_id).toBe(b1.order_id);
|
||||
expect(b2.total_ore).toBe(b1.total_ore);
|
||||
});
|
||||
|
||||
it("reusing the same key for a materially different order is a 409, not a silent merge", async () => {
|
||||
const key = `idem_${crypto.randomUUID()}`;
|
||||
const r1 = await ordersPOST(postReq(BODY, { "Idempotency-Key": key }));
|
||||
expect(r1.status).toBe(201);
|
||||
const r2 = await ordersPOST(postReq(BODY_DIFFERENT, { "Idempotency-Key": key }));
|
||||
expect(r2.status).toBe(409);
|
||||
const b2 = await r2.json();
|
||||
expect(b2.error.code).toBe("idempotency_key_conflict");
|
||||
});
|
||||
|
||||
it("header name is case-insensitive (Fetch/Next Headers normalize casing)", async () => {
|
||||
const key = `idem_${crypto.randomUUID()}`;
|
||||
const r1 = await ordersPOST(postReq(BODY, { "idempotency-key": key }));
|
||||
const r2 = await ordersPOST(postReq(BODY, { "IDEMPOTENCY-KEY": key }));
|
||||
expect(r1.status).toBe(201);
|
||||
expect(r2.status).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* C8: tests for POST /api/orders/import — the symmetric counterpart of the
|
||||
* våg-3.4 CSV export and the first real product host of the @siax/ui
|
||||
* ImportWizard kernel. Follows the suite pattern of calling the route handler
|
||||
* directly with a hand-built NextRequest and mocked auth/store/audit.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const mockOwner = { owner: { tenantId: "tenant-test", subject: "buyer-test" } };
|
||||
const requireOrderOwnerMock = vi.fn();
|
||||
vi.mock("@/src/auth/require-order-owner", () => ({
|
||||
requireOrderOwner: (...args: unknown[]) => requireOrderOwnerMock(...args),
|
||||
}));
|
||||
|
||||
const createOrderMock = vi.fn();
|
||||
vi.mock("@/lib/orders-store", () => ({
|
||||
createOrder: (...args: unknown[]) => createOrderMock(...args),
|
||||
}));
|
||||
|
||||
const ingestEventMock = vi.fn().mockResolvedValue({});
|
||||
vi.mock("@/src/clients/aud0-client", () => ({
|
||||
createAud0Client: () => ({ ingestEvent: ingestEventMock }),
|
||||
}));
|
||||
|
||||
import { POST, parseCsv, validateImport, MAX_IMPORT_ROWS } from "@/app/api/orders/import/route";
|
||||
|
||||
function postReq(body: unknown, withAuth = true): NextRequest {
|
||||
requireOrderOwnerMock.mockResolvedValue(withAuth ? mockOwner : { response: NextResponse.json({ error: "OPT_UNAUTHENTICATED" }, { status: 401 }) });
|
||||
return new NextRequest(new URL("/api/orders/import", "http://localhost"), {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
headers: withAuth ? { authorization: "Bearer x" } : {},
|
||||
});
|
||||
}
|
||||
|
||||
const HEADER = "flow,service_type,type,volume,frequency,markets";
|
||||
|
||||
function csv(lines: string[]): string {
|
||||
return [HEADER, ...lines].join("\r\n") + "\r\n";
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
createOrderMock.mockReset();
|
||||
ingestEventMock.mockClear();
|
||||
createOrderMock.mockImplementation(async (flow: string, config: unknown, _key: unknown, owner: { tenantId: string }) => ({
|
||||
order: { order_id: `ord_${createOrderMock.mock.calls.length}`, flow, status: "draft", config, tenant_id: owner.tenantId },
|
||||
replayed: false,
|
||||
}));
|
||||
});
|
||||
|
||||
describe("parseCsv (server-parsed, RFC 4180, no eval)", () => {
|
||||
it("parses quoted fields with doubled quotes", () => {
|
||||
const { rows } = parseCsv('flow,markets\r\ncustom,"A;""B,C"""\r\n');
|
||||
expect(rows[0].flow).toBe("custom");
|
||||
expect(rows[0].markets).toBe('A;"B,C"');
|
||||
});
|
||||
|
||||
it("rejects unknown header columns (fail-closed, never silently dropped)", () => {
|
||||
const { headerError } = parseCsv("flow,evil\r\ncustom,x\r\n");
|
||||
expect(headerError).toMatch(/Okänd kolumn: evil/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateImport — kernel + host rules", () => {
|
||||
it("reports missing required flow as missing_required", () => {
|
||||
const { report } = validateImport(csv([",icp,Bolag,10,Engångs,SE"]));
|
||||
expect(report.errorCount).toBeGreaterThan(0);
|
||||
expect(report.errors.some((e) => e.code === "missing_required")).toBe(true);
|
||||
});
|
||||
|
||||
it("reports bad host fields with row/field/code", () => {
|
||||
const { report } = validateImport(csv(["nope,icp,Bolag,-5,Engångs,SE"]));
|
||||
const fields = report.errors.map((e) => e.field).sort();
|
||||
expect(fields).toContain("flow");
|
||||
expect(fields).toContain("volume");
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/orders/import", () => {
|
||||
it("happy path: execute imports all valid rows through createOrder with the verified owner + emits AUD0", async () => {
|
||||
const r = await POST(postReq({ mode: "execute", csv: csv(["custom,icp,Bolag,10,Engångs,SE", "catalog,icp,Fordon,2,Engångs,", "subscription,,Beslutsfattare,50,Veckovis,SE;NO"]) }));
|
||||
expect(r.status).toBe(200);
|
||||
const body = await r.json();
|
||||
expect(body.imported).toBe(3);
|
||||
expect(body.errors).toHaveLength(0);
|
||||
expect(body.order_ids).toHaveLength(3);
|
||||
expect(createOrderMock).toHaveBeenCalledTimes(3);
|
||||
expect(createOrderMock.mock.calls[0][3]).toEqual({ tenantId: "tenant-test", subject: "buyer-test" });
|
||||
expect(createOrderMock.mock.calls[0][1]).toMatchObject({ service_type: "icp", type: "Bolag", volume: 10, frequency: "Engångs", markets: ["SE"] });
|
||||
expect(createOrderMock.mock.calls[2][1]).toMatchObject({ markets: ["SE", "NO"] });
|
||||
expect(ingestEventMock).toHaveBeenCalledTimes(1);
|
||||
expect(ingestEventMock.mock.calls[0][0]).toMatchObject({ event_type: "0pt.orders.import", tenant_id: "tenant-test", risk_level: "L2" });
|
||||
});
|
||||
|
||||
it("partial success: failing rows are reported per row and never created; passing rows import", async () => {
|
||||
const r = await POST(postReq({ mode: "execute", csv: csv(["custom,icp,Bolag,10,Engångs,SE", "bogus_flow,icp,Bolag,10,Engångs,SE", "catalog,icp,Bolag,notanumber,Engångs,SE"]) }));
|
||||
expect(r.status).toBe(200);
|
||||
const body = await r.json();
|
||||
expect(body.imported).toBe(1);
|
||||
expect(body.errorCount).toBe(2);
|
||||
const badFlow = body.errors.find((e: { field: string }) => e.field === "flow");
|
||||
const badVol = body.errors.find((e: { field: string }) => e.field === "volume");
|
||||
expect(badFlow.row).toBe(2);
|
||||
expect(badVol.row).toBe(3);
|
||||
expect(createOrderMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("validate/dry_run never write (createOrder not called)", async () => {
|
||||
const r1 = await POST(postReq({ mode: "validate", csv: csv(["custom,icp,Bolag,10,Engångs,SE"]) }));
|
||||
expect(r1.status).toBe(200);
|
||||
const b1 = await r1.json();
|
||||
expect(b1.validRows).toBe(1);
|
||||
expect(b1.would_import).toBe(1);
|
||||
const r2 = await POST(postReq({ mode: "dry_run", csv: csv(["custom,icp,Bolag,10,Engångs,SE"]) }));
|
||||
expect(r2.status).toBe(200);
|
||||
expect(createOrderMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fail-closed auth: no principal → 401 and createOrder is never reached", async () => {
|
||||
const r = await POST(postReq({ mode: "execute", csv: csv(["custom,icp,Bolag,10,Engångs,SE"]) }, false));
|
||||
expect(r.status).toBe(401);
|
||||
expect(createOrderMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("row cap: more than MAX_IMPORT_ROWS data rows → 413, no writes", async () => {
|
||||
const lines = Array.from({ length: MAX_IMPORT_ROWS + 1 }, () => "custom,icp,Bolag,10,Engångs,SE");
|
||||
const r = await POST(postReq({ mode: "execute", csv: csv(lines) }));
|
||||
expect(r.status).toBe(413);
|
||||
expect(createOrderMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("unknown header → 400 fail-closed", async () => {
|
||||
const r = await POST(postReq({ mode: "execute", csv: "flow,evil\r\ncustom,x\r\n" }));
|
||||
expect(r.status).toBe(400);
|
||||
const body = await r.json();
|
||||
expect(body.error.code).toBe("bad_header");
|
||||
});
|
||||
|
||||
it("empty/missing csv → 400", async () => {
|
||||
const r = await POST(postReq({ mode: "execute", csv: " " }));
|
||||
expect(r.status).toBe(400);
|
||||
});
|
||||
|
||||
it("execute-time creation failure is reported per row without aborting the batch", async () => {
|
||||
createOrderMock.mockImplementationOnce(async () => {
|
||||
throw new Error("db down");
|
||||
});
|
||||
const r = await POST(postReq({ mode: "execute", csv: csv(["custom,icp,Bolag,10,Engångs,SE", "catalog,icp,Bolag,1,Engångs,SE"]) }));
|
||||
expect(r.status).toBe(200);
|
||||
const body = await r.json();
|
||||
expect(body.imported).toBe(1);
|
||||
expect(body.errors[0].row).toBe(1);
|
||||
expect(body.errors[0].message).toContain("db down");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Route-level test for GET /api/ready (BACKLOG P0-3: "no /ready route
|
||||
* existed at all"). Unlike /api/health, readiness fails closed: 503 when the
|
||||
* load-bearing dependency (db) is not both configured and reachable.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import { GET as readyGET } from "@/app/api/ready/route";
|
||||
|
||||
describe("GET /api/ready", () => {
|
||||
const savedEnv = {
|
||||
DATABASE_URL: process.env.DATABASE_URL,
|
||||
POSTGRES_URL: process.env.POSTGRES_URL,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.DATABASE_URL;
|
||||
delete process.env.POSTGRES_URL;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const [k, v] of Object.entries(savedEnv)) {
|
||||
if (v === undefined) delete process.env[k];
|
||||
else process.env[k] = v;
|
||||
}
|
||||
});
|
||||
|
||||
it("fails closed with 503 when the database is not configured", async () => {
|
||||
const res = await readyGET();
|
||||
expect(res.status).toBe(503);
|
||||
const body = await res.json();
|
||||
expect(body.ready).toBe(false);
|
||||
expect(body.db).toBe("not_configured");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { NextRequest } from 'next/server';
|
||||
import { GET as screen } from '@/app/api/screen/route';
|
||||
import { GET as vehicles } from '@/app/api/vehicles/route';
|
||||
|
||||
const originalEngine = process.env.ENGINE_URL;
|
||||
afterEach(() => { if (originalEngine === undefined) delete process.env.ENGINE_URL; else process.env.ENGINE_URL = originalEngine; vi.unstubAllGlobals(); });
|
||||
const screening = () => screen(new NextRequest('http://localhost/api/screen?q=example'));
|
||||
const vehicle = () => vehicles(new NextRequest('http://localhost/api/vehicles?plate=AB123'));
|
||||
|
||||
describe('source failure cannot mean absence', () => {
|
||||
it.each([screening, vehicle])('returns 503 for source failures and malformed responses', async (call) => {
|
||||
delete process.env.ENGINE_URL;
|
||||
for (const response of [new Response('down', { status: 503 }), Response.json({}), new Response('{')]) {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => response));
|
||||
const result = await call();
|
||||
expect(result.status).toBe(503);
|
||||
expect(await result.json()).toEqual({ error: expect.objectContaining({ code: 'source_unavailable' }) });
|
||||
}
|
||||
});
|
||||
it('preserves an actual empty screening result', async () => {
|
||||
delete process.env.ENGINE_URL;
|
||||
vi.stubGlobal('fetch', vi.fn(async () => Response.json({ results: [] })));
|
||||
expect(await (await screening()).json()).toEqual({ source: 'opensanctions', matches: [] });
|
||||
});
|
||||
it('preserves an actual missing vehicle', async () => {
|
||||
delete process.env.ENGINE_URL;
|
||||
vi.stubGlobal('fetch', vi.fn(async () => Response.json([])));
|
||||
expect(await (await vehicle()).json()).toEqual({ vehicle: null });
|
||||
});
|
||||
it.each([screening, vehicle])('does not trust an old engine which can fabricate empty results', async (call) => {
|
||||
process.env.ENGINE_URL = 'https://engine.test';
|
||||
vi.stubGlobal('fetch', vi.fn(async () => Response.json({ matches: [], vehicle: null })));
|
||||
expect((await call()).status).toBe(503);
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
});
|
||||
it('accepts verified engine screening results', async () => {
|
||||
process.env.ENGINE_URL = 'https://engine.test';
|
||||
vi.stubGlobal('fetch', vi.fn(async () => Response.json({ source: 'opensanctions', source_status: 'ok', matches: [] })));
|
||||
expect((await screening()).status).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ create: vi.fn(), setStatus: vi.fn(), auth: vi.fn() }));
|
||||
vi.mock("@/lib/stripe", () => ({
|
||||
getStripe: () => ({ checkout: { sessions: { create: mocks.create } } }),
|
||||
}));
|
||||
vi.mock("@/lib/orders-store", () => ({
|
||||
getOwnedOrder: vi.fn().mockResolvedValue({ order_id: "order-1", status: "accepted", balance_ore: 5000 }),
|
||||
setStatus: mocks.setStatus,
|
||||
}));
|
||||
vi.mock("@/src/auth/require-order-owner", () => ({
|
||||
requireOrderOwner: mocks.auth,
|
||||
}));
|
||||
|
||||
import { POST } from "@/app/api/payments/[order_id]/release/route";
|
||||
import { getOwnedOrder } from "@/lib/orders-store";
|
||||
|
||||
it("does not mark delivery complete merely by creating a balance Checkout Session", async () => {
|
||||
mocks.auth.mockResolvedValue({ owner: { tenantId: "verified-tenant", subject: "buyer-1" } });
|
||||
mocks.create.mockResolvedValue({ url: "https://checkout.stripe.com/test" });
|
||||
const req = new NextRequest("https://0pt.app/api/payments/order-1/release", { method: "POST" });
|
||||
|
||||
const res = await POST(req, { params: Promise.resolve({ order_id: "order-1" }) });
|
||||
expect(res.status).toBe(200);
|
||||
expect(getOwnedOrder).toHaveBeenCalledWith("order-1", "verified-tenant");
|
||||
expect(mocks.create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
metadata: { order_id: "order-1", kind: "balance" },
|
||||
}));
|
||||
expect(mocks.setStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unauthenticated balance Checkout request", async () => {
|
||||
mocks.create.mockClear();
|
||||
mocks.auth.mockResolvedValue({ response: NextResponse.json({ error: "unauthenticated" }, { status: 401 }) });
|
||||
const req = new NextRequest("https://0pt.app/api/payments/order-1/release", { method: "POST" });
|
||||
|
||||
expect((await POST(req, { params: Promise.resolve({ order_id: "order-1" }) })).status).toBe(401);
|
||||
expect(mocks.create).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/orders-store", () => ({
|
||||
getOwnedOrder: vi.fn().mockResolvedValue({ order_id: "order-1", deposit_ore: 5000 }),
|
||||
}));
|
||||
vi.mock("@/src/auth/require-order-owner", () => ({
|
||||
requireOrderOwner: vi.fn().mockResolvedValue({ owner: { tenantId: "tenant-test", subject: "buyer-test" } }),
|
||||
}));
|
||||
|
||||
import { POST } from "@/app/api/payments/[order_id]/deposit/route";
|
||||
import { getOwnedOrder } from "@/lib/orders-store";
|
||||
|
||||
const savedKey = process.env.STRIPE_SECRET_KEY;
|
||||
const savedFetch = globalThis.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
if (savedKey === undefined) delete process.env.STRIPE_SECRET_KEY;
|
||||
else process.env.STRIPE_SECRET_KEY = savedKey;
|
||||
globalThis.fetch = savedFetch;
|
||||
});
|
||||
|
||||
it("binds a deposit Checkout Session to its order and payment kind", async () => {
|
||||
process.env.STRIPE_SECRET_KEY = "sk_test_fake_local_regression";
|
||||
const mockFetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ url: "https://checkout.stripe.com/test" }),
|
||||
});
|
||||
globalThis.fetch = mockFetch;
|
||||
|
||||
const req = new NextRequest("https://0pt.app/api/payments/order-1/deposit", { method: "POST" });
|
||||
const res = await POST(req, { params: Promise.resolve({ order_id: "order-1" }) });
|
||||
expect(res.status).toBe(200);
|
||||
expect(getOwnedOrder).toHaveBeenCalledWith("order-1", "tenant-test");
|
||||
const init = mockFetch.mock.calls[0]?.[1] as RequestInit;
|
||||
const body = init.body as URLSearchParams;
|
||||
expect(body.get("metadata[order_id]")).toBe("order-1");
|
||||
expect(body.get("metadata[kind]")).toBe("deposit");
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { POST } from "@/app/api/webhooks/stripe/route";
|
||||
|
||||
const savedSecretKey = process.env.STRIPE_SECRET_KEY;
|
||||
const savedWebhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
|
||||
|
||||
afterEach(() => {
|
||||
if (savedSecretKey === undefined) delete process.env.STRIPE_SECRET_KEY;
|
||||
else process.env.STRIPE_SECRET_KEY = savedSecretKey;
|
||||
if (savedWebhookSecret === undefined) delete process.env.STRIPE_WEBHOOK_SECRET;
|
||||
else process.env.STRIPE_WEBHOOK_SECRET = savedWebhookSecret;
|
||||
});
|
||||
|
||||
it("does not acknowledge an unverified Stripe event when credentials are absent", async () => {
|
||||
delete process.env.STRIPE_SECRET_KEY;
|
||||
delete process.env.STRIPE_WEBHOOK_SECRET;
|
||||
const req = new NextRequest("https://0pt.app/api/webhooks/stripe", {
|
||||
method: "POST",
|
||||
headers: { "stripe-signature": "unverified" },
|
||||
body: "{}",
|
||||
});
|
||||
|
||||
const res = await POST(req);
|
||||
expect(res.status).toBe(503);
|
||||
expect(await res.json()).toEqual({ received: false, reason: "not_configured" });
|
||||
});
|
||||
|
||||
it("rejects a delivery with no Stripe signature even when configured", async () => {
|
||||
process.env.STRIPE_SECRET_KEY = "sk_test_fake_local_regression";
|
||||
process.env.STRIPE_WEBHOOK_SECRET = "whsec_fake_local_regression";
|
||||
const req = new NextRequest("https://0pt.app/api/webhooks/stripe", {
|
||||
method: "POST",
|
||||
body: "{}",
|
||||
});
|
||||
|
||||
const res = await POST(req);
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.json()).toEqual({ error: "missing_signature" });
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
constructEvent: vi.fn(),
|
||||
getOrder: vi.fn(),
|
||||
setStatusIfCurrent: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/stripe", () => ({
|
||||
getStripe: () => ({ webhooks: { constructEvent: mocks.constructEvent } }),
|
||||
}));
|
||||
vi.mock("@/lib/orders-store", () => ({
|
||||
getOrder: mocks.getOrder,
|
||||
setStatusIfCurrent: mocks.setStatusIfCurrent,
|
||||
}));
|
||||
|
||||
import { POST } from "@/app/api/webhooks/stripe/route";
|
||||
|
||||
const savedWebhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
|
||||
const owner = { tenant_id: "tenant-test", buyer_subject: "buyer-test" };
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.STRIPE_WEBHOOK_SECRET = "whsec_fake_local_regression";
|
||||
mocks.constructEvent.mockReset();
|
||||
mocks.getOrder.mockReset();
|
||||
mocks.setStatusIfCurrent.mockReset();
|
||||
mocks.setStatusIfCurrent.mockResolvedValue({ order_id: "order-1" });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (savedWebhookSecret === undefined) delete process.env.STRIPE_WEBHOOK_SECRET;
|
||||
else process.env.STRIPE_WEBHOOK_SECRET = savedWebhookSecret;
|
||||
});
|
||||
|
||||
function delivery() {
|
||||
return new NextRequest("https://0pt.app/api/webhooks/stripe", {
|
||||
method: "POST",
|
||||
headers: { "stripe-signature": "signed-in-test" },
|
||||
body: "{}",
|
||||
});
|
||||
}
|
||||
|
||||
function session(kind: "deposit" | "balance", paymentStatus: string, amount: number) {
|
||||
mocks.constructEvent.mockReturnValue({
|
||||
type: "checkout.session.completed",
|
||||
data: { object: {
|
||||
metadata: { order_id: "order-1", kind },
|
||||
payment_status: paymentStatus,
|
||||
amount_total: amount,
|
||||
currency: "sek",
|
||||
} },
|
||||
});
|
||||
}
|
||||
|
||||
it("advances a matching paid deposit only after a verified event", async () => {
|
||||
session("deposit", "paid", 5000);
|
||||
mocks.getOrder.mockResolvedValue({ order_id: "order-1", ...owner, status: "draft", deposit_ore: 5000, balance_ore: 5000 });
|
||||
|
||||
expect((await POST(delivery())).status).toBe(200);
|
||||
expect(mocks.setStatusIfCurrent).toHaveBeenCalledWith("order-1", "draft", "in_production");
|
||||
});
|
||||
|
||||
it("never advances an unpaid or amount-mismatched deposit", async () => {
|
||||
mocks.getOrder.mockResolvedValue({ order_id: "order-1", ...owner, status: "draft", deposit_ore: 5000, balance_ore: 5000 });
|
||||
session("deposit", "unpaid", 5000);
|
||||
expect((await POST(delivery())).status).toBe(503);
|
||||
session("deposit", "paid", 4999);
|
||||
expect((await POST(delivery())).status).toBe(422);
|
||||
expect(mocks.setStatusIfCurrent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("marks a matching paid balance delivered only after acceptance", async () => {
|
||||
session("balance", "paid", 5000);
|
||||
mocks.getOrder.mockResolvedValue({ order_id: "order-1", ...owner, status: "accepted", deposit_ore: 5000, balance_ore: 5000 });
|
||||
|
||||
expect((await POST(delivery())).status).toBe(200);
|
||||
expect(mocks.setStatusIfCurrent).toHaveBeenCalledWith("order-1", "accepted", "delivered");
|
||||
});
|
||||
|
||||
it("does not acknowledge a paid event for a legacy anonymous draft", async () => {
|
||||
session("deposit", "paid", 5000);
|
||||
mocks.getOrder.mockResolvedValue({ order_id: "order-1", status: "draft", deposit_ore: 5000 });
|
||||
expect((await POST(delivery())).status).toBe(503);
|
||||
expect(mocks.setStatusIfCurrent).not.toHaveBeenCalled();
|
||||
});
|
||||
Reference in New Issue
Block a user