Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
68 changes: 68 additions & 0 deletions apps/admin-worker/component.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
apiVersion: sourceplane.io/v1
kind: Component
metadata:
name: admin-worker
description: Internal Cloudflare Worker for audited support/administration diagnostics
spec:
type: cloudflare-worker-turbo
lifecycle: production
owner: platform
domain: starter-runtime
path: apps/admin-worker
dependsOn:
- component: cloudflare-d1
# BF6 wiring documents from orun secrets (SEC-JOB): lease-published by
# the infra components; wire-live renders the wrangler template from
# these instead of Secrets Manager documents.
secretEnv:
WIRING_CLOUDFLARE_D1_STAGE: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/stage/WIRING_CLOUDFLARE_D1"
WIRING_CLOUDFLARE_D1_PROD: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/prod/WIRING_CLOUDFLARE_D1"

subscribe:
environments:
- name: dev
profile: verify
- name: stage
profile: verify
profileRules:
- profile: deploy
when:
triggerRef: github-push-main
- name: prod
profile: verify
profileRules:
- profile: deploy
when:
triggerRef: github-push-main
parameters:
nodeVersion: "22"
pnpmVersion: "10.12.1"
workspaceDir: ../..
appDir: .
# BF6b: deploy-time wiring — wrangler.jsonc is rendered, never committed.
# Verify lanes render from wiring.fixture.json (offline); deploy lanes
# resolve real IDs from the Secrets Manager wiring manifest (BF5).
orgName: sourceplane
owner: sourceplane
repo: new-test

turboFilter: "@saas/admin-worker"
wranglerConfig: wrangler.jsonc
wranglerTemplate: wrangler.template.jsonc
wiringComponents: "cloudflare-d1"
wiringEnvs: "stage,prod"
wiringFixture: wiring.fixture.json
installCommand: pnpm install --frozen-lockfile
buildCommand: pnpm exec turbo run build --filter=@saas/admin-worker
typecheckCommand: pnpm exec turbo run typecheck --filter=@saas/admin-worker
dryRunCommand: pnpm exec wrangler deploy --dry-run --config wrangler.jsonc --env prod
deployCommand: pnpm exec wrangler deploy --config wrangler.jsonc --env prod
preDeployCommand: "echo 'No pre-deploy step configured.'"
migrationCommand: "echo 'No migrations configured.'"
smokeCommand: "echo 'No smoke test configured.'"
labels:
team: platform
layer: runtime
surface: admin-support
runtime: cloudflare
# ci: re-trigger deploy (batch A — runner-starvation recovery 20260622T115650Z)
19 changes: 19 additions & 0 deletions apps/admin-worker/docs/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# admin-worker — architecture

A `cloudflare-worker-turbo` component: TypeScript built by the turbo pipeline
from `apps/admin-worker`, deployed per environment by its CI lane.

## Bindings and wiring

- **Wired configuration** (resolved at deploy time from job-output
secrets published by the infrastructure terraform; names only):
`WIRING_CLOUDFLARE_D1_STAGE`, `WIRING_CLOUDFLARE_D1_PROD`.
- **`PLATFORM_DB`** is a D1 binding. SQLite types apply: timestamps are
ISO-8601 text, JSON is text, booleans are 0/1, and there is no
interactive transaction (see `packages/db/src/d1`).

## Boundaries

This Worker owns its bounded context: its data, its invariants, its
API surface (exposed to the fleet through the edge). Cross-context calls
go over service bindings; nothing else may reach into its storage.
13 changes: 13 additions & 0 deletions apps/admin-worker/docs/overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# admin-worker

Internal Cloudflare Worker for audited support/administration diagnostics

Part of the new-test runtime: a Cloudflare Worker deployed per environment (`stage`, `prod`; `dev` is verify-only). Not publicly routable — reached only through `api-edge` service bindings.

## Depends on

- **cloudflare-d1** — Provisions the Cloudflare D1 platform database for stage and prod

## Depended on by

- (none)
32 changes: 32 additions & 0 deletions apps/admin-worker/docs/runbook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# admin-worker — runbook

## How it deploys

