Files
0pt/src/clients/cl0ud-client.ts
T
Simon AxelssonandClaude Fable 5 b7038d7675 feat(platform): canonical SIAX context/errors + real-contract clients, no prod mock fallback
- src/platform/: SiaxRequestContext + propagation headers + 12 canonical
  error codes (documented mirror of cl0ud packages/contract), SiaxError,
  resource refs (st0re:artifact:...), and the §3/§10 dependency-mode guard:
  production runtime + unconfigured dependency/store => hard
  DEPENDENCY_UNAVAILABLE at construction, never silent mock/in-memory.
- src/clients/: all four platform clients rewritten against the REAL wire
  contracts verified on sibling main branches this session:
  * cl0ud: POST /api/policy/evaluate ({data} envelope, allow+requiresApproval)
    - the old /v1/cl0ud/policies/evaluate path never existed on CL0UD
  * st0re: camelCase ArtifactInput on /v1/st0re/artifacts/register incl.
    X-Tenant-Id/X-Actor-Id + X-Idempotency-Key - the old snake_case body
    would have been a 400 against the live registry
  * n0d: required_role + resource_requirements + body idempotency_key +
    CloudEvents callback_url per n0d createJobSchema; adds getJob/getJobResult
  * aud0: /v1/aud0/openlineage is AUD0's only lineage ingest -
    /v1/aud0/lineage/events never existed; legacy shape converts to a
    spec-shaped OpenLineage RunEvent (deterministic runId dedup)
- src/lineage/: OpenLineage subset types + LineageEmitter (never-throw,
  §16 evidence semantics)
- shared SiaxHttp transport: timeouts, typed SiaxError mapping, context
  propagation, no raw upstream bodies in errors

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-31 16:35:01 +02:00

