@wildo-ai/platform-infra-providers 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/postgres-self/postgres-self.infra.module.d.ts.map +1 -1
- package/dist/esm/postgres-self/postgres-self.infra.module.js +12 -1
- package/dist/esm/postgres-self/postgres-self.infra.module.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +3 -3
- package/src/postgres-self/__tests__/postgres-self.infra.module.test.ts +23 -1
- package/src/postgres-self/postgres-self.infra.module.ts +14 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-self.infra.module.d.ts","sourceRoot":"","sources":["../../../src/postgres-self/postgres-self.infra.module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmEG;AAEH,OAAO,EAOL,mBAAmB,
|
|
1
|
+
{"version":3,"file":"postgres-self.infra.module.d.ts","sourceRoot":"","sources":["../../../src/postgres-self/postgres-self.infra.module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmEG;AAEH,OAAO,EAOL,mBAAmB,EAQpB,MAAM,+BAA+B,CAAC;AA6HvC,eAAO,MAAM,+BAA+B,EAAE,mBA4M7C,CAAC"}
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
* so it is disabled (`NOLOGIN`, null password, sessions terminated) and the
|
|
67
67
|
* database is kept. Neither path destroys data — that is #1562.
|
|
68
68
|
*/
|
|
69
|
-
import { InfraCapability, InfraPlatformAdminConsumer, InfraProvider, ApplicationRuntimePrincipalKind, deriveMinionDatabaseGrants, resolveGrantStorageNames, } from '@wildo-ai/platform-config-lib';
|
|
69
|
+
import { InfraCapability, InfraPlatformAdminConsumer, InfraProvider, ApplicationRuntimePrincipalKind, deriveMinionDatabaseGrants, deriveMinionDatabaseQueueConfinement, resolveGrantStorageNames, } from '@wildo-ai/platform-config-lib';
|
|
70
70
|
/**
|
|
71
71
|
* Default Postgres port (matches `INFRA_DEFAULT_PORTS.POSTGRES` in
|
|
72
72
|
* the shared platform constants — duplicated as a literal because
|
|
@@ -255,6 +255,16 @@ export const PostgresSelfInfraProviderModule = {
|
|
|
255
255
|
// the shared derivation so this adapter and the Mongo one cannot disagree
|
|
256
256
|
// about what that floor is.
|
|
257
257
|
const databaseGrants = deriveMinionDatabaseGrants(grants);
|
|
258
|
+
// #2303: a MINION reaches the DATABASE queue's table, confined by row-level security to its own queues. Granted
|
|
259
|
+
// under every service profile, because a profile is not the role's to know. Under `full` the table is unused, so the
|
|
260
|
+
// only reach this adds there is publishing into an empty queue nobody consumes, and reading its own (empty) queues.
|
|
261
|
+
// Only minions: no other named principal consumes that queue.
|
|
262
|
+
const rowConfinedTables = [];
|
|
263
|
+
if (context.principal.kind === ApplicationRuntimePrincipalKind.MINION) {
|
|
264
|
+
const queue = deriveMinionDatabaseQueueConfinement(context.wildoApplicationId, context.principal.name ?? '');
|
|
265
|
+
const [table] = resolveGrantStorageNames([queue.resourceType]);
|
|
266
|
+
rowConfinedTables.push({ table, column: queue.field, rowsReachable: queue.rowsReachable });
|
|
267
|
+
}
|
|
258
268
|
const { connectionUrl: principalConnectionUrl } = await adminClient.upsertTableScopedDatabaseRole({
|
|
259
269
|
databaseName,
|
|
260
270
|
username,
|
|
@@ -270,6 +280,7 @@ export const PostgresSelfInfraProviderModule = {
|
|
|
270
280
|
writeTables: resolveGrantStorageNames(databaseGrants.write),
|
|
271
281
|
appendTables: resolveGrantStorageNames(databaseGrants.append),
|
|
272
282
|
maintainTables: resolveGrantStorageNames(databaseGrants.maintain),
|
|
283
|
+
rowConfinedTables,
|
|
273
284
|
});
|
|
274
285
|
return {
|
|
275
286
|
secretBlobValues: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-self.infra.module.js","sourceRoot":"","sources":["../../../src/postgres-self/postgres-self.infra.module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmEG;AAEH,OAAO,EAIL,eAAe,EACf,0BAA0B,EAC1B,aAAa,EAIb,+BAA+B,EAC/B,0BAA0B,EAC1B,wBAAwB,GACzB,MAAM,+BAA+B,CAAC;AAEvC;;;;;GAKG;AACH,MAAM,qBAAqB,GAAG,IAAI,CAAC;AAEnC;;;;;;;;;;;GAWG;AACH,MAAM,2BAA2B,GAAG,kCAAkC,CAAC;AACvE,MAAM,sBAAsB,GAAG,8BAA8B,CAAC;AAC9D,MAAM,yBAAyB,GAAG,gCAAgC,CAAC;AACnE;;;;;;;GAOG;AACH,MAAM,+BAA+B,GAA0B;IAC7D,2BAA2B;IAC3B,sBAAsB;IACtB,yBAAyB;CAC1B,CAAC;AAGF;;;GAGG;AACH,MAAM,2BAA2B,GAAG,8BAA8B,CAAC;AAEnE;;;;GAIG;AACH,MAAM,gCAAgC,GAAG,cAAc,CAAC;AAExD;;;;;;;;;;;;;GAaG;AACH,SAAS,mBAAmB,CAAC,KAAa;IACxC,OAAO,KAAK;SACT,WAAW,EAAE;SACb,OAAO,CAAC,aAAa,EAAE,GAAG,CAAC;SAC3B,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC;SACrB,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AACtB,CAAC;AAED;;;;GAIG;AACH,SAAS,iBAAiB,CAAC,OAAe;IACxC,OAAO,SAAS,mBAAmB,CAAC,OAAO,CAAC,EAAE,CAAC;AACjD,CAAC;AAED;;;;GAIG;AACH,SAAS,aAAa,CAAC,OAAe;IACpC,OAAO,SAAS,mBAAmB,CAAC,OAAO,CAAC,OAAO,CAAC;AACtD,CAAC;AAED;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;QAC7D,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CACb,wDAAwD;gBACxD,oBAAoB;gBACpB,gDAAgD,CACjD,CAAC;QACJ,CAAC;QACD,MAAM,WAAW,GAAG,OAAO,CAAC,WAAmC,CAAC;QAChE,MAAM,QAAQ,GAAG,8BAA8B,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;QAEpF,IAAI,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,SAAS,CAAC,IAAI,KAAK,+BAA+B,CAAC,mBAAmB,EAAE,CAAC;YACxG,MAAM,YAAY,GAChB,OAAO,CAAC,uBAAuB,EAAE,CAAC,gCAAgC,CAAC;mBAChE,iBAAiB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YACxC,sEAAsE;YACtE,yEAAyE;YACzE,mEAAmE;YACnE,iDAAiD;YACjD,MAAM,WAAW,CAAC,2BAA2B,CAAC;gBAC5C,YAAY;gBACZ,QAAQ;gBACR,UAAU,EAAE,2BAA2B;aACxC,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QAED;;;;;;;;;WASG;QACH,MAAM,WAAW,CAAC,8BAA8B,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;IACjE,CAAC;IAED,0DAA0D;IAC1D,qDAAqD;CACtD,CAAC","sourcesContent":["/**\n * `PostgresSelfInfraProviderModule` — third concrete `InfraProviderModule`\n * (generalizing the RabbitMQ / Redis module pattern).\n *\n * Implements the `POSTGRES_SELF` `InfraProvider` over the\n * `IPostgresAdminClient` transport (raw `pg` Pool against the\n * Postgres admin connection, exposed by\n * `PostgreSQLConnectionManagerService` after the Slice 4.B.2 5C\n * policy/transport split). Owns ALL per-app naming policy — the\n * per-app database-name + role-name conventions (`wildo_<sanitized>_user`,\n * `wildo_<sanitized>` mirroring the legacy\n * `PlatformInfrastructureManagerService.provisionPostgreSQLDatabase`).\n *\n * **What this module reads from `AppCredentialMintingContext`**:\n * - `appSlug` — used as the source for the sanitized database +\n * user name. Mirrors the legacy convention at\n * `platform-infrastructure-manager.service.ts:300-302`\n * (`sanitizedName = sanitizeForPostgreSQL(applicationName)`,\n * `databaseName = wildo_${sanitizedName}`,\n * `username = wildo_${sanitizedName}_user`).\n * - `secretInputs['database.postgresql.password']` — orchestrator-\n * supplied password (module is upsert-only, never generator).\n * - `applicationConfigInputs?.['databaseName']` — optional override\n * for the derived database name. Mirrors the legacy\n * `provisionPostgreSQLDatabase(appSlug, { databaseName? })` arg.\n * - `adminClient` — narrowed to `IPostgresAdminClient`.\n *\n * **What this module IGNORES from the context** (Slice 4.A.2 / M4\n * forward-compat documentation):\n * - `applicationNamespace` — Postgres per-app DB names use the\n * slug-derived sanitized form (env-suffix isolation comes from\n * the surrounding env-scoped admin connection). Future modules\n * may switch to namespace-scoped naming if cross-env collision\n * risk surfaces.\n * - `wildoApplicationId` — Postgres role names embed the\n * sanitized slug, NOT the application id. This is the legacy\n * convention; preserved for back-compat with apps already\n * provisioned.\n *\n * **Two audiences this module serves:**\n *\n * 1. **Audience-1 (platform-admin, declared via `plan().platformAdmin`)**:\n * cluster-wide Postgres admin creds. Consumers: `apps-manager`\n * (mints per-app DB+role via `mintAppCredentials`), `companion`\n * (mirrors apps-manager admin role for local dev).\n *\n * 2. **Audience-3 (app-scoped, via `plan().appRuntime` +\n * `mintAppCredentials`)**: per-customer-app Postgres database +\n * role. Result threaded into\n * `Wildo_Application_Secrets.database.postgresql.{\n * databaseName, username, connectUrl}` via\n * `_merge_WildoApplicationSecrets`. Note: the password is\n * embedded in `connectUrl` — there is no separate\n * `database.postgresql.password` blob path today (matches the\n * legacy persistence shape at\n * `wildo-application-lifecycle.service.ts:2191-2200`).\n *\n * **NOT served (D-4 of Slice 4.B locked decisions, 2026-05-10)**:\n * - **Audience-2 (platform-service-scoped)**: no platform service\n * uses Postgres for inter-service messaging today. Method omitted.\n *\n * **`revokeAppCredentials`** is called by apps-manager runtime-principal\n * declaration reconciliation when a minion is removed, and for every principal\n * of an application withdrawn from the platform (#1307). A minion's role is\n * DROPPED (it owns nothing); the application backend's role OWNS the database,\n * so it is disabled (`NOLOGIN`, null password, sessions terminated) and the\n * database is kept. Neither path destroys data — that is #1562.\n */\n\nimport {\n AppCredentialMintingContext,\n AppCredentialMintingResult,\n IPostgresAdminClient,\n InfraCapability,\n InfraPlatformAdminConsumer,\n InfraProvider,\n InfraProviderModule,\n InfraProviderPlanContribution,\n ApplicationRuntimePrincipal,\n ApplicationRuntimePrincipalKind,\n deriveMinionDatabaseGrants,\n resolveGrantStorageNames,\n} from '@wildo-ai/platform-config-lib';\n\n/**\n * Default Postgres port (matches `INFRA_DEFAULT_PORTS.POSTGRES` in\n * the shared platform constants — duplicated as a literal because\n * the planner output is consumed by the CLI which materializes it\n * into `Wildo_Application_Config` blob paths).\n */\nconst DEFAULT_POSTGRES_PORT = 5432;\n\n/**\n * The `Wildo_Application_Secrets` JSON paths this module writes\n * through `mintAppCredentials`. Declared once and reused as\n * `appRuntime.perAppSecretBlobPaths` in `plan()` AND as the keys of\n * `secretBlobValues` in the result, so a refactor that renames a\n * path fails loudly at one place.\n *\n * Note: the password is embedded in `connectUrl` (Postgres\n * convention); there is no separate `database.postgresql.password`\n * blob path today. The orchestrator persists `connectUrl`\n * verbatim into `Wildo_Application_Secrets`.\n */\nconst POSTGRES_DATABASE_NAME_PATH = 'database.postgresql.databaseName';\nconst POSTGRES_USERNAME_PATH = 'database.postgresql.username';\nconst POSTGRES_CONNECT_URL_PATH = 'database.postgresql.connectUrl';\n/**\n * The paths this module mints PER RUNTIME PRINCIPAL — the single source for both consumers.\n *\n * Read by `InfraProviderModule.perPrincipalSecretBlobPaths` (statically, so apps-manager can strip\n * these from the application blob before delivering a principal's own material) AND spread into\n * `appRuntime.perAppSecretBlobPaths` inside `plan()`. Declaring the list twice is how the delivery\n * path would silently stop covering a path this module still mints.\n */\nconst PER_PRINCIPAL_SECRET_BLOB_PATHS: ReadonlyArray<string> = [\n POSTGRES_DATABASE_NAME_PATH,\n POSTGRES_USERNAME_PATH,\n POSTGRES_CONNECT_URL_PATH,\n];\n\n\n/**\n * Key the module looks for in `secretInputs` to read the\n * orchestrator-supplied password.\n */\nconst POSTGRES_PASSWORD_INPUT_KEY = 'database.postgresql.password';\n\n/**\n * Optional key the module looks for in `applicationConfigInputs`\n * for an authored database-name override. When omitted, the module\n * derives the database name from `appSlug` via `sanitizeForPostgreSQL`.\n */\nconst POSTGRES_DATABASE_NAME_INPUT_KEY = 'databaseName';\n\n/**\n * Sanitize an application slug for Postgres identifier rules.\n * Mirrors the legacy `sanitizeForPostgreSQL` at\n * `platform-infrastructure-manager.service.ts:371-378`:\n * - lowercase\n * - `[^a-z0-9_]` → `_`\n * - collapse multiple `_`\n * - strip leading/trailing `_`\n * - cap at 50 chars (Postgres identifier limit is 63; leaves room\n * for the `wildo_` prefix and `_user` suffix).\n *\n * Centralized here so the module owns the convention; if the cap\n * or escape rules change, one site changes.\n */\nfunction sanitizeForPostgres(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9_]/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '')\n .substring(0, 50);\n}\n\n/**\n * Compute the per-app database name. Mirrors legacy convention at\n * `platform-infrastructure-manager.service.ts:301`:\n * `wildo_<sanitized>`\n */\nfunction buildDatabaseName(appSlug: string): string {\n return `wildo_${sanitizeForPostgres(appSlug)}`;\n}\n\n/**\n * Compute the per-app database role. Mirrors legacy convention at\n * `platform-infrastructure-manager.service.ts:302`:\n * `wildo_<sanitized>_user`\n */\nfunction buildUsername(appSlug: string): string {\n return `wildo_${sanitizeForPostgres(appSlug)}_user`;\n}\n\n/**\n * The schema a per-app database's resource tables live in.\n *\n * `public` is what the schema planner targets today. Named as a constant rather\n * than inlined at the four sites that need it because a grant issued into one\n * schema and revoked from another is a revocation that silently succeeds while\n * narrowing nothing.\n */\nconst POSTGRES_APPLICATION_SCHEMA = 'public';\n\n/**\n * Per-principal Postgres role name — the SAME derivation the revoke path uses.\n *\n * Fourth time this shape appears (Redis, RabbitMQ, Mongo, now Postgres), and the\n * consequence is worse here than anywhere else: a revoke that derived the name\n * differently would miss the minion's role AND, on the pre-existing\n * `dropApplicationDatabase` path, take the application's entire database with\n * it. The application backend keeps `wildo_<slug>_user` VERBATIM so an existing\n * deployment's owner role is never orphaned.\n */\nfunction buildPostgresPrincipalUsername(\n appSlug: string,\n principal: ApplicationRuntimePrincipal | undefined,\n): string {\n if (!principal || principal.kind === ApplicationRuntimePrincipalKind.APPLICATION_BACKEND) {\n return buildUsername(appSlug);\n }\n return `wildo_${sanitizeForPostgres(appSlug)}_${sanitizeForPostgres(principal.kind)}_`\n + `${sanitizeForPostgres(principal.name ?? '')}_user`;\n}\n\nexport const PostgresSelfInfraProviderModule: InfraProviderModule = {\n provider: InfraProvider.POSTGRES_SELF,\n supportedCapabilities: [InfraCapability.RELATIONAL_DATABASE],\n perPrincipalSecretBlobPaths: PER_PRINCIPAL_SECRET_BLOB_PATHS,\n\n plan(): InfraProviderPlanContribution {\n return {\n dockerComposeServices: ['postgres'],\n k8sResources: ['templates/infra/k8s/internal/postgres/deployment.yaml.hbs'],\n platformAdmin: {\n envVars: {\n PG_HOST: 'postgres',\n PG_PORT: String(DEFAULT_POSTGRES_PORT),\n },\n // Admin user + password to provision per-app DBs/roles. The\n // legacy admin-init code reads these from `PG_ADMIN_USER` /\n // `PG_ADMIN_PASSWORD`; the planner emits the keys, the\n // CLI's `env-vars-builder` writes the values at sync time.\n secretEnvVars: ['PG_ADMIN_USER', 'PG_ADMIN_PASSWORD'],\n // Audience-1 only (DB-admin access). No audience-2\n // platform-service-scoped Postgres use case today (D-4).\n consumers: [\n InfraPlatformAdminConsumer.APPS_MANAGER,\n InfraPlatformAdminConsumer.COMPANION,\n ],\n },\n appRuntime: {\n // Static topology — same for every app in this env. The\n // per-app values (databaseName, username, connectUrl) flow\n // through `perAppSecretBlobPaths`.\n perAppConfigBlobPaths: {\n 'database.postgresql.host': 'postgres',\n 'database.postgresql.port': DEFAULT_POSTGRES_PORT,\n },\n perAppSecretBlobPaths: [...PER_PRINCIPAL_SECRET_BLOB_PATHS],\n },\n };\n },\n\n async mintAppCredentials(\n context: AppCredentialMintingContext,\n ): Promise<AppCredentialMintingResult> {\n const adminClient = context.adminClient as IPostgresAdminClient;\n const password = context.secretInputs[POSTGRES_PASSWORD_INPUT_KEY];\n if (!password) {\n throw new Error(\n `PostgresSelfInfraProviderModule.mintAppCredentials: ` +\n `secretInputs is missing '${POSTGRES_PASSWORD_INPUT_KEY}'. ` +\n `The orchestrator MUST supply the Postgres password — modules are upsert-only.`,\n );\n }\n if (!context.appSlug) {\n throw new Error(\n `PostgresSelfInfraProviderModule.mintAppCredentials: ` +\n `appSlug is empty. ` +\n `The orchestrator MUST supply a non-empty slug.`,\n );\n }\n\n // Allow operator override of the derived database name. Without\n // an override, derive from `appSlug` via the legacy convention.\n const databaseName =\n context.applicationConfigInputs?.[POSTGRES_DATABASE_NAME_INPUT_KEY]\n || buildDatabaseName(context.appSlug);\n const username = buildPostgresPrincipalUsername(context.appSlug, context.principal);\n\n if (context.principal && context.principal.kind !== ApplicationRuntimePrincipalKind.APPLICATION_BACKEND) {\n // A named principal gets a TABLE-SCOPED role (Step 3 / R1 / D14): exactly\n // the authored business verbs plus the mandatory runtime floor, inside\n // a database it does not own.\n //\n // `resourceGrants` is REQUIRED and its absence is an error rather than a\n // default. Falling through to `upsertApplicationDatabase` would make the\n // minion the OWNER of the application's database with `ALL PRIVILEGES` —\n // the exact over-grant this path replaces, arriving silently through a\n // code path that reads as if it were doing the narrow thing.\n const grants = context.resourceGrants;\n if (!grants) {\n throw new Error(\n `PostgresSelfInfraProviderModule.mintAppCredentials: `\n + `principal '${context.principal.kind}:${context.principal.name}' has no resourceGrants. `\n + `Refusing to fall back to the database-wide application role. The orchestrator must pass `\n + `an explicit empty resource grant when only the mandatory runtime floor is required.`,\n );\n }\n // The authored declaration plus the engine's own floor — the reads and\n // appends the framework performs for ANY principal, which no\n // `resourceAccess` can express and none should have to. Applied through\n // the shared derivation so this adapter and the Mongo one cannot disagree\n // about what that floor is.\n const databaseGrants = deriveMinionDatabaseGrants(grants);\n\n const { connectionUrl: principalConnectionUrl } = await adminClient.upsertTableScopedDatabaseRole({\n databaseName,\n username,\n password,\n schemaName: POSTGRES_APPLICATION_SCHEMA,\n // Resource types → table names HERE, at the adapter that speaks\n // Postgres. The grant contract itself stays in the platform vocabulary,\n // and passes through the SAME translation Mongo uses, so the two\n // adapters cannot disagree about which rows a resource type addresses.\n // SQL identifier casing is applied by the manager, which is the one site\n // that issues the DDL and runs the existence check those names must match.\n readTables: resolveGrantStorageNames(databaseGrants.read),\n writeTables: resolveGrantStorageNames(databaseGrants.write),\n appendTables: resolveGrantStorageNames(databaseGrants.append),\n maintainTables: resolveGrantStorageNames(databaseGrants.maintain),\n });\n\n return {\n secretBlobValues: {\n [POSTGRES_DATABASE_NAME_PATH]: databaseName,\n [POSTGRES_USERNAME_PATH]: username,\n [POSTGRES_CONNECT_URL_PATH]: principalConnectionUrl,\n },\n };\n }\n\n // CREATE/ALTER USER + CREATE DATABASE — idempotent upsert. The\n // admin-client reapplies privileges every time so the call is\n // safe to repeat.\n const { connectionUrl } = await adminClient.upsertApplicationDatabase({\n databaseName,\n username,\n password,\n });\n\n return {\n secretBlobValues: {\n [POSTGRES_DATABASE_NAME_PATH]: databaseName,\n [POSTGRES_USERNAME_PATH]: username,\n [POSTGRES_CONNECT_URL_PATH]: connectionUrl,\n },\n };\n },\n\n /**\n * Revoke a principal's PostgreSQL credential — and destroy no data (#1307). A minion's\n * table-scoped role is dropped (it owns nothing); the application backend's role OWNS the\n * database, so its login is disabled and the role, its ownership and every row are kept.\n * Idempotent: the admin client treats a missing role as a no-op.\n *\n * **Caller status**: apps-manager runtime-principal declaration reconciliation calls this for\n * removed minions, and application withdrawal (`deregisterApplication`) for the backend and every\n * minion; `restoreApplication` re-mints them. Destroying the database is #1562's separate door.\n *\n * **Defensive validation** (Slice 4.A.2 / L4 pattern): empty\n * `appSlug` would derive an empty database name; we fail-loud\n * instead so a bad caller surfaces immediately.\n */\n async revokeAppCredentials(context: AppCredentialMintingContext): Promise<void> {\n if (!context.appSlug) {\n throw new Error(\n `PostgresSelfInfraProviderModule.revokeAppCredentials: ` +\n `appSlug is empty. ` +\n `The orchestrator MUST supply a non-empty slug.`,\n );\n }\n const adminClient = context.adminClient as IPostgresAdminClient;\n const username = buildPostgresPrincipalUsername(context.appSlug, context.principal);\n\n if (context.principal && context.principal.kind !== ApplicationRuntimePrincipalKind.APPLICATION_BACKEND) {\n const databaseName =\n context.applicationConfigInputs?.[POSTGRES_DATABASE_NAME_INPUT_KEY]\n || buildDatabaseName(context.appSlug);\n // A named principal owns NOTHING but its own role. Routing it through\n // `dropApplicationDatabase` — which is what this method did before named\n // principals existed — would DROP THE APPLICATION'S DATABASE while\n // believing it was retiring one minion's access.\n await adminClient.dropTableScopedDatabaseRole({\n databaseName,\n username,\n schemaName: POSTGRES_APPLICATION_SCHEMA,\n });\n return;\n }\n\n /*\n * The APPLICATION BACKEND's role OWNS the application database, so revoking it disables the LOGIN\n * and keeps the role, its ownership and every row (#1307).\n *\n * This branch used to call `dropApplicationDatabase` — the database AND the role. Nothing called it\n * for the backend until deregistration did, and deregistration is a REVERSIBLE withdrawal: `restore`\n * re-mints the recorded credential and the application boots on the data it left. A revocation that\n * dropped the database would have turned every withdrawal into the irreversible destruction #1562\n * parks behind its own door. Revocation removes authentication; it never removes data.\n */\n await adminClient.revokeApplicationDatabaseLogin({ username });\n },\n\n // No `mintPlatformServiceCredentials` (D-4 of Slice 4.B —\n // audience-2 not applicable to Postgres_Self today).\n};\n"]}
|
|
1
|
+
{"version":3,"file":"postgres-self.infra.module.js","sourceRoot":"","sources":["../../../src/postgres-self/postgres-self.infra.module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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D;IAC1D,qDAAqD;CACtD,CAAC","sourcesContent":["/**\n * `PostgresSelfInfraProviderModule` — third concrete `InfraProviderModule`\n * (generalizing the RabbitMQ / Redis module pattern).\n *\n * Implements the `POSTGRES_SELF` `InfraProvider` over the\n * `IPostgresAdminClient` transport (raw `pg` Pool against the\n * Postgres admin connection, exposed by\n * `PostgreSQLConnectionManagerService` after the Slice 4.B.2 5C\n * policy/transport split). Owns ALL per-app naming policy — the\n * per-app database-name + role-name conventions (`wildo_<sanitized>_user`,\n * `wildo_<sanitized>` mirroring the legacy\n * `PlatformInfrastructureManagerService.provisionPostgreSQLDatabase`).\n *\n * **What this module reads from `AppCredentialMintingContext`**:\n * - `appSlug` — used as the source for the sanitized database +\n * user name. Mirrors the legacy convention at\n * `platform-infrastructure-manager.service.ts:300-302`\n * (`sanitizedName = sanitizeForPostgreSQL(applicationName)`,\n * `databaseName = wildo_${sanitizedName}`,\n * `username = wildo_${sanitizedName}_user`).\n * - `secretInputs['database.postgresql.password']` — orchestrator-\n * supplied password (module is upsert-only, never generator).\n * - `applicationConfigInputs?.['databaseName']` — optional override\n * for the derived database name. Mirrors the legacy\n * `provisionPostgreSQLDatabase(appSlug, { databaseName? })` arg.\n * - `adminClient` — narrowed to `IPostgresAdminClient`.\n *\n * **What this module IGNORES from the context** (Slice 4.A.2 / M4\n * forward-compat documentation):\n * - `applicationNamespace` — Postgres per-app DB names use the\n * slug-derived sanitized form (env-suffix isolation comes from\n * the surrounding env-scoped admin connection). Future modules\n * may switch to namespace-scoped naming if cross-env collision\n * risk surfaces.\n * - `wildoApplicationId` — Postgres role names embed the\n * sanitized slug, NOT the application id. This is the legacy\n * convention; preserved for back-compat with apps already\n * provisioned.\n *\n * **Two audiences this module serves:**\n *\n * 1. **Audience-1 (platform-admin, declared via `plan().platformAdmin`)**:\n * cluster-wide Postgres admin creds. Consumers: `apps-manager`\n * (mints per-app DB+role via `mintAppCredentials`), `companion`\n * (mirrors apps-manager admin role for local dev).\n *\n * 2. **Audience-3 (app-scoped, via `plan().appRuntime` +\n * `mintAppCredentials`)**: per-customer-app Postgres database +\n * role. Result threaded into\n * `Wildo_Application_Secrets.database.postgresql.{\n * databaseName, username, connectUrl}` via\n * `_merge_WildoApplicationSecrets`. Note: the password is\n * embedded in `connectUrl` — there is no separate\n * `database.postgresql.password` blob path today (matches the\n * legacy persistence shape at\n * `wildo-application-lifecycle.service.ts:2191-2200`).\n *\n * **NOT served (D-4 of Slice 4.B locked decisions, 2026-05-10)**:\n * - **Audience-2 (platform-service-scoped)**: no platform service\n * uses Postgres for inter-service messaging today. Method omitted.\n *\n * **`revokeAppCredentials`** is called by apps-manager runtime-principal\n * declaration reconciliation when a minion is removed, and for every principal\n * of an application withdrawn from the platform (#1307). A minion's role is\n * DROPPED (it owns nothing); the application backend's role OWNS the database,\n * so it is disabled (`NOLOGIN`, null password, sessions terminated) and the\n * database is kept. Neither path destroys data — that is #1562.\n */\n\nimport {\n AppCredentialMintingContext,\n AppCredentialMintingResult,\n IPostgresAdminClient,\n InfraCapability,\n InfraPlatformAdminConsumer,\n InfraProvider,\n InfraProviderModule,\n InfraProviderPlanContribution,\n ApplicationRuntimePrincipal,\n ApplicationRuntimePrincipalKind,\n deriveMinionDatabaseGrants,\n deriveMinionDatabaseQueueConfinement,\n resolveGrantStorageNames,\n type PostgresRowConfinedTableGrant,\n} from '@wildo-ai/platform-config-lib';\n\n/**\n * Default Postgres port (matches `INFRA_DEFAULT_PORTS.POSTGRES` in\n * the shared platform constants — duplicated as a literal because\n * the planner output is consumed by the CLI which materializes it\n * into `Wildo_Application_Config` blob paths).\n */\nconst DEFAULT_POSTGRES_PORT = 5432;\n\n/**\n * The `Wildo_Application_Secrets` JSON paths this module writes\n * through `mintAppCredentials`. Declared once and reused as\n * `appRuntime.perAppSecretBlobPaths` in `plan()` AND as the keys of\n * `secretBlobValues` in the result, so a refactor that renames a\n * path fails loudly at one place.\n *\n * Note: the password is embedded in `connectUrl` (Postgres\n * convention); there is no separate `database.postgresql.password`\n * blob path today. The orchestrator persists `connectUrl`\n * verbatim into `Wildo_Application_Secrets`.\n */\nconst POSTGRES_DATABASE_NAME_PATH = 'database.postgresql.databaseName';\nconst POSTGRES_USERNAME_PATH = 'database.postgresql.username';\nconst POSTGRES_CONNECT_URL_PATH = 'database.postgresql.connectUrl';\n/**\n * The paths this module mints PER RUNTIME PRINCIPAL — the single source for both consumers.\n *\n * Read by `InfraProviderModule.perPrincipalSecretBlobPaths` (statically, so apps-manager can strip\n * these from the application blob before delivering a principal's own material) AND spread into\n * `appRuntime.perAppSecretBlobPaths` inside `plan()`. Declaring the list twice is how the delivery\n * path would silently stop covering a path this module still mints.\n */\nconst PER_PRINCIPAL_SECRET_BLOB_PATHS: ReadonlyArray<string> = [\n POSTGRES_DATABASE_NAME_PATH,\n POSTGRES_USERNAME_PATH,\n POSTGRES_CONNECT_URL_PATH,\n];\n\n\n/**\n * Key the module looks for in `secretInputs` to read the\n * orchestrator-supplied password.\n */\nconst POSTGRES_PASSWORD_INPUT_KEY = 'database.postgresql.password';\n\n/**\n * Optional key the module looks for in `applicationConfigInputs`\n * for an authored database-name override. When omitted, the module\n * derives the database name from `appSlug` via `sanitizeForPostgreSQL`.\n */\nconst POSTGRES_DATABASE_NAME_INPUT_KEY = 'databaseName';\n\n/**\n * Sanitize an application slug for Postgres identifier rules.\n * Mirrors the legacy `sanitizeForPostgreSQL` at\n * `platform-infrastructure-manager.service.ts:371-378`:\n * - lowercase\n * - `[^a-z0-9_]` → `_`\n * - collapse multiple `_`\n * - strip leading/trailing `_`\n * - cap at 50 chars (Postgres identifier limit is 63; leaves room\n * for the `wildo_` prefix and `_user` suffix).\n *\n * Centralized here so the module owns the convention; if the cap\n * or escape rules change, one site changes.\n */\nfunction sanitizeForPostgres(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9_]/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '')\n .substring(0, 50);\n}\n\n/**\n * Compute the per-app database name. Mirrors legacy convention at\n * `platform-infrastructure-manager.service.ts:301`:\n * `wildo_<sanitized>`\n */\nfunction buildDatabaseName(appSlug: string): string {\n return `wildo_${sanitizeForPostgres(appSlug)}`;\n}\n\n/**\n * Compute the per-app database role. Mirrors legacy convention at\n * `platform-infrastructure-manager.service.ts:302`:\n * `wildo_<sanitized>_user`\n */\nfunction buildUsername(appSlug: string): string {\n return `wildo_${sanitizeForPostgres(appSlug)}_user`;\n}\n\n/**\n * The schema a per-app database's resource tables live in.\n *\n * `public` is what the schema planner targets today. Named as a constant rather\n * than inlined at the four sites that need it because a grant issued into one\n * schema and revoked from another is a revocation that silently succeeds while\n * narrowing nothing.\n */\nconst POSTGRES_APPLICATION_SCHEMA = 'public';\n\n/**\n * Per-principal Postgres role name — the SAME derivation the revoke path uses.\n *\n * Fourth time this shape appears (Redis, RabbitMQ, Mongo, now Postgres), and the\n * consequence is worse here than anywhere else: a revoke that derived the name\n * differently would miss the minion's role AND, on the pre-existing\n * `dropApplicationDatabase` path, take the application's entire database with\n * it. The application backend keeps `wildo_<slug>_user` VERBATIM so an existing\n * deployment's owner role is never orphaned.\n */\nfunction buildPostgresPrincipalUsername(\n appSlug: string,\n principal: ApplicationRuntimePrincipal | undefined,\n): string {\n if (!principal || principal.kind === ApplicationRuntimePrincipalKind.APPLICATION_BACKEND) {\n return buildUsername(appSlug);\n }\n return `wildo_${sanitizeForPostgres(appSlug)}_${sanitizeForPostgres(principal.kind)}_`\n + `${sanitizeForPostgres(principal.name ?? '')}_user`;\n}\n\nexport const PostgresSelfInfraProviderModule: InfraProviderModule = {\n provider: InfraProvider.POSTGRES_SELF,\n supportedCapabilities: [InfraCapability.RELATIONAL_DATABASE],\n perPrincipalSecretBlobPaths: PER_PRINCIPAL_SECRET_BLOB_PATHS,\n\n plan(): InfraProviderPlanContribution {\n return {\n dockerComposeServices: ['postgres'],\n k8sResources: ['templates/infra/k8s/internal/postgres/deployment.yaml.hbs'],\n platformAdmin: {\n envVars: {\n PG_HOST: 'postgres',\n PG_PORT: String(DEFAULT_POSTGRES_PORT),\n },\n // Admin user + password to provision per-app DBs/roles. The\n // legacy admin-init code reads these from `PG_ADMIN_USER` /\n // `PG_ADMIN_PASSWORD`; the planner emits the keys, the\n // CLI's `env-vars-builder` writes the values at sync time.\n secretEnvVars: ['PG_ADMIN_USER', 'PG_ADMIN_PASSWORD'],\n // Audience-1 only (DB-admin access). No audience-2\n // platform-service-scoped Postgres use case today (D-4).\n consumers: [\n InfraPlatformAdminConsumer.APPS_MANAGER,\n InfraPlatformAdminConsumer.COMPANION,\n ],\n },\n appRuntime: {\n // Static topology — same for every app in this env. The\n // per-app values (databaseName, username, connectUrl) flow\n // through `perAppSecretBlobPaths`.\n perAppConfigBlobPaths: {\n 'database.postgresql.host': 'postgres',\n 'database.postgresql.port': DEFAULT_POSTGRES_PORT,\n },\n perAppSecretBlobPaths: [...PER_PRINCIPAL_SECRET_BLOB_PATHS],\n },\n };\n },\n\n async mintAppCredentials(\n context: AppCredentialMintingContext,\n ): Promise<AppCredentialMintingResult> {\n const adminClient = context.adminClient as IPostgresAdminClient;\n const password = context.secretInputs[POSTGRES_PASSWORD_INPUT_KEY];\n if (!password) {\n throw new Error(\n `PostgresSelfInfraProviderModule.mintAppCredentials: ` +\n `secretInputs is missing '${POSTGRES_PASSWORD_INPUT_KEY}'. ` +\n `The orchestrator MUST supply the Postgres password — modules are upsert-only.`,\n );\n }\n if (!context.appSlug) {\n throw new Error(\n `PostgresSelfInfraProviderModule.mintAppCredentials: ` +\n `appSlug is empty. ` +\n `The orchestrator MUST supply a non-empty slug.`,\n );\n }\n\n // Allow operator override of the derived database name. Without\n // an override, derive from `appSlug` via the legacy convention.\n const databaseName =\n context.applicationConfigInputs?.[POSTGRES_DATABASE_NAME_INPUT_KEY]\n || buildDatabaseName(context.appSlug);\n const username = buildPostgresPrincipalUsername(context.appSlug, context.principal);\n\n if (context.principal && context.principal.kind !== ApplicationRuntimePrincipalKind.APPLICATION_BACKEND) {\n // A named principal gets a TABLE-SCOPED role (Step 3 / R1 / D14): exactly\n // the authored business verbs plus the mandatory runtime floor, inside\n // a database it does not own.\n //\n // `resourceGrants` is REQUIRED and its absence is an error rather than a\n // default. Falling through to `upsertApplicationDatabase` would make the\n // minion the OWNER of the application's database with `ALL PRIVILEGES` —\n // the exact over-grant this path replaces, arriving silently through a\n // code path that reads as if it were doing the narrow thing.\n const grants = context.resourceGrants;\n if (!grants) {\n throw new Error(\n `PostgresSelfInfraProviderModule.mintAppCredentials: `\n + `principal '${context.principal.kind}:${context.principal.name}' has no resourceGrants. `\n + `Refusing to fall back to the database-wide application role. The orchestrator must pass `\n + `an explicit empty resource grant when only the mandatory runtime floor is required.`,\n );\n }\n // The authored declaration plus the engine's own floor — the reads and\n // appends the framework performs for ANY principal, which no\n // `resourceAccess` can express and none should have to. Applied through\n // the shared derivation so this adapter and the Mongo one cannot disagree\n // about what that floor is.\n const databaseGrants = deriveMinionDatabaseGrants(grants);\n\n // #2303: a MINION reaches the DATABASE queue's table, confined by row-level security to its own queues. Granted\n // under every service profile, because a profile is not the role's to know. Under `full` the table is unused, so the\n // only reach this adds there is publishing into an empty queue nobody consumes, and reading its own (empty) queues.\n // Only minions: no other named principal consumes that queue.\n const rowConfinedTables: PostgresRowConfinedTableGrant[] = [];\n if (context.principal.kind === ApplicationRuntimePrincipalKind.MINION) {\n const queue = deriveMinionDatabaseQueueConfinement(context.wildoApplicationId, context.principal.name ?? '');\n const [table] = resolveGrantStorageNames([queue.resourceType]);\n rowConfinedTables.push({ table, column: queue.field, rowsReachable: queue.rowsReachable });\n }\n\n const { connectionUrl: principalConnectionUrl } = await adminClient.upsertTableScopedDatabaseRole({\n databaseName,\n username,\n password,\n schemaName: POSTGRES_APPLICATION_SCHEMA,\n // Resource types → table names HERE, at the adapter that speaks\n // Postgres. The grant contract itself stays in the platform vocabulary,\n // and passes through the SAME translation Mongo uses, so the two\n // adapters cannot disagree about which rows a resource type addresses.\n // SQL identifier casing is applied by the manager, which is the one site\n // that issues the DDL and runs the existence check those names must match.\n readTables: resolveGrantStorageNames(databaseGrants.read),\n writeTables: resolveGrantStorageNames(databaseGrants.write),\n appendTables: resolveGrantStorageNames(databaseGrants.append),\n maintainTables: resolveGrantStorageNames(databaseGrants.maintain),\n rowConfinedTables,\n });\n\n return {\n secretBlobValues: {\n [POSTGRES_DATABASE_NAME_PATH]: databaseName,\n [POSTGRES_USERNAME_PATH]: username,\n [POSTGRES_CONNECT_URL_PATH]: principalConnectionUrl,\n },\n };\n }\n\n // CREATE/ALTER USER + CREATE DATABASE — idempotent upsert. The\n // admin-client reapplies privileges every time so the call is\n // safe to repeat.\n const { connectionUrl } = await adminClient.upsertApplicationDatabase({\n databaseName,\n username,\n password,\n });\n\n return {\n secretBlobValues: {\n [POSTGRES_DATABASE_NAME_PATH]: databaseName,\n [POSTGRES_USERNAME_PATH]: username,\n [POSTGRES_CONNECT_URL_PATH]: connectionUrl,\n },\n };\n },\n\n /**\n * Revoke a principal's PostgreSQL credential — and destroy no data (#1307). A minion's\n * table-scoped role is dropped (it owns nothing); the application backend's role OWNS the\n * database, so its login is disabled and the role, its ownership and every row are kept.\n * Idempotent: the admin client treats a missing role as a no-op.\n *\n * **Caller status**: apps-manager runtime-principal declaration reconciliation calls this for\n * removed minions, and application withdrawal (`deregisterApplication`) for the backend and every\n * minion; `restoreApplication` re-mints them. Destroying the database is #1562's separate door.\n *\n * **Defensive validation** (Slice 4.A.2 / L4 pattern): empty\n * `appSlug` would derive an empty database name; we fail-loud\n * instead so a bad caller surfaces immediately.\n */\n async revokeAppCredentials(context: AppCredentialMintingContext): Promise<void> {\n if (!context.appSlug) {\n throw new Error(\n `PostgresSelfInfraProviderModule.revokeAppCredentials: ` +\n `appSlug is empty. ` +\n `The orchestrator MUST supply a non-empty slug.`,\n );\n }\n const adminClient = context.adminClient as IPostgresAdminClient;\n const username = buildPostgresPrincipalUsername(context.appSlug, context.principal);\n\n if (context.principal && context.principal.kind !== ApplicationRuntimePrincipalKind.APPLICATION_BACKEND) {\n const databaseName =\n context.applicationConfigInputs?.[POSTGRES_DATABASE_NAME_INPUT_KEY]\n || buildDatabaseName(context.appSlug);\n // A named principal owns NOTHING but its own role. Routing it through\n // `dropApplicationDatabase` — which is what this method did before named\n // principals existed — would DROP THE APPLICATION'S DATABASE while\n // believing it was retiring one minion's access.\n await adminClient.dropTableScopedDatabaseRole({\n databaseName,\n username,\n schemaName: POSTGRES_APPLICATION_SCHEMA,\n });\n return;\n }\n\n /*\n * The APPLICATION BACKEND's role OWNS the application database, so revoking it disables the LOGIN\n * and keeps the role, its ownership and every row (#1307).\n *\n * This branch used to call `dropApplicationDatabase` — the database AND the role. Nothing called it\n * for the backend until deregistration did, and deregistration is a REVERSIBLE withdrawal: `restore`\n * re-mints the recorded credential and the application boots on the data it left. A revocation that\n * dropped the database would have turned every withdrawal into the irreversible destruction #1562\n * parks behind its own door. Revocation removes authentication; it never removes data.\n */\n await adminClient.revokeApplicationDatabaseLogin({ username });\n },\n\n // No `mintPlatformServiceCredentials` (D-4 of Slice 4.B —\n // audience-2 not applicable to Postgres_Self today).\n};\n"]}
|