Merges to `main` converge automatically: CI plans changed components
(`orun plan --changed`) and runs this component's lane via
`orun run --remote-state` with credential-free OIDC auth. The convergence
run is the deployment; the DAG orders this component after everything it
depends on. Failed lanes resume with `gh run rerun --failed`.

## Rollback

Revert the offending commit on `main`; the next convergence applies the
previous desired state. There is no out-of-band mutation to undo — the
repo is the source of truth.

## Verify

The deploy lane's own verify/smoke is the gate. End-to-end behavior is
exercised through `api-edge` (this Worker has no public URL).

## Common failures

- **Missing `WIRING_*` secret at deploy**: the infrastructure terraform
upstream has not applied — check that lane first; within one
convergence run the DAG guarantees order.
- **Service-binding target missing (Cloudflare 10143)**: the target
Worker does not exist yet on this account — converge the fleet before
this lane (the bootstrap's two-pass landing handles first boot).
- **Smoke fails right after a first deploy**: a brand-new workers.dev
route can 4xx for a few seconds; the lane already retries — persistent
failure means a real regression.
2 changes: 2 additions & 0 deletions apps/admin-worker/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import config from "../../tooling/eslint/index.js";
export default config;
25 changes: 25 additions & 0 deletions apps/admin-worker/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "@saas/admin-worker",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "wrangler dev",
"build": "wrangler deploy --dry-run --outdir dist",
"deploy": "wrangler deploy",
"typecheck": "tsc --noEmit",
"lint": "eslint src",
"wire:fixture": "node ../../tooling/wire/render.mjs --template wrangler.template.jsonc --out wrangler.jsonc --map wiring.fixture.json"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20250508.0",
"@saas/eslint-config": "workspace:*",
"@saas/tsconfig": "workspace:*",
"typescript": "^5.8.3",
"wrangler": "^4.14.4"
},
"dependencies": {
"@saas/contracts": "workspace:*",
"@saas/db": "workspace:*"
}
}
4 changes: 4 additions & 0 deletions apps/admin-worker/src/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface Env {
PLATFORM_DB?: D1Database;
ENVIRONMENT: string;
}
21 changes: 21 additions & 0 deletions apps/admin-worker/src/handlers/health.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { Env } from "../env.js";
import { isDbConfigured } from "../support-events.js";

export function handleHealth(env: Env, requestId: string): Response {
return Response.json(
{
status: "ok",
service: "admin-worker",
environment: env.ENVIRONMENT ?? "local",
timestamp: new Date().toISOString(),
checks: { database: { configured: isDbConfigured(env) } },
},
{
status: 200,
headers: {
"content-type": "application/json",
"x-request-id": requestId,
},
},
);
}
156 changes: 156 additions & 0 deletions apps/admin-worker/src/handlers/list-entitlement-decisions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import type { Env } from "../env.js";
import type { SupportActor } from "../support-auth.js";
import type {
EntitlementDecisionRepository,
DecisionAggregateBucket,
} from "@saas/db/billing";
import type { EventsRepository } from "@saas/db/events";
import { createSqlExecutor } from "@saas/db/d1";
import { createEntitlementDecisionRepository } from "@saas/db/billing";
import { authorizeSupportAction } from "../support-auth.js";
import { successResponse, errorResponse, validationError } from "../http.js";
import { parseOrgPublicId, orgPublicId, generateSupportActionUuid } from "../ids.js";
import { emitAccessDenied } from "./record-support-action.js";
import type { SupportRequestContext } from "./record-support-action.js";

// Bounded-window read configuration. The aggregation is ALWAYS over a bounded
// time window and a bounded number of distinct groups — no unbounded scan is
// ever reachable through the API.
const DEFAULT_WINDOW_HOURS = 24;
const MAX_WINDOW_HOURS = 168; // 7 days
const MAX_GROUPS = 200;

// Test seam. When provided, the handler runs against an injected repo (no DB).
export interface ListEntitlementDecisionsDeps {
decisionRepo: Pick<EntitlementDecisionRepository, "aggregateDecisions">;
eventsRepo?: Pick<EventsRepository, "appendEventWithAudit">;
now?: () => Date;
generateId?: () => string;
}