168 lines
6.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* src/clients/cl0ud-client.ts
* ============================
* 0pt's ONLY path to the CL0UD control-plane policy decision point.
*
* REWRITTEN 2026-08-31 against CL0UD's REAL wire contract (cl0ud main,
* `packages/contract/openapi.yaml` + `apps/console/app/api/policy/evaluate/
* route.ts`, verified this session):
*
* evaluatePolicy -> POST {baseUrl}/api/policy/evaluate
* listCapabilities -> GET {baseUrl}/api/capabilities
*
* The earlier client POSTed snake_case to `/v1/cl0ud/policies/evaluate` — a
* path that has never existed on CL0UD. That was exactly the MOCK_ONLY trap
* the Master-DoD audit predicted: the mock worked, the HTTP path had never
* been exercised against the real contract. The real contract is camelCase,
* envelope `{ data, meta }`, decision ∈ {allow, deny} plus a separate
* `requiresApproval` flag (allow+requiresApproval = route into approval, NOT
* a deny). 0pt maps that pair onto its historical three-value
* `PolicyDecisionValue` so existing call sites keep their exact semantics:
* anything other than plain "allow" aborts the caller.
*
* Production fallback policy (Master-DoD §3/§10): `createCl0udClient()`
* without a base URL THROWS `SiaxError("DEPENDENCY_UNAVAILABLE")` in a
* production runtime (NODE_ENV=production). The allow-only local
* pass-through survives ONLY for non-production runtimes (unit tests, local
* dev) — it never invents a deny, and it stamps a clearly local decision id.
* Policy itself remains fail-closed: a configured CL0UD answering 200 with a
* body missing `decision` is read as deny, never allow.
*/
import crypto from "crypto";
import { SiaxHttp } from "./http";
import { resolveDependencyBaseUrl } from "../platform/dependency-mode";
import type { SiaxRequestContext } from "../platform/siax-context";
/** The decision vocabulary 0pt call sites consume (unchanged). */
export type PolicyDecisionValue = "allow" | "deny" | "approval_required";
export interface EvaluatePolicyInput {
tenant_id: string;
project_id: string;
actor_id: string;
capability_id: string;
resource_type: string;
resource_id: string;
/** Risk level L0–L5 per the SIAX Cloud risk taxonomy. */
risk_level: string;
correlation_id?: string;
/**
* The CL0UD actor descriptor. 0pt calls CL0UD as a platform service, and
* cl0ud's resolve-actor only lets an OPERATOR principal name an arbitrary
* actor — default is therefore `{ kind: "operator", role: "member" }`.
*/
actor?: { kind: "customer" | "operator"; role: "owner" | "admin" | "member" | "viewer" };
}
/** The decision record 0pt call sites consume (unchanged shape). */
export interface PolicyDecision {
decision: PolicyDecisionValue;
decision_id: string;
reason?: string;
/** CL0UD's deny code when decision = "deny" (e.g. rbac_forbidden). */
deny_code?: string;
}
/** Alias so both historical import names resolve to the same shape. */
export type PolicyResult = PolicyDecision;
/** One CL0UD capability-registry entry (discovery API, tolerant-reader subset). */
export interface Cl0udCapability {
name: string;
version: string;
owner: string;
status?: "beta" | "active" | "deprecated" | "retired";
deprecation?: { since: string; replacement?: string; sunsetAt?: string; note?: string };
requiredEntitlement?: string;
surfaces?: string[];
[extra: string]: unknown;
}
export interface Cl0udClient {
evaluatePolicy(input: EvaluatePolicyInput, context?: SiaxRequestContext): Promise<PolicyDecision>;
listCapabilities(
filter?: { owner?: string; surface?: string; status?: string; version?: string },
context?: SiaxRequestContext
): Promise<Cl0udCapability[]>;
}
export function createCl0udClient(baseUrl?: string, opts?: { token?: string }): Cl0udClient {
const resolved = resolveDependencyBaseUrl("cl0ud", baseUrl ?? process.env.CL0UD_URL);
if (!resolved) return new LocalAllowCl0udClient();
return new HttpCl0udClient(resolved, opts?.token ?? process.env.CL0UD_SERVICE_TOKEN);
}
/**
* Non-production runtimes only (the factory has already thrown in
* production): allow-only local pass-through, empty capability catalog.
*/
class LocalAllowCl0udClient implements Cl0udClient {
async evaluatePolicy(_input: EvaluatePolicyInput): Promise<PolicyDecision> {
return { decision: "allow", decision_id: `pdec_local_${crypto.randomUUID()}` };
}
async listCapabilities(): Promise<Cl0udCapability[]> {
return [];
}
}
class HttpCl0udClient implements Cl0udClient {
private readonly http: SiaxHttp;
constructor(baseUrl: string, token?: string) {
this.http = new SiaxHttp({ dependency: "cl0ud", baseUrl, token });
}
async evaluatePolicy(input: EvaluatePolicyInput, context?: SiaxRequestContext): Promise<PolicyDecision> {
const res = await this.http.request({
method: "POST",
path: "/api/policy/evaluate",
context,
body: {
capability: input.capability_id,
actor: input.actor ?? { kind: "operator", role: "member" },
tenantId: input.tenant_id,
projectId: input.project_id,
surface: "api",
resource: { type: input.resource_type, id: input.resource_id },
...(input.correlation_id ? { correlationId: input.correlation_id } : {}),
},
});
const data = (res.json as { data?: Record<string, unknown> } | undefined)?.data;
const rawDecision = data?.decision;
// FAIL CLOSED: 200 with a missing/unknown decision is a deny, never allow.
let decision: PolicyDecisionValue = "deny";
if (rawDecision === "allow") {
decision = data?.requiresApproval === true ? "approval_required" : "allow";
} else if (rawDecision === "deny") {
decision = "deny";
}
return {
decision,
decision_id:
typeof data?.decisionId === "string" ? data.decisionId : `pdec_${crypto.randomUUID()}`,
reason: typeof data?.reason === "string" ? data.reason : undefined,
deny_code: typeof data?.denyCode === "string" ? data.denyCode : undefined,
};
}
async listCapabilities(
filter?: { owner?: string; surface?: string; status?: string; version?: string },
context?: SiaxRequestContext
): Promise<Cl0udCapability[]> {
const res = await this.http.request({
method: "GET",
path: "/api/capabilities",
context,
query: {
owner: filter?.owner,
surface: filter?.surface,
status: filter?.status,
version: filter?.version,
},
});
const data = (res.json as { data?: unknown } | undefined)?.data;
return Array.isArray(data) ? (data as Cl0udCapability[]) : [];
}
}