@wildo-ai/platform-infra-providers 1.1.11 → 1.1.13

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.
Files changed (57) hide show
  1. package/dist/esm/aws-s3/aws-s3.infra.module.d.ts +11 -10
  2. package/dist/esm/aws-s3/aws-s3.infra.module.d.ts.map +1 -1
  3. package/dist/esm/aws-s3/aws-s3.infra.module.js +14 -12
  4. package/dist/esm/aws-s3/aws-s3.infra.module.js.map +1 -1
  5. package/dist/esm/clamav-self/clamav-self.infra.module.d.ts +1 -2
  6. package/dist/esm/clamav-self/clamav-self.infra.module.d.ts.map +1 -1
  7. package/dist/esm/clamav-self/clamav-self.infra.module.js +1 -2
  8. package/dist/esm/clamav-self/clamav-self.infra.module.js.map +1 -1
  9. package/dist/esm/immudb-self/immudb-self.infra.module.d.ts.map +1 -1
  10. package/dist/esm/immudb-self/immudb-self.infra.module.js.map +1 -1
  11. package/dist/esm/index.d.ts +1 -1
  12. package/dist/esm/index.d.ts.map +1 -1
  13. package/dist/esm/index.js +2 -2
  14. package/dist/esm/index.js.map +1 -1
  15. package/dist/esm/minio-self/minio-self.infra.module.d.ts +1 -4
  16. package/dist/esm/minio-self/minio-self.infra.module.d.ts.map +1 -1
  17. package/dist/esm/minio-self/minio-self.infra.module.js +1 -4
  18. package/dist/esm/minio-self/minio-self.infra.module.js.map +1 -1
  19. package/dist/esm/mongodb-atlas/mongodb-atlas.infra.module.d.ts +1 -2
  20. package/dist/esm/mongodb-atlas/mongodb-atlas.infra.module.d.ts.map +1 -1
  21. package/dist/esm/mongodb-atlas/mongodb-atlas.infra.module.js +1 -2
  22. package/dist/esm/mongodb-atlas/mongodb-atlas.infra.module.js.map +1 -1
  23. package/dist/esm/mongodb-self/mongodb-self.infra.module.d.ts +1 -2
  24. package/dist/esm/mongodb-self/mongodb-self.infra.module.d.ts.map +1 -1
  25. package/dist/esm/mongodb-self/mongodb-self.infra.module.js +1 -2
  26. package/dist/esm/mongodb-self/mongodb-self.infra.module.js.map +1 -1
  27. package/dist/esm/postgres-self/postgres-self.infra.module.d.ts +1 -2
  28. package/dist/esm/postgres-self/postgres-self.infra.module.d.ts.map +1 -1
  29. package/dist/esm/postgres-self/postgres-self.infra.module.js +1 -2
  30. package/dist/esm/postgres-self/postgres-self.infra.module.js.map +1 -1
  31. package/dist/esm/rabbitmq-self/rabbitmq-self.infra.module.d.ts +1 -2
  32. package/dist/esm/rabbitmq-self/rabbitmq-self.infra.module.d.ts.map +1 -1
  33. package/dist/esm/rabbitmq-self/rabbitmq-self.infra.module.js +4 -7
  34. package/dist/esm/rabbitmq-self/rabbitmq-self.infra.module.js.map +1 -1
  35. package/dist/esm/redis-self/redis-self.infra.module.d.ts +1 -2
  36. package/dist/esm/redis-self/redis-self.infra.module.d.ts.map +1 -1
  37. package/dist/esm/redis-self/redis-self.infra.module.js +1 -2
  38. package/dist/esm/redis-self/redis-self.infra.module.js.map +1 -1
  39. package/dist/tsconfig.build.tsbuildinfo +1 -1
  40. package/package.json +6 -6
  41. package/src/aws-s3/__tests__/aws-s3.infra.module.test.ts +1 -2
  42. package/src/aws-s3/aws-s3.infra.module.ts +14 -12
  43. package/src/clamav-self/__tests__/clamav-self.infra.module.test.ts +1 -2
  44. package/src/clamav-self/clamav-self.infra.module.ts +1 -2
  45. package/src/index.ts +2 -2
  46. package/src/minio-self/__tests__/minio-self.infra.module.test.ts +1 -2
  47. package/src/minio-self/minio-self.infra.module.ts +1 -4
  48. package/src/mongodb-atlas/__tests__/mongodb-atlas.infra.module.test.ts +3 -2
  49. package/src/mongodb-atlas/mongodb-atlas.infra.module.ts +1 -2
  50. package/src/mongodb-self/__tests__/mongodb-self.infra.module.test.ts +11 -7
  51. package/src/mongodb-self/mongodb-self.infra.module.ts +1 -2
  52. package/src/postgres-self/__tests__/postgres-self.infra.module.test.ts +3 -4
  53. package/src/postgres-self/postgres-self.infra.module.ts +1 -2
  54. package/src/rabbitmq-self/__tests__/rabbitmq-self.infra.module.test.ts +2 -3
  55. package/src/rabbitmq-self/rabbitmq-self.infra.module.ts +4 -7
  56. package/src/redis-self/__tests__/redis-self.infra.module.test.ts +1 -2
  57. package/src/redis-self/redis-self.infra.module.ts +1 -2
