@wildo-ai/platform-config-lib 1.1.12 → 1.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/bootstrap/minion-database-queue-confinement.contracts.d.ts +41 -0
- package/dist/esm/bootstrap/minion-database-queue-confinement.contracts.d.ts.map +1 -0
- package/dist/esm/bootstrap/minion-database-queue-confinement.contracts.js +53 -0
- package/dist/esm/bootstrap/minion-database-queue-confinement.contracts.js.map +1 -0
- package/dist/esm/bootstrap/postgresql-owed-grants.contracts.d.ts +64 -0
- package/dist/esm/bootstrap/postgresql-owed-grants.contracts.d.ts.map +1 -1
- package/dist/esm/bootstrap/postgresql-owed-grants.contracts.js +49 -0
- package/dist/esm/bootstrap/postgresql-owed-grants.contracts.js.map +1 -1
- package/dist/esm/bootstrap/runtime-topology.contracts.d.ts +14 -0
- package/dist/esm/bootstrap/runtime-topology.contracts.d.ts.map +1 -1
- package/dist/esm/bootstrap/runtime-topology.contracts.js +24 -0
- package/dist/esm/bootstrap/runtime-topology.contracts.js.map +1 -1
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +1 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/key-management/approval-seal-verifier.d.ts +85 -3
- package/dist/esm/key-management/approval-seal-verifier.d.ts.map +1 -1
- package/dist/esm/key-management/approval-seal-verifier.js +112 -1
- package/dist/esm/key-management/approval-seal-verifier.js.map +1 -1
- package/dist/esm/pnpm-settings/application-pnpm-settings.d.ts +1 -1
- package/dist/esm/pnpm-settings/application-pnpm-settings.js +1 -1
- package/dist/esm/pnpm-settings/application-pnpm-settings.js.map +1 -1
- package/dist/esm/project-config/define-infra-env-config.d.ts +37 -0
- package/dist/esm/project-config/define-infra-env-config.d.ts.map +1 -1
- package/dist/esm/project-config/define-infra-env-config.js +16 -1
- package/dist/esm/project-config/define-infra-env-config.js.map +1 -1
- package/dist/esm/project-config/hosted-infra-env-config.d.ts.map +1 -1
- package/dist/esm/project-config/hosted-infra-env-config.js +1 -0
- package/dist/esm/project-config/hosted-infra-env-config.js.map +1 -1
- package/dist/esm/project-config/provider-runtime-artifacts.d.ts +10 -0
- package/dist/esm/project-config/provider-runtime-artifacts.d.ts.map +1 -1
- package/dist/esm/project-config/provider-runtime-artifacts.js +29 -5
- package/dist/esm/project-config/provider-runtime-artifacts.js.map +1 -1
- package/dist/esm/project-config/shared/environment.schemas.d.ts +37 -5
- package/dist/esm/project-config/shared/environment.schemas.d.ts.map +1 -1
- package/dist/esm/project-config/shared/environment.schemas.js +57 -5
- package/dist/esm/project-config/shared/environment.schemas.js.map +1 -1
- package/dist/esm/project-config/shared/infra-providers.schemas.d.ts +8 -0
- package/dist/esm/project-config/shared/infra-providers.schemas.d.ts.map +1 -1
- package/dist/esm/project-config/shared/infra-providers.schemas.js.map +1 -1
- package/dist/esm/project-config/shared/platform-key-management.schemas.d.ts +5 -2
- package/dist/esm/project-config/shared/platform-key-management.schemas.d.ts.map +1 -1
- package/dist/esm/project-config/shared/platform-key-management.schemas.js +8 -2
- package/dist/esm/project-config/shared/platform-key-management.schemas.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"infra-providers.schemas.js","sourceRoot":"","sources":["../../../../src/project-config/shared/infra-providers.schemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAKxB;;;;;;GAMG;AACH,MAAM,CAAN,IAAY,eAkBX;AAlBD,WAAY,eAAe;IACzB,0DAAuC,CAAA;IACvC,8DAA2C,CAAA;IAC3C,0DAAuC,CAAA;IACvC,oDAAiC,CAAA;IACjC,4DAAyC,CAAA;IACzC,oDAAiC,CAAA;IACjC,kDAA+B,CAAA;IAC/B;;;OAGG;IACH,0DAAuC,CAAA;IACvC;;;OAGG;IACH,oDAAiC,CAAA;AACnC,C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AAC,QAAQ,EAAE;CAClE,CAAC,CAAC;AAKH;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAM,yCAAyC,GAAG,CAAC,CAAC,YAAY,CAAC;IAC/D,qBAAqB,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,QAAQ,EAAE;IAC1E,qBAAqB,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE;CAC7D,CAAC,CAAC;AAKH;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAC9C,4CAA4C,CAAC,MAAM,CAAC;IAClD,aAAa,EAAE,4CAA4C,CAAC,QAAQ,EAAE;IACtE,UAAU,EAAE,yCAAyC,CAAC,QAAQ,EAAE;CACjE,CAAC,CAAC,WAAW,EAAE,CAAC;AAgiBnB;;;;;;;;;;GAUG;AACH,MAAM,CAAN,IAAY,wBAEX;AAFD,WAAY,wBAAwB;IAClC,mFAAc,CAAA;AAChB,CAAC,EAFW,wBAAwB,KAAxB,wBAAwB,QAEnC","sourcesContent":["import { z } from 'zod';\nimport type { ApplicationRuntimePrincipal } from '../../bootstrap/runtime-principal.contracts';\nimport type { MinionResourceGrants } from './minion-resource-access.validation';\nimport type { PostgreSQLSSLMode } from '@wildo-ai/saas-models';\n\n/**\n * Environment functions an infra environment must fulfill.\n *\n * This vocabulary is intentionally platform/config-owned, not part of\n * `@wildo-ai/saas-models`, because browser/runtime packages must not\n * import infrastructure provider concepts.\n */\nexport enum InfraCapability {\n DOCUMENT_DATABASE = 'DOCUMENT_DATABASE',\n RELATIONAL_DATABASE = 'RELATIONAL_DATABASE',\n AUDIT_LOG_STORAGE = 'AUDIT_LOG_STORAGE',\n OBJECT_STORAGE = 'OBJECT_STORAGE',\n ANTIVIRUS_SCANNING = 'ANTIVIRUS_SCANNING',\n QUEUING_SYSTEM = 'QUEUING_SYSTEM',\n CACHE_MANAGER = 'CACHE_MANAGER',\n /**\n * OTLP telemetry. GRANTED TO EVERY RUNTIME, never declared as a backing service — see\n * {@link RUNTIME_GRANTED_INFRA_CAPABILITIES}.\n */\n METRICS_TELEMETRY = 'METRICS_TELEMETRY',\n /**\n * Backup. RESERVED — no backing-service kind declares it and no module serves it; see\n * {@link RESERVED_INFRA_CAPABILITIES}.\n */\n BACKUP_MANAGER = 'BACKUP_MANAGER',\n}\n\n/**\n * Capabilities NO `BackingServiceKind` projects to — granted to a runtime by the platform rather\n * than declared by an environment.\n *\n * `BackingServiceKindToInfraCapability` used to be described as bijective, and a test asserted the\n * reverse direction: every capability reachable from some kind. That held only while every\n * capability was something an environment points at. It is not a property of the model, and reading\n * it as one is what kept `metrics-telemetry` alive as an authoring surface with no consumer.\n *\n * Membership here is the ANSWER to \"why does this capability have no kind\", so a capability that\n * belongs in neither place is a real gap and stays visible as one.\n */\nexport const RUNTIME_GRANTED_INFRA_CAPABILITIES: Readonly<Partial<Record<InfraCapability, string>>> = {\n /*\n * Telemetry is configured in TWO places, and a backing service is neither of them: the endpoint is\n * authored at `observability.telemetry.endpoint` (projected to `OTEL_EXPORTER_OTLP_ENDPOINT`), and\n * the auth header is derived provider-agnostically from the selected `OBSERVABILITY_TELEMETRY`\n * engine provider. Nothing is left for an environment to declare, and nothing for an\n * infra-provider module to mint — those exist to issue PER-APPLICATION credentials, and a\n * telemetry token is one provider-level secret shared by every runtime.\n *\n * The capability itself is load-bearing and must NOT be withdrawn with the kind: it carries the\n * `DATA_TELEMETRY` network in `NETWORK_FOR_CAPABILITY` and sits in\n * `MINION_UNCONDITIONAL_CAPABILITIES`, so every runtime reaches the collector through it. Setting\n * it to `null` there was corrected on 2026-08-12 precisely because it \"would have cut tracing for\n * every runtime the moment segmentation was enforced, with NO readiness check covering it\".\n */\n [InfraCapability.METRICS_TELEMETRY]:\n 'Authored at observability.telemetry + the OBSERVABILITY_TELEMETRY provider; granted to every '\n + 'runtime for the DATA_TELEMETRY network, so no environment declares it and no module mints it.',\n};\n\n/**\n * Capabilities kept as VOCABULARY with no way to be selected yet — neither declared by an\n * environment (no `BackingServiceKind` projects to them) nor granted to runtimes by the platform.\n *\n * This is the third answer to \"why does this capability have no kind\", beside\n * `BackingServiceKindToInfraCapability` and {@link RUNTIME_GRANTED_INFRA_CAPABILITIES}. It exists so\n * that answer is WRITTEN DOWN: a capability in none of the three is an unexplained gap, and the\n * reachability test still fails on it.\n *\n * Membership is a statement that nothing can reach the capability today. It is not a placeholder\n * an environment may fill in — withdrawing the declarable kind is what stopped it being one.\n */\nexport const RESERVED_INFRA_CAPABILITIES: Readonly<Partial<Record<InfraCapability, string>>> = {\n /*\n * The `backup` backing-service kind was WITHDRAWN 2026-09-26 (#1693): it resolved to no provider,\n * rendered no workload, and nothing read it. The capability stays because whether backup is modelled\n * as a capability at all is the design question #8 owns. Its network is `null` in\n * `NETWORK_FOR_CAPABILITY` for the same reason — no runtime dials a backup target.\n */\n [InfraCapability.BACKUP_MANAGER]:\n 'Reserved for the backup design (#8): no environment can declare it and no module serves it.',\n};\n\n/**\n * Built-in environment-facing provider ids — the (kind × hosting-model\n * × brand) projection vocabulary. Apps SELECT these implicitly via\n * `wildo.infra.<env>.config.ts > backingServices.<kind>.{source,\n * provider?}`; the planner resolves the tuple to one of these\n * `InfraProvider` values via `resolveInfraProvider`.\n *\n * **Naming convention**: `<KIND>_<BRAND>` — `BRAND` is either a\n * vendor (Atlas / AWS_RDS / Supabase / …) for managed services, or\n * an open-source software name (MinIO / vanilla self-hosted) for\n * self-hosted. `<KIND>_MANAGED` exists as a generic fallback when\n * the operator hasn't named a brand (Postgres in particular —\n * acceptable while the brand catalog is incomplete; Mongo's\n * `MONGODB_ATLAS` is the only branded managed option today, so no\n * `MONGODB_MANAGED` generic is needed).\n *\n * Slice 4.B.0 (2026-05-07) added the Postgres brand expansion to\n * generalize the source/brand split that S3 already had.\n */\nexport enum InfraProvider {\n // === MongoDB ===\n /** Self-hosted vanilla MongoDB (in-cluster docker-compose / K8s\n * deployment). Selected via `source: SELF`. No `provider` brand\n * required (Mongo's `provider` axis is reserved for managed\n * variants like `'atlas'`). */\n MONGODB_SELF = 'mongodb-self',\n /** MongoDB Atlas (managed cloud). brand: `'atlas'`. */\n MONGODB_ATLAS = 'mongodb-atlas',\n\n // === PostgreSQL ===\n /** Self-hosted vanilla PostgreSQL (in-cluster docker-compose /\n * K8s deployment). Selected via `source: SELF`. */\n POSTGRES_SELF = 'postgres-self',\n /** Generic managed Postgres — fallback when the operator hasn't\n * named a brand. Concrete brand identifiers below are preferred. */\n POSTGRES_MANAGED = 'postgres-managed',\n /** AWS RDS for PostgreSQL. brand: `'aws-rds'`. */\n POSTGRES_AWS_RDS = 'postgres-aws-rds',\n /** Google Cloud SQL for PostgreSQL. brand: `'gcp-cloud-sql'`. */\n POSTGRES_GCP_CLOUD_SQL = 'postgres-gcp-cloud-sql',\n /** Azure Database for PostgreSQL. brand: `'azure-database'`. */\n POSTGRES_AZURE_DATABASE = 'postgres-azure-database',\n /** Supabase. brand: `'supabase'`. */\n POSTGRES_SUPABASE = 'postgres-supabase',\n /** Neon. brand: `'neon'`. */\n POSTGRES_NEON = 'postgres-neon',\n /** Render. brand: `'render'`. */\n POSTGRES_RENDER = 'postgres-render',\n\n // === Redis / Valkey ===\n /** Self-hosted Redis-compatible cache (today: Valkey under the\n * hood; the engine adapter is wire-protocol compatible with\n * Redis OSS). Selected via `source: SELF`. */\n REDIS_SELF = 'redis-self',\n\n // === RabbitMQ ===\n /** Self-hosted RabbitMQ broker (in-cluster docker-compose / K8s\n * deployment). Selected via `source: SELF`. */\n RABBITMQ_SELF = 'rabbitmq-self',\n\n // === Object storage ===\n /** MinIO (self-hosted S3-compatible). brand: `'minio'` (or unset on\n * source=self — MinIO is the canonical default). */\n MINIO_SELF = 'minio-self',\n /** AWS S3 (managed). brand: `'aws'`. */\n AWS_S3 = 'aws-s3',\n\n // === Stateless infra ===\n /** Self-hosted ClamAV antivirus scanning service. Stateless (no\n * auth, no per-tenant state); apps connect to a shared host:port.\n * Selected via `source: SELF`. */\n CLAMAV_SELF = 'clamav-self',\n /** Self-hosted immudb — immutable, cryptographically-verifiable DB used as a\n * tamper-evident audit-log store. Selected via `source: SELF`. */\n IMMUDB_SELF = 'immudb-self',\n}\n\n/**\n * Platform-side consumers of an `InfraProviderPlanContribution.platformAdmin`\n * block. Each provider declares which platform services receive its\n * admin credentials so the planner can route them to the right pod /\n * compose service / env file.\n *\n * Locked enum (2026-05-05). Extending requires adding the consumer\n * enum value here AND in every `InfraProviderModule.plan()` that\n * legitimately delivers admin credentials to the new consumer.\n *\n * Excluded by design (consume platform-service APIs, not direct infra-admin):\n * - `file-generator`\n * - `sourcecode-provider`\n *\n * Add as real consumers surface, not pre-emptively.\n */\nexport enum InfraPlatformAdminConsumer {\n APPS_MANAGER = 'apps-manager',\n COMPANION = 'companion',\n CRONTABS_BATCHES_MANAGER = 'crontabs-batches-manager',\n MODULE_REGISTRY = 'module-registry',\n}\n\n/**\n * Audience-less contributions: describe the infra resource itself.\n * Same payload regardless of who consumes it (compose definitions,\n * K8s manifests, CI checks).\n */\nconst InfraProviderResourceContributionShapeSchema = z.strictObject({\n dockerComposeServices: z.array(z.string().min(1)).optional(),\n k8sResources: z.array(z.string().min(1)).optional(),\n startupScripts: z.array(z.string().min(1)).optional(),\n ciChecks: z.array(z.string().min(1)).optional(),\n policyChecks: z.array(z.string().min(1)).optional(),\n});\n\n/**\n * Audience: platform services that need **management-API access** to\n * administer the infra resource (create per-app users / vhosts / ACLs\n * / DBs). This is audience-1 in the three-audience model:\n *\n * 1. **Platform-admin** (this contribution slice). Cluster-wide\n * management-API credentials. Consumed by apps-manager (mints\n * per-app users via `mintAppCredentials`), companion (mirrors\n * apps-manager admin role for local dev). `crontabs` /\n * `module-registry` are listed in the enum because they MAY\n * surface admin needs in future slices, but no provider should\n * declare them as consumers in this slice unless evidence\n * surfaces.\n * 2. **Platform-service-scoped** (NOT modeled in `plan()` yet —\n * see LD-8 / Slice 2.5). Per-platform-service publish/consume\n * creds for the platform-services that participate in\n * inter-service messaging (`PLATFORM_SERVICES` enum:\n * apps-manager, crontabs-batches-manager, file-generator).\n * Today provisioned inline by\n * `PlatformInfrastructureManagerService.provisionAllPlatformServices`.\n * 3. **App-scoped** (`appRuntime` slice below). Per-app\n * publish/consume creds, minted by `mintAppCredentials`.\n *\n * `consumers` is the explicit audience declaration: every provider\n * states which platform services receive this block. The planner\n * routes the credentials accordingly.\n */\nconst InfraProviderPlatformAdminContributionSchema = z.strictObject({\n envVars: z.record(z.string(), z.string()).optional(),\n secretEnvVars: z.array(z.string().min(1)).optional(),\n consumers: z.array(z.enum(InfraPlatformAdminConsumer)).optional(),\n});\nexport type InfraProviderPlatformAdminContribution = z.infer<\n typeof InfraProviderPlatformAdminContributionSchema\n>;\n\n/**\n * Audience: customer-app + minion + Node-worker pods. Per-app\n * runtime delivery flows through the persisted\n * `Wildo_Application_Config` and `Wildo_Application_Secrets` blobs in\n * MongoDB (NOT through K8s deployment-Secret env vars; engine\n * consumers like `queue.backend.service.ts:144-149` read from\n * `appConfigService.{config,secrets}` after fetching them at startup\n * via app-config-fetch).\n *\n * - `perAppConfigBlobPaths`: JSON paths into `Wildo_Application_Config`\n * carrying static values (same for every app in this env) — e.g.\n * `'database.rabbitmq.host': 'rabbitmq'`. Merged into the persisted\n * config blob by the planner at sync time.\n * - `perAppSecretBlobPaths`: JSON paths into `Wildo_Application_Secrets`\n * that `mintAppCredentials` will populate at deploy time (e.g.\n * `'database.rabbitmq.username'`). The planner emits only the path\n * list; apps-manager invokes `mintAppCredentials` per app to produce\n * the values, then merges them into the persisted secrets blob via\n * the existing `_merge_WildoApplicationSecrets` machinery.\n *\n * No K8s-Secret-env-var output is intentional: the K8s\n * `{appSlug}-secret` carries only the four-env bootstrap-env-contract\n * (APPLICATION_ID / PLATFORM_APPLICATION_PRIMARY_SECRET /\n * PLATFORM_APPS_MANAGER_URL / APPLICATION_ENV); per-resource creds\n * land in MongoDB, not env. If a future provider genuinely needs\n * env-var injection it can extend this contribution shape via\n * `.passthrough()` — not pre-emptively designed for here.\n */\nconst InfraProviderAppRuntimeContributionSchema = z.strictObject({\n perAppConfigBlobPaths: z.record(z.string().min(1), z.unknown()).optional(),\n perAppSecretBlobPaths: z.array(z.string().min(1)).optional(),\n});\nexport type InfraProviderAppRuntimeContribution = z.infer<\n typeof InfraProviderAppRuntimeContributionSchema\n>;\n\n/**\n * Two-slice contribution shape. The audience-less resource block\n * (compose / K8s / CI) merges with the audience-scoped credential\n * blocks (`platformAdmin`, `appRuntime`).\n *\n * `.passthrough()` is preserved on the merged shape so future\n * contribution kinds (dashboards, alerting rules, autoscaler hints)\n * can be added without breaking existing modules.\n */\nexport const InfraProviderPlanContributionSchema =\n InfraProviderResourceContributionShapeSchema.extend({\n platformAdmin: InfraProviderPlatformAdminContributionSchema.optional(),\n appRuntime: InfraProviderAppRuntimeContributionSchema.optional(),\n }).passthrough();\nexport type InfraProviderPlanContribution = z.infer<typeof InfraProviderPlanContributionSchema>;\n\nexport interface InfraProviderPlanningContext {\n environment: string;\n runtime: string;\n backingServiceKey: string;\n config: unknown;\n}\n\n/**\n * Per-app credential minting context. Called by the orchestrator\n * (apps-manager `wildo-application-lifecycle.service.ts`) at app-init\n * time — not at K8s deploy time. The orchestrator is responsible for\n * **generation policy** (read existing creds from MongoDB; decide\n * rotate-vs-preserve based on `overrideCredentials` flag; generate\n * new password when needed); the module is responsible for the\n * **broker upsert** (install / replace the user on the broker with\n * the supplied password).\n *\n * Inputs:\n * - `appSlug` — the application slug (or its derived namespace\n * `ns`); used by the module to compute the rabbit username,\n * permission regex, etc.\n * - `adminClient` — pre-wired by the orchestrator from the resolved\n * `platformAdmin` env vars; concrete type narrowed per provider at\n * the module's implementation site (e.g., RabbitMQ modules narrow\n * to `RabbitMQManagementClient`).\n * - `secretInputs` — orchestrator-supplied scalars keyed by the JSON\n * path the module declared in `appRuntime.perAppSecretBlobPaths`.\n * For RabbitMQ: `{ 'database.rabbitmq.password': '<orchestrator-generated-password>' }`.\n * The module installs these on the broker; it does NOT generate\n * passwords itself.\n *\n * Note: `applicationEnv` was previously included in this context but\n * removed 2026-05-06 — the integration site (`wildo-application-lifecycle`)\n * does not carry an env field on its options shape.\n */\nexport interface AppCredentialMintingContext {\n /**\n * Raw application slug (e.g., `'wonder-todos'`). Used by modules\n * whose per-app resource names embed the slug directly without\n * env-scoping (e.g., MongoDB database name).\n */\n appSlug: string;\n /**\n * Application namespace = `<appSlug>-<environmentId>`, derived\n * server-side via `buildApplicationNamespace` in platform-config-lib.\n * Used by modules whose per-app resource names scope by namespace\n * (RabbitMQ username, Redis ACL keyPattern, …) — i.e., resources\n * that must remain isolated across env boundaries (`wonder-todos-local`\n * vs `wonder-todos-staging`).\n */\n applicationNamespace: string;\n /**\n * Stable opaque application identifier (Mongo ObjectId-shaped string,\n * matches the convention at\n * `wildo-application-lifecycle.service.ts:552` where the broker\n * permission regex disambiguates per-app queue/reply names by this\n * id, NOT by `appSlug` — the slug is human-readable and could\n * theoretically be reassigned, the id is forever-stable). Required\n * by modules whose per-app resource names embed the application id\n * (RabbitMQ permission regex, …).\n */\n wildoApplicationId: string;\n /**\n * WHICH runtime principal these credentials are for (Step 2 / D17).\n *\n * Optional, and absent means the APPLICATION BACKEND — which keeps every\n * existing module and call site meaning exactly what it meant before, since\n * per-application minting IS the backend principal's case.\n *\n * A module that ignores this field still mints correctly for the backend and\n * simply does not participate in per-principal narrowing; a module that reads\n * it must derive a DISTINCT resource name (ACL username, DB user, queue\n * permission) per principal, or two principals will share one credential and\n * the narrowing will exist only on paper.\n *\n * `buildRuntimePrincipalKey` renders the stable identity to embed in such a\n * name — the same string the stored section is keyed by, so a minted resource\n * and the row that records it cannot drift.\n */\n principal?: ApplicationRuntimePrincipal;\n /**\n * What this principal may touch, in RESOURCE TYPES (Step 3).\n *\n * Deliberately the platform vocabulary, not storage names: a module that\n * grants on tables and a module that grants on collections must receive the\n * same contract, and the translation belongs at each adapter via\n * `resolveGrantStorageNames`.\n *\n * Absent for the application backend, which is granted database-wide by a\n * different path. Absent for a NAMED principal means \"no grants derived\" —\n * which a module must treat as an ERROR rather than as a reason to fall back\n * to the wide grant. A minion with no declared access is passed an EXPLICIT\n * empty grant by the orchestrator, so it gets the engine-floor role and no\n * business table (#1771); the error is for a caller that forgot to pass one.\n */\n resourceGrants?: MinionResourceGrants;\n adminClient: unknown;\n secretInputs: Record<string, string>;\n /**\n * Optional non-secret per-app config inputs supplied by the\n * orchestrator. Distinct from `secretInputs` (passwords) — these\n * are authored topology values that affect HOW the module\n * provisions the per-app resource. Each module documents the keys\n * it consumes in its own JSDoc.\n *\n * Slice 2.5c-3 introduced this field for `RabbitmqSelfInfraProviderModule`\n * to receive the optional per-app vhost (key `'vhost'`); future\n * modules may use it for per-app database suffixes, bucket prefixes,\n * or other authored topology overrides without further extending\n * the context shape.\n *\n * When `undefined` or missing a key the module relies on, the\n * module falls back to its default behavior (e.g., RabbitMQ\n * provisions on the default vhost `/`).\n */\n applicationConfigInputs?: Record<string, string>;\n}\n\n// =============================================================================\n// Platform-service-scoped credential minting (audience-2)\n// =============================================================================\n//\n// `provisionAllPlatformServices` (in apps-manager\n// `PlatformInfrastructureManagerService`) hands each platform service\n// (`apps-manager`, `crontabs-batches-manager`, `file-generator`) a SCOPED\n// (non-admin) broker user for inter-service messaging. The policy\n// (per-service permission regex, the broader-permissions special case for\n// crontabs) lives on the `InfraProviderModule` interface so each provider owns\n// its own per-platform-service policy.\n//\n// Distinct from `mintAppCredentials` (audience-3): platform-service creds\n// land in MongoDB `platformApplicationsSecrets` (orchestrator-owned), NOT\n// in `Wildo_Application_Secrets`.\n\n/**\n * Context for `InfraProviderModule.mintPlatformServiceCredentials`.\n * Same orchestrator-pattern as `mintAppCredentials`: orchestrator\n * generates the password, passes it via `secretInputs`; module is\n * upsert-only on the broker.\n */\nexport interface PlatformServiceCredentialMintingContext {\n /**\n * Stable identifier of the platform service this credential is for.\n * Today: members of `PlatformApplicationType` (e.g.,\n * `'platform_apps_manager'`, `'platform_crontabs_batches_manager'`,\n * `'platform_file_generator'`). Module derives the per-service\n * permission regex from this string.\n */\n serviceName: string;\n adminClient: unknown;\n /**\n * Orchestrator-supplied scalars. For RabbitMQ the only required\n * key is `'password'` (no JSON-blob-path conventions because\n * platform-service creds don't go into a per-app blob — they're\n * persisted at the platform-services collection level).\n */\n secretInputs: Record<string, string>;\n}\n\nexport interface PlatformServiceCredentialMintingResult {\n /**\n * Username installed on the broker. Equals `serviceName` today\n * (the legacy convention preserved from the inline ceremony in\n * `PlatformInfrastructureManagerService.provisionServiceCredentials`).\n * Future modules may transform if needed; the orchestrator persists\n * this value alongside the password.\n */\n username: string;\n}\n\n/**\n * Per-app credential minting result. Keys are JSON paths into\n * `Wildo_Application_Secrets` (those declared in\n * `appRuntime.perAppSecretBlobPaths`); values are the canonical\n * persisted form post-broker-upsert. Typically:\n * - **Module-derived** values (e.g., `'database.rabbitmq.username': 'app_<ns>'`).\n * The module computes these from `appSlug`.\n * - **Echoed** values from `secretInputs` (e.g.,\n * `'database.rabbitmq.password': '<the-password-you-passed-in>'`)\n * — the module confirms it installed them on the broker.\n *\n * The orchestrator (apps-manager) merges this map into the persisted\n * secrets blob via `_merge_WildoApplicationSecrets`. The customer\n * pod reads at startup via the standard app-config-fetch path — no\n * K8s Secret involvement for per-app data creds.\n */\nexport interface AppCredentialMintingResult {\n secretBlobValues: Record<string, string>;\n /**\n * Optional non-persisted return values the module produces in the\n * course of upsert. Distinct from `secretBlobValues` (which lands\n * in `Wildo_Application_Secrets`) — `runtimeArtifacts` is a back-\n * channel for values the orchestrator needs at app-init time but\n * deliberately does NOT persist.\n *\n * This field was introduced for the MongoDB modules: `MongodbAtlasInfraProviderModule`\n * returns `runtimeArtifacts['connectionString']` (the per-app\n * SRV URL with credentials embedded) so the orchestrator can use\n * it for transient app-database seeding without persisting the\n * whole credentialed URL into secrets — the persistence shape is\n * `(username, password)` in secrets + `(host, protocol, options,\n * database)` in config, NOT a single URL string.\n *\n * When `undefined`, the module has no transient artifacts; the\n * orchestrator should rely on `secretBlobValues` only.\n */\n runtimeArtifacts?: Record<string, string>;\n}\n\n// =============================================================================\n// Per-provider admin-client contracts\n// =============================================================================\n//\n// Each `InfraProviderModule.mintAppCredentials` call narrows the\n// `AppCredentialMintingContext.adminClient` field to a per-provider\n// management-client interface. The interfaces live HERE (in\n// platform-config-lib, contracts-only per platform/CLAUDE.md) so the\n// module implementation (in platform-apps-manager) and the manager\n// implementation (also in platform-apps-manager) share one definition\n// — and any future caller (companion, CLI) can implement the same\n// interface without depending on the manager class.\n\n/**\n * Raw RabbitMQ management-API transport (HTTP `PUT/DELETE`). Surface\n * what `RabbitmqSelfInfraProviderModule.mintAppCredentials` /\n * `revokeAppCredentials` need; nothing more. The 5C policy/transport\n * split (LD-4) carves *policy* methods (`upsertTenantUserPermissions`\n * etc.) out of the manager into the module; this interface is the\n * pure-transport remainder.\n *\n * **Argument-order convention** (Slice 4.A.2 / L3): for permission\n * methods, the order is `(vhost, username, permissions)` — vhost\n * first. The legacy pre-Slice-2 convention was `(username, vhost, ...)`\n * (positional, username first). The new convention is cleaner but\n * silently swappable since both args are strings. **Do NOT reorder**;\n * stale call sites copying the legacy positional order will produce\n * wrong-vhost permissions without compile-time complaint.\n */\nexport interface IRabbitMQManagementClient {\n /** PUT /api/users/{name} — idempotent upsert. */\n putUser(username: string, password: string, tags: ReadonlyArray<string>): Promise<void>;\n /** PUT /api/permissions/{vhost}/{name} — vhost-first per the\n * argument-order convention noted on the interface JSDoc. */\n setPermissions(\n vhost: string,\n username: string,\n permissions: { configure: string; write: string; read: string },\n ): Promise<void>;\n /** PUT /api/topic-permissions/{vhost}/{name} — vhost-first. */\n setTopicPermissions(\n vhost: string,\n username: string,\n permissions: { exchange: string; write: string; read: string },\n ): Promise<void>;\n /** DELETE /api/users/{name} — idempotent (404 → no-op). */\n deleteUser(username: string): Promise<void>;\n /** PUT /api/vhosts/{name} — ensures vhost exists; idempotent. */\n ensureVhost(vhost: string): Promise<void>;\n /**\n * PUT /api/policies/{vhost}/{name} with `apply-to: queues` — idempotent upsert of a QUEUE policy.\n *\n * A policy, not a queue argument, because RabbitMQ refuses to change the arguments of a queue that\n * already exists, while a policy is re-applied to matching queues whenever it changes. Exactly one\n * policy applies to a queue (the highest priority), so a caller's `pattern` must not overlap\n * another policy at the same priority.\n */\n ensureQueuePolicy(\n vhost: string,\n name: string,\n policy: { pattern: string; definition: Readonly<Record<string, string | number>>; priority: number },\n ): Promise<void>;\n}\n\n/**\n * Raw Redis (Valkey) ACL transport. Surface what\n * `RedisSelfInfraProviderModule.mintAppCredentials` /\n * `revokeAppCredentials` need; nothing more. Used over a `redis-cli`-\n * equivalent ACL connection (the apps-manager's\n * `RedisConnectionManagerService` opens it once at boot and reuses).\n *\n * **Channel pattern policy** (Slice 4.B.1, 2026-05-10): the legacy\n * `RedisConnectionManagerService.upsertTenantUserAcl` derived a\n * fixed family of pub/sub channel patterns from `username`\n * (`<u>#*`, `<u>#/#*`, `<u>-request#*`, `<u>-request#/#*`,\n * `<u>-response#*`, `<u>-response#/#*`). That fan-out is module-\n * internal policy, NOT transport. The contract therefore takes\n * only `username`/`password`/`keyPattern` — the channel patterns\n * live inside the manager implementation today (preserves Slice 2\n * behavior parity); when the legacy method is retired the policy\n * moves into `RedisSelfInfraProviderModule` proper. Until then,\n * `upsertUser` is a thin delegator and the contract is the\n * forward-looking shape.\n *\n * **Idempotent persistence** (`persistAcl`): Valkey/Redis ACL\n * changes are in-memory until `ACL SAVE` is called. The legacy\n * code paired every `upsertTenantUserAcl` with `aclSave`; the\n * module mirrors that pairing.\n */\nexport interface IRedisAclClient {\n /**\n * `ACL SETUSER <name> on >password resetkeys ~<keyPattern> ...`\n * — idempotent upsert. The implementation owns the full ACL\n * command shape (channel patterns, allow/deny categories,\n * dangerous-command denials) — the contract surfaces only the\n * orchestrator-supplied identity material. Slice 4.B.1's manager\n * impl preserves the legacy channel-pattern fan-out from\n * `RedisConnectionManagerService.upsertTenantUserAcl`.\n */\n upsertUser(input: {\n username: string;\n password: string;\n keyPattern: string;\n }): Promise<void>;\n /**\n * `ACL DELUSER <name>` — idempotent (no-op when the user is\n * already absent).\n */\n deleteUser(username: string): Promise<void>;\n /**\n * `ACL SAVE` — flushes the in-memory ACL list to disk. MUST be\n * called after every mutation set so Valkey restarts don't lose\n * tenant users.\n */\n persistAcl(): Promise<void>;\n}\n\n/**\n * Raw Postgres admin transport. Surface what\n * `PostgresSelfInfraProviderModule.mintAppCredentials` /\n * `revokeAppCredentials` need; nothing more. The legacy\n * `PostgreSQLConnectionManagerService` (apps-manager) implements\n * this contract via its existing `createApplicationDatabase` /\n * `deleteApplicationDatabase` methods (Slice 4.B.2 5C policy/\n * transport split).\n *\n * **Identifier-injection-safe**: implementations MUST validate\n * `databaseName` / `username` shapes (alphanumeric + underscore;\n * 63-char Postgres limit) and quote them safely — module callers\n * pass authored slugs verbatim. `PostgreSQLConnectionManagerService`\n * uses the legacy `validateIdentifier` + `quoteIdentifier` pair.\n *\n * **Idempotent upsert** (`upsertApplicationDatabase`): the legacy\n * `createApplicationDatabase` is upsert-style — `CREATE USER` falls\n * back to `ALTER USER` on conflict; `CREATE DATABASE` skips when the\n * DB exists; ownership + privileges always reapplied. The module\n * surface preserves that contract; \"create\" is renamed to \"upsert\"\n * in the contract to match the orchestrator-pattern vocabulary.\n */\nexport interface IPostgresAdminClient {\n /**\n * Upsert per-app database + role. Returns the resolved\n * `connectionUrl` so the orchestrator can persist it into\n * `Wildo_Application_Secrets.database.postgresql.connectUrl`.\n * Idempotent: safe to call repeatedly with the same input.\n */\n upsertApplicationDatabase(input: {\n databaseName: string;\n username: string;\n password: string;\n sslMode?: PostgreSQLSSLMode;\n }): Promise<{ connectionUrl: string }>;\n /**\n * Drop per-app database + user. Idempotent: missing DB / missing\n * user are non-throws (best-effort cleanup, see legacy\n * `deleteApplicationDatabase` semantics).\n */\n dropApplicationDatabase(input: {\n databaseName: string;\n username: string;\n }): Promise<void>;\n /**\n * Stop the application's OWNER role from authenticating — and destroy nothing (#1307).\n *\n * The application backend's role OWNS its database, so it cannot be dropped without first handing\n * ownership of every object to somebody else (PostgreSQL refuses `DROP ROLE` while objects depend\n * on it). Revocation therefore keeps the role and removes its ability to open a session:\n * `NOLOGIN` (a role without it cannot be \"the initial session authorization name during client\n * connection\") plus `PASSWORD NULL` (\"password authentication will always fail for that user\"),\n * then terminates the sessions it already holds, because a login attribute is checked only when a\n * session starts.\n *\n * spec-cite: PostgreSQL 17 `CREATE ROLE` — `LOGIN`/`NOLOGIN` and `PASSWORD` parameter descriptions\n * (https://www.postgresql.org/docs/17/sql-createrole.html); `pg_terminate_backend`, System\n * Administration Functions (https://www.postgresql.org/docs/17/functions-admin.html).\n *\n * Separate from {@link IPostgresAdminClient.dropApplicationDatabase}, which DROPS the database: a\n * withdrawn application's data is kept (#1562 owns destruction), and a revocation that routed\n * through the drop would erase it while believing it was only retiring a login.\n *\n * Reversible by {@link IPostgresAdminClient.upsertApplicationDatabase}, which re-applies\n * `LOGIN PASSWORD` to an existing role. Idempotent: a role that does not exist is a no-op.\n */\n revokeApplicationDatabaseLogin(input: {\n username: string;\n }): Promise<void>;\n /**\n * Upsert a LOGIN role holding exactly the given per-table privileges inside an\n * existing application database (Step 3 / R1).\n *\n * A SEPARATE method from {@link IPostgresAdminClient.upsertApplicationDatabase},\n * for the same reason the Mongo port is split: that one CREATEs the database\n * and makes its caller the OWNER with `ALL PRIVILEGES`, this one grants named\n * verbs on named tables inside a database somebody else owns. One method with\n * an optional privileges argument would make OWNERSHIP the behaviour you get\n * by forgetting to pass something.\n *\n * The grants are AUTHORITATIVE: the implementation must revoke what the role\n * previously held before granting, or a table removed from `resourceAccess`\n * keeps its privilege and revocation becomes a no-op that reports success.\n *\n * A declared table that does not exist yet cannot be granted, and is OWED: the\n * implementation must record every grant it derived, in the same transaction, in\n * the in-database contract of `postgresql-owed-grants.contracts.ts`, so the\n * application's migration run grants each table as it creates it (#3027).\n * `dropTableScopedDatabaseRole` must remove the role's record with its grants.\n *\n * An empty `readTables`/`writeTables` pair is legitimate — a role that can\n * connect and see nothing — and must NOT be read as \"unspecified, leave the\n * previous grants alone\".\n */\n /**\n * Remove a table-scoped LOGIN role and everything it holds — WITHOUT touching\n * the database it was scoped into.\n *\n * Separate from {@link IPostgresAdminClient.dropApplicationDatabase}, which\n * drops the DATABASE and its owner. Reusing that one to retire a minion would\n * destroy the entire application's data while believing it was removing one\n * principal's access. That asymmetry is why revocation gets its own method\n * rather than a flag.\n */\n dropTableScopedDatabaseRole(input: {\n databaseName: string;\n username: string;\n schemaName: string;\n }): Promise<void>;\n upsertTableScopedDatabaseRole(input: {\n databaseName: string;\n username: string;\n password: string;\n schemaName: string;\n readTables: readonly string[];\n writeTables: readonly string[];\n /**\n * Insert-only tables — `GRANT INSERT`, never UPDATE and never DELETE.\n *\n * A third axis rather than a flag on `writeTables`, because the two say\n * different things about the same verb set and a boolean would make the\n * safer one the thing you get by remembering to pass it. Today this carries\n * the engine's mandatory append floor — the audit trail and retained job\n * output (see `deriveMinionDatabaseGrants`): a principal must be able to record\n * what it did, and must never be able to unrecord it.\n */\n appendTables: readonly string[];\n /** Insert/update durable runtime records without granting DELETE. Read is granted separately. */\n maintainTables?: readonly string[];\n sslMode?: PostgreSQLSSLMode;\n }): Promise<{ connectionUrl: string }>;\n}\n\n/**\n * Raw MongoDB Atlas API transport. Surface what\n * `MongodbAtlasInfraProviderModule.mintAppCredentials` /\n * `revokeAppCredentials` need; nothing more. The legacy\n * `MongoAtlasManagerService` (apps-manager) implements this\n * contract via its existing `createApplicationDatabase` /\n * `deleteDatabaseUser` methods (Slice 4.B.3 5C policy/transport\n * split).\n *\n * **Idempotent upsert** (`upsertApplicationDatabase`): the legacy\n * `createApplicationDatabase` is upsert-style — `POST /databaseUsers`\n * falls back to `PATCH` on conflict (existing user); cluster scope +\n * roles are reapplied on every call. Returns the SRV connection\n * string with credentials embedded, ready for transient\n * app-database seeding by the orchestrator.\n */\nexport interface IMongoAtlasClient {\n /**\n * Upsert per-app Atlas database user. Returns the SRV connection\n * string (with credentials embedded, `mongodb+srv://user:pass@...`)\n * that the orchestrator uses for transient app-init operations.\n * The string is NOT persisted into `Wildo_Application_Secrets`\n * by today's orchestrator — it's exposed via\n * `AppCredentialMintingResult.runtimeArtifacts.connectionString`.\n */\n upsertApplicationDatabase(input: {\n clusterName: string;\n databaseName: string;\n username: string;\n password: string;\n }): Promise<{ connectionString: string }>;\n /**\n * Delete an Atlas database user. Idempotent: 404 → no-op.\n */\n deleteDatabaseUser(username: string): Promise<void>;\n /**\n * Upsert a database user holding exactly ONE Atlas custom database role, which carries exactly the\n * given collection-scoped privileges and inherits nothing (#1694). The Atlas twin of\n * {@link IMongoSelfAdminClient.upsertCollectionScopedDatabaseUser}, for a runtime principal (a minion).\n *\n * A SEPARATE method from {@link IMongoAtlasClient.upsertApplicationDatabase} for the reason the\n * self-hosted contract gives: that one grants `readWrite` on the whole database, this one grants named\n * actions on named collections, and an optional \"privileges\" argument would make the wide grant the\n * behaviour you get by forgetting to pass something.\n *\n * - `privileges[].actions` are Atlas Admin API privilege-action names (`FIND`, `INSERT`, `UPDATE`,\n * `REMOVE`, …). The caller translates from MongoDB's own vocabulary; this transport never widens it.\n * - `privileges` is AUTHORITATIVE: an existing role's actions are REPLACED, so a resource removed from\n * `resourceAccess` loses its grant on the next sync.\n * - The user is scoped to `clusterName` alone (Atlas grants every cluster in the project when `scopes`\n * is omitted), and holds the custom role and nothing else.\n * - Idempotent: safe when the role and user already exist; the password is re-applied, which is how a\n * rotation lands.\n *\n * Returns the SRV connection string carrying THIS user's credentials, for the same transient use as\n * {@link IMongoAtlasClient.upsertApplicationDatabase}'s.\n */\n upsertCollectionScopedDatabaseUser(input: {\n clusterName: string;\n databaseName: string;\n username: string;\n password: string;\n roleName: string;\n privileges: ReadonlyArray<{\n resource: { db: string; collection: string };\n actions: readonly string[];\n }>;\n }): Promise<{ connectionString: string }>;\n /**\n * Retire a collection-scoped user AND the custom role it holds — and nothing else.\n *\n * Two objects, deleted user FIRST: Atlas refuses to delete a custom role that would leave a database\n * user with no roles, so the reverse order fails while the user exists. Dropping only the user would\n * leave a privileged role behind that the next mint silently adopts. Idempotent in both halves: a\n * missing user or a missing role is a no-op.\n */\n dropCollectionScopedDatabaseUser(input: {\n username: string;\n roleName: string;\n }): Promise<void>;\n}\n\n/**\n * The immudb permission an application's audit user holds on its OWN database (#1696).\n *\n * The values are immudb's own permission bytes, because the admin transport sends them verbatim.\n * spec-cite: immudb v1.11.1 `pkg/auth/permissions.go` — `PermissionNone = iota`, `PermissionR`, `PermissionRW`\n * (0, 1, 2), `PermissionAdmin = 254`, `PermissionSysAdmin = 255`\n * (https://raw.githubusercontent.com/codenotary/immudb/v1.11.1/pkg/auth/permissions.go, fetched 2026-09-29).\n *\n * Only READ_WRITE is named: an audit sink appends and verifies, and nothing in the framework grants an\n * application more. `ADMIN` and `SYSADMIN` are deliberately absent — holding either is the defect #1696 removes.\n */\nexport enum ImmudbDatabasePermission {\n READ_WRITE = 2,\n}\n\n/**\n * Raw immudb admin transport (#1696). Surfaces exactly what `ImmudbSelfInfraProviderModule` needs to give each\n * application ONE database and ONE user confined to it, and to revoke that user — nothing more.\n *\n * Implemented in apps-manager over the gRPC admin API with the PLATFORM's own admin credential (a\n * framework-managed secret no application receives). Every method is idempotent, because registration,\n * withdrawal and restore all retry by re-running.\n *\n * **No method deletes anything.** immudb keeps every database and every user it has created: an append-only\n * store's audit history must outlive the application's credential, and a withdrawn application is restored by\n * RE-ACTIVATING its user onto the same database (#1307).\n */\nexport interface IImmudbAdminClient {\n /** Create the database when it does not exist; a no-op when it does. */\n ensureDatabase(input: { databaseName: string }): Promise<void>;\n /**\n * Create the user, or bring an existing one back to exactly this state: ACTIVE, this password, and `permission`\n * on `databaseName`. Re-applying the password and re-activating are what make a restore after withdrawal work.\n */\n upsertDatabaseUser(input: {\n username: string;\n password: string;\n databaseName: string;\n permission: ImmudbDatabasePermission;\n }): Promise<void>;\n /**\n * Refuse the user's credential from now on: revoke its permission on `databaseName` and DEACTIVATE it.\n * immudb has no user deletion; a deactivated user cannot log in. A user that does not exist is a no-op.\n */\n deactivateDatabaseUser(input: { username: string; databaseName: string }): Promise<void>;\n}\n\n/**\n * Raw self-managed MongoDB admin transport. Surface what\n * `MongodbSelfInfraProviderModule.mintAppCredentials` /\n * `revokeAppCredentials` need; nothing more. Implemented by a\n * lightweight admin-side mongoose connection — the legacy inline\n * `ensureSelfManagedMongoApplicationUser` at\n * `wildo-application-lifecycle.service.ts:2710-2745` is the source\n * of behavior.\n *\n * **Why this contract is asymmetric to `IMongoAtlasClient`** (Slice\n * 4.B.3 design note, 2026-05-10): Atlas exposes a stateless REST\n * API for user management; self-managed Mongo requires opening an\n * admin-DB connection and running `createUser` / `updateUser`\n * commands. The contract therefore takes the admin connect URL as\n * an input (not a constructor-time configuration) — implementations\n * open transient connections per call, mirroring the legacy\n * pattern.\n */\nexport interface IMongoSelfAdminClient {\n /**\n * Upsert per-app database user on a self-managed MongoDB\n * instance. Connects to `adminConnectUrl` (admin-scoped),\n * creates or updates the user with `readWrite` + `dbAdmin`\n * roles on `databaseName`, then closes the connection. Idempotent.\n */\n upsertApplicationDatabaseUser(input: {\n adminConnectUrl: string;\n databaseName: string;\n username: string;\n password: string;\n }): Promise<void>;\n /**\n * Delete a per-app database user. Idempotent: missing user is a\n * no-op (best-effort cleanup, mirrors `IPostgresAdminClient`\n * semantics).\n */\n deleteApplicationDatabaseUser(input: {\n adminConnectUrl: string;\n username: string;\n }): Promise<void>;\n /**\n * Upsert a database user holding ONE custom role carrying exactly the given\n * collection-scoped privileges (Step 3 / R1 / D14).\n *\n * Deliberately a SEPARATE method from\n * {@link IMongoSelfAdminClient.upsertApplicationDatabaseUser} rather than an\n * optional parameter on it. The two grant fundamentally different authority —\n * that one grants `readWrite` + `dbAdmin` on the WHOLE database, this one\n * grants named actions on named collections and nothing else — and a single\n * method with an optional \"privileges\" argument would make the wide grant the\n * behaviour you get by forgetting to pass something. Two methods make the\n * caller name which authority it intends.\n *\n * `privileges` is authoritative and REPLACES the role's previous contents, so\n * a resource removed from `resourceAccess` loses its grant on the next sync.\n * An empty list is legitimate — a principal with no data access — and MUST\n * yield a role granting nothing rather than being treated as \"unspecified\".\n *\n * Idempotent: safe to call when the role and user already exist.\n */\n /**\n * Retire a collection-scoped user AND the custom role it holds.\n *\n * Separate from {@link IMongoSelfAdminClient.deleteApplicationDatabaseUser}\n * because a scoped principal owns TWO objects in TWO databases — the user in\n * `admin`, the role in the application database — and dropping only the user\n * leaves a privileged role behind that the next mint silently adopts.\n *\n * Idempotent in both halves: a missing user or a missing role is a no-op.\n */\n dropCollectionScopedDatabaseUser(input: {\n adminConnectUrl: string;\n databaseName: string;\n username: string;\n roleName: string;\n }): Promise<void>;\n upsertCollectionScopedDatabaseUser(input: {\n adminConnectUrl: string;\n databaseName: string;\n username: string;\n password: string;\n roleName: string;\n privileges: ReadonlyArray<{\n resource: { db: string; collection: string };\n actions: readonly string[];\n }>;\n }): Promise<void>;\n}\n\nexport interface InfraProviderModule {\n provider: InfraProvider;\n supportedCapabilities: ReadonlyArray<InfraCapability>;\n\n /**\n * Present when this module EXISTS but the platform cannot yet deliver a working connection for the\n * provider — the module can plan, and an application selecting it would still receive no usable\n * credential. The value says why, and what would change it.\n *\n * ## Why the module stays in the catalogue instead of being removed\n *\n * The module's `plan()` is correct and useful: it formalizes the env contract an operator will set\n * and gives the lockfile a stable digest. What is missing is elsewhere (for `AWS_S3`, the credential\n * broker that speaks only MinIO's AssumeRole, #14). Removing the module would lose the correct half\n * to express the missing one.\n *\n * ## What it does\n *\n * A declaration resolving to a provider whose module carries this is REFUSED at authoring time\n * (`wildo config validate` / `config sync` / `lock check`), exactly like a declaration resolving to\n * a provider with no module. Delete the field in the same change that makes the provider servable.\n */\n unservableReason?: string;\n\n /**\n * Every `Wildo_Application_Secrets` JSON path this module can mint PER RUNTIME PRINCIPAL.\n *\n * ## Why this is static, when `plan()` already reports the same paths\n *\n * `plan()` answers \"what does THIS application get\", so it needs an\n * {@link InfraProviderPlanningContext}. The secret-DELIVERY path in apps-manager asks a different\n * question — \"which paths are per-principal AT ALL\" — and must answer it with no application in\n * hand, because it decides what to STRIP from the application blob before overlaying a\n * principal's own material. A principal must receive a credential only where one was minted for\n * it; anything left un-stripped is delivered with the APPLICATION's value, which for a database\n * means `readWrite` + `dbAdmin` on the whole database.\n *\n * Empty for a provider with no per-app credentials — shared-bucket object storage\n * (`MINIO_SELF`, `AWS_S3`) and stateless infra (`CLAMAV_SELF`). Empty is a\n * real answer, not a missing one, which is why the field is required rather than optional: a\n * module that mints per-principal material must not be able to omit it and be silently read as\n * \"nothing to confine\".\n *\n * **Modules MUST derive `appRuntime.perAppSecretBlobPaths` from this same constant** rather than\n * repeating the literal list. Two spellings of where a credential lives is the defect this exists\n * to prevent, one layer up.\n *\n * **A module declaring paths here MUST derive a distinct resource name per principal**, in its mint\n * AND its revoke, through one function. apps-manager dispatches every minion mint and revocation\n * through the catalogue (#1692), so a module that ignored `principal` and derived the application\n * backend's own name would OVERWRITE the backend's user on a minion mint and DELETE it on a minion\n * revocation — the defect `invariant-call-site-enumeration.md` #18 records. MongoDB Atlas shipped in\n * exactly that shape and was refused at registration until its per-principal path landed (#1694).\n */\n perPrincipalSecretBlobPaths: ReadonlyArray<string>;\n\n plan(context: InfraProviderPlanningContext): InfraProviderPlanContribution;\n\n /**\n * Optional. Called by apps-manager at app-init time (see\n * `wildo-application-lifecycle.service.ts:432-580` — the existing\n * per-resource ceremony this method abstracts). Upserts the per-app\n * user / role / DB on the broker using `secretInputs` for any\n * orchestrator-supplied passwords; returns the canonical form of\n * the persisted secrets blob slice.\n *\n * Returns `null` when the provider has no per-app credentials (e.g.,\n * shared S3 bucket with shared access key).\n *\n * **Idempotent broker upsert** — the module installs / replaces the\n * user with the password from `secretInputs`. It does NOT make\n * generation/rotation decisions; that is the orchestrator's\n * responsibility (driven by the existing `overrideCredentials`\n * flag on `WildoApplicationInitOptions`). The module MUST NOT\n * crash on \"user already exists\" (PUT semantics on the broker\n * management API are sufficient for RabbitMQ; equivalent\n * upsert-on-conflict semantics for other providers).\n */\n mintAppCredentials?(\n context: AppCredentialMintingContext,\n ): Promise<AppCredentialMintingResult | null>;\n\n /**\n * Optional. Symmetric to `mintAppCredentials`: afterwards the principal's credential is REFUSED by the\n * server. Called by apps-manager when a minion leaves the declaration, and for EVERY principal of an\n * application withdrawn from the platform (`deregisterApplication`, #1307).\n *\n * **It revokes and never destroys.** It removes the ability to authenticate — an ACL user, a broker\n * user, a database user, or a login — and leaves the application's DATA where it is: its database,\n * keys, queues and blobs. A withdrawn application is restored by re-minting (`mintAppCredentials` with\n * the recorded material), which only works if nothing it owns was dropped. Destroying data is a\n * different verb with its own protection (#1562); a module must never reach it through this one.\n *\n * Idempotent: safe to call when the per-principal user / role does not exist (no throw on\n * already-absent), because a retry after a partial revocation must converge.\n */\n revokeAppCredentials?(context: AppCredentialMintingContext): Promise<void>;\n\n /**\n * Optional (LD-8 / Slice 2.5). Called by the orchestrator\n * (`PlatformInfrastructureManagerService.provisionServiceCredentials`\n * + `ensureAppsManagerCredentials`) at platform-service-init time.\n * Upserts a SCOPED (non-admin) per-platform-service user on the\n * broker for inter-service messaging — distinct from\n * `mintAppCredentials` (audience-3, customer-app per-app creds).\n *\n * Same orchestrator-pattern as `mintAppCredentials`: orchestrator\n * owns generation, module is upsert-only.\n *\n * Returns `null` when the provider has no per-platform-service\n * credentials concept (e.g., S3 modules — platform services use a\n * shared bucket).\n */\n mintPlatformServiceCredentials?(\n context: PlatformServiceCredentialMintingContext,\n ): Promise<PlatformServiceCredentialMintingResult | null>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"infra-providers.schemas.js","sourceRoot":"","sources":["../../../../src/project-config/shared/infra-providers.schem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ConfinedTableGrant } from '../../bootstrap/postgresql-owed-grants.contracts';\nimport type { MinionResourceGrants } from './minion-resource-access.validation';\nimport type { PostgreSQLSSLMode } from '@wildo-ai/saas-models';\n\n/**\n * Environment functions an infra environment must fulfill.\n *\n * This vocabulary is intentionally platform/config-owned, not part of\n * `@wildo-ai/saas-models`, because browser/runtime packages must not\n * import infrastructure provider concepts.\n */\nexport enum InfraCapability {\n DOCUMENT_DATABASE = 'DOCUMENT_DATABASE',\n RELATIONAL_DATABASE = 'RELATIONAL_DATABASE',\n AUDIT_LOG_STORAGE = 'AUDIT_LOG_STORAGE',\n OBJECT_STORAGE = 'OBJECT_STORAGE',\n ANTIVIRUS_SCANNING = 'ANTIVIRUS_SCANNING',\n QUEUING_SYSTEM = 'QUEUING_SYSTEM',\n CACHE_MANAGER = 'CACHE_MANAGER',\n /**\n * OTLP telemetry. GRANTED TO EVERY RUNTIME, never declared as a backing service — see\n * {@link RUNTIME_GRANTED_INFRA_CAPABILITIES}.\n */\n METRICS_TELEMETRY = 'METRICS_TELEMETRY',\n /**\n * Backup. RESERVED — no backing-service kind declares it and no module serves it; see\n * {@link RESERVED_INFRA_CAPABILITIES}.\n */\n BACKUP_MANAGER = 'BACKUP_MANAGER',\n}\n\n/**\n * Capabilities NO `BackingServiceKind` projects to — granted to a runtime by the platform rather\n * than declared by an environment.\n *\n * `BackingServiceKindToInfraCapability` used to be described as bijective, and a test asserted the\n * reverse direction: every capability reachable from some kind. That held only while every\n * capability was something an environment points at. It is not a property of the model, and reading\n * it as one is what kept `metrics-telemetry` alive as an authoring surface with no consumer.\n *\n * Membership here is the ANSWER to \"why does this capability have no kind\", so a capability that\n * belongs in neither place is a real gap and stays visible as one.\n */\nexport const RUNTIME_GRANTED_INFRA_CAPABILITIES: Readonly<Partial<Record<InfraCapability, string>>> = {\n /*\n * Telemetry is configured in TWO places, and a backing service is neither of them: the endpoint is\n * authored at `observability.telemetry.endpoint` (projected to `OTEL_EXPORTER_OTLP_ENDPOINT`), and\n * the auth header is derived provider-agnostically from the selected `OBSERVABILITY_TELEMETRY`\n * engine provider. Nothing is left for an environment to declare, and nothing for an\n * infra-provider module to mint — those exist to issue PER-APPLICATION credentials, and a\n * telemetry token is one provider-level secret shared by every runtime.\n *\n * The capability itself is load-bearing and must NOT be withdrawn with the kind: it carries the\n * `DATA_TELEMETRY` network in `NETWORK_FOR_CAPABILITY` and sits in\n * `MINION_UNCONDITIONAL_CAPABILITIES`, so every runtime reaches the collector through it. Setting\n * it to `null` there was corrected on 2026-08-12 precisely because it \"would have cut tracing for\n * every runtime the moment segmentation was enforced, with NO readiness check covering it\".\n */\n [InfraCapability.METRICS_TELEMETRY]:\n 'Authored at observability.telemetry + the OBSERVABILITY_TELEMETRY provider; granted to every '\n + 'runtime for the DATA_TELEMETRY network, so no environment declares it and no module mints it.',\n};\n\n/**\n * Capabilities kept as VOCABULARY with no way to be selected yet — neither declared by an\n * environment (no `BackingServiceKind` projects to them) nor granted to runtimes by the platform.\n *\n * This is the third answer to \"why does this capability have no kind\", beside\n * `BackingServiceKindToInfraCapability` and {@link RUNTIME_GRANTED_INFRA_CAPABILITIES}. It exists so\n * that answer is WRITTEN DOWN: a capability in none of the three is an unexplained gap, and the\n * reachability test still fails on it.\n *\n * Membership is a statement that nothing can reach the capability today. It is not a placeholder\n * an environment may fill in — withdrawing the declarable kind is what stopped it being one.\n */\nexport const RESERVED_INFRA_CAPABILITIES: Readonly<Partial<Record<InfraCapability, string>>> = {\n /*\n * The `backup` backing-service kind was WITHDRAWN 2026-09-26 (#1693): it resolved to no provider,\n * rendered no workload, and nothing read it. The capability stays because whether backup is modelled\n * as a capability at all is the design question #8 owns. Its network is `null` in\n * `NETWORK_FOR_CAPABILITY` for the same reason — no runtime dials a backup target.\n */\n [InfraCapability.BACKUP_MANAGER]:\n 'Reserved for the backup design (#8): no environment can declare it and no module serves it.',\n};\n\n/**\n * Built-in environment-facing provider ids — the (kind × hosting-model\n * × brand) projection vocabulary. Apps SELECT these implicitly via\n * `wildo.infra.<env>.config.ts > backingServices.<kind>.{source,\n * provider?}`; the planner resolves the tuple to one of these\n * `InfraProvider` values via `resolveInfraProvider`.\n *\n * **Naming convention**: `<KIND>_<BRAND>` — `BRAND` is either a\n * vendor (Atlas / AWS_RDS / Supabase / …) for managed services, or\n * an open-source software name (MinIO / vanilla self-hosted) for\n * self-hosted. `<KIND>_MANAGED` exists as a generic fallback when\n * the operator hasn't named a brand (Postgres in particular —\n * acceptable while the brand catalog is incomplete; Mongo's\n * `MONGODB_ATLAS` is the only branded managed option today, so no\n * `MONGODB_MANAGED` generic is needed).\n *\n * Slice 4.B.0 (2026-05-07) added the Postgres brand expansion to\n * generalize the source/brand split that S3 already had.\n */\nexport enum InfraProvider {\n // === MongoDB ===\n /** Self-hosted vanilla MongoDB (in-cluster docker-compose / K8s\n * deployment). Selected via `source: SELF`. No `provider` brand\n * required (Mongo's `provider` axis is reserved for managed\n * variants like `'atlas'`). */\n MONGODB_SELF = 'mongodb-self',\n /** MongoDB Atlas (managed cloud). brand: `'atlas'`. */\n MONGODB_ATLAS = 'mongodb-atlas',\n\n // === PostgreSQL ===\n /** Self-hosted vanilla PostgreSQL (in-cluster docker-compose /\n * K8s deployment). Selected via `source: SELF`. */\n POSTGRES_SELF = 'postgres-self',\n /** Generic managed Postgres — fallback when the operator hasn't\n * named a brand. Concrete brand identifiers below are preferred. */\n POSTGRES_MANAGED = 'postgres-managed',\n /** AWS RDS for PostgreSQL. brand: `'aws-rds'`. */\n POSTGRES_AWS_RDS = 'postgres-aws-rds',\n /** Google Cloud SQL for PostgreSQL. brand: `'gcp-cloud-sql'`. */\n POSTGRES_GCP_CLOUD_SQL = 'postgres-gcp-cloud-sql',\n /** Azure Database for PostgreSQL. brand: `'azure-database'`. */\n POSTGRES_AZURE_DATABASE = 'postgres-azure-database',\n /** Supabase. brand: `'supabase'`. */\n POSTGRES_SUPABASE = 'postgres-supabase',\n /** Neon. brand: `'neon'`. */\n POSTGRES_NEON = 'postgres-neon',\n /** Render. brand: `'render'`. */\n POSTGRES_RENDER = 'postgres-render',\n\n // === Redis / Valkey ===\n /** Self-hosted Redis-compatible cache (today: Valkey under the\n * hood; the engine adapter is wire-protocol compatible with\n * Redis OSS). Selected via `source: SELF`. */\n REDIS_SELF = 'redis-self',\n\n // === RabbitMQ ===\n /** Self-hosted RabbitMQ broker (in-cluster docker-compose / K8s\n * deployment). Selected via `source: SELF`. */\n RABBITMQ_SELF = 'rabbitmq-self',\n\n // === Object storage ===\n /** MinIO (self-hosted S3-compatible). brand: `'minio'` (or unset on\n * source=self — MinIO is the canonical default). */\n MINIO_SELF = 'minio-self',\n /** AWS S3 (managed). brand: `'aws'`. */\n AWS_S3 = 'aws-s3',\n\n // === Stateless infra ===\n /** Self-hosted ClamAV antivirus scanning service. Stateless (no\n * auth, no per-tenant state); apps connect to a shared host:port.\n * Selected via `source: SELF`. */\n CLAMAV_SELF = 'clamav-self',\n /** Self-hosted immudb — immutable, cryptographically-verifiable DB used as a\n * tamper-evident audit-log store. Selected via `source: SELF`. */\n IMMUDB_SELF = 'immudb-self',\n}\n\n/**\n * Platform-side consumers of an `InfraProviderPlanContribution.platformAdmin`\n * block. Each provider declares which platform services receive its\n * admin credentials so the planner can route them to the right pod /\n * compose service / env file.\n *\n * Locked enum (2026-05-05). Extending requires adding the consumer\n * enum value here AND in every `InfraProviderModule.plan()` that\n * legitimately delivers admin credentials to the new consumer.\n *\n * Excluded by design (consume platform-service APIs, not direct infra-admin):\n * - `file-generator`\n * - `sourcecode-provider`\n *\n * Add as real consumers surface, not pre-emptively.\n */\nexport enum InfraPlatformAdminConsumer {\n APPS_MANAGER = 'apps-manager',\n COMPANION = 'companion',\n CRONTABS_BATCHES_MANAGER = 'crontabs-batches-manager',\n MODULE_REGISTRY = 'module-registry',\n}\n\n/**\n * Audience-less contributions: describe the infra resource itself.\n * Same payload regardless of who consumes it (compose definitions,\n * K8s manifests, CI checks).\n */\nconst InfraProviderResourceContributionShapeSchema = z.strictObject({\n dockerComposeServices: z.array(z.string().min(1)).optional(),\n k8sResources: z.array(z.string().min(1)).optional(),\n startupScripts: z.array(z.string().min(1)).optional(),\n ciChecks: z.array(z.string().min(1)).optional(),\n policyChecks: z.array(z.string().min(1)).optional(),\n});\n\n/**\n * Audience: platform services that need **management-API access** to\n * administer the infra resource (create per-app users / vhosts / ACLs\n * / DBs). This is audience-1 in the three-audience model:\n *\n * 1. **Platform-admin** (this contribution slice). Cluster-wide\n * management-API credentials. Consumed by apps-manager (mints\n * per-app users via `mintAppCredentials`), companion (mirrors\n * apps-manager admin role for local dev). `crontabs` /\n * `module-registry` are listed in the enum because they MAY\n * surface admin needs in future slices, but no provider should\n * declare them as consumers in this slice unless evidence\n * surfaces.\n * 2. **Platform-service-scoped** (NOT modeled in `plan()` yet —\n * see LD-8 / Slice 2.5). Per-platform-service publish/consume\n * creds for the platform-services that participate in\n * inter-service messaging (`PLATFORM_SERVICES` enum:\n * apps-manager, crontabs-batches-manager, file-generator).\n * Today provisioned inline by\n * `PlatformInfrastructureManagerService.provisionAllPlatformServices`.\n * 3. **App-scoped** (`appRuntime` slice below). Per-app\n * publish/consume creds, minted by `mintAppCredentials`.\n *\n * `consumers` is the explicit audience declaration: every provider\n * states which platform services receive this block. The planner\n * routes the credentials accordingly.\n */\nconst InfraProviderPlatformAdminContributionSchema = z.strictObject({\n envVars: z.record(z.string(), z.string()).optional(),\n secretEnvVars: z.array(z.string().min(1)).optional(),\n consumers: z.array(z.enum(InfraPlatformAdminConsumer)).optional(),\n});\nexport type InfraProviderPlatformAdminContribution = z.infer<\n typeof InfraProviderPlatformAdminContributionSchema\n>;\n\n/**\n * Audience: customer-app + minion + Node-worker pods. Per-app\n * runtime delivery flows through the persisted\n * `Wildo_Application_Config` and `Wildo_Application_Secrets` blobs in\n * MongoDB (NOT through K8s deployment-Secret env vars; engine\n * consumers like `queue.backend.service.ts:144-149` read from\n * `appConfigService.{config,secrets}` after fetching them at startup\n * via app-config-fetch).\n *\n * - `perAppConfigBlobPaths`: JSON paths into `Wildo_Application_Config`\n * carrying static values (same for every app in this env) — e.g.\n * `'database.rabbitmq.host': 'rabbitmq'`. Merged into the persisted\n * config blob by the planner at sync time.\n * - `perAppSecretBlobPaths`: JSON paths into `Wildo_Application_Secrets`\n * that `mintAppCredentials` will populate at deploy time (e.g.\n * `'database.rabbitmq.username'`). The planner emits only the path\n * list; apps-manager invokes `mintAppCredentials` per app to produce\n * the values, then merges them into the persisted secrets blob via\n * the existing `_merge_WildoApplicationSecrets` machinery.\n *\n * No K8s-Secret-env-var output is intentional: the K8s\n * `{appSlug}-secret` carries only the four-env bootstrap-env-contract\n * (APPLICATION_ID / PLATFORM_APPLICATION_PRIMARY_SECRET /\n * PLATFORM_APPS_MANAGER_URL / APPLICATION_ENV); per-resource creds\n * land in MongoDB, not env. If a future provider genuinely needs\n * env-var injection it can extend this contribution shape via\n * `.passthrough()` — not pre-emptively designed for here.\n */\nconst InfraProviderAppRuntimeContributionSchema = z.strictObject({\n perAppConfigBlobPaths: z.record(z.string().min(1), z.unknown()).optional(),\n perAppSecretBlobPaths: z.array(z.string().min(1)).optional(),\n});\nexport type InfraProviderAppRuntimeContribution = z.infer<\n typeof InfraProviderAppRuntimeContributionSchema\n>;\n\n/**\n * Two-slice contribution shape. The audience-less resource block\n * (compose / K8s / CI) merges with the audience-scoped credential\n * blocks (`platformAdmin`, `appRuntime`).\n *\n * `.passthrough()` is preserved on the merged shape so future\n * contribution kinds (dashboards, alerting rules, autoscaler hints)\n * can be added without breaking existing modules.\n */\nexport const InfraProviderPlanContributionSchema =\n InfraProviderResourceContributionShapeSchema.extend({\n platformAdmin: InfraProviderPlatformAdminContributionSchema.optional(),\n appRuntime: InfraProviderAppRuntimeContributionSchema.optional(),\n }).passthrough();\nexport type InfraProviderPlanContribution = z.infer<typeof InfraProviderPlanContributionSchema>;\n\nexport interface InfraProviderPlanningContext {\n environment: string;\n runtime: string;\n backingServiceKey: string;\n config: unknown;\n}\n\n/**\n * Per-app credential minting context. Called by the orchestrator\n * (apps-manager `wildo-application-lifecycle.service.ts`) at app-init\n * time — not at K8s deploy time. The orchestrator is responsible for\n * **generation policy** (read existing creds from MongoDB; decide\n * rotate-vs-preserve based on `overrideCredentials` flag; generate\n * new password when needed); the module is responsible for the\n * **broker upsert** (install / replace the user on the broker with\n * the supplied password).\n *\n * Inputs:\n * - `appSlug` — the application slug (or its derived namespace\n * `ns`); used by the module to compute the rabbit username,\n * permission regex, etc.\n * - `adminClient` — pre-wired by the orchestrator from the resolved\n * `platformAdmin` env vars; concrete type narrowed per provider at\n * the module's implementation site (e.g., RabbitMQ modules narrow\n * to `RabbitMQManagementClient`).\n * - `secretInputs` — orchestrator-supplied scalars keyed by the JSON\n * path the module declared in `appRuntime.perAppSecretBlobPaths`.\n * For RabbitMQ: `{ 'database.rabbitmq.password': '<orchestrator-generated-password>' }`.\n * The module installs these on the broker; it does NOT generate\n * passwords itself.\n *\n * Note: `applicationEnv` was previously included in this context but\n * removed 2026-05-06 — the integration site (`wildo-application-lifecycle`)\n * does not carry an env field on its options shape.\n */\nexport interface AppCredentialMintingContext {\n /**\n * Raw application slug (e.g., `'wonder-todos'`). Used by modules\n * whose per-app resource names embed the slug directly without\n * env-scoping (e.g., MongoDB database name).\n */\n appSlug: string;\n /**\n * Application namespace = `<appSlug>-<environmentId>`, derived\n * server-side via `buildApplicationNamespace` in platform-config-lib.\n * Used by modules whose per-app resource names scope by namespace\n * (RabbitMQ username, Redis ACL keyPattern, …) — i.e., resources\n * that must remain isolated across env boundaries (`wonder-todos-local`\n * vs `wonder-todos-staging`).\n */\n applicationNamespace: string;\n /**\n * Stable opaque application identifier (Mongo ObjectId-shaped string,\n * matches the convention at\n * `wildo-application-lifecycle.service.ts:552` where the broker\n * permission regex disambiguates per-app queue/reply names by this\n * id, NOT by `appSlug` — the slug is human-readable and could\n * theoretically be reassigned, the id is forever-stable). Required\n * by modules whose per-app resource names embed the application id\n * (RabbitMQ permission regex, …).\n */\n wildoApplicationId: string;\n /**\n * WHICH runtime principal these credentials are for (Step 2 / D17).\n *\n * Optional, and absent means the APPLICATION BACKEND — which keeps every\n * existing module and call site meaning exactly what it meant before, since\n * per-application minting IS the backend principal's case.\n *\n * A module that ignores this field still mints correctly for the backend and\n * simply does not participate in per-principal narrowing; a module that reads\n * it must derive a DISTINCT resource name (ACL username, DB user, queue\n * permission) per principal, or two principals will share one credential and\n * the narrowing will exist only on paper.\n *\n * `buildRuntimePrincipalKey` renders the stable identity to embed in such a\n * name — the same string the stored section is keyed by, so a minted resource\n * and the row that records it cannot drift.\n */\n principal?: ApplicationRuntimePrincipal;\n /**\n * What this principal may touch, in RESOURCE TYPES (Step 3).\n *\n * Deliberately the platform vocabulary, not storage names: a module that\n * grants on tables and a module that grants on collections must receive the\n * same contract, and the translation belongs at each adapter via\n * `resolveGrantStorageNames`.\n *\n * Absent for the application backend, which is granted database-wide by a\n * different path. Absent for a NAMED principal means \"no grants derived\" —\n * which a module must treat as an ERROR rather than as a reason to fall back\n * to the wide grant. A minion with no declared access is passed an EXPLICIT\n * empty grant by the orchestrator, so it gets the engine-floor role and no\n * business table (#1771); the error is for a caller that forgot to pass one.\n */\n resourceGrants?: MinionResourceGrants;\n adminClient: unknown;\n secretInputs: Record<string, string>;\n /**\n * Optional non-secret per-app config inputs supplied by the\n * orchestrator. Distinct from `secretInputs` (passwords) — these\n * are authored topology values that affect HOW the module\n * provisions the per-app resource. Each module documents the keys\n * it consumes in its own JSDoc.\n *\n * Slice 2.5c-3 introduced this field for `RabbitmqSelfInfraProviderModule`\n * to receive the optional per-app vhost (key `'vhost'`); future\n * modules may use it for per-app database suffixes, bucket prefixes,\n * or other authored topology overrides without further extending\n * the context shape.\n *\n * When `undefined` or missing a key the module relies on, the\n * module falls back to its default behavior (e.g., RabbitMQ\n * provisions on the default vhost `/`).\n */\n applicationConfigInputs?: Record<string, string>;\n}\n\n// =============================================================================\n// Platform-service-scoped credential minting (audience-2)\n// =============================================================================\n//\n// `provisionAllPlatformServices` (in apps-manager\n// `PlatformInfrastructureManagerService`) hands each platform service\n// (`apps-manager`, `crontabs-batches-manager`, `file-generator`) a SCOPED\n// (non-admin) broker user for inter-service messaging. The policy\n// (per-service permission regex, the broader-permissions special case for\n// crontabs) lives on the `InfraProviderModule` interface so each provider owns\n// its own per-platform-service policy.\n//\n// Distinct from `mintAppCredentials` (audience-3): platform-service creds\n// land in MongoDB `platformApplicationsSecrets` (orchestrator-owned), NOT\n// in `Wildo_Application_Secrets`.\n\n/**\n * Context for `InfraProviderModule.mintPlatformServiceCredentials`.\n * Same orchestrator-pattern as `mintAppCredentials`: orchestrator\n * generates the password, passes it via `secretInputs`; module is\n * upsert-only on the broker.\n */\nexport interface PlatformServiceCredentialMintingContext {\n /**\n * Stable identifier of the platform service this credential is for.\n * Today: members of `PlatformApplicationType` (e.g.,\n * `'platform_apps_manager'`, `'platform_crontabs_batches_manager'`,\n * `'platform_file_generator'`). Module derives the per-service\n * permission regex from this string.\n */\n serviceName: string;\n adminClient: unknown;\n /**\n * Orchestrator-supplied scalars. For RabbitMQ the only required\n * key is `'password'` (no JSON-blob-path conventions because\n * platform-service creds don't go into a per-app blob — they're\n * persisted at the platform-services collection level).\n */\n secretInputs: Record<string, string>;\n}\n\nexport interface PlatformServiceCredentialMintingResult {\n /**\n * Username installed on the broker. Equals `serviceName` today\n * (the legacy convention preserved from the inline ceremony in\n * `PlatformInfrastructureManagerService.provisionServiceCredentials`).\n * Future modules may transform if needed; the orchestrator persists\n * this value alongside the password.\n */\n username: string;\n}\n\n/**\n * Per-app credential minting result. Keys are JSON paths into\n * `Wildo_Application_Secrets` (those declared in\n * `appRuntime.perAppSecretBlobPaths`); values are the canonical\n * persisted form post-broker-upsert. Typically:\n * - **Module-derived** values (e.g., `'database.rabbitmq.username': 'app_<ns>'`).\n * The module computes these from `appSlug`.\n * - **Echoed** values from `secretInputs` (e.g.,\n * `'database.rabbitmq.password': '<the-password-you-passed-in>'`)\n * — the module confirms it installed them on the broker.\n *\n * The orchestrator (apps-manager) merges this map into the persisted\n * secrets blob via `_merge_WildoApplicationSecrets`. The customer\n * pod reads at startup via the standard app-config-fetch path — no\n * K8s Secret involvement for per-app data creds.\n */\nexport interface AppCredentialMintingResult {\n secretBlobValues: Record<string, string>;\n /**\n * Optional non-persisted return values the module produces in the\n * course of upsert. Distinct from `secretBlobValues` (which lands\n * in `Wildo_Application_Secrets`) — `runtimeArtifacts` is a back-\n * channel for values the orchestrator needs at app-init time but\n * deliberately does NOT persist.\n *\n * This field was introduced for the MongoDB modules: `MongodbAtlasInfraProviderModule`\n * returns `runtimeArtifacts['connectionString']` (the per-app\n * SRV URL with credentials embedded) so the orchestrator can use\n * it for transient app-database seeding without persisting the\n * whole credentialed URL into secrets — the persistence shape is\n * `(username, password)` in secrets + `(host, protocol, options,\n * database)` in config, NOT a single URL string.\n *\n * When `undefined`, the module has no transient artifacts; the\n * orchestrator should rely on `secretBlobValues` only.\n */\n runtimeArtifacts?: Record<string, string>;\n}\n\n// =============================================================================\n// Per-provider admin-client contracts\n// =============================================================================\n//\n// Each `InfraProviderModule.mintAppCredentials` call narrows the\n// `AppCredentialMintingContext.adminClient` field to a per-provider\n// management-client interface. The interfaces live HERE (in\n// platform-config-lib, contracts-only per platform/CLAUDE.md) so the\n// module implementation (in platform-apps-manager) and the manager\n// implementation (also in platform-apps-manager) share one definition\n// — and any future caller (companion, CLI) can implement the same\n// interface without depending on the manager class.\n\n/**\n * Raw RabbitMQ management-API transport (HTTP `PUT/DELETE`). Surface\n * what `RabbitmqSelfInfraProviderModule.mintAppCredentials` /\n * `revokeAppCredentials` need; nothing more. The 5C policy/transport\n * split (LD-4) carves *policy* methods (`upsertTenantUserPermissions`\n * etc.) out of the manager into the module; this interface is the\n * pure-transport remainder.\n *\n * **Argument-order convention** (Slice 4.A.2 / L3): for permission\n * methods, the order is `(vhost, username, permissions)` — vhost\n * first. The legacy pre-Slice-2 convention was `(username, vhost, ...)`\n * (positional, username first). The new convention is cleaner but\n * silently swappable since both args are strings. **Do NOT reorder**;\n * stale call sites copying the legacy positional order will produce\n * wrong-vhost permissions without compile-time complaint.\n */\nexport interface IRabbitMQManagementClient {\n /** PUT /api/users/{name} — idempotent upsert. */\n putUser(username: string, password: string, tags: ReadonlyArray<string>): Promise<void>;\n /** PUT /api/permissions/{vhost}/{name} — vhost-first per the\n * argument-order convention noted on the interface JSDoc. */\n setPermissions(\n vhost: string,\n username: string,\n permissions: { configure: string; write: string; read: string },\n ): Promise<void>;\n /** PUT /api/topic-permissions/{vhost}/{name} — vhost-first. */\n setTopicPermissions(\n vhost: string,\n username: string,\n permissions: { exchange: string; write: string; read: string },\n ): Promise<void>;\n /** DELETE /api/users/{name} — idempotent (404 → no-op). */\n deleteUser(username: string): Promise<void>;\n /** PUT /api/vhosts/{name} — ensures vhost exists; idempotent. */\n ensureVhost(vhost: string): Promise<void>;\n /**\n * PUT /api/policies/{vhost}/{name} with `apply-to: queues` — idempotent upsert of a QUEUE policy.\n *\n * A policy, not a queue argument, because RabbitMQ refuses to change the arguments of a queue that\n * already exists, while a policy is re-applied to matching queues whenever it changes. Exactly one\n * policy applies to a queue (the highest priority), so a caller's `pattern` must not overlap\n * another policy at the same priority.\n */\n ensureQueuePolicy(\n vhost: string,\n name: string,\n policy: { pattern: string; definition: Readonly<Record<string, string | number>>; priority: number },\n ): Promise<void>;\n}\n\n/**\n * Raw Redis (Valkey) ACL transport. Surface what\n * `RedisSelfInfraProviderModule.mintAppCredentials` /\n * `revokeAppCredentials` need; nothing more. Used over a `redis-cli`-\n * equivalent ACL connection (the apps-manager's\n * `RedisConnectionManagerService` opens it once at boot and reuses).\n *\n * **Channel pattern policy** (Slice 4.B.1, 2026-05-10): the legacy\n * `RedisConnectionManagerService.upsertTenantUserAcl` derived a\n * fixed family of pub/sub channel patterns from `username`\n * (`<u>#*`, `<u>#/#*`, `<u>-request#*`, `<u>-request#/#*`,\n * `<u>-response#*`, `<u>-response#/#*`). That fan-out is module-\n * internal policy, NOT transport. The contract therefore takes\n * only `username`/`password`/`keyPattern` — the channel patterns\n * live inside the manager implementation today (preserves Slice 2\n * behavior parity); when the legacy method is retired the policy\n * moves into `RedisSelfInfraProviderModule` proper. Until then,\n * `upsertUser` is a thin delegator and the contract is the\n * forward-looking shape.\n *\n * **Idempotent persistence** (`persistAcl`): Valkey/Redis ACL\n * changes are in-memory until `ACL SAVE` is called. The legacy\n * code paired every `upsertTenantUserAcl` with `aclSave`; the\n * module mirrors that pairing.\n */\nexport interface IRedisAclClient {\n /**\n * `ACL SETUSER <name> on >password resetkeys ~<keyPattern> ...`\n * — idempotent upsert. The implementation owns the full ACL\n * command shape (channel patterns, allow/deny categories,\n * dangerous-command denials) — the contract surfaces only the\n * orchestrator-supplied identity material. Slice 4.B.1's manager\n * impl preserves the legacy channel-pattern fan-out from\n * `RedisConnectionManagerService.upsertTenantUserAcl`.\n */\n upsertUser(input: {\n username: string;\n password: string;\n keyPattern: string;\n }): Promise<void>;\n /**\n * `ACL DELUSER <name>` — idempotent (no-op when the user is\n * already absent).\n */\n deleteUser(username: string): Promise<void>;\n /**\n * `ACL SAVE` — flushes the in-memory ACL list to disk. MUST be\n * called after every mutation set so Valkey restarts don't lose\n * tenant users.\n */\n persistAcl(): Promise<void>;\n}\n\n/**\n * Raw Postgres admin transport. Surface what\n * `PostgresSelfInfraProviderModule.mintAppCredentials` /\n * `revokeAppCredentials` need; nothing more. The legacy\n * `PostgreSQLConnectionManagerService` (apps-manager) implements\n * this contract via its existing `createApplicationDatabase` /\n * `deleteApplicationDatabase` methods (Slice 4.B.2 5C policy/\n * transport split).\n *\n * **Identifier-injection-safe**: implementations MUST validate\n * `databaseName` / `username` shapes (alphanumeric + underscore;\n * 63-char Postgres limit) and quote them safely — module callers\n * pass authored slugs verbatim. `PostgreSQLConnectionManagerService`\n * uses the legacy `validateIdentifier` + `quoteIdentifier` pair.\n *\n * **Idempotent upsert** (`upsertApplicationDatabase`): the legacy\n * `createApplicationDatabase` is upsert-style — `CREATE USER` falls\n * back to `ALTER USER` on conflict; `CREATE DATABASE` skips when the\n * DB exists; ownership + privileges always reapplied. The module\n * surface preserves that contract; \"create\" is renamed to \"upsert\"\n * in the contract to match the orchestrator-pattern vocabulary.\n */\nexport interface IPostgresAdminClient {\n /**\n * Upsert per-app database + role. Returns the resolved\n * `connectionUrl` so the orchestrator can persist it into\n * `Wildo_Application_Secrets.database.postgresql.connectUrl`.\n * Idempotent: safe to call repeatedly with the same input.\n */\n upsertApplicationDatabase(input: {\n databaseName: string;\n username: string;\n password: string;\n sslMode?: PostgreSQLSSLMode;\n }): Promise<{ connectionUrl: string }>;\n /**\n * Drop per-app database + user. Idempotent: missing DB / missing\n * user are non-throws (best-effort cleanup, see legacy\n * `deleteApplicationDatabase` semantics).\n */\n dropApplicationDatabase(input: {\n databaseName: string;\n username: string;\n }): Promise<void>;\n /**\n * Stop the application's OWNER role from authenticating — and destroy nothing (#1307).\n *\n * The application backend's role OWNS its database, so it cannot be dropped without first handing\n * ownership of every object to somebody else (PostgreSQL refuses `DROP ROLE` while objects depend\n * on it). Revocation therefore keeps the role and removes its ability to open a session:\n * `NOLOGIN` (a role without it cannot be \"the initial session authorization name during client\n * connection\") plus `PASSWORD NULL` (\"password authentication will always fail for that user\"),\n * then terminates the sessions it already holds, because a login attribute is checked only when a\n * session starts.\n *\n * spec-cite: PostgreSQL 17 `CREATE ROLE` — `LOGIN`/`NOLOGIN` and `PASSWORD` parameter descriptions\n * (https://www.postgresql.org/docs/17/sql-createrole.html); `pg_terminate_backend`, System\n * Administration Functions (https://www.postgresql.org/docs/17/functions-admin.html).\n *\n * Separate from {@link IPostgresAdminClient.dropApplicationDatabase}, which DROPS the database: a\n * withdrawn application's data is kept (#1562 owns destruction), and a revocation that routed\n * through the drop would erase it while believing it was only retiring a login.\n *\n * Reversible by {@link IPostgresAdminClient.upsertApplicationDatabase}, which re-applies\n * `LOGIN PASSWORD` to an existing role. Idempotent: a role that does not exist is a no-op.\n */\n revokeApplicationDatabaseLogin(input: {\n username: string;\n }): Promise<void>;\n /**\n * Upsert a LOGIN role holding exactly the given per-table privileges inside an\n * existing application database (Step 3 / R1).\n *\n * A SEPARATE method from {@link IPostgresAdminClient.upsertApplicationDatabase},\n * for the same reason the Mongo port is split: that one CREATEs the database\n * and makes its caller the OWNER with `ALL PRIVILEGES`, this one grants named\n * verbs on named tables inside a database somebody else owns. One method with\n * an optional privileges argument would make OWNERSHIP the behaviour you get\n * by forgetting to pass something.\n *\n * The grants are AUTHORITATIVE: the implementation must revoke what the role\n * previously held before granting, or a table removed from `resourceAccess`\n * keeps its privilege and revocation becomes a no-op that reports success.\n *\n * A declared table that does not exist yet cannot be granted, and is OWED: the\n * implementation must record every grant it derived, in the same transaction, in\n * the in-database contract of `postgresql-owed-grants.contracts.ts`, so the\n * application's migration run grants each table as it creates it (#3027).\n * `dropTableScopedDatabaseRole` must remove the role's record with its grants.\n *\n * An empty `readTables`/`writeTables` pair is legitimate — a role that can\n * connect and see nothing — and must NOT be read as \"unspecified, leave the\n * previous grants alone\".\n */\n /**\n * Remove a table-scoped LOGIN role and everything it holds — WITHOUT touching\n * the database it was scoped into.\n *\n * Separate from {@link IPostgresAdminClient.dropApplicationDatabase}, which\n * drops the DATABASE and its owner. Reusing that one to retire a minion would\n * destroy the entire application's data while believing it was removing one\n * principal's access. That asymmetry is why revocation gets its own method\n * rather than a flag.\n */\n dropTableScopedDatabaseRole(input: {\n databaseName: string;\n username: string;\n schemaName: string;\n }): Promise<void>;\n upsertTableScopedDatabaseRole(input: {\n databaseName: string;\n username: string;\n password: string;\n schemaName: string;\n readTables: readonly string[];\n writeTables: readonly string[];\n /**\n * Insert-only tables — `GRANT INSERT`, never UPDATE and never DELETE.\n *\n * A third axis rather than a flag on `writeTables`, because the two say\n * different things about the same verb set and a boolean would make the\n * safer one the thing you get by remembering to pass it. Today this carries\n * the engine's mandatory append floor — the audit trail and retained job\n * output (see `deriveMinionDatabaseGrants`): a principal must be able to record\n * what it did, and must never be able to unrecord it.\n */\n appendTables: readonly string[];\n /** Insert/update durable runtime records without granting DELETE. Read is granted separately. */\n maintainTables?: readonly string[];\n /**\n * Tables the role reaches only PARTLY (#2303): SELECT, INSERT, UPDATE and DELETE are granted, and every statement but\n * INSERT reaches only the rows a row-level security policy admits (`PostgresRowConfinedTableGrant`). The grant and\n * the policy are recorded together in the owed-grants contract and applied together: the grant is never issued\n * before its policy is in place. Authoritative like every axis here: a table absent on a pass loses its policies.\n */\n rowConfinedTables?: readonly PostgresRowConfinedTableGrant[];\n sslMode?: PostgreSQLSSLMode;\n }): Promise<{ connectionUrl: string }>;\n}\n\n/**\n * Raw MongoDB Atlas API transport. Surface what\n * `MongodbAtlasInfraProviderModule.mintAppCredentials` /\n * `revokeAppCredentials` need; nothing more. The legacy\n * `MongoAtlasManagerService` (apps-manager) implements this\n * contract via its existing `createApplicationDatabase` /\n * `deleteDatabaseUser` methods (Slice 4.B.3 5C policy/transport\n * split).\n *\n * **Idempotent upsert** (`upsertApplicationDatabase`): the legacy\n * `createApplicationDatabase` is upsert-style — `POST /databaseUsers`\n * falls back to `PATCH` on conflict (existing user); cluster scope +\n * roles are reapplied on every call. Returns the SRV connection\n * string with credentials embedded, ready for transient\n * app-database seeding by the orchestrator.\n */\nexport interface IMongoAtlasClient {\n /**\n * Upsert per-app Atlas database user. Returns the SRV connection\n * string (with credentials embedded, `mongodb+srv://user:pass@...`)\n * that the orchestrator uses for transient app-init operations.\n * The string is NOT persisted into `Wildo_Application_Secrets`\n * by today's orchestrator — it's exposed via\n * `AppCredentialMintingResult.runtimeArtifacts.connectionString`.\n */\n upsertApplicationDatabase(input: {\n clusterName: string;\n databaseName: string;\n username: string;\n password: string;\n }): Promise<{ connectionString: string }>;\n /**\n * Delete an Atlas database user. Idempotent: 404 → no-op.\n */\n deleteDatabaseUser(username: string): Promise<void>;\n /**\n * Upsert a database user holding exactly ONE Atlas custom database role, which carries exactly the\n * given collection-scoped privileges and inherits nothing (#1694). The Atlas twin of\n * {@link IMongoSelfAdminClient.upsertCollectionScopedDatabaseUser}, for a runtime principal (a minion).\n *\n * A SEPARATE method from {@link IMongoAtlasClient.upsertApplicationDatabase} for the reason the\n * self-hosted contract gives: that one grants `readWrite` on the whole database, this one grants named\n * actions on named collections, and an optional \"privileges\" argument would make the wide grant the\n * behaviour you get by forgetting to pass something.\n *\n * - `privileges[].actions` are Atlas Admin API privilege-action names (`FIND`, `INSERT`, `UPDATE`,\n * `REMOVE`, …). The caller translates from MongoDB's own vocabulary; this transport never widens it.\n * - `privileges` is AUTHORITATIVE: an existing role's actions are REPLACED, so a resource removed from\n * `resourceAccess` loses its grant on the next sync.\n * - The user is scoped to `clusterName` alone (Atlas grants every cluster in the project when `scopes`\n * is omitted), and holds the custom role and nothing else.\n * - Idempotent: safe when the role and user already exist; the password is re-applied, which is how a\n * rotation lands.\n *\n * Returns the SRV connection string carrying THIS user's credentials, for the same transient use as\n * {@link IMongoAtlasClient.upsertApplicationDatabase}'s.\n */\n upsertCollectionScopedDatabaseUser(input: {\n clusterName: string;\n databaseName: string;\n username: string;\n password: string;\n roleName: string;\n privileges: ReadonlyArray<{\n resource: { db: string; collection: string };\n actions: readonly string[];\n }>;\n }): Promise<{ connectionString: string }>;\n /**\n * Retire a collection-scoped user AND the custom role it holds — and nothing else.\n *\n * Two objects, deleted user FIRST: Atlas refuses to delete a custom role that would leave a database\n * user with no roles, so the reverse order fails while the user exists. Dropping only the user would\n * leave a privileged role behind that the next mint silently adopts. Idempotent in both halves: a\n * missing user or a missing role is a no-op.\n */\n dropCollectionScopedDatabaseUser(input: {\n username: string;\n roleName: string;\n }): Promise<void>;\n}\n\n/**\n * The immudb permission an application's audit user holds on its OWN database (#1696).\n *\n * The values are immudb's own permission bytes, because the admin transport sends them verbatim.\n * spec-cite: immudb v1.11.1 `pkg/auth/permissions.go` — `PermissionNone = iota`, `PermissionR`, `PermissionRW`\n * (0, 1, 2), `PermissionAdmin = 254`, `PermissionSysAdmin = 255`\n * (https://raw.githubusercontent.com/codenotary/immudb/v1.11.1/pkg/auth/permissions.go, fetched 2026-09-29).\n *\n * Only READ_WRITE is named: an audit sink appends and verifies, and nothing in the framework grants an\n * application more. `ADMIN` and `SYSADMIN` are deliberately absent — holding either is the defect #1696 removes.\n */\nexport enum ImmudbDatabasePermission {\n READ_WRITE = 2,\n}\n\n/**\n * Raw immudb admin transport (#1696). Surfaces exactly what `ImmudbSelfInfraProviderModule` needs to give each\n * application ONE database and ONE user confined to it, and to revoke that user — nothing more.\n *\n * Implemented in apps-manager over the gRPC admin API with the PLATFORM's own admin credential (a\n * framework-managed secret no application receives). Every method is idempotent, because registration,\n * withdrawal and restore all retry by re-running.\n *\n * **No method deletes anything.** immudb keeps every database and every user it has created: an append-only\n * store's audit history must outlive the application's credential, and a withdrawn application is restored by\n * RE-ACTIVATING its user onto the same database (#1307).\n */\nexport interface IImmudbAdminClient {\n /** Create the database when it does not exist; a no-op when it does. */\n ensureDatabase(input: { databaseName: string }): Promise<void>;\n /**\n * Create the user, or bring an existing one back to exactly this state: ACTIVE, this password, and `permission`\n * on `databaseName`. Re-applying the password and re-activating are what make a restore after withdrawal work.\n */\n upsertDatabaseUser(input: {\n username: string;\n password: string;\n databaseName: string;\n permission: ImmudbDatabasePermission;\n }): Promise<void>;\n /**\n * Refuse the user's credential from now on: revoke its permission on `databaseName` and DEACTIVATE it.\n * immudb has no user deletion; a deactivated user cannot log in. A user that does not exist is a no-op.\n */\n deactivateDatabaseUser(input: { username: string; databaseName: string }): Promise<void>;\n}\n\n/**\n * Raw self-managed MongoDB admin transport. Surface what\n * `MongodbSelfInfraProviderModule.mintAppCredentials` /\n * `revokeAppCredentials` need; nothing more. Implemented by a\n * lightweight admin-side mongoose connection — the legacy inline\n * `ensureSelfManagedMongoApplicationUser` at\n * `wildo-application-lifecycle.service.ts:2710-2745` is the source\n * of behavior.\n *\n * **Why this contract is asymmetric to `IMongoAtlasClient`** (Slice\n * 4.B.3 design note, 2026-05-10): Atlas exposes a stateless REST\n * API for user management; self-managed Mongo requires opening an\n * admin-DB connection and running `createUser` / `updateUser`\n * commands. The contract therefore takes the admin connect URL as\n * an input (not a constructor-time configuration) — implementations\n * open transient connections per call, mirroring the legacy\n * pattern.\n */\nexport interface IMongoSelfAdminClient {\n /**\n * Upsert per-app database user on a self-managed MongoDB\n * instance. Connects to `adminConnectUrl` (admin-scoped),\n * creates or updates the user with `readWrite` + `dbAdmin`\n * roles on `databaseName`, then closes the connection. Idempotent.\n */\n upsertApplicationDatabaseUser(input: {\n adminConnectUrl: string;\n databaseName: string;\n username: string;\n password: string;\n }): Promise<void>;\n /**\n * Delete a per-app database user. Idempotent: missing user is a\n * no-op (best-effort cleanup, mirrors `IPostgresAdminClient`\n * semantics).\n */\n deleteApplicationDatabaseUser(input: {\n adminConnectUrl: string;\n username: string;\n }): Promise<void>;\n /**\n * Upsert a database user holding ONE custom role carrying exactly the given\n * collection-scoped privileges (Step 3 / R1 / D14).\n *\n * Deliberately a SEPARATE method from\n * {@link IMongoSelfAdminClient.upsertApplicationDatabaseUser} rather than an\n * optional parameter on it. The two grant fundamentally different authority —\n * that one grants `readWrite` + `dbAdmin` on the WHOLE database, this one\n * grants named actions on named collections and nothing else — and a single\n * method with an optional \"privileges\" argument would make the wide grant the\n * behaviour you get by forgetting to pass something. Two methods make the\n * caller name which authority it intends.\n *\n * `privileges` is authoritative and REPLACES the role's previous contents, so\n * a resource removed from `resourceAccess` loses its grant on the next sync.\n * An empty list is legitimate — a principal with no data access — and MUST\n * yield a role granting nothing rather than being treated as \"unspecified\".\n *\n * Idempotent: safe to call when the role and user already exist.\n */\n /**\n * Retire a collection-scoped user AND the custom role it holds.\n *\n * Separate from {@link IMongoSelfAdminClient.deleteApplicationDatabaseUser}\n * because a scoped principal owns TWO objects in TWO databases — the user in\n * `admin`, the role in the application database — and dropping only the user\n * leaves a privileged role behind that the next mint silently adopts.\n *\n * Idempotent in both halves: a missing user or a missing role is a no-op.\n */\n dropCollectionScopedDatabaseUser(input: {\n adminConnectUrl: string;\n databaseName: string;\n username: string;\n roleName: string;\n }): Promise<void>;\n upsertCollectionScopedDatabaseUser(input: {\n adminConnectUrl: string;\n databaseName: string;\n username: string;\n password: string;\n roleName: string;\n privileges: ReadonlyArray<{\n resource: { db: string; collection: string };\n actions: readonly string[];\n }>;\n }): Promise<void>;\n}\n\nexport interface InfraProviderModule {\n provider: InfraProvider;\n supportedCapabilities: ReadonlyArray<InfraCapability>;\n\n /**\n * Present when this module EXISTS but the platform cannot yet deliver a working connection for the\n * provider — the module can plan, and an application selecting it would still receive no usable\n * credential. The value says why, and what would change it.\n *\n * ## Why the module stays in the catalogue instead of being removed\n *\n * The module's `plan()` is correct and useful: it formalizes the env contract an operator will set\n * and gives the lockfile a stable digest. What is missing is elsewhere (for `AWS_S3`, the credential\n * broker that speaks only MinIO's AssumeRole, #14). Removing the module would lose the correct half\n * to express the missing one.\n *\n * ## What it does\n *\n * A declaration resolving to a provider whose module carries this is REFUSED at authoring time\n * (`wildo config validate` / `config sync` / `lock check`), exactly like a declaration resolving to\n * a provider with no module. Delete the field in the same change that makes the provider servable.\n */\n unservableReason?: string;\n\n /**\n * Every `Wildo_Application_Secrets` JSON path this module can mint PER RUNTIME PRINCIPAL.\n *\n * ## Why this is static, when `plan()` already reports the same paths\n *\n * `plan()` answers \"what does THIS application get\", so it needs an\n * {@link InfraProviderPlanningContext}. The secret-DELIVERY path in apps-manager asks a different\n * question — \"which paths are per-principal AT ALL\" — and must answer it with no application in\n * hand, because it decides what to STRIP from the application blob before overlaying a\n * principal's own material. A principal must receive a credential only where one was minted for\n * it; anything left un-stripped is delivered with the APPLICATION's value, which for a database\n * means `readWrite` + `dbAdmin` on the whole database.\n *\n * Empty for a provider with no per-app credentials — shared-bucket object storage\n * (`MINIO_SELF`, `AWS_S3`) and stateless infra (`CLAMAV_SELF`). Empty is a\n * real answer, not a missing one, which is why the field is required rather than optional: a\n * module that mints per-principal material must not be able to omit it and be silently read as\n * \"nothing to confine\".\n *\n * **Modules MUST derive `appRuntime.perAppSecretBlobPaths` from this same constant** rather than\n * repeating the literal list. Two spellings of where a credential lives is the defect this exists\n * to prevent, one layer up.\n *\n * **A module declaring paths here MUST derive a distinct resource name per principal**, in its mint\n * AND its revoke, through one function. apps-manager dispatches every minion mint and revocation\n * through the catalogue (#1692), so a module that ignored `principal` and derived the application\n * backend's own name would OVERWRITE the backend's user on a minion mint and DELETE it on a minion\n * revocation — the defect `invariant-call-site-enumeration.md` #18 records. MongoDB Atlas shipped in\n * exactly that shape and was refused at registration until its per-principal path landed (#1694).\n */\n perPrincipalSecretBlobPaths: ReadonlyArray<string>;\n\n plan(context: InfraProviderPlanningContext): InfraProviderPlanContribution;\n\n /**\n * Optional. Called by apps-manager at app-init time (see\n * `wildo-application-lifecycle.service.ts:432-580` — the existing\n * per-resource ceremony this method abstracts). Upserts the per-app\n * user / role / DB on the broker using `secretInputs` for any\n * orchestrator-supplied passwords; returns the canonical form of\n * the persisted secrets blob slice.\n *\n * Returns `null` when the provider has no per-app credentials (e.g.,\n * shared S3 bucket with shared access key).\n *\n * **Idempotent broker upsert** — the module installs / replaces the\n * user with the password from `secretInputs`. It does NOT make\n * generation/rotation decisions; that is the orchestrator's\n * responsibility (driven by the existing `overrideCredentials`\n * flag on `WildoApplicationInitOptions`). The module MUST NOT\n * crash on \"user already exists\" (PUT semantics on the broker\n * management API are sufficient for RabbitMQ; equivalent\n * upsert-on-conflict semantics for other providers).\n */\n mintAppCredentials?(\n context: AppCredentialMintingContext,\n ): Promise<AppCredentialMintingResult | null>;\n\n /**\n * Optional. Symmetric to `mintAppCredentials`: afterwards the principal's credential is REFUSED by the\n * server. Called by apps-manager when a minion leaves the declaration, and for EVERY principal of an\n * application withdrawn from the platform (`deregisterApplication`, #1307).\n *\n * **It revokes and never destroys.** It removes the ability to authenticate — an ACL user, a broker\n * user, a database user, or a login — and leaves the application's DATA where it is: its database,\n * keys, queues and blobs. A withdrawn application is restored by re-minting (`mintAppCredentials` with\n * the recorded material), which only works if nothing it owns was dropped. Destroying data is a\n * different verb with its own protection (#1562); a module must never reach it through this one.\n *\n * Idempotent: safe to call when the per-principal user / role does not exist (no throw on\n * already-absent), because a retry after a partial revocation must converge.\n */\n revokeAppCredentials?(context: AppCredentialMintingContext): Promise<void>;\n\n /**\n * Optional (LD-8 / Slice 2.5). Called by the orchestrator\n * (`PlatformInfrastructureManagerService.provisionServiceCredentials`\n * + `ensureAppsManagerCredentials`) at platform-service-init time.\n * Upserts a SCOPED (non-admin) per-platform-service user on the\n * broker for inter-service messaging — distinct from\n * `mintAppCredentials` (audience-3, customer-app per-app creds).\n *\n * Same orchestrator-pattern as `mintAppCredentials`: orchestrator\n * owns generation, module is upsert-only.\n *\n * Returns `null` when the provider has no per-platform-service\n * credentials concept (e.g., S3 modules — platform services use a\n * shared bucket).\n */\n mintPlatformServiceCredentials?(\n context: PlatformServiceCredentialMintingContext,\n ): Promise<PlatformServiceCredentialMintingResult | null>;\n}\n"]}
|
|
@@ -64,11 +64,14 @@ import { BackingServiceSource } from './backing-services.schemas';
|
|
|
64
64
|
* - Azure Key Vault (a vault in the Azure RBAC permission model): two user-assigned managed identities on apps-manager,
|
|
65
65
|
* each with a CUSTOM role on the vault. The built-in roles do not fit: "Key Vault Crypto User" can update and back up a
|
|
66
66
|
* key, and "Key Vault Crypto Officer" holds `vaults/keys/*`, signing included.
|
|
67
|
-
* - Signer: `Microsoft.KeyVault/vaults/keys/read`, `…/keys/
|
|
67
|
+
* - Signer: `Microsoft.KeyVault/vaults/keys/read`, `…/keys/sign/action`,
|
|
68
68
|
* `…/keys/encrypt/action`, `…/keys/decrypt/action` (a data key is wrapped with A256GCM under an `oct-HSM` key, which
|
|
69
69
|
* a Premium vault offers in preview; a Standard vault cannot hold one and serves signing only).
|
|
70
|
-
* - Operator: `…/keys/read`, `…/keys/
|
|
70
|
+
* - Operator: `…/keys/read`, `…/keys/create/action`, `…/keys/update/action` (disable),
|
|
71
71
|
* `…/keys/delete`, `…/keys/purge/action`.
|
|
72
|
+
* Azure has no `keys/versions/read` data action: `keys/read` reads every version. Measured 2026-11-12 (#3697) with two
|
|
73
|
+
* user-assigned managed identities holding exactly these roles: each verb succeeded as its own identity and answered
|
|
74
|
+
* 403 as the other one.
|
|
72
75
|
* The vault's recovery level decides whether a destroyed key is purged at once or kept until retention ends.
|
|
73
76
|
* - Azure Managed HSM (`*.managedhsm.azure.net`): the same two identities, with custom roles in the HSM's LOCAL RBAC
|
|
74
77
|
* (the built-in "Managed HSM Crypto User" can sign and back up, and cannot purge). Signer:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform-key-management.schemas.d.ts","sourceRoot":"","sources":["../../../../src/project-config/shared/platform-key-management.schemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"platform-key-management.schemas.d.ts","sourceRoot":"","sources":["../../../../src/project-config/shared/platform-key-management.schemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAkBxB,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAElE,4IAA4I;AAC5I;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyGG;AACH,eAAO,MAAM,gCAAgC;;kBAE3C,CAAC;AAEH,+HAA+H;AAC/H,eAAO,MAAM,6BAA6B;;;;;;;kBASxC,CAAC;AAEH,eAAO,MAAM,4BAA4B;;;;;;;;;8BAAoG,CAAC;AAC9I,MAAM,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,4BAA4B,CAAC,CAAC;AAElF,0EAA0E;AAC1E,oBAAY,8BAA8B;IACxC,4EAA4E;IAC5E,GAAG,QAAQ;IACX,iGAAiG;IACjG,QAAQ,aAAa;CACtB;AAED,yCAAyC;AACzC,eAAO,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1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { PlatformAdminEnvKey, PlatformDocumentationSiteEnvKey, PlatformEmailEnvKey, PlatformInfrastructureEnvKey, PlatformIngressEnvKey, PlatformKubernetesEnvKey, PlatformLoggingEnvKey, PlatformObservabilityEnvKey, PlatformOwnershipDnsEnvKey, PlatformProcessEnvKey, PlatformProviderSelectionEnvKey, PlatformSecurityEnvKey, PlatformServiceUrlEnvKey, } from '../../bootstrap/platform-runtime-env.contracts.js';
|
|
3
|
+
import { AGENT_CONTENT_GUARDRAILS_ENV_VAR } from '@wildo-ai/saas-models';
|
|
3
4
|
import { BackingServiceSource } from './backing-services.schemas.js';
|
|
4
5
|
/** @wildo_source:part:start platform.config.platform-key-management facet:layer:platform facet:family:infra facet:audience:app-developer */
|
|
5
6
|
/**
|
|
@@ -65,11 +66,14 @@ import { BackingServiceSource } from './backing-services.schemas.js';
|
|
|
65
66
|
* - Azure Key Vault (a vault in the Azure RBAC permission model): two user-assigned managed identities on apps-manager,
|
|
66
67
|
* each with a CUSTOM role on the vault. The built-in roles do not fit: "Key Vault Crypto User" can update and back up a
|
|
67
68
|
* key, and "Key Vault Crypto Officer" holds `vaults/keys/*`, signing included.
|
|
68
|
-
* - Signer: `Microsoft.KeyVault/vaults/keys/read`, `…/keys/
|
|
69
|
+
* - Signer: `Microsoft.KeyVault/vaults/keys/read`, `…/keys/sign/action`,
|
|
69
70
|
* `…/keys/encrypt/action`, `…/keys/decrypt/action` (a data key is wrapped with A256GCM under an `oct-HSM` key, which
|
|
70
71
|
* a Premium vault offers in preview; a Standard vault cannot hold one and serves signing only).
|
|
71
|
-
* - Operator: `…/keys/read`, `…/keys/
|
|
72
|
+
* - Operator: `…/keys/read`, `…/keys/create/action`, `…/keys/update/action` (disable),
|
|
72
73
|
* `…/keys/delete`, `…/keys/purge/action`.
|
|
74
|
+
* Azure has no `keys/versions/read` data action: `keys/read` reads every version. Measured 2026-11-12 (#3697) with two
|
|
75
|
+
* user-assigned managed identities holding exactly these roles: each verb succeeded as its own identity and answered
|
|
76
|
+
* 403 as the other one.
|
|
73
77
|
* The vault's recovery level decides whether a destroyed key is purged at once or kept until retention ends.
|
|
74
78
|
* - Azure Managed HSM (`*.managedhsm.azure.net`): the same two identities, with custom roles in the HSM's LOCAL RBAC
|
|
75
79
|
* (the built-in "Managed HSM Crypto User" can sign and back up, and cannot purge). Signer:
|
|
@@ -265,6 +269,8 @@ const WILDO_OWNED_PLATFORM_ENV_KEYS = new Set([
|
|
|
265
269
|
PlatformKubernetesEnvKey, PlatformIngressEnvKey, PlatformLoggingEnvKey, PlatformObservabilityEnvKey, PlatformProviderSelectionEnvKey,
|
|
266
270
|
PlatformEmailEnvKey, PlatformOwnershipDnsEnvKey, PlatformDocumentationSiteEnvKey,
|
|
267
271
|
].flatMap((vocabulary) => Object.values(vocabulary)),
|
|
272
|
+
// An application runtime's guardrail posture (`WildoInfraEnvConfig.agentContentGuardrails`), named by saas-models.
|
|
273
|
+
AGENT_CONTENT_GUARDRAILS_ENV_VAR,
|
|
268
274
|
// Set literally by the deployment templates rather than through the env contract.
|
|
269
275
|
'PLATFORM_SERVICE', 'NODE_OPTIONS', 'NODE_ENV',
|
|
270
276
|
]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform-key-management.schemas.js","sourceRoot":"","sources":["../../../../src/project-config/shared/platform-key-management.schemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,mBAAmB,EACnB,+BAA+B,EAC/B,mBAAmB,EACnB,4BAA4B,EAC5B,qBAAqB,EACrB,wBAAwB,EACxB,qBAAqB,EACrB,2BAA2B,EAC3B,0BAA0B,EAC1B,qBAAqB,EACrB,+BAA+B,EAC/B,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAElE,4IAA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AM,SAAS,GAAG,aAAa,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QACpD,OAAO,MAAM,CAAC,UAAU,KAAK,SAAS,IAAI,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,GAAG,SAAS,GAAG,CAAC,CAAC;IAC1F,CAAC,CAAC,CAAC;AACL,CAAC;AAED,sHAAsH;AACtH,MAAM,UAAU,+BAA+B,CAAC,MAA6B,EAAE,eAAwB;IACrG,MAAM,MAAM,GAAG,CAAC,MAAM,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;IAC5E,OAAO,GAAG,eAAe,CAAC,CAAC,CAAC,gBAAgB,eAAe,KAAK,CAAC,CAAC,CAAC,EAAE,4CAA4C,MAAM,CAAC,UAAU,IAAI;UAClI,0DAA0D,yCAAyC,sBAAsB;UACzH,6DAA6D,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,eAAe,KAAK;UACzH,2HAA2H;UAC3H,wFAAwF,CAAC;AAC/F,CAAC;AAED,uHAAuH;AACvH,MAAM,UAAU,yBAAyB,CAAC,qBAAmE;IAC3G,OAAO,qBAAqB,EAAE,KAAK,EAAE,MAAM,KAAK,oBAAoB,CAAC,IAAI,CAAC;AAC5E,CAAC","sourcesContent":["import { z } from 'zod';\n\nimport {\n PlatformAdminEnvKey,\n PlatformDocumentationSiteEnvKey,\n PlatformEmailEnvKey,\n PlatformInfrastructureEnvKey,\n PlatformIngressEnvKey,\n PlatformKubernetesEnvKey,\n PlatformLoggingEnvKey,\n PlatformObservabilityEnvKey,\n PlatformOwnershipDnsEnvKey,\n PlatformProcessEnvKey,\n PlatformProviderSelectionEnvKey,\n PlatformSecurityEnvKey,\n PlatformServiceUrlEnvKey,\n} from '../../bootstrap/platform-runtime-env.contracts';\nimport { BackingServiceSource } from './backing-services.schemas';\n\n/** @wildo_source:part:start platform.config.platform-key-management facet:layer:platform facet:family:infra facet:audience:app-developer */\n/**\n * # Where the platform keeps the keys it holds for applications (#2933)\n *\n * apps-manager is the custodian of every platform-held key (approval seals, signature requests, and the wrapping keys\n * of an application's sealed secrets, #2894). Without this block it\n * seals them under its own key-encryption root (the LOCAL provider). With it, apps-manager also serves the\n * `vault-transit` and `vault-kv` key providers, and an application's key binding may name one of them.\n *\n * This is a PLATFORM-tier declaration, like `platformStorage`: one apps-manager holds one Vault, whatever application\n * an environment file belongs to. It is deliberately not a `backingServices` kind. A backing service is something an\n * application runtime dials, with credentials minted per application; no application runtime ever reaches this Vault,\n * and nothing is minted per application in it.\n *\n * - `{ vault: { source: 'self' } }` — the CLI renders a single-node OpenBao (the MPL-licensed Vault fork, API\n * compatible for everything used) beside apps-manager, in docker compose and in Kubernetes. It unseals itself from a\n * framework-managed key and configures itself on its first start: the Transit and KV mounts, the two least-privilege\n * policies, and the two tokens apps-manager speaks with. Good for development and for a small self-hosted platform;\n * its protection is SOFTWARE, as every Vault's is. Its self-initialization runs only on EMPTY storage, so an OpenBao\n * first started before a policy changed keeps the older policy: one started before #2894 cannot wrap data keys\n * (`transit/encrypt` and `transit/decrypt` answer 403) until the signer policy is written again (`bao policy write`\n * with `vaultSignerPolicy`) or its storage is recreated.\n * - `{ vault: { source: 'managed', address, … } }` — the operator's own Vault or OpenBao. The operator configures the\n * mounts and policies (`vaultSignerPolicy` / `vaultOperatorPolicy` in the key-management contracts) and puts the two\n * tokens in `secrets.json` under `platformKeyVaultManaged`.\n *\n * Absent, apps-manager serves no Vault provider, and a binding that names one is refused PROVIDER_UNAVAILABLE.\n *\n * ## Cloud KMS (#2896)\n *\n * `awsKms`, `googleCloudKms` and `azureKeyVault` make apps-manager serve the `aws-kms`, `google-cloud-kms` and\n * `azure-key-vault` providers: the key is generated inside the vendor's HSM, never leaves it, and the vendor signs. They\n * are always the operator's own account, so they carry no `source`. apps-manager authenticates with its WORKLOAD\n * identity (an IAM role for its service account, GKE workload identity, an Azure managed identity): nothing here is a\n * secret, and `secrets.json` holds nothing for them.\n *\n * Each provider acts as two identities, as Vault does with two tokens. The SIGNER may only read keys, sign, and wrap and\n * unwrap data keys under a wrapping key (#2894); the OPERATOR creates, disables and destroys keys and may never sign, wrap\n * or unwrap. Every wrap is authenticated encryption under a key only the vendor holds. Neither vendor's broad built-in role keeps to that, so\n * grant, per vendor:\n * - AWS: apps-manager's identity may only `sts:AssumeRole` the two roles. Every key apps-manager creates carries the tag\n * `wildo:key-ref`, and the policies are scoped by it:\n * - Signer, on `arn:aws:kms:<region>:<account>:key/*`: `kms:Sign`, `kms:Encrypt` and `kms:Decrypt` only where\n * `aws:ResourceTag/wildo:key-ref` is present (`\"Null\": { … \"false\" }`), so it cannot sign with, or decrypt under,\n * another key in the account; `kms:GetPublicKey` and `kms:DescribeKey` unconditioned (both read-only).\n * - Operator: `kms:CreateKey` and `kms:TagResource` on `\"Resource\": \"*\"` (CreateKey names no key yet), only where\n * `aws:RequestTag/wildo:key-ref` is present and `aws:TagKeys` is exactly `[\"wildo:key-ref\"]`; on `key/*`,\n * `kms:DisableKey` and `kms:ScheduleKeyDeletion` only where `aws:ResourceTag/wildo:key-ref` is present, and\n * `kms:DescribeKey`; never `kms:Sign`, `kms:Encrypt`, `kms:Decrypt` nor `kms:UntagResource`.\n * - The tag is what admits a key to the signer, so whoever may tag may admit: the operator's `kms:TagResource` lets it\n * put `wildo:key-ref` on ANY key in the account, which the signer could then sign with. AWS warns of exactly this\n * (\"Be cautious about giving principals the `kms:TagResource` … permissions\"). Keep the operator role to apps-manager\n * alone, and consider a permissions boundary or SCP denying `kms:TagResource` on keys outside the custodian's.\n * - KMS applies a tag to authorization up to five minutes after it is set, so a NEW version may be refused `kms:Sign`\n * for those minutes: the first ACTIVE version of every new keyring (made at its first signature request), and one\n * made by an emergency rotation. The signature fails as a provider fault and the caller retries it; so does the first\n * wrap under a new wrapping key, which the application's data-key ring asks for again on its own retry.\n * - Google: apps-manager's identity holds `roles/iam.serviceAccountTokenCreator` on the two service accounts only.\n * Signer: `roles/cloudkms.signer`, `roles/cloudkms.cryptoKeyEncrypterDecrypter`, `roles/cloudkms.publicKeyViewer` and\n * `roles/cloudkms.viewer` on the key ring (sign, wrap and unwrap data keys, read the public key, read a version's state). Operator: `roles/cloudkms.admin` on the key ring, which contains no\n * cryptographic operation.\n * - Azure Key Vault (a vault in the Azure RBAC permission model): two user-assigned managed identities on apps-manager,\n * each with a CUSTOM role on the vault. The built-in roles do not fit: \"Key Vault Crypto User\" can update and back up a\n * key, and \"Key Vault Crypto Officer\" holds `vaults/keys/*`, signing included.\n * - Signer: `Microsoft.KeyVault/vaults/keys/read`, `…/keys/versions/read`, `…/keys/sign/action`,\n * `…/keys/encrypt/action`, `…/keys/decrypt/action` (a data key is wrapped with A256GCM under an `oct-HSM` key, which\n * a Premium vault offers in preview; a Standard vault cannot hold one and serves signing only).\n * - Operator: `…/keys/read`, `…/keys/versions/read`, `…/keys/create/action`, `…/keys/update/action` (disable),\n * `…/keys/delete`, `…/keys/purge/action`.\n * The vault's recovery level decides whether a destroyed key is purged at once or kept until retention ends.\n * - Azure Managed HSM (`*.managedhsm.azure.net`): the same two identities, with custom roles in the HSM's LOCAL RBAC\n * (the built-in \"Managed HSM Crypto User\" can sign and back up, and cannot purge). Signer:\n * `Microsoft.KeyVault/managedHsm/keys/read/action`, `…/keys/sign/action`, `…/keys/encrypt/action`, `…/keys/decrypt/action`.\n * Operator: `…/keys/read/action`,\n * `…/keys/create`, `…/keys/write/action`, `…/keys/delete`, `…/keys/deletedKeys/read/action`,\n * `…/keys/deletedKeys/delete` (purge).\n *\n * spec-cite: AWS KMS developer guide, \"Use tags to control access to KMS keys\" (`aws:ResourceTag`, the five-minute\n * delay, limiting `kms:TagResource` with `aws:RequestTag` / `aws:TagKeys`),\n * https://docs.aws.amazon.com/kms/latest/developerguide/tag-authorization.html; AWS KMS permissions reference\n * (`CreateKey`'s resource is `*`), https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html; Azure built-in roles, Security (Key\n * Vault Crypto Officer DataActions `Microsoft.KeyVault/vaults/keys/*`) and Azure permissions, Microsoft.KeyVault (the\n * `vaults/keys/*` data actions), https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles/security;\n * Managed HSM local RBAC built-in roles (the data-action table),\n * https://learn.microsoft.com/en-us/azure/key-vault/managed-hsm/built-in-roles.\n *\n * When a provider registers at startup, apps-manager logs the vendor's quota and per-request cost. It also holds its own\n * signing under 80% of the vendor's per-second quota, per process.\n *\n * ## Corroboration\n *\n * Every ten minutes, apps-manager compares, per key version and closed hour, the signatures its signing log records with\n * the ones the vendor's own audit log records, and writes one audit row per provider and hour:\n * - UNACCOUNTED (CRITICAL) the moment the vendor shows more signatures than apps-manager can account for: a key was used\n * outside the custodian, or a signature went unrecorded;\n * - otherwise, once the hour is six hours old (vendor logs arrive late): UNCORROBORATED (the vendor recorded fewer, or its\n * log could not be read) or CORROBORATED.\n * It reads as the OPERATOR identity, which therefore also needs:\n * - AWS: `cloudtrail:LookupEvents` (KMS `Sign` is a CloudTrail management event; nothing to enable).\n * - Google: `roles/logging.privateLogViewer` on the project, and Cloud KMS Data Access audit logs ENABLED (they are off by\n * default, and until they are on, every hour is uncorroborated).\n * - Azure: Log Analytics Reader on the workspace named by `logAnalyticsWorkspaceId`, which the vault's diagnostic setting\n * sends `AuditEvent` to.\n */\nexport const PlatformKeyVaultSelfHostedSchema = z.strictObject({\n source: z.literal(BackingServiceSource.SELF),\n});\n\n/** The operator's own Vault or OpenBao. Mounts and prefix default to the provider defaults (`transit`, `secret`, `wildo-`). */\nexport const PlatformKeyVaultManagedSchema = z.strictObject({\n source: z.literal(BackingServiceSource.MANAGED),\n /** The Vault API address apps-manager dials, e.g. `https://vault.internal:8200`. */\n address: z.url(),\n /** Vault Enterprise namespace (`team/keys/`); absent on open-source Vault and OpenBao's root namespace. */\n namespace: z.string().min(1).optional(),\n transitMount: z.string().min(1).optional(),\n kvMount: z.string().min(1).optional(),\n keyNamePrefix: z.string().min(1).optional(),\n});\n\nexport const PlatformKeyVaultConfigSchema = z.discriminatedUnion('source', [PlatformKeyVaultSelfHostedSchema, PlatformKeyVaultManagedSchema]);\nexport type PlatformKeyVaultConfig = z.infer<typeof PlatformKeyVaultConfigSchema>;\n\n/** The protection level apps-manager creates Google Cloud KMS keys at. */\nexport enum PlatformGoogleKmsKeyProtection {\n /** In Cloud HSM (FIPS 140-2 Level 3): the key's attestation is HARDWARE. */\n HSM = 'HSM',\n /** In Cloud KMS software: the key's attestation is SOFTWARE, and a HARDWARE floor refuses it. */\n SOFTWARE = 'SOFTWARE',\n}\n\n/** AWS KMS in the operator's account. */\nexport const PlatformKeyAwsKmsConfigSchema = z.strictObject({\n region: z.string().regex(/^[a-z]{2}(-[a-z]+)+-\\d$/),\n /** The role apps-manager assumes to read keys and sign. */\n signerRoleArn: z.string().regex(/^arn:aws[a-z-]*:iam::\\d{12}:role\\/.+$/),\n /** The role apps-manager assumes to create, disable and schedule the deletion of keys. */\n operatorRoleArn: z.string().regex(/^arn:aws[a-z-]*:iam::\\d{12}:role\\/.+$/),\n /** A KMS endpoint other than the region's public one (a VPC interface endpoint). */\n endpoint: z.url().optional(),\n});\n\n/** Google Cloud KMS in the operator's project. */\nexport const PlatformKeyGoogleCloudKmsConfigSchema = z.strictObject({\n /** `projects/<project>/locations/<location>/keyRings/<ring>`; created by the operator, since a key ring cannot be deleted. */\n keyRing: z.string().regex(/^projects\\/[^/]+\\/locations\\/[^/]+\\/keyRings\\/[^/]+$/),\n signerServiceAccount: z.email(),\n operatorServiceAccount: z.email(),\n protectionLevel: z.enum(PlatformGoogleKmsKeyProtection).default(PlatformGoogleKmsKeyProtection.HSM),\n});\n\n/** Azure Key Vault (Premium) or Managed HSM in the operator's subscription. */\nexport const PlatformKeyAzureKeyVaultConfigSchema = z.strictObject({\n /** `https://<vault>.vault.azure.net` or `https://<hsm>.managedhsm.azure.net`. */\n vaultUrl: z.url(),\n /** The client id of the signer's user-assigned managed identity. */\n signerClientId: z.uuid(),\n /** The client id of the operator's user-assigned managed identity. */\n operatorClientId: z.uuid(),\n /** HSM-protected keys (`EC-HSM`, a Premium vault or Managed HSM); `false` makes software `EC` keys. */\n hsm: z.boolean().default(true),\n /**\n * The Log Analytics workspace (its GUID) the vault's diagnostic setting sends `AuditEvent` to, in the `AzureDiagnostics`\n * destination mode. apps-manager reads it hourly to corroborate its signatures; absent, no Azure hour is compared.\n */\n logAnalyticsWorkspaceId: z.uuid().optional(),\n});\n\n/** The SoftHSM2 module the platform image carries: the one PKCS#11 module a containerised apps-manager has without a mount. */\nexport const PLATFORM_IMAGE_BUNDLED_PKCS11_MODULE_PATH = '/usr/lib/softhsm/libsofthsm2.so';\n\n/** An absolute path with no `.` or `..` segment, so \"is this path inside that mount\" is a plain prefix question. */\nconst AbsoluteNormalPathSchema = z\n .string()\n .regex(/^\\//, 'an absolute path')\n .refine((path) => !/(^|\\/)\\.{1,2}(\\/|$)/.test(path), 'a path with no `.` or `..` segment');\n\n/** Where the platform image keeps apps-manager itself: a mount here (or over `/`) would hide the service it serves. */\nconst PLATFORM_IMAGE_APPLICATION_ROOT = '/app';\n\n/**\n * One file or directory of the HSM vendor's PKCS#11 client, mounted READ-ONLY into apps-manager's container (#3019): the\n * module, its configuration, the client certificates. `hostPath` is on the docker host (compose) or on every node that\n * may run apps-manager (Kubernetes, a `hostPath` volume); `containerPath` is where apps-manager sees it.\n */\nexport const PlatformKeyPkcs11ClientFileSchema = z.strictObject({\n hostPath: AbsoluteNormalPathSchema,\n containerPath: AbsoluteNormalPathSchema.refine(\n (path) => path !== '/' && path.replace(/\\/+$/, '') !== PLATFORM_IMAGE_APPLICATION_ROOT && !path.startsWith(`${PLATFORM_IMAGE_APPLICATION_ROOT}/`),\n `a path outside \\`/\\` and \\`${PLATFORM_IMAGE_APPLICATION_ROOT}\\` (the platform image keeps apps-manager there)`,\n ),\n});\nexport type PlatformKeyPkcs11ClientFile = z.infer<typeof PlatformKeyPkcs11ClientFileSchema>;\n\n/**\n * A dedicated HSM reached over PKCS#11 (#2934): Thales Luna, Entrust nShield, AWS CloudHSM, Azure Cloud HSM, an\n * on-premises appliance, or SoftHSM2. apps-manager loads the vendor's PKCS#11 module, logs in to one token with a user PIN\n * (operator-typed in `secrets.json` under `platformKeyPkcs11: { pin }`, never here) and serves the `pkcs11` provider.\n *\n * Protection is read from the token, not declared: a key counts as HARDWARE only when the slot reports a hardware slot\n * AND the token's model is listed in `hardwareTokenModels`, which is your statement that this model is the hardware you\n * run. SoftHSM2 is always SOFTWARE. The binding (`pkcs11js`) is compiled by `pnpm setup:pkcs11`; an apps-manager that\n * cannot load it says so at boot and refuses every signature on this provider.\n *\n * ## A real HSM in a containerised platform (#3019)\n *\n * The platform image carries only SoftHSM2. A real HSM's client comes from the host, and every vendor documents the same\n * containerised shape: mount the client library and its configuration READ-ONLY, and point the client at its\n * configuration with the vendor's own variable. So:\n * - `clientFiles` lists what to mount, each `{ hostPath, containerPath }`. compose renders a read-only bind mount and refuses\n * to start the service when the host path is missing; Kubernetes renders a read-only `hostPath` volume, which it mounts\n * unchecked, so the files must exist on every node that may run apps-manager (a missing one shows as a token that cannot\n * be opened, logged at boot). Both apps-manager services get them (INIT and serving).\n * - `environment` carries the vendor's variables (`ChrystokiConfigurationPath` for a Thales Luna client, …). It is\n * rendered in plain text beside the service, so it may hold paths and settings, never a credential; it may not name a\n * variable Wildo sets itself. The token PIN stays in `secrets.json`.\n * - In a container, `modulePath` must be the bundled SoftHSM2 or lie under a `containerPath`. Declaring `clientFiles` says\n * apps-manager runs in a container, so that is refused here; without `clientFiles` it is refused when compose or\n * Kubernetes renders apps-manager, because a framework developer's NATIVE apps-manager loads a host path legitimately\n * (Homebrew's SoftHSM2, `/opt/homebrew/lib/softhsm/libsofthsm2.so`).\n * - Both are for the CONTAINER lanes. A framework developer's native apps-manager runs on the host, where the client is\n * installed and configured as the vendor documents, and receives neither.\n *\n * Example, a Thales Luna client installed under `/usr/safenet/lunaclient` on the host:\n * `{ modulePath: '/usr/safenet/lunaclient/lib/libCryptoki2_64.so', tokenLabel: 'wildo', hardwareTokenModels: ['Luna K7'],\n * clientFiles: [{ hostPath: '/usr/safenet/lunaclient', containerPath: '/usr/safenet/lunaclient' },\n * { hostPath: '/etc/Chrystoki.conf', containerPath: '/etc/Chrystoki.conf' }],\n * environment: { ChrystokiConfigurationPath: '/etc' } }`.\n */\nexport const PlatformKeyPkcs11ConfigSchema = z\n .strictObject({\n /**\n * The vendor's PKCS#11 module, as an absolute path in apps-manager's filesystem: in the platform image, the bundled\n * `/usr/lib/softhsm/libsofthsm2.so` or a path under a `clientFiles[].containerPath`.\n */\n modulePath: z.string().regex(/^\\//, 'an absolute path'),\n /** The token's label, as the module reports it. */\n tokenLabel: z.string().min(1).max(32),\n /** Token models (`CK_TOKEN_INFO.model`) you state are hardware. Empty: every key reports SOFTWARE. */\n hardwareTokenModels: z.array(z.string().min(1)).default([]),\n /** The vendor client's files, mounted read-only into apps-manager's container (#3019). */\n clientFiles: z.array(PlatformKeyPkcs11ClientFileSchema).optional(),\n /** The vendor client's own environment variables (no credential, and no variable Wildo sets). */\n environment: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/, 'an environment variable name'), z.string()).optional(),\n })\n .superRefine((pkcs11, context) => {\n const containerPaths = (pkcs11.clientFiles ?? []).map((file) => file.containerPath.replace(/\\/+$/, ''));\n containerPaths.forEach((containerPath, index) => {\n if (containerPaths.indexOf(containerPath) !== index) {\n context.addIssue({ code: 'custom', path: ['clientFiles', index, 'containerPath'], message: `\"${containerPath}\" is mounted twice` });\n }\n });\n for (const name of Object.keys(pkcs11.environment ?? {})) {\n if (WILDO_OWNED_PLATFORM_ENV_KEYS.has(name)) {\n context.addIssue({ code: 'custom', path: ['environment', name], message: `\"${name}\" is a variable Wildo sets on apps-manager itself` });\n }\n }\n if (containerPaths.length > 0 && !pkcs11ModuleIsReachableInPlatformContainer(pkcs11)) {\n context.addIssue({ code: 'custom', path: ['modulePath'], message: describeUnreachablePkcs11Module(pkcs11) });\n }\n });\nexport type PlatformKeyPkcs11Config = z.infer<typeof PlatformKeyPkcs11ConfigSchema>;\n\nexport const WildoPlatformKeyManagementConfigSchema = z.strictObject({\n vault: PlatformKeyVaultConfigSchema.optional(),\n awsKms: PlatformKeyAwsKmsConfigSchema.optional(),\n googleCloudKms: PlatformKeyGoogleCloudKmsConfigSchema.optional(),\n azureKeyVault: PlatformKeyAzureKeyVaultConfigSchema.optional(),\n pkcs11: PlatformKeyPkcs11ConfigSchema.optional(),\n});\nexport type WildoPlatformKeyManagementConfig = z.infer<typeof WildoPlatformKeyManagementConfigSchema>;\n\n/** @wildo_source:part:end platform.config.platform-key-management */\n\n/** What deciding a module's reachability needs: the module, and where the client files are mounted. */\nexport interface Pkcs11ModuleMountView {\n readonly modulePath: string;\n readonly clientFiles?: readonly { readonly containerPath: string }[];\n}\n\n/**\n * Every environment variable Wildo itself sets on a platform process. A vendor `environment` entry may name none of them:\n * it would overwrite the platform's own value (a PIN, a connection string, the service's mode), and the vendor block is\n * rendered in plain text beside the service, never into a Secret.\n */\nconst WILDO_OWNED_PLATFORM_ENV_KEYS: ReadonlySet<string> = new Set<string>([\n ...[\n PlatformProcessEnvKey, PlatformServiceUrlEnvKey, PlatformInfrastructureEnvKey, PlatformSecurityEnvKey, PlatformAdminEnvKey,\n PlatformKubernetesEnvKey, PlatformIngressEnvKey, PlatformLoggingEnvKey, PlatformObservabilityEnvKey, PlatformProviderSelectionEnvKey,\n PlatformEmailEnvKey, PlatformOwnershipDnsEnvKey, PlatformDocumentationSiteEnvKey,\n ].flatMap((vocabulary) => Object.values(vocabulary) as string[]),\n // Set literally by the deployment templates rather than through the env contract.\n 'PLATFORM_SERVICE', 'NODE_OPTIONS', 'NODE_ENV',\n]);\n\n/**\n * Whether apps-manager, running in the PLATFORM IMAGE, can load `modulePath`: it is the bundled SoftHSM2, or it lies at or\n * under one of the declared `clientFiles[].containerPath`. Nothing else exists in that container.\n */\nexport function pkcs11ModuleIsReachableInPlatformContainer(pkcs11: Pkcs11ModuleMountView): boolean {\n if (pkcs11.modulePath === PLATFORM_IMAGE_BUNDLED_PKCS11_MODULE_PATH) return true;\n return (pkcs11.clientFiles ?? []).some(({ containerPath }) => {\n const mountRoot = containerPath.replace(/\\/+$/, '');\n return pkcs11.modulePath === mountRoot || pkcs11.modulePath.startsWith(`${mountRoot}/`);\n });\n}\n\n/** The refusal both container lanes (compose, Kubernetes) raise for an unreachable module, naming the declaration. */\nexport function describeUnreachablePkcs11Module(pkcs11: Pkcs11ModuleMountView, environmentName?: string): string {\n const mounts = (pkcs11.clientFiles ?? []).map((file) => file.containerPath);\n return `${environmentName ? `Environment \"${environmentName}\": ` : ''}platformKeyManagement.pkcs11.modulePath \"${pkcs11.modulePath}\" `\n + `is not the SoftHSM2 module the platform image carries (${PLATFORM_IMAGE_BUNDLED_PKCS11_MODULE_PATH}) and lies under no `\n + `platformKeyManagement.pkcs11.clientFiles[].containerPath (${mounts.length > 0 ? mounts.join(', ') : 'none declared'}). `\n + 'apps-manager runs in the platform image, where nothing else exists: declare the vendor\\'s module (and its configuration) '\n + 'in clientFiles as { hostPath, containerPath } and point modulePath inside one of them.';\n}\n\n/** Whether the platform runs its own Vault (OpenBao) in this environment: the one predicate both lanes render from. */\nexport function selfHostsPlatformKeyVault(platformKeyManagement: WildoPlatformKeyManagementConfig | undefined): boolean {\n return platformKeyManagement?.vault?.source === BackingServiceSource.SELF;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"platform-key-management.schemas.js","sourceRoot":"","sources":["../../../../src/project-config/shared/platform-key-management.schemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,mBAAmB,EACnB,+BAA+B,EAC/B,mBAAmB,EACnB,4BAA4B,EAC5B,qBAAqB,EACrB,wB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minEnvKey,\n PlatformDocumentationSiteEnvKey,\n PlatformEmailEnvKey,\n PlatformInfrastructureEnvKey,\n PlatformIngressEnvKey,\n PlatformKubernetesEnvKey,\n PlatformLoggingEnvKey,\n PlatformObservabilityEnvKey,\n PlatformOwnershipDnsEnvKey,\n PlatformProcessEnvKey,\n PlatformProviderSelectionEnvKey,\n PlatformSecurityEnvKey,\n PlatformServiceUrlEnvKey,\n} from '../../bootstrap/platform-runtime-env.contracts';\nimport { AGENT_CONTENT_GUARDRAILS_ENV_VAR } from '@wildo-ai/saas-models';\nimport { BackingServiceSource } from './backing-services.schemas';\n\n/** @wildo_source:part:start platform.config.platform-key-management facet:layer:platform facet:family:infra facet:audience:app-developer */\n/**\n * # Where the platform keeps the keys it holds for applications (#2933)\n *\n * apps-manager is the custodian of every platform-held key (approval seals, signature requests, and the wrapping keys\n * of an application's sealed secrets, #2894). Without this block it\n * seals them under its own key-encryption root (the LOCAL provider). With it, apps-manager also serves the\n * `vault-transit` and `vault-kv` key providers, and an application's key binding may name one of them.\n *\n * This is a PLATFORM-tier declaration, like `platformStorage`: one apps-manager holds one Vault, whatever application\n * an environment file belongs to. It is deliberately not a `backingServices` kind. A backing service is something an\n * application runtime dials, with credentials minted per application; no application runtime ever reaches this Vault,\n * and nothing is minted per application in it.\n *\n * - `{ vault: { source: 'self' } }` — the CLI renders a single-node OpenBao (the MPL-licensed Vault fork, API\n * compatible for everything used) beside apps-manager, in docker compose and in Kubernetes. It unseals itself from a\n * framework-managed key and configures itself on its first start: the Transit and KV mounts, the two least-privilege\n * policies, and the two tokens apps-manager speaks with. Good for development and for a small self-hosted platform;\n * its protection is SOFTWARE, as every Vault's is. Its self-initialization runs only on EMPTY storage, so an OpenBao\n * first started before a policy changed keeps the older policy: one started before #2894 cannot wrap data keys\n * (`transit/encrypt` and `transit/decrypt` answer 403) until the signer policy is written again (`bao policy write`\n * with `vaultSignerPolicy`) or its storage is recreated.\n * - `{ vault: { source: 'managed', address, … } }` — the operator's own Vault or OpenBao. The operator configures the\n * mounts and policies (`vaultSignerPolicy` / `vaultOperatorPolicy` in the key-management contracts) and puts the two\n * tokens in `secrets.json` under `platformKeyVaultManaged`.\n *\n * Absent, apps-manager serves no Vault provider, and a binding that names one is refused PROVIDER_UNAVAILABLE.\n *\n * ## Cloud KMS (#2896)\n *\n * `awsKms`, `googleCloudKms` and `azureKeyVault` make apps-manager serve the `aws-kms`, `google-cloud-kms` and\n * `azure-key-vault` providers: the key is generated inside the vendor's HSM, never leaves it, and the vendor signs. They\n * are always the operator's own account, so they carry no `source`. apps-manager authenticates with its WORKLOAD\n * identity (an IAM role for its service account, GKE workload identity, an Azure managed identity): nothing here is a\n * secret, and `secrets.json` holds nothing for them.\n *\n * Each provider acts as two identities, as Vault does with two tokens. The SIGNER may only read keys, sign, and wrap and\n * unwrap data keys under a wrapping key (#2894); the OPERATOR creates, disables and destroys keys and may never sign, wrap\n * or unwrap. Every wrap is authenticated encryption under a key only the vendor holds. Neither vendor's broad built-in role keeps to that, so\n * grant, per vendor:\n * - AWS: apps-manager's identity may only `sts:AssumeRole` the two roles. Every key apps-manager creates carries the tag\n * `wildo:key-ref`, and the policies are scoped by it:\n * - Signer, on `arn:aws:kms:<region>:<account>:key/*`: `kms:Sign`, `kms:Encrypt` and `kms:Decrypt` only where\n * `aws:ResourceTag/wildo:key-ref` is present (`\"Null\": { … \"false\" }`), so it cannot sign with, or decrypt under,\n * another key in the account; `kms:GetPublicKey` and `kms:DescribeKey` unconditioned (both read-only).\n * - Operator: `kms:CreateKey` and `kms:TagResource` on `\"Resource\": \"*\"` (CreateKey names no key yet), only where\n * `aws:RequestTag/wildo:key-ref` is present and `aws:TagKeys` is exactly `[\"wildo:key-ref\"]`; on `key/*`,\n * `kms:DisableKey` and `kms:ScheduleKeyDeletion` only where `aws:ResourceTag/wildo:key-ref` is present, and\n * `kms:DescribeKey`; never `kms:Sign`, `kms:Encrypt`, `kms:Decrypt` nor `kms:UntagResource`.\n * - The tag is what admits a key to the signer, so whoever may tag may admit: the operator's `kms:TagResource` lets it\n * put `wildo:key-ref` on ANY key in the account, which the signer could then sign with. AWS warns of exactly this\n * (\"Be cautious about giving principals the `kms:TagResource` … permissions\"). Keep the operator role to apps-manager\n * alone, and consider a permissions boundary or SCP denying `kms:TagResource` on keys outside the custodian's.\n * - KMS applies a tag to authorization up to five minutes after it is set, so a NEW version may be refused `kms:Sign`\n * for those minutes: the first ACTIVE version of every new keyring (made at its first signature request), and one\n * made by an emergency rotation. The signature fails as a provider fault and the caller retries it; so does the first\n * wrap under a new wrapping key, which the application's data-key ring asks for again on its own retry.\n * - Google: apps-manager's identity holds `roles/iam.serviceAccountTokenCreator` on the two service accounts only.\n * Signer: `roles/cloudkms.signer`, `roles/cloudkms.cryptoKeyEncrypterDecrypter`, `roles/cloudkms.publicKeyViewer` and\n * `roles/cloudkms.viewer` on the key ring (sign, wrap and unwrap data keys, read the public key, read a version's state). Operator: `roles/cloudkms.admin` on the key ring, which contains no\n * cryptographic operation.\n * - Azure Key Vault (a vault in the Azure RBAC permission model): two user-assigned managed identities on apps-manager,\n * each with a CUSTOM role on the vault. The built-in roles do not fit: \"Key Vault Crypto User\" can update and back up a\n * key, and \"Key Vault Crypto Officer\" holds `vaults/keys/*`, signing included.\n * - Signer: `Microsoft.KeyVault/vaults/keys/read`, `…/keys/sign/action`,\n * `…/keys/encrypt/action`, `…/keys/decrypt/action` (a data key is wrapped with A256GCM under an `oct-HSM` key, which\n * a Premium vault offers in preview; a Standard vault cannot hold one and serves signing only).\n * - Operator: `…/keys/read`, `…/keys/create/action`, `…/keys/update/action` (disable),\n * `…/keys/delete`, `…/keys/purge/action`.\n * Azure has no `keys/versions/read` data action: `keys/read` reads every version. Measured 2026-11-12 (#3697) with two\n * user-assigned managed identities holding exactly these roles: each verb succeeded as its own identity and answered\n * 403 as the other one.\n * The vault's recovery level decides whether a destroyed key is purged at once or kept until retention ends.\n * - Azure Managed HSM (`*.managedhsm.azure.net`): the same two identities, with custom roles in the HSM's LOCAL RBAC\n * (the built-in \"Managed HSM Crypto User\" can sign and back up, and cannot purge). Signer:\n * `Microsoft.KeyVault/managedHsm/keys/read/action`, `…/keys/sign/action`, `…/keys/encrypt/action`, `…/keys/decrypt/action`.\n * Operator: `…/keys/read/action`,\n * `…/keys/create`, `…/keys/write/action`, `…/keys/delete`, `…/keys/deletedKeys/read/action`,\n * `…/keys/deletedKeys/delete` (purge).\n *\n * spec-cite: AWS KMS developer guide, \"Use tags to control access to KMS keys\" (`aws:ResourceTag`, the five-minute\n * delay, limiting `kms:TagResource` with `aws:RequestTag` / `aws:TagKeys`),\n * https://docs.aws.amazon.com/kms/latest/developerguide/tag-authorization.html; AWS KMS permissions reference\n * (`CreateKey`'s resource is `*`), https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html; Azure built-in roles, Security (Key\n * Vault Crypto Officer DataActions `Microsoft.KeyVault/vaults/keys/*`) and Azure permissions, Microsoft.KeyVault (the\n * `vaults/keys/*` data actions), https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles/security;\n * Managed HSM local RBAC built-in roles (the data-action table),\n * https://learn.microsoft.com/en-us/azure/key-vault/managed-hsm/built-in-roles.\n *\n * When a provider registers at startup, apps-manager logs the vendor's quota and per-request cost. It also holds its own\n * signing under 80% of the vendor's per-second quota, per process.\n *\n * ## Corroboration\n *\n * Every ten minutes, apps-manager compares, per key version and closed hour, the signatures its signing log records with\n * the ones the vendor's own audit log records, and writes one audit row per provider and hour:\n * - UNACCOUNTED (CRITICAL) the moment the vendor shows more signatures than apps-manager can account for: a key was used\n * outside the custodian, or a signature went unrecorded;\n * - otherwise, once the hour is six hours old (vendor logs arrive late): UNCORROBORATED (the vendor recorded fewer, or its\n * log could not be read) or CORROBORATED.\n * It reads as the OPERATOR identity, which therefore also needs:\n * - AWS: `cloudtrail:LookupEvents` (KMS `Sign` is a CloudTrail management event; nothing to enable).\n * - Google: `roles/logging.privateLogViewer` on the project, and Cloud KMS Data Access audit logs ENABLED (they are off by\n * default, and until they are on, every hour is uncorroborated).\n * - Azure: Log Analytics Reader on the workspace named by `logAnalyticsWorkspaceId`, which the vault's diagnostic setting\n * sends `AuditEvent` to.\n */\nexport const PlatformKeyVaultSelfHostedSchema = z.strictObject({\n source: z.literal(BackingServiceSource.SELF),\n});\n\n/** The operator's own Vault or OpenBao. Mounts and prefix default to the provider defaults (`transit`, `secret`, `wildo-`). */\nexport const PlatformKeyVaultManagedSchema = z.strictObject({\n source: z.literal(BackingServiceSource.MANAGED),\n /** The Vault API address apps-manager dials, e.g. `https://vault.internal:8200`. */\n address: z.url(),\n /** Vault Enterprise namespace (`team/keys/`); absent on open-source Vault and OpenBao's root namespace. */\n namespace: z.string().min(1).optional(),\n transitMount: z.string().min(1).optional(),\n kvMount: z.string().min(1).optional(),\n keyNamePrefix: z.string().min(1).optional(),\n});\n\nexport const PlatformKeyVaultConfigSchema = z.discriminatedUnion('source', [PlatformKeyVaultSelfHostedSchema, PlatformKeyVaultManagedSchema]);\nexport type PlatformKeyVaultConfig = z.infer<typeof PlatformKeyVaultConfigSchema>;\n\n/** The protection level apps-manager creates Google Cloud KMS keys at. */\nexport enum PlatformGoogleKmsKeyProtection {\n /** In Cloud HSM (FIPS 140-2 Level 3): the key's attestation is HARDWARE. */\n HSM = 'HSM',\n /** In Cloud KMS software: the key's attestation is SOFTWARE, and a HARDWARE floor refuses it. */\n SOFTWARE = 'SOFTWARE',\n}\n\n/** AWS KMS in the operator's account. */\nexport const PlatformKeyAwsKmsConfigSchema = z.strictObject({\n region: z.string().regex(/^[a-z]{2}(-[a-z]+)+-\\d$/),\n /** The role apps-manager assumes to read keys and sign. */\n signerRoleArn: z.string().regex(/^arn:aws[a-z-]*:iam::\\d{12}:role\\/.+$/),\n /** The role apps-manager assumes to create, disable and schedule the deletion of keys. */\n operatorRoleArn: z.string().regex(/^arn:aws[a-z-]*:iam::\\d{12}:role\\/.+$/),\n /** A KMS endpoint other than the region's public one (a VPC interface endpoint). */\n endpoint: z.url().optional(),\n});\n\n/** Google Cloud KMS in the operator's project. */\nexport const PlatformKeyGoogleCloudKmsConfigSchema = z.strictObject({\n /** `projects/<project>/locations/<location>/keyRings/<ring>`; created by the operator, since a key ring cannot be deleted. */\n keyRing: z.string().regex(/^projects\\/[^/]+\\/locations\\/[^/]+\\/keyRings\\/[^/]+$/),\n signerServiceAccount: z.email(),\n operatorServiceAccount: z.email(),\n protectionLevel: z.enum(PlatformGoogleKmsKeyProtection).default(PlatformGoogleKmsKeyProtection.HSM),\n});\n\n/** Azure Key Vault (Premium) or Managed HSM in the operator's subscription. */\nexport const PlatformKeyAzureKeyVaultConfigSchema = z.strictObject({\n /** `https://<vault>.vault.azure.net` or `https://<hsm>.managedhsm.azure.net`. */\n vaultUrl: z.url(),\n /** The client id of the signer's user-assigned managed identity. */\n signerClientId: z.uuid(),\n /** The client id of the operator's user-assigned managed identity. */\n operatorClientId: z.uuid(),\n /** HSM-protected keys (`EC-HSM`, a Premium vault or Managed HSM); `false` makes software `EC` keys. */\n hsm: z.boolean().default(true),\n /**\n * The Log Analytics workspace (its GUID) the vault's diagnostic setting sends `AuditEvent` to, in the `AzureDiagnostics`\n * destination mode. apps-manager reads it hourly to corroborate its signatures; absent, no Azure hour is compared.\n */\n logAnalyticsWorkspaceId: z.uuid().optional(),\n});\n\n/** The SoftHSM2 module the platform image carries: the one PKCS#11 module a containerised apps-manager has without a mount. */\nexport const PLATFORM_IMAGE_BUNDLED_PKCS11_MODULE_PATH = '/usr/lib/softhsm/libsofthsm2.so';\n\n/** An absolute path with no `.` or `..` segment, so \"is this path inside that mount\" is a plain prefix question. */\nconst AbsoluteNormalPathSchema = z\n .string()\n .regex(/^\\//, 'an absolute path')\n .refine((path) => !/(^|\\/)\\.{1,2}(\\/|$)/.test(path), 'a path with no `.` or `..` segment');\n\n/** Where the platform image keeps apps-manager itself: a mount here (or over `/`) would hide the service it serves. */\nconst PLATFORM_IMAGE_APPLICATION_ROOT = '/app';\n\n/**\n * One file or directory of the HSM vendor's PKCS#11 client, mounted READ-ONLY into apps-manager's container (#3019): the\n * module, its configuration, the client certificates. `hostPath` is on the docker host (compose) or on every node that\n * may run apps-manager (Kubernetes, a `hostPath` volume); `containerPath` is where apps-manager sees it.\n */\nexport const PlatformKeyPkcs11ClientFileSchema = z.strictObject({\n hostPath: AbsoluteNormalPathSchema,\n containerPath: AbsoluteNormalPathSchema.refine(\n (path) => path !== '/' && path.replace(/\\/+$/, '') !== PLATFORM_IMAGE_APPLICATION_ROOT && !path.startsWith(`${PLATFORM_IMAGE_APPLICATION_ROOT}/`),\n `a path outside \\`/\\` and \\`${PLATFORM_IMAGE_APPLICATION_ROOT}\\` (the platform image keeps apps-manager there)`,\n ),\n});\nexport type PlatformKeyPkcs11ClientFile = z.infer<typeof PlatformKeyPkcs11ClientFileSchema>;\n\n/**\n * A dedicated HSM reached over PKCS#11 (#2934): Thales Luna, Entrust nShield, AWS CloudHSM, Azure Cloud HSM, an\n * on-premises appliance, or SoftHSM2. apps-manager loads the vendor's PKCS#11 module, logs in to one token with a user PIN\n * (operator-typed in `secrets.json` under `platformKeyPkcs11: { pin }`, never here) and serves the `pkcs11` provider.\n *\n * Protection is read from the token, not declared: a key counts as HARDWARE only when the slot reports a hardware slot\n * AND the token's model is listed in `hardwareTokenModels`, which is your statement that this model is the hardware you\n * run. SoftHSM2 is always SOFTWARE. The binding (`pkcs11js`) is compiled by `pnpm setup:pkcs11`; an apps-manager that\n * cannot load it says so at boot and refuses every signature on this provider.\n *\n * ## A real HSM in a containerised platform (#3019)\n *\n * The platform image carries only SoftHSM2. A real HSM's client comes from the host, and every vendor documents the same\n * containerised shape: mount the client library and its configuration READ-ONLY, and point the client at its\n * configuration with the vendor's own variable. So:\n * - `clientFiles` lists what to mount, each `{ hostPath, containerPath }`. compose renders a read-only bind mount and refuses\n * to start the service when the host path is missing; Kubernetes renders a read-only `hostPath` volume, which it mounts\n * unchecked, so the files must exist on every node that may run apps-manager (a missing one shows as a token that cannot\n * be opened, logged at boot). Both apps-manager services get them (INIT and serving).\n * - `environment` carries the vendor's variables (`ChrystokiConfigurationPath` for a Thales Luna client, …). It is\n * rendered in plain text beside the service, so it may hold paths and settings, never a credential; it may not name a\n * variable Wildo sets itself. The token PIN stays in `secrets.json`.\n * - In a container, `modulePath` must be the bundled SoftHSM2 or lie under a `containerPath`. Declaring `clientFiles` says\n * apps-manager runs in a container, so that is refused here; without `clientFiles` it is refused when compose or\n * Kubernetes renders apps-manager, because a framework developer's NATIVE apps-manager loads a host path legitimately\n * (Homebrew's SoftHSM2, `/opt/homebrew/lib/softhsm/libsofthsm2.so`).\n * - Both are for the CONTAINER lanes. A framework developer's native apps-manager runs on the host, where the client is\n * installed and configured as the vendor documents, and receives neither.\n *\n * Example, a Thales Luna client installed under `/usr/safenet/lunaclient` on the host:\n * `{ modulePath: '/usr/safenet/lunaclient/lib/libCryptoki2_64.so', tokenLabel: 'wildo', hardwareTokenModels: ['Luna K7'],\n * clientFiles: [{ hostPath: '/usr/safenet/lunaclient', containerPath: '/usr/safenet/lunaclient' },\n * { hostPath: '/etc/Chrystoki.conf', containerPath: '/etc/Chrystoki.conf' }],\n * environment: { ChrystokiConfigurationPath: '/etc' } }`.\n */\nexport const PlatformKeyPkcs11ConfigSchema = z\n .strictObject({\n /**\n * The vendor's PKCS#11 module, as an absolute path in apps-manager's filesystem: in the platform image, the bundled\n * `/usr/lib/softhsm/libsofthsm2.so` or a path under a `clientFiles[].containerPath`.\n */\n modulePath: z.string().regex(/^\\//, 'an absolute path'),\n /** The token's label, as the module reports it. */\n tokenLabel: z.string().min(1).max(32),\n /** Token models (`CK_TOKEN_INFO.model`) you state are hardware. Empty: every key reports SOFTWARE. */\n hardwareTokenModels: z.array(z.string().min(1)).default([]),\n /** The vendor client's files, mounted read-only into apps-manager's container (#3019). */\n clientFiles: z.array(PlatformKeyPkcs11ClientFileSchema).optional(),\n /** The vendor client's own environment variables (no credential, and no variable Wildo sets). */\n environment: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/, 'an environment variable name'), z.string()).optional(),\n })\n .superRefine((pkcs11, context) => {\n const containerPaths = (pkcs11.clientFiles ?? []).map((file) => file.containerPath.replace(/\\/+$/, ''));\n containerPaths.forEach((containerPath, index) => {\n if (containerPaths.indexOf(containerPath) !== index) {\n context.addIssue({ code: 'custom', path: ['clientFiles', index, 'containerPath'], message: `\"${containerPath}\" is mounted twice` });\n }\n });\n for (const name of Object.keys(pkcs11.environment ?? {})) {\n if (WILDO_OWNED_PLATFORM_ENV_KEYS.has(name)) {\n context.addIssue({ code: 'custom', path: ['environment', name], message: `\"${name}\" is a variable Wildo sets on apps-manager itself` });\n }\n }\n if (containerPaths.length > 0 && !pkcs11ModuleIsReachableInPlatformContainer(pkcs11)) {\n context.addIssue({ code: 'custom', path: ['modulePath'], message: describeUnreachablePkcs11Module(pkcs11) });\n }\n });\nexport type PlatformKeyPkcs11Config = z.infer<typeof PlatformKeyPkcs11ConfigSchema>;\n\nexport const WildoPlatformKeyManagementConfigSchema = z.strictObject({\n vault: PlatformKeyVaultConfigSchema.optional(),\n awsKms: PlatformKeyAwsKmsConfigSchema.optional(),\n googleCloudKms: PlatformKeyGoogleCloudKmsConfigSchema.optional(),\n azureKeyVault: PlatformKeyAzureKeyVaultConfigSchema.optional(),\n pkcs11: PlatformKeyPkcs11ConfigSchema.optional(),\n});\nexport type WildoPlatformKeyManagementConfig = z.infer<typeof WildoPlatformKeyManagementConfigSchema>;\n\n/** @wildo_source:part:end platform.config.platform-key-management */\n\n/** What deciding a module's reachability needs: the module, and where the client files are mounted. */\nexport interface Pkcs11ModuleMountView {\n readonly modulePath: string;\n readonly clientFiles?: readonly { readonly containerPath: string }[];\n}\n\n/**\n * Every environment variable Wildo itself sets on a platform process. A vendor `environment` entry may name none of them:\n * it would overwrite the platform's own value (a PIN, a connection string, the service's mode), and the vendor block is\n * rendered in plain text beside the service, never into a Secret.\n */\nconst WILDO_OWNED_PLATFORM_ENV_KEYS: ReadonlySet<string> = new Set<string>([\n ...[\n PlatformProcessEnvKey, PlatformServiceUrlEnvKey, PlatformInfrastructureEnvKey, PlatformSecurityEnvKey, PlatformAdminEnvKey,\n PlatformKubernetesEnvKey, PlatformIngressEnvKey, PlatformLoggingEnvKey, PlatformObservabilityEnvKey, PlatformProviderSelectionEnvKey,\n PlatformEmailEnvKey, PlatformOwnershipDnsEnvKey, PlatformDocumentationSiteEnvKey,\n ].flatMap((vocabulary) => Object.values(vocabulary) as string[]),\n // An application runtime's guardrail posture (`WildoInfraEnvConfig.agentContentGuardrails`), named by saas-models.\n AGENT_CONTENT_GUARDRAILS_ENV_VAR,\n // Set literally by the deployment templates rather than through the env contract.\n 'PLATFORM_SERVICE', 'NODE_OPTIONS', 'NODE_ENV',\n]);\n\n/**\n * Whether apps-manager, running in the PLATFORM IMAGE, can load `modulePath`: it is the bundled SoftHSM2, or it lies at or\n * under one of the declared `clientFiles[].containerPath`. Nothing else exists in that container.\n */\nexport function pkcs11ModuleIsReachableInPlatformContainer(pkcs11: Pkcs11ModuleMountView): boolean {\n if (pkcs11.modulePath === PLATFORM_IMAGE_BUNDLED_PKCS11_MODULE_PATH) return true;\n return (pkcs11.clientFiles ?? []).some(({ containerPath }) => {\n const mountRoot = containerPath.replace(/\\/+$/, '');\n return pkcs11.modulePath === mountRoot || pkcs11.modulePath.startsWith(`${mountRoot}/`);\n });\n}\n\n/** The refusal both container lanes (compose, Kubernetes) raise for an unreachable module, naming the declaration. */\nexport function describeUnreachablePkcs11Module(pkcs11: Pkcs11ModuleMountView, environmentName?: string): string {\n const mounts = (pkcs11.clientFiles ?? []).map((file) => file.containerPath);\n return `${environmentName ? `Environment \"${environmentName}\": ` : ''}platformKeyManagement.pkcs11.modulePath \"${pkcs11.modulePath}\" `\n + `is not the SoftHSM2 module the platform image carries (${PLATFORM_IMAGE_BUNDLED_PKCS11_MODULE_PATH}) and lies under no `\n + `platformKeyManagement.pkcs11.clientFiles[].containerPath (${mounts.length > 0 ? mounts.join(', ') : 'none declared'}). `\n + 'apps-manager runs in the platform image, where nothing else exists: declare the vendor\\'s module (and its configuration) '\n + 'in clientFiles as { hostPath, containerPath } and point modulePath inside one of them.';\n}\n\n/** Whether the platform runs its own Vault (OpenBao) in this environment: the one predicate both lanes render from. */\nexport function selfHostsPlatformKeyVault(platformKeyManagement: WildoPlatformKeyManagementConfig | undefined): boolean {\n return platformKeyManagement?.vault?.source === BackingServiceSource.SELF;\n}\n"]}
|