Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6aa1f76657 |
@@ -58,16 +58,6 @@ DEV_LOGIN_KEY=
|
||||
# Shared token for internal/service-to-service calls; sent as X-Internal-Token
|
||||
# on every engineFetch() call (lib/engine.ts).
|
||||
INTERNAL_TOKEN=change-me-internal-token
|
||||
# Tenant authority for the internal-token principal. Comma-separated allowlist
|
||||
# of tenants this deployment's engine is entitled to write for, e.g.
|
||||
# "379976258701823235". This is the ONLY source of tenant authority for
|
||||
# X-Internal-Token: a request header may never name a tenant. Empty/unset means
|
||||
# the service principal has no tenant authority and tenant-scoped writes
|
||||
# (canonical facts, quality bridge runs) are denied with 403. Exactly ONE
|
||||
# tenant is supported: the shared token identifies one service process, not a
|
||||
# set of principals. A multi-tenant list is refused (401) until a verified
|
||||
# workload-identity binding exists.
|
||||
INTERNAL_SERVICE_TENANTS=
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Zitadel / OIDC Bearer verification (Wave 2 hardening) -- wired in code today
|
||||
@@ -290,11 +280,6 @@ OPT_CREDIT_PRICE_BOOK=
|
||||
# purchases stay disabled. Unset/`on` requires the price book + ledger.
|
||||
OPT_CREDITS_MODE=
|
||||
|
||||
# One-time trial credits granted per tenant (server-owned, idempotent, NOT a
|
||||
# payment). 0 disables. With OPT_CREDITS_MODE=on this lets reserve/settle run
|
||||
# in production before any customer purchase.
|
||||
OPT_TRIAL_CREDITS=0
|
||||
|
||||
# Central Keycloak (SIAX Portal)
|
||||
KEYCLOAK_ISSUER=https://auth.portal.siax.dev/realms/portal
|
||||
KEYCLOAK_EXPECTED_AUDIENCE=account
|
||||
|
||||
+2
-55
@@ -36,8 +36,6 @@ jobs:
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
- name: Enable corepack + pin pnpm@9 (pnpm-lock.yaml is lockfileVersion 9.0)
|
||||
run: |
|
||||
corepack enable
|
||||
@@ -97,9 +95,6 @@ jobs:
|
||||
# cluster_name (the OpenSearch image maps dotted env keys to
|
||||
# settings).
|
||||
cluster.name: opt_ci_${{ github.run_id }}_${{ github.run_attempt }}
|
||||
# Throwaway CI cluster: never let the runner's disk fill turn indices
|
||||
# read-only (the 403 index_create_block_exception seen in run 388536).
|
||||
cluster.routing.allocation.disk.threshold_enabled: "false"
|
||||
# `--workdir` is REQUIRED (measured 2026-08-31, PR #25 CI run 7745,
|
||||
# job "integration"): this runner's act_runner (v0.6.1) merges the
|
||||
# JOB's WorkingDir (`/workspace/sax3l/0pt`) into every SERVICE
|
||||
@@ -137,8 +132,6 @@ jobs:
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
- name: Enable corepack + pin pnpm@9
|
||||
run: |
|
||||
corepack enable
|
||||
@@ -156,33 +149,6 @@ jobs:
|
||||
if [ "$NAME" = "$WANT" ]; then FOUND="$ip"; fi
|
||||
done
|
||||
[ -n "$FOUND" ] || { echo "FATAL: no OpenSearch behind the alias identifies as $WANT"; exit 1; }
|
||||
|
||||
# The single-node test cluster inherits the runner's disk watermark.
|
||||
# On a busy runner the flood-stage watermark makes every new index
|
||||
# read-only and the suite fails with HTTP 403
|
||||
# index_create_block_exception (measured on run 388536). The container
|
||||
# is throwaway CI state, so disable the disk threshold and PROVE that
|
||||
# index creation works before the blocking tests run.
|
||||
for attempt in 1 2 3 4 5; do
|
||||
# Disabling the watermark alone does NOT clear a cluster that is
|
||||
# already read-only: the flood stage sets
|
||||
# cluster.blocks.read_only_allow_delete and every write keeps
|
||||
# returning 403. Clear that block explicitly every attempt.
|
||||
curl -sS --max-time 10 -X PUT "http://$FOUND:9200/_cluster/settings" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"persistent":{"cluster.routing.allocation.disk.threshold_enabled":false,"cluster.blocks.read_only_allow_delete":null}}' >/tmp/os-settings.json || true
|
||||
cat /tmp/os-settings.json 2>/dev/null || true
|
||||
probe_status=$(curl -sS --max-time 10 -o /tmp/os-probe.json -w '%{http_code}' -X PUT "http://$FOUND:9200/opt-ci-probe-${{ github.run_id }}")
|
||||
if [ "$probe_status" = "200" ]; then
|
||||
curl -fsS --max-time 10 -X DELETE "http://$FOUND:9200/opt-ci-probe-${{ github.run_id }}" >/dev/null || true
|
||||
echo "OpenSearch accepts index creation"
|
||||
break
|
||||
fi
|
||||
echo "index creation not ready (attempt $attempt/5, HTTP $probe_status) — waiting"
|
||||
cat /tmp/os-probe.json 2>/dev/null || true
|
||||
[ "$attempt" = "5" ] && { echo "FATAL: OpenSearch still refuses index creation"; exit 1; }
|
||||
sleep 10
|
||||
done
|
||||
echo "OPENSEARCH_URL=http://$FOUND:9200" >> "$GITHUB_ENV"
|
||||
- name: Select THIS run's ClickHouse by identity
|
||||
run: |
|
||||
@@ -294,9 +260,9 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: SonarQube analysis (self-hosted sonar.siax.dev)
|
||||
- name: SonarQube analysis (self-hosted sonar.siax.io)
|
||||
env:
|
||||
SONAR_HOST_URL: https://sonar.siax.dev
|
||||
SONAR_HOST_URL: https://sonar.siax.io
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -309,22 +275,3 @@ jobs:
|
||||
trap 'docker rm -f "$cid" >/dev/null 2>&1 || true' EXIT
|
||||
docker cp . "$cid":/usr/src
|
||||
docker start -a "$cid"
|
||||
|
||||
design-conformance:
|
||||
name: Component conformance (blocking)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- name: Checkout canonical siax-standard (SSOT)
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: admin/siax-standard
|
||||
token: ${{ secrets.SIAX_CI_TOKEN }}
|
||||
path: siax-standard-ssot
|
||||
- name: Component conformance (blocking)
|
||||
run: |
|
||||
node --input-type=module -e "import('./siax-standard-ssot/packages/doctor/src/commands/component-conformance.mjs').then(m=>{process.exit(m.run(['--repo', process.env.GITHUB_WORKSPACE, '--allow-path-prefix', 'siax-standard-ssot/', '--fail-on=block']))})"
|
||||
|
||||
@@ -21,8 +21,6 @@ jobs:
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
- name: Enable corepack + pin pnpm@9
|
||||
run: |
|
||||
corepack enable
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
{"allow":[{"pathPrefix":"components/states.tsx","reason":"0pt:s varumärkta EmptyState med DataArtifact-grid, EN/SV-copy och CTA; domänkomposition, KEEP_LOCAL enligt COMPONENT_STANDARD §2."},{"pathPrefix":"components/theme-provider.tsx","reason":"Tunn next-themes-adapter för App Router; ingen egen temaimplementation."},{"pathPrefix":"components/ui/toaster.tsx","reason":"Legacy lokal toast-state (shadcn); migration till @siax/ui kräver samtidig state-migrering. KEEP_LOCAL med backlog."}]}
|
||||
@@ -1,36 +0,0 @@
|
||||
{
|
||||
"$schema": "https://git.siax.io/sax3l/siax-standard/raw/branch/main/schema/siax.acquisition-consumer.schema.json",
|
||||
"schemaVersion": "siax.acquisition-consumer/v1",
|
||||
"application": "0pt",
|
||||
"owner": "0pt",
|
||||
"tenantScoped": true,
|
||||
"capabilities": [
|
||||
"siax.acquisition.plan",
|
||||
"siax.acquisition.run",
|
||||
"siax.acquisition.status",
|
||||
"siax.acquisition.result",
|
||||
"siax.acquisition.query_existing",
|
||||
"siax.acquisition.discovery_search",
|
||||
"siax.acquisition.extract",
|
||||
"siax.acquisition.evidence"
|
||||
],
|
||||
"allowedPurposes": [
|
||||
"data.acquisition",
|
||||
"source.registration"
|
||||
],
|
||||
"dataCategories": [
|
||||
"public",
|
||||
"company",
|
||||
"product",
|
||||
"pricing",
|
||||
"vehicle",
|
||||
"property",
|
||||
"document",
|
||||
"event",
|
||||
"other"
|
||||
],
|
||||
"maxCostSEK": 25,
|
||||
"reuseExistingFacts": true,
|
||||
"mustNotOwnEngines": true,
|
||||
"engines": []
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
/**
|
||||
* app/api/0pt/canonical/facts/route.ts
|
||||
* ====================================
|
||||
* POST — canonical structured-observation write (entities/facts/relations).
|
||||
* GET — tenant-scoped read for consumers (products, agents, L0RE projection).
|
||||
*
|
||||
* 0pt owns observed facts; L0RE owns epistemic propositions/projections and
|
||||
* consumes this API. Tenant is always cross-checked against the verified
|
||||
* principal (assertTenantMatchesVerified), never trusted from the body alone.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { canonicalWriteSchema, parseBody } from "@/src/validation/0pt-schemas";
|
||||
import { canonicalFactService } from "@/src/services/canonical-fact-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const parsed = parseBody(canonicalWriteSchema, await request.json());
|
||||
if (!parsed.ok) return NextResponse.json(parsed.body, { status: parsed.status });
|
||||
const body = parsed.data;
|
||||
const guard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (guard) return guard;
|
||||
const result = await canonicalFactService.write(body);
|
||||
return NextResponse.json(result, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
const limitRaw = searchParams.get("limit");
|
||||
const facts = await canonicalFactService.query({
|
||||
tenant_id: tenantId,
|
||||
entity_id: searchParams.get("entity_id") ?? undefined,
|
||||
entity_type: searchParams.get("entity_type") ?? undefined,
|
||||
identity_namespace: searchParams.get("identity_namespace") ?? undefined,
|
||||
identity_value: searchParams.get("identity_value") ?? undefined,
|
||||
predicate: searchParams.get("predicate") ?? undefined,
|
||||
limit: limitRaw ? Number(limitRaw) : undefined,
|
||||
});
|
||||
return NextResponse.json({ facts });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { PostgresCreditLedger } from '@/src/document-workbench/credit-ledger';
|
||||
import { ensureTrialCredits, readTrialCredits } from '@/src/document-workbench/trial-credits';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
import { resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
@@ -25,8 +24,6 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
try {
|
||||
const ledger = new PostgresCreditLedger(getRepositorySql(url));
|
||||
const trial = readTrialCredits();
|
||||
if (trial > 0) await ensureTrialCredits(ledger, verified.scope.tenantId, trial);
|
||||
const balance = await ledger.balance(verified.scope.tenantId);
|
||||
return NextResponse.json({ tenant_id: verified.scope.tenantId, ...balance });
|
||||
} catch (error: unknown) {
|
||||
|
||||
@@ -27,15 +27,6 @@ export async function POST(request: NextRequest) {
|
||||
if ('response' in verified) return verified.response;
|
||||
const { tenantId } = verified.scope;
|
||||
|
||||
if (process.env.OPT_CREDITS_MODE === 'off') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'CREDITS_DISABLED',
|
||||
message: 'Billing is not active yet (pilot mode). No payment can be taken.',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const book = readCreditPriceBook();
|
||||
if (!book) {
|
||||
return NextResponse.json(
|
||||
|
||||
@@ -27,7 +27,6 @@ export async function GET(request: NextRequest) {
|
||||
return NextResponse.json({
|
||||
version: book.version,
|
||||
currency: book.currency,
|
||||
purchases_enabled: process.env.OPT_CREDITS_MODE !== 'off',
|
||||
packs: book.packs.map((pack) => ({
|
||||
id: pack.id,
|
||||
credits: pack.credits,
|
||||
|
||||
@@ -3,7 +3,6 @@ import { Doc0SourceClient, Doc0SourceUnavailableError } from '@/src/document-wor
|
||||
import { Inf0OutcomeUnknownError } from '@/src/document-workbench/inf0-gateway-client';
|
||||
import { createInf0Gateway } from '@/src/document-workbench/inf0-gateway';
|
||||
import { PostgresCreditLedger } from '@/src/document-workbench/credit-ledger';
|
||||
import { ensureTrialCredits, readTrialCredits } from '@/src/document-workbench/trial-credits';
|
||||
import { creditsForUsage, readCreditPriceBook } from '@/src/document-workbench/price-book';
|
||||
import { structureDocument } from '@/src/document-workbench/structure-document';
|
||||
import { exportValidatedOutput } from '@/src/document-workbench/export-validated-output';
|
||||
@@ -164,22 +163,13 @@ export async function POST(request: NextRequest) {
|
||||
const dataClass = body.data_class ?? 'low';
|
||||
const format = body.format ?? 'json';
|
||||
|
||||
if (pipelineStage !== 'parsed') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'DOCUMENT_NOT_PARSED',
|
||||
message:
|
||||
'The document has no verified text layer yet (parse_failed or not parsed). OCR is required before structuring.',
|
||||
},
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
if (
|
||||
!isValidScopeId(projectId) ||
|
||||
!isValidScopeId(documentId) ||
|
||||
!isValidScopeId(versionId) ||
|
||||
typeof checksum !== 'string' ||
|
||||
!/^[0-9a-f]{64}$/.test(checksum) ||
|
||||
pipelineStage !== 'parsed' ||
|
||||
typeof instruction !== 'string' ||
|
||||
!instruction.trim() ||
|
||||
instruction.length > 4000 ||
|
||||
@@ -280,7 +270,6 @@ export async function POST(request: NextRequest) {
|
||||
creditsEnabled && databaseUrl ? new PostgresCreditLedger(getRepositorySql(databaseUrl)) : undefined;
|
||||
if (ledger) {
|
||||
try {
|
||||
await ensureTrialCredits(ledger, tenantId, readTrialCredits());
|
||||
await ledger.apply({
|
||||
tenantId,
|
||||
idempotencyKey: `reserve:${reservationId}`,
|
||||
|
||||
@@ -26,7 +26,6 @@ import { parseBody, qualityBridgeRunSchema } from "@/src/validation/0pt-schemas"
|
||||
import { qualityService } from "@/src/services/quality";
|
||||
import { ensureBaselineRules } from "@/src/quality/quality-bridge";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
@@ -36,11 +35,6 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
// Tenant-scoped write (auto-provisions baseline rules + stores a run):
|
||||
// the internal service principal must stay inside its server-configured
|
||||
// tenant allowlist, never a tenant named by the caller.
|
||||
const guard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (guard) return guard;
|
||||
|
||||
await ensureBaselineRules(qualityService, {
|
||||
tenant_id: body.tenant_id,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { FileDropzone } from '@siax/ui/components/file-dropzone';
|
||||
import { useT } from '@/components/locale-provider';
|
||||
import { PortalShell } from '@/components/portal-shell';
|
||||
|
||||
@@ -73,10 +72,7 @@ export default function DocumentsPage() {
|
||||
const [uploadNote, setUploadNote] = useState<string | null>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [unknownOutcome, setUnknownOutcome] = useState<unknown | null>(null);
|
||||
// One idempotency key per selected file: a retry (double click, network
|
||||
// error, reload-and-pick-the-same-file) returns the SAME document instead of
|
||||
// creating a duplicate. Picking a different file resets it.
|
||||
const uploadKey = useRef<string | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [instruction, setInstruction] = useState('');
|
||||
const [fields, setFields] = useState<FieldRow[]>([{ name: 'organization', type: 'string' }]);
|
||||
@@ -123,9 +119,7 @@ export default function DocumentsPage() {
|
||||
const form = new FormData();
|
||||
form.set('file', file);
|
||||
form.set('project_id', projectId.trim());
|
||||
const key = uploadKey.current ?? crypto.randomUUID();
|
||||
uploadKey.current = key;
|
||||
form.set('idempotency_key', key);
|
||||
form.set('idempotency_key', crypto.randomUUID());
|
||||
form.set('classification', 'restricted');
|
||||
try {
|
||||
const response = await fetch('/api/0pt/documents/upload', {
|
||||
@@ -277,16 +271,31 @@ export default function DocumentsPage() {
|
||||
/>
|
||||
</label>
|
||||
|
||||
<FileDropzone
|
||||
className="mt-4"
|
||||
label={t({ en: 'choose a file', sv: 'välj en fil' })}
|
||||
hint={file ? file.name : t({ en: 'PDF, Word, Excel, CSV, images…', sv: 'PDF, Word, Excel, CSV, bilder…' })}
|
||||
disabled={uploading}
|
||||
onFiles={(files) => {
|
||||
uploadKey.current = null;
|
||||
setFile(files[0] ?? null);
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
inputRef.current?.click();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
className="mt-4 flex cursor-pointer flex-col items-center justify-center border border-dashed border-border px-6 py-10 text-center focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<span className={label}>{t({ en: 'choose a file', sv: 'välj en fil' })}</span>
|
||||
<span className="mt-3 text-[15px]">
|
||||
{file
|
||||
? file.name
|
||||
: t({ en: 'PDF, Word, Excel, CSV, images…', sv: 'PDF, Word, Excel, CSV, bilder…' })}
|
||||
</span>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -12,7 +12,6 @@ export default function CreditsPage() {
|
||||
const [balance, setBalance] = useState<{ available: number; reserved: number } | null>(null);
|
||||
const [balanceNote, setBalanceNote] = useState<string | null>(null);
|
||||
const [packs, setPacks] = useState<Pack[]>([]);
|
||||
const [purchasesEnabled, setPurchasesEnabled] = useState(true);
|
||||
const [currency, setCurrency] = useState('SEK');
|
||||
const [packsNote, setPacksNote] = useState<string | null>(null);
|
||||
const [buying, setBuying] = useState<string | null>(null);
|
||||
@@ -32,16 +31,10 @@ export default function CreditsPage() {
|
||||
}
|
||||
try {
|
||||
const r = await fetch('/api/0pt/credits/packs', { cache: 'no-store' });
|
||||
const body = (await r.json()) as {
|
||||
packs?: Pack[];
|
||||
currency?: string;
|
||||
purchases_enabled?: boolean;
|
||||
message?: string;
|
||||
};
|
||||
const body = (await r.json()) as { packs?: Pack[]; currency?: string; message?: string };
|
||||
if (r.ok && body.packs) {
|
||||
setPacks(body.packs);
|
||||
setCurrency(body.currency ?? 'SEK');
|
||||
setPurchasesEnabled(body.purchases_enabled !== false);
|
||||
} else {
|
||||
setPacksNote(
|
||||
body.message ??
|
||||
@@ -134,30 +127,18 @@ export default function CreditsPage() {
|
||||
{formatSEK(pack.amount_minor / 100)}
|
||||
</p>
|
||||
</div>
|
||||
{purchasesEnabled ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => buy(pack.id)}
|
||||
disabled={buying !== null}
|
||||
className="border border-foreground px-4 py-2 font-mono text-[11px] uppercase tracking-[0.18em] disabled:opacity-40"
|
||||
>
|
||||
{buying === pack.id
|
||||
? t({ en: 'opening…', sv: 'öppnar…' })
|
||||
: t({ en: 'buy', sv: 'köp' })}
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => buy(pack.id)}
|
||||
disabled={buying !== null}
|
||||
className="border border-foreground px-4 py-2 font-mono text-[11px] uppercase tracking-[0.18em] disabled:opacity-40"
|
||||
>
|
||||
{buying === pack.id ? t({ en: 'opening…', sv: 'öppnar…' }) : t({ en: 'buy', sv: 'köp' })}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{!purchasesEnabled ? (
|
||||
<p className="mt-4 text-[14px] text-muted-foreground">
|
||||
{t({
|
||||
en: 'Billing is not active yet (pilot). No payment can be taken.',
|
||||
sv: 'Betalning är inte aktiverad än (pilot). Ingen betalning kan tas.',
|
||||
})}
|
||||
</p>
|
||||
) : null}
|
||||
{status ? <p className="mt-4 text-[14px] text-muted-foreground">{status}</p> : null}
|
||||
<p className="mt-4 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground">
|
||||
{currency}
|
||||
|
||||
@@ -37,11 +37,7 @@ is accepted by middleware as a verified principal (Bearer still wins).
|
||||
releasing it.
|
||||
6. **No price is ever read from the client.** The price book is a versioned,
|
||||
server-owned JSON document (`OPT_CREDIT_PRICE_BOOK`).
|
||||
7. **Trial credits are a grant, not a payment.** `OPT_TRIAL_CREDITS=N` grants N
|
||||
credits once per tenant (`kind='grant'`, idempotency key `trial:<tenant>`),
|
||||
so the ledger is fully exercised before any real purchase. It is never read
|
||||
from a client and never looks like a Stripe payment.
|
||||
8. **Pilot mode is explicit.** `OPT_CREDITS_MODE=off` skips reserve/settle and
|
||||
7. **Pilot mode is explicit.** `OPT_CREDITS_MODE=off` skips reserve/settle and
|
||||
reports `credits: null`. It is not a silent fallback and it does not enable
|
||||
purchases; unset/`on` requires the price book and the ledger.
|
||||
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
# Legacy instance audit — 0pt (server5) and L0RE (server5) — 2026-11-07
|
||||
|
||||
Canonical runtimes: **0pt on server6** (Coolify app `shxd6lepxuxfsjsp0ath3z1g`,
|
||||
`0pt.app`) and **L0RE on server9** (`l0re.siax.io`). This document records the
|
||||
older instances on server5 and their disposition. It is not production
|
||||
documentation for either product.
|
||||
|
||||
## 1. 0pt legacy (server5)
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Containers | `0pt-api` (`0pt-api:c46ebbf`, created 2026-11-05), `0pt-web` (`:18080`) |
|
||||
| Database | `0pt-pg`, user/db `opt`, 11 MB |
|
||||
| Exposure | `0pt-web` only on `100.124.7.55:18080`; no DNS record, no reverse proxy |
|
||||
| Consumers | none found (`/etc/siax`, `/opt/siax`, site0 and L0RE deploy configs) |
|
||||
| Unique data | 32 canonical facts (30 GLEIF web observations + `body_type` YDL405 + `passmark.find_prime_numbers.v10`) |
|
||||
|
||||
**Data reconciliation:** all 32 facts were exported and re-imported through the
|
||||
canonical API (`POST /api/0pt/canonical/facts`) into the server6 deployment.
|
||||
Replay returned `duplicates: 32`, so the import is idempotent. Production now
|
||||
holds 34 facts (32 migrated + 2 verification observations) and 4 entities.
|
||||
|
||||
**Backup:** `server5:/var/backups/0pt-legacy/opt_legacy_20261107.dump.zst`
|
||||
(custom format, 32 KB) + offsite `server11:/home/backup/0pt/`.
|
||||
|
||||
**Action taken:** `docker update --restart=no` + `docker stop` for `0pt-api` and
|
||||
`0pt-web`. `0pt-pg` left running for forensics/rollback. `0pt.app` verified 200
|
||||
after the stop (served by server6).
|
||||
|
||||
**Full removal (requires owner decision):** snapshot/destroy `0pt-pg` volume
|
||||
after the retention window, remove the legacy compose project, revoke the old
|
||||
`INTERNAL_TOKEN` if it was ever stored on server5.
|
||||
|
||||
## 2. L0RE orphan (server5)
|
||||
|
||||
Documented separately in `admin/l0re` PR #485
|
||||
(`docs/runbook/l0re-orphan-decommission-20261107.md`): API stopped with
|
||||
`restart=no`, dump + restore proof (8 propositions/62 assertions), no unique
|
||||
legitimate data (pilot facts already re-projected to production). `l0re-pg` and
|
||||
`l0re-opensearch` remain for forensics.
|
||||
|
||||
## 3. Single-runtime rule
|
||||
|
||||
One primary runtime per logical service. A container image of a product running
|
||||
outside its registered Coolify app is a finding, not a fallback. Both server5
|
||||
instances were reachable only from the host, which is why the split survived
|
||||
until this audit.
|
||||
@@ -1,78 +0,0 @@
|
||||
# 0pt workload identity — målbild, nuläge och övergång
|
||||
|
||||
Status: **design klar, provisionering blockerad** (2026-11-07).
|
||||
Ägare: CL0UD (identitet) / 0pt (konsument).
|
||||
|
||||
## 1. Nuläge
|
||||
|
||||
0pt autentiserar maskin-till-maskin med en **delad hemlighet**:
|
||||
|
||||
- `X-Internal-Token` mot `INTERNAL_TOKEN` (samma värde i engine och edge).
|
||||
- Tenant-auktoritet kommer från serverkonfigurationen `INTERNAL_SERVICE_TENANTS`
|
||||
(se `src/auth/internal-service-tenant.ts`), aldrig från en klientheader.
|
||||
- Tom allowlist ⇒ ingen tenant-auktoritet ⇒ tenant-scopade skrivningar 403.
|
||||
|
||||
Det här är säkert men grovkornigt: en enda hemlighet representerar hela
|
||||
engine-processen, och varje ny konsument kräver en manuell allowlist-post.
|
||||
|
||||
## 2. Målbild (CL0UD workload identity)
|
||||
|
||||
CL0UD äger redan maskineriet:
|
||||
|
||||
- `POST /account/service-accounts` skapar en service account (identitet).
|
||||
- `POST /account/service-accounts/{id}/workload-token` mints en **kortlivad**
|
||||
(10 min default, 1 h max) workload-token vars `capabilities` är en delmängd av
|
||||
service accountens `platform.cl0ud_service_account_scopes.allowedCapabilities`.
|
||||
- `@siax/platform-core` `auth/workload.ts` är verifieringsadaptern; publika
|
||||
nycklar via JWKS.
|
||||
- `packages/capability-registry/src/workload-identities.ts` deklarerar
|
||||
arbetsbelastningsnamn och `aud:*`-audiences. Modulen är uttryckligen **inte**
|
||||
provisionerad och **inte** inkopplad i utfärdande eller verifiering än.
|
||||
|
||||
För 0pt innebär det:
|
||||
|
||||
| Egenskap | Idag | Mål |
|
||||
|---|---|---|
|
||||
| Credential | delad `INTERNAL_TOKEN` | CL0UD-workload-token, `aud:0pt`, 10 min |
|
||||
| Tenant | serverkonfigurerad allowlist | `tenant_id`-claim i verifierad token |
|
||||
| Capabilities | route-lista i middleware | `capabilities`-claim (t.ex. `0pt.canonical.write`) |
|
||||
| Rotation | manuell | automatisk (kortlivad token) |
|
||||
| Spårbarhet | delad hemlighet | per-arbetsbelastning (`0pt-engine`, `site0-pipeline`) |
|
||||
|
||||
## 3. Integrationsdesign (när provisionering är möjlig)
|
||||
|
||||
1. **Verifiering före route-logik.** Middleware accepterar
|
||||
`Authorization: Bearer <workload-token>` för `INTERNAL_SERVICE_ROUTES` om
|
||||
signaturen verifieras mot CL0UD JWKS, `aud` innehåller `0pt` och `exp` är
|
||||
giltig. Ingen klientheader får bidra till tenant.
|
||||
2. **Tenant från claim, inte från allowlist.** `tenant_id` i den verifierade
|
||||
tokenen sätts som `x-0pt-verified-tenant`; `INTERNAL_SERVICE_TENANTS`
|
||||
används endast för legacy `X-Internal-Token`.
|
||||
3. **Capabilities per route.** Route-metadata (`0pt.canonical.write`,
|
||||
`0pt.quality.run`) jämförs med tokenens `capabilities`. Saknad capability ⇒
|
||||
403, inte 401 (identiteten är giltig, behörigheten räcker inte).
|
||||
4. **Dual-accept under övergång.** Båda credentialtyperna accepteras tills
|
||||
engine och site0-pipeline mintar workload-tokens; därefter tas
|
||||
`X-Internal-Token` bort i en egen release med negativt test.
|
||||
5. **Negativa tester i samma svit som idag**
|
||||
(`tests/auth/internal-token-tenant-scope.test.ts`): fel `aud` ⇒ 401, utgången
|
||||
token ⇒ 401, tenant utanför claim ⇒ 403, saknad capability ⇒ 403.
|
||||
|
||||
## 4. Blockerare
|
||||
|
||||
- `/account/service-accounts` svarar **307 → /login** utan operator-session;
|
||||
ingen giltig `SIAX_TOKEN` finns i Infisical-miljön.
|
||||
- Zitadel admin-PAT (`/opt/siax-access/zitadel-admin-pat`) är invalid
|
||||
(AUTH-7fs1e), så nya machine users kan inte mintas via det flödet.
|
||||
- `workload-identities.ts` är deklaration-only: ingen identitet är
|
||||
`provisioned: true`.
|
||||
|
||||
Åtgärd kräver en operatörsinloggning i CL0UD-konsolen (eller en ny giltig
|
||||
admin-PAT) och är därför **EXTERNALLY_BLOCKED** från agentsidan.
|
||||
|
||||
## 5. Vad som inte ska göras
|
||||
|
||||
- Ingen egen JWT-signering i 0pt.
|
||||
- Ingen parallell identitetsplattform.
|
||||
- Ingen klientheader som bär tenant.
|
||||
- Ingen långlivad delad hemlighet som "tillfällig" lösning utan slutdatum.
|
||||
+5
-69
@@ -4,16 +4,12 @@
|
||||
* 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.
|
||||
* defence in depth.
|
||||
*/
|
||||
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';
|
||||
import {
|
||||
SERVICE_TENANT_SCOPE_HEADER,
|
||||
resolveInternalServiceTenants,
|
||||
} from '@/src/auth/internal-service-tenant';
|
||||
|
||||
assertAuthConfigSafe();
|
||||
|
||||
@@ -30,77 +26,19 @@ const EXEMPT_PATTERNS: RegExp[] = [
|
||||
/** 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 internalScopeWarned = false;
|
||||
|
||||
/**
|
||||
* Headers that only middleware may set. Anything a client sends under these
|
||||
* names is a forgery attempt and is removed before forwarding — including on
|
||||
* the internal-token path, which previously passed the original header map
|
||||
* through unchanged.
|
||||
*/
|
||||
const VERIFIED_HEADERS = [
|
||||
'x-0pt-verified-tenant',
|
||||
'x-0pt-verified-sub',
|
||||
SERVICE_TENANT_SCOPE_HEADER,
|
||||
] as const;
|
||||
|
||||
function stripVerifiedHeaders(req: NextRequest): Headers {
|
||||
const forwarded = new Headers(req.headers);
|
||||
for (const name of VERIFIED_HEADERS) forwarded.delete(name);
|
||||
return forwarded;
|
||||
}
|
||||
|
||||
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)) {
|
||||
// P0 tenant isolation (2026-11-07): X-Internal-Token proves the service —
|
||||
// not a tenant. Tenant authority is SERVER CONFIG (INTERNAL_SERVICE_TENANTS),
|
||||
// never a client header: an inbound `X-0pt-Internal-Tenant` is ignored and
|
||||
// stripped. With no configured tenants the principal has no tenant
|
||||
// authority and tenant-scoped writes fail closed with 403.
|
||||
const forwarded = stripVerifiedHeaders(req);
|
||||
const tenants = resolveInternalServiceTenants();
|
||||
if (tenants.length > 1) {
|
||||
// The shared X-Internal-Token identifies ONE service process, not a set
|
||||
// of independently authenticated principals. A multi-tenant allowlist
|
||||
// would let any holder of that shared token choose between all listed
|
||||
// tenants, which is exactly the client-controlled authority this guard
|
||||
// exists to remove. Multi-tenant service access requires a verified
|
||||
// workload-identity binding (CL0UD delegation contract); until that
|
||||
// exists, an ambiguous configuration fails closed.
|
||||
console.error(
|
||||
'[0pt-auth] INTERNAL_SERVICE_TENANTS lists more than one tenant: refusing the internal request until workload-identity binding exists',
|
||||
);
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'OPT_UNAUTHENTICATED',
|
||||
message:
|
||||
'internal service tenant scope is ambiguous: configure exactly one tenant until a verified workload-identity binding exists',
|
||||
},
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
forwarded.set(SERVICE_TENANT_SCOPE_HEADER, tenants.join(','));
|
||||
if (tenants.length === 1) {
|
||||
forwarded.set('x-0pt-verified-tenant', tenants[0]);
|
||||
} else if (tenants.length === 0 && !internalScopeWarned) {
|
||||
internalScopeWarned = true;
|
||||
console.warn(
|
||||
'[0pt-auth] INTERNAL_SERVICE_TENANTS is unset: the internal service principal has no tenant authority; tenant-scoped writes will be denied',
|
||||
);
|
||||
}
|
||||
return NextResponse.next({ request: { headers: forwarded } });
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
if (_authDiagCount < 5) {
|
||||
@@ -124,7 +62,7 @@ export async function middleware(req: NextRequest): Promise<NextResponse> {
|
||||
typeof session.exp === 'number' &&
|
||||
session.exp > Date.now()
|
||||
) {
|
||||
const forwarded = stripVerifiedHeaders(req);
|
||||
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 } });
|
||||
@@ -145,13 +83,11 @@ export async function middleware(req: NextRequest): Promise<NextResponse> {
|
||||
|
||||
const principal = decision.ctx.principal;
|
||||
if (principal) {
|
||||
const forwarded = stripVerifiedHeaders(req);
|
||||
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 } });
|
||||
}
|
||||
|
||||
// No verified principal (explicit AUTH_ENFORCE=false development mode).
|
||||
// Never forward a client-named verified header, even in dev.
|
||||
return NextResponse.next({ request: { headers: stripVerifiedHeaders(req) } });
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
+4
-5
@@ -52,15 +52,13 @@
|
||||
"@radix-ui/react-toggle-group": "1.1.19",
|
||||
"@radix-ui/react-tooltip": "1.2.16",
|
||||
"@siax/0pt-decision": "workspace:*",
|
||||
"@siax/access": "workspace:*",
|
||||
"@siax/auth-zitadel": "0.1.1",
|
||||
"@siax/charts": "^0.5.0",
|
||||
"@siax/collaboration": "0.3.0",
|
||||
"@siax/config": "^0.2.1",
|
||||
"@siax/contracts": "^0.12.1",
|
||||
"@siax/contracts": "^0.11.1",
|
||||
"@siax/import-export": "^0.2.2",
|
||||
"@siax/tokens": "^0.1.2",
|
||||
"@siax/ui": "^0.16.13",
|
||||
"@siax/ui": "^0.15.1",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
@@ -83,7 +81,8 @@
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"vaul": "^1.1.2",
|
||||
"zod": "3.25.76"
|
||||
"zod": "3.25.76",
|
||||
"@siax/access": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.15.0",
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
/**
|
||||
* @siax/access idempotency primitives — the universal SIAX contract for any
|
||||
* operation that must either happen exactly once or replay its receipt.
|
||||
*
|
||||
* This package is derived from the pattern proven in 0pt's durable upload
|
||||
* attempts (prepare -> claim -> dispatch -> store receipt -> replay), then
|
||||
* generalized so DOC0, N0D and future products can adopt the identical shape
|
||||
* instead of re-implementing it.
|
||||
*
|
||||
* Rules encoded here:
|
||||
* 1. An operation identity binds EVERY result-affecting input (tenant,
|
||||
* project, actor, payload version). A changed payload under the same key
|
||||
* is a CONFLICT, never a replay of someone else's receipt.
|
||||
* 2. One claimant per key: returning `false` from `start` means another
|
||||
* caller owns the dispatch, and only the stored receipt (or bounded
|
||||
* observation) may be answered.
|
||||
* 3. A stored receipt is replayed verbatim; the caller never invents one.
|
||||
* 4. Commit boundaries: NEVER write a network command before the claim is
|
||||
* durably persisted, and never lose the claim after the command may have
|
||||
* committed.
|
||||
*/
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
/** Stable JSON canonicalization (sorted array stays sorted; v-prefix bumped on contract change). */
|
||||
export function operationFingerprint(parts: readonly unknown[], version = "siax-idempotency-v1"): string {
|
||||
return createHash("sha256")
|
||||
.update(JSON.stringify([version, ...parts]))
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
export interface OperationIdentity {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
/** Client-generated, transport-level key (<=256 visible ASCII). */
|
||||
idempotencyKey: string;
|
||||
/** Supply result-affecting inputs; the helper adds the scope fields itself. */
|
||||
payload: readonly unknown[];
|
||||
}
|
||||
|
||||
export function operationIdentity(operation: OperationIdentity): {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
idempotencyKey: string;
|
||||
fingerprint: string;
|
||||
} {
|
||||
if (
|
||||
!operation ||
|
||||
![operation.tenantId, operation.projectId, operation.actorId, operation.idempotencyKey].every(
|
||||
(value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._@:+-]{0,255}$/.test(value),
|
||||
) ||
|
||||
!Array.isArray(operation.payload)
|
||||
) {
|
||||
throw new Error("Invalid idempotent operation identity");
|
||||
}
|
||||
void operation.payload;
|
||||
return {
|
||||
tenantId: operation.tenantId,
|
||||
projectId: operation.projectId,
|
||||
actorId: operation.actorId,
|
||||
idempotencyKey: operation.idempotencyKey,
|
||||
fingerprint: operationFingerprint([
|
||||
operation.tenantId,
|
||||
operation.projectId,
|
||||
operation.actorId,
|
||||
...operation.payload,
|
||||
]),
|
||||
};
|
||||
}
|
||||
|
||||
export type OperationOutcome<R> =
|
||||
| { kind: "claimed"; execute: () => Promise<R> }
|
||||
| { kind: "replayed"; receipt: R }
|
||||
| { kind: "conflict"; expected?: string };
|
||||
|
||||
/** Structural contract for an attempt store. Matched by Postgres adapters per product. */
|
||||
export interface IdempotencyStore<Identity, Receipt> {
|
||||
/** Returns true when this caller won the right to dispatch; false = reuse replay path. */
|
||||
start(identity: Identity, fingerprint: string): Promise<boolean>;
|
||||
/** Persist after a verified downstream commit. Must never be called before. */
|
||||
save(identity: Identity, fingerprint: string, receipt: Receipt): Promise<void>;
|
||||
/** Load a stored receipt for replay (exact fingerprint match). */
|
||||
receipt(identity: Identity, fingerprint: string): Promise<Receipt | undefined>;
|
||||
}
|
||||
|
||||
export type IdempotentStoreItemIdentity<I> = {
|
||||
identity: I;
|
||||
fingerprint: string;
|
||||
};
|
||||
|
||||
export async function runIdempotentOperation<I, R>(input: {
|
||||
store: IdempotencyStore<I, R>;
|
||||
identity: I;
|
||||
fingerprint: string;
|
||||
/** Must be safe to call exactly once; a second call is never attempted here. */
|
||||
dispatch: () => Promise<R>;
|
||||
}): Promise<OperationOutcome<R>> {
|
||||
if (typeof input.dispatch !== "function") throw new Error("Dispatch is required");
|
||||
try {
|
||||
const won = await input.store.start(input.identity, input.fingerprint);
|
||||
if (!won) {
|
||||
const stored = await input.store.receipt(input.identity, input.fingerprint);
|
||||
return stored !== undefined
|
||||
? { kind: "replayed", receipt: stored }
|
||||
: { kind: "replayed", receipt: undefined as unknown as R };
|
||||
}
|
||||
} catch (error) {
|
||||
return { kind: "conflict", expected: error instanceof Error ? error.message : "store_unavailable" };
|
||||
}
|
||||
const receipt = await input.dispatch();
|
||||
try {
|
||||
await input.store.save(input.identity, input.fingerprint, receipt);
|
||||
} catch {
|
||||
/* The downstream commit is real; a journal-write failure must not turn a
|
||||
real receipt into an error. The next retry replays via the stored receipt
|
||||
if the save ever succeeds before a downstream resend. */
|
||||
}
|
||||
return { kind: "claimed", execute: async () => receipt };
|
||||
}
|
||||
@@ -1,2 +1,235 @@
|
||||
export * from './relationships';
|
||||
export * from './idempotency';
|
||||
/**
|
||||
* @siax/access — universal project/tenant relationship checks for SIAX Cloud.
|
||||
*
|
||||
* This is the reusable extraction of the pattern first proven in DOC0's
|
||||
* `src/clients/project-relationships.ts`. It is deliberately framework-neutral
|
||||
* (no Next.js, Fastify, Prisma or product types) so every SIAX product can
|
||||
* consume the exact same authorization primitive instead of copying it:
|
||||
*
|
||||
* 0pt — document upload + structuring scope
|
||||
* DOC0 — document/version/signature scope
|
||||
* N0D — job submission scope
|
||||
* any app — tenant/project membership
|
||||
*
|
||||
* IMPORTANT: a relationship match is ONE input to authorization, never a
|
||||
* complete decision. The caller must independently bind tenant and actor to a
|
||||
* verified principal (never to request headers), enforce tenant/project
|
||||
* status, capability, data-handling policy and an authoritative tuple
|
||||
* lifecycle. `resolveRelationship` fails closed: only an explicit
|
||||
* `relationships_match` is treated as allowed.
|
||||
*/
|
||||
|
||||
export type RelationshipResult = 'allowed' | 'denied' | 'unavailable';
|
||||
|
||||
/** The outcome of the composite project check. */
|
||||
export type ProjectRelationshipResult = 'relationships_match' | 'denied' | 'unavailable';
|
||||
|
||||
export interface ProjectRelationshipScope {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
}
|
||||
|
||||
const objectId = /^[A-Za-z0-9][A-Za-z0-9._@+-]{0,127}$/;
|
||||
const ulid = /^[0-9A-HJKMNP-TV-Z]{26}$/;
|
||||
const maxResponseBytes = 16 * 1024;
|
||||
|
||||
export interface OpenFgaRelationshipsOptions {
|
||||
baseUrl: string;
|
||||
storeId: string;
|
||||
modelId: string;
|
||||
serviceToken: string;
|
||||
timeoutMs?: number;
|
||||
fetchImpl?: typeof fetch;
|
||||
/** Explicit test-only opt-in for an isolated loopback OpenFGA process. */
|
||||
testOnlyAllowLoopbackHttp?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only OpenFGA relationship reader. Never writes tuples, never caches,
|
||||
* and never retries: an unavailable authorization source must stay visible to
|
||||
* the caller so it can fail closed.
|
||||
*/
|
||||
export class OpenFgaRelationships {
|
||||
private readonly baseUrl: string;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
private readonly storeId: string;
|
||||
private readonly modelId: string;
|
||||
private readonly serviceToken: string;
|
||||
private readonly timeoutMs: number;
|
||||
|
||||
constructor(options: OpenFgaRelationshipsOptions) {
|
||||
const url = new URL(options.baseUrl);
|
||||
const loopbackTest =
|
||||
process.env.NODE_ENV === 'test' &&
|
||||
options.testOnlyAllowLoopbackHttp === true &&
|
||||
url.protocol === 'http:' &&
|
||||
url.hostname === '127.0.0.1';
|
||||
if (
|
||||
(!loopbackTest && url.protocol !== 'https:') ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash ||
|
||||
typeof options.storeId !== 'string' ||
|
||||
typeof options.modelId !== 'string' ||
|
||||
!ulid.test(options.storeId) ||
|
||||
!ulid.test(options.modelId) ||
|
||||
typeof options.serviceToken !== 'string' ||
|
||||
!/^[\x21-\x7e]{1,8192}$/.test(options.serviceToken) ||
|
||||
(options.timeoutMs !== undefined &&
|
||||
(!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 100 || options.timeoutMs > 30_000))
|
||||
) {
|
||||
throw new Error('Invalid trusted OpenFGA configuration');
|
||||
}
|
||||
this.baseUrl = url.toString().replace(/\/+$/, '');
|
||||
this.fetchImpl = options.fetchImpl ?? fetch;
|
||||
this.storeId = options.storeId;
|
||||
this.modelId = options.modelId;
|
||||
this.serviceToken = options.serviceToken;
|
||||
this.timeoutMs = options.timeoutMs ?? 5_000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Both checks are necessary: project membership alone may inherit from a
|
||||
* different parent tenant if bad tuples associate a project with two
|
||||
* tenants. Returns `relationships_match` only when both hold.
|
||||
*/
|
||||
async checkProject(scope: ProjectRelationshipScope): Promise<ProjectRelationshipResult> {
|
||||
if (!scope || typeof scope !== 'object' || Array.isArray(scope)) {
|
||||
return 'denied';
|
||||
}
|
||||
const { tenantId, projectId, actorId } = scope;
|
||||
if (![tenantId, projectId, actorId].every((value) => typeof value === 'string' && objectId.test(value))) {
|
||||
return 'denied';
|
||||
}
|
||||
const actor = await this.checkTuple(`user:${actorId}`, 'member', `tenant:${tenantId}`);
|
||||
if (actor !== 'allowed') return actor === 'denied' ? 'denied' : 'unavailable';
|
||||
const parent = await this.checkTuple(`tenant:${tenantId}`, 'tenant', `project:${projectId}`);
|
||||
return parent === 'allowed' ? 'relationships_match' : parent;
|
||||
}
|
||||
|
||||
/** One raw relationship check. Public so products can map their own tuples. */
|
||||
async checkTuple(user: string, relation: string, object: string): Promise<RelationshipResult> {
|
||||
if (
|
||||
![user, relation, object].every(
|
||||
(value) => typeof value === 'string' && value.length > 0 && value.length <= 256,
|
||||
)
|
||||
) {
|
||||
return 'denied';
|
||||
}
|
||||
try {
|
||||
const response = await this.fetchImpl(`${this.baseUrl}/stores/${this.storeId}/check`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: `Bearer ${this.serviceToken}`,
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
authorization_model_id: this.modelId,
|
||||
consistency: 'HIGHER_CONSISTENCY',
|
||||
tuple_key: { user, relation, object },
|
||||
}),
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
});
|
||||
if (!response.ok || !response.body) return 'unavailable';
|
||||
const reader = response.body.getReader();
|
||||
try {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
const part = await reader.read();
|
||||
if (part.done) break;
|
||||
total += part.value.byteLength;
|
||||
if (total > maxResponseBytes) {
|
||||
void reader.cancel().catch(() => undefined);
|
||||
return 'unavailable';
|
||||
}
|
||||
chunks.push(part.value);
|
||||
}
|
||||
const result: unknown = JSON.parse(
|
||||
new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)),
|
||||
);
|
||||
if (
|
||||
!result ||
|
||||
typeof result !== 'object' ||
|
||||
Array.isArray(result) ||
|
||||
typeof (result as { allowed?: unknown }).allowed !== 'boolean'
|
||||
) {
|
||||
return 'unavailable';
|
||||
}
|
||||
return (result as { allowed: boolean }).allowed ? 'allowed' : 'denied';
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
} catch {
|
||||
return 'unavailable';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical environment variable names used across the fleet. Reads are
|
||||
* explicit (no implicit defaults) so a missing value is visible.
|
||||
*/
|
||||
export const OPENFGA_ENV = {
|
||||
baseUrl: 'OPENFGA_API_URL',
|
||||
storeId: 'OPENFGA_STORE_ID',
|
||||
modelId: 'OPENFGA_MODEL_ID',
|
||||
serviceToken: 'OPENFGA_AUTH_TOKEN',
|
||||
} as const;
|
||||
|
||||
export interface ProjectAccessOptions {
|
||||
/** The already-configured relationship reader, or undefined when OpenFGA is not configured. */
|
||||
relationships?: OpenFgaRelationships;
|
||||
/**
|
||||
* Optional extra policy (project status, capability, data-handling). It runs
|
||||
* only after the relationship check matched; a rejection is final.
|
||||
*/
|
||||
additionalPolicy?: (scope: ProjectRelationshipScope) => Promise<boolean> | boolean;
|
||||
}
|
||||
|
||||
/** Fail closed: only an explicit match with no policy objection is allowed. */
|
||||
export async function isProjectAccessAllowed(
|
||||
scope: ProjectRelationshipScope,
|
||||
options: ProjectAccessOptions,
|
||||
): Promise<boolean> {
|
||||
if (!options.relationships) return false;
|
||||
const result = await options.relationships.checkProject(scope);
|
||||
if (result !== 'relationships_match') return false;
|
||||
if (options.additionalPolicy) {
|
||||
try {
|
||||
return (await options.additionalPolicy(scope)) === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a relationship reader from a `NodeJS.ProcessEnv`-shaped object.
|
||||
* Returns `undefined` (fail closed) when any value is missing or invalid.
|
||||
*/
|
||||
export function openFgaFromEnv(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
fetchImpl?: typeof fetch,
|
||||
): OpenFgaRelationships | undefined {
|
||||
const baseUrl = env[OPENFGA_ENV.baseUrl];
|
||||
const storeId = env[OPENFGA_ENV.storeId];
|
||||
const modelId = env[OPENFGA_ENV.modelId];
|
||||
const serviceToken = env[OPENFGA_ENV.serviceToken];
|
||||
if (!baseUrl || !storeId || !modelId || !serviceToken) return undefined;
|
||||
try {
|
||||
return new OpenFgaRelationships({
|
||||
baseUrl,
|
||||
storeId,
|
||||
modelId,
|
||||
serviceToken,
|
||||
...(fetchImpl ? { fetchImpl } : {}),
|
||||
});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,235 +0,0 @@
|
||||
/**
|
||||
* @siax/access — universal project/tenant relationship checks for SIAX Cloud.
|
||||
*
|
||||
* This is the reusable extraction of the pattern first proven in DOC0's
|
||||
* `src/clients/project-relationships.ts`. It is deliberately framework-neutral
|
||||
* (no Next.js, Fastify, Prisma or product types) so every SIAX product can
|
||||
* consume the exact same authorization primitive instead of copying it:
|
||||
*
|
||||
* 0pt — document upload + structuring scope
|
||||
* DOC0 — document/version/signature scope
|
||||
* N0D — job submission scope
|
||||
* any app — tenant/project membership
|
||||
*
|
||||
* IMPORTANT: a relationship match is ONE input to authorization, never a
|
||||
* complete decision. The caller must independently bind tenant and actor to a
|
||||
* verified principal (never to request headers), enforce tenant/project
|
||||
* status, capability, data-handling policy and an authoritative tuple
|
||||
* lifecycle. `resolveRelationship` fails closed: only an explicit
|
||||
* `relationships_match` is treated as allowed.
|
||||
*/
|
||||
|
||||
export type RelationshipResult = 'allowed' | 'denied' | 'unavailable';
|
||||
|
||||
/** The outcome of the composite project check. */
|
||||
export type ProjectRelationshipResult = 'relationships_match' | 'denied' | 'unavailable';
|
||||
|
||||
export interface ProjectRelationshipScope {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
}
|
||||
|
||||
const objectId = /^[A-Za-z0-9][A-Za-z0-9._@+-]{0,127}$/;
|
||||
const ulid = /^[0-9A-HJKMNP-TV-Z]{26}$/;
|
||||
const maxResponseBytes = 16 * 1024;
|
||||
|
||||
export interface OpenFgaRelationshipsOptions {
|
||||
baseUrl: string;
|
||||
storeId: string;
|
||||
modelId: string;
|
||||
serviceToken: string;
|
||||
timeoutMs?: number;
|
||||
fetchImpl?: typeof fetch;
|
||||
/** Explicit test-only opt-in for an isolated loopback OpenFGA process. */
|
||||
testOnlyAllowLoopbackHttp?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only OpenFGA relationship reader. Never writes tuples, never caches,
|
||||
* and never retries: an unavailable authorization source must stay visible to
|
||||
* the caller so it can fail closed.
|
||||
*/
|
||||
export class OpenFgaRelationships {
|
||||
private readonly baseUrl: string;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
private readonly storeId: string;
|
||||
private readonly modelId: string;
|
||||
private readonly serviceToken: string;
|
||||
private readonly timeoutMs: number;
|
||||
|
||||
constructor(options: OpenFgaRelationshipsOptions) {
|
||||
const url = new URL(options.baseUrl);
|
||||
const loopbackTest =
|
||||
process.env.NODE_ENV === 'test' &&
|
||||
options.testOnlyAllowLoopbackHttp === true &&
|
||||
url.protocol === 'http:' &&
|
||||
url.hostname === '127.0.0.1';
|
||||
if (
|
||||
(!loopbackTest && url.protocol !== 'https:') ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash ||
|
||||
typeof options.storeId !== 'string' ||
|
||||
typeof options.modelId !== 'string' ||
|
||||
!ulid.test(options.storeId) ||
|
||||
!ulid.test(options.modelId) ||
|
||||
typeof options.serviceToken !== 'string' ||
|
||||
!/^[\x21-\x7e]{1,8192}$/.test(options.serviceToken) ||
|
||||
(options.timeoutMs !== undefined &&
|
||||
(!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 100 || options.timeoutMs > 30_000))
|
||||
) {
|
||||
throw new Error('Invalid trusted OpenFGA configuration');
|
||||
}
|
||||
this.baseUrl = url.toString().replace(/\/+$/, '');
|
||||
this.fetchImpl = options.fetchImpl ?? fetch;
|
||||
this.storeId = options.storeId;
|
||||
this.modelId = options.modelId;
|
||||
this.serviceToken = options.serviceToken;
|
||||
this.timeoutMs = options.timeoutMs ?? 5_000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Both checks are necessary: project membership alone may inherit from a
|
||||
* different parent tenant if bad tuples associate a project with two
|
||||
* tenants. Returns `relationships_match` only when both hold.
|
||||
*/
|
||||
async checkProject(scope: ProjectRelationshipScope): Promise<ProjectRelationshipResult> {
|
||||
if (!scope || typeof scope !== 'object' || Array.isArray(scope)) {
|
||||
return 'denied';
|
||||
}
|
||||
const { tenantId, projectId, actorId } = scope;
|
||||
if (![tenantId, projectId, actorId].every((value) => typeof value === 'string' && objectId.test(value))) {
|
||||
return 'denied';
|
||||
}
|
||||
const actor = await this.checkTuple(`user:${actorId}`, 'member', `tenant:${tenantId}`);
|
||||
if (actor !== 'allowed') return actor === 'denied' ? 'denied' : 'unavailable';
|
||||
const parent = await this.checkTuple(`tenant:${tenantId}`, 'tenant', `project:${projectId}`);
|
||||
return parent === 'allowed' ? 'relationships_match' : parent;
|
||||
}
|
||||
|
||||
/** One raw relationship check. Public so products can map their own tuples. */
|
||||
async checkTuple(user: string, relation: string, object: string): Promise<RelationshipResult> {
|
||||
if (
|
||||
![user, relation, object].every(
|
||||
(value) => typeof value === 'string' && value.length > 0 && value.length <= 256,
|
||||
)
|
||||
) {
|
||||
return 'denied';
|
||||
}
|
||||
try {
|
||||
const response = await this.fetchImpl(`${this.baseUrl}/stores/${this.storeId}/check`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: `Bearer ${this.serviceToken}`,
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
authorization_model_id: this.modelId,
|
||||
consistency: 'HIGHER_CONSISTENCY',
|
||||
tuple_key: { user, relation, object },
|
||||
}),
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
});
|
||||
if (!response.ok || !response.body) return 'unavailable';
|
||||
const reader = response.body.getReader();
|
||||
try {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
const part = await reader.read();
|
||||
if (part.done) break;
|
||||
total += part.value.byteLength;
|
||||
if (total > maxResponseBytes) {
|
||||
void reader.cancel().catch(() => undefined);
|
||||
return 'unavailable';
|
||||
}
|
||||
chunks.push(part.value);
|
||||
}
|
||||
const result: unknown = JSON.parse(
|
||||
new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)),
|
||||
);
|
||||
if (
|
||||
!result ||
|
||||
typeof result !== 'object' ||
|
||||
Array.isArray(result) ||
|
||||
typeof (result as { allowed?: unknown }).allowed !== 'boolean'
|
||||
) {
|
||||
return 'unavailable';
|
||||
}
|
||||
return (result as { allowed: boolean }).allowed ? 'allowed' : 'denied';
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
} catch {
|
||||
return 'unavailable';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical environment variable names used across the fleet. Reads are
|
||||
* explicit (no implicit defaults) so a missing value is visible.
|
||||
*/
|
||||
export const OPENFGA_ENV = {
|
||||
baseUrl: 'OPENFGA_API_URL',
|
||||
storeId: 'OPENFGA_STORE_ID',
|
||||
modelId: 'OPENFGA_MODEL_ID',
|
||||
serviceToken: 'OPENFGA_AUTH_TOKEN',
|
||||
} as const;
|
||||
|
||||
export interface ProjectAccessOptions {
|
||||
/** The already-configured relationship reader, or undefined when OpenFGA is not configured. */
|
||||
relationships?: OpenFgaRelationships;
|
||||
/**
|
||||
* Optional extra policy (project status, capability, data-handling). It runs
|
||||
* only after the relationship check matched; a rejection is final.
|
||||
*/
|
||||
additionalPolicy?: (scope: ProjectRelationshipScope) => Promise<boolean> | boolean;
|
||||
}
|
||||
|
||||
/** Fail closed: only an explicit match with no policy objection is allowed. */
|
||||
export async function isProjectAccessAllowed(
|
||||
scope: ProjectRelationshipScope,
|
||||
options: ProjectAccessOptions,
|
||||
): Promise<boolean> {
|
||||
if (!options.relationships) return false;
|
||||
const result = await options.relationships.checkProject(scope);
|
||||
if (result !== 'relationships_match') return false;
|
||||
if (options.additionalPolicy) {
|
||||
try {
|
||||
return (await options.additionalPolicy(scope)) === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a relationship reader from a `NodeJS.ProcessEnv`-shaped object.
|
||||
* Returns `undefined` (fail closed) when any value is missing or invalid.
|
||||
*/
|
||||
export function openFgaFromEnv(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
fetchImpl?: typeof fetch,
|
||||
): OpenFgaRelationships | undefined {
|
||||
const baseUrl = env[OPENFGA_ENV.baseUrl];
|
||||
const storeId = env[OPENFGA_ENV.storeId];
|
||||
const modelId = env[OPENFGA_ENV.modelId];
|
||||
const serviceToken = env[OPENFGA_ENV.serviceToken];
|
||||
if (!baseUrl || !storeId || !modelId || !serviceToken) return undefined;
|
||||
try {
|
||||
return new OpenFgaRelationships({
|
||||
baseUrl,
|
||||
storeId,
|
||||
modelId,
|
||||
serviceToken,
|
||||
...(fetchImpl ? { fetchImpl } : {}),
|
||||
});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
Generated
+21
-55
@@ -108,9 +108,6 @@ importers:
|
||||
'@siax/access':
|
||||
specifier: workspace:*
|
||||
version: link:packages/siax-access
|
||||
'@siax/auth-zitadel':
|
||||
specifier: 0.1.1
|
||||
version: 0.1.1
|
||||
'@siax/charts':
|
||||
specifier: ^0.5.0
|
||||
version: 0.5.0([email protected]([email protected]))([email protected])
|
||||
@@ -121,8 +118,8 @@ importers:
|
||||
specifier: ^0.2.1
|
||||
version: 0.2.1([email protected])
|
||||
'@siax/contracts':
|
||||
specifier: ^0.12.1
|
||||
version: 0.12.1
|
||||
specifier: ^0.11.1
|
||||
version: 0.11.1
|
||||
'@siax/import-export':
|
||||
specifier: ^0.2.2
|
||||
version: 0.2.2
|
||||
@@ -130,8 +127,8 @@ importers:
|
||||
specifier: ^0.1.2
|
||||
version: 0.1.2
|
||||
'@siax/ui':
|
||||
specifier: ^0.16.13
|
||||
version: 0.16.13(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])
|
||||
specifier: ^0.15.1
|
||||
version: 0.15.1(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])
|
||||
autoprefixer:
|
||||
specifier: ^10.4.20
|
||||
version: 10.5.5([email protected])
|
||||
@@ -1549,23 +1546,14 @@ packages:
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@siax/analytical-context@0.5.1':
|
||||
resolution: {integrity: sha512-bqc2NGPyzLVcu4VUgz1XYsyghSM4c3ck5gBVFSzeRYMhe2cj0nf5Fm5n/sFaOuhMaKdDnX/TIR2FO6f21lgufg==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fanalytical-context/-/0.5.1/analytical-context-0.5.1.tgz}
|
||||
|
||||
'@siax/[email protected]':
|
||||
resolution: {integrity: sha512-oTfEO4S6pv3rQ6bSh44+fRWPiwGr9nYCf6uWSBF8g5PFUspW6nr4wKQZVAkLNwfC0Pu6o+CH8ltsuu+fY8gOQA==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fauth-core/-/0.1.0/auth-core-0.1.0.tgz}
|
||||
|
||||
'@siax/[email protected]':
|
||||
resolution: {integrity: sha512-SmoBswG5P7szZIaETqmo1NN5RhdXLq2RDR/1wObfxHM2yUEXNSZQJznZoAb8z3lm/PvBgQhmnHiOHCfidN1ZQg==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fauth-zitadel/-/0.1.1/auth-zitadel-0.1.1.tgz}
|
||||
|
||||
'@siax/[email protected]':
|
||||
resolution: {integrity: sha512-IQnby+h6jVMaRAM7DcfUMuMbSUjd8B3+AGk9N4pXk2GDudMRMjt0bTtu75637Jc1Mf4iNonvgp8ytKlS7KdW4A==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fcharts/-/0.11.0/charts-0.11.0.tgz}
|
||||
'@siax/charts@0.5.0':
|
||||
resolution: {integrity: sha512-hQA5s0OD0L5aka9yg2mzajoW1tU+RIjZco4lrJFRw8k+EBRPES6ooKi8OAUCsuO/5u+RWrQZsea9nWJCu0oI+g==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fcharts/-/0.5.0/charts-0.5.0.tgz}
|
||||
peerDependencies:
|
||||
react: ^19.2.0
|
||||
react-dom: ^19.2.0
|
||||
|
||||
'@siax/[email protected].0':
|
||||
resolution: {integrity: sha512-hQA5s0OD0L5aka9yg2mzajoW1tU+RIjZco4lrJFRw8k+EBRPES6ooKi8OAUCsuO/5u+RWrQZsea9nWJCu0oI+g==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fcharts/-/0.5.0/charts-0.5.0.tgz}
|
||||
'@siax/[email protected].1':
|
||||
resolution: {integrity: sha512-SFo6771jplE3fpUu2IsK11NipM5iAlM2h1N7jdVgsqqs3do+TnOi2knhIPSpUBhKfh5bZwMvO5v2TsrZmtsO+g==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fcharts/-/0.5.1/charts-0.5.1.tgz}
|
||||
peerDependencies:
|
||||
react: ^19.2.0
|
||||
react-dom: ^19.2.0
|
||||
@@ -1581,20 +1569,14 @@ packages:
|
||||
'@siax/[email protected]':
|
||||
resolution: {integrity: sha512-sn0ZlprJE8LcbKF4PF8wBOhdOfygOG/JbU7nB+NDFBBP/AhtvMXcxFGl1oX0GadifD7VqZrVSoCliQqY/V/HYg==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fcontracts/-/0.11.1/contracts-0.11.1.tgz}
|
||||
|
||||
'@siax/[email protected]':
|
||||
resolution: {integrity: sha512-gSvMYRSxfbPPAqUGRjUMO1s38E4LdmIzDEpiNNIiGVminDHHwCOCybnhf2YNYaIfm6VBYoq4rP4yCERrpJregA==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fcontracts/-/0.12.1/contracts-0.12.1.tgz}
|
||||
|
||||
'@siax/[email protected]':
|
||||
resolution: {integrity: sha512-mb2fM6lVjWh6cVdoBFOLTdyjYRtjMjlSxNtpNHZHdW51tDrNZRNZc0Mz+lVIFsJHQ79NbL2J8GsWpHmL/rVBzg==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fimport-export/-/0.2.2/import-export-0.2.2.tgz}
|
||||
|
||||
'@siax/[email protected]':
|
||||
resolution: {integrity: sha512-xYRLF/5B7EyK3jbZCsPvDcEhZRGC/72QQpkEIsFJQqKwUxsejiQ1RabjzLoF0wNjIKlubEYnkfxDBaJMeIgKrg==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fimport-export/-/0.2.4/import-export-0.2.4.tgz}
|
||||
|
||||
'@siax/[email protected]':
|
||||
resolution: {integrity: sha512-pz4tP8cyzhWh5gGw9GQLHjl4E/w/WemfYR5x5rdejneg+OSJYEmf6pvGCirj7247DhPqX0BH19uJK8ZN8S/Hcg==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Ftokens/-/0.1.2/tokens-0.1.2.tgz}
|
||||
|
||||
'@siax/[email protected]6.13':
|
||||
resolution: {integrity: sha512-qWmGexMa7kqol5O3MBDkraF/s5APAahNyGHQusDZ34YDZvGnlr3t7raWIVJMFHgz6D0Fsgyuak6210Ktn3SpHA==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fui/-/0.16.13/ui-0.16.13.tgz}
|
||||
'@siax/[email protected]5.1':
|
||||
resolution: {integrity: sha512-GeU+Iwj7s3cWJUHfvt0r07dWGCGvh9jG9cS9D4EkdKb+EQGhOns2IGbDNPYRkLj/t55Qz2fjSrYCMwXO19zPDw==, tarball: https://git.siax.io/api/packages/sax3l/npm/%40siax%2Fui/-/0.15.1/ui-0.15.1.tgz}
|
||||
peerDependencies:
|
||||
react: ^19.2.0
|
||||
react-dom: ^19.2.0
|
||||
@@ -4243,17 +4225,16 @@ snapshots:
|
||||
'@rollup/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@siax/[email protected]': {}
|
||||
|
||||
'@siax/[email protected]': {}
|
||||
|
||||
'@siax/[email protected]':
|
||||
'@siax/[email protected]([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@siax/auth-core': 0.1.0
|
||||
clsx: 2.1.1
|
||||
echarts: 6.1.0
|
||||
react: 19.2.8
|
||||
react-dom: 19.2.8([email protected])
|
||||
tailwind-merge: 2.6.1
|
||||
|
||||
'@siax/charts@0.11.0([email protected]([email protected]))([email protected])([email protected])':
|
||||
'@siax/charts@0.5.1([email protected]([email protected]))([email protected])([email protected])':
|
||||
dependencies:
|
||||
'@siax/analytical-context': 0.5.1
|
||||
'@siax/config': 0.2.1([email protected])
|
||||
clsx: 2.1.1
|
||||
echarts: 6.1.0
|
||||
@@ -4263,14 +4244,6 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- tailwindcss
|
||||
|
||||
'@siax/[email protected]([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
clsx: 2.1.1
|
||||
echarts: 6.1.0
|
||||
react: 19.2.8
|
||||
react-dom: 19.2.8([email protected])
|
||||
tailwind-merge: 2.6.1
|
||||
|
||||
'@siax/[email protected]': {}
|
||||
|
||||
'@siax/[email protected]([email protected])':
|
||||
@@ -4279,19 +4252,13 @@ snapshots:
|
||||
|
||||
'@siax/[email protected]': {}
|
||||
|
||||
'@siax/[email protected]': {}
|
||||
|
||||
'@siax/[email protected]':
|
||||
dependencies:
|
||||
'@siax/contracts': 0.11.1
|
||||
|
||||
'@siax/[email protected]':
|
||||
dependencies:
|
||||
'@siax/contracts': 0.12.1
|
||||
|
||||
'@siax/[email protected]': {}
|
||||
|
||||
'@siax/[email protected]6.13(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])':
|
||||
'@siax/[email protected]5.1(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])':
|
||||
dependencies:
|
||||
'@radix-ui/react-alert-dialog': 1.1.23(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
|
||||
'@radix-ui/react-aspect-ratio': 1.1.15(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
|
||||
@@ -4314,11 +4281,10 @@ snapshots:
|
||||
'@radix-ui/react-toggle': 1.1.18(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
|
||||
'@radix-ui/react-toggle-group': 1.1.19(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
|
||||
'@radix-ui/react-tooltip': 1.2.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
|
||||
'@siax/analytical-context': 0.5.1
|
||||
'@siax/charts': 0.11.0([email protected]([email protected]))([email protected])([email protected])
|
||||
'@siax/charts': 0.5.1([email protected]([email protected]))([email protected])([email protected])
|
||||
'@siax/config': 0.2.1([email protected])
|
||||
'@siax/contracts': 0.12.1
|
||||
'@siax/import-export': 0.2.4
|
||||
'@siax/contracts': 0.11.1
|
||||
'@siax/import-export': 0.2.2
|
||||
'@siax/tokens': 0.1.2
|
||||
'@tanstack/react-table': 8.21.3([email protected]([email protected]))([email protected])
|
||||
'@tanstack/react-virtual': 3.14.13([email protected]([email protected]))([email protected])
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
FROM python:3.12-slim
|
||||
WORKDIR /app
|
||||
ENV PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1
|
||||
COPY requirements.txt .
|
||||
RUN pip install -r requirements.txt
|
||||
COPY app.py ingest_aud0.py ./
|
||||
EXPOSE 8096
|
||||
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
|
||||
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8096/health', timeout=3)"
|
||||
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8096"]
|
||||
@@ -1,47 +0,0 @@
|
||||
# 0pt analytics HTTP surface
|
||||
|
||||
The missing read plane between API0's `/analytics/*` contract and the
|
||||
`opt_analytics` ClickHouse database.
|
||||
|
||||
## Surface
|
||||
|
||||
Serves the BI-P068 operation paths under `/api/0pt/analytics`:
|
||||
|
||||
- `GET /health`
|
||||
- `GET /datasets`, `GET /datasets/{id}`
|
||||
- `GET /metrics`, `GET /metrics/{id}`, `GET /metrics/{id}/explain`
|
||||
- `POST /metrics/{id}/query`
|
||||
- `POST /query`, `POST /query/estimate`, `POST /query/explain`
|
||||
- `GET /query/{id}` (404: executions are not persisted yet)
|
||||
- `GET /dashboards`, `GET /reports` (empty until the BI metadata lane writes them)
|
||||
- `GET /search`
|
||||
|
||||
Identity: the caller's Keycloak token is verified against the portal realm
|
||||
JWKS; `tenant_id` is taken from the token and cross-checked against
|
||||
`X-Tenant-Id`. An `X-Internal-Token` path exists only for the ingestion worker.
|
||||
|
||||
## Ingest
|
||||
|
||||
`ingest_aud0.py` maps AUD0 audit events to `opt_analytics_event`
|
||||
(`dataset_id=aud0.events`, `metric=event_count`, dimensions event_type/app_id/
|
||||
capability_id/risk_level). It is idempotent per `event_id`.
|
||||
|
||||
```bash
|
||||
AUD0_TOKEN=... AUD0_TENANT_ID=... CLICKHOUSE_URL=http://opt-analytics-clickhouse:8123 \
|
||||
python ingest_aud0.py --limit 50000
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
CLICKHOUSE_URL=http://opt-analytics-clickhouse:8123 \
|
||||
KEYCLOAK_ISSUER=https://auth.portal.siax.dev/realms/portal \
|
||||
uvicorn app:app --host 0.0.0.0 --port 8096
|
||||
```
|
||||
|
||||
## Test
|
||||
|
||||
```bash
|
||||
python -m pytest tests -q
|
||||
```
|
||||
@@ -1,464 +0,0 @@
|
||||
"""
|
||||
0pt analytics HTTP surface (BI-P068-compatible).
|
||||
|
||||
This is the missing read plane between API0's `/analytics/*` contract and the
|
||||
`opt_analytics` ClickHouse database. It does not invent a second analytics
|
||||
model:
|
||||
|
||||
* datasets/metrics are the distinct ids actually present in
|
||||
`opt_analytics_event` / `opt_metric_daily` / `opt_dataset_projection`;
|
||||
* query/estimate/explain are computed against the tenant-forced ClickHouse
|
||||
rows, never against a local cache;
|
||||
* dashboards/reports are honest empty lists until the 0pt BI metadata lane
|
||||
writes them;
|
||||
* every response is either real ClickHouse data or an explicit error.
|
||||
|
||||
IDENTITY. API0 verifies the caller and forwards the caller's own Keycloak
|
||||
token plus `X-Tenant-Id`. This service verifies the same token against the
|
||||
portal realm's JWKS and cross-checks `tenant_id` against `X-Tenant-Id`. A
|
||||
service-to-service `X-Internal-Token` is also accepted for the ingestion
|
||||
worker, but never for a request that reads tenant data without an explicit,
|
||||
already-verified `X-Tenant-Id`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from functools import lru_cache
|
||||
from typing import Any, Iterable, Literal
|
||||
|
||||
import httpx
|
||||
import jwt
|
||||
from fastapi import FastAPI, Header, HTTPException, Query, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
CLICKHOUSE_URL = os.getenv("CLICKHOUSE_URL", "").rstrip("/")
|
||||
CLICKHOUSE_USER = os.getenv("CLICKHOUSE_USER", "default")
|
||||
CLICKHOUSE_PASSWORD = os.getenv("CLICKHOUSE_PASSWORD", "")
|
||||
CLICKHOUSE_DATABASE = os.getenv("CLICKHOUSE_DATABASE", "opt_analytics")
|
||||
KEYCLOAK_ISSUER = os.getenv("KEYCLOAK_ISSUER", "").rstrip("/")
|
||||
KEYCLOAK_AUDIENCE = os.getenv("KEYCLOAK_AUDIENCE", "account")
|
||||
KEYCLOAK_AUTHORIZED_PARTY = os.getenv("KEYCLOAK_AUTHORIZED_PARTY", "siax-portal")
|
||||
INTERNAL_TOKEN = os.getenv("INTERNAL_TOKEN", "")
|
||||
ALLOWED_DIMENSIONS = {"event_type", "app_id", "capability_id", "risk_level", "source_service"}
|
||||
|
||||
app = FastAPI(title="0pt analytics", version="0.1")
|
||||
|
||||
|
||||
class AnalyticsError(Exception):
|
||||
def __init__(self, code: str, message: str, status: int = 400):
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.status = status
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
@app.exception_handler(AnalyticsError)
|
||||
async def analytics_error_handler(_request: Request, exc: AnalyticsError) -> JSONResponse:
|
||||
return JSONResponse(status_code=exc.status, content={"error": {"code": exc.code, "message": exc.message}})
|
||||
|
||||
|
||||
# ── identity ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _jwks_client() -> jwt.PyJWKClient:
|
||||
if not KEYCLOAK_ISSUER:
|
||||
raise AnalyticsError("ANALYTICS_NOT_CONFIGURED", "KEYCLOAK_ISSUER is not set", 503)
|
||||
return jwt.PyJWKClient(f"{KEYCLOAK_ISSUER}/protocol/openid-connect/certs", cache_keys=True, lifespan=3600)
|
||||
|
||||
|
||||
def _bearer(request: Request) -> str | None:
|
||||
raw = request.headers.get("authorization", "")
|
||||
if not raw.lower().startswith("bearer "):
|
||||
return None
|
||||
return raw[7:].strip() or None
|
||||
|
||||
|
||||
def verified_identity(request: Request, x_tenant_id: str | None) -> str:
|
||||
"""Return the tenant the request is allowed to read.
|
||||
|
||||
An `X-Internal-Token` may only be used by the ingestion worker and never
|
||||
substitutes for a tenant claim. For user/API0 calls the JWT is the source
|
||||
of truth; a mismatching X-Tenant-Id is a hard 403, not a preference.
|
||||
"""
|
||||
if INTERNAL_TOKEN and request.headers.get("x-internal-token") == INTERNAL_TOKEN:
|
||||
if not x_tenant_id:
|
||||
raise AnalyticsError("TENANT_REQUIRED", "X-Tenant-Id is required for internal calls", 400)
|
||||
return x_tenant_id
|
||||
|
||||
token = _bearer(request)
|
||||
if not token:
|
||||
raise AnalyticsError("UNAUTHENTICATED", "A bearer token is required", 401)
|
||||
try:
|
||||
signing_key = _jwks_client().get_signing_key_from_jwt(token)
|
||||
claims = jwt.decode(
|
||||
token,
|
||||
signing_key.key,
|
||||
algorithms=["RS256", "RS384", "RS512"],
|
||||
audience=KEYCLOAK_AUDIENCE,
|
||||
issuer=KEYCLOAK_ISSUER,
|
||||
options={"require": ["exp", "iss", "sub"]},
|
||||
)
|
||||
except jwt.PyJWTError as exc:
|
||||
raise AnalyticsError("UNAUTHENTICATED", f"Invalid bearer token: {exc}", 401) from exc
|
||||
|
||||
if KEYCLOAK_AUTHORIZED_PARTY and claims.get("azp") not in (None, KEYCLOAK_AUTHORIZED_PARTY):
|
||||
raise AnalyticsError("FORBIDDEN", "Token was issued for a different client", 403)
|
||||
tenant = claims.get("tenant_id")
|
||||
if not isinstance(tenant, str) or not tenant.strip():
|
||||
raise AnalyticsError("NO_TENANT", "Token is not bound to a tenant", 403)
|
||||
if x_tenant_id and x_tenant_id != tenant:
|
||||
raise AnalyticsError("TENANT_MISMATCH", "X-Tenant-Id does not match the verified tenant", 403)
|
||||
return tenant
|
||||
|
||||
|
||||
# ── clickhouse ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _ch_client() -> httpx.Client:
|
||||
if not CLICKHOUSE_URL:
|
||||
raise AnalyticsError("ANALYTICS_NOT_CONFIGURED", "CLICKHOUSE_URL is not set", 503)
|
||||
auth = (CLICKHOUSE_USER, CLICKHOUSE_PASSWORD) if CLICKHOUSE_PASSWORD else None
|
||||
return httpx.Client(base_url=CLICKHOUSE_URL, auth=auth, timeout=20.0)
|
||||
|
||||
|
||||
def ch_json(sql: str, params: dict[str, str] | None = None) -> dict[str, Any]:
|
||||
params = params or {}
|
||||
query_params = {
|
||||
"database": CLICKHOUSE_DATABASE,
|
||||
"output_format_json_quote_64bit_integers": "0",
|
||||
**{f"param_{key}": value for key, value in params.items()},
|
||||
}
|
||||
try:
|
||||
with _ch_client() as client:
|
||||
response = client.post("/", params=query_params, content=sql)
|
||||
except httpx.HTTPError as exc:
|
||||
raise AnalyticsError("CLICKHOUSE_UNREACHABLE", str(exc), 503) from exc
|
||||
if response.status_code != 200:
|
||||
raise AnalyticsError("CLICKHOUSE_REFUSED", response.text[:500], 502)
|
||||
try:
|
||||
return response.json()
|
||||
except ValueError as exc:
|
||||
raise AnalyticsError("CLICKHOUSE_BAD_RESPONSE", "ClickHouse did not return JSON", 502) from exc
|
||||
|
||||
|
||||
def _literal(value: str) -> str:
|
||||
# ClickHouse query parameters are preferable; the only values interpolated
|
||||
# here are identifiers from ALLOWED_DIMENSIONS, never caller text.
|
||||
if value not in ALLOWED_DIMENSIONS:
|
||||
raise AnalyticsError("INVALID_DIMENSION", f"Unsupported dimension: {value}")
|
||||
return value
|
||||
|
||||
|
||||
def rows(sql: str, params: dict[str, str] | None = None) -> list[dict[str, Any]]:
|
||||
return ch_json(sql, params).get("data", [])
|
||||
|
||||
|
||||
def scalar(sql: str, params: dict[str, str] | None = None) -> Any:
|
||||
data = rows(sql, params)
|
||||
if not data:
|
||||
return None
|
||||
return next(iter(data[0].values()))
|
||||
|
||||
|
||||
def build_query(
|
||||
*,
|
||||
tenant: str,
|
||||
dataset: str | None,
|
||||
metrics: Iterable[str],
|
||||
dimensions: Iterable[str],
|
||||
filters: dict[str, str] | None,
|
||||
from_time: str | None,
|
||||
to_time: str | None,
|
||||
limit: int,
|
||||
) -> tuple[str, dict[str, str]]:
|
||||
dims = [_literal(d) for d in dimensions]
|
||||
metric_list = [m for m in metrics if m.strip()]
|
||||
if not metric_list:
|
||||
raise AnalyticsError("INVALID_REQUEST", "At least one metric is required")
|
||||
where = ["tenant_id = {tenant:String}"]
|
||||
params: dict[str, str] = {"tenant": tenant, "limit": str(max(1, min(limit, 1000)))}
|
||||
if dataset:
|
||||
where.append("dataset_id = {dataset:String}")
|
||||
params["dataset"] = dataset
|
||||
metric_params = []
|
||||
for i, metric in enumerate(metric_list):
|
||||
key = f"metric{i}"
|
||||
metric_params.append(f"{{{key}:String}}")
|
||||
params[key] = metric
|
||||
where.append(f"metric IN ({', '.join(metric_params)})")
|
||||
for i, (key, value) in enumerate((filters or {}).items()):
|
||||
dim = _literal(key)
|
||||
p = f"filter{i}"
|
||||
where.append(f"dim_values[indexOf(dim_names, '{dim}')] = {{{p}:String}}")
|
||||
params[p] = value
|
||||
if from_time:
|
||||
where.append("event_time >= {from:String}")
|
||||
params["from"] = from_time
|
||||
if to_time:
|
||||
where.append("event_time <= {to:String}")
|
||||
params["to"] = to_time
|
||||
|
||||
select_dims = []
|
||||
for i, dim in enumerate(dims):
|
||||
select_dims.append(f"dim_values[indexOf(dim_names, '{dim}')] AS d{i}")
|
||||
select = ", ".join(select_dims + ["count() AS value"])
|
||||
group = f" GROUP BY {', '.join(f'd{i}' for i in range(len(dims)))}" if dims else ""
|
||||
sql = (
|
||||
f"SELECT {select} FROM {CLICKHOUSE_DATABASE}.opt_analytics_event "
|
||||
f"WHERE {' AND '.join(where)}{group} ORDER BY value DESC LIMIT {{limit:UInt32}} FORMAT JSON"
|
||||
)
|
||||
return sql, params
|
||||
|
||||
|
||||
# ── models ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class QueryRequest(BaseModel):
|
||||
dataset: str | None = None
|
||||
metrics: list[str] = Field(default_factory=list)
|
||||
dimensions: list[str] = Field(default_factory=list)
|
||||
filters: dict[str, str] | None = None
|
||||
timeRange: dict[str, str] | None = None
|
||||
limit: int = 100
|
||||
|
||||
|
||||
# ── surface ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health() -> dict[str, Any]:
|
||||
try:
|
||||
ch_json("SELECT 1")
|
||||
return {"status": "ok", "providers": {"clickhouse": {"status": "ok"}}}
|
||||
except AnalyticsError as exc:
|
||||
return {"status": "error", "providers": {"clickhouse": {"status": "error", "detail": exc.message}}}
|
||||
|
||||
|
||||
@app.get("/api/0pt/analytics/health")
|
||||
def analytics_health() -> dict[str, Any]:
|
||||
return health()
|
||||
|
||||
|
||||
@app.get("/api/0pt/analytics/datasets")
|
||||
def list_datasets(request: Request, x_tenant_id: str | None = Header(default=None)) -> list[dict[str, Any]]:
|
||||
tenant = verified_identity(request, x_tenant_id)
|
||||
rows_ = rows(
|
||||
f"SELECT dataset_id, count() AS events FROM {CLICKHOUSE_DATABASE}.opt_analytics_event "
|
||||
"WHERE tenant_id = {tenant:String} GROUP BY dataset_id ORDER BY dataset_id FORMAT JSON",
|
||||
{"tenant": tenant},
|
||||
)
|
||||
if not rows_:
|
||||
rows_ = rows(
|
||||
f"SELECT dataset_id, count() AS rows FROM {CLICKHOUSE_DATABASE}.opt_dataset_projection "
|
||||
"WHERE tenant_id = {tenant:String} GROUP BY dataset_id ORDER BY dataset_id FORMAT JSON",
|
||||
{"tenant": tenant},
|
||||
)
|
||||
return [
|
||||
{
|
||||
"id": r["dataset_id"],
|
||||
"name": r["dataset_id"],
|
||||
"tier": "SERVING",
|
||||
"owner": "0pt",
|
||||
"source": "0pt analytics",
|
||||
"tenant_id": tenant,
|
||||
**({"events": r.get("events")} if "events" in r else {}),
|
||||
**({"rows": r.get("rows")} if "rows" in r else {}),
|
||||
}
|
||||
for r in rows_
|
||||
]
|
||||
|
||||
|
||||
@app.get("/api/0pt/analytics/datasets/{dataset_id}")
|
||||
def get_dataset(dataset_id: str, request: Request, x_tenant_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
tenant = verified_identity(request, x_tenant_id)
|
||||
found = [d for d in list_datasets(request, x_tenant_id) if d["id"] == dataset_id]
|
||||
if not found:
|
||||
raise AnalyticsError("NOT_FOUND", f"dataset {dataset_id} does not exist for this tenant", 404)
|
||||
return found[0]
|
||||
|
||||
|
||||
@app.get("/api/0pt/analytics/metrics")
|
||||
def list_metrics(request: Request, x_tenant_id: str | None = Header(default=None)) -> list[dict[str, Any]]:
|
||||
tenant = verified_identity(request, x_tenant_id)
|
||||
rows_ = rows(
|
||||
f"SELECT metric, count() AS events FROM {CLICKHOUSE_DATABASE}.opt_analytics_event "
|
||||
"WHERE tenant_id = {tenant:String} GROUP BY metric ORDER BY metric FORMAT JSON",
|
||||
{"tenant": tenant},
|
||||
)
|
||||
if not rows_:
|
||||
rows_ = rows(
|
||||
f"SELECT metric, sum(count_state) AS events FROM {CLICKHOUSE_DATABASE}.opt_metric_daily "
|
||||
"WHERE tenant_id = {tenant:String} GROUP BY metric ORDER BY metric FORMAT JSON",
|
||||
{"tenant": tenant},
|
||||
)
|
||||
dims = rows(
|
||||
f"SELECT DISTINCT arrayJoin(dim_names) AS name FROM {CLICKHOUSE_DATABASE}.opt_analytics_event "
|
||||
"WHERE tenant_id = {tenant:String} FORMAT JSON",
|
||||
{"tenant": tenant},
|
||||
)
|
||||
dimension_defs = [{"name": d["name"], "type": "string"} for d in dims]
|
||||
return [
|
||||
{
|
||||
"id": r["metric"],
|
||||
"name": r["metric"],
|
||||
"description": f"0pt analytics metric {r['metric']}",
|
||||
"datasets": ["aud0.events"],
|
||||
"dimensions": dimension_defs,
|
||||
"tenant_id": tenant,
|
||||
**({"events": r.get("events")} if "events" in r else {}),
|
||||
}
|
||||
for r in rows_
|
||||
]
|
||||
|
||||
|
||||
@app.get("/api/0pt/analytics/metrics/{metric_id}")
|
||||
def get_metric(metric_id: str, request: Request, x_tenant_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
tenant = verified_identity(request, x_tenant_id)
|
||||
found = [m for m in list_metrics(request, x_tenant_id) if m["id"] == metric_id]
|
||||
if not found:
|
||||
raise AnalyticsError("NOT_FOUND", f"metric {metric_id} does not exist for this tenant", 404)
|
||||
return found[0]
|
||||
|
||||
|
||||
def _run_query(request: Request, x_tenant_id: str | None, body: QueryRequest, metric: str | None = None) -> dict[str, Any]:
|
||||
tenant = verified_identity(request, x_tenant_id)
|
||||
metrics = [metric] if metric else body.metrics
|
||||
dataset = body.dataset or "aud0.events"
|
||||
sql, params = build_query(
|
||||
tenant=tenant,
|
||||
dataset=dataset,
|
||||
metrics=metrics,
|
||||
dimensions=body.dimensions,
|
||||
filters=body.filters,
|
||||
from_time=(body.timeRange or {}).get("from"),
|
||||
to_time=(body.timeRange or {}).get("to"),
|
||||
limit=body.limit,
|
||||
)
|
||||
started = time.time()
|
||||
data = ch_json(sql, params)
|
||||
result_rows = data.get("data", [])
|
||||
duration_ms = int((time.time() - started) * 1000)
|
||||
columns = []
|
||||
if result_rows:
|
||||
columns = [{"name": key, "type": "string" if key.startswith("d") else "number"} for key in result_rows[0].keys()]
|
||||
return {
|
||||
"query_id": f"ch-{int(time.time() * 1000)}",
|
||||
"status": "succeeded",
|
||||
"engine": "clickhouse",
|
||||
"submitted_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"completed_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"duration": duration_ms,
|
||||
"rows": len(result_rows),
|
||||
"tenant_id": tenant,
|
||||
"result": {"columns": columns, "rows": result_rows, "truncated": len(result_rows) >= body.limit},
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/0pt/analytics/query")
|
||||
def execute_query(body: QueryRequest, request: Request, x_tenant_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
return _run_query(request, x_tenant_id, body)
|
||||
|
||||
|
||||
@app.post("/api/0pt/analytics/metrics/{metric_id}/query")
|
||||
def execute_metric(metric_id: str, body: QueryRequest, request: Request, x_tenant_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
return _run_query(request, x_tenant_id, body, metric=metric_id)
|
||||
|
||||
|
||||
@app.post("/api/0pt/analytics/query/estimate")
|
||||
def estimate_query(body: QueryRequest, request: Request, x_tenant_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
tenant = verified_identity(request, x_tenant_id)
|
||||
sql, params = build_query(
|
||||
tenant=tenant,
|
||||
dataset=body.dataset or "aud0.events",
|
||||
metrics=body.metrics or ["event_count"],
|
||||
dimensions=body.dimensions,
|
||||
filters=body.filters,
|
||||
from_time=(body.timeRange or {}).get("from"),
|
||||
to_time=(body.timeRange or {}).get("to"),
|
||||
limit=body.limit,
|
||||
)
|
||||
count = scalar(
|
||||
f"SELECT count() FROM {CLICKHOUSE_DATABASE}.opt_analytics_event WHERE tenant_id = {{tenant:String}} FORMAT JSON",
|
||||
{"tenant": tenant},
|
||||
)
|
||||
return {"estimated_rows_to_read": count or 0, "within_budget": True, "rows": count or 0}
|
||||
|
||||
|
||||
@app.post("/api/0pt/analytics/query/explain")
|
||||
def explain_query(body: QueryRequest, request: Request, x_tenant_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
tenant = verified_identity(request, x_tenant_id)
|
||||
sql, _params = build_query(
|
||||
tenant=tenant,
|
||||
dataset=body.dataset or "aud0.events",
|
||||
metrics=body.metrics or ["event_count"],
|
||||
dimensions=body.dimensions,
|
||||
filters=body.filters,
|
||||
from_time=(body.timeRange or {}).get("from"),
|
||||
to_time=(body.timeRange or {}).get("to"),
|
||||
limit=body.limit,
|
||||
)
|
||||
return {"plan": sql, "forced_tenant_predicate": "tenant_id = {tenant:String}", "table": "opt_analytics_event"}
|
||||
|
||||
|
||||
@app.get("/api/0pt/analytics/metrics/{metric_id}/explain")
|
||||
def explain_metric(metric_id: str, request: Request, x_tenant_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
return explain_query(QueryRequest(metrics=[metric_id]), request, x_tenant_id)
|
||||
|
||||
|
||||
@app.get("/api/0pt/analytics/dashboards")
|
||||
def list_dashboards(request: Request, x_tenant_id: str | None = Header(default=None)) -> list[dict[str, Any]]:
|
||||
verified_identity(request, x_tenant_id)
|
||||
return []
|
||||
|
||||
|
||||
@app.get("/api/0pt/analytics/dashboards/{dashboard_id}")
|
||||
def get_dashboard(dashboard_id: str, request: Request, x_tenant_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
verified_identity(request, x_tenant_id)
|
||||
raise AnalyticsError("NOT_FOUND", f"dashboard {dashboard_id} does not exist", 404)
|
||||
|
||||
|
||||
@app.get("/api/0pt/analytics/reports")
|
||||
def list_reports(request: Request, x_tenant_id: str | None = Header(default=None)) -> list[dict[str, Any]]:
|
||||
verified_identity(request, x_tenant_id)
|
||||
return []
|
||||
|
||||
|
||||
@app.get("/api/0pt/analytics/reports/{report_id}")
|
||||
def get_report(report_id: str, request: Request, x_tenant_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
verified_identity(request, x_tenant_id)
|
||||
raise AnalyticsError("NOT_FOUND", f"report {report_id} does not exist", 404)
|
||||
|
||||
|
||||
@app.get("/api/0pt/analytics/search")
|
||||
def search_catalog(
|
||||
request: Request,
|
||||
q: str = Query(default=""),
|
||||
types: str = Query(default=""),
|
||||
limit: int = Query(default=20, ge=1, le=100),
|
||||
x_tenant_id: str | None = Header(default=None),
|
||||
) -> dict[str, Any]:
|
||||
tenant = verified_identity(request, x_tenant_id)
|
||||
wanted = {t.strip() for t in types.split(",") if t.strip()}
|
||||
hits: list[dict[str, Any]] = []
|
||||
for dataset in list_datasets(request, x_tenant_id):
|
||||
if (not wanted or "dataset" in wanted) and (not q or q.lower() in dataset["id"].lower()):
|
||||
hits.append({**dataset, "type": "dataset", "canonical": False, "canonicalOperation": "getDataset"})
|
||||
for metric in list_metrics(request, x_tenant_id):
|
||||
if (not wanted or "metric" in wanted) and (not q or q.lower() in metric["id"].lower()):
|
||||
hits.append({**metric, "type": "metric", "canonical": False, "canonicalOperation": "getMetric"})
|
||||
return {"query": q, "derived": True, "hits": hits[:limit], "tenant_id": tenant}
|
||||
|
||||
|
||||
@app.get("/api/0pt/analytics/query/{query_id}")
|
||||
def get_query(query_id: str, request: Request, x_tenant_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
verified_identity(request, x_tenant_id)
|
||||
raise AnalyticsError("NOT_FOUND", f"query {query_id} is not persisted", 404)
|
||||
|
||||
|
||||
@app.post("/api/0pt/analytics/query/{query_id}/cancel")
|
||||
def cancel_query(query_id: str, request: Request, x_tenant_id: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
verified_identity(request, x_tenant_id)
|
||||
raise AnalyticsError("NOT_FOUND", f"query {query_id} is not running", 404)
|
||||
@@ -1,154 +0,0 @@
|
||||
"""
|
||||
Backfill/refresh: AUD0 events -> 0pt ClickHouse analytics events.
|
||||
|
||||
One audit event becomes one analytics event with metric `event_count` and
|
||||
dimensions `event_type`, `app_id`, `capability_id`, `risk_level`. The write is
|
||||
idempotent per event_id: already-present ids are skipped before the batch is
|
||||
inserted. No synthetic event is ever created; an empty AUD0 page writes
|
||||
nothing.
|
||||
|
||||
Usage:
|
||||
AUD0_TOKEN=... AUD0_TENANT_ID=379... CLICKHOUSE_URL=http://... \
|
||||
python ingest_aud0.py --limit 50000
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from typing import Any, Iterable
|
||||
|
||||
import httpx
|
||||
|
||||
AUD0_API_URL = os.getenv("AUD0_API_URL", "https://api.aud0.siax.io").rstrip("/")
|
||||
AUD0_TOKEN = os.getenv("AUD0_TOKEN", "")
|
||||
AUD0_TENANT_ID = os.getenv("AUD0_TENANT_ID", "")
|
||||
CLICKHOUSE_URL = os.getenv("CLICKHOUSE_URL", "").rstrip("/")
|
||||
CLICKHOUSE_USER = os.getenv("CLICKHOUSE_USER", "default")
|
||||
CLICKHOUSE_PASSWORD = os.getenv("CLICKHOUSE_PASSWORD", "")
|
||||
CLICKHOUSE_DATABASE = os.getenv("CLICKHOUSE_DATABASE", "opt_analytics")
|
||||
|
||||
|
||||
def dims(event: dict[str, Any]) -> tuple[list[str], list[str]]:
|
||||
names: list[str] = []
|
||||
values: list[str] = []
|
||||
for key in ("event_type", "app_id", "capability_id", "risk_level"):
|
||||
value = event.get(key)
|
||||
if isinstance(value, str) and value:
|
||||
names.append(key)
|
||||
values.append(value)
|
||||
return names, values
|
||||
|
||||
|
||||
def to_row(tenant: str, event: dict[str, Any]) -> dict[str, Any] | None:
|
||||
event_id = event.get("event_id")
|
||||
created_at = event.get("created_at")
|
||||
event_type = event.get("event_type")
|
||||
if not isinstance(event_id, str) or not event_id:
|
||||
return None
|
||||
if not isinstance(created_at, str) or not created_at:
|
||||
return None
|
||||
if not isinstance(event_type, str) or not event_type:
|
||||
return None
|
||||
names, values = dims(event)
|
||||
return {
|
||||
"tenant_id": tenant,
|
||||
"project_id": "aud0",
|
||||
"dataset_id": "aud0.events",
|
||||
"metric": "event_count",
|
||||
"event_id": event_id,
|
||||
"event_time": created_at,
|
||||
"value": 1,
|
||||
"dim_names": names,
|
||||
"dim_values": values,
|
||||
}
|
||||
|
||||
|
||||
def ch_insert(rows: Iterable[dict[str, Any]]) -> None:
|
||||
payload = "\n".join(json.dumps(row, ensure_ascii=False) for row in rows)
|
||||
if not payload:
|
||||
return
|
||||
auth = (CLICKHOUSE_USER, CLICKHOUSE_PASSWORD) if CLICKHOUSE_PASSWORD else None
|
||||
with httpx.Client(base_url=CLICKHOUSE_URL, auth=auth, timeout=60.0) as client:
|
||||
response = client.post(
|
||||
"/",
|
||||
params={"database": CLICKHOUSE_DATABASE, "query": "INSERT INTO opt_analytics_event FORMAT JSONEachRow"},
|
||||
content=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
def existing_ids(tenant: str, ids: list[str]) -> set[str]:
|
||||
if not ids:
|
||||
return set()
|
||||
auth = (CLICKHOUSE_USER, CLICKHOUSE_PASSWORD) if CLICKHOUSE_PASSWORD else None
|
||||
found: set[str] = set()
|
||||
sql = (
|
||||
f"SELECT event_id FROM {CLICKHOUSE_DATABASE}.opt_analytics_event "
|
||||
"WHERE tenant_id = {tenant:String} AND event_id IN ({ids:Array(String)}) FORMAT JSON"
|
||||
)
|
||||
with httpx.Client(base_url=CLICKHOUSE_URL, auth=auth, timeout=30.0) as client:
|
||||
# ClickHouse query parameters travel in the URL; 1000 ids overflow it.
|
||||
for start in range(0, len(ids), 50):
|
||||
chunk = ids[start : start + 50]
|
||||
response = client.post(
|
||||
"/",
|
||||
params={
|
||||
"database": CLICKHOUSE_DATABASE,
|
||||
"param_tenant": tenant,
|
||||
"param_ids": "[" + ",".join("'" + value.replace("'", "\\'") + "'" for value in chunk) + "]",
|
||||
},
|
||||
content=sql,
|
||||
)
|
||||
response.raise_for_status()
|
||||
found.update(row["event_id"] for row in response.json().get("data", []))
|
||||
return found
|
||||
|
||||
|
||||
def fetch_page(offset: int, limit: int) -> dict[str, Any]:
|
||||
if not AUD0_TOKEN or not AUD0_TENANT_ID:
|
||||
raise SystemExit("AUD0_TOKEN and AUD0_TENANT_ID are required")
|
||||
with httpx.Client(base_url=AUD0_API_URL, timeout=30.0) as client:
|
||||
response = client.get(
|
||||
"/v1/aud0/events",
|
||||
params={"tenant_id": AUD0_TENANT_ID, "limit": limit, "offset": offset},
|
||||
headers={"authorization": f"Bearer {AUD0_TOKEN}", "x-tenant-id": AUD0_TENANT_ID},
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--limit", type=int, default=50_000, help="maximum events to read")
|
||||
parser.add_argument("--page", type=int, default=1000)
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not CLICKHOUSE_URL:
|
||||
raise SystemExit("CLICKHOUSE_URL is required")
|
||||
|
||||
written = skipped = seen = 0
|
||||
for offset in range(0, args.limit, args.page):
|
||||
page = fetch_page(offset, min(args.page, args.limit - offset))
|
||||
events = page.get("events") or []
|
||||
if not events:
|
||||
break
|
||||
rows = [row for row in (to_row(AUD0_TENANT_ID, event) for event in events) if row]
|
||||
present = existing_ids(AUD0_TENANT_ID, [row["event_id"] for row in rows])
|
||||
fresh = [row for row in rows if row["event_id"] not in present]
|
||||
skipped += len(rows) - len(fresh)
|
||||
seen += len(events)
|
||||
if not args.dry_run:
|
||||
ch_insert(fresh)
|
||||
written += len(fresh)
|
||||
print(json.dumps({"offset": offset, "read": len(events), "written": len(fresh), "skipped": skipped}))
|
||||
if len(events) < args.page:
|
||||
break
|
||||
print(json.dumps({"seen": seen, "written": written, "skipped": skipped, "dry_run": args.dry_run}))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,5 +0,0 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.34.0
|
||||
httpx==0.28.1
|
||||
PyJWT[crypto]==2.14.0
|
||||
pytest==8.3.4
|
||||
@@ -1,52 +0,0 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import app as analytics # noqa: E402
|
||||
|
||||
|
||||
def test_build_query_forces_tenant_and_dimension_whitelist():
|
||||
sql, params = analytics.build_query(
|
||||
tenant="379",
|
||||
dataset="aud0.events",
|
||||
metrics=["event_count"],
|
||||
dimensions=["event_type"],
|
||||
filters={"app_id": "portal"},
|
||||
from_time="2026-01-01T00:00:00Z",
|
||||
to_time=None,
|
||||
limit=50,
|
||||
)
|
||||
assert "tenant_id = {tenant:String}" in sql
|
||||
assert "dataset_id = {dataset:String}" in sql
|
||||
assert "dim_values[indexOf(dim_names, 'event_type')]" in sql
|
||||
assert params["tenant"] == "379"
|
||||
assert params["dataset"] == "aud0.events"
|
||||
assert params["metric0"] == "event_count"
|
||||
assert params["filter0"] == "portal"
|
||||
with pytest.raises(analytics.AnalyticsError):
|
||||
analytics.build_query(
|
||||
tenant="379",
|
||||
dataset=None,
|
||||
metrics=["event_count"],
|
||||
dimensions=["drop table"],
|
||||
filters=None,
|
||||
from_time=None,
|
||||
to_time=None,
|
||||
limit=10,
|
||||
)
|
||||
|
||||
|
||||
def test_data_routes_require_a_verified_identity():
|
||||
client = TestClient(analytics.app)
|
||||
assert client.get("/api/0pt/analytics/datasets").status_code == 401
|
||||
assert client.get("/api/0pt/analytics/metrics").status_code == 401
|
||||
|
||||
|
||||
def test_health_is_always_a_liveness_answer():
|
||||
client = TestClient(analytics.app)
|
||||
response = client.get("/health")
|
||||
assert response.status_code == 200
|
||||
assert "providers" in response.json()
|
||||
+1
-10
@@ -89,16 +89,7 @@
|
||||
"0pt.source_registry_list",
|
||||
"0pt.order_create",
|
||||
"0pt.order_payment",
|
||||
"0pt.write_iceberg_table",
|
||||
"0pt.structure.resolve_entities",
|
||||
"0pt.structure.get_lineage",
|
||||
"0pt.structure.quality_run",
|
||||
"0pt.structure.quality_list_runs",
|
||||
"0pt.structure.quality_checks",
|
||||
"0pt.structure.quality_reports",
|
||||
"0pt.structure.extract_document",
|
||||
"0pt.structure.route_parsing",
|
||||
"0pt.structure.normalize_value"
|
||||
"0pt.write_iceberg_table"
|
||||
],
|
||||
"surfaces": [
|
||||
"api",
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"id": "0pt.structure.extract_document",
|
||||
"name": "0pt.structure.extract_document",
|
||||
"owner": "0pt",
|
||||
"version": "1.0.0",
|
||||
"riskLevel": "L2",
|
||||
"piiLevel": "high",
|
||||
"surfaces": [
|
||||
"api"
|
||||
],
|
||||
"requiresJob": false,
|
||||
"tenantScoped": true,
|
||||
"operationId": "0pt.extract_document",
|
||||
"description": "Canonical capability descriptor for 0pt.structure.extract_document (owner 0pt). Verified against registry + openapi operationId 0pt.extract_document."
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user