Files
0pt/src/http/tenant-guard.ts
T
SIAX Agent b97ad0b2f4
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (push) Successful in 4s
masterplan-lock / check (pull_request) Successful in 4s
CI (SIAX Cloud) / security (pull_request) Successful in 16s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 16s
CI (SIAX Cloud) / integration (pull_request) Successful in 36s
CI (SIAX Cloud) / quality (pull_request) Successful in 10m24s
fix(auth): bind internal-service tenant authority to server config
The first revision of this fix copied a CLIENT header (X-0pt-Internal-Tenant)
or a single INTERNAL_TENANT_ID into x-0pt-verified-tenant. That is not an
authorization source: any holder of the shared internal token could still name
any tenant, leaving the original cross-tenant write reachable through a
different header.

- INTERNAL_SERVICE_TENANTS (server env) is now the only tenant authority for
  the X-Internal-Token principal; empty => no authority (fail closed, 403).
- Middleware strips inbound x-0pt-verified-{tenant,sub} and the service scope
  header on every path, including the dev escape hatch.
- x-0pt-verified-service-tenants carries the allowlist; the tenant guard checks
  membership and denies anything outside it.
- POST /api/0pt/quality/bridge-run now runs the same tenant guard as
  canonical/facts (it auto-provisions tenant-scoped rules).
- 16 new regression tests; auth + cross-tenant + canonical + bridge suites
  87/87; tsc --noEmit clean.
2026-11-07 15:32:51 +01:00

109 lines
5.2 KiB
TypeScript

/**
* src/http/tenant-guard.ts
* ==========================
* P014 fix: every route under `app/api/0pt/**` sits behind `middleware.ts`,
* which performs real Zitadel Bearer verification and — only when a
* principal was actually verified — forwards the result as the
* `x-0pt-verified-tenant` request header (see middleware.ts, src/auth/context.ts).
*
* Independently of that, every one of these route handlers reads `tenant_id`
* from CLIENT-CONTROLLED input (a `?tenant_id=` query param or a JSON body
* field) to decide which tenant's rows to read or write. Until this pass,
* NONE of them cross-checked that client-supplied value against the verified
* header — so a caller holding a valid token for tenant A could read or
* write tenant B's sources, rights, provenance, health, quality rules/runs,
* documents, or lakehouse mappings simply by naming `tenant_id=t_b` in the
* request. `SourceRegistryService.assertSourceTenant` (and friends) only
* checks that the object being read *belongs* to the tenant_id it was asked
* to check against — it has no way to know whether the CALLER is actually
* entitled to assert that tenant_id in the first place. That entitlement
* check belongs at the HTTP boundary, once, here.
*
* This mirrors the exact decision `src/auth/context.ts`'s `resolveAuthContext`
* already makes for the enforced-Bearer path ("a disagreeing X-Tenant-Id
* header is a 403"), applied uniformly to every 0pt capability route that
* takes tenant_id as a body/query parameter rather than relying on
* middleware to inject ctx.tenantId directly (most of these routes predate
* that plumbing and read tenant_id straight from the request; fixing that
* more deeply is a larger refactor than this pass — this closes the actual
* authz hole without changing every route's request contract).
*/
import { NextResponse, type NextRequest } from "next/server";
import { readServiceTenantScope } from "@/src/auth/internal-service-tenant";
export const VERIFIED_TENANT_HEADER = "x-0pt-verified-tenant";
/**
* Returns a 403 NextResponse when `tenantId` (whatever the route read it
* from — query string or body) disagrees with the tenant middleware.ts
* already verified for this request. Returns `null` when the caller may
* proceed — either because the tenant matches, or because no verified
* tenant is present on the request at all.
*
* The header is absent only in the explicit local-development escape hatch
* (`AUTH_ENFORCE=false` with no bearer token presented) — `assertAuthConfigSafe()`
* refuses to boot that way in production, so an absent header here can only
* happen in a mode that already accepts fully unauthenticated requests.
* Rejecting in that mode would be strictly more restrictive than the
* existing dev escape hatch intends, so this deliberately no-ops rather than
* invents a tenant to compare against.
*/
export function assertTenantMatchesVerified(
request: NextRequest,
tenantId: string | null | undefined,
): NextResponse | null {
const verified = request.headers.get(VERIFIED_TENANT_HEADER);
// Internal service principal: tenant authority is the SERVER-CONFIGURED
// allowlist middleware installed (never a client header). The scope header is
// present even when the allowlist is empty, which means "no tenant
// authority" -> fail closed. Routes that do not take a tenant never call
// this guard, so evidence dispatch / ER / search definitions keep working.
if (request.headers.get("x-0pt-verified-service-tenants") !== null) {
if (!tenantId) return null; // handlers already 400 on a missing tenant_id separately
const scope = readServiceTenantScope(request.headers);
if (!scope.includes(tenantId)) {
return NextResponse.json(
{
error: "OPT_ACCESS_DENIED",
message: "tenant_id is outside the internal service principal's configured tenant scope",
details: { requested_tenant: tenantId, service_tenant_scope: scope },
},
{ status: 403 },
);
}
return null;
}
if (!verified) return null;
if (!tenantId) return null; // handlers already 400 on a missing tenant_id separately
if (tenantId !== verified) {
return NextResponse.json(
{
error: "OPT_ACCESS_DENIED",
message: "tenant_id disagrees with the authenticated token's tenant",
details: { requested_tenant: tenantId, verified_tenant: verified },
},
{ status: 403 },
);
}
return null;
}
/** Bind document operations to middleware's verified subject; never accept a conflicting body actor. */
export function resolveDocumentActor(
request: NextRequest,
requestedActor: string | undefined,
): { actorId?: string; response?: NextResponse } {
const verified = request.headers.get('x-0pt-verified-sub');
if (verified && requestedActor && requestedActor !== verified) {
return {
response: NextResponse.json(
{ error: 'OPT_ACCESS_DENIED', message: 'actor_id disagrees with the authenticated token subject' },
{ status: 403 },
),
};
}
// Absence is the existing unauthenticated development path. In enforced
// mode middleware always installs the verified subject before this route.
return { actorId: verified || requestedActor };
}