Files
0pt/middleware.ts
T
admin 849e7ae802
masterplan-lock / check (push) Successful in 4s
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 5s
CI (SIAX Cloud) / security (pull_request) Successful in 15s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 43s
CI (SIAX Cloud) / integration (pull_request) Successful in 10m3s
CI (SIAX Cloud) / quality (pull_request) Successful in 10m15s
fix(auth): internal-token requests får verifierad tenant (P0 tenant-isolering)
Bevisat: POST /api/0pt/canonical/facts med X-Internal-Token och tenant_id
999999999999999999 returnerade 201 och skrev data i annan tenant. Orsak:
internal-token-grenen returnerade next() utan x-0pt-verified-tenant, så
assertTenantMatchesVerified blev no-op.

Fix: INTERNAL_TENANT_ID (eller X-0pt-Internal-Tenant) sätts som verifierad
tenant, vilket gör guard-enforcement identisk med verifierad Bearer. Varnar
om variabeln saknas.
2026-11-07 14:55:59 +01:00

115 lines
4.3 KiB
TypeScript

/**
* Next.js auth seam for the complete /api/0pt capability surface.
*
* Customer calls use verified Zitadel bearer identity and receive immutable
* x-0pt-verified-* headers. Explicit machine routes may instead use the
* shared X-Internal-Token convention; mutation handlers verify it again for
* defence in depth. The canonical-fact write is one such explicit machine route.
*/
import { NextResponse, type NextRequest } from 'next/server';
import { assertAuthConfigSafe, resolveAuthContext } from '@/src/auth/context';
import { SESSION_COOKIE, verifySession } from '@/lib/auth';
import { verifyInternalServiceToken } from '@/src/auth/internal-token';
assertAuthConfigSafe();
export const config = {
matcher: ['/api/0pt', '/api/0pt/:path*'],
};
const EXEMPT_PATTERNS: RegExp[] = [
/^\/api\/health(\/|$)/,
/^\/api\/ready(\/|$)/,
/^\/api\/admin\/metrics(\/|$)/,
];
/** Routes that may be reached with a service token instead of end-user bearer auth. */
const INTERNAL_SERVICE_ROUTES: RegExp[] = [
/^\/api\/0pt\/quality\/bridge-run$/,
// Acquisition engine -> 0pt canonical observation write (machine-to-machine,
// same X-Internal-Token class as the quality bridge; not a blanket bypass).
/^\/api\/0pt\/canonical\/facts$/,
/^\/api\/0pt\/internal\/evidence-outbox\/dispatch$/,
/^\/api\/0pt\/internal\/er\/candidates$/,
/^\/api\/0pt\/search\/definitions$/,
];
let _authDiagCount = 0;
let internalTenantWarned = false;
export async function middleware(req: NextRequest): Promise<NextResponse> {
const path = req.nextUrl.pathname;
if (EXEMPT_PATTERNS.some((re) => re.test(path))) return NextResponse.next();
if (INTERNAL_SERVICE_ROUTES.some((re) => re.test(path)) && verifyInternalServiceToken(req.headers)) {
// P014/P0 tenant isolation (2026-11-07): the internal-token path used to
// return next() WITHOUT a verified tenant, which made
// assertTenantMatchesVerified a no-op and let a service principal write
// ANY tenant_id (proven: POST canonical/facts with tenant_id
// 999999999999999999 returned 201). When INTERNAL_TENANT_ID is configured
// the guard is now enforced exactly like a verified Bearer principal.
const forwarded = new Headers(req.headers);
const internalTenant =
req.headers.get('x-0pt-internal-tenant') ?? process.env.INTERNAL_TENANT_ID;
if (internalTenant) {
forwarded.set('x-0pt-verified-tenant', internalTenant);
} else if (!internalTenantWarned) {
internalTenantWarned = true;
console.warn(
'[0pt-auth] INTERNAL_TENANT_ID is unset: internal-token requests are not tenant-scoped (set it in production)',
);
}
return NextResponse.next({ request: { headers: forwarded } });
}
if (_authDiagCount < 5) {
_authDiagCount += 1;
const hasAuth = !!req.headers.get('authorization');
console.log(
`[0pt-auth] middleware path=${path} auth_header=${hasAuth} ` +
`auth_enforce=${process.env.AUTH_ENFORCE ?? 'unset'} ` +
`node_env=${process.env.NODE_ENV ?? 'unset'} request#${_authDiagCount}`,
);
}
// Browser sessions (Zitadel OIDC -> signed cookie) are a first-class
// principal for the portal. A Bearer token always wins when present.
if (!req.headers.get('authorization')) {
const session = await verifySession(req.cookies.get(SESSION_COOKIE)?.value);
if (
session &&
typeof session.sub === 'string' &&
typeof session.tenantId === 'string' &&
typeof session.exp === 'number' &&
session.exp > Date.now()
) {
const forwarded = new Headers(req.headers);
forwarded.set('x-0pt-verified-sub', session.sub);
forwarded.set('x-0pt-verified-tenant', session.tenantId);
return NextResponse.next({ request: { headers: forwarded } });
}
}
const decision = await resolveAuthContext(req.headers);
if (!decision.ok) {
return NextResponse.json(
{
error: decision.code,
message: decision.message,
...(decision.details ? { details: decision.details } : {}),
},
{ status: decision.status },
);
}
const principal = decision.ctx.principal;
if (principal) {
const forwarded = new Headers(req.headers);
forwarded.set('x-0pt-verified-sub', principal.sub);
forwarded.set('x-0pt-verified-tenant', principal.tenantId);
return NextResponse.next({ request: { headers: forwarded } });
}
return NextResponse.next();
}