Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Merge branch 'feat/adilsitos/eng-4966-stack-1' into feat/adilsitos/eng-4966-stack-2
adilson6b71e51c9c1c
diff --cc AGENTS.mdindex d430107cb7,1611242721..c40b94d8d0--- a/AGENTS.md+++ b/AGENTS.md@@@ -1,6 -1,186 +1,233 @@@- ## Feature Development+ # AGENTS.md- Check out CLAUDE.md for additional context on project file structure and general feature development.+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.++ ## Essential Commands++ - `make reviewable-api` / `make reviewable-ui` — lint:fix + type:check (run before PRs). Neither checks [`backend/CODE_QUALITY.md`](backend/CODE_QUALITY.md); review backend changes against it yourself.+ - `cd backend && npm run migration:new` — create new DB migration+ - `cd backend && npm run generate:schema` — regenerate Zod types from DB after migration changes+ - `make test-api-unit` / `make test-api-e2e` — run the Node backend suites in the FIPS image CI uses, against a throwaway database. Narrow with `SPEC=<pattern>`. See `backend/AGENTS.md` for why running `npm run test:e2e` directly can destroy your dev data.+ - `cd backend-go && make test` — run Go integration tests++ Both backend and frontend use `@app/*` as path alias to `./src/*`.++ ## Repository Structure++ Infisical is an open-source secret management platform. Monorepo layout:++ ```+ infisical/+ ├── backend/ # Fastify 4 API server (see backend/AGENTS.md)+ ├── backend-go/ # Go API server — partial rewrite (see backend-go/AGENTS.md)+ ├── frontend/ # React 19 SPA (see frontend/AGENTS.md)+ ├── wasm/ # Rust crates compiled to WASM for the frontend (see wasm/<crate>/AGENTS.md)+ ├── e2e/ # External Playwright suite — gates prod deploys against gamma (see e2e/AGENTS.md)+ ├── tests/ # Go blackbox suite — real containers, HTTP only (see tests/AGENTS.md)+ ├── docs/ # Documentation site (Mintlify-based)+ ├── build-versions.env # Versions pinned across several Dockerfiles (see Dependency Policy)+ ├── docker-compose.dev.yml # Local dev (PostgreSQL, Redis, backend, frontend, Nginx)+ ├── docker-compose.prod.yml # Production deployment stack+ ├── docker-compose.bdd.yml # BDD testing environment+ ├── docker-compose.e2e-dbs.yml # E2E test databases (Oracle, SAP, Snowflake, etc.)+ ├── Dockerfile.standalone-infisical # Standalone image (frontend + backend)+ ├── Dockerfile.fips.standalone-infisical # FIPS-compliant standalone image+ ├── .github/ # CI workflows, PR template+ └── AGENTS.md # This file+ ```++ - **`backend/`** — Fastify 4 API server, TypeScript, PostgreSQL via Knex, BullMQ queues. See [`backend/AGENTS.md`](backend/AGENTS.md) for architecture, patterns, and commands.+ - **`backend-go/`** — Go API server (partial rewrite), chi + chita framework, raw pgx queries, same PostgreSQL database. See [`backend-go/AGENTS.md`](backend-go/AGENTS.md) for architecture, patterns, and commands.+ - **`frontend/`** — React 19 SPA, Vite 8, TanStack Router + React Query, Tailwind CSS v4. See [`frontend/AGENTS.md`](frontend/AGENTS.md) for architecture, patterns, and commands.+ - **`wasm/`** — Rust crates that compile to WASM for the frontend. Generated bindings are committed under `frontend/src/lib/<crate>/` so the frontend builds without a Rust toolchain. Each crate has its own `AGENTS.md` with the rebuild command (e.g. [`wasm/ironrdp-decoder/AGENTS.md`](wasm/ironrdp-decoder/AGENTS.md)) — run it after any change to that crate's `src/` or `Cargo.toml` so source and bindings stay in sync.+ - **`docs/`** — Product documentation site. Has its own Dockerfile for building. Reference docs for up-to-date feature descriptions and API usage.+ - **`e2e/`** — Playwright suite that runs against a deployed environment (gamma) between deploy and prod promotion. Distinct from `backend/e2e-test/` (in-process Vitest). Failure blocks every prod-deploy job. Covers SCIM + SAML flows (SP-initiated, IdP-initiated, deactivation, response rejection) against a mock IdP we control — see [`e2e/AGENTS.md`](e2e/AGENTS.md) for the harness and the one-time gamma bootstrap.++ - **`tests/`** — Go blackbox suite. Boots a real Infisical in Docker and talks to it over HTTP only, so the same tests run against the Node and Go servers unchanged. Distinct from `backend/e2e-test/` (in-process Vitest, compiled against the Node source) and from `e2e/` (Playwright against a deployed gamma). `make test-suites` from `tests/` runs everything; see [`tests/AGENTS.md`](tests/AGENTS.md) before writing one.++ Enterprise features live in `backend/src/ee/` (services and routes), registered before community routes so they can override/extend them.++ ### Self-Hosted Deployment++ Infisical supports self-hosted deployment via Docker. Key considerations:+ - **`Dockerfile.standalone-infisical`** — single-container image with both frontend and backend; used for simple deployments.+ - **`Dockerfile.fips.standalone-infisical`** — FIPS 140-2 compliant variant for regulated environments. Be strict about not introducing dependencies that break FIPS compliance.+ - **`docker-compose.prod.yml`** — production compose with backend, PostgreSQL, and Redis.+ - New backend dependencies should be evaluated carefully — they affect container size, FIPS compliance, and the encryption boundary. Check `docs/` for self-hosted deployment documentation when in doubt.++ ### Dependency Policy++ `build-versions.env` holds versions that several Dockerfiles install, currently the bundled+ Infisical CLI. Each Dockerfile keeps a matching `ARG` default so external builders (Northflank,+ Render, a plain `docker build`) work without passing anything, and CI and compose override it from+ that file. `check-dockerfile-pins.yml` fails a PR when the defaults drift from it, so change the+ file and the `ARG` defaults together.++ Both `backend/` and `frontend/` enforce a minimum release age of 7 days for npm packages (configured via `.npmrc` in each directory). This means `npm install` will only resolve package versions published at least 7 days ago, as a supply-chain security measure.++ The backend installs with the npm bundled in Node 26 (11.x), which skips dependency install scripts unless `allowScripts` in `backend/package.json` approves them. The install still succeeds when a script is skipped, so a native addon that was not approved fails only when it is first `require`d. When adding or bumping a dependency with an install script, run `npm install-scripts ls` and approve or deny what it lists (`npm install-scripts approve <pkg>`).++ ## Cross-Cutting Patterns++ ### Backend Code Quality++ **Read [`backend/CODE_QUALITY.md`](backend/CODE_QUALITY.md) for every backend change, and check the change against it before calling the work done.** This applies to all work under `backend/`: new features, refactors, bug fixes, and reviews alike.++ It is a floor, not an exhaustive standard: user-understandable error messages and no pointless 500s, explicit validation on every API input, correct pagination when calling third-party APIs, avoiding deadlock conditions on a small connection pool (thread `tx`, keep transactions short), REST-aligned API interfaces (flag deviations for the author to confirm rather than implementing them silently), and audit log events an admin can actually read.++ That list describes what the guide currently covers; it is **not** a test for whether the guide applies. Do not skip it because a change does not look like one of those topics. Read it, then decide which items are relevant.++ ### Code Comments++ **Default to no comments.** One earns its place only by explaining *why*: a non-obvious constraint, a workaround, an ordering dependency, or logic that looks wrong until you know the reason.++ Never write: narration restating the next line; section headers inside a function (`// --- validation ---`); change history (`// Added retry logic`, `// NEW`); references to plans, tickets, PRs, or reviewers; docstrings restating the signature; commented-out code.++ Before finishing, delete any comment you added that only says what the code says.++ ### Product Analytics++ Read [`ANALYTICS.md`](ANALYTICS.md) before adding or changing product analytics. Every event has one owning producer: the frontend records UI exposure and intent, the application backend records accepted commands it can establish, and the system of record records durable outcomes. Define stable dimensions, cardinality, firing conditions, and dashboard consumers before implementation.++ ### Design System & Voice++ The v3 visual system (colors, typography, components, layout) and product voice/content tone are documented in [`DESIGN.md`](DESIGN.md). Read it before producing new UI or user-visible copy.++ ### Documentation++ **Use the `docs-style` skill for any work under `docs/`** (`.agents/skills/docs-style/`). It carries the procedure for the [Documentation Style Guide](docs/STYLE_GUIDE.md): what belongs on a page, and the sentence-level review pass Vale cannot check.++ If the user wrote or edited the docs prose themselves, don't just accept it. Tell them the `docs-style` skill can run the review pass over their changes, and offer to run it.++ The style guide covers writing for users (not implementers), Mintlify component usage, cross-referencing, page structure, the sentence-level writing rules in section 5, and the bolding and UI conventions in section 11.++ Run `make lint-docs-branch` after any change under `docs/`. It runs [Vale](https://vale.sh) over the docs and enforces the mechanical half of the style guide: sentence case in headings and frontmatter titles, product and vendor spellings, spelling against a curated vocabulary, `$` prompts in code blocks, and em dash density. See [docs/CONTRIBUTING.MD](docs/CONTRIBUTING.MD) for how to extend the vocabulary or suppress a rule. It lints only the `.mdx` files the branch touched; `make lint-docs` checks every page. The `Check docs style` GitHub workflow runs that same script, so local and CI agree by construction. Every rule except `Infisical.EmDashes` reports at error level, including `Infisical.UIActions` (click/tap where the verb should be select) and `Infisical.Contractions`, so the run fails if either one reports a finding. `Infisical.EmDashes` reports at warning level and never changes the exit code -- read the printed output, not just the status. Note that Vale cannot see prose indented four or more spaces inside components -- roughly half of this repo -- and reports nothing about what it skipped, so a clean run does not mean a nested page was checked.++ ### Auth & Permissions++ Auth modes (JWT, IDENTITY_ACCESS_TOKEN, SCIM_TOKEN) are extracted in `backend/src/server/plugins/auth/`. Authorization uses CASL (`@casl/ability`) with project-level and org-level permission checks — see `backend/AGENTS.md` for backend details and `frontend/AGENTS.md` for frontend permission hooks/HOCs. Note: `API_KEY` and `SERVICE_TOKEN` auth modes are deprecated — do not use them in new code.++ ### Org-Scoped Products++ PAM and Agent Vault are products over one implicit project per organization, not projects a user creates. Their URLs are `/organizations/$orgId/<product>/…` with no `$projectId`, the frontend resolves the project from the org (`useImplicitProjectId`), the backend bootstraps it lazily and blocks generic create and delete, their roles are admin or member only, and each has its own metered identities dimension (`pam_identities`, `agent_vault_identities`). When you add a `ProjectType.PAM` arm anywhere, add the Agent Vault arm beside it. See `backend/src/ee/services/pam/AGENTS.md` and `backend/src/ee/services/agent-vault/AGENTS.md`.++ ### Single-Project Products++ Secret Scanning has one active project per organization (the newest). Like Certificate Manager, its URLs are `/organizations/$orgId/secret-scanning/…` with no `$projectId`; legacy orgs can still hold several projects, so the frontend pins the one being viewed (see `frontend/AGENTS.md`). New orgs and sub-orgs get it at creation (`bootstrapSecretScanningProject`), older orgs lazily from `GET /api/v2/secret-scanning/project`, and `projectId` is optional on its API (`inject-secret-scanning-project-id`). Do not add a project picker or a way to create more Secret Scanning projects.++ ### Service Factory + Manual DI (Backend)++ No IoC container in either backend. Every service is a factory function with explicit dependencies.+ - **Node.js**: Wired in `backend/src/server/routes/index.ts` — see `backend/AGENTS.md`.+ - **Go**: Wired in `backend-go/internal/server/api/api.go` via `NewRegistry()` — see `backend-go/AGENTS.md`.++ ### Interface Pattern (Go)++ Both handlers and services define narrow interfaces for their dependencies (consumer-defined interfaces). Only expose methods or fields that are needed — keep everything else private. This enables testability and loose coupling.++ ### Alerting++ All user-facing "notify me when X happens" features share one module: `backend/src/services/alert/`. It owns the alert CRUD, the channel stack (email, Slack, webhook, PagerDuty), recipients, dedup, history, and dispatch. To alert on a new resource, register an `IResourceAlertProvider` on the shared registry — do not stand up a per-domain alert service, channel table, or notification cron. See `backend/AGENTS.md` for the provider contract and invariants.++ **If you touch a code path that deletes or detaches an alertable resource, it must reap that resource's alerts.** `alerts.resourceId` has no foreign key, so nothing cascades and the alert is left dangling. Use `alertService.deleteAlertsForDeletedResource` when the row is gone (unscoped, reaps across every org) and `deleteAlertsForResource` when the resource only left a scope. See the alerting invariants in `backend/AGENTS.md`.++ ### Approvals++ All "someone has to approve this before it happens" features share one module:+ `backend/src/services/approval-policy/`, which owns policies, requests, steps, grants, break-glass, and+ the generic `/v1/<policy-type>/approval-policies` endpoints. Current types: PAM access, certificate+ requests, code signing.++ A policy type plugs in through **one** extension point, a `TApprovalResource` (see its doc comment),+ constructed with its own dependencies and registered in the `approvalResources` map in+ `server/routes/index.ts`; that also gives it the generic `/v1/approval-policies/<type>/...` endpoints,+ which every type now uses for policy CRUD, requests, approve, reject and grant revocation. **Do not stand up a per-product approval service, request table, or review+ endpoint**: `access-approval-*` and `secret-approval-*` predate this module and are what we are+ converging away from. A product-facing service on top of it (PAM's `pam-access-request-service.ts`) is+ for product vocabulary only: resolving the resource a request names, notifications, and read models.+ Any rule about what is *allowed* belongs in the resource, or the product's own API and the shared API+ stop agreeing.++ Auto-approval rules (`approval-policy/auto-approval/`) live on the policy and are evaluated once in+ `createRequest`, outside any transaction, failing closed. Another service becomes checkable by adding a+ provider to `AUTO_APPROVAL_PROVIDER_REGISTRY`, keyed by its App Connection, not by per-product code. A+ resource gates them per request with `allowsAutoApproval`. A policy may have rules and no approvers (no+ steps): then a request no rule approves is refused at submission, and only break-glass gets past it. The+ engine itself adds a reuse check (`not-used-before`) to every input, answered from the policy's approved+ requests' evidence and claimed under an advisory lock in the auto-approve transaction. The+ stored evidence holds data fetched from that service, so responses return only its outcome (`autoApproval`),+ never `autoApprovalEvidence`.+++A policy on the global approval system can hand its requests to a delegated approval system (ServiceNow)++through `backend/src/services/delegated-approval/`, which owns the `delegated_approval_policies` and++`delegated_approval_requests` rows. Secret access policies opt in with `delegatedApproval: { type, connectionId }`++on create and update (`secret-access-approval-global-policy-bridge-service.ts`). A delegated policy has no++Infisical approvers, cannot use break glass (soft enforcement or bypassers) or self approval, cannot be updated++while it has pending requests, and a policy on the legacy approval system can never be delegated. Keep those++rules in `assertDelegatedApprovalPolicyConstraints` when another policy type opts in. Only secret access++policies may opt in today: `assertPolicyTypeSupportsDelegatedApproval` refuses the rest, and secret change++policies return it as a 400 rather than dropping the field.++++Delivery to the delegated system is asynchronous and goes through the event outbox (see `backend/AGENTS.md`).++`delegatedApprovalService.createRequest` writes the `delegated_approval_requests` row and emits++`delegated-approval.request.dispatch-requested` (`delegated-approval-events.ts`) in the caller's transaction, so++the dispatch is exactly as durable as the request; never enqueue it after commit. The++`delegated-approval-dispatch` consumer (`delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts`)++calls the provider inline and moves the row `pending_dispatch` → `waiting_approval` (storing the provider's++record id in `providerRequestId`) or `failed_dispatch` with a `statusReason` a user can read. A transient++failure returns `Retry`, so the outbox backs off and tries again (up to `MAX_OUTBOX_ATTEMPTS`), and the reason++text promises that retry. The outbox flags the last attempt (`TEvent.isFinalAttempt`), and a transient failure++on it closes the request instead: the delegated row goes `failed` with a reason that says so, the approval++request goes `cancelled`, and the consumer returns `Failed`. A terminal failure the consumer raises itself (an++`UnrecoverableError`: SITE_URL unset, the app connection gone, the policy no longer delegated) stays++`failed_dispatch` on every attempt, because an admin can fix the cause and resend. A user resends a++`failed_dispatch` request with `POST /api/v1/access-approvals/requests/:requestId/retry-delegated-dispatch`. The++product's bridge checks who may retry, and `delegatedApprovalService.retryDispatch` checks the request can be++retried and emits the same event with no transaction. The event id is derived (uuid v5) from the delegated++request id and that row's `updatedAt`, so repeated emits of one attempt collapse on the outbox's++`(consumer, eventId)` key, and a later resend still inserts after the status write bumps `updatedAt`. A batch dispatches up to 10 different requests at once;++events for one request stay serial. A second event for a request that was already delivered is marked delivered++without calling the provider. A delegated request has++no Infisical approvers, so `POST /api/v1/access-approvals/requests/:requestId/cancel-delegated-dispatch` is the only way to close++one from Infisical: the requester, or anyone who can edit the policy, sets it `cancelled`, which is also how a++policy blocked by pending requests is freed for editing. Every provider implements `TDelegatedApprovalProvider` against the same++`TDelegatedApprovalDispatchInput` and registers in `DELEGATED_APPROVAL_PROVIDER_MAP`++(`dispatch/providers/<name>/`); a new policy type adds an arm to `TDelegatedApprovalDispatchDetails` and a++builder in `DELEGATED_APPROVAL_DISPATCH_DETAILS_BUILDER_MAP` rather than branching in a provider. The consumer++reads from the primary, never checks the license, and treats bullmq's `UnrecoverableError` as the terminal failure++signal, returning `Failed` for it and `Retry` for anything else until the last attempt. The callback contract (token issuance now, the inbound route and approve / reject later) is its own++module, `backend/src/services/delegated-approval-callback/`, so the delegated approval module never grows a++callback branch. A request gets exactly one callback token for its whole life: it is random, issued on the first++dispatch attempt, and stored in `encryptedCallbackToken` under the SecretManager KMS key of the request's project++(`getOrIssueCallbackToken` resolves the project from the delegated request itself, since the inbound route knows++only that row) so every retry resends the same value; the inbound side finds the row by the provider's record id++and compares the decrypted token with the presented one. Never send a provider a token that differs from the one++stored for the request; the provider keeps the first token it was given and cannot be told another, so a mismatch++is unrecoverable.+++ ### Object Storage++ New product files go to S3 through `backend/src/services/object-storage/`, not a product's own S3 client (PAM+ recordings predate it and haven't moved). A product+ registers a namespace (record-first path like `sessions/{sessionId}/logs/{file}`, checked for naming collisions at+ boot) and the layer builds org-first keys, signs links, and applies the retention tag and, for default storage on Infisical Cloud, a daily upload cap. Storage is+ `default` (the instance's bucket, `OBJECT_STORAGE_S3_*`) or `external` (the customer's, through an AWS connection);+ use those two words everywhere.++ ### API Layer (Frontend)++ React Query + Axios with query key factories per domain. Each API domain in `frontend/src/hooks/api/` has `queries.tsx`, `mutations.tsx`, and `types.tsx` — see `frontend/AGENTS.md` for conventions.++ ## Keeping AGENTS.md Up to Date++ When making significant changes to the codebase (new services, architectural shifts, new patterns, major refactors), update the relevant AGENTS.md file(s) with high-level findings. This includes this root file for cross-cutting concerns, `backend/AGENTS.md` for Node.js backend changes, `backend-go/AGENTS.md` for Go backend changes, and `frontend/AGENTS.md` for frontend changes. The goal is to keep these files accurate as living documentation so future sessions start with correct context.++ ## Wiring a New Full-Stack Feature++ 1. **Backend**: Create service module, migration, wire DI, add routes — see checklist in `backend/AGENTS.md`+ 2. **Frontend**: Add API hooks in `src/hooks/api/<domain>/`, create page/view, wire route — see `frontend/AGENTS.md` for routing and component patterns+ 3. Check the backend work against [`backend/CODE_QUALITY.md`](backend/CODE_QUALITY.md)+ 4. Run `make reviewable-api` and `make reviewable-ui` before submitting## Backend Developmentdiff --cc backend/AGENTS.mdindex 51dc6ee328,a78579136c..914abfd2a3--- a/backend/AGENTS.md+++ b/backend/AGENTS.md@@@ -774,39 -774,69 +774,71 @@@ Invariants worth knowing before extendian event is exactly as durable as the business write. Enqueueing to Redis after commit loses the eventwhenever the pod dies or Redis is down in that window. It's not alert-specific:`alert-event-consumer.ts` is one consumer on the shared registry, and anything else that needs-at-least-once delivery of a domain event registers next to it.+at-least-once delivery of a domain event registers next to it. The delegated approval dispatch consumer+(`delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts`) is the second: it calls the external+approval system inline from `handle()` and maps the outcome to `Delivered` / `Retry` / `Failed`, with no queue hop.**Naming:** the outbox is an implementation detail to both sides of it. Emitters depend on- `TEventEmitter` and pass a `TEventInput`; consumers implement `IEventConsumer`, receive `TEvent[]`- (the row minus its lock, attempt, and status columns) and return `TEventConsumerResult` with an- `EventResultStatus`. Names with "outbox" in them (the DAL, queue, cron jobs, metrics,- `EventOutboxStatus`, `TOutboxFlushKey`) describe the mechanism and stay inside the module and its- wiring. A dependency field for the emitter is `eventEmitter`, not `eventOutboxService`.+ `TEventEmitter` and pass a `TEventInput`; consumers implement `IEventConsumer`, receive `TEvent[]` (the+ CloudEvents envelope) and return `TEventConsumerResult` with an `EventResultStatus`. Names with "outbox"+ in them (the DAL, queue, cron jobs, metrics, `EventOutboxStatus`, `TOutboxFlushKey`) describe the+ mechanism and stay inside the module and its wiring. A dependency field for the emitter is+ `eventEmitter`, not `eventOutboxService`.++ #### How to implement an event++ Events are public API: their names and shapes are a contract we can't take back. Read the+ [Event Standards and Versioning ADR](https://app.notion.com/p/3c2564692229804b93a1d0ff069016d6) and, for+ an event about something being created, updated or deleted, the+ [CRUD Event Design ADR](https://app.notion.com/p/3ff5646922298176bd92f298433f7d60). The steps below+ summarise them.++ 1. **Define it with `defineEvent`, in the domain that emits it.** It goes in that domain's `*-events.ts`+ (eg `secret-folder/secret-folder-events.ts`), never in a consumer (see "The event contract belongs to+ the domain" below). The name is `com.infisical.<domain>.<entity>.<action>.v<version>`: lower-kebab+ segments, a singular entity, a past-tense action, and words a customer recognises rather than+ implementation detail. `defineEvent` throws on boot for a name that breaks this. Start at `v1` and+ bump only for a breaking change to `data`; adding an optional field is not one.+ 2. **Give `data` what a consumer needs to decide whether it cares and to find the thing again, not the+ thing itself.** That is ids, the owning scope (eg `projectId`) and the location where there is one+ (eg `environment` and `secretPath`). Consumers read the current state from the source. Never put+ secret values, credentials or other sensitive content in an event.+ 3. **For create, update and delete, use one `modified` event per entity.** Its `data` carries+ `modificationType` (`created`, `updated` or `deleted`) and, on an update that changed a field the+ event carries, `previous` with only those fields' earlier values. A change that keeps the entity's id+ is one `updated` event (eg a folder rename). A change that gives it a new id is `deleted` for the old+ id and `created` for the new one (eg a secret move). A delete that cascades is one event for the+ entity deleted, which covers everything beneath it. The secret, folder and secret import events+ (`secret-v2-bridge/secret-events.ts`, `secret-folder/secret-folder-events.ts`,+ `secret-import/secret-import-events.ts`) are the reference.+ 4. **Emit it in the transaction of the write it describes**, so the event is exactly as durable as that+ write: `SomeEventV1.emit(eventEmitter, data, tx)`, or `build` several and pass them to+ `eventEmitter.emit(events, tx)` in one call. Omit `tx` only when there is no such write left to be+ atomic with (eg after it already committed); the insert then runs on its own. Nothing around the emit+ is caught: a swallowed insert failure hands the caller a poisoned transaction (`25P02` on its next+ statement). When several services emit the same event, give it one helper in the domain's events+ file rather than repeating the call.- **Emitting:** `eventEmitter.emit(event, tx)`. Pass the transaction of the write the event describes, so the event is exactly as durable as that write. Omit `tx` only when there is no such write left to be atomic with (for example after it already committed); the insert then runs on its own.+ ```ts+ await folderDAL.transaction(async (tx) => {+ const folder = await folderDAL.create({ ... }, tx);+ await FolderModifiedEventV1.emit(+ eventEmitter,+ { folderId: folder.id, projectId, environment, secretPath, modificationType: EventModificationType.Created },+ tx+ );+ });+ ```- ```ts- await someDAL.transaction(async (tx) => {- const request = await approvalRequestDAL.create({ ... }, tx);- await eventEmitter.emit(- {- eventType: "approval.workflow.request_opened",- payload: { orgId, projectId, resourceType: "approval.workflow", resourceId: policyId, targetIds: [request.id] }- },- tx- );- });- ```+ 5. **Consume it with an `IEventConsumer`** whose `subscribesTo` matches the definition's `type` and+ whose `dataSchema` is the definition's `data` schema. Nothing is written for an event no consumer+ subscribes to. Only `subscribesTo` runs before the insert, in memory: whether a customer configured+ anything for the resource is decided in the worker, and a row nobody wanted is marked `Delivered` and+ pruned within a day. If that ever matters for a hot event type, cache inside the consumer rather than+ adding a read to the emit path.- - Only `subscribesTo(eventType)` runs before the insert, in memory. Whether a customer configured- anything for this resource is decided in the worker; a row nobody wanted is marked `Delivered` and- pruned within a day. If that ever matters for a hot event type, cache inside the consumer rather than- adding a read to the emit path.- - Nothing is caught. A swallowed insert failure hands the caller a poisoned transaction (`25P02` on its- next statement), and a payload that fails the consumer's `payloadSchema` is a bug at the emit site.- Both checks run before any DB access.+ Events named before the ADR (eg `identity.authentication.auth-method-changed`) keep their names until+ they move to it.**How delivery works:**diff --cc backend/src/server/routes/index.tsindex 1f492a891a,fefd2b60a5..90a518e5bd--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@@ -864,10 -873,9 +878,11 @@@ export const registerRoutes = asyncconst approvalPolicyStepsDAL = approvalPolicyStepsDALFactory(db);const approvalPolicyStepApproversDAL = approvalPolicyStepApproversDALFactory(db);const approvalPolicyBypassersDAL = approvalPolicyBypassersDALFactory(db);+ const approvalPolicyAutoApprovalDAL = approvalPolicyAutoApprovalDALFactory(db);const approvalPolicySecretEnvironmentDAL = approvalPolicySecretEnvironmentDALFactory(db);const approvalRequestDAL = approvalRequestDALFactory(db);+ const delegatedApprovalPolicyDAL = delegatedApprovalPolicyDALFactory(db);+ const delegatedApprovalRequestDAL = delegatedApprovalRequestDALFactory(db);const secretChangeGlobalPolicyBridgeDAL = secretChangeGlobalPolicyBridgeDALFactory(db);const roleDAL = roleDALFactory(db);const pkiAlertHistoryDAL = pkiAlertHistoryDALFactory(db);@@@ -2651,7 -2722,92 +2729,8 @@@additionalPrivilegeDAL});- const secretAccessApprovalGlobalPolicyBridgeService = secretAccessApprovalGlobalPolicyBridgeServiceFactory({- projectDAL,- permissionService,- projectEnvDAL,- userDAL,- groupDAL,- accessApprovalPolicyDAL,- approvalPolicyDAL,- approvalPolicyStepsDAL,- approvalPolicyStepApproversDAL,- approvalPolicyBypassersDAL,- approvalPolicySecretEnvironmentDAL,- secretAccessApprovalGlobalPolicyBridgeDAL,- approvalRequestDAL,- approvalRequestStepsDAL,- approvalRequestStepEligibleApproversDAL,- approvalRequestGrantsDAL,- additionalPrivilegeDAL- });-- const secretAccessApprovalGlobalRequestBridgeService = secretAccessApprovalGlobalRequestBridgeServiceFactory({- projectDAL,- projectEnvDAL,- permissionService,- userDAL,- userGroupMembershipDAL,- approvalRequestDAL,- approvalRequestStepsDAL,- approvalRequestStepEligibleApproversDAL,- approvalRequestApprovalsDAL,- approvalRequestGrantsDAL,- additionalPrivilegeDAL,- secretAccessApprovalGlobalPolicyBridgeDAL,- secretAccessApprovalGlobalRequestBridgeDAL,- smtpService,- notificationService,- kmsService,- projectSlackConfigDAL,- microsoftTeamsService,- projectMicrosoftTeamsConfigDAL,- queueService,- secretAccessApprovalGlobalResource- });-- const accessApprovalPolicyService = accessApprovalPolicyServiceFactory({- accessApprovalPolicyDAL,- accessApprovalPolicyApproverDAL,- accessApprovalPolicyBypasserDAL,- accessApprovalPolicyEnvironmentDAL,- groupDAL,- permissionService,- projectEnvDAL,- projectDAL,- userDAL,- accessApprovalRequestDAL,- accessApprovalRequestReviewerDAL,- additionalPrivilegeDAL,- approvalPolicyDAL,- approvalPolicySecretEnvironmentDAL,- secretAccessApprovalGlobalPolicyBridge: secretAccessApprovalGlobalPolicyBridgeService- });-- const accessApprovalRequestService = accessApprovalRequestServiceFactory({- projectDAL,- permissionService,- accessApprovalRequestReviewerDAL,- accessApprovalPolicyDAL,- secretAccessApprovalGlobalResource,- secretAccessApprovalGlobalRequestBridge: secretAccessApprovalGlobalRequestBridgeService,- accessApprovalRequestDAL,- projectEnvDAL,- userDAL,- smtpService,- accessApprovalPolicyApproverDAL,- projectSlackConfigDAL,- kmsService,- groupDAL,- microsoftTeamsService,- projectMicrosoftTeamsConfigDAL,- notificationService,- additionalPrivilegeDAL,- queueService- });-const secretReplicationService = secretReplicationServiceFactory({+ eventEmitter: eventOutboxService,secretTagDAL,secretVersionTagDAL,secretDAL,diff --cc backend/src/services/alert/alert-event-consumer.test.tsindex 0342925398,98ee6cce38..e9a85d7b47--- a/backend/src/services/alert/alert-event-consumer.test.ts+++ b/backend/src/services/alert/alert-event-consumer.test.ts@@@ -24,15 -24,15 +24,16 @@@ const makePayload = (overrides?: Record...overrides});- const makeEvent = (overrides?: Partial<TEvent>): TEvent =>- ({- id: 1,- eventType: EVENT_TYPE,- payload: makePayload(),- occurredAt: new Date(),- isFinalAttempt: false,- ...overrides- }) as TEvent;+ const makeEvent = (overrides?: Partial<TEvent>): TEvent => ({+ specversion: "1.0",+ id: "event-1",+ source: "urn:infisical:approval",+ type: EVENT_TYPE,+ time: new Date().toISOString(),+ data: makePayload(),++ isFinalAttempt: false,+ ...overrides+ });const buildConsumer = (opts?: {alerts?: unknown[];diff --cc backend/src/services/delegated-approval/delegated-approval-events.tsindex 0e9edc777d,0000000000..3c346512d2mode 100644,000000..100644--- a/backend/src/services/delegated-approval/delegated-approval-events.ts+++ b/backend/src/services/delegated-approval/delegated-approval-events.ts@@@ -1,32 -1,0 +1,44 @@@+import { Knex } from "knex";++import { v5 as uuidv5 } from "uuid";+import { z } from "zod";++import { TEventEmitter } from "@app/services/event-outbox/event-outbox-types";++export const DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT = "delegated-approval.request.dispatch-requested";+++// Namespaces the event ids derived below, so they can't collide with ids derived the same way elsewhere.++const DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT_ID_NAMESPACE = "95183bf5-9016-4f76-9263-b7682f7e6a14";+++export const DelegatedApprovalDispatchRequestedPayloadSchema = z.object({+ delegatedRequestId: z.string().uuid()+});++export type TDelegatedApprovalDispatchRequestedPayload = z.infer<+ typeof DelegatedApprovalDispatchRequestedPayloadSchema+>;+- // updatedAt is the attempt. Repeated retries of one failure share it and collapse on the outbox unique- // key. A request id alone would not: the previous row is still retained (delivered for a day, failed for- // 30 days), so a later resend has to insert beside it. The consumer's status write bumps updatedAt,- // which is what gives that resend a new key.++// The id is derived from updatedAt, which is the attempt. Repeated retries of one failure share it and++// the outbox drops all but the first. A request id alone would not do: the previous row is still retained++// (delivered for a day, failed for 30 days), so a later resend has to insert beside it. The consumer's++// status write bumps updatedAt, which is what gives that resend a new id.++export const buildDelegatedApprovalDispatchRequestedEventId = ({++ delegatedRequestId,++ updatedAt++}: TDelegatedApprovalDispatchRequestedPayload & { updatedAt: Date }): string =>++ uuidv5(`${delegatedRequestId}:${updatedAt.toISOString()}`, DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT_ID_NAMESPACE);+++export const emitDelegatedApprovalDispatchRequested = (+ eventEmitter: TEventEmitter,+ { delegatedRequestId, updatedAt }: TDelegatedApprovalDispatchRequestedPayload & { updatedAt: Date },+ tx?: Knex+): Promise<void> =>+ eventEmitter.emit(- {- eventType: DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,- idempotencyKey: `${DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT}:${delegatedRequestId}:${updatedAt.toISOString()}`,- payload: { delegatedRequestId }- },++ [++ {++ id: buildDelegatedApprovalDispatchRequestedEventId({ delegatedRequestId, updatedAt }),++ type: DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,++ data: { delegatedRequestId }++ }++ ],+ tx+ );diff --cc backend/src/services/delegated-approval/delegated-approval-service.test.tsindex 3d93b09597,0000000000..b4cf047ef1mode 100644,000000..100644--- a/backend/src/services/delegated-approval/delegated-approval-service.test.ts+++ b/backend/src/services/delegated-approval/delegated-approval-service.test.ts@@@ -1,150 -1,0 +1,155 @@@+import { describe, expect, test, vi } from "vitest";++import { BadRequestError } from "@app/lib/errors";+import { ApprovalPolicyType, ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";++import { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "./delegated-approval-enums";- import { DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT } from "./delegated-approval-events";++import {++ buildDelegatedApprovalDispatchRequestedEventId,++ DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT++} from "./delegated-approval-events";+import { delegatedApprovalServiceFactory } from "./delegated-approval-service";++const UPDATED_AT = new Date("2026-10-23T13:00:00.000Z");+const failedRequest = {+ id: "delegated-1",+ requestId: "req-1",+ status: DelegatedApprovalRequestStatus.FailedDispatch,+ updatedAt: UPDATED_AT+};+const serviceNowPolicy = {+ id: "delegated-policy-1",+ policyId: "policy-1",+ type: DelegatedApprovalPolicyType.ServiceNow+};+const pendingApprovalRequest = {+ id: "req-1",+ policyId: "policy-1",+ type: ApprovalPolicyType.SecretAccess,+ status: ApprovalRequestStatus.Pending,+ expiresAt: null+};++// emit has to receive the caller's tx untouched; a second connection is how the pool deadlocks.+const TX = { sentinel: true } as never;+const PRIMARY = { primary: true } as never;++const createService = ({+ delegatedRequest = failedRequest as unknown,+ delegatedPolicy = serviceNowPolicy as unknown+} = {}) => {+ const emit = vi.fn().mockResolvedValue(undefined);+ const findOne = vi.fn().mockResolvedValue(delegatedRequest);+ const create = vi.fn().mockImplementation(async (row: { requestId: string; status: string }) => ({+ id: "delegated-1",+ updatedAt: UPDATED_AT,+ ...row+ }));+ const service = delegatedApprovalServiceFactory({+ delegatedApprovalRequestDAL: { findOne, create, primaryNode: () => PRIMARY },+ delegatedApprovalPolicyDAL: { findOne: vi.fn().mockResolvedValue(delegatedPolicy) },+ eventEmitter: { emit }+ } as never);+ return { service, emit, create, findOne };+};+- const dispatchRequestedEvent = {- eventType: DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,- idempotencyKey: `${DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT}:delegated-1:${UPDATED_AT.toISOString()}`,- payload: { delegatedRequestId: "delegated-1" }- };++const dispatchRequestedEvent = [++ {++ id: buildDelegatedApprovalDispatchRequestedEventId({ delegatedRequestId: "delegated-1", updatedAt: UPDATED_AT }),++ type: DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,++ data: { delegatedRequestId: "delegated-1" }++ }++];++describe("delegatedApprovalService.createRequest", () => {+ test("records the dispatch event in the same transaction as the request row", async () => {+ const { service, emit, create } = createService();++ const request = await service.createRequest({ approvalRequest: pendingApprovalRequest as never }, TX);++ expect(request).toMatchObject({ id: "delegated-1", status: DelegatedApprovalRequestStatus.PendingDispatch });+ expect(create).toHaveBeenCalledWith(+ { requestId: "req-1", status: DelegatedApprovalRequestStatus.PendingDispatch },+ TX+ );+ expect(emit).toHaveBeenCalledTimes(1);+ expect(emit).toHaveBeenCalledWith(dispatchRequestedEvent, TX);+ });+});++describe("delegatedApprovalService.retryDispatch", () => {+ test("asks for a new dispatch of a pending request that failed to reach the delegated system", async () => {+ const { service, emit, findOne } = createService();++ await expect(service.retryDispatch({ approvalRequest: pendingApprovalRequest })).resolves.toEqual({+ delegatedRequest: failedRequest,+ delegatedPolicy: serviceNowPolicy+ });+ expect(findOne).toHaveBeenCalledWith({ requestId: "req-1" }, PRIMARY);+ expect(emit).toHaveBeenCalledWith(dispatchRequestedEvent, undefined);+ });+- test("emits the same idempotency key when the same failed attempt is sent again", async () => {++ test("emits the same event id when the same failed attempt is sent again", async () => {+ const { service, emit } = createService();++ await service.retryDispatch({ approvalRequest: pendingApprovalRequest });+ await service.retryDispatch({ approvalRequest: pendingApprovalRequest });++ expect(emit).toHaveBeenCalledTimes(2);+ expect(emit).toHaveBeenNthCalledWith(1, dispatchRequestedEvent, undefined);+ expect(emit).toHaveBeenNthCalledWith(2, dispatchRequestedEvent, undefined);+ });++ test("refuses a request without a delegated approval", async () => {+ const { service, emit } = createService({ delegatedRequest: null });++ await expect(service.retryDispatch({ approvalRequest: pendingApprovalRequest })).rejects.toThrow(+ new BadRequestError({ message: "Request with ID 'req-1' is not reviewed in an external approval system" })+ );+ expect(emit).not.toHaveBeenCalled();+ });++ test("refuses a request that is no longer pending", async () => {+ const { service, emit } = createService();++ await expect(+ service.retryDispatch({+ approvalRequest: { ...pendingApprovalRequest, status: ApprovalRequestStatus.Cancelled }+ })+ ).rejects.toThrow("Only pending requests can be sent again");+ expect(emit).not.toHaveBeenCalled();+ });++ test("refuses an expired request", async () => {+ const { service, emit } = createService();++ await expect(+ service.retryDispatch({+ approvalRequest: { ...pendingApprovalRequest, expiresAt: new Date("2020-01-01T00:00:00.000Z") }+ })+ ).rejects.toThrow("This request has expired. Create a new request instead.");+ expect(emit).not.toHaveBeenCalled();+ });++ test("refuses a request whose policy no longer delegates approval", async () => {+ const { service, emit } = createService({ delegatedPolicy: null });++ await expect(service.retryDispatch({ approvalRequest: pendingApprovalRequest })).rejects.toThrow(+ "The policy for this request no longer uses an external approval system. Create a new request instead."+ );+ expect(emit).not.toHaveBeenCalled();+ });++ test.each([+ DelegatedApprovalRequestStatus.PendingDispatch,+ DelegatedApprovalRequestStatus.WaitingApproval,+ DelegatedApprovalRequestStatus.Approved+ ])("refuses a request in the %s state", async (status) => {+ const { service, emit } = createService({ delegatedRequest: { ...failedRequest, status } });++ await expect(service.retryDispatch({ approvalRequest: pendingApprovalRequest })).rejects.toThrow(+ "Only requests that failed to reach ServiceNow can be sent again"+ );+ expect(emit).not.toHaveBeenCalled();+ });+});diff --cc backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.test.tsindex ce5c299cdf,0000000000..bd92e61c31mode 100644,000000..100644--- a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.test.ts+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.test.ts@@@ -1,481 -1,0 +1,504 @@@+import { UnrecoverableError } from "bullmq";+import { beforeEach, describe, expect, test, vi } from "vitest";++import { TEventOutbox } from "@app/db/schemas";+import { ApprovalPolicyType, ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";+import { eventOutboxRegistryFactory } from "@app/services/event-outbox/event-outbox-registry";+import { eventOutboxServiceFactory } from "@app/services/event-outbox/event-outbox-service";+import {+ EventOutboxStatus,+ EventResultStatus,+ MAX_OUTBOX_ATTEMPTS,+ TEvent+} from "@app/services/event-outbox/event-outbox-types";++import { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "../delegated-approval-enums";+import { DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT } from "../delegated-approval-events";+import { delegatedApprovalDispatchConsumerFactory } from "./delegated-approval-dispatch-consumer";++vi.mock("@app/lib/logger", () => ({+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },+ initLogger: () => {}+}));++vi.mock("@app/lib/telemetry/metrics", () => ({++ EventOutboxRejectReason: {++ InvalidEvent: "invalid_event",++ DataTooLarge: "data_too_large",++ DataRejected: "data_rejected"++ },+ recordEventOutboxLagMetric: () => {},- recordEventOutboxExhaustedMetric: () => {}++ recordEventOutboxExhaustedMetric: () => {},++ recordEventOutboxRejectedMetric: () => {}+}));++const { dispatch } = vi.hoisted(() => ({ dispatch: vi.fn() }));+vi.mock("./delegated-approval-dispatch-fns", () => ({+ getDelegatedApprovalProvider: () => ({ dispatch }),+ getDelegatedApprovalDispatchDetailsBuilder: () => () => ({+ policyType: "secret-access",+ environment: "dev",+ secretPath: "/",+ permissions: ["read"],+ isTemporary: false,+ temporaryRange: null+ })+}));++vi.mock("@app/services/app-connection/app-connection-fns", () => ({+ decryptAppConnection: async (connection: unknown) => connection+}));++const DELEGATED_REQUEST_ID = "11111111-1111-1111-1111-111111111111";++const EVENT_ID = "44444444-4444-4444-8444-444444444444";+const ORG_ID = "22222222-2222-2222-2222-222222222222";+const RETRY_REASON =+ "ServiceNow did not respond. Infisical will retry automatically. If it keeps failing, send the request again.";++const pendingDelegatedRequest = {+ id: DELEGATED_REQUEST_ID,+ requestId: "req-1",+ status: DelegatedApprovalRequestStatus.PendingDispatch,+ statusReason: null as string | null,+ providerRequestId: null as string | null,+ encryptedCallbackToken: null+};++type TRow = typeof pendingDelegatedRequest;++const approvalRequest = {+ id: "req-1",+ policyId: "policy-1",+ projectId: "project-1",+ organizationId: ORG_ID,+ type: ApprovalPolicyType.SecretAccess,+ status: ApprovalRequestStatus.Pending,+ requesterName: "Ada",+ requesterEmail: "[email protected]",+ justification: null+};++const delegatedPolicy = {+ id: "delegated-policy-1",+ policyId: "policy-1",+ type: DelegatedApprovalPolicyType.ServiceNow,+ connectionId: "connection-1"+};++const PRIMARY = { primary: true } as never;+const TX = { tx: true } as never;++const buildConsumer = ({+ delegatedRequest = pendingDelegatedRequest as TRow | null,+ approval = approvalRequest as unknown,+ policy = delegatedPolicy as unknown,+ findById = undefined as ((id: string) => Promise<TRow | null>) | undefined+} = {}) => {+ let row: TRow | null = delegatedRequest ? { ...delegatedRequest } : null;++ const update = vi.fn(async (filter: Partial<TRow>, patch: Partial<TRow>) => {+ const current = row;+ if (!current) return [];+ const matches = Object.entries(filter).every(([key, value]) => current[key as keyof TRow] === value);+ if (!matches) return [];+ row = { ...current, ...patch };+ return [row];+ });+ const updateById = vi.fn(async (_id: string, patch: Partial<TRow>) => {+ row = row ? { ...row, ...patch } : row;+ return row;+ });++ const approvalUpdate = vi.fn(async () => [approval]);++ const consumer = delegatedApprovalDispatchConsumerFactory({+ delegatedApprovalRequestDAL: {+ findById: findById ?? vi.fn(async () => row),+ primaryNode: () => PRIMARY,+ transaction: async (cb: (tx: never) => Promise<unknown>) => cb(TX),+ update,+ updateById+ },+ delegatedApprovalPolicyDAL: { findOne: vi.fn().mockResolvedValue(policy) },+ delegatedApprovalCallbackService: {+ getCallbackUrl: () => "https://infisical.example.com/api/v1/delegated-approvals/callback",+ getOrIssueCallbackToken: vi.fn().mockResolvedValue("callback-token")+ },+ approvalRequestDAL: { findById: vi.fn().mockResolvedValue(approval), update: approvalUpdate },+ projectDAL: { findById: vi.fn().mockResolvedValue({ id: "project-1", name: "Project", type: "secret-manager" }) },+ appConnectionDAL: {+ findById: vi.fn().mockResolvedValue({ id: "connection-1", orgId: ORG_ID, app: "servicenow" })+ },+ kmsService: { createCipherPairWithDataKey: vi.fn() }+ } as never);++ return { consumer, row: () => row, update, approvalUpdate };+};++const makeEvent = (overrides?: Partial<TEvent>): TEvent => ({- id: 1,- eventType: DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,- payload: { delegatedRequestId: DELEGATED_REQUEST_ID },- occurredAt: new Date(),++ specversion: "1.0",++ id: "event-1",++ source: "urn:infisical:delegated-approval",++ type: DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,++ time: new Date().toISOString(),++ data: { delegatedRequestId: DELEGATED_REQUEST_ID },+ isFinalAttempt: false,+ ...overrides+});++beforeEach(() => {+ dispatch.mockReset();+});++describe("delegatedApprovalDispatchConsumer", () => {+ test("delivers the request and records the provider's record id", async () => {+ dispatch.mockResolvedValueOnce({ providerRequestId: "snow-1" });+ const { consumer, row } = buildConsumer();++ const results = await consumer.handle([makeEvent()]);+- expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);++ expect(results).toEqual([{ id: "event-1", status: EventResultStatus.Delivered }]);+ expect(dispatch).toHaveBeenCalledTimes(1);+ expect(dispatch.mock.calls[0][0]).toMatchObject({+ delegatedRequestId: DELEGATED_REQUEST_ID,+ approvalRequestId: "req-1",+ callback: { token: "callback-token" }+ });+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.WaitingApproval,+ providerRequestId: "snow-1",+ statusReason: null+ });+ });++ test("asks the outbox to retry a transient provider failure and tells the user it will", async () => {+ dispatch.mockRejectedValueOnce(new Error("ServiceNow did not respond."));+ const { consumer, row } = buildConsumer();++ const results = await consumer.handle([makeEvent()]);+- expect(results).toEqual([{ id: "1", status: EventResultStatus.Retry, error: "ServiceNow did not respond." }]);++ expect(results).toEqual([{ id: "event-1", status: EventResultStatus.Retry, error: "ServiceNow did not respond." }]);+ expect(row()).toMatchObject({ status: DelegatedApprovalRequestStatus.FailedDispatch, statusReason: RETRY_REASON });+ });++ test("fails terminally on an unrecoverable error without promising a retry", async () => {+ dispatch.mockRejectedValueOnce(new UnrecoverableError("ServiceNow rejected the credentials."));+ const { consumer, row } = buildConsumer();++ const results = await consumer.handle([makeEvent()]);++ expect(results).toEqual([- { id: "1", status: EventResultStatus.Failed, error: "ServiceNow rejected the credentials." }++ { id: "event-1", status: EventResultStatus.Failed, error: "ServiceNow rejected the credentials." }+ ]);+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.FailedDispatch,+ statusReason: "ServiceNow rejected the credentials."+ });+ });++ test("closes the request when a transient failure lands on the last attempt", async () => {+ dispatch.mockRejectedValueOnce(new Error("ServiceNow did not respond."));+ const { consumer, row, approvalUpdate } = buildConsumer();++ const results = await consumer.handle([makeEvent({ isFinalAttempt: true })]);+- expect(results).toEqual([{ id: "1", status: EventResultStatus.Failed, error: "ServiceNow did not respond." }]);++ expect(results).toEqual([++ { id: "event-1", status: EventResultStatus.Failed, error: "ServiceNow did not respond." }++ ]);+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.Failed,+ statusReason: `ServiceNow did not respond. Infisical could not send this request after ${MAX_OUTBOX_ATTEMPTS} attempts and closed it. Create a new request.`+ });+ expect(approvalUpdate).toHaveBeenCalledWith(+ { id: "req-1", status: ApprovalRequestStatus.Pending },+ { status: ApprovalRequestStatus.Cancelled },+ TX+ );+ });++ test("keeps a terminal failure on the last attempt resendable", async () => {+ dispatch.mockRejectedValueOnce(new UnrecoverableError("ServiceNow rejected the credentials."));+ const { consumer, row, approvalUpdate } = buildConsumer();++ const [result] = await consumer.handle([makeEvent({ isFinalAttempt: true })]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.FailedDispatch,+ statusReason: "ServiceNow rejected the credentials."+ });+ expect(approvalUpdate).not.toHaveBeenCalled();+ });++ test("fails terminally when the approval request is no longer pending", async () => {+ const { consumer, row } = buildConsumer({+ approval: { ...approvalRequest, status: ApprovalRequestStatus.Cancelled }+ });++ const [result] = await consumer.handle([makeEvent()]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(dispatch).not.toHaveBeenCalled();+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.FailedDispatch);+ });++ test("fails terminally when the approval request expired before it was sent", async () => {+ const { consumer, row } = buildConsumer({+ approval: { ...approvalRequest, expiresAt: new Date(Date.now() - 60_000) }+ });++ const [result] = await consumer.handle([makeEvent()]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(dispatch).not.toHaveBeenCalled();+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.FailedDispatch);+ expect(row()?.statusReason).toContain("expired");+ });++ test.each([+ ["is gone", null],+ ["is no longer awaiting dispatch", { ...pendingDelegatedRequest, status: DelegatedApprovalRequestStatus.Approved }],+ ["was already delivered", { ...pendingDelegatedRequest, providerRequestId: "snow-1" }]+ ])("marks the event delivered without calling the provider when the request %s", async (_, delegatedRequest) => {+ const { consumer } = buildConsumer({ delegatedRequest });++ const results = await consumer.handle([makeEvent()]);+- expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);++ expect(results).toEqual([{ id: "event-1", status: EventResultStatus.Delivered }]);+ expect(dispatch).not.toHaveBeenCalled();+ });++ test("dispatches different requests together", async () => {+ const otherRequestId = "33333333-3333-3333-3333-333333333333";+ let releaseFirst: () => void = () => {};+ const firstHeld = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });++ dispatch.mockImplementation(async (input: { delegatedRequestId: string }) => {+ if (input.delegatedRequestId === DELEGATED_REQUEST_ID) await firstHeld;+ return { providerRequestId: `snow-${input.delegatedRequestId}` };+ });++ const { consumer } = buildConsumer({+ findById: async (id: string) => ({+ ...pendingDelegatedRequest,+ id,+ requestId: id === DELEGATED_REQUEST_ID ? "req-1" : "req-2"+ })+ });++ const pending = consumer.handle([- makeEvent({ id: 1 }),- makeEvent({ id: 2, payload: { delegatedRequestId: otherRequestId } })++ makeEvent({ id: "event-1" }),++ makeEvent({ id: "event-2", data: { delegatedRequestId: otherRequestId } })+ ]);++ try {+ await vi.waitFor(() => expect(dispatch).toHaveBeenCalledTimes(2));+ } finally {+ releaseFirst();+ }++ await expect(pending).resolves.toEqual([- { id: "1", status: EventResultStatus.Delivered },- { id: "2", status: EventResultStatus.Delivered }++ { id: "event-1", status: EventResultStatus.Delivered },++ { id: "event-2", status: EventResultStatus.Delivered }+ ]);+ });++ test("dispatches a second event for the same request only after the first settles", async () => {+ let releaseFirst: () => void = () => {};+ const firstHeld = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ let firstSettledAt = 0;+ let secondStartedAt = 0;++ dispatch.mockImplementation(async () => {+ if (dispatch.mock.calls.length === 1) {+ await firstHeld;+ firstSettledAt = Date.now();+ throw new Error("ServiceNow did not respond.");+ }+ secondStartedAt = Date.now();+ return { providerRequestId: "snow-2" };+ });++ const { consumer } = buildConsumer();- const pending = consumer.handle([makeEvent({ id: 1 }), makeEvent({ id: 2 })]);++ const pending = consumer.handle([makeEvent({ id: "event-1" }), makeEvent({ id: "event-2" })]);++ try {+ await vi.waitFor(() => expect(dispatch).toHaveBeenCalledTimes(1));+ await new Promise((resolve) => {+ setTimeout(resolve, 30);+ });+ expect(dispatch).toHaveBeenCalledTimes(1);+ } finally {+ releaseFirst();+ }++ const results = await pending;++ expect(dispatch).toHaveBeenCalledTimes(2);+ expect(firstSettledAt).toBeGreaterThan(0);+ expect(secondStartedAt).toBeGreaterThanOrEqual(firstSettledAt);+ expect(results.map((result) => result.status)).toEqual([EventResultStatus.Retry, EventResultStatus.Delivered]);+ });++ test("fails an unreadable payload terminally", async () => {+ const { consumer } = buildConsumer();+- const [result] = await consumer.handle([makeEvent({ payload: { delegatedRequestId: "not-a-uuid" } })]);++ const [result] = await consumer.handle([makeEvent({ data: { delegatedRequestId: "not-a-uuid" } })]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(result.error).toContain("Unreadable delegated approval dispatch payload");+ expect(dispatch).not.toHaveBeenCalled();+ });+});++// Why this consumer exists: a dispatch that fails is kept by the outbox and tried again, instead of+// depending on an enqueue that ran after the request committed and could be lost with it.+describe("delegatedApprovalDispatchConsumer through the outbox", () => {+ const buildOutbox = (consumer: ReturnType<typeof buildConsumer>["consumer"]) => {+ const registry = eventOutboxRegistryFactory();+ registry.register(consumer);++ const rows: TEventOutbox[] = [];+ const isDue = (row: TEventOutbox) =>+ (row.status === EventOutboxStatus.Pending || row.status === EventOutboxStatus.Retry) &&+ row.nextRetryAt <= new Date();++ const service = eventOutboxServiceFactory({+ eventOutboxDAL: {+ insertEvents: async (inserted: Pick<TEventOutbox, "consumer" | "eventType" | "payload">[]) => {+ inserted.forEach((row) =>+ rows.push({+ id: rows.length + 1,+ status: EventOutboxStatus.Pending,+ attempts: 0,+ nextRetryAt: new Date(0),+ occurredAt: new Date(),+ ...row+ } as TEventOutbox)+ );+ },+ claimBatch: async () => {+ const claimable = rows.filter(isDue);+ claimable.forEach((row) => Object.assign(row, { status: EventOutboxStatus.Processing }));+ return { lockToken: "token", rows: claimable.map((row) => ({ ...row })) };+ },+ extendClaims: async () => {},+ commitResults: async (input: {+ delivered: { ids: string[] }[];+ retriable: { ids: string[]; nextRetryDelayMs: number; error?: string }[];+ failed: { ids: string[]; error?: string }[];+ }) => {+ const apply = (+ groups: { ids: string[]; nextRetryDelayMs?: number; error?: string }[],+ status: EventOutboxStatus+ ) =>+ groups.forEach((group) =>+ group.ids.forEach((id) => {+ const row = rows.find((candidate) => String(candidate.id) === id);+ if (!row) return;+ row.status = status;+ row.attempts += 1;+ row.lastError = group.error ?? null;+ row.nextRetryAt = new Date(Date.now() + (group.nextRetryDelayMs ?? 0));+ })+ );+ apply(input.delivered, EventOutboxStatus.Delivered);+ apply(input.retriable, EventOutboxStatus.Retry);+ apply(input.failed, EventOutboxStatus.Failed);+ return [...input.delivered, ...input.retriable, ...input.failed].reduce(+ (n, group) => n + group.ids.length,+ 0+ );+ }+ } as never,+ eventOutboxRegistry: registry+ });++ const elapseBackoff = () => {+ rows.forEach((row) => Object.assign(row, { nextRetryAt: new Date(0) }));+ };++ return { service, rows, elapseBackoff };+ };++ test("retries a dispatch the provider refused and delivers it on a later flush", async () => {+ dispatch+ .mockRejectedValueOnce(new Error("ServiceNow did not respond."))+ .mockResolvedValueOnce({ providerRequestId: "snow-1" });+ const { consumer, row } = buildConsumer();+ const { service, rows, elapseBackoff } = buildOutbox(consumer);++ await service.emit(- { eventType: DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT, payload: { delegatedRequestId: DELEGATED_REQUEST_ID } },++ [++ {++ id: EVENT_ID,++ type: DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,++ data: { delegatedRequestId: DELEGATED_REQUEST_ID }++ }++ ],+ PRIMARY+ );+ expect(rows).toHaveLength(1);++ await service.drain({ consumer: consumer.name });++ expect(rows[0]).toMatchObject({+ status: EventOutboxStatus.Retry,+ attempts: 1,+ lastError: "ServiceNow did not respond."+ });+ expect(row()).toMatchObject({ status: DelegatedApprovalRequestStatus.FailedDispatch, statusReason: RETRY_REASON });++ await service.drain({ consumer: consumer.name });+ expect(rows[0].status).toBe(EventOutboxStatus.Retry);+ expect(dispatch).toHaveBeenCalledTimes(1);++ elapseBackoff();+ await service.drain({ consumer: consumer.name });++ expect(rows[0]).toMatchObject({ status: EventOutboxStatus.Delivered, attempts: 2 });+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.WaitingApproval,+ providerRequestId: "snow-1",+ statusReason: null+ });+ expect(dispatch).toHaveBeenCalledTimes(2);+ });++ test("closes the request once the outbox has used up its attempts", async () => {+ dispatch.mockRejectedValue(new Error("ServiceNow did not respond."));+ const { consumer, row, approvalUpdate } = buildConsumer();+ const { service, rows, elapseBackoff } = buildOutbox(consumer);++ await service.emit(- { eventType: DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT, payload: { delegatedRequestId: DELEGATED_REQUEST_ID } },++ [++ {++ id: EVENT_ID,++ type: DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,++ data: { delegatedRequestId: DELEGATED_REQUEST_ID }++ }++ ],+ PRIMARY+ );++ for (let attempt = 1; attempt < MAX_OUTBOX_ATTEMPTS; attempt += 1) {+ // eslint-disable-next-line no-await-in-loop -- one drain per attempt+ await service.drain({ consumer: consumer.name });+ expect(rows[0].status).toBe(EventOutboxStatus.Retry);+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.FailedDispatch);+ expect(approvalUpdate).not.toHaveBeenCalled();+ elapseBackoff();+ }++ await service.drain({ consumer: consumer.name });++ expect(dispatch).toHaveBeenCalledTimes(MAX_OUTBOX_ATTEMPTS);+ expect(rows[0]).toMatchObject({ status: EventOutboxStatus.Failed, attempts: MAX_OUTBOX_ATTEMPTS });+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);+ expect(approvalUpdate).toHaveBeenCalledTimes(1);+ });+});diff --cc backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.tsindex b81dad2903,0000000000..6a1e5d6098mode 100644,000000..100644--- a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts@@@ -1,365 -1,0 +1,365 @@@+import { UnrecoverableError } from "bullmq";+import pLimit from "p-limit";++import { ProjectType } from "@app/db/schemas";+import { logger } from "@app/lib/logger";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";+import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";+import { APP_CONNECTION_NAME_MAP } from "@app/services/app-connection/app-connection-maps";+import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";+import { TApprovalRequestDALFactory } from "@app/services/approval-policy/approval-request-dal";+import { TDelegatedApprovalCallbackServiceFactory } from "@app/services/delegated-approval-callback/delegated-approval-callback-service";+import {+ EventResultStatus,+ IEventConsumer,+ MAX_OUTBOX_ATTEMPTS,+ TEvent,+ TEventConsumerResult+} from "@app/services/event-outbox/event-outbox-types";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { TProjectDALFactory } from "@app/services/project/project-dal";++import { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "../delegated-approval-enums";+import {+ DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,+ DelegatedApprovalDispatchRequestedPayloadSchema,+ TDelegatedApprovalDispatchRequestedPayload+} from "../delegated-approval-events";+import { DELEGATED_APPROVAL_CONNECTION_MAP } from "../delegated-approval-maps";+import { TDelegatedApprovalPolicyDALFactory } from "../delegated-approval-policy-dal";+import { TDelegatedApprovalRequestDALFactory } from "../delegated-approval-request-dal";+import { DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS } from "./delegated-approval-dispatch-constants";+import {+ getDelegatedApprovalDispatchDetailsBuilder,+ getDelegatedApprovalProvider+} from "./delegated-approval-dispatch-fns";+import { TDelegatedApprovalDispatchInput } from "./delegated-approval-dispatch-types";++export const DELEGATED_APPROVAL_DISPATCH_CONSUMER = "delegated-approval-dispatch";++const DELEGATED_APPROVAL_DISPATCH_CONCURRENCY = 10;++type TDelegatedApprovalDispatchConsumerDep = {+ delegatedApprovalRequestDAL: Pick<+ TDelegatedApprovalRequestDALFactory,+ "findById" | "primaryNode" | "transaction" | "update" | "updateById"+ >;+ delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;+ delegatedApprovalCallbackService: Pick<+ TDelegatedApprovalCallbackServiceFactory,+ "getCallbackUrl" | "getOrIssueCallbackToken"+ >;+ approvalRequestDAL: Pick<TApprovalRequestDALFactory, "findById" | "update">;+ projectDAL: Pick<TProjectDALFactory, "findById">;+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+};++export type TDelegatedApprovalDispatchConsumer = ReturnType<typeof delegatedApprovalDispatchConsumerFactory>;++export const delegatedApprovalDispatchConsumerFactory = ({+ delegatedApprovalRequestDAL,+ delegatedApprovalPolicyDAL,+ delegatedApprovalCallbackService,+ approvalRequestDAL,+ projectDAL,+ appConnectionDAL,+ kmsService+}: TDelegatedApprovalDispatchConsumerDep): IEventConsumer<TDelegatedApprovalDispatchRequestedPayload> => {+ const $markDispatchFailed = async (delegatedRequestId: string, statusReason: string) => {+ try {+ await delegatedApprovalRequestDAL.update(+ { id: delegatedRequestId, status: DelegatedApprovalRequestStatus.PendingDispatch },+ {+ status: DelegatedApprovalRequestStatus.FailedDispatch,+ statusReason: statusReason.slice(0, DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS)+ }+ );+ } catch (error) {+ logger.error(+ error,+ `Failed to record delegated approval dispatch failure [delegatedRequestId=${delegatedRequestId}]`+ );+ }+ };++ const $closeAfterExhaustedAttempts = async ({+ delegatedRequestId,+ approvalRequestId,+ statusReason+ }: {+ delegatedRequestId: string;+ approvalRequestId: string;+ statusReason: string;+ }) => {+ try {+ await delegatedApprovalRequestDAL.transaction(async (tx) => {+ await delegatedApprovalRequestDAL.update(+ { id: delegatedRequestId, status: DelegatedApprovalRequestStatus.PendingDispatch },+ {+ status: DelegatedApprovalRequestStatus.Failed,+ statusReason: statusReason.slice(0, DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS)+ },+ tx+ );+ await approvalRequestDAL.update(+ { id: approvalRequestId, status: ApprovalRequestStatus.Pending },+ { status: ApprovalRequestStatus.Cancelled },+ tx+ );+ });+ } catch (error) {+ logger.error(+ error,+ `Failed to close a delegated approval request whose dispatch attempts ran out [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequestId}]`+ );+ }+ };++ // Both rows were committed together with the event, so they are read from the primary.+ const $loadRequests = async (delegatedRequestId: string) => {+ const primary = delegatedApprovalRequestDAL.primaryNode();++ const delegatedRequest = await delegatedApprovalRequestDAL.findById(delegatedRequestId, primary);+ if (!delegatedRequest) return null;++ const approvalRequest = await approvalRequestDAL.findById(delegatedRequest.requestId, primary);+ const delegatedPolicy = approvalRequest?.policyId+ ? await delegatedApprovalPolicyDAL.findOne({ policyId: approvalRequest.policyId }, primary)+ : null;++ return { delegatedRequest, approvalRequest, delegatedPolicy };+ };++ const $dispatch = async (+ delegatedRequestId: string,+ isFinalAttempt: boolean+ ): Promise<Omit<TEventConsumerResult, "id">> => {+ const requests = await $loadRequests(delegatedRequestId);+ if (!requests) {+ logger.warn(+ `Delegated approval request no longer exists, skipping dispatch [delegatedRequestId=${delegatedRequestId}]`+ );+ return { status: EventResultStatus.Delivered };+ }++ const { delegatedRequest, approvalRequest, delegatedPolicy } = requests;++ if (+ delegatedRequest.status !== DelegatedApprovalRequestStatus.PendingDispatch &&+ delegatedRequest.status !== DelegatedApprovalRequestStatus.FailedDispatch+ ) {+ logger.info(+ `Delegated approval request is not awaiting dispatch, skipping [delegatedRequestId=${delegatedRequestId}] [status=${delegatedRequest.status}]`+ );+ return { status: EventResultStatus.Delivered };+ }++ if (delegatedRequest.providerRequestId) {+ logger.info(+ `Delegated approval request was already delivered, skipping [delegatedRequestId=${delegatedRequestId}] [providerRequestId=${delegatedRequest.providerRequestId}]`+ );+ return { status: EventResultStatus.Delivered };+ }++ if (delegatedRequest.status === DelegatedApprovalRequestStatus.FailedDispatch) {+ await delegatedApprovalRequestDAL.update(+ { id: delegatedRequestId, status: DelegatedApprovalRequestStatus.FailedDispatch },+ { status: DelegatedApprovalRequestStatus.PendingDispatch, statusReason: null }+ );+ }++ try {+ if (!approvalRequest) {+ throw new UnrecoverableError("The approval request no longer exists.");+ }+ if (approvalRequest.status !== ApprovalRequestStatus.Pending) {+ throw new UnrecoverableError(+ "The approval request is no longer pending, so it was not sent to the delegated approval system."+ );+ }+ if (approvalRequest.expiresAt && new Date(approvalRequest.expiresAt) < new Date()) {+ throw new UnrecoverableError(+ "The approval request expired before it could be sent to the delegated approval system. Create the request again."+ );+ }+ if (!delegatedPolicy) {+ throw new UnrecoverableError(+ "The policy's delegated approver was removed before the request could be sent. Configure a delegated approver on the policy and create the request again."+ );+ }++ const provider = getDelegatedApprovalProvider(delegatedPolicy.type);+ const buildDetails = getDelegatedApprovalDispatchDetailsBuilder(approvalRequest.type);+ const details = buildDetails(approvalRequest);++ const callbackUrl = delegatedApprovalCallbackService.getCallbackUrl();+ if (!callbackUrl) {+ throw new UnrecoverableError(+ "SITE_URL must be configured so the delegated approval system can call Infisical back."+ );+ }++ const primary = delegatedApprovalRequestDAL.primaryNode();+ const [project, rawConnection] = await Promise.all([+ projectDAL.findById(approvalRequest.projectId, primary),+ appConnectionDAL.findById(delegatedPolicy.connectionId, primary)+ ]);+ if (!project) {+ throw new UnrecoverableError("The project of the approval request no longer exists.");+ }+ if (!rawConnection || rawConnection.orgId !== approvalRequest.organizationId) {+ const connectionApp = DELEGATED_APPROVAL_CONNECTION_MAP[delegatedPolicy.type as DelegatedApprovalPolicyType];+ throw new UnrecoverableError(+ `App Connection with ID '${delegatedPolicy.connectionId}' was not found. Select a ${APP_CONNECTION_NAME_MAP[connectionApp]} Connection on the policy and create the request again.`+ );+ }++ const connection = await decryptAppConnection(rawConnection, kmsService);++ const callbackToken = await delegatedApprovalCallbackService.getOrIssueCallbackToken({ delegatedRequest });+ if (!callbackToken) {+ throw new UnrecoverableError(+ "A callback token could not be issued for this request. Create the request again."+ );+ }++ const input: TDelegatedApprovalDispatchInput = {+ delegatedRequestId,+ approvalRequestId: approvalRequest.id,+ organizationId: approvalRequest.organizationId,+ productType: project.type as ProjectType,+ project: { id: project.id, name: project.name },+ requester: { name: approvalRequest.requesterName, email: approvalRequest.requesterEmail },+ justification: approvalRequest.justification ?? null,+ callback: { url: callbackUrl, token: callbackToken },+ details+ };++ const { providerRequestId } = await provider.dispatch(input, connection);++ const [waitingRequest] = await delegatedApprovalRequestDAL.update(+ { id: delegatedRequestId, status: DelegatedApprovalRequestStatus.PendingDispatch },+ { status: DelegatedApprovalRequestStatus.WaitingApproval, statusReason: null, providerRequestId }+ );+ if (!waitingRequest) {+ await delegatedApprovalRequestDAL.updateById(delegatedRequestId, { providerRequestId });+ logger.warn(+ `Delegated approval request left pending dispatch while it was being delivered [delegatedRequestId=${delegatedRequestId}] [providerRequestId=${providerRequestId}]`+ );+ }++ logger.info(+ `Delegated approval request delivered [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}] [provider=${delegatedPolicy.type}] [providerRequestId=${providerRequestId}]`+ );+ return { status: EventResultStatus.Delivered };+ } catch (error) {+ const isTerminal = error instanceof UnrecoverableError;+ const message = error instanceof Error ? error.message : String(error);+ const logContext = { err: { name: (error as Error)?.name, message } };++ if (!isTerminal && isFinalAttempt && approvalRequest) {+ await $closeAfterExhaustedAttempts({+ delegatedRequestId,+ approvalRequestId: approvalRequest.id,+ statusReason: `${message} Infisical could not send this request after ${MAX_OUTBOX_ATTEMPTS} attempts and closed it. Create a new request.`+ });+ logger.error(+ logContext,+ `Delegated approval dispatch attempts ran out, request closed [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}]`+ );+ return { status: EventResultStatus.Failed, error: message };+ }++ // The row is failed_dispatch throughout, which is what makes the manual resend available while the+ // outbox is still retrying.+ await $markDispatchFailed(+ delegatedRequestId,+ isTerminal+ ? message+ : `${message} Infisical will retry automatically. If it keeps failing, send the request again.`+ );++ const logMessage = `Delegated approval dispatch failed [delegatedRequestId=${delegatedRequestId}] [terminal=${isTerminal}]`;+ if (isTerminal) {+ logger.error(logContext, logMessage);+ return { status: EventResultStatus.Failed, error: message };+ }+ logger.warn(logContext, logMessage);+ return { status: EventResultStatus.Retry, error: message };+ }+ };++ const $handleEvent = async (event: TEvent): Promise<TEventConsumerResult> => {- const id = String(event.id);++ const { id } = event;+- const payload = DelegatedApprovalDispatchRequestedPayloadSchema.safeParse(event.payload);++ const payload = DelegatedApprovalDispatchRequestedPayloadSchema.safeParse(event.data);+ if (!payload.success) {+ return {+ id,+ status: EventResultStatus.Failed,+ error: `Unreadable delegated approval dispatch payload: ${payload.error.issues.map((issue) => issue.message).join(", ")}`+ };+ }++ return { id, ...(await $dispatch(payload.data.delegatedRequestId, event.isFinalAttempt)) };+ };++ const $runEvent = async (event: TEvent): Promise<TEventConsumerResult> => {+ try {+ return await $handleEvent(event);+ } catch (error) {+ return {- id: String(event.id),++ id: event.id,+ status: EventResultStatus.Retry,+ error: error instanceof Error ? error.message : "Unknown error"+ };+ }+ };++ // Unreadable payloads have no request id, so each one is its own group and cannot block another request.+ const $groupByRequest = (events: TEvent[]): TEvent[][] => {+ const groups: TEvent[][] = [];+ const indexByRequest = new Map<string, number>();++ events.forEach((event) => {- const payload = DelegatedApprovalDispatchRequestedPayloadSchema.safeParse(event.payload);- const key = payload.success ? payload.data.delegatedRequestId : `event:${String(event.id)}`;++ const payload = DelegatedApprovalDispatchRequestedPayloadSchema.safeParse(event.data);++ const key = payload.success ? payload.data.delegatedRequestId : `event:${event.id}`;+ const existing = indexByRequest.get(key);+ if (existing === undefined) {+ indexByRequest.set(key, groups.length);+ groups.push([event]);+ } else {+ groups[existing].push(event);+ }+ });++ return groups;+ };++ const handle = async (events: TEvent[]): Promise<TEventConsumerResult[]> => {+ const limit = pLimit(DELEGATED_APPROVAL_DISPATCH_CONCURRENCY);++ const groupResults = await Promise.all(+ $groupByRequest(events).map((group) =>+ limit(async () => {+ const results: TEventConsumerResult[] = [];+ for (const event of group) {+ // eslint-disable-next-line no-await-in-loop -- two events for one request must not both pass the providerRequestId check+ results.push(await $runEvent(event));+ }+ return results;+ })+ )+ );++ return groupResults.flat();+ };++ return {+ name: DELEGATED_APPROVAL_DISPATCH_CONSUMER,- payloadSchema: DelegatedApprovalDispatchRequestedPayloadSchema,- subscribesTo: (eventType: string) => eventType === DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,++ dataSchema: DelegatedApprovalDispatchRequestedPayloadSchema,++ subscribesTo: (type: string) => type === DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,+ handle+ };+};diff --cc backend/src/services/event-outbox/event-outbox-service.test.tsindex 9316073af9,fa652c423d..b8ca619833--- a/backend/src/services/event-outbox/event-outbox-service.test.ts+++ b/backend/src/services/event-outbox/event-outbox-service.test.ts@@@ -233,6 -297,31 +297,32 @@@ describe("event outbox drain", () =>expect(commits[0].delivered).toEqual([{ ids: ["1"] }]);});+ test("hands the consumer each row as a CloudEvent and settles its result on that row", async () => {+ let received: unknown[] = [];+ const { service, commits } = buildDrain({+ batches: [[makeRow({ id: 7, eventId: "550e8400-e29b-41d4-a716-446655440000" })]],+ handle: async (events) => {+ received = events;+ return events.map((event) => ({ id: event.id, status: EventResultStatus.Delivered }));+ }+ });++ await service.drain(KEY);++ expect(received).toEqual([+ {+ specversion: "1.0",+ id: "550e8400-e29b-41d4-a716-446655440000",+ source: "urn:infisical:approval",+ type: "approval.workflow.request_opened",+ time: "2026-08-20T17:42:31.000Z",- data: makePayload()++ data: makePayload(),++ isFinalAttempt: false+ }+ ]);+ expect(commits[0].delivered).toEqual([{ ids: ["7"] }]);+ });+test("retries the whole batch when the consumer throws", async () => {const { service, commits } = buildDrain({batches: [[makeRow()]],@@@ -270,24 -359,6 +360,24 @@@expect(commits[0].retriable).toEqual([]);});+ test("hands the consumer isFinalAttempt only on its last attempt", async () => {+ const received: { id: string; isFinalAttempt: boolean }[] = [];+ const { service } = buildDrain({+ batches: [[makeRow({ id: 1, attempts: 0 }), makeRow({ id: 2, attempts: MAX_OUTBOX_ATTEMPTS - 1 })]],+ handle: async (events) => {- events.forEach((event) => received.push({ id: String(event.id), isFinalAttempt: event.isFinalAttempt }));- return events.map((event) => ({ id: String(event.id), status: EventResultStatus.Retry }));++ events.forEach((event) => received.push({ id: event.id, isFinalAttempt: event.isFinalAttempt }));++ return events.map((event) => ({ id: event.id, status: EventResultStatus.Retry }));+ }+ });++ await service.drain(KEY);++ expect(received).toEqual([- { id: "1", isFinalAttempt: false },- { id: "2", isFinalAttempt: true }++ { id: "event-1", isFinalAttempt: false },++ { id: "event-2", isFinalAttempt: true }+ ]);+ });+// One UPDATE per distinct outcome, so a hundred deliveries is one statement. Rows on the same attempt// share a retry delay, so they group too.test("groups rows that share an outcome into one commit entry", async () => {diff --cc backend/src/services/event-outbox/event-outbox-service.tsindex b5370e29b4,2de604482e..0d5f6323dd--- a/backend/src/services/event-outbox/event-outbox-service.ts+++ b/backend/src/services/event-outbox/event-outbox-service.ts@@@ -69,6 -73,15 +74,16 @@@ const withTimeout = async <T>(promise:}};+ const toEvent = (row: TClaimedOutboxRow): TEvent => ({+ specversion: "1.0",+ id: row.eventId,+ source: eventSource(row.eventType),+ type: row.eventType,+ time: new Date(row.occurredAt).toISOString(),- data: row.payload++ data: row.payload,++ isFinalAttempt: isFinalOutboxAttempt(row.attempts)+ });+const formatIssues = (issues: { path: (string | number)[]; message: string }[]) =>issues.map((issue) => `${issue.path.join(".")} ${issue.message}`).join(", ");diff --cc backend/src/services/event-outbox/event-outbox-types.tsindex b7613bca99,e3a3902305..aa739a1c21--- a/backend/src/services/event-outbox/event-outbox-types.ts+++ b/backend/src/services/event-outbox/event-outbox-types.ts@@@ -60,12 -57,17 +59,19 @@@ export const EventInputSchema = z.objecexport type TEventInput = z.input<typeof EventInputSchema>;export type TEventEmitter = {- emit: (event: TEventInput, tx?: Knex) => Promise<void>;+ emit: (events: TEventInput[], tx?: Knex) => Promise<void>;};- // What a consumer sees. Lock and status columns are the outbox's business.- export type TEvent = Pick<TEventOutbox, "id" | "eventType" | "payload" | "occurredAt"> & {-// What a consumer sees: the CloudEvents 1.0 envelope. Lock, attempt and status columns stay inside the outbox.++// What a consumer sees: the CloudEvents 1.0 envelope, plus whether this is its last attempt. Lock and++// status columns stay inside the outbox.+ export type TEvent<TData = unknown> = {+ specversion: "1.0";+ id: string;+ source: string;+ type: string;+ time: string;+ data: TData;+ isFinalAttempt: boolean;};export enum EventResultStatus {diff --cc backend/src/services/org/org-access-reconcile-consumer.test.tsindex 0000000000,8495402ebb..85b2ec2746mode 000000,100644..100644--- a/backend/src/services/org/org-access-reconcile-consumer.test.ts+++ b/backend/src/services/org/org-access-reconcile-consumer.test.ts@@@ -1,0 -1,371 +1,372 @@@+ import { EventType } from "@app/ee/services/audit-log/audit-log-types";+ import { ActorType } from "@app/services/auth/auth-type";+ import { EventResultStatus, TEvent } from "@app/services/event-outbox/event-outbox-types";+ import { TRevokedProjectAccess } from "@app/services/membership/project-access-revoke-service";++ import { ACTORS_PER_RECONCILE_TX, orgAccessReconcileConsumerFactory } from "./org-access-reconcile-consumer";+ import {+ GROUP_LINK_REMOVED_EVENT,+ GROUP_MEMBERSHIP_REMOVED_EVENT,+ GROUP_REMOVED_EVENT,+ ORG_MEMBERSHIP_REMOVED_EVENT,+ OrgAccessRemovalCause+ } from "./org-membership-events";++ vi.mock("@app/lib/logger", () => ({+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },+ initLogger: () => {}+ }));++ const uuid = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`;+ const ORG_ID = uuid(1);+ const SUB_ORG_ID = uuid(2);+ const USER_ID = uuid(10);+ const IDENTITY_ID = uuid(20);+ const GROUP_ID = uuid(30);+ const PROJECT_A = uuid(40);+ const PROJECT_B = uuid(41);++ const makeEvent = (type: string, data: Record<string, unknown>, id = uuid(9000)): TEvent => ({+ specversion: "1.0",+ id,+ source: "infisical",+ type,+ time: new Date().toISOString(),- data++ data,++ isFinalAttempt: false+ });+ const userRemovedFromOrg = (orgId = ORG_ID) =>+ makeEvent(ORG_MEMBERSHIP_REMOVED_EVENT, { orgId, actorType: ActorType.USER, actorId: USER_ID });++ // The revoke service only reports actors it found rows for.+ const build = (opts?: {+ withAccess?: { userIds?: string[]; identityIds?: string[] };+ // The mock stamps the org it was called for, like the real service does from the rows.+ revoked?: Omit<TRevokedProjectAccess, "orgId">[];+ orgs?: Record<string, unknown>;+ childOrgs?: string[];+ }) => {+ const tx = { raw: vi.fn().mockResolvedValue(undefined) };+ const primary = { node: "primary" };+ const sendPamCancellations = vi.fn();+ const deps = {+ orgDAL: {+ primaryNode: vi.fn(() => primary),+ findById: vi.fn((id: string) => {+ const orgs = opts?.orgs ?? { [ORG_ID]: { id: ORG_ID }, [SUB_ORG_ID]: { id: SUB_ORG_ID } };+ const org = orgs[id];+ if (org instanceof Error) return Promise.reject(org);+ return Promise.resolve(org);+ }),+ find: vi.fn().mockResolvedValue((opts?.childOrgs ?? []).map((id) => ({ id }))),+ findActorsWithOrgAccess: vi.fn().mockResolvedValue({+ userIds: new Set(opts?.withAccess?.userIds ?? []),+ identityIds: new Set(opts?.withAccess?.identityIds ?? [])+ }),+ lockActorsForOrgAccess: vi.fn().mockResolvedValue(undefined),+ transaction: vi.fn(async (cb: (trx: unknown) => Promise<unknown>) => cb(tx))+ },+ projectAccessRevokeService: {+ revokeActorsInOrgs: vi.fn(+ async ({+ orgIds,+ userIds = [],+ identityIds = []+ }: {+ orgIds: string[];+ userIds?: string[];+ identityIds?: string[];+ }) => ({+ revoked: (opts?.revoked ?? [])+ .filter(+ (entry) =>+ (entry.userId && userIds.includes(entry.userId)) ||+ (entry.identityId && identityIds.includes(entry.identityId))+ )+ .map((entry) => ({ ...entry, orgId: orgIds[0] })),+ sendPamCancellations+ })+ )+ },+ auditLogService: { createAuditLog: vi.fn().mockResolvedValue(undefined) },+ usageMeteringService: { emit: vi.fn() }+ };+ const consumer = orgAccessReconcileConsumerFactory(deps as never);+ return { consumer, deps, tx, primary, sendPamCancellations };+ };++ const auditMetadata = (deps: ReturnType<typeof build>["deps"], call = 0) =>+ (deps.auditLogService.createAuditLog.mock.calls[call] as [{ event: { metadata: Record<string, unknown> } }])[0].event+ .metadata;++ describe("org access reconcile consumer", () => {+ test("subscribes to the four org membership events only", () => {+ const { consumer } = build();+ for (const eventType of [+ GROUP_MEMBERSHIP_REMOVED_EVENT,+ GROUP_LINK_REMOVED_EVENT,+ GROUP_REMOVED_EVENT,+ ORG_MEMBERSHIP_REMOVED_EVENT+ ]) {+ expect(consumer.subscribesTo(eventType)).toBe(true);+ }+ expect(consumer.subscribesTo("approval.workflow.request_opened")).toBe(false);+ });++ describe("works out which orgs and actors to recheck from each event", () => {+ test("a group membership removal rechecks the orgs the group held when the actor left it", async () => {+ const { consumer, deps } = build();++ await consumer.handle([+ makeEvent(GROUP_MEMBERSHIP_REMOVED_EVENT, {+ groupId: GROUP_ID,+ orgIds: [ORG_ID, SUB_ORG_ID],+ members: [{ actorType: ActorType.USER, actorId: USER_ID }]+ })+ ]);++ expect(deps.orgDAL.findActorsWithOrgAccess).toHaveBeenCalledTimes(2);+ expect(deps.orgDAL.findActorsWithOrgAccess).toHaveBeenCalledWith(+ { orgId: SUB_ORG_ID, userIds: [USER_ID], identityIds: [] },+ expect.anything()+ );+ });++ test("a group link removal rechecks the members the group had when it was unlinked", async () => {+ const { consumer, deps } = build();++ await consumer.handle([+ makeEvent(GROUP_LINK_REMOVED_EVENT, {+ orgId: SUB_ORG_ID,+ groupId: GROUP_ID,+ members: [+ { actorType: ActorType.USER, actorId: USER_ID },+ { actorType: ActorType.IDENTITY, actorId: IDENTITY_ID }+ ]+ })+ ]);++ expect(deps.orgDAL.findActorsWithOrgAccess).toHaveBeenCalledWith(+ { orgId: SUB_ORG_ID, userIds: [USER_ID], identityIds: [IDENTITY_ID] },+ expect.anything()+ );+ });++ test("a group removal uses the snapshot the event carries, since the rows are gone", async () => {+ const { consumer, deps } = build();++ await consumer.handle([+ makeEvent(GROUP_REMOVED_EVENT, {+ groupId: GROUP_ID,+ orgIds: [ORG_ID, SUB_ORG_ID],+ members: [{ actorType: ActorType.IDENTITY, actorId: IDENTITY_ID }]+ })+ ]);++ expect(deps.orgDAL.findActorsWithOrgAccess).toHaveBeenCalledTimes(2);+ expect(deps.orgDAL.findActorsWithOrgAccess).toHaveBeenCalledWith(+ { orgId: SUB_ORG_ID, userIds: [], identityIds: [IDENTITY_ID] },+ expect.anything()+ );+ });++ test("an org membership removal also rechecks the org's sub-orgs", async () => {+ const { consumer, deps, primary } = build({ childOrgs: [SUB_ORG_ID] });++ await consumer.handle([userRemovedFromOrg()]);++ expect(deps.orgDAL.find).toHaveBeenCalledWith({ rootOrgId: ORG_ID }, { tx: primary });+ expect(deps.orgDAL.findById).toHaveBeenCalledWith(ORG_ID, primary);+ expect(deps.orgDAL.findActorsWithOrgAccess).toHaveBeenCalledTimes(2);+ });+ });++ test("keeps everything when the actor still reaches the org by any path", async () => {+ const { consumer, deps } = build({+ withAccess: { userIds: [USER_ID] },+ revoked: [{ userId: USER_ID, projectIds: [PROJECT_A], resources: [] }]+ });++ const [result] = await consumer.handle([userRemovedFromOrg()]);++ expect(result.status).toBe(EventResultStatus.Delivered);+ expect(deps.projectAccessRevokeService.revokeActorsInOrgs).not.toHaveBeenCalled();+ expect(deps.auditLogService.createAuditLog).not.toHaveBeenCalled();+ expect(deps.usageMeteringService.emit).not.toHaveBeenCalled();+ });++ // A group with no org rows names no orgs, so the actual reconcile is driven by an org membership event.+ test("revokes the actor's project access in the org, under the actor lock, when no path remains", async () => {+ const { consumer, deps, tx, sendPamCancellations } = build({+ revoked: [{ userId: USER_ID, projectIds: [PROJECT_A, PROJECT_B], resources: [] }]+ });++ const [result] = await consumer.handle([+ makeEvent(GROUP_MEMBERSHIP_REMOVED_EVENT, {+ groupId: GROUP_ID,+ orgIds: [],+ members: [{ actorType: ActorType.USER, actorId: USER_ID }]+ })+ ]);+ expect(result.status).toBe(EventResultStatus.Delivered);+ expect(deps.orgDAL.transaction).not.toHaveBeenCalled();++ const [orgResult] = await consumer.handle([userRemovedFromOrg()]);++ expect(orgResult.status).toBe(EventResultStatus.Delivered);+ expect(deps.orgDAL.lockActorsForOrgAccess).toHaveBeenCalledWith({ orgId: ORG_ID, actorIds: [USER_ID] }, tx);+ expect(deps.projectAccessRevokeService.revokeActorsInOrgs).toHaveBeenCalledWith(+ { orgIds: [ORG_ID], userIds: [USER_ID], identityIds: [] },+ tx+ );+ expect(sendPamCancellations).toHaveBeenCalledTimes(1);++ expect(deps.auditLogService.createAuditLog).toHaveBeenCalledTimes(1);+ expect(deps.auditLogService.createAuditLog).toHaveBeenCalledWith(+ expect.objectContaining({+ orgId: ORG_ID,+ actor: { type: ActorType.PLATFORM, metadata: {} },+ event: {+ type: EventType.REVOKE_ORG_PROJECT_ACCESS,+ metadata: {+ userId: USER_ID,+ identityId: undefined,+ projectIds: [PROJECT_A, PROJECT_B],+ resources: [],+ reason: OrgAccessRemovalCause.RemovedFromOrg,+ groupId: undefined+ }+ }+ })+ );+ expect(deps.usageMeteringService.emit).toHaveBeenCalledTimes(3);+ });++ test("records the identity and the group that carried the lost path, and says which grants went", async () => {+ const { consumer, deps, tx } = build({+ revoked: [+ {+ identityId: IDENTITY_ID,+ projectIds: [PROJECT_A],+ resources: [{ projectId: PROJECT_A, resourceType: "pam-account", resourceId: uuid(302) }]+ }+ ]+ });++ const [result] = await consumer.handle([+ makeEvent(GROUP_MEMBERSHIP_REMOVED_EVENT, {+ groupId: GROUP_ID,+ orgIds: [ORG_ID],+ members: [{ actorType: ActorType.IDENTITY, actorId: IDENTITY_ID }]+ })+ ]);++ expect(result.status).toBe(EventResultStatus.Delivered);+ expect(deps.projectAccessRevokeService.revokeActorsInOrgs).toHaveBeenCalledWith(+ { orgIds: [ORG_ID], userIds: [], identityIds: [IDENTITY_ID] },+ tx+ );+ expect(auditMetadata(deps)).toEqual({+ userId: undefined,+ identityId: IDENTITY_ID,+ projectIds: [PROJECT_A],+ resources: [{ projectId: PROJECT_A, resourceType: "pam-account", resourceId: uuid(302) }],+ reason: OrgAccessRemovalCause.RemovedFromGroup,+ groupId: GROUP_ID+ });+ });++ test("a replay that finds nothing left writes no audit entry and emits no meters", async () => {+ const { consumer, deps, sendPamCancellations } = build({ revoked: [] });++ const [result] = await consumer.handle([userRemovedFromOrg()]);++ expect(result.status).toBe(EventResultStatus.Delivered);+ expect(deps.projectAccessRevokeService.revokeActorsInOrgs).toHaveBeenCalledTimes(1);+ expect(sendPamCancellations).toHaveBeenCalledTimes(1);+ expect(deps.auditLogService.createAuditLog).not.toHaveBeenCalled();+ expect(deps.usageMeteringService.emit).not.toHaveBeenCalled();+ });++ test("treats an org deleted before the run as delivered with nothing to do", async () => {+ const { consumer, deps } = build({ orgs: {} });++ const [result] = await consumer.handle([userRemovedFromOrg()]);++ expect(result.status).toBe(EventResultStatus.Delivered);+ expect(deps.orgDAL.transaction).not.toHaveBeenCalled();+ });++ test("retries the event when one org fails and still reconciles the others", async () => {+ const { consumer, deps } = build({+ orgs: { [ORG_ID]: new Error("connection reset"), [SUB_ORG_ID]: { id: SUB_ORG_ID } },+ childOrgs: [SUB_ORG_ID],+ revoked: [{ userId: USER_ID, projectIds: [PROJECT_A], resources: [] }]+ });++ const [result] = await consumer.handle([userRemovedFromOrg()]);++ expect(result.status).toBe(EventResultStatus.Retry);+ expect(result.error).toContain(ORG_ID);+ expect(deps.orgDAL.transaction).toHaveBeenCalledTimes(1);+ expect(deps.projectAccessRevokeService.revokeActorsInOrgs).toHaveBeenCalledWith(+ expect.objectContaining({ orgIds: [SUB_ORG_ID] }),+ expect.anything()+ );+ });++ test("retries the event when a lookup before reconciling fails", async () => {+ const { consumer, deps } = build();+ deps.orgDAL.find.mockRejectedValueOnce(new Error("connection reset"));++ const [result] = await consumer.handle([userRemovedFromOrg()]);++ expect(result.status).toBe(EventResultStatus.Retry);+ expect(result.error).toContain("connection reset");+ expect(deps.orgDAL.transaction).not.toHaveBeenCalled();+ });++ test("fails terminally on a payload it cannot read or an event it does not know", async () => {+ const { consumer } = build();++ const [bad, unknown] = await consumer.handle([+ makeEvent(ORG_MEMBERSHIP_REMOVED_EVENT, { orgId: "not-a-uuid" }),+ makeEvent("com.infisical.organization.something.happened.v1", {}, uuid(9001))+ ]);++ expect(bad.status).toBe(EventResultStatus.Failed);+ expect(bad.error).toContain("Unreadable org membership event");+ expect(unknown.status).toBe(EventResultStatus.Failed);+ });++ test("splits the actors into short, time-boxed transactions and logs each batch after it commits", async () => {+ const userIds = Array.from({ length: ACTORS_PER_RECONCILE_TX + 1 }, (_, i) => uuid(200 + i));+ const { consumer, deps, tx } = build({+ revoked: userIds.map((userId) => ({ userId, projectIds: [PROJECT_A], resources: [] }))+ });++ const [result] = await consumer.handle([+ makeEvent(GROUP_LINK_REMOVED_EVENT, {+ orgId: ORG_ID,+ groupId: GROUP_ID,+ members: userIds.map((actorId) => ({ actorType: ActorType.USER, actorId }))+ })+ ]);++ expect(result.status).toBe(EventResultStatus.Delivered);+ expect(deps.orgDAL.transaction).toHaveBeenCalledTimes(2);+ expect(tx.raw).toHaveBeenCalledTimes(2);+ expect(tx.raw).toHaveBeenCalledWith(expect.stringContaining("SET LOCAL statement_timeout"));+ expect(deps.orgDAL.lockActorsForOrgAccess).toHaveBeenNthCalledWith(+ 1,+ { orgId: ORG_ID, actorIds: userIds.slice(0, ACTORS_PER_RECONCILE_TX) },+ tx+ );+ expect(deps.orgDAL.lockActorsForOrgAccess).toHaveBeenNthCalledWith(+ 2,+ { orgId: ORG_ID, actorIds: userIds.slice(ACTORS_PER_RECONCILE_TX) },+ tx+ );+ expect(deps.auditLogService.createAuditLog).toHaveBeenCalledTimes(userIds.length);+ });+ });diff --cc frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsxindex b8620d4641,8c7d51c9d6..107ca41623--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx@@@ -12,7 -11,6 +11,7 @@@ importRotateCwIcon} from "lucide-react";- import { AppConnectionOption } from "@app/components/app-connections";++import { useConnectionCreation } from "@app/components/app-connections/useConnectionCreation";import {CertificateEnrollmentUpgradeIntent,useUpgradeGate@@@ -98,7 -102,7 +103,6 @@@ importuseSetPkiApplicationScepEnrollment} from "@app/hooks/api/pkiApplications/mutations";import { ScepChallengeType, TPkiApplicationProfile } from "@app/hooks/api/pkiApplications/types";- import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";-import { useConnectionCreation } from "@app/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/useConnectionCreation";import { PkiDocsUrls } from "../../pki-docs-urls";diff --cc frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsxindex 40e8cb3ef9,bdc7115531..7f6e71a5ca--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx@@@ -1,8 -1,7 +1,8 @@@import { useState } from "react";import { Controller, UseFormReturn } from "react-hook-form";- import { SingleValue } from "react-select";- import { AppConnectionOption } from "@app/components/app-connections";+ import { AppConnectionOptionContent } from "@app/components/app-connections";++import { useConnectionCreation } from "@app/components/app-connections/useConnectionCreation";import {PostQuantumCertificatesUpgradeIntent,useUpgradeGate@@@ -37,8 -34,9 +35,8 @@@ import { InternalCaType } from "@app/hoimport { certKeyAlgorithms, isPqcAlgorithm } from "@app/hooks/api/certificates/constants";import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";import { CertKeySource } from "@app/hooks/api/signers";- import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";+ import { CreateHsmConnectorWizard } from "@app/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard";-import { useConnectionCreation } from "../CaInstallCertModal/useConnectionCreation";import { CaWizardForm } from "./schemas";import { HsmConnectorOption, isKeyAlgorithmSupportedByKeySource } from "./types";diff --cc frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AppConnectionSelectField.tsxindex e2ff9296db,4758284c97..2180659170--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AppConnectionSelectField.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AppConnectionSelectField.tsx@@@ -1,10 -1,10 +1,11 @@@- import { ReactNode, useState } from "react";+ import { ReactNode, useId } from "react";import { Control, FieldPath, useController } from "react-hook-form";- import { SingleValue } from "react-select";import { Info } from "lucide-react";- import { AppConnectionOption } from "@app/components/app-connections";+ import { AppConnectionOptionContent } from "@app/components/app-connections";++import { useConnectionCreation } from "@app/components/app-connections/useConnectionCreation";import {+ Combobox,Field,FieldError,FieldLabel,@@@ -13,13 -12,10 +13,9 @@@TooltipContent,TooltipTrigger} from "@app/components/v3";- import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";- import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";- import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";import { TAvailableAppConnection } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";- import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";-import { useConnectionCreation } from "../CaInstallCertModal/useConnectionCreation";import { FormData } from "./schema";type AppConnectionValue = { id: string; name: string };diff --cc frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/AccessApprovalRequest.tsxindex 970c1776bd,dd54acd016..60321a7d19--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/AccessApprovalRequest.tsx+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/AccessApprovalRequest.tsx@@@ -1,7 -1,7 +1,7 @@@/* eslint-disable no-nested-ternary *//* eslint-disable react/jsx-no-useless-fragment */-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";- import { useNavigate, useSearch } from "@tanstack/react-router";+ import { Link, useNavigate, useSearch } from "@tanstack/react-router";import { format, formatDistance } from "date-fns";import {BanIcon,