@@ -1 +1 @@
1
- {"version":3,"file":"rabbitmq-self.infra.module.js","sourceRoot":"","sources":["../../../../src/rabbitmq-self/rabbitmq-self.infra.module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqFG;AAEH,OAAO,EAIL,eAAe,EACf,0BAA0B,EAC1B,aAAa,EAKb,+BAA+B,EAC/B,iCAAiC,GAElC,MAAM,+BAA+B,CAAC;AAEvC;;;;;;;;;;GAUG;AACH,MAAM,aAAa,GAAG,GAAG,CAAC;AAE1B;;;;;GAKG;AACH,MAAM,cAAc,GAAG,WAAW,CAAC;AAEnC;;;;;;GAMG;AACH,MAAM,sBAAsB,GAAG,4BAA4B,CAAC;AAC5D,MAAM,sBAAsB,GAAG,4BAA4B,CAAC;AAC5D;;;;;;;GAOG;AACH,MAAM,+BAA+B,GAA0B,CAAC,sBAAsB,EAAE,sBAAsB,CAAC,CAAC;AAGhH;;;;;;;GAOG;AACH,MAAM,eAAe,GAAG,OAAO,CAAC;AAEhC;;;;;;;GAOG;AACH,MAAM,mCAAmC,GAAG,UAAU,CAAC;AAEvD;;;;;;GAMG;AACH,SAAS,mBAAmB,CAAC,oBAA4B;IACvD,OAAO,oBAAoB,CAAC;AAC9B,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,8CAA8C,GAAG,mCAAmC,CAAC;AAE3F;;;;;;;;;;;;;;GAcG;AACH,SAAS,yBAAyB,CAAC,WAAmB;IACpD,IAAI,WAAW,KAAK,8CAA8C,EAAE,CAAC;QACnE,OAAO,sCAAsC,CAAC;IAChD,CAAC;IACD,MAAM,WAAW,GAAG,WAAW,CAAC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`InfraProviderModule`\n * (Slices 1–2.5 of `infra-provider-planner.md`).\n *\n * Implements the `RABBITMQ_SELF` `InfraProvider` over the\n * `IRabbitMQManagementClient` transport (raw HTTP `PUT /api/users` etc.,\n * exposed by `RabbitMQConnectionManagerService` after the 5C policy/\n * transport split). Owns ALL per-app and per-platform-service\n * permission policy — the regex shapes, the broader-permission\n * special case for `crontabs-batches-manager`, the per-app username\n * convention, the optional vhost activation.\n *\n * **What this module reads from `AppCredentialMintingContext`**:\n * - `applicationNamespace` — used as the rabbit username\n * (`<appSlug>-<envId>`, the legacy convention from\n * `wildo-application-lifecycle.service.ts`).\n * - `wildoApplicationId` — used as the permission-regex disambiguator\n * (matches `^wildo\\.(queue|reply)\\.<id>\\..*`).\n * - `secretInputs['database.rabbitmq.password']` — orchestrator-\n * supplied password (module is upsert-only, never generator).\n * - `applicationConfigInputs?.['vhost']` — optional per-app vhost\n * for true vhost-level isolation (Slice 2.5c-3).\n * - `adminClient` — narrowed to `IRabbitMQManagementClient`.\n *\n * **What this module IGNORES from the context** (Slice 4.A.2 / M4):\n * - `appSlug` — RabbitMQ resources are namespace-scoped, not slug-\n * scoped. Future modules (MongoDB DB name, etc.) WILL use `appSlug`.\n * This is documented forward-compat for module authors: not every\n * module reads every context field; each declares which it consumes.\n *\n * **Three audiences this module serves:**\n *\n * 1. **Audience-1 (platform-admin, declared via `plan().platformAdmin`)**:\n * cluster-wide management-API creds (`RABBITMQ_ADMIN_USERNAME` /\n * `RABBITMQ_ADMIN_PASSWORD`). Consumers: `apps-manager`,\n * `companion`. Delivered through process.env (the CLI's\n * `env-vars-builder` writes them per-env). No method.\n *\n * 2. **Audience-2 (platform-service-scoped, via\n * `mintPlatformServiceCredentials`)**: per-platform-service broker\n * users for inter-service messaging (`apps-manager`,\n * `crontabs-batches-manager`, `file-generator`). Username =\n * `serviceName`; permission regex is service-namespaced\n * (`^wildo\\.platform\\.<slug>\\..*`); crontabs gets the broader\n * `^wildo\\.(queue|reply|platform)\\..*` per the legacy override.\n *\n * **Slice 2.5 behavior-parity note**: the legacy code paths\n * `provisionServiceCredentials` and `ensureAppsManagerCredentials`\n * produced slightly different topic-permission regexes for the\n * same apps-manager user (`wildo\\.platform\\.apps_manager\\..*` vs\n * `wildo.platform.apps_manager.*`). User permissions were therefore\n * order-dependent. This module unifies on the dot-escaped variant.\n * Functionally equivalent for real queue names; tighter spec.\n *\n * **Slice 4.A.2 / M2 design note**: the legacy\n * `getDefaultRabbitMQPermissions.read` field declared a BROADER\n * regex than `configure`/`write` (included\n * `wildo.platform.broadcast.*`) — but that widening NEVER reached\n * the broker (the legacy `upsertTenantUserPermissions` ignored\n * the `read` arg and used `resourceNameRegex` for both\n * `configure` and `read`). This module preserves that behavior:\n * `read === configure`. If platform services need a broadcast\n * namespace in the future, extend `mintPlatformServiceCredentials`\n * with an explicit broadcast-read regex.\n *\n * 3. **Audience-3 (app-scoped, via `plan().appRuntime` +\n * `mintAppCredentials`)**: per-customer-app broker user. Username\n * = `applicationNamespace`; permission regex disambiguates by\n * `wildoApplicationId` (Mongo ObjectId — globally unique). Result\n * threaded into `Wildo_Application_Secrets.database.rabbitmq.{\n * username, password}` via `_merge_WildoApplicationSecrets`.\n *\n * **Vhost activation (Slice 2.5c-3, opt-in)**: when the operator\n * authors `backingServices.rabbitmq.vhost` in\n * `wildo.infra.<envName>.config.ts`, the CLI sends it with that\n * application's registration (`backingServiceAddressing`, #1107); the lifecycle\n * service threads it via `applicationConfigInputs.vhost`; this module\n * `ensureVhost`-then-permissions-on-it. Without the field, the\n * module falls back to `/` (legacy permission-regex isolation).\n *\n * **`revokeAppCredentials`** is called by apps-manager runtime-principal\n * declaration reconciliation when a minion is removed, and for every principal\n * (the application backend included) of an application withdrawn from the\n * platform (#1307). The lifecycle service passes the application namespace and\n * the principal; its broker user is deleted; the vhost and its queues stay (#1562 owns destruction).\n */\n\nimport {\n AppCredentialMintingContext,\n AppCredentialMintingResult,\n IRabbitMQManagementClient,\n InfraCapability,\n InfraPlatformAdminConsumer,\n InfraProvider,\n InfraProviderModule,\n InfraProviderPlanContribution,\n PlatformServiceCredentialMintingContext,\n PlatformServiceCredentialMintingResult,\n ApplicationRuntimePrincipalKind,\n buildRuntimePrincipalQueueSegment,\n type ApplicationRuntimePrincipal,\n} from '@wildo-ai/platform-config-lib';\n\n/**\n * Default vhost — apps share `/` with regex-based per-user permission\n * isolation. Per-app vhost is intentionally NOT modeled (engine has no\n * `RABBITMQ_VHOST` consumer; isolation comes from the permission regex\n * on the per-app user, not from a per-app vhost).\n *\n * **No `ensureVhost(DEFAULT_VHOST)` call** is needed: vhost `/` is\n * created by RabbitMQ at server boot. Any future module variant that\n * uses a non-default vhost MUST call `adminClient.ensureVhost(...)`\n * before user/permissions setup.\n */\nconst DEFAULT_VHOST = '/';\n\n/**\n * Topic exchange used by every Wildo runtime publisher / consumer.\n * Matches the value already in use at\n * `wildo-application-lifecycle.service.ts:568` and\n * `platform-infrastructure-manager.service.ts:485`.\n */\nconst TOPIC_EXCHANGE = 'amq.topic';\n\n/**\n * The `Wildo_Application_Secrets` JSON paths this module writes through\n * `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 path\n * fails loudly at one place instead of drifting silently.\n */\nconst RABBITMQ_USERNAME_PATH = 'database.rabbitmq.username';\nconst RABBITMQ_PASSWORD_PATH = 'database.rabbitmq.password';\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> = [RABBITMQ_USERNAME_PATH, RABBITMQ_PASSWORD_PATH];\n\n\n/**\n * Key the module looks for in\n * `AppCredentialMintingContext.applicationConfigInputs` to read the\n * optional per-app virtual host. Documented here as the public\n * contract: the orchestrator supplies the vhost via this key, the\n * module reads it via this key. Slice 2.5c-3 of\n * `infra-provider-planner.md`.\n */\nconst VHOST_INPUT_KEY = 'vhost';\n\n/**\n * Key the module looks for in\n * `PlatformServiceCredentialMintingContext.secretInputs` to read the\n * orchestrator-supplied platform-service password. Slice 4.A.2 / M5\n * of `infra-provider-planner.md` — extracted as a constant for\n * symmetry with `RABBITMQ_PASSWORD_PATH` (used by `mintAppCredentials`),\n * so a future rename touches one site instead of drifting silently.\n */\nconst PLATFORM_SERVICE_PASSWORD_INPUT_KEY = 'password';\n\n/**\n * Compute the per-app rabbit username. Mirrors the existing convention\n * at `wildo-application-lifecycle.service.ts:434, 440` — username is\n * the application namespace (`<appSlug>-<environmentId>` per\n * `buildApplicationNamespace`), NOT the raw slug. Centralized here so\n * future changes touch one site.\n */\nfunction buildRabbitUsername(applicationNamespace: string): string {\n return applicationNamespace;\n}\n\n/**\n * Identifier of the platform-crontabs-batches-manager service. The\n * crontabs special case (broader permissions covering all per-app\n * queue/reply names so it can fan out scheduled jobs) lives here so\n * the legacy hard-coded check at\n * `platform-infrastructure-manager.service.ts:466-475` becomes a\n * module-internal concern.\n *\n * Hardcoded as a string literal rather than imported from\n * `PlatformApplicationType` because that enum lives in saas-models\n * and importing it here would couple the module to that enum's\n * runtime shape — the value `'platform_crontabs_batches_manager'` is\n * stable and small.\n */\nconst PLATFORM_CRONTABS_BATCHES_MANAGER_SERVICE_NAME = 'platform_crontabs_batches_manager';\n\n/**\n * Compute the per-platform-service permission regex.\n *\n * Default policy (apps-manager, file-generator, …): the service can\n * configure / write / read on `^wildo\\.platform\\.<serviceSlug>\\..*`\n * where `serviceSlug = serviceName.replace('platform_', '')`. Mirrors\n * the legacy `getDefaultRabbitMQPermissions` at\n * `credentials-provisioner.service.ts:267-275`.\n *\n * Crontabs-batches-manager override: broader regex\n * `^wildo\\.(queue|reply|platform)\\..*` so the crontab can publish\n * scheduled jobs onto every per-app queue and read replies. Mirrors\n * the legacy inline override at\n * `platform-infrastructure-manager.service.ts:466-475`.\n */\nfunction buildPlatformServiceRegex(serviceName: string): string {\n if (serviceName === PLATFORM_CRONTABS_BATCHES_MANAGER_SERVICE_NAME) {\n return '^wildo\\\\.(queue|reply|platform)\\\\..*';\n }\n const serviceSlug = serviceName.replace('platform_', '');\n return `^wildo\\\\.platform\\\\.${serviceSlug}\\\\..*`;\n}\n\n/**\n * Compute the per-app permission regex. Matches the convention at\n * `wildo-application-lifecycle.service.ts:552`:\n * `^wildo\\.(queue|reply)\\.${wildoApplicationId}\\..*`\n * The disambiguator is the application ID, NOT the slug — slugs could\n * theoretically be reassigned; the id is forever-stable. The `^` and\n * `\\.` escaping is required by the RabbitMQ regex evaluator.\n */\nfunction buildPermissionRegex(wildoApplicationId: string): string {\n // Escape regex metacharacters that may appear in application ids\n // (today they're Mongo ObjectId hex strings — no specials — but the\n // contract only commits to \"stable opaque string\", so guard).\n const escapedId = wildoApplicationId.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return `^wildo\\\\.(queue|reply)\\\\.${escapedId}\\\\..*`;\n}\n\n/**\n * The bound on an application's DEAD-LETTER queues (#2214), declared as a broker POLICY.\n *\n * ## Why it exists\n *\n * Every application dead-letter queue (`<category>.deadletter`, and `domain.<name>.deadletter`) is\n * terminal and consumer-less BY DECISION (#469, 2026-09-08): a parked message is inspected and\n * replayed with the broker's own tooling, never through a Wildo read surface, because a job payload\n * may carry personal data. Measured on 2026-10-01, that left a sink with no reader AND no bound —\n * `scheduled.deadletter` held 359 messages for one local application after one day of restarts,\n * and every restart added to it permanently. A queue an operator is expected to read must stay small\n * enough to read, and must not grow without limit in a deployment that lives for months.\n *\n * ## Why a policy and not a queue argument\n *\n * RabbitMQ refuses to change the arguments of an existing queue (406 PRECONDITION_FAILED), so a\n * `x-max-length` argument would only reach a queue declared after the change and would break the\n * declaration of every queue that already exists. A policy reaches existing and future queues alike\n * and can be changed later. RabbitMQ's documentation recommends a policy for exactly this setting.\n * spec-cite: https://www.rabbitmq.com/docs/maxlength — max length \"using a policy (this option is highly recommended)\"; `overflow` defaults to `drop-head`.\n * spec-cite: https://www.rabbitmq.com/docs/policies — \"At most one policy matches a queue\"; policies \"can change at any time\" and are re-applied.\n * spec-cite: https://www.rabbitmq.com/docs/ttl — `message-ttl` in milliseconds; with no dead-letter exchange an expired message is removed.\n *\n * ## The values\n *\n * - `message-ttl` 14 days: a parked message is kept long enough for an operator to notice and act on\n * it, then removed. The dead-letter queues have no dead-letter exchange of their own, so an expired\n * message is discarded, not moved.\n * - `max-length` 10 000 with `overflow: drop-head`: a burst cannot grow the queue past what a person\n * can inspect; the OLDEST message goes first, so the most recent failures — the ones being\n * investigated — survive.\n *\n * Scoped to ONE application's own dead-letter queues, so the policies of applications sharing the\n * default vhost never overlap: at most one policy applies to a queue, and two overlapping policies at\n * the same priority would be applied non-deterministically.\n */\nexport const RABBITMQ_DEAD_LETTER_QUEUE_BOUND = {\n /** 14 days, in milliseconds. */\n messageTtlMs: 14 * 24 * 60 * 60 * 1000,\n maxLength: 10_000,\n priority: 0,\n} as const;\n\n/** The policy name, per application — unique on a shared vhost. */\nexport function buildDeadLetterBoundPolicyName(wildoApplicationId: string): string {\n return `wildo-deadletter-bound.${wildoApplicationId}`;\n}\n\n/** Every dead-letter queue of ONE application: `wildo.queue.<appId>.<anything>.deadletter`. */\nexport function buildDeadLetterBoundPolicyPattern(wildoApplicationId: string): string {\n const escapedId = wildoApplicationId.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return `^wildo\\\\.queue\\\\.${escapedId}\\\\..+\\\\.deadletter$`;\n}\n\n/**\n * The queues a MINION may CONSUME from — its own tick queue only.\n *\n * ## Why only `read` narrows, measured rather than assumed\n *\n * A minion runs the full backend pipeline headless, so the three RabbitMQ\n * permission axes are not interchangeable here:\n *\n * - **`read`** governs CONSUMING. Narrowing it is the containment that matters:\n * without it a minion can drain the application backend's job queue, consume\n * another minion's ticks, or read RPC replies addressed to the backend.\n * - **`configure`** governs DECLARE. The tick consumer declares its own queue\n * (`channel.assertQueue`) — but the delayed-publish path can declare a delay\n * queue too, so narrowing this risks breaking a legitimate publish.\n * - **`write`** governs PUBLISHING. A minion legitimately enqueues jobs and\n * sends RPC replies into the application's namespace; `publish` calls\n * `sendToQueue` WITHOUT asserting (verified in\n * `rabbitmq-adapter.backend.service.ts`), so it needs `write` on the app\n * namespace and nothing more.\n *\n * **What this therefore does NOT prevent, stated plainly:** a minion can still\n * PUBLISH anywhere in its application's queue namespace — it could enqueue a job\n * the backend will run. Constraining that is a different control (who may\n * request what work), not a broker permission, and pretending otherwise would\n * overstate the boundary.\n *\n * The trailing `(\\..*)?$` admits the tick queue itself and any suffixed\n * variant, while the anchored `$` stops it matching a SIBLING whose name merely\n * starts with this one's.\n */\n/**\n * Per-principal broker username — the SAME derivation `revokeAppCredentials`\n * must use.\n *\n * The application backend keeps `applicationNamespace` VERBATIM so an existing\n * deployment's user is never orphaned. A revoke that derived this differently\n * would delete the BACKEND's broker user while believing it was removing a\n * minion's — the identical trap already caught on the Redis side.\n */\nfunction buildRabbitPrincipalUsername(\n applicationNamespace: string,\n principal: ApplicationRuntimePrincipal | undefined,\n): string {\n if (!principal || principal.kind === ApplicationRuntimePrincipalKind.APPLICATION_BACKEND) {\n return buildRabbitUsername(applicationNamespace);\n }\n const sanitizedName = (principal.name ?? '').replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '');\n return `${applicationNamespace}-${principal.kind}-${sanitizedName}`;\n}\n\nfunction buildMinionConsumeRegex(wildoApplicationId: string, minionName: string): string {\n const escape = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const appId = escape(wildoApplicationId);\n const name = escape(minionName);\n // Two alternatives, and nothing else:\n // its tick queue — wildo.queue.<appId>.minion-tick.<name>\n // its OWN reply queue — wildo.reply.<appId>.<segment>.<podId>\n // The reply segment is IMPORTED from the same builder the minion's own AMQP\n // adapter uses, not reproduced here. It used to be hand-written as\n // `minion-<name>` with a comment saying it \"mirrors\" what the adapter emits —\n // which agreed only while every minion name survived sanitisation unchanged.\n // The application backend gets no segment at all (the builder returns\n // undefined for it), keeping the historical layout, so this cannot match its\n // replies.\n const replySegment = escape(\n buildRuntimePrincipalQueueSegment(ApplicationRuntimePrincipalKind.MINION, minionName) ?? '',\n );\n return `^(wildo\\\\.queue\\\\.${appId}\\\\.minion-tick\\\\.${name}(\\\\..*)?`\n + `|wildo\\\\.reply\\\\.${appId}\\\\.${replySegment}\\\\..*)$`;\n}\n\nexport const RabbitmqSelfInfraProviderModule: InfraProviderModule = {\n provider: InfraProvider.RABBITMQ_SELF,\n supportedCapabilities: [InfraCapability.QUEUING_SYSTEM],\n perPrincipalSecretBlobPaths: PER_PRINCIPAL_SECRET_BLOB_PATHS,\n\n plan(): InfraProviderPlanContribution {\n return {\n dockerComposeServices: ['rabbitmq'],\n k8sResources: ['templates/infra/k8s/internal/rabbitmq/deployment.yaml.hbs'],\n platformAdmin: {\n envVars: {\n RABBITMQ_HOST: 'rabbitmq',\n RABBITMQ_PORT: '5672',\n RABBITMQ_MANAGEMENT_PORT: '15672',\n },\n secretEnvVars: ['RABBITMQ_ADMIN_USERNAME', 'RABBITMQ_ADMIN_PASSWORD'],\n // Audience-1 only (management-API access). audience-2 platform-\n // service-scoped consumers (apps-manager / crontabs / file-\n // generator publish-consume creds via `provisionAllPlatformServices`)\n // are LD-8 territory, deferred to Slice 2.5 — they get their\n // own `mintPlatformServiceCredentials` method then.\n consumers: [\n InfraPlatformAdminConsumer.APPS_MANAGER,\n InfraPlatformAdminConsumer.COMPANION,\n ],\n },\n appRuntime: {\n // Declared for forward-compat with Slice 2.5's\n // `_merge_WildoApplicationConfig` integration. Not consumed by\n // any planner path in Slice 2 — the existing hard-coded values\n // at `wildo-application-lifecycle.service.ts:1796-1799` stay in\n // effect (host: 'localhost', port: 5672) until the planner\n // wires this slice's contribution.\n perAppConfigBlobPaths: {\n 'database.rabbitmq.host': 'rabbitmq',\n 'database.rabbitmq.port': 5672,\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 IRabbitMQManagementClient;\n const password = context.secretInputs[RABBITMQ_PASSWORD_PATH];\n if (!password) {\n throw new Error(\n `RabbitmqSelfInfraProviderModule.mintAppCredentials: ` +\n `secretInputs is missing '${RABBITMQ_PASSWORD_PATH}'. ` +\n `The orchestrator MUST supply the rabbit password — modules are upsert-only.`,\n );\n }\n\n const username = buildRabbitPrincipalUsername(context.applicationNamespace, context.principal);\n const permissionRegex = buildPermissionRegex(context.wildoApplicationId);\n // A MINION consumes exactly two things: its own tick queue, and its own RPC\n // REPLY queue. Both are admitted; everything else in the application's\n // namespace is refused.\n //\n // The reply half is why an earlier attempt at this failed. Reply queues used\n // to be `wildo.reply.<appId>.<podId>`, and `podId` is a per-PROCESS token\n // carrying no principal — so no regex could admit a minion's replies while\n // refusing the backend's, and narrowing `read` crash-looped the minion on\n // its own replies. `buildReplyQueueName` now embeds the owning runtime,\n // which is what makes this expressible at all.\n const readRegex = context.principal?.kind === ApplicationRuntimePrincipalKind.MINION && context.principal.name\n ? buildMinionConsumeRegex(context.wildoApplicationId, context.principal.name)\n : permissionRegex;\n\n // Slice 2.5c-3: optional per-app vhost. When the orchestrator\n // supplies a non-empty `applicationConfigInputs.vhost`, the module\n // ensures the vhost exists and sets permissions ON THAT vhost\n // (provides true vhost-level isolation). When omitted, the module\n // falls back to the default vhost `/` (legacy Slice 2 behavior:\n // permission-regex isolation only). This is the opt-in seam — apps\n // without an authored `backingServices.rabbitmq.vhost` continue to\n // share `/`.\n const vhost = context.applicationConfigInputs?.[VHOST_INPUT_KEY] || DEFAULT_VHOST;\n if (vhost !== DEFAULT_VHOST) {\n await adminClient.ensureVhost(vhost);\n }\n\n // PUT /api/users — idempotent upsert (replaces password + tags on conflict).\n await adminClient.putUser(username, password, []);\n\n // PUT /api/permissions — `configure` and `read` use the per-app\n // queue/reply regex; `write` widens to allow `amq.default` (the\n // default exchange RabbitMQ uses for direct routing) and the empty\n // string (broker-internal). Mirrors the legacy\n // `upsertTenantUserPermissions` write-regex shape so the Wonder\n // Todos behavior is unchanged.\n const writeRegex = `(^$|amq\\\\.default|${permissionRegex})`;\n await adminClient.setPermissions(vhost, username, {\n configure: permissionRegex,\n write: writeRegex,\n read: readRegex,\n });\n\n // PUT /api/topic-permissions — same regex on the topic exchange.\n await adminClient.setTopicPermissions(vhost, username, {\n exchange: TOPIC_EXCHANGE,\n write: permissionRegex,\n read: readRegex,\n });\n\n // Per-app-vhost cron delivery (`.claude/plans/crontab-publisher-vhost-gap.md`).\n //\n // A per-app vhost is a HARD broker isolation boundary: the platform\n // cron/minion publisher (`platform_crontabs_batches_manager`) — a single\n // global user that fans scheduled jobs into every app — cannot reach THIS\n // app's queues until granted access on THIS vhost. On the default vhost `/`\n // it already holds a broad publish grant (see `mintPlatformServiceCredentials`),\n // so the grant is only needed for a non-default per-app vhost.\n //\n // Scope it to this app's own queue namespace (`^wildo\\.(queue|reply)\\.<appId>\\..*`)\n // — the publisher gets exactly the reach it needs and no more, TIGHTER than\n // its broad default-vhost grant. It is PUBLISH-ONLY: `configure` for the\n // passive `checkQueue` existence probe the publisher runs before sending +\n // any declare, `write` (`amq.default`) for `basic.publish`; NO `read` (never\n // consumes) and NO topic permissions (uses the default exchange, not\n // `amq.topic`). The crontabs user is provisioned before any app\n // (apps-manager INIT Phase 4 < Phase 5), so it reliably exists here, and\n // `setPermissions` is an idempotent PUT — a re-init safely re-applies it.\n if (vhost !== DEFAULT_VHOST) {\n await adminClient.setPermissions(vhost, PLATFORM_CRONTABS_BATCHES_MANAGER_SERVICE_NAME, {\n configure: permissionRegex,\n write: writeRegex,\n read: '',\n });\n }\n\n // Bound this application's dead-letter queues (#2214) — on the default vhost too, where the\n // per-application pattern keeps it from touching any other application's queues. Re-applied on\n // every mint (backend and each minion) because it is an idempotent PUT; it reaches queues that\n // already exist. Revocation leaves it in place, like the vhost and the queues it governs (on the\n // shared default vhost it then matches nothing, which is harmless).\n //\n // FAIL-CLOSED, deliberately, and last: the credential is already upserted above, so a failure\n // here aborts the mint after the access is in place rather than before. A management API that\n // accepts users and permissions but refuses a policy is a broker this module cannot reason\n // about, and a mint that reported success there would leave the bound silently missing.\n await adminClient.ensureQueuePolicy(vhost, buildDeadLetterBoundPolicyName(context.wildoApplicationId), {\n pattern: buildDeadLetterBoundPolicyPattern(context.wildoApplicationId),\n definition: {\n 'message-ttl': RABBITMQ_DEAD_LETTER_QUEUE_BOUND.messageTtlMs,\n 'max-length': RABBITMQ_DEAD_LETTER_QUEUE_BOUND.maxLength,\n // semantic-literal-boundary: RabbitMQ's own overflow vocabulary.\n overflow: 'drop-head',\n },\n priority: RABBITMQ_DEAD_LETTER_QUEUE_BOUND.priority,\n });\n\n return {\n secretBlobValues: {\n [RABBITMQ_USERNAME_PATH]: username,\n // Echo the orchestrator-supplied password — proves the module\n // is upsert-only, not generator. The orchestrator persists\n // this exact value into `Wildo_Application_Secrets`.\n [RABBITMQ_PASSWORD_PATH]: password,\n },\n };\n },\n\n /**\n * Tear down the per-app rabbit user. RabbitMQ users are global, so\n * `deleteUser` removes the user (and its permissions on every vhost\n * it had access to) atomically.\n *\n * **Vhost retention** (Slice 4.A.2 / M6): when `mintAppCredentials`\n * provisioned a per-app vhost (Slice 2.5c-3), `revokeAppCredentials`\n * does NOT delete the vhost. Reasoning: vhost deletion drops every\n * queue and exchange inside it, which would destroy in-flight\n * messages mid-flight if a redeploy or restart is happening\n * concurrently. The user-deletion alone is sufficient to revoke\n * access; the empty vhost lingers as a paper trail. A future\n * \"app-deletion lifecycle\" slice can layer vhost cleanup with\n * proper drain semantics.\n *\n * **Caller status**: apps-manager runtime-principal declaration reconciliation\n * calls this for removed minions, and application withdrawal\n * (`deregisterApplication`, #1307) for the backend and every minion. The vhost\n * and its queues are kept; `restoreApplication` re-mints the user.\n *\n * **Defensive validation** (Slice 4.A.2 / L4): empty\n * `applicationNamespace` would call `DELETE /api/users/` and\n * silently 404; we fail-loud instead so a bad caller surfaces\n * immediately.\n */\n async revokeAppCredentials(context: AppCredentialMintingContext): Promise<void> {\n if (!context.applicationNamespace) {\n throw new Error(\n `RabbitmqSelfInfraProviderModule.revokeAppCredentials: ` +\n `applicationNamespace is empty. ` +\n `The orchestrator MUST supply a non-empty namespace.`,\n );\n }\n const adminClient = context.adminClient as IRabbitMQManagementClient;\n const username = buildRabbitPrincipalUsername(context.applicationNamespace, context.principal);\n await adminClient.deleteUser(username);\n },\n\n async mintPlatformServiceCredentials(\n context: PlatformServiceCredentialMintingContext,\n ): Promise<PlatformServiceCredentialMintingResult> {\n const adminClient = context.adminClient as IRabbitMQManagementClient;\n const password = context.secretInputs[PLATFORM_SERVICE_PASSWORD_INPUT_KEY];\n if (!password) {\n throw new Error(\n `RabbitmqSelfInfraProviderModule.mintPlatformServiceCredentials: ` +\n `secretInputs is missing '${PLATFORM_SERVICE_PASSWORD_INPUT_KEY}'. ` +\n `The orchestrator MUST supply the platform-service password — modules are upsert-only.`,\n );\n }\n\n // Username is the platform service identifier verbatim — preserves\n // the legacy convention from\n // `PlatformInfrastructureManagerService.provisionServiceCredentials`\n // (line 478: `username: serviceName`).\n const username = context.serviceName;\n const permissionRegex = buildPlatformServiceRegex(context.serviceName);\n\n // PUT /api/users — idempotent upsert.\n await adminClient.putUser(username, password, []);\n\n // Permissions: configure/read use the per-service regex; write\n // widens to allow `amq.default` + empty string (broker-internal),\n // matching the `upsertTenantUserPermissions` write-regex shape so\n // post-Slice-2.5 broker permissions match pre-Slice-2.5.\n const writeRegex = `(^$|amq\\\\.default|${permissionRegex})`;\n await adminClient.setPermissions(DEFAULT_VHOST, username, {\n configure: permissionRegex,\n write: writeRegex,\n read: permissionRegex,\n });\n\n // Topic permissions: same dot-escaped regex on amq.topic. The\n // legacy two-caller divergence (one path stripped the `^` and\n // produced `wildo\\.platform\\.<slug>\\..*`; the other produced\n // `wildo.platform.<slug>.*` with literal dots) is unified here on\n // the dot-escaped variant — see module JSDoc behavior-parity note.\n await adminClient.setTopicPermissions(DEFAULT_VHOST, username, {\n exchange: TOPIC_EXCHANGE,\n write: permissionRegex,\n read: permissionRegex,\n });\n\n return { username };\n },\n};\n"]}
1
+ {"version":3,"file":"rabbitmq-self.infra.module.js","sourceRoot":"","sources":["../../../src/rabbitmq-self/rabbitmq-self.infra.module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoFG;AAEH,OAAO,EAIL,eAAe,EACf,0BAA0B,EAC1B,aAAa,EAKb,+BAA+B,EAC/B,iCAAiC,GAElC,MAAM,+BAA+B,CAAC;AAEvC;;;;;;;;;;GAUG;AACH,MAAM,aAAa,GAAG,GAAG,CAAC;AAE1B;;;;;GAKG;AACH,MAAM,cAAc,GAAG,WAAW,CAAC;AAEnC;;;;;;GAMG;AACH,MAAM,sBAAsB,GAAG,4BAA4B,CAAC;AAC5D,MAAM,sBAAsB,GAAG,4BAA4B,CAAC;AAC5D;;;;;;;GAOG;AACH,MAAM,+BAA+B,GAA0B,CAAC,sBAAsB,EAAE,sBAAsB,CAAC,CAAC;AAGhH;;;;;;GAMG;AACH,MAAM,eAAe,GAAG,OAAO,CAAC;AAEhC;;;;;;GAMG;AACH,MAAM,mCAAmC,GAAG,UAAU,CAAC;AAEvD;;;;;;GAMG;AACH,SAAS,mBAAmB,CAAC,oBAA4B;IACvD,OAAO,oBAAoB,CAAC;AAC9B,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,8CAA8C,GAAG,mCAAmC,CAAC;AAE3F;;;;;;;;;;;;;;GAcG;AACH,SAAS,yBAAyB,CAAC,WAA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ACtB,CAAC,CAAC;QAEH,OAAO,EAAE,QAAQ,EAAE,CAAC;IACtB,CAAC;CACF,CAAC","sourcesContent":["/**\n * `RabbitmqSelfInfraProviderModule` — first concrete `InfraProviderModule`.\n *\n * Implements the `RABBITMQ_SELF` `InfraProvider` over the\n * `IRabbitMQManagementClient` transport (raw HTTP `PUT /api/users` etc.,\n * exposed by `RabbitMQConnectionManagerService` after the 5C policy/\n * transport split). Owns ALL per-app and per-platform-service\n * permission policy — the regex shapes, the broader-permission\n * special case for `crontabs-batches-manager`, the per-app username\n * convention, the optional vhost activation.\n *\n * **What this module reads from `AppCredentialMintingContext`**:\n * - `applicationNamespace` — used as the rabbit username\n * (`<appSlug>-<envId>`, the legacy convention from\n * `wildo-application-lifecycle.service.ts`).\n * - `wildoApplicationId` — used as the permission-regex disambiguator\n * (matches `^wildo\\.(queue|reply)\\.<id>\\..*`).\n * - `secretInputs['database.rabbitmq.password']` — orchestrator-\n * supplied password (module is upsert-only, never generator).\n * - `applicationConfigInputs?.['vhost']` — optional per-app vhost\n * for true vhost-level isolation (Slice 2.5c-3).\n * - `adminClient` — narrowed to `IRabbitMQManagementClient`.\n *\n * **What this module IGNORES from the context** (Slice 4.A.2 / M4):\n * - `appSlug` — RabbitMQ resources are namespace-scoped, not slug-\n * scoped. Future modules (MongoDB DB name, etc.) WILL use `appSlug`.\n * This is documented forward-compat for module authors: not every\n * module reads every context field; each declares which it consumes.\n *\n * **Three audiences this module serves:**\n *\n * 1. **Audience-1 (platform-admin, declared via `plan().platformAdmin`)**:\n * cluster-wide management-API creds (`RABBITMQ_ADMIN_USERNAME` /\n * `RABBITMQ_ADMIN_PASSWORD`). Consumers: `apps-manager`,\n * `companion`. Delivered through process.env (the CLI's\n * `env-vars-builder` writes them per-env). No method.\n *\n * 2. **Audience-2 (platform-service-scoped, via\n * `mintPlatformServiceCredentials`)**: per-platform-service broker\n * users for inter-service messaging (`apps-manager`,\n * `crontabs-batches-manager`, `file-generator`). Username =\n * `serviceName`; permission regex is service-namespaced\n * (`^wildo\\.platform\\.<slug>\\..*`); crontabs gets the broader\n * `^wildo\\.(queue|reply|platform)\\..*` per the legacy override.\n *\n * **Slice 2.5 behavior-parity note**: the legacy code paths\n * `provisionServiceCredentials` and `ensureAppsManagerCredentials`\n * produced slightly different topic-permission regexes for the\n * same apps-manager user (`wildo\\.platform\\.apps_manager\\..*` vs\n * `wildo.platform.apps_manager.*`). User permissions were therefore\n * order-dependent. This module unifies on the dot-escaped variant.\n * Functionally equivalent for real queue names; tighter spec.\n *\n * **Slice 4.A.2 / M2 design note**: the legacy\n * `getDefaultRabbitMQPermissions.read` field declared a BROADER\n * regex than `configure`/`write` (included\n * `wildo.platform.broadcast.*`) — but that widening NEVER reached\n * the broker (the legacy `upsertTenantUserPermissions` ignored\n * the `read` arg and used `resourceNameRegex` for both\n * `configure` and `read`). This module preserves that behavior:\n * `read === configure`. If platform services need a broadcast\n * namespace in the future, extend `mintPlatformServiceCredentials`\n * with an explicit broadcast-read regex.\n *\n * 3. **Audience-3 (app-scoped, via `plan().appRuntime` +\n * `mintAppCredentials`)**: per-customer-app broker user. Username\n * = `applicationNamespace`; permission regex disambiguates by\n * `wildoApplicationId` (Mongo ObjectId — globally unique). Result\n * threaded into `Wildo_Application_Secrets.database.rabbitmq.{\n * username, password}` via `_merge_WildoApplicationSecrets`.\n *\n * **Vhost activation (Slice 2.5c-3, opt-in)**: when the operator\n * authors `backingServices.rabbitmq.vhost` in\n * `wildo.infra.<envName>.config.ts`, the CLI sends it with that\n * application's registration (`backingServiceAddressing`, #1107); the lifecycle\n * service threads it via `applicationConfigInputs.vhost`; this module\n * `ensureVhost`-then-permissions-on-it. Without the field, the\n * module falls back to `/` (legacy permission-regex isolation).\n *\n * **`revokeAppCredentials`** is called by apps-manager runtime-principal\n * declaration reconciliation when a minion is removed, and for every principal\n * (the application backend included) of an application withdrawn from the\n * platform (#1307). The lifecycle service passes the application namespace and\n * the principal; its broker user is deleted; the vhost and its queues stay (#1562 owns destruction).\n */\n\nimport {\n AppCredentialMintingContext,\n AppCredentialMintingResult,\n IRabbitMQManagementClient,\n InfraCapability,\n InfraPlatformAdminConsumer,\n InfraProvider,\n InfraProviderModule,\n InfraProviderPlanContribution,\n PlatformServiceCredentialMintingContext,\n PlatformServiceCredentialMintingResult,\n ApplicationRuntimePrincipalKind,\n buildRuntimePrincipalQueueSegment,\n type ApplicationRuntimePrincipal,\n} from '@wildo-ai/platform-config-lib';\n\n/**\n * Default vhost — apps share `/` with regex-based per-user permission\n * isolation. Per-app vhost is intentionally NOT modeled (engine has no\n * `RABBITMQ_VHOST` consumer; isolation comes from the permission regex\n * on the per-app user, not from a per-app vhost).\n *\n * **No `ensureVhost(DEFAULT_VHOST)` call** is needed: vhost `/` is\n * created by RabbitMQ at server boot. Any future module variant that\n * uses a non-default vhost MUST call `adminClient.ensureVhost(...)`\n * before user/permissions setup.\n */\nconst DEFAULT_VHOST = '/';\n\n/**\n * Topic exchange used by every Wildo runtime publisher / consumer.\n * Matches the value already in use at\n * `wildo-application-lifecycle.service.ts:568` and\n * `platform-infrastructure-manager.service.ts:485`.\n */\nconst TOPIC_EXCHANGE = 'amq.topic';\n\n/**\n * The `Wildo_Application_Secrets` JSON paths this module writes through\n * `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 path\n * fails loudly at one place instead of drifting silently.\n */\nconst RABBITMQ_USERNAME_PATH = 'database.rabbitmq.username';\nconst RABBITMQ_PASSWORD_PATH = 'database.rabbitmq.password';\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> = [RABBITMQ_USERNAME_PATH, RABBITMQ_PASSWORD_PATH];\n\n\n/**\n * Key the module looks for in\n * `AppCredentialMintingContext.applicationConfigInputs` to read the\n * optional per-app virtual host. Documented here as the public\n * contract: the orchestrator supplies the vhost via this key, the\n * module reads it via this key.\n */\nconst VHOST_INPUT_KEY = 'vhost';\n\n/**\n * Key the module looks for in\n * `PlatformServiceCredentialMintingContext.secretInputs` to read the\n * orchestrator-supplied platform-service password. Extracted as a constant for\n * symmetry with `RABBITMQ_PASSWORD_PATH` (used by `mintAppCredentials`),\n * so a future rename touches one site instead of drifting silently.\n */\nconst PLATFORM_SERVICE_PASSWORD_INPUT_KEY = 'password';\n\n/**\n * Compute the per-app rabbit username. Mirrors the existing convention\n * at `wildo-application-lifecycle.service.ts:434, 440` — username is\n * the application namespace (`<appSlug>-<environmentId>` per\n * `buildApplicationNamespace`), NOT the raw slug. Centralized here so\n * future changes touch one site.\n */\nfunction buildRabbitUsername(applicationNamespace: string): string {\n return applicationNamespace;\n}\n\n/**\n * Identifier of the platform-crontabs-batches-manager service. The\n * crontabs special case (broader permissions covering all per-app\n * queue/reply names so it can fan out scheduled jobs) lives here so\n * the legacy hard-coded check at\n * `platform-infrastructure-manager.service.ts:466-475` becomes a\n * module-internal concern.\n *\n * Hardcoded as a string literal rather than imported from\n * `PlatformApplicationType` because that enum lives in saas-models\n * and importing it here would couple the module to that enum's\n * runtime shape — the value `'platform_crontabs_batches_manager'` is\n * stable and small.\n */\nconst PLATFORM_CRONTABS_BATCHES_MANAGER_SERVICE_NAME = 'platform_crontabs_batches_manager';\n\n/**\n * Compute the per-platform-service permission regex.\n *\n * Default policy (apps-manager, file-generator, …): the service can\n * configure / write / read on `^wildo\\.platform\\.<serviceSlug>\\..*`\n * where `serviceSlug = serviceName.replace('platform_', '')`. Mirrors\n * the legacy `getDefaultRabbitMQPermissions` at\n * `credentials-provisioner.service.ts:267-275`.\n *\n * Crontabs-batches-manager override: broader regex\n * `^wildo\\.(queue|reply|platform)\\..*` so the crontab can publish\n * scheduled jobs onto every per-app queue and read replies. Mirrors\n * the legacy inline override at\n * `platform-infrastructure-manager.service.ts:466-475`.\n */\nfunction buildPlatformServiceRegex(serviceName: string): string {\n if (serviceName === PLATFORM_CRONTABS_BATCHES_MANAGER_SERVICE_NAME) {\n return '^wildo\\\\.(queue|reply|platform)\\\\..*';\n }\n const serviceSlug = serviceName.replace('platform_', '');\n return `^wildo\\\\.platform\\\\.${serviceSlug}\\\\..*`;\n}\n\n/**\n * Compute the per-app permission regex. Matches the convention at\n * `wildo-application-lifecycle.service.ts:552`:\n * `^wildo\\.(queue|reply)\\.${wildoApplicationId}\\..*`\n * The disambiguator is the application ID, NOT the slug — slugs could\n * theoretically be reassigned; the id is forever-stable. The `^` and\n * `\\.` escaping is required by the RabbitMQ regex evaluator.\n */\nfunction buildPermissionRegex(wildoApplicationId: string): string {\n // Escape regex metacharacters that may appear in application ids\n // (today they're Mongo ObjectId hex strings — no specials — but the\n // contract only commits to \"stable opaque string\", so guard).\n const escapedId = wildoApplicationId.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return `^wildo\\\\.(queue|reply)\\\\.${escapedId}\\\\..*`;\n}\n\n/**\n * The bound on an application's DEAD-LETTER queues (#2214), declared as a broker POLICY.\n *\n * ## Why it exists\n *\n * Every application dead-letter queue (`<category>.deadletter`, and `domain.<name>.deadletter`) is\n * terminal and consumer-less BY DECISION (#469, 2026-09-08): a parked message is inspected and\n * replayed with the broker's own tooling, never through a Wildo read surface, because a job payload\n * may carry personal data. Measured on 2026-10-01, that left a sink with no reader AND no bound —\n * `scheduled.deadletter` held 359 messages for one local application after one day of restarts,\n * and every restart added to it permanently. A queue an operator is expected to read must stay small\n * enough to read, and must not grow without limit in a deployment that lives for months.\n *\n * ## Why a policy and not a queue argument\n *\n * RabbitMQ refuses to change the arguments of an existing queue (406 PRECONDITION_FAILED), so a\n * `x-max-length` argument would only reach a queue declared after the change and would break the\n * declaration of every queue that already exists. A policy reaches existing and future queues alike\n * and can be changed later. RabbitMQ's documentation recommends a policy for exactly this setting.\n * spec-cite: https://www.rabbitmq.com/docs/maxlength — max length \"using a policy (this option is highly recommended)\"; `overflow` defaults to `drop-head`.\n * spec-cite: https://www.rabbitmq.com/docs/policies — \"At most one policy matches a queue\"; policies \"can change at any time\" and are re-applied.\n * spec-cite: https://www.rabbitmq.com/docs/ttl — `message-ttl` in milliseconds; with no dead-letter exchange an expired message is removed.\n *\n * ## The values\n *\n * - `message-ttl` 14 days: a parked message is kept long enough for an operator to notice and act on\n * it, then removed. The dead-letter queues have no dead-letter exchange of their own, so an expired\n * message is discarded, not moved.\n * - `max-length` 10 000 with `overflow: drop-head`: a burst cannot grow the queue past what a person\n * can inspect; the OLDEST message goes first, so the most recent failures — the ones being\n * investigated — survive.\n *\n * Scoped to ONE application's own dead-letter queues, so the policies of applications sharing the\n * default vhost never overlap: at most one policy applies to a queue, and two overlapping policies at\n * the same priority would be applied non-deterministically.\n */\nexport const RABBITMQ_DEAD_LETTER_QUEUE_BOUND = {\n /** 14 days, in milliseconds. */\n messageTtlMs: 14 * 24 * 60 * 60 * 1000,\n maxLength: 10_000,\n priority: 0,\n} as const;\n\n/** The policy name, per application — unique on a shared vhost. */\nexport function buildDeadLetterBoundPolicyName(wildoApplicationId: string): string {\n return `wildo-deadletter-bound.${wildoApplicationId}`;\n}\n\n/** Every dead-letter queue of ONE application: `wildo.queue.<appId>.<anything>.deadletter`. */\nexport function buildDeadLetterBoundPolicyPattern(wildoApplicationId: string): string {\n const escapedId = wildoApplicationId.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return `^wildo\\\\.queue\\\\.${escapedId}\\\\..+\\\\.deadletter$`;\n}\n\n/**\n * The queues a MINION may CONSUME from — its own tick queue only.\n *\n * ## Why only `read` narrows, measured rather than assumed\n *\n * A minion runs the full backend pipeline headless, so the three RabbitMQ\n * permission axes are not interchangeable here:\n *\n * - **`read`** governs CONSUMING. Narrowing it is the containment that matters:\n * without it a minion can drain the application backend's job queue, consume\n * another minion's ticks, or read RPC replies addressed to the backend.\n * - **`configure`** governs DECLARE. The tick consumer declares its own queue\n * (`channel.assertQueue`) — but the delayed-publish path can declare a delay\n * queue too, so narrowing this risks breaking a legitimate publish.\n * - **`write`** governs PUBLISHING. A minion legitimately enqueues jobs and\n * sends RPC replies into the application's namespace; `publish` calls\n * `sendToQueue` WITHOUT asserting (verified in\n * `rabbitmq-adapter.backend.service.ts`), so it needs `write` on the app\n * namespace and nothing more.\n *\n * **What this therefore does NOT prevent, stated plainly:** a minion can still\n * PUBLISH anywhere in its application's queue namespace — it could enqueue a job\n * the backend will run. Constraining that is a different control (who may\n * request what work), not a broker permission, and pretending otherwise would\n * overstate the boundary.\n *\n * The trailing `(\\..*)?$` admits the tick queue itself and any suffixed\n * variant, while the anchored `$` stops it matching a SIBLING whose name merely\n * starts with this one's.\n */\n/**\n * Per-principal broker username — the SAME derivation `revokeAppCredentials`\n * must use.\n *\n * The application backend keeps `applicationNamespace` VERBATIM so an existing\n * deployment's user is never orphaned. A revoke that derived this differently\n * would delete the BACKEND's broker user while believing it was removing a\n * minion's — the identical trap already caught on the Redis side.\n */\nfunction buildRabbitPrincipalUsername(\n applicationNamespace: string,\n principal: ApplicationRuntimePrincipal | undefined,\n): string {\n if (!principal || principal.kind === ApplicationRuntimePrincipalKind.APPLICATION_BACKEND) {\n return buildRabbitUsername(applicationNamespace);\n }\n const sanitizedName = (principal.name ?? '').replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '');\n return `${applicationNamespace}-${principal.kind}-${sanitizedName}`;\n}\n\nfunction buildMinionConsumeRegex(wildoApplicationId: string, minionName: string): string {\n const escape = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const appId = escape(wildoApplicationId);\n const name = escape(minionName);\n // Two alternatives, and nothing else:\n // its tick queue — wildo.queue.<appId>.minion-tick.<name>\n // its OWN reply queue — wildo.reply.<appId>.<segment>.<podId>\n // The reply segment is IMPORTED from the same builder the minion's own AMQP\n // adapter uses, not reproduced here. It used to be hand-written as\n // `minion-<name>` with a comment saying it \"mirrors\" what the adapter emits —\n // which agreed only while every minion name survived sanitisation unchanged.\n // The application backend gets no segment at all (the builder returns\n // undefined for it), keeping the historical layout, so this cannot match its\n // replies.\n const replySegment = escape(\n buildRuntimePrincipalQueueSegment(ApplicationRuntimePrincipalKind.MINION, minionName) ?? '',\n );\n return `^(wildo\\\\.queue\\\\.${appId}\\\\.minion-tick\\\\.${name}(\\\\..*)?`\n + `|wildo\\\\.reply\\\\.${appId}\\\\.${replySegment}\\\\..*)$`;\n}\n\nexport const RabbitmqSelfInfraProviderModule: InfraProviderModule = {\n provider: InfraProvider.RABBITMQ_SELF,\n supportedCapabilities: [InfraCapability.QUEUING_SYSTEM],\n perPrincipalSecretBlobPaths: PER_PRINCIPAL_SECRET_BLOB_PATHS,\n\n plan(): InfraProviderPlanContribution {\n return {\n dockerComposeServices: ['rabbitmq'],\n k8sResources: ['templates/infra/k8s/internal/rabbitmq/deployment.yaml.hbs'],\n platformAdmin: {\n envVars: {\n RABBITMQ_HOST: 'rabbitmq',\n RABBITMQ_PORT: '5672',\n RABBITMQ_MANAGEMENT_PORT: '15672',\n },\n secretEnvVars: ['RABBITMQ_ADMIN_USERNAME', 'RABBITMQ_ADMIN_PASSWORD'],\n // Audience-1 only (management-API access). audience-2 platform-\n // service-scoped consumers (apps-manager / crontabs / file-\n // generator publish-consume creds via `provisionAllPlatformServices`)\n // are LD-8 territory, deferred to Slice 2.5 — they get their\n // own `mintPlatformServiceCredentials` method then.\n consumers: [\n InfraPlatformAdminConsumer.APPS_MANAGER,\n InfraPlatformAdminConsumer.COMPANION,\n ],\n },\n appRuntime: {\n // Declared for forward-compat with Slice 2.5's\n // `_merge_WildoApplicationConfig` integration. Not consumed by\n // any planner path in Slice 2 — the existing hard-coded values\n // at `wildo-application-lifecycle.service.ts:1796-1799` stay in\n // effect (host: 'localhost', port: 5672) until the planner\n // wires this slice's contribution.\n perAppConfigBlobPaths: {\n 'database.rabbitmq.host': 'rabbitmq',\n 'database.rabbitmq.port': 5672,\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 IRabbitMQManagementClient;\n const password = context.secretInputs[RABBITMQ_PASSWORD_PATH];\n if (!password) {\n throw new Error(\n `RabbitmqSelfInfraProviderModule.mintAppCredentials: ` +\n `secretInputs is missing '${RABBITMQ_PASSWORD_PATH}'. ` +\n `The orchestrator MUST supply the rabbit password — modules are upsert-only.`,\n );\n }\n\n const username = buildRabbitPrincipalUsername(context.applicationNamespace, context.principal);\n const permissionRegex = buildPermissionRegex(context.wildoApplicationId);\n // A MINION consumes exactly two things: its own tick queue, and its own RPC\n // REPLY queue. Both are admitted; everything else in the application's\n // namespace is refused.\n //\n // The reply half is why an earlier attempt at this failed. Reply queues used\n // to be `wildo.reply.<appId>.<podId>`, and `podId` is a per-PROCESS token\n // carrying no principal — so no regex could admit a minion's replies while\n // refusing the backend's, and narrowing `read` crash-looped the minion on\n // its own replies. `buildReplyQueueName` now embeds the owning runtime,\n // which is what makes this expressible at all.\n const readRegex = context.principal?.kind === ApplicationRuntimePrincipalKind.MINION && context.principal.name\n ? buildMinionConsumeRegex(context.wildoApplicationId, context.principal.name)\n : permissionRegex;\n\n // Slice 2.5c-3: optional per-app vhost. When the orchestrator\n // supplies a non-empty `applicationConfigInputs.vhost`, the module\n // ensures the vhost exists and sets permissions ON THAT vhost\n // (provides true vhost-level isolation). When omitted, the module\n // falls back to the default vhost `/` (legacy Slice 2 behavior:\n // permission-regex isolation only). This is the opt-in seam — apps\n // without an authored `backingServices.rabbitmq.vhost` continue to\n // share `/`.\n const vhost = context.applicationConfigInputs?.[VHOST_INPUT_KEY] || DEFAULT_VHOST;\n if (vhost !== DEFAULT_VHOST) {\n await adminClient.ensureVhost(vhost);\n }\n\n // PUT /api/users — idempotent upsert (replaces password + tags on conflict).\n await adminClient.putUser(username, password, []);\n\n // PUT /api/permissions — `configure` and `read` use the per-app\n // queue/reply regex; `write` widens to allow `amq.default` (the\n // default exchange RabbitMQ uses for direct routing) and the empty\n // string (broker-internal). Mirrors the legacy\n // `upsertTenantUserPermissions` write-regex shape so the Wonder\n // Todos behavior is unchanged.\n const writeRegex = `(^$|amq\\\\.default|${permissionRegex})`;\n await adminClient.setPermissions(vhost, username, {\n configure: permissionRegex,\n write: writeRegex,\n read: readRegex,\n });\n\n // PUT /api/topic-permissions — same regex on the topic exchange.\n await adminClient.setTopicPermissions(vhost, username, {\n exchange: TOPIC_EXCHANGE,\n write: permissionRegex,\n read: readRegex,\n });\n\n // Per-app-vhost cron delivery.\n //\n // A per-app vhost is a HARD broker isolation boundary: the platform\n // cron/minion publisher (`platform_crontabs_batches_manager`) — a single\n // global user that fans scheduled jobs into every app — cannot reach THIS\n // app's queues until granted access on THIS vhost. On the default vhost `/`\n // it already holds a broad publish grant (see `mintPlatformServiceCredentials`),\n // so the grant is only needed for a non-default per-app vhost.\n //\n // Scope it to this app's own queue namespace (`^wildo\\.(queue|reply)\\.<appId>\\..*`)\n // — the publisher gets exactly the reach it needs and no more, TIGHTER than\n // its broad default-vhost grant. It is PUBLISH-ONLY: `configure` for the\n // passive `checkQueue` existence probe the publisher runs before sending +\n // any declare, `write` (`amq.default`) for `basic.publish`; NO `read` (never\n // consumes) and NO topic permissions (uses the default exchange, not\n // `amq.topic`). The crontabs user is provisioned before any app\n // (apps-manager INIT Phase 4 < Phase 5), so it reliably exists here, and\n // `setPermissions` is an idempotent PUT — a re-init safely re-applies it.\n if (vhost !== DEFAULT_VHOST) {\n await adminClient.setPermissions(vhost, PLATFORM_CRONTABS_BATCHES_MANAGER_SERVICE_NAME, {\n configure: permissionRegex,\n write: writeRegex,\n read: '',\n });\n }\n\n // Bound this application's dead-letter queues (#2214) — on the default vhost too, where the\n // per-application pattern keeps it from touching any other application's queues. Re-applied on\n // every mint (backend and each minion) because it is an idempotent PUT; it reaches queues that\n // already exist. Revocation leaves it in place, like the vhost and the queues it governs (on the\n // shared default vhost it then matches nothing, which is harmless).\n //\n // FAIL-CLOSED, deliberately, and last: the credential is already upserted above, so a failure\n // here aborts the mint after the access is in place rather than before. A management API that\n // accepts users and permissions but refuses a policy is a broker this module cannot reason\n // about, and a mint that reported success there would leave the bound silently missing.\n await adminClient.ensureQueuePolicy(vhost, buildDeadLetterBoundPolicyName(context.wildoApplicationId), {\n pattern: buildDeadLetterBoundPolicyPattern(context.wildoApplicationId),\n definition: {\n 'message-ttl': RABBITMQ_DEAD_LETTER_QUEUE_BOUND.messageTtlMs,\n 'max-length': RABBITMQ_DEAD_LETTER_QUEUE_BOUND.maxLength,\n // semantic-literal-boundary: RabbitMQ's own overflow vocabulary.\n overflow: 'drop-head',\n },\n priority: RABBITMQ_DEAD_LETTER_QUEUE_BOUND.priority,\n });\n\n return {\n secretBlobValues: {\n [RABBITMQ_USERNAME_PATH]: username,\n // Echo the orchestrator-supplied password — proves the module\n // is upsert-only, not generator. The orchestrator persists\n // this exact value into `Wildo_Application_Secrets`.\n [RABBITMQ_PASSWORD_PATH]: password,\n },\n };\n },\n\n /**\n * Tear down the per-app rabbit user. RabbitMQ users are global, so\n * `deleteUser` removes the user (and its permissions on every vhost\n * it had access to) atomically.\n *\n * **Vhost retention** (Slice 4.A.2 / M6): when `mintAppCredentials`\n * provisioned a per-app vhost (Slice 2.5c-3), `revokeAppCredentials`\n * does NOT delete the vhost. Reasoning: vhost deletion drops every\n * queue and exchange inside it, which would destroy in-flight\n * messages mid-flight if a redeploy or restart is happening\n * concurrently. The user-deletion alone is sufficient to revoke\n * access; the empty vhost lingers as a paper trail. A future\n * \"app-deletion lifecycle\" slice can layer vhost cleanup with\n * proper drain semantics.\n *\n * **Caller status**: apps-manager runtime-principal declaration reconciliation\n * calls this for removed minions, and application withdrawal\n * (`deregisterApplication`, #1307) for the backend and every minion. The vhost\n * and its queues are kept; `restoreApplication` re-mints the user.\n *\n * **Defensive validation** (Slice 4.A.2 / L4): empty\n * `applicationNamespace` would call `DELETE /api/users/` and\n * silently 404; we fail-loud instead so a bad caller surfaces\n * immediately.\n */\n async revokeAppCredentials(context: AppCredentialMintingContext): Promise<void> {\n if (!context.applicationNamespace) {\n throw new Error(\n `RabbitmqSelfInfraProviderModule.revokeAppCredentials: ` +\n `applicationNamespace is empty. ` +\n `The orchestrator MUST supply a non-empty namespace.`,\n );\n }\n const adminClient = context.adminClient as IRabbitMQManagementClient;\n const username = buildRabbitPrincipalUsername(context.applicationNamespace, context.principal);\n await adminClient.deleteUser(username);\n },\n\n async mintPlatformServiceCredentials(\n context: PlatformServiceCredentialMintingContext,\n ): Promise<PlatformServiceCredentialMintingResult> {\n const adminClient = context.adminClient as IRabbitMQManagementClient;\n const password = context.secretInputs[PLATFORM_SERVICE_PASSWORD_INPUT_KEY];\n if (!password) {\n throw new Error(\n `RabbitmqSelfInfraProviderModule.mintPlatformServiceCredentials: ` +\n `secretInputs is missing '${PLATFORM_SERVICE_PASSWORD_INPUT_KEY}'. ` +\n `The orchestrator MUST supply the platform-service password — modules are upsert-only.`,\n );\n }\n\n // Username is the platform service identifier verbatim — preserves\n // the legacy convention from\n // `PlatformInfrastructureManagerService.provisionServiceCredentials`\n // (line 478: `username: serviceName`).\n const username = context.serviceName;\n const permissionRegex = buildPlatformServiceRegex(context.serviceName);\n\n // PUT /api/users — idempotent upsert.\n await adminClient.putUser(username, password, []);\n\n // Permissions: configure/read use the per-service regex; write\n // widens to allow `amq.default` + empty string (broker-internal),\n // matching the `upsertTenantUserPermissions` write-regex shape so\n // post-Slice-2.5 broker permissions match pre-Slice-2.5.\n const writeRegex = `(^$|amq\\\\.default|${permissionRegex})`;\n await adminClient.setPermissions(DEFAULT_VHOST, username, {\n configure: permissionRegex,\n write: writeRegex,\n read: permissionRegex,\n });\n\n // Topic permissions: same dot-escaped regex on amq.topic. The\n // legacy two-caller divergence (one path stripped the `^` and\n // produced `wildo\\.platform\\.<slug>\\..*`; the other produced\n // `wildo.platform.<slug>.*` with literal dots) is unified here on\n // the dot-escaped variant — see module JSDoc behavior-parity note.\n await adminClient.setTopicPermissions(DEFAULT_VHOST, username, {\n exchange: TOPIC_EXCHANGE,\n write: permissionRegex,\n read: permissionRegex,\n });\n\n return { username };\n },\n};\n"]}
@@ -1,7 +1,6 @@
1
1
  /**
2
2
  * `RedisSelfInfraProviderModule` — second concrete `InfraProviderModule`
3
- * (Slice 4.B.1 of `infra-provider-planner.md`, generalizing the
4
- * Slice 2 `RabbitmqSelfInfraProviderModule` pattern).
3
+ * (generalizing the `RabbitmqSelfInfraProviderModule` pattern).
5
4
  *
6
5
  * Implements the `REDIS_SELF` `InfraProvider` over the
7
6
  * `IRedisAclClient` transport (Valkey/Redis ACL commands, exposed by
@@ -1 +1 @@
1
- {"version":3,"file":"redis-self.infra.module.d.ts","sourceRoot":"","sources":["../../../../src/redis-self/redis-self.infra.module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsFG;AAEH,OAAO,EAOL,mBAAmB,EAKpB,MAAM,+BAA+B,CAAC;AA+GvC,eAAO,MAAM,4BAA4B,EAAE,mBA+J1C,CAAC"}
1
+ {"version":3,"file":"redis-self.infra.module.d.ts","sourceRoot":"","sources":["../../../src/redis-self/redis-self.infra.module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqFG;AAEH,OAAO,EAOL,mBAAmB,EAKpB,MAAM,+BAA+B,CAAC;AA+GvC,eAAO,MAAM,4BAA4B,EAAE,mBA+J1C,CAAC"}
@@ -1,7 +1,6 @@
1
1
  /**
2
2
  * `RedisSelfInfraProviderModule` — second concrete `InfraProviderModule`
3
- * (Slice 4.B.1 of `infra-provider-planner.md`, generalizing the
4
- * Slice 2 `RabbitmqSelfInfraProviderModule` pattern).
3
+ * (generalizing the `RabbitmqSelfInfraProviderModule` pattern).
5
4
  *
6
5
  * Implements the `REDIS_SELF` `InfraProvider` over the
7
6
  * `IRedisAclClient` transport (Valkey/Redis ACL commands, exposed by
@@ -1 +1 @@
1
- {"version":3,"file":"redis-self.infra.module.js","sourceRoot":"","sources":["../../../../src/redis-self/redis-self.infra.module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsFG;AAEH,OAAO,EAIL,eAAe,EACf,0BAA0B,EAC1B,aAAa,EAGb,+BAA+B,EAC/B,yBAAyB,GAE1B,MAAM,+BAA+B,CAAC;AAEvC;;;;;;GAMG;AACH,MAAM,mBAAmB,GAAG,IAAI,CAAC;AAEjC;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAE3B;;;;;;GAMG;AACH,MAAM,mBAAmB,GAAG,yBAAyB,CAAC;AACtD,MAAM,mBAAmB,GAAG,yBAAyB,CAAC;AACtD;;;;;;;GAOG;AACH,MAAM,+BAA+B,GAA0B,CAAC,mBAAmB,EAAE,mBAAmB,CAAC,CAAC;AAG1G;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,oBAA4B;IACtD,OAAO,oBAAoB,CAAC;AAC9B,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAS,2BAA2B,CAClC,oBAA4B,EAC5B,SAAkD;IAElD,IAAI,CAAC,SAAS,IAAI,SAAS,CAAC,IAAI,KAAK,+BAA+B,CAAC,mBAAmB,EAAE,CAAC;QACzF,OAAO,kBAAkB,CAAC,oBAAoB,CAAC,CAAC;IAClD,CAAC;IACD,MAAM,aAAa,GAAG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;QAC7D,6DAA6D;QAC7D,6DAA6D;QAC7D,4DAA4D;QAC5D,8DAA8D;QAC9D,8BAA8B;QAC9B,gEAAgE;QAChE,6DAA6D;QAC7D,8DAA8D;QAC9D,+DAA+D;QAC/D,8DAA8D;QAC9D,6CAA6C;QAC7C,MAAM,WAAW,CAAC,UAAU,CAAC;YAC3B,QAAQ;YACR,QAAQ;YACR,UAAU;SACX,CAAC,CAAC;QAEH,gEAAgE;QAChE,4BAA4B;QAC5B,wDAAwD;QACxD,MAAM,WAAW,CAAC,UAAU,EAAE,CAAC;QAE/B,OAAO;YACL,gBAAgB,EAAE;gBAChB,CAAC,mBAAmB,CAAC,EAAE,QAAQ;gBAC/B,8DAA8D;gBAC9D,2DAA2D;gBAC3D,qDAAqD;gBACrD,CAAC,mBAAmB,CAAC,EAAE,QAAQ;aAChC;SACF,CAAC;IACJ,CAAC;IAED;;;;;;;;;;;;;;;OAeG;IACH,KAAK,CAAC,oBAAoB,CAAC,OAAoC;QAC7D,IAAI,CAAC,OAAO,CAAC,oBAAoB,EAAE,CAAC;YAClC,MAAM,IAAI,KAAK,CACb,qDAAqD;gBACrD,iCAAiC;gBACjC,qDAAqD,CACtD,CAAC;QACJ,CAAC;QACD,MAAM,WAAW,GAAG,OAAO,CAAC,WAA8B,CAAC;QAC3D,MAAM,QAAQ,GAAG,2BAA2B,CAAC,OAAO,CAAC,oBAAoB,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;QAC9F,MAAM,WAAW,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;QACvC,+DAA+D;QAC/D,iEAAiE;QACjE,MAAM,WAAW,CAAC,UAAU,EAAE,CAAC;IACjC,CAAC;IAED,0DAA0D;IAC1D,8DAA8D;IAC9D,mDAAmD;IACnD,2CAA2C;CAC5C,CAAC","sourcesContent":["/**\n * `RedisSelfInfraProviderModule` — second concrete `InfraProviderModule`\n * (Slice 4.B.1 of `infra-provider-planner.md`, generalizing the\n * Slice 2 `RabbitmqSelfInfraProviderModule` pattern).\n *\n * Implements the `REDIS_SELF` `InfraProvider` over the\n * `IRedisAclClient` transport (Valkey/Redis ACL commands, exposed by\n * `RedisConnectionManagerService` after the Slice 4.B.1 5C policy/\n * transport split). Owns ALL per-app ACL policy — the per-app\n * keyPattern, the channel-pattern fan-out family, the per-app\n * username convention.\n *\n * **What this module reads from `AppCredentialMintingContext`**:\n * - `appSlug` — used as the **key-pattern** prefix\n * (`<appSlug>:*`). This MUST match the backend's effective\n * `dataServices.redis.keyPrefix`, which is the slug-derived key\n * namespace every backend write is rooted under (see\n * `engine/saas-backend-lib/src/databases/services/redis.service.ts`\n * `appPrefix` field — every `org:`/`global:` scope is composed with\n * that prefix). Slot owner: the SaaS app's authored config.\n * ACL invariant: `keyPrefix` MUST start with `<appSlug>:` so the\n * `~<appSlug>:*` grant covers every key the backend writes.\n * - `applicationNamespace` — used as the Redis ACL **username** AND\n * as the channel-pattern prefix (`<ns>#*`, `<ns>-request#*`,\n * `<ns>-response#*`). Mirrors the legacy username convention from\n * `wildo-application-lifecycle.service.ts:441` (`redisUsername =\n * ns`). Channels stay namespace-scoped because the Socket.IO Redis\n * adapter (`engine/saas-backend-lib/src/requests/service/websocket\n * .service.ts:1501`) uses the Redis username as its `key:` — the\n * ACL channel pattern MUST match that.\n * - `secretInputs['database.redis.password']` — orchestrator-supplied\n * password (module is upsert-only, never generator).\n * - `adminClient` — narrowed to `IRedisAclClient`.\n *\n * **Key vs channel pattern split** (2026-05-26 framework-correct fix):\n * Pre-fix, this module derived BOTH key and channel patterns from\n * `applicationNamespace` (`<ns>:*` for keys, `<ns>#*` for channels).\n * That was correct pre-Slice-3.6, when the backend used the username\n * to namespace keys too. Slice 3.6 moved key namespacing to\n * `dataServices.redis.keyPrefix` (default + recommended value\n * `<appSlug>:`) but the ACL provisioner was not updated — every per-app\n * Redis read/write returned `NOPERM No permissions to access a key`\n * because the ACL only granted `<ns>:*` while the backend wrote\n * `<appSlug>:*`. Fix: key pattern now derives from `appSlug`, channel\n * patterns continue to derive from the username/namespace (Socket.IO\n * adapter still uses the username as its channel key, so channels\n * stay correct unchanged).\n *\n * **What this module IGNORES from the context** (Slice 4.A.2 / M4\n * forward-compat documentation):\n * - `wildoApplicationId` — the keyPattern uses appSlug + the channel\n * patterns use namespace; the application id is redundant for both\n * (no globally-shared key namespace risk because slug/namespace\n * already disambiguate by tenant and environment).\n * - `applicationConfigInputs` — Redis_Self has no per-app authored\n * topology (no equivalent of RabbitMQ's vhost). Future modules may\n * read it for per-app db-index overrides etc.\n *\n * **Two audiences this module serves:**\n *\n * 1. **Audience-1 (platform-admin, declared via `plan().platformAdmin`)**:\n * cluster-wide ACL admin creds (`REDIS_HOST`, `REDIS_PORT`,\n * `REDIS_DATABASE` env + `REDIS_ADMIN_PASSWORD` secret env).\n * Consumers: `apps-manager` (mints per-app ACL users via\n * `mintAppCredentials`), `companion` (mirrors apps-manager admin\n * role for local dev).\n *\n * 2. **Audience-3 (app-scoped, via `plan().appRuntime` +\n * `mintAppCredentials`)**: per-customer-app Redis ACL user.\n * Username = `applicationNamespace`; keyPattern disambiguates by\n * the same namespace. Result threaded into\n * `Wildo_Application_Secrets.database.redis.{username, password}`\n * via `_merge_WildoApplicationSecrets`.\n *\n * **NOT served (D-4 of Slice 4.B locked decisions, 2026-05-10)**:\n * - **Audience-2 (platform-service-scoped)**: Redis is currently NOT\n * used for inter-platform-service messaging (RabbitMQ is the bus).\n * `mintPlatformServiceCredentials` is therefore not implemented.\n * When/if a platform service surfaces a Redis-scoped per-service\n * credential need, this module gains the method.\n *\n * **`revokeAppCredentials`** is called by apps-manager runtime-principal\n * declaration reconciliation when a minion is removed, and for every principal\n * (the application backend included) of an application withdrawn from the\n * platform (#1307). The lifecycle service passes the application namespace and\n * the principal; its ACL user is deleted; the keys it wrote stay (#1562 owns destruction).\n */\n\nimport {\n AppCredentialMintingContext,\n AppCredentialMintingResult,\n IRedisAclClient,\n InfraCapability,\n InfraPlatformAdminConsumer,\n InfraProvider,\n InfraProviderModule,\n InfraProviderPlanContribution,\n ApplicationRuntimePrincipalKind,\n buildMinionRedisKeyPrefix,\n type ApplicationRuntimePrincipal,\n} from '@wildo-ai/platform-config-lib';\n\n/**\n * Default Valkey port (matches `INFRA_DEFAULT_PORTS.VALKEY` in the\n * shared platform constants — duplicated here as a literal because\n * the planner output is consumed by the CLI which materializes it\n * into `Wildo_Application_Config` blob paths; the value is stable\n * and small).\n */\nconst DEFAULT_VALKEY_PORT = 6379;\n\n/**\n * Default DB index for app workloads. Wildo applications use db `0`\n * across the board; per-app DB-index isolation is intentionally NOT\n * modeled — keyPattern + ACL is the isolation seam.\n */\nconst DEFAULT_DB_INDEX = 0;\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 instead of drifting silently.\n */\nconst REDIS_USERNAME_PATH = 'database.redis.username';\nconst REDIS_PASSWORD_PATH = 'database.redis.password';\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> = [REDIS_USERNAME_PATH, REDIS_PASSWORD_PATH];\n\n\n/**\n * Compute the per-app Redis ACL username. Mirrors the existing\n * convention at `wildo-application-lifecycle.service.ts:441`\n * (`redisUsername = ns`) — username is the application namespace\n * (`<appSlug>-<environmentId>`), NOT the raw slug. Centralized here\n * so future changes touch one site.\n */\nfunction buildRedisUsername(applicationNamespace: string): string {\n return applicationNamespace;\n}\n\n/**\n * Per-principal ACL username (Step 2 / D17).\n *\n * The application backend keeps `applicationNamespace` VERBATIM — its username\n * must not move, or an existing deployment's ACL user is orphaned and a running\n * backend loses Redis on the next sync.\n *\n * A named principal appends its kind and name. The separator is `-`: an ACL\n * username is whitespace-delimited in `ACL SETUSER`, and the principal key's own\n * `:` is already meaningful in Redis KEY space, so reusing it in a username\n * blurs the two namespaces at a glance. Non-alphanumeric characters in a bucket\n * key are collapsed — the key is a TypeScript object key and may legally contain\n * `$` or `_`, while a username reaching the wire should stay conservative.\n *\n * Used by BOTH `mintAppCredentials` and `revokeAppCredentials`. That is the\n * point of it being a function: a revoke that derived the username differently\n * would delete the APPLICATION BACKEND's ACL user while believing it was\n * removing a minion's.\n */\nfunction buildRedisPrincipalUsername(\n applicationNamespace: string,\n principal: ApplicationRuntimePrincipal | undefined,\n): string {\n if (!principal || principal.kind === ApplicationRuntimePrincipalKind.APPLICATION_BACKEND) {\n return buildRedisUsername(applicationNamespace);\n }\n const sanitizedName = (principal.name ?? '').replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '');\n return `${applicationNamespace}-${principal.kind}-${sanitizedName}`;\n}\n\n/**\n * Compute the per-app Redis ACL key pattern.\n *\n * The pattern derives from `appSlug` (NOT `applicationNamespace`)\n * because the backend's effective key namespace is sourced from\n * `dataServices.redis.keyPrefix` (Slice 3.6 — see\n * `engine/saas-backend-lib/src/databases/services/redis.service.ts`\n * `appPrefix` field JSDoc) whose default + recommended value is\n * `<appSlug>:`. The ACL `~<appSlug>:*` rule must match the key shape\n * the backend writes; ANY namespace-derived ACL (the pre-2026-05-26\n * shape) would only grant `<ns>:*` and `NOPERM` every backend access.\n *\n * The channel patterns are computed separately from the username\n * (== applicationNamespace) inside `IRedisAclClient.upsertUser`,\n * because the Socket.IO Redis adapter uses the username as its\n * channel key (`engine/saas-backend-lib/src/requests/service/\n * websocket.service.ts:1501`). The two namespaces are split:\n * - key namespace = `<appSlug>:` (app-authored\n * `dataServices.redis.keyPrefix`)\n * - channel namespace = `<applicationNamespace>#` (Socket.IO adapter\n * key, == redisUsername)\n *\n * App-author contract (validated by `validateKeyPrefixContract`\n * downstream — see `databases.backend.schemas.ts`): if the SaaS app\n * overrides the default `keyPrefix`, the override MUST still start\n * with `<appSlug>:` so the `~<appSlug>:*` grant remains a superset\n * of the keys the backend writes.\n */\nfunction buildRedisKeyPattern(appSlug: string): string {\n return `${appSlug}:*`;\n}\n\nexport const RedisSelfInfraProviderModule: InfraProviderModule = {\n provider: InfraProvider.REDIS_SELF,\n supportedCapabilities: [InfraCapability.CACHE_MANAGER],\n perPrincipalSecretBlobPaths: PER_PRINCIPAL_SECRET_BLOB_PATHS,\n\n plan(): InfraProviderPlanContribution {\n return {\n dockerComposeServices: ['valkey'],\n k8sResources: ['templates/infra/k8s/internal/valkey/deployment.yaml.hbs'],\n platformAdmin: {\n envVars: {\n REDIS_HOST: 'valkey',\n REDIS_PORT: String(DEFAULT_VALKEY_PORT),\n REDIS_DATABASE: String(DEFAULT_DB_INDEX),\n },\n // ACL admin password is the only secret env. The legacy\n // `RedisConnectionManagerService.initializeAclAdmin` reads it\n // from `REDIS_ADMIN_PASSWORD`; the planner emits the key, the\n // CLI's `env-vars-builder` writes the value at sync time.\n secretEnvVars: ['REDIS_ADMIN_PASSWORD'],\n // Audience-1 only (ACL-admin access). No audience-2\n // platform-service-scoped Redis 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.\n // Per-app values (username/password) flow through\n // `perAppSecretBlobPaths` below.\n perAppConfigBlobPaths: {\n 'database.redis.host': 'valkey',\n 'database.redis.port': DEFAULT_VALKEY_PORT,\n 'database.redis.db': DEFAULT_DB_INDEX,\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 IRedisAclClient;\n const password = context.secretInputs[REDIS_PASSWORD_PATH];\n if (!password) {\n throw new Error(\n `RedisSelfInfraProviderModule.mintAppCredentials: ` +\n `secretInputs is missing '${REDIS_PASSWORD_PATH}'. ` +\n `The orchestrator MUST supply the Redis password — modules are upsert-only.`,\n );\n }\n if (!context.applicationNamespace) {\n throw new Error(\n `RedisSelfInfraProviderModule.mintAppCredentials: ` +\n `applicationNamespace is empty. ` +\n `The orchestrator MUST supply a non-empty namespace.`,\n );\n }\n if (!context.appSlug) {\n throw new Error(\n `RedisSelfInfraProviderModule.mintAppCredentials: ` +\n `appSlug is empty. ` +\n `The orchestrator MUST supply a non-empty appSlug — the ACL key ` +\n `pattern derives from it (must match the backend's effective ` +\n `\\`dataServices.redis.keyPrefix\\`, default \\`<appSlug>:\\`).`,\n );\n }\n\n const username = buildRedisPrincipalUsername(context.applicationNamespace, context.principal);\n // Key pattern derives from appSlug (matches backend `keyPrefix`),\n // channel patterns derive from username/namespace inside upsertUser\n // (matches Socket.IO adapter's `key:` config). See module JSDoc for\n // the full key-vs-channel-namespace split rationale.\n // A MINION is confined to its own namespace (D20); the application backend\n // keeps the app-wide pattern.\n //\n // This and the minion's `REDIS_KEY_PREFIX` are ONE COUPLED PAIR — a\n // mismatch DENIES every operation the minion performs, and the error names\n // an ACL rather than the mismatch. Both sides derive from\n // `buildMinionRedisKeyPrefix`, so they cannot drift.\n const keyPattern = context.principal?.kind === ApplicationRuntimePrincipalKind.MINION && context.principal.name\n ? `${buildMinionRedisKeyPrefix(context.appSlug, context.principal.name)}*`\n : buildRedisKeyPattern(context.appSlug);\n\n // ACL SETUSER — idempotent upsert. Replaces password + key\n // patterns + channel patterns + category allow/deny on conflict.\n //\n // **Atomicity guard** (Slice 6 audit / F-2, 2026-05-10): the\n // sequential `await upsertUser(); await persistAcl();` shape\n // intentionally relies on JavaScript exception propagation —\n // when `upsertUser` throws, the thrown error bubbles up the\n // async stack BEFORE `persistAcl` is reached, leaving the ACL\n // list on disk unchanged. The\n // `redis-self.infra.module.test.ts` \"atomicity guard\" case pins\n // this behavior. **DO NOT wrap this pair in a try/catch that\n // swallows the upsert error** — that would silently persist a\n // partially-applied state. Any future refactor that introduces\n // a try-block here MUST re-throw on the upsert error AND must\n // gate `persistAcl` on the upsert's success.\n await adminClient.upsertUser({\n username,\n password,\n keyPattern,\n });\n\n // Persist ACL list to disk so Valkey restarts don't lose tenant\n // users. Mirrors the legacy\n // `wildo-application-lifecycle.service.ts:540` pairing.\n await adminClient.persistAcl();\n\n return {\n secretBlobValues: {\n [REDIS_USERNAME_PATH]: username,\n // Echo the orchestrator-supplied password — proves the module\n // is upsert-only, not generator. The orchestrator persists\n // this exact value into `Wildo_Application_Secrets`.\n [REDIS_PASSWORD_PATH]: password,\n },\n };\n },\n\n /**\n * Tear down the per-app Redis ACL user. Valkey ACL users are\n * global (no vhost equivalent), so `deleteUser` removes the user\n * (and its key/channel access) atomically.\n *\n * **Caller status**: apps-manager runtime-principal declaration reconciliation\n * calls this for removed minions, and application withdrawal\n * (`deregisterApplication`, #1307) for the backend and every minion. The keys the\n * user wrote are kept; `restoreApplication` re-mints the user.\n *\n * **Defensive validation** (Slice 4.A.2 / L4 pattern): empty\n * `applicationNamespace` would call `ACL DELUSER` with an empty\n * username (Valkey would either error or silently no-op,\n * depending on version); we fail-loud instead so a bad caller\n * surfaces immediately.\n */\n async revokeAppCredentials(context: AppCredentialMintingContext): Promise<void> {\n if (!context.applicationNamespace) {\n throw new Error(\n `RedisSelfInfraProviderModule.revokeAppCredentials: ` +\n `applicationNamespace is empty. ` +\n `The orchestrator MUST supply a non-empty namespace.`,\n );\n }\n const adminClient = context.adminClient as IRedisAclClient;\n const username = buildRedisPrincipalUsername(context.applicationNamespace, context.principal);\n await adminClient.deleteUser(username);\n // Persist after deletion so the ACL list on disk stays in sync\n // with the in-memory state. Mirrors mintAppCredentials' pairing.\n await adminClient.persistAcl();\n },\n\n // No `mintPlatformServiceCredentials` (D-4 of Slice 4.B —\n // audience-2 not applicable to Redis_Self today). When a real\n // need surfaces, add the method here following the\n // `RabbitmqSelfInfraProviderModule` shape.\n};\n"]}
1
+ {"version":3,"file":"redis-self.infra.module.js","sourceRoot":"","sources":["../../../src/redis-self/redis-self.infra.module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqFG;AAEH,OAAO,EAIL,eAAe,EACf,0BAA0B,EAC1B,aAAa,EAGb,+BAA+B,EAC/B,yBAAyB,GAE1B,MAAM,+BAA+B,CAAC;AAEvC;;;;;;GAMG;AACH,MAAM,mBAAmB,GAAG,IAAI,CAAC;AAEjC;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAE3B;;;;;;GAMG;AACH,MAAM,mBAAmB,GAAG,yBAAyB,CAAC;AACtD,MAAM,mBAAmB,GAAG,yBAAyB,CAAC;AACtD;;;;;;;GAOG;AACH,MAAM,+BAA+B,GAA0B,CAAC,mBAAmB,EAAE,mBAAmB,CAAC,CAAC;AAG1G;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,oBAA4B;IACtD,OAAO,oBAAoB,CAAC;AAC9B,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAS,2BAA2B,CAClC,oBAA4B,EAC5B,SAAkD;IAElD,IAAI,CAAC,SAAS,IAAI,SAAS,CAAC,IAAI,KAAK,+BAA+B,CAAC,mBAAmB,EAAE,CAAC;QACzF,OAAO,kBAAkB,CAAC,oBAAoB,CAAC,CAAC;IAClD,CAAC;IACD,MAAM,aAAa,GAAG,CAAC,SAAS,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IACpG,OAAO,GAAG,oBAAoB,IAAI,SAAS,CAAC,IAAI,IAAI,aAAa,EAAE,CAAC;AACtE,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QAAQ;YACR,QAAQ;YACR,UAAU;SACX,CAAC,CAAC;QAEH,gEAAgE;QAChE,4BAA4B;QAC5B,wDAAwD;QACxD,MAAM,WAAW,CAAC,UAAU,EAAE,CAAC;QAE/B,OAAO;YACL,gBAAgB,EAAE;gBAChB,CAAC,mBAAmB,CAAC,EAAE,QAAQ;gBAC/B,8DAA8D;gBAC9D,2DAA2D;gBAC3D,qDAAqD;gBACrD,CAAC,mBAAmB,CAAC,EAAE,QAAQ;aAChC;SACF,CAAC;IACJ,CAAC;IAED;;;;;;;;;;;;;;;OAeG;IACH,KAAK,CAAC,oBAAoB,CAAC,OAAoC;QAC7D,IAAI,CAAC,OAAO,CAAC,oBAAoB,EAAE,CAAC;YAClC,MAAM,IAAI,KAAK,CACb,qDAAqD;gBACrD,iCAAiC;gBACjC,qDAAqD,CACtD,CAAC;QACJ,CAAC;QACD,MAAM,WAAW,GAAG,OAAO,CAAC,WAA8B,CAAC;QAC3D,MAAM,QAAQ,GAAG,2BAA2B,CAAC,OAAO,CAAC,oBAAoB,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;QAC9F,MAAM,WAAW,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;QACvC,+DAA+D;QAC/D,iEAAiE;QACjE,MAAM,WAAW,CAAC,UAAU,EAAE,CAAC;IACjC,CAAC;IAED,0DAA0D;IAC1D,8DAA8D;IAC9D,mDAAmD;IACnD,2CAA2C;CAC5C,CAAC","sourcesContent":["/**\n * `RedisSelfInfraProviderModule` — second concrete `InfraProviderModule`\n * (generalizing the `RabbitmqSelfInfraProviderModule` pattern).\n *\n * Implements the `REDIS_SELF` `InfraProvider` over the\n * `IRedisAclClient` transport (Valkey/Redis ACL commands, exposed by\n * `RedisConnectionManagerService` after the Slice 4.B.1 5C policy/\n * transport split). Owns ALL per-app ACL policy — the per-app\n * keyPattern, the channel-pattern fan-out family, the per-app\n * username convention.\n *\n * **What this module reads from `AppCredentialMintingContext`**:\n * - `appSlug` — used as the **key-pattern** prefix\n * (`<appSlug>:*`). This MUST match the backend's effective\n * `dataServices.redis.keyPrefix`, which is the slug-derived key\n * namespace every backend write is rooted under (see\n * `engine/saas-backend-lib/src/databases/services/redis.service.ts`\n * `appPrefix` field — every `org:`/`global:` scope is composed with\n * that prefix). Slot owner: the SaaS app's authored config.\n * ACL invariant: `keyPrefix` MUST start with `<appSlug>:` so the\n * `~<appSlug>:*` grant covers every key the backend writes.\n * - `applicationNamespace` — used as the Redis ACL **username** AND\n * as the channel-pattern prefix (`<ns>#*`, `<ns>-request#*`,\n * `<ns>-response#*`). Mirrors the legacy username convention from\n * `wildo-application-lifecycle.service.ts:441` (`redisUsername =\n * ns`). Channels stay namespace-scoped because the Socket.IO Redis\n * adapter (`engine/saas-backend-lib/src/requests/service/websocket\n * .service.ts:1501`) uses the Redis username as its `key:` — the\n * ACL channel pattern MUST match that.\n * - `secretInputs['database.redis.password']` — orchestrator-supplied\n * password (module is upsert-only, never generator).\n * - `adminClient` — narrowed to `IRedisAclClient`.\n *\n * **Key vs channel pattern split** (2026-05-26 framework-correct fix):\n * Pre-fix, this module derived BOTH key and channel patterns from\n * `applicationNamespace` (`<ns>:*` for keys, `<ns>#*` for channels).\n * That was correct pre-Slice-3.6, when the backend used the username\n * to namespace keys too. Slice 3.6 moved key namespacing to\n * `dataServices.redis.keyPrefix` (default + recommended value\n * `<appSlug>:`) but the ACL provisioner was not updated — every per-app\n * Redis read/write returned `NOPERM No permissions to access a key`\n * because the ACL only granted `<ns>:*` while the backend wrote\n * `<appSlug>:*`. Fix: key pattern now derives from `appSlug`, channel\n * patterns continue to derive from the username/namespace (Socket.IO\n * adapter still uses the username as its channel key, so channels\n * stay correct unchanged).\n *\n * **What this module IGNORES from the context** (Slice 4.A.2 / M4\n * forward-compat documentation):\n * - `wildoApplicationId` — the keyPattern uses appSlug + the channel\n * patterns use namespace; the application id is redundant for both\n * (no globally-shared key namespace risk because slug/namespace\n * already disambiguate by tenant and environment).\n * - `applicationConfigInputs` — Redis_Self has no per-app authored\n * topology (no equivalent of RabbitMQ's vhost). Future modules may\n * read it for per-app db-index overrides etc.\n *\n * **Two audiences this module serves:**\n *\n * 1. **Audience-1 (platform-admin, declared via `plan().platformAdmin`)**:\n * cluster-wide ACL admin creds (`REDIS_HOST`, `REDIS_PORT`,\n * `REDIS_DATABASE` env + `REDIS_ADMIN_PASSWORD` secret env).\n * Consumers: `apps-manager` (mints per-app ACL users via\n * `mintAppCredentials`), `companion` (mirrors apps-manager admin\n * role for local dev).\n *\n * 2. **Audience-3 (app-scoped, via `plan().appRuntime` +\n * `mintAppCredentials`)**: per-customer-app Redis ACL user.\n * Username = `applicationNamespace`; keyPattern disambiguates by\n * the same namespace. Result threaded into\n * `Wildo_Application_Secrets.database.redis.{username, password}`\n * via `_merge_WildoApplicationSecrets`.\n *\n * **NOT served (D-4 of Slice 4.B locked decisions, 2026-05-10)**:\n * - **Audience-2 (platform-service-scoped)**: Redis is currently NOT\n * used for inter-platform-service messaging (RabbitMQ is the bus).\n * `mintPlatformServiceCredentials` is therefore not implemented.\n * When/if a platform service surfaces a Redis-scoped per-service\n * credential need, this module gains the method.\n *\n * **`revokeAppCredentials`** is called by apps-manager runtime-principal\n * declaration reconciliation when a minion is removed, and for every principal\n * (the application backend included) of an application withdrawn from the\n * platform (#1307). The lifecycle service passes the application namespace and\n * the principal; its ACL user is deleted; the keys it wrote stay (#1562 owns destruction).\n */\n\nimport {\n AppCredentialMintingContext,\n AppCredentialMintingResult,\n IRedisAclClient,\n InfraCapability,\n InfraPlatformAdminConsumer,\n InfraProvider,\n InfraProviderModule,\n InfraProviderPlanContribution,\n ApplicationRuntimePrincipalKind,\n buildMinionRedisKeyPrefix,\n type ApplicationRuntimePrincipal,\n} from '@wildo-ai/platform-config-lib';\n\n/**\n * Default Valkey port (matches `INFRA_DEFAULT_PORTS.VALKEY` in the\n * shared platform constants — duplicated here as a literal because\n * the planner output is consumed by the CLI which materializes it\n * into `Wildo_Application_Config` blob paths; the value is stable\n * and small).\n */\nconst DEFAULT_VALKEY_PORT = 6379;\n\n/**\n * Default DB index for app workloads. Wildo applications use db `0`\n * across the board; per-app DB-index isolation is intentionally NOT\n * modeled — keyPattern + ACL is the isolation seam.\n */\nconst DEFAULT_DB_INDEX = 0;\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 instead of drifting silently.\n */\nconst REDIS_USERNAME_PATH = 'database.redis.username';\nconst REDIS_PASSWORD_PATH = 'database.redis.password';\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> = [REDIS_USERNAME_PATH, REDIS_PASSWORD_PATH];\n\n\n/**\n * Compute the per-app Redis ACL username. Mirrors the existing\n * convention at `wildo-application-lifecycle.service.ts:441`\n * (`redisUsername = ns`) — username is the application namespace\n * (`<appSlug>-<environmentId>`), NOT the raw slug. Centralized here\n * so future changes touch one site.\n */\nfunction buildRedisUsername(applicationNamespace: string): string {\n return applicationNamespace;\n}\n\n/**\n * Per-principal ACL username (Step 2 / D17).\n *\n * The application backend keeps `applicationNamespace` VERBATIM — its username\n * must not move, or an existing deployment's ACL user is orphaned and a running\n * backend loses Redis on the next sync.\n *\n * A named principal appends its kind and name. The separator is `-`: an ACL\n * username is whitespace-delimited in `ACL SETUSER`, and the principal key's own\n * `:` is already meaningful in Redis KEY space, so reusing it in a username\n * blurs the two namespaces at a glance. Non-alphanumeric characters in a bucket\n * key are collapsed — the key is a TypeScript object key and may legally contain\n * `$` or `_`, while a username reaching the wire should stay conservative.\n *\n * Used by BOTH `mintAppCredentials` and `revokeAppCredentials`. That is the\n * point of it being a function: a revoke that derived the username differently\n * would delete the APPLICATION BACKEND's ACL user while believing it was\n * removing a minion's.\n */\nfunction buildRedisPrincipalUsername(\n applicationNamespace: string,\n principal: ApplicationRuntimePrincipal | undefined,\n): string {\n if (!principal || principal.kind === ApplicationRuntimePrincipalKind.APPLICATION_BACKEND) {\n return buildRedisUsername(applicationNamespace);\n }\n const sanitizedName = (principal.name ?? '').replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '');\n return `${applicationNamespace}-${principal.kind}-${sanitizedName}`;\n}\n\n/**\n * Compute the per-app Redis ACL key pattern.\n *\n * The pattern derives from `appSlug` (NOT `applicationNamespace`)\n * because the backend's effective key namespace is sourced from\n * `dataServices.redis.keyPrefix` (Slice 3.6 — see\n * `engine/saas-backend-lib/src/databases/services/redis.service.ts`\n * `appPrefix` field JSDoc) whose default + recommended value is\n * `<appSlug>:`. The ACL `~<appSlug>:*` rule must match the key shape\n * the backend writes; ANY namespace-derived ACL (the pre-2026-05-26\n * shape) would only grant `<ns>:*` and `NOPERM` every backend access.\n *\n * The channel patterns are computed separately from the username\n * (== applicationNamespace) inside `IRedisAclClient.upsertUser`,\n * because the Socket.IO Redis adapter uses the username as its\n * channel key (`engine/saas-backend-lib/src/requests/service/\n * websocket.service.ts:1501`). The two namespaces are split:\n * - key namespace = `<appSlug>:` (app-authored\n * `dataServices.redis.keyPrefix`)\n * - channel namespace = `<applicationNamespace>#` (Socket.IO adapter\n * key, == redisUsername)\n *\n * App-author contract (validated by `validateKeyPrefixContract`\n * downstream — see `databases.backend.schemas.ts`): if the SaaS app\n * overrides the default `keyPrefix`, the override MUST still start\n * with `<appSlug>:` so the `~<appSlug>:*` grant remains a superset\n * of the keys the backend writes.\n */\nfunction buildRedisKeyPattern(appSlug: string): string {\n return `${appSlug}:*`;\n}\n\nexport const RedisSelfInfraProviderModule: InfraProviderModule = {\n provider: InfraProvider.REDIS_SELF,\n supportedCapabilities: [InfraCapability.CACHE_MANAGER],\n perPrincipalSecretBlobPaths: PER_PRINCIPAL_SECRET_BLOB_PATHS,\n\n plan(): InfraProviderPlanContribution {\n return {\n dockerComposeServices: ['valkey'],\n k8sResources: ['templates/infra/k8s/internal/valkey/deployment.yaml.hbs'],\n platformAdmin: {\n envVars: {\n REDIS_HOST: 'valkey',\n REDIS_PORT: String(DEFAULT_VALKEY_PORT),\n REDIS_DATABASE: String(DEFAULT_DB_INDEX),\n },\n // ACL admin password is the only secret env. The legacy\n // `RedisConnectionManagerService.initializeAclAdmin` reads it\n // from `REDIS_ADMIN_PASSWORD`; the planner emits the key, the\n // CLI's `env-vars-builder` writes the value at sync time.\n secretEnvVars: ['REDIS_ADMIN_PASSWORD'],\n // Audience-1 only (ACL-admin access). No audience-2\n // platform-service-scoped Redis 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.\n // Per-app values (username/password) flow through\n // `perAppSecretBlobPaths` below.\n perAppConfigBlobPaths: {\n 'database.redis.host': 'valkey',\n 'database.redis.port': DEFAULT_VALKEY_PORT,\n 'database.redis.db': DEFAULT_DB_INDEX,\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 IRedisAclClient;\n const password = context.secretInputs[REDIS_PASSWORD_PATH];\n if (!password) {\n throw new Error(\n `RedisSelfInfraProviderModule.mintAppCredentials: ` +\n `secretInputs is missing '${REDIS_PASSWORD_PATH}'. ` +\n `The orchestrator MUST supply the Redis password — modules are upsert-only.`,\n );\n }\n if (!context.applicationNamespace) {\n throw new Error(\n `RedisSelfInfraProviderModule.mintAppCredentials: ` +\n `applicationNamespace is empty. ` +\n `The orchestrator MUST supply a non-empty namespace.`,\n );\n }\n if (!context.appSlug) {\n throw new Error(\n `RedisSelfInfraProviderModule.mintAppCredentials: ` +\n `appSlug is empty. ` +\n `The orchestrator MUST supply a non-empty appSlug — the ACL key ` +\n `pattern derives from it (must match the backend's effective ` +\n `\\`dataServices.redis.keyPrefix\\`, default \\`<appSlug>:\\`).`,\n );\n }\n\n const username = buildRedisPrincipalUsername(context.applicationNamespace, context.principal);\n // Key pattern derives from appSlug (matches backend `keyPrefix`),\n // channel patterns derive from username/namespace inside upsertUser\n // (matches Socket.IO adapter's `key:` config). See module JSDoc for\n // the full key-vs-channel-namespace split rationale.\n // A MINION is confined to its own namespace (D20); the application backend\n // keeps the app-wide pattern.\n //\n // This and the minion's `REDIS_KEY_PREFIX` are ONE COUPLED PAIR — a\n // mismatch DENIES every operation the minion performs, and the error names\n // an ACL rather than the mismatch. Both sides derive from\n // `buildMinionRedisKeyPrefix`, so they cannot drift.\n const keyPattern = context.principal?.kind === ApplicationRuntimePrincipalKind.MINION && context.principal.name\n ? `${buildMinionRedisKeyPrefix(context.appSlug, context.principal.name)}*`\n : buildRedisKeyPattern(context.appSlug);\n\n // ACL SETUSER — idempotent upsert. Replaces password + key\n // patterns + channel patterns + category allow/deny on conflict.\n //\n // **Atomicity guard** (Slice 6 audit / F-2, 2026-05-10): the\n // sequential `await upsertUser(); await persistAcl();` shape\n // intentionally relies on JavaScript exception propagation —\n // when `upsertUser` throws, the thrown error bubbles up the\n // async stack BEFORE `persistAcl` is reached, leaving the ACL\n // list on disk unchanged. The\n // `redis-self.infra.module.test.ts` \"atomicity guard\" case pins\n // this behavior. **DO NOT wrap this pair in a try/catch that\n // swallows the upsert error** — that would silently persist a\n // partially-applied state. Any future refactor that introduces\n // a try-block here MUST re-throw on the upsert error AND must\n // gate `persistAcl` on the upsert's success.\n await adminClient.upsertUser({\n username,\n password,\n keyPattern,\n });\n\n // Persist ACL list to disk so Valkey restarts don't lose tenant\n // users. Mirrors the legacy\n // `wildo-application-lifecycle.service.ts:540` pairing.\n await adminClient.persistAcl();\n\n return {\n secretBlobValues: {\n [REDIS_USERNAME_PATH]: username,\n // Echo the orchestrator-supplied password — proves the module\n // is upsert-only, not generator. The orchestrator persists\n // this exact value into `Wildo_Application_Secrets`.\n [REDIS_PASSWORD_PATH]: password,\n },\n };\n },\n\n /**\n * Tear down the per-app Redis ACL user. Valkey ACL users are\n * global (no vhost equivalent), so `deleteUser` removes the user\n * (and its key/channel access) atomically.\n *\n * **Caller status**: apps-manager runtime-principal declaration reconciliation\n * calls this for removed minions, and application withdrawal\n * (`deregisterApplication`, #1307) for the backend and every minion. The keys the\n * user wrote are kept; `restoreApplication` re-mints the user.\n *\n * **Defensive validation** (Slice 4.A.2 / L4 pattern): empty\n * `applicationNamespace` would call `ACL DELUSER` with an empty\n * username (Valkey would either error or silently no-op,\n * depending on version); we fail-loud instead so a bad caller\n * surfaces immediately.\n */\n async revokeAppCredentials(context: AppCredentialMintingContext): Promise<void> {\n if (!context.applicationNamespace) {\n throw new Error(\n `RedisSelfInfraProviderModule.revokeAppCredentials: ` +\n `applicationNamespace is empty. ` +\n `The orchestrator MUST supply a non-empty namespace.`,\n );\n }\n const adminClient = context.adminClient as IRedisAclClient;\n const username = buildRedisPrincipalUsername(context.applicationNamespace, context.principal);\n await adminClient.deleteUser(username);\n // Persist after deletion so the ACL list on disk stays in sync\n // with the in-memory state. Mirrors mintAppCredentials' pairing.\n await adminClient.persistAcl();\n },\n\n // No `mintPlatformServiceCredentials` (D-4 of Slice 4.B —\n // audience-2 not applicable to Redis_Self today). When a real\n // need surfaces, add the method here following the\n // `RabbitmqSelfInfraProviderModule` shape.\n};\n"]}