// Narrow projection: per (entitlementKey, outcome) count, with an optional
// denial-reason breakdown. NEVER exposes limit values, subscription IDs,
// sources, provider payloads, or any secret — the underlying observation rows
// physically cannot carry them (migration 150).
function publicBucket(b: DecisionAggregateBucket): Record<string, unknown> {
const out: Record<string, unknown> = {
entitlementKey: b.entitlementKey,
outcome: b.outcome,
count: b.count,
};
if (b.denialReason !== null) {
out.denialReason = b.denialReason;
}
return out;
}

interface WindowParams {
windowHours: number;
}

function parseWindowParams(url: URL | undefined): { ok: true; value: WindowParams } | { ok: false; field: string; reason: string } {
if (!url) return { ok: true, value: { windowHours: DEFAULT_WINDOW_HOURS } };
const raw = url.searchParams.get("windowHours");
if (raw === null) return { ok: true, value: { windowHours: DEFAULT_WINDOW_HOURS } };
const parsed = Number(raw);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > MAX_WINDOW_HOURS) {
return { ok: false, field: "windowHours", reason: `Must be an integer between 1 and ${MAX_WINDOW_HOURS}` };
}
return { ok: true, value: { windowHours: parsed } };
}

export async function handleListEntitlementDecisions(
env: Env,
requestId: string,
ctx: SupportRequestContext,
targetOrgIdParam: string,
url?: URL,
deps?: ListEntitlementDecisionsDeps,
): Promise<Response> {
const targetOrgUuid = parseOrgPublicId(targetOrgIdParam);
if (!targetOrgUuid) {
return errorResponse("not_found", "Organization not found", 404, requestId);
}

const now = deps?.now ? deps.now() : new Date();
const genId = deps?.generateId ?? (() => generateSupportActionUuid());

// Deny-by-default authorization. Reading entitlement-decision observability is
// itself a support action and must fail closed + audit the denial.
const decision = authorizeSupportAction({
actor: ctx.actor,
supportRoleClaim: ctx.supportRoleClaim,
systemOverride: ctx.systemOverride,
});

if (!decision.allow) {
const denialActor: SupportActor = ctx.actor ?? { subjectId: "anonymous", subjectType: "user" };
const denialInput = {
actor: denialActor,
targetOrgId: targetOrgUuid,
attemptedAction: "support.entitlement_decisions.list",
reason: decision.reason,
requestId,
occurredAt: now,
genId,
};
if (deps?.eventsRepo) {
await emitAccessDenied(env, { ...denialInput, deps: { supportRepo: {} as never, eventsRepo: deps.eventsRepo } });
} else {
await emitAccessDenied(env, denialInput);
}
return errorResponse("forbidden", "Support action denied", 403, requestId, { reason: decision.reason });
}

const windowResult = parseWindowParams(url);
if (!windowResult.ok) {
return validationError(requestId, { [windowResult.field]: [windowResult.reason] });
}
const since = new Date(now.getTime() - windowResult.value.windowHours * 60 * 60 * 1000);

const respond = (buckets: DecisionAggregateBucket[]): Response =>
successResponse(
{
orgId: orgPublicId(targetOrgUuid),
windowHours: windowResult.value.windowHours,
decisions: buckets.map(publicBucket),
},
requestId,
200,
);

// Injected-deps (unit test) path.
if (deps) {
const aggResult = await deps.decisionRepo.aggregateDecisions(targetOrgUuid, {
since,
until: now,
maxGroups: MAX_GROUPS,
});
if (!aggResult.ok) {
return errorResponse("internal_error", "Failed to aggregate entitlement decisions", 500, requestId);
}
return respond(aggResult.value);
}

if (!env.PLATFORM_DB) {
return errorResponse("internal_error", "Database not configured", 503, requestId);
}

const executor = createSqlExecutor(env.PLATFORM_DB);
try {
const repo = createEntitlementDecisionRepository(executor);
const aggResult = await repo.aggregateDecisions(targetOrgUuid, {
since,
until: now,
maxGroups: MAX_GROUPS,
});
if (!aggResult.ok) {
return errorResponse("internal_error", "Failed to aggregate entitlement decisions", 500, requestId);
}
return respond(aggResult.value);
} catch {
return errorResponse("internal_error", "Failed to aggregate entitlement decisions", 500, requestId);
} finally {
await executor.dispose();
}
}
Loading
Loading