Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

Merge branch 'feat/adilsitos/eng-4966-stack-2' into feat/adilsitos/eng-4966-stack-3

adilson426058e5d9f5
diff --cc AGENTS.md
index d430107cb7,c40b94d8d0..da308d61ba
--- a/AGENTS.md
+++ b/AGENTS.md
@@@ -1,6 -1,233 +1,275 @@@
- ## 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
++`delegatedApprovalService.createRequest` writes the `delegated_approval_requests` row, stamped with the policy's
++provider as `providerType` so `(providerRequestId, providerType)` can be unique, 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
++(`delegated-approval/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.
++callback branch. A request gets exactly one callback token for its whole life: it is random, prefixed `inf_ext_`,
++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. 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. The provider calls `POST /api/v1/delegated-approvals/callback` (unauthenticated, IP rate limited)
++with the token in the `Infisical-Approval-Token` header and a body naming the event and the provider's record id;
++the body carries no decision, which a later worker reads back from the provider. The route finds the row by
++`providerRequestId` and checks the token. Only a callback that starts a read-back counts in `callbackAttempts`,
++so the limit bounds read-backs rather than repeats; on the sixth such callback it sets the row `failed` with a
++readable `statusReason` and cancels the attached approval request in the claim's transaction, so the policy is
++freed and the UI stops offering Cancel. That transaction locks the approval request before it claims, the same
++order the decision consumer and cancel take, or failing the request inside it would invert their lock order. A
++refused callback is never counted: the limit closes the request, so counting it would let anyone who knows the
++record id cancel the request, and the token is 256 random bits, so there is nothing to brute force. Every other
++refusal (no row for the record id, bad or missing token, request not `waiting_approval`)
++gets one neutral 403 while the reason goes to the log. An accepted callback only emits an outbox event, and
++only when it wins `claimDecisionRead`: a conditional update of `decisionReadRequestedAt`, in the emit's
++transaction, that one of any number of concurrent callbacks wins. A repeat while a read-back is still in
++flight gets the same 200, emits nothing and is not counted. The last read-back attempt clears
++`decisionReadRequestedAt`, so a callback after the outbox gives up claims immediately. A claim whose worker
++died before that write stays until it is older than `DELEGATED_APPROVAL_DECISION_READ_CLAIM_TTL_MS`
++(70 minutes), which is what lets a fresh notification start one then. The event's `type` is the body's event
++and its id is derived (uuid v5) from the delegated request id plus the attempt count. The
++`delegated-approval-decision` consumer (`backend/src/services/delegated-approval-decision/`, a thin outbox
++adapter over `delegatedApprovalDecisionService.applyDecision` that, like dispatch, reads up to 10 different
++requests at once and one request's events serially) then reads the decision back through the
++policy's app connection: `TDelegatedApprovalProvider.fetchDecision` returns `pending` or a decision with
++the permissions the provider holds, and the consumer answers `Retry` for `pending` (on the last attempt, `Failed`
++with the request left open, `decisionReadRequestedAt` cleared, and a `statusReason` saying Infisical stopped
++checking and the callback has to be sent again), compares the approved
++permissions with the ones it dispatched after both go through `normalizeDelegatedApprovalPermissions` (set
++comparison: padding, order, duplicates and case never count as a change), and finalizes in one transaction
++that locks the approval request, moves the delegated row `waiting_approval` → `approved` / `rejected`, and
++runs the policy type's `postApprovalTxRoutine` from `approvalResources`. A mismatch, a record for another
++request, or any other `UnrecoverableError` goes through `failDelegatedApprovalRequest`: the delegated row
++becomes `failed` with a readable `statusReason`, the approval request is cancelled, and nothing can retry
++it. A request whose requester was deleted (`requesterId` is set null) or is no longer a member of the
++project, directly or through a group (`membershipDAL.isUserProjectMember`), takes the same path before the
++decision is read back. The secret access `postApprovalTxRoutine` refuses a non-member too, on both approval
++paths: removing a member reaps only the privileges that already exist, so one written afterwards would take
++effect if the user were ever added back. Every outcome is audited as
++`ACCESS_APPROVAL_REQUEST_DELEGATED_DECISION` with the `PLATFORM` actor, and
++product notifications (the access request webhook) go through `decisionNotifiers`, never through the
++consumer itself. A new delegated policy type adds its `postApprovalTxRoutine` and decision notifier in
++`delegatedApprovalDecisionMapsFactory`, the same way dispatch details get a builder in
++`DELEGATED_APPROVAL_DISPATCH_DETAILS_BUILDER_MAP`. ServiceNow stamps an immutable `decision` on its record before it posts the callback, so
++the provider reads that field alone and ignores `state`.
+
+ ### 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 Development
diff --cc backend/e2e-test/membership-dal.spec.ts
index deb208dead,0000000000..d8b7c0c2e8
mode 100644,000000..100644
--- a/backend/e2e-test/membership-dal.spec.ts
+++ b/backend/e2e-test/membership-dal.spec.ts
@@@ -1,100 -1,0 +1,103 @@@
+import { afterAll, beforeAll, describe, expect, test } from "vitest";
+
+import { OrgMembershipRole, ProjectMembershipRole } from "@app/db/schemas";
++import { groupDALFactory } from "@app/ee/services/group/group-dal";
+import { removeUsersFromGroupByUserIds } from "@app/ee/services/group/group-fns";
+import { userGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
+import { additionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
+import { alertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";
+import { membershipDALFactory } from "@app/services/membership/membership-dal";
+import { membershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";
+import { projectKeyDALFactory } from "@app/services/project-key/project-key-dal";
+import { userDALFactory } from "@app/services/user/user-dal";
+
+import { createIsolatedOrgAndProject } from "./testUtils/fixtures";
+import { createProjectGroup } from "./testUtils/groups";
+import { pollUntil } from "./testUtils/poll";
+import { addUserMembership, createUser, deleteUsers } from "./testUtils/users";
+
+const membershipDAL = membershipDALFactory(testDb);
+
+const removalDeps = {
+ userDAL: userDALFactory(testDb),
+ userGroupMembershipDAL: userGroupMembershipDALFactory(testDb),
+ membershipGroupDAL: membershipGroupDALFactory(testDb),
+ projectKeyDAL: projectKeyDALFactory(testDb),
+ additionalPrivilegeDAL: additionalPrivilegeDALFactory(testDb),
- alertChannelRecipientDAL: alertChannelRecipientDALFactory(testDb)
++ alertChannelRecipientDAL: alertChannelRecipientDALFactory(testDb),
++ groupDAL: groupDALFactory(testDb),
++ eventEmitter: { emit: async () => {} }
+};
+
+const waitUntilBlockedBy = (pid: number) =>
+ pollUntil({
+ describe: `a query blocked by backend ${pid}`,
+ read: async () => {
+ const { rows } = await testDb.raw(
+ "select count(*)::int as waiting from pg_stat_activity where ? = any(pg_blocking_pids(pid))",
+ [pid]
+ );
+ return rows[0].waiting as number;
+ },
+ done: (waiting) => waiting > 0,
+ timeoutMs: 5_000
+ });
+
+describe("membershipDAL.lockUserProjectMemberships", () => {
+ let fixture: Awaited<ReturnType<typeof createIsolatedOrgAndProject>>;
+ const userIds: string[] = [];
+
+ const createOrgUser = async (label: string) => {
+ const { userId } = await createUser(label);
+ userIds.push(userId);
+ await addUserMembership({ userId, orgId: fixture.orgId, role: OrgMembershipRole.Member });
+ return userId;
+ };
+
+ const lockWhileRemovedFromGroup = async (userId: string, group: Awaited<ReturnType<typeof createProjectGroup>>) => {
+ const removal = await testDb.transaction();
+ const grant = await testDb.transaction();
+ try {
+ const { rows } = await removal.raw("select pg_backend_pid() as pid");
+ await removeUsersFromGroupByUserIds({ ...removalDeps, group, userIds: [userId], tx: removal });
+
+ const isMember = membershipDAL.lockUserProjectMemberships({ projectId: fixture.projectId, userId }, grant);
+ await waitUntilBlockedBy(rows[0].pid as number);
+ await removal.commit();
+
+ return await isMember;
+ } finally {
+ if (!removal.isCompleted()) await removal.rollback();
+ if (!grant.isCompleted()) await grant.rollback();
+ }
+ };
+
+ beforeAll(async () => {
+ fixture = await createIsolatedOrgAndProject("membership-lock");
+ });
+
+ afterAll(async () => {
+ await fixture.cleanup();
+ await deleteUsers(userIds);
+ });
+
+ test("does not count a group the user was removed from while waiting for its lock", async () => {
+ const userId = await createOrgUser("group-only");
+ const group = await createProjectGroup({ orgId: fixture.orgId, projectId: fixture.projectId, userIds: [userId] });
+
+ expect(await lockWhileRemovedFromGroup(userId, group)).toBe(false);
+ });
+
+ test("still counts a direct membership when the user leaves a group while waiting for its lock", async () => {
+ const userId = await createOrgUser("direct-and-group");
+ await addUserMembership({
+ userId,
+ orgId: fixture.orgId,
+ projectId: fixture.projectId,
+ role: ProjectMembershipRole.Member
+ });
+ const group = await createProjectGroup({ orgId: fixture.orgId, projectId: fixture.projectId, userIds: [userId] });
+
+ expect(await lockWhileRemovedFromGroup(userId, group)).toBe(true);
+ });
+});
diff --cc backend/e2e-test/testUtils/groups.ts
index 96d247526f,3597616180..55edb247ca
--- a/backend/e2e-test/testUtils/groups.ts
+++ b/backend/e2e-test/testUtils/groups.ts
@@@ -1,32 -1,91 +1,122 @@@
-import { AccessScope, OrgMembershipRole, TableName } from "@app/db/schemas";
+import crypto from "node:crypto";
+
+import { AccessScope, OrgMembershipRole, ProjectMembershipRole, TableName } from "@app/db/schemas";
+
+export const createProjectGroup = async (dto: { orgId: string; projectId: string; userIds: string[] }) => {
+ const slug = `group-${crypto.randomUUID().slice(0, 8)}`;
+ const [group] = (await testDb(TableName.Groups)
+ .insert({ orgId: dto.orgId, name: slug, slug })
+ .returning(["id", "name", "slug"])) as { id: string; name: string; slug: string }[];
+
+ const [orgMembership] = await testDb(TableName.Membership)
+ .insert({ scope: AccessScope.Organization, scopeOrgId: dto.orgId, actorGroupId: group.id })
+ .returning("id");
+ const [projectMembership] = await testDb(TableName.Membership)
+ .insert({
+ scope: AccessScope.Project,
+ scopeOrgId: dto.orgId,
+ scopeProjectId: dto.projectId,
+ actorGroupId: group.id
+ })
+ .returning("id");
+ await testDb(TableName.MembershipRole).insert([
+ { membershipId: (orgMembership as { id: string }).id, role: OrgMembershipRole.Member },
+ { membershipId: (projectMembership as { id: string }).id, role: ProjectMembershipRole.Member }
+ ]);
+
+ if (dto.userIds.length) {
+ await testDb(TableName.UserGroupMembership).insert(dto.userIds.map((userId) => ({ userId, groupId: group.id })));
+ }
+
+ return { ...group, orgId: dto.orgId };
+};
+
+ // Inserts rows directly: the group API refuses users with no org membership, which is exactly who these specs test.
+ // `ownerOrgId` puts the group row in another org while its membership stays in `orgId`, the shape a parent
+ // org's group takes when it is linked into a sub-org.
+ export const createOrgGroup = async (dto: {
+ orgId: string;
+ ownerOrgId?: string;
+ name: string;
+ role: OrgMembershipRole;
+ temporaryRole?: { role: OrgMembershipRole; endsAt: Date };
+ }) => {
+ const [group] = await testDb(TableName.Groups)
+ .insert({ orgId: dto.ownerOrgId ?? dto.orgId, name: dto.name, slug: dto.name })
+ .returning("id");
+ const groupId = (group as { id: string }).id;
+
+ const [membership] = await testDb(TableName.Membership)
+ .insert({ scope: AccessScope.Organization, scopeOrgId: dto.orgId, actorGroupId: groupId, isActive: true })
+ .returning("id");
+ const membershipId = (membership as { id: string }).id;
+
+ await testDb(TableName.MembershipRole).insert([
+ { membershipId, role: dto.role },
+ ...(dto.temporaryRole
+ ? [
+ {
+ membershipId,
+ role: dto.temporaryRole.role,
+ isTemporary: true,
+ temporaryAccessEndTime: dto.temporaryRole.endsAt
+ }
+ ]
+ : [])
+ ]);
+
+ return groupId;
+ };
+
+ export const addUsersToGroup = async (groupId: string, userIds: string[]) => {
+ if (userIds.length === 0) return;
+ await testDb(TableName.UserGroupMembership).insert(userIds.map((userId) => ({ userId, groupId })));
+ };
+
+ export const deleteGroups = async (groupIds: string[]) => {
+ if (groupIds.length === 0) return;
+ await testDb(TableName.UserGroupMembership).whereIn("groupId", groupIds).delete();
+ await testDb(TableName.IdentityGroupMembership).whereIn("groupId", groupIds).delete();
+ const membershipIds = await testDb(TableName.Membership).whereIn("actorGroupId", groupIds).pluck("id");
+ await testDb(TableName.MembershipRole).whereIn("membershipId", membershipIds).delete();
+ await testDb(TableName.Membership).whereIn("id", membershipIds).delete();
+ await testDb(TableName.Groups).whereIn("id", groupIds).delete();
+ };
+
+ // `authToken` has to be scoped to the sub-org, the route reads the org from it.
+ export const linkGroupToOrg = async (dto: { groupId: string; authToken: string }) => {
+ const res = await testServer.inject({
+ method: "POST",
+ url: `/api/v1/organizations/memberships/groups/${dto.groupId}`,
+ headers: { authorization: `Bearer ${dto.authToken}` },
+ body: { roles: [{ role: OrgMembershipRole.Member }] }
+ });
+ expect(res.statusCode).toBe(200);
+ };
+
+ export const unlinkGroupFromOrg = async (dto: { groupId: string; authToken: string }) => {
+ const res = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v1/organizations/memberships/groups/${dto.groupId}`,
+ headers: { authorization: `Bearer ${dto.authToken}` }
+ });
+ expect(res.statusCode).toBe(200);
+ };
+
+ export const removeUserFromGroup = async (dto: { groupId: string; username: string; authToken: string }) => {
+ const res = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v1/groups/${dto.groupId}/users/${encodeURIComponent(dto.username)}`,
+ headers: { authorization: `Bearer ${dto.authToken}` }
+ });
+ expect(res.statusCode).toBe(200);
+ };
+
+ export const removeIdentityFromGroup = async (dto: { groupId: string; identityId: string; authToken: string }) => {
+ const res = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v1/groups/${dto.groupId}/machine-identities/${dto.identityId}`,
+ headers: { authorization: `Bearer ${dto.authToken}` }
+ });
+ expect(res.statusCode).toBe(200);
+ };
diff --cc backend/src/ee/services/group/group-fns.ts
index e03fd17880,0a5e3d0b2a..fad63abfa6
--- a/backend/src/ee/services/group/group-fns.ts
+++ b/backend/src/ee/services/group/group-fns.ts
@@@ -6,7 -6,7 +6,8 @@@ import { BadRequestError, ForbiddenRequ
import { logger } from "@app/lib/logger";
import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";
import { AgentVaultIdentities, PamIdentities, SecretIdentities } from "@app/services/license-client";
+import { lockMembershipsById } from "@app/services/membership/membership-dal";
+ import { emitGroupMembershipRemoved, toOrgMembershipActors } from "@app/services/org/org-membership-events";
import {
TAddIdentitiesToGroup,
@@@ -478,23 -490,18 +491,22 @@@ export const removeUsersFromGroupByUser
}
});
+ const groupProjectMemberships = await membershipGroupDAL.find(
+ {
+ scope: AccessScope.Project,
- actorGroupId: group.id,
- scopeOrgId: group.orgId
++ actorGroupId: group.id
+ },
+ { tx }
+ );
const projectIds = Array.from(
- new Set(
- (
- await membershipGroupDAL.find(
- {
- scope: AccessScope.Project,
- actorGroupId: group.id
- },
- { tx }
- )
- ).map((gp) => gp.scopeProjectId as string)
- )
+ new Set(groupProjectMemberships.map((membership) => membership.scopeProjectId as string))
+ );
+ const lockedMemberships = await lockMembershipsById(
+ groupProjectMemberships.map((membership) => membership.id),
+ tx
+ );
+ const lockedProjectIds = new Set(
+ lockedMemberships.flatMap((membership) => (membership.scopeProjectId ? [membership.scopeProjectId] : []))
);
if (membersToRemoveFromGroupNonPending.length) {
diff --cc backend/src/services/delegated-approval-callback/delegated-approval-callback-events.ts
index 8f195ac8b9,0000000000..c6bb383b04
mode 100644,000000..100644
--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-events.ts
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-events.ts
@@@ -1,20 -1,0 +1,33 @@@
++import { v5 as uuidv5 } from "uuid";
+import { z } from "zod";
+
+import { DelegatedApprovalCallbackEvent } from "./delegated-approval-callback-enums";
+
+// What the callback route emits once it has accepted a decision notification. The consumer that reads
+// the decision back lives in delegated-approval-decision; the contract stays with the emitter.
+export const DelegatedApprovalCallbackEventPayloadSchema = z.object({
+ delegatedRequestId: z.string().uuid(),
+ approvalRequestId: z.string().uuid(),
+ orgId: z.string().uuid(),
+ event: z.nativeEnum(DelegatedApprovalCallbackEvent),
+ externalId: z.string().trim().min(1).max(255)
+});
+
+export type TDelegatedApprovalCallbackEventPayload = z.infer<typeof DelegatedApprovalCallbackEventPayloadSchema>;
+
++// Namespaces the event ids derived below, so they can't collide with ids derived the same way elsewhere.
++const DELEGATED_APPROVAL_CALLBACK_EVENT_ID_NAMESPACE = "6583d64a-24ad-474f-8de8-48cbd24dd1f3";
++
++// One id per counted callback, so the read-back each one starts is its own outbox row.
++export const buildDelegatedApprovalCallbackEventId = ({
++ delegatedRequestId,
++ attempts
++}: {
++ delegatedRequestId: string;
++ attempts: number;
++}): string => uuidv5(`${delegatedRequestId}:${attempts}`, DELEGATED_APPROVAL_CALLBACK_EVENT_ID_NAMESPACE);
++
+const DELEGATED_APPROVAL_CALLBACK_EVENTS = new Set<string>(Object.values(DelegatedApprovalCallbackEvent));
+
+export const isDelegatedApprovalCallbackEvent = (eventType: string): eventType is DelegatedApprovalCallbackEvent =>
+ DELEGATED_APPROVAL_CALLBACK_EVENTS.has(eventType);
diff --cc backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.ts
index e5241b8b73,3e20ed8d5e..dc6974a4af
--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.ts
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.ts
@@@ -19,14 -8,8 +19,16 @@@ import { DelegatedApprovalRequestStatu
import { KmsDataKey } from "@app/services/kms/kms-types";
// eslint-disable-next-line import/first
-import { DELEGATED_APPROVAL_CALLBACK_PATH } from "./delegated-approval-callback-constants";
+import {
+ DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS,
+ DELEGATED_APPROVAL_CALLBACK_PATH,
+ DELEGATED_APPROVAL_DECISION_READ_CLAIM_TTL_MS
+} from "./delegated-approval-callback-constants";
+// eslint-disable-next-line import/first
+import { DelegatedApprovalCallbackEvent } from "./delegated-approval-callback-enums";
+// eslint-disable-next-line import/first
++import { buildDelegatedApprovalCallbackEventId } from "./delegated-approval-callback-events";
+ // eslint-disable-next-line import/first
import { delegatedApprovalCallbackServiceFactory } from "./delegated-approval-callback-service";
const CIPHER_PREFIX = Buffer.from("enc:");
@@@ -150,234 -118,3 +152,236 @@@ describe("getOrIssueCallbackToken", ()
expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();
});
});
+
+describe("handleCallback", () => {
+ const TOKEN = "inf_ext_stored-token";
+ const EXTERNAL_ID = "9d41f2a7c3b24e1088f6a05e7b1d4c93";
+ const EVENT = DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest;
+
+ const makeDelegatedRequest = (overrides?: Record<string, unknown>) => ({
+ id: "delegated-1",
+ requestId: "request-1",
+ status: DelegatedApprovalRequestStatus.WaitingApproval,
+ encryptedCallbackToken: encrypt(Buffer.from(TOKEN)),
+ providerRequestId: EXTERNAL_ID,
+ callbackAttempts: 0,
+ approvalRequestOrganizationId: "org-1",
+ approvalRequestProjectId: "project-1",
+ ...overrides
+ });
+
+ const makeCallbackService = ({
+ delegatedRequest = makeDelegatedRequest(),
+ attemptsAfterIncrement = 1,
+ lockedApprovalRequest = { id: "request-1", status: ApprovalRequestStatus.Pending }
+ }: {
+ delegatedRequest?: ReturnType<typeof makeDelegatedRequest> | null;
+ attemptsAfterIncrement?: number;
+ lockedApprovalRequest?: { id: string; status: ApprovalRequestStatus } | null;
+ } = {}) => {
+ const built = makeService();
+ built.delegatedApprovalRequestDAL.findByProviderRequestId.mockResolvedValue(delegatedRequest);
+ built.delegatedApprovalRequestDAL.update.mockResolvedValue([
+ { ...delegatedRequest, callbackAttempts: attemptsAfterIncrement }
+ ] as never);
+ built.approvalRequestDAL.findByIdForUpdate.mockResolvedValue(lockedApprovalRequest);
+ return built;
+ };
+
+ const callback = (overrides?: Partial<{ token: string | undefined; event: typeof EVENT; externalId: string }>) => ({
+ token: TOKEN,
+ event: EVENT,
+ externalId: EXTERNAL_ID,
+ ...overrides
+ });
+
+ test("refuses an external ID no request has with the same 403 as any other refusal", async () => {
+ const { service, delegatedApprovalRequestDAL, eventEmitter } = makeCallbackService({ delegatedRequest: null });
+
+ await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(ForbiddenRequestError);
+ expect(delegatedApprovalRequestDAL.findByProviderRequestId).toHaveBeenCalledWith(EXTERNAL_ID);
+ expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();
+ expect(eventEmitter.emit).not.toHaveBeenCalled();
+ });
+
+ test.each([
+ ["missing", undefined],
+ ["unprefixed", "stored-token"],
+ ["mismatched", "inf_ext_other-token"]
+ ])("rejects a %s token without counting it, even when it would pass the limit", async (_label, token) => {
+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL, eventEmitter } = makeCallbackService({
+ delegatedRequest: makeDelegatedRequest({ callbackAttempts: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS }),
+ attemptsAfterIncrement: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS + 1
+ });
+
+ await expect(service.handleCallback(callback({ token }))).rejects.toBeInstanceOf(ForbiddenRequestError);
+ expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();
+ expect(delegatedApprovalRequestDAL.updateWithDetails).not.toHaveBeenCalled();
+ expect(approvalRequestDAL.updateById).not.toHaveBeenCalled();
+ expect(eventEmitter.emit).not.toHaveBeenCalled();
+ });
+
+ test("counts a callback that claims the read-back, in the claim's transaction", async () => {
+ const { service, delegatedApprovalRequestDAL } = makeCallbackService();
+
+ await service.handleCallback(callback());
+
+ expect(delegatedApprovalRequestDAL.update).toHaveBeenCalledWith(
+ { id: "delegated-1" },
+ { $incr: { callbackAttempts: 1 } },
+ TX
+ );
+ expect(delegatedApprovalRequestDAL.claimDecisionRead.mock.invocationCallOrder[0]).toBeLessThan(
+ delegatedApprovalRequestDAL.update.mock.invocationCallOrder[0]
+ );
+ });
+
+ test("locks the approval request before claiming the read-back", async () => {
+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL } = makeCallbackService();
+
+ await service.handleCallback(callback());
+
+ expect(approvalRequestDAL.findByIdForUpdate).toHaveBeenCalledWith("request-1", TX);
+ expect(approvalRequestDAL.findByIdForUpdate.mock.invocationCallOrder[0]).toBeLessThan(
+ delegatedApprovalRequestDAL.claimDecisionRead.mock.invocationCallOrder[0]
+ );
+ });
+
+ test("rejects a request that is not awaiting a decision without counting it", async () => {
+ const { service, delegatedApprovalRequestDAL, eventEmitter } = makeCallbackService({
+ delegatedRequest: makeDelegatedRequest({ status: DelegatedApprovalRequestStatus.Approved })
+ });
+
+ await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(ForbiddenRequestError);
+ expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();
+ expect(eventEmitter.emit).not.toHaveBeenCalled();
+ });
+
+ test("fails the request and cancels its approval request on the callback past the limit", async () => {
+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL, eventEmitter } = makeCallbackService({
+ attemptsAfterIncrement: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS + 1
+ });
+
+ await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(ForbiddenRequestError);
+
+ expect(approvalRequestDAL.findByIdForUpdate).toHaveBeenCalledWith("request-1", TX);
+ expect(approvalRequestDAL.updateById).toHaveBeenCalledWith(
+ "request-1",
+ { status: ApprovalRequestStatus.Cancelled },
+ TX
+ );
+ const [filter, patch, tx] = delegatedApprovalRequestDAL.updateWithDetails.mock.lastCall as unknown as [
+ unknown,
+ { status: string; details: { statusReason: string } },
+ unknown
+ ];
+ expect(filter).toEqual({ id: "delegated-1", status: DelegatedApprovalRequestStatus.WaitingApproval });
+ expect(patch.status).toBe(DelegatedApprovalRequestStatus.Failed);
+ expect(patch.details.statusReason).toContain(`more than ${DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS} times`);
+ expect(tx).toBe(TX);
+ expect(eventEmitter.emit).not.toHaveBeenCalled();
+ });
+
+ test("leaves an approval request that is no longer pending alone when attempts run out", async () => {
+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL } = makeCallbackService({
+ attemptsAfterIncrement: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS + 1,
+ lockedApprovalRequest: { id: "request-1", status: ApprovalRequestStatus.Expired }
+ });
+
+ await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(ForbiddenRequestError);
+
+ expect(approvalRequestDAL.updateById).not.toHaveBeenCalled();
+ const [, patch] = delegatedApprovalRequestDAL.updateWithDetails.mock.lastCall as unknown as [
+ unknown,
+ { status: string }
+ ];
+ expect(patch.status).toBe(DelegatedApprovalRequestStatus.Failed);
+ });
+
+ test("still accepts the callback at the limit", async () => {
+ const { service, eventEmitter } = makeCallbackService({
+ attemptsAfterIncrement: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS
+ });
+
+ await expect(service.handleCallback(callback())).resolves.toEqual({ delegatedRequestId: "delegated-1" });
+ expect(eventEmitter.emit).toHaveBeenCalledTimes(1);
+ });
+
+ test("emits an outbox event keyed on the delegated request", async () => {
+ const { service, eventEmitter, kmsService } = makeCallbackService();
+
+ await expect(service.handleCallback(callback())).resolves.toEqual({ delegatedRequestId: "delegated-1" });
+
+ expect(kmsService.createCipherPairWithDataKey).toHaveBeenCalledWith({
+ type: KmsDataKey.SecretManager,
+ projectId: "project-1"
+ });
+ expect(eventEmitter.emit).toHaveBeenCalledWith(
- {
- eventType: EVENT,
- idempotencyKey: "delegated-1:1",
- payload: {
- delegatedRequestId: "delegated-1",
- approvalRequestId: "request-1",
- orgId: "org-1",
- event: EVENT,
- externalId: EXTERNAL_ID
++ [
++ {
++ id: buildDelegatedApprovalCallbackEventId({ delegatedRequestId: "delegated-1", attempts: 1 }),
++ type: EVENT,
++ data: {
++ delegatedRequestId: "delegated-1",
++ approvalRequestId: "request-1",
++ orgId: "org-1",
++ event: EVENT,
++ externalId: EXTERNAL_ID
++ }
+ }
- },
++ ],
+ TX
+ );
+ });
+
+ test("claims the read-back in the emit's transaction, expiring claims older than their TTL", async () => {
+ vi.useFakeTimers({ now: new Date("2026-10-21T12:00:00.000Z") });
+ try {
+ const { service, delegatedApprovalRequestDAL } = makeCallbackService();
+
+ await service.handleCallback(callback());
+
+ expect(delegatedApprovalRequestDAL.claimDecisionRead).toHaveBeenCalledWith(
+ { id: "delegated-1", staleBefore: new Date(Date.now() - DELEGATED_APPROVAL_DECISION_READ_CLAIM_TTL_MS) },
+ TX
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test("accepts a repeat without emitting while another read-back holds the claim", async () => {
+ const { service, delegatedApprovalRequestDAL, eventEmitter } = makeCallbackService();
+ delegatedApprovalRequestDAL.claimDecisionRead.mockResolvedValue(null);
+ delegatedApprovalRequestDAL.findById.mockResolvedValue(makeDelegatedRequest());
+
+ await expect(service.handleCallback(callback())).resolves.toEqual({ delegatedRequestId: "delegated-1" });
+ expect(eventEmitter.emit).not.toHaveBeenCalled();
+ });
+
+ test("does not count a repeat while another read-back holds the claim, even at the limit", async () => {
+ const atLimit = makeDelegatedRequest({ callbackAttempts: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS });
+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL } = makeCallbackService({
+ delegatedRequest: atLimit,
+ attemptsAfterIncrement: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS + 1
+ });
+ delegatedApprovalRequestDAL.claimDecisionRead.mockResolvedValue(null);
+ delegatedApprovalRequestDAL.findById.mockResolvedValue(atLimit);
+
+ await expect(service.handleCallback(callback())).resolves.toEqual({ delegatedRequestId: "delegated-1" });
+ expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();
+ expect(delegatedApprovalRequestDAL.updateWithDetails).not.toHaveBeenCalled();
+ expect(approvalRequestDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test("rejects a callback whose request stopped awaiting a decision before the claim", async () => {
+ const { service, delegatedApprovalRequestDAL, eventEmitter } = makeCallbackService();
+ delegatedApprovalRequestDAL.claimDecisionRead.mockResolvedValue(null);
+ delegatedApprovalRequestDAL.findById.mockResolvedValue(
+ makeDelegatedRequest({ status: DelegatedApprovalRequestStatus.Approved })
+ );
+
+ await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(ForbiddenRequestError);
+ expect(eventEmitter.emit).not.toHaveBeenCalled();
+ });
+});
diff --cc backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts
index 1c20c13c5f,e1057bbb5d..5a85891119
--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts
@@@ -1,22 -1,11 +1,25 @@@
import { getConfig } from "@app/lib/config/env";
+import { logger } from "@app/lib/logger";
+import { DelegatedApprovalRequestStatus } from "@app/services/delegated-approval/delegated-approval-enums";
+import { failDelegatedApprovalRequest } from "@app/services/delegated-approval/delegated-approval-request-fns";
import { KmsDataKey } from "@app/services/kms/kms-types";
-import { DELEGATED_APPROVAL_CALLBACK_PATH } from "./delegated-approval-callback-constants";
-import { generateDelegatedApprovalCallbackToken } from "./delegated-approval-callback-fns";
+import {
+ DELEGATED_APPROVAL_CALLBACK_ATTEMPTS_EXHAUSTED_REASON,
+ DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS,
+ DELEGATED_APPROVAL_CALLBACK_PATH,
+ DELEGATED_APPROVAL_CALLBACK_TOKEN_PREFIX,
+ DELEGATED_APPROVAL_DECISION_READ_CLAIM_TTL_MS
+} from "./delegated-approval-callback-constants";
- import { TDelegatedApprovalCallbackEventPayload } from "./delegated-approval-callback-events";
++import {
++ buildDelegatedApprovalCallbackEventId,
++ TDelegatedApprovalCallbackEventPayload
++} from "./delegated-approval-callback-events";
+import { generateCallbackToken, isTokenMatch, rejectApprovalCallback } from "./delegated-approval-callback-fns";
import {
TDelegatedApprovalCallbackServiceFactoryDep,
- TGetOrIssueCallbackTokenDTO
+ TGetOrIssueCallbackTokenDTO,
+ THandleDelegatedApprovalCallbackDTO
} from "./delegated-approval-callback-types";
export type TDelegatedApprovalCallbackServiceFactory = ReturnType<typeof delegatedApprovalCallbackServiceFactory>;
@@@ -60,97 -47,5 +63,106 @@@ export const delegatedApprovalCallbackS
return decryptor({ cipherTextBlob: current.encryptedCallbackToken }).toString();
};
- return { getCallbackUrl, getOrIssueCallbackToken };
+ const handleCallback = async ({ token, event, externalId }: THandleDelegatedApprovalCallbackDTO) => {
+ const delegatedRequest = await delegatedApprovalRequestDAL.findByProviderRequestId(externalId);
+ if (!delegatedRequest) {
+ throw rejectApprovalCallback("no request matches the external ID", { externalId });
+ }
+
+ const logContext = { delegatedRequestId: delegatedRequest.id, externalId };
+
+ if (!token || !token.startsWith(DELEGATED_APPROVAL_CALLBACK_TOKEN_PREFIX)) {
+ throw rejectApprovalCallback("missing or malformed token", logContext);
+ }
+ if (!delegatedRequest.encryptedCallbackToken) {
+ throw rejectApprovalCallback("request has no callback token", logContext);
+ }
+
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId: delegatedRequest.approvalRequestProjectId
+ });
+ const storedToken = decryptor({ cipherTextBlob: delegatedRequest.encryptedCallbackToken }).toString();
+ if (!isTokenMatch(token, storedToken)) {
+ throw rejectApprovalCallback("token mismatch", logContext);
+ }
+
+ if (delegatedRequest.status !== DelegatedApprovalRequestStatus.WaitingApproval) {
+ throw rejectApprovalCallback("request is not awaiting a decision", {
+ ...logContext,
+ status: delegatedRequest.status
+ });
+ }
+
+ const payload: TDelegatedApprovalCallbackEventPayload = {
+ delegatedRequestId: delegatedRequest.id,
+ approvalRequestId: delegatedRequest.requestId,
+ orgId: delegatedRequest.approvalRequestOrganizationId,
+ event,
+ externalId
+ };
+ // A read-back already in flight will see the decision this callback announces, so a repeat only
+ // starts another once that one has had time to finish.
+ const outcome = await delegatedApprovalRequestDAL.transaction(async (tx) => {
+ await approvalRequestDAL.findByIdForUpdate(delegatedRequest.requestId, tx);
+ const claimed = await delegatedApprovalRequestDAL.claimDecisionRead(
+ { id: delegatedRequest.id, staleBefore: new Date(Date.now() - DELEGATED_APPROVAL_DECISION_READ_CLAIM_TTL_MS) },
+ tx
+ );
+ if (!claimed) {
+ const current = await delegatedApprovalRequestDAL.findById(delegatedRequest.id, tx);
+ if (current?.status !== DelegatedApprovalRequestStatus.WaitingApproval) return { status: "closed" } as const;
+ return { status: "deduplicated", attempts: current.callbackAttempts } as const;
+ }
+
+ const [counted] = await delegatedApprovalRequestDAL.update(
+ { id: delegatedRequest.id },
+ { $incr: { callbackAttempts: 1 } },
+ tx
+ );
+ const attempts = counted?.callbackAttempts ?? claimed.callbackAttempts + 1;
+ if (attempts > DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS) {
+ await failDelegatedApprovalRequest(
+ {
+ id: delegatedRequest.id,
+ requestId: delegatedRequest.requestId,
+ reason: DELEGATED_APPROVAL_CALLBACK_ATTEMPTS_EXHAUSTED_REASON
+ },
+ { approvalRequestDAL, delegatedApprovalRequestDAL },
+ tx
+ );
+ return { status: "exhausted", attempts } as const;
+ }
+
- await eventEmitter.emit({ eventType: event, idempotencyKey: `${delegatedRequest.id}:${attempts}`, payload }, tx);
++ await eventEmitter.emit(
++ [
++ {
++ id: buildDelegatedApprovalCallbackEventId({ delegatedRequestId: delegatedRequest.id, attempts }),
++ type: event,
++ data: payload
++ }
++ ],
++ tx
++ );
+ return { status: "accepted", attempts } as const;
+ });
+
+ if (outcome.status === "closed") {
+ throw rejectApprovalCallback("request is not awaiting a decision", logContext);
+ }
+ if (outcome.status === "exhausted") {
+ throw rejectApprovalCallback("callback attempts exhausted", {
+ ...logContext,
+ attempts: String(outcome.attempts)
+ });
+ }
+
+ logger.info(
+ `Delegated approval callback ${outcome.status} [delegatedRequestId=${delegatedRequest.id}] [approvalRequestId=${delegatedRequest.requestId}] [event=${event}] [callbackAttempts=${outcome.attempts}]`
+ );
+
+ return { delegatedRequestId: delegatedRequest.id };
+ };
+
+ return { getCallbackUrl, getOrIssueCallbackToken, handleCallback };
};
diff --cc backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts
index ea05536c65,0000000000..8246ac2366
mode 100644,000000..100644
--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts
@@@ -1,773 -1,0 +1,790 @@@
+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 {
+ DelegatedApprovalPolicyType,
+ DelegatedApprovalRequestStatus
+} from "@app/services/delegated-approval/delegated-approval-enums";
+import { TDelegatedApprovalRequestDetails } from "@app/services/delegated-approval/delegated-approval-schemas";
+import { DelegatedApprovalCallbackEvent } from "@app/services/delegated-approval-callback/delegated-approval-callback-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 {
+ DELEGATED_APPROVAL_DECISION_RETRY_HINT,
+ DELEGATED_APPROVAL_DECISION_STOPPED_HINT
+} from "./delegated-approval-decision-constants";
+import { delegatedApprovalDecisionConsumerFactory } from "./delegated-approval-decision-consumer";
+import { DelegatedApprovalDecision, DelegatedApprovalDecisionOutcome } from "./delegated-approval-decision-enums";
+import { delegatedApprovalDecisionServiceFactory } from "./delegated-approval-decision-service";
+import { TDelegatedApprovalDecisionReadResult } from "./delegated-approval-decision-types";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
+ initLogger: () => {}
+}));
+
+vi.mock("@app/lib/telemetry/metrics", () => ({
+ recordEventOutboxLagMetric: () => {},
+ recordEventOutboxExhaustedMetric: () => {}
+}));
+
+const { fetchDecision, REQUESTED_PERMISSIONS } = vi.hoisted(() => ({
+ fetchDecision: vi.fn(),
+ REQUESTED_PERMISSIONS: ["secrets: read, create", "secret-folders: edit"]
+}));
+vi.mock("@app/services/delegated-approval/dispatch/delegated-approval-dispatch-fns", () => ({
+ getDelegatedApprovalProvider: () => ({ fetchDecision }),
+ getDelegatedApprovalDispatchDetailsBuilder: () => () => ({
+ policyType: "secret-access",
+ environment: "dev",
+ secretPath: "/",
+ permissions: REQUESTED_PERMISSIONS,
+ 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 APPROVAL_REQUEST_ID = "33333333-3333-3333-3333-333333333333";
+const ORG_ID = "22222222-2222-2222-2222-222222222222";
+const EXTERNAL_ID = "snow-1";
++const EVENT_ID = "44444444-4444-4444-8444-444444444444";
+const POLICY_NAME = "Production secrets";
+const DECISION_READ_REQUESTED_AT = new Date("2026-10-27T15:00:00.000Z");
+const TX = { tx: true } as never;
+const PRIMARY = { primary: true } as never;
+const SERVICENOW_RECORD = { type: DelegatedApprovalPolicyType.ServiceNow, recordNumber: "INFAR1000000" };
+const waitingDelegatedRequest = {
+ id: DELEGATED_REQUEST_ID,
+ requestId: APPROVAL_REQUEST_ID,
+ status: DelegatedApprovalRequestStatus.WaitingApproval,
+ details: { statusReason: null, provider: SERVICENOW_RECORD } as TDelegatedApprovalRequestDetails,
+ providerRequestId: EXTERNAL_ID as string | null,
+ decisionReadRequestedAt: DECISION_READ_REQUESTED_AT as Date | null
+};
+
+type TDelegatedRow = typeof waitingDelegatedRequest;
+
+const pendingApprovalRequest = {
+ id: APPROVAL_REQUEST_ID,
+ policyId: "policy-1",
+ projectId: "project-1",
+ organizationId: ORG_ID,
+ requesterId: "user-1" as string | null,
+ type: ApprovalPolicyType.SecretAccess,
+ status: ApprovalRequestStatus.Pending as string,
+ expiresAt: null as Date | null
+};
+
+type TApprovalRow = typeof pendingApprovalRequest;
+
+const delegatedPolicy = {
+ id: "delegated-policy-1",
+ policyId: "policy-1",
+ type: DelegatedApprovalPolicyType.ServiceNow,
+ connectionId: "connection-1"
+};
+
+const decided = (
+ decision: DelegatedApprovalDecision,
+ overrides: Partial<Extract<TDelegatedApprovalDecisionReadResult, { status: "decided" }>> = {}
+): TDelegatedApprovalDecisionReadResult => ({
+ status: "decided",
+ decision,
+ approvalRequestId: APPROVAL_REQUEST_ID,
+ permissions: ["secrets: create, read", "secret-folders: edit"],
+ decidedBy: "Grace Hopper",
+ decidedAt: "2026-10-20 10:15:00",
+ notes: null,
+ ...overrides
+});
+
+const buildConsumer = ({
+ delegatedRequest = waitingDelegatedRequest as TDelegatedRow | null,
+ approvalRequest = pendingApprovalRequest as TApprovalRow | null,
+ policy = delegatedPolicy as typeof delegatedPolicy | null,
+ connection = { id: "connection-1", orgId: ORG_ID, app: "servicenow" } as { id: string; orgId: string } | null,
+ isRequesterProjectMember = true
+} = {}) => {
+ let row: TDelegatedRow | null = delegatedRequest ? { ...delegatedRequest } : null;
+ let approval: TApprovalRow | null = approvalRequest ? { ...approvalRequest } : null;
+
+ // Merges details the way the DAL's jsonb concatenation does.
+ const updateWithDetails = vi.fn(
+ async (
+ filter: Partial<TDelegatedRow>,
+ { details, ...columns }: Partial<TDelegatedRow> & { details?: Partial<TDelegatedRow["details"]> }
+ ) => {
+ const current = row;
+ if (!current) return [];
+ const matches = Object.entries(filter).every(([key, value]) => current[key as keyof TDelegatedRow] === value);
+ if (!matches) return [];
+ row = { ...current, ...columns, details: { ...current.details, ...details } };
+ return [row];
+ }
+ );
+
+ const updateById = vi.fn(async (_id: string, patch: Partial<TApprovalRow>) => {
+ approval = approval ? { ...approval, ...patch } : approval;
+ return approval;
+ });
+ const postApprovalTxRoutine = vi.fn(async () => ({ grantId: "grant-1" }));
+ const createAuditLog = vi.fn(async () => {});
+ const notify = vi.fn(async () => {});
+
+ const delegatedApprovalDecisionService = delegatedApprovalDecisionServiceFactory({
+ delegatedApprovalRequestDAL: {
+ findById: vi.fn(async () => row),
+ primaryNode: () => PRIMARY,
+ updateWithDetails
+ },
+ delegatedApprovalPolicyDAL: { findOne: vi.fn().mockResolvedValue(policy) },
+ approvalPolicyDAL: { findById: vi.fn().mockResolvedValue({ id: "policy-1", name: POLICY_NAME }) },
+ approvalRequestDAL: {
+ findById: vi.fn(async () => approval),
+ findByIdForUpdate: vi.fn(async () => approval),
+ updateById,
+ // Rolls back on a throw, as Postgres would, so a failed finalize leaves both rows as they were.
+ transaction: vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => {
+ const snapshot = { row, approval };
+ try {
+ return await fn(TX);
+ } catch (error) {
+ ({ row, approval } = snapshot);
+ throw error;
+ }
+ })
+ },
+ appConnectionDAL: { findById: vi.fn().mockResolvedValue(connection) },
+ membershipDAL: { isUserProjectMember: vi.fn().mockResolvedValue(isRequesterProjectMember) },
+ kmsService: { createCipherPairWithDataKey: vi.fn() },
+ auditLogService: { createAuditLog },
+ approvalResources: { [ApprovalPolicyType.SecretAccess]: { postApprovalTxRoutine } },
+ decisionNotifiers: { [ApprovalPolicyType.SecretAccess]: notify }
+ } as never);
+ const consumer = delegatedApprovalDecisionConsumerFactory({ delegatedApprovalDecisionService });
+
+ return {
+ consumer,
+ row: () => row,
+ approval: () => approval,
+ postApprovalTxRoutine,
+ createAuditLog,
+ notify,
+ updateById
+ };
+};
+
+const makeEvent = (overrides?: Partial<TEvent>): TEvent => ({
- id: 1,
- eventType: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
- payload: {
++ specversion: "1.0",
++ id: "event-1",
++ source: "urn:infisical:secrets_management",
++ type: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
++ time: new Date().toISOString(),
++ data: {
+ delegatedRequestId: DELEGATED_REQUEST_ID,
+ approvalRequestId: APPROVAL_REQUEST_ID,
+ orgId: ORG_ID,
+ event: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
+ externalId: EXTERNAL_ID
+ },
- occurredAt: new Date(),
+ isFinalAttempt: false,
+ ...overrides
+});
+
+const auditedWith = (createAuditLog: ReturnType<typeof vi.fn>, expected: Record<string, unknown>) => {
+ expect(createAuditLog).toHaveBeenCalledTimes(1);
+ expect(createAuditLog.mock.calls[0][0]).toMatchObject({
+ orgId: ORG_ID,
+ projectId: "project-1",
+ event: {
+ metadata: {
+ requestId: APPROVAL_REQUEST_ID,
+ policyName: POLICY_NAME,
+ delegatedProviderRequestId: EXTERNAL_ID,
+ permissions: REQUESTED_PERMISSIONS,
+ ...expected
+ }
+ }
+ });
+};
+
+beforeEach(() => {
+ fetchDecision.mockReset();
+});
+
+describe("delegatedApprovalDecisionConsumer", () => {
+ test("applies an approval: both rows move, the grant routine runs in the same transaction", async () => {
+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));
+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog, notify } = 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(fetchDecision.mock.calls[0][0]).toEqual({
+ delegatedRequestId: DELEGATED_REQUEST_ID,
+ approvalRequestId: APPROVAL_REQUEST_ID,
+ providerRequestId: EXTERNAL_ID
+ });
+ expect(row()).toEqual({
+ ...waitingDelegatedRequest,
+ status: DelegatedApprovalRequestStatus.Approved,
+ details: { statusReason: null, provider: SERVICENOW_RECORD }
+ });
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Approved);
+ expect(postApprovalTxRoutine).toHaveBeenCalledWith(expect.objectContaining({ id: APPROVAL_REQUEST_ID }), TX);
+ auditedWith(createAuditLog, {
+ outcome: DelegatedApprovalDecisionOutcome.Applied,
+ decision: DelegatedApprovalDecision.Approved,
+ decidedBy: "Grace Hopper",
+ decidedAt: "2026-10-20 10:15:00",
+ providerRecordNumber: "INFAR1000000"
+ });
+ expect(notify).toHaveBeenCalledWith({
+ approvalRequestId: APPROVAL_REQUEST_ID,
+ decision: DelegatedApprovalDecision.Approved
+ });
+ });
+
+ test("applies a rejection without granting anything", async () => {
+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Rejected, { notes: "Not now." }));
+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog } = 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(row()?.status).toBe(DelegatedApprovalRequestStatus.Rejected);
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Rejected);
+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();
+ auditedWith(createAuditLog, { decision: DelegatedApprovalDecision.Rejected, decisionNotes: "Not now." });
+ });
+
+ test("accepts the record's permissions in whatever order and padding the system stores them", async () => {
+ fetchDecision.mockResolvedValueOnce(
+ decided(DelegatedApprovalDecision.Approved, { permissions: ["secret-folders:edit", "secrets:read,create"] })
+ );
+ const { consumer, row } = buildConsumer();
+
+ await consumer.handle([makeEvent()]);
+
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Approved);
+ });
+
+ test("fails for good when the approved permissions differ from the request, and closes the request", async () => {
+ fetchDecision.mockResolvedValueOnce(
+ decided(DelegatedApprovalDecision.Approved, {
+ permissions: ["secrets: read, create, delete", "secret-folders: edit"]
+ })
+ );
+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog, notify } = buildConsumer();
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(result.error).toContain("approved different permissions");
+ expect(result.error).toContain("Requested: secret-folders: edit; secrets: create, read");
+ expect(result.error).toContain("Approved in ServiceNow: secret-folders: edit; secrets: create, delete, read");
+ expect(row()).toMatchObject({
+ status: DelegatedApprovalRequestStatus.Failed,
+ details: { statusReason: result.error, provider: SERVICENOW_RECORD }
+ });
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();
+ expect(notify).not.toHaveBeenCalled();
+ auditedWith(createAuditLog, { outcome: DelegatedApprovalDecisionOutcome.Failed, reason: result.error });
+ });
+
+ test("fails for good when the record belongs to another request", async () => {
+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved, { approvalRequestId: "other" }));
+ const { consumer, row, approval } = buildConsumer();
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ });
+
+ test("cancels a request whose requester was deleted without reading the decision", async () => {
+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog } = buildConsumer({
+ approvalRequest: { ...pendingApprovalRequest, requesterId: null }
+ });
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(result.error).toContain("was deleted");
+ expect(fetchDecision).not.toHaveBeenCalled();
+ expect(row()).toMatchObject({
+ status: DelegatedApprovalRequestStatus.Failed,
+ details: { statusReason: result.error }
+ });
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();
+ auditedWith(createAuditLog, { outcome: DelegatedApprovalDecisionOutcome.Failed, reason: result.error });
+ });
+
+ test("cancels a request whose requester left the project without reading the decision", async () => {
+ const { consumer, row, approval, postApprovalTxRoutine } = buildConsumer({ isRequesterProjectMember: false });
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(result.error).toContain("no longer a member of this project");
+ expect(fetchDecision).not.toHaveBeenCalled();
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();
+ });
+
+ test("retries while the system has not recorded a decision, telling the user why", async () => {
+ fetchDecision.mockResolvedValueOnce({ status: "pending", reason: "ServiceNow has not recorded a decision yet." });
+ const { consumer, row, approval, createAuditLog } = buildConsumer();
+
+ const results = await consumer.handle([makeEvent()]);
+
+ expect(results).toEqual([
- { id: "1", status: EventResultStatus.Retry, error: "ServiceNow has not recorded a decision yet." }
++ { id: "event-1", status: EventResultStatus.Retry, error: "ServiceNow has not recorded a decision yet." }
+ ]);
+ expect(row()).toMatchObject({
+ status: DelegatedApprovalRequestStatus.WaitingApproval,
+ details: {
+ statusReason: `ServiceNow has not recorded a decision yet. ${DELEGATED_APPROVAL_DECISION_RETRY_HINT}`,
+ provider: SERVICENOW_RECORD
+ }
+ });
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);
+ expect(row()?.decisionReadRequestedAt).toEqual(DECISION_READ_REQUESTED_AT);
+ expect(createAuditLog).not.toHaveBeenCalled();
+ });
+
+ test("retries a transient read failure without touching the request", async () => {
+ fetchDecision.mockRejectedValueOnce(new Error("ServiceNow could not be reached."));
+ const { consumer, row, approval } = buildConsumer();
+
+ const [result] = await consumer.handle([makeEvent()]);
+
- expect(result).toEqual({ id: "1", status: EventResultStatus.Retry, error: "ServiceNow could not be reached." });
++ expect(result).toEqual({
++ id: "event-1",
++ status: EventResultStatus.Retry,
++ error: "ServiceNow could not be reached."
++ });
+ expect(row()).toMatchObject({ status: DelegatedApprovalRequestStatus.WaitingApproval });
+ expect(row()?.details.statusReason).toContain(DELEGATED_APPROVAL_DECISION_RETRY_HINT);
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);
+ });
+
+ test("fails for good on an unrecoverable read error", async () => {
+ fetchDecision.mockRejectedValueOnce(new UnrecoverableError("ServiceNow rejected the credentials."));
+ const { consumer, row, approval } = buildConsumer();
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result).toEqual({
- id: "1",
++ id: "event-1",
+ status: EventResultStatus.Failed,
+ error: "ServiceNow rejected the credentials."
+ });
+ expect(row()).toMatchObject({
+ status: DelegatedApprovalRequestStatus.Failed,
+ details: { statusReason: "ServiceNow rejected the credentials." }
+ });
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ });
+
+ test("fails for good without reading when the policy names an unsupported delegated approval system", async () => {
+ const { consumer, row, approval, createAuditLog } = buildConsumer({
+ policy: { ...delegatedPolicy, type: "jira" as DelegatedApprovalPolicyType }
+ });
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(result.error).toBe("The delegated approval system 'jira' is not supported. Create the request again.");
+ expect(fetchDecision).not.toHaveBeenCalled();
+ expect(row()).toMatchObject({
+ status: DelegatedApprovalRequestStatus.Failed,
+ details: { statusReason: result.error }
+ });
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ auditedWith(createAuditLog, {
+ outcome: DelegatedApprovalDecisionOutcome.Failed,
+ reason: result.error,
+ delegatedApprovalType: "the delegated approval system"
+ });
+ });
+
+ test.each([
+ ["the delegated approver was removed from the policy", { policy: null }],
+ ["the connection is gone", { connection: null }],
+ ["the connection belongs to another org", { connection: { id: "connection-1", orgId: "other-org" } }]
+ ])("fails for good without reading when %s", async (_, overrides) => {
+ const { consumer, row, approval } = buildConsumer(overrides);
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(fetchDecision).not.toHaveBeenCalled();
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ });
+
+ test("records a decision that arrives after the request was cancelled, without granting", async () => {
+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));
+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog } = buildConsumer({
+ approvalRequest: { ...pendingApprovalRequest, status: ApprovalRequestStatus.Cancelled }
+ });
+
+ const results = await consumer.handle([makeEvent()]);
+
- expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);
++ expect(results).toEqual([{ id: "event-1", status: EventResultStatus.Delivered }]);
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);
+ expect(row()?.details.statusReason).toContain("after the request was cancelled");
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();
+ auditedWith(createAuditLog, { outcome: DelegatedApprovalDecisionOutcome.Failed });
+ });
+
+ test("expires a request whose decision arrives after its deadline", async () => {
+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));
+ const { consumer, row, approval, postApprovalTxRoutine } = buildConsumer({
+ approvalRequest: { ...pendingApprovalRequest, expiresAt: new Date(Date.now() - 60_000) }
+ });
+
+ await consumer.handle([makeEvent()]);
+
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);
+ expect(row()?.details.statusReason).toContain("expired");
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Expired);
+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();
+ });
+
+ test.each([
+ ["is gone", null],
+ ["was approved", { ...waitingDelegatedRequest, status: DelegatedApprovalRequestStatus.Approved }],
+ ["was rejected", { ...waitingDelegatedRequest, status: DelegatedApprovalRequestStatus.Rejected }],
+ ["failed", { ...waitingDelegatedRequest, status: DelegatedApprovalRequestStatus.Failed }],
+ ["was never sent", { ...waitingDelegatedRequest, status: DelegatedApprovalRequestStatus.PendingDispatch }]
+ ])("marks the event delivered without reading 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(fetchDecision).not.toHaveBeenCalled();
+ });
+
+ test("audits without a record number when the provider never reported one", async () => {
+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));
+ const { consumer, createAuditLog } = buildConsumer({
+ delegatedRequest: { ...waitingDelegatedRequest, details: { statusReason: null } }
+ });
+
+ await consumer.handle([makeEvent()]);
+
+ expect(createAuditLog).toHaveBeenCalledTimes(1);
+ const [entry] = createAuditLog.mock.calls[0] as unknown as [{ event: { metadata: Record<string, unknown> } }];
+ expect(entry.event.metadata).not.toHaveProperty("providerRecordNumber");
+ });
+
+ test("fails the event, not the request, when the callback names another record", async () => {
+ const { consumer, row } = buildConsumer({
+ delegatedRequest: { ...waitingDelegatedRequest, providerRequestId: "snow-2" }
+ });
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(fetchDecision).not.toHaveBeenCalled();
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.WaitingApproval);
+ });
+
+ test("stops checking on the last attempt without closing a request that has no decision yet", async () => {
+ fetchDecision.mockResolvedValueOnce({ status: "pending", reason: "ServiceNow has not recorded a decision yet." });
+ const { consumer, row, approval, createAuditLog } = buildConsumer();
+
+ const results = await consumer.handle([makeEvent({ isFinalAttempt: true })]);
+
+ expect(results).toEqual([
- { id: "1", status: EventResultStatus.Failed, error: "ServiceNow has not recorded a decision yet." }
++ { id: "event-1", status: EventResultStatus.Failed, error: "ServiceNow has not recorded a decision yet." }
+ ]);
+ expect(row()).toMatchObject({
+ status: DelegatedApprovalRequestStatus.WaitingApproval,
+ details: {
+ statusReason: `ServiceNow has not recorded a decision yet. ${DELEGATED_APPROVAL_DECISION_STOPPED_HINT}`
+ }
+ });
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);
+ expect(row()?.decisionReadRequestedAt).toBeNull();
+ expect(createAuditLog).not.toHaveBeenCalled();
+ });
+
+ test("stops checking on the last attempt after a transient read failure, keeping the request open", async () => {
+ fetchDecision.mockRejectedValueOnce(new Error("ServiceNow could not be reached."));
+ const { consumer, row, approval } = buildConsumer();
+
+ const [result] = await consumer.handle([makeEvent({ isFinalAttempt: true })]);
+
- expect(result).toEqual({ id: "1", status: EventResultStatus.Failed, error: "ServiceNow could not be reached." });
++ expect(result).toEqual({
++ id: "event-1",
++ status: EventResultStatus.Failed,
++ error: "ServiceNow could not be reached."
++ });
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.WaitingApproval);
+ expect(row()?.details.statusReason).toBe(
+ `ServiceNow could not be reached. ${DELEGATED_APPROVAL_DECISION_STOPPED_HINT}`
+ );
+ expect(row()?.decisionReadRequestedAt).toBeNull();
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);
+ });
+
+ test.each([
+ { isFinalAttempt: false, status: EventResultStatus.Retry, statusReason: null },
+ {
+ isFinalAttempt: true,
+ status: EventResultStatus.Failed,
+ statusReason: `The grant could not be written. ${DELEGATED_APPROVAL_DECISION_STOPPED_HINT}`
+ }
+ ])(
+ "rolls back a decision that could not be applied, and explains it once attempts run out (final=$isFinalAttempt)",
+ async ({ isFinalAttempt, status, statusReason }) => {
+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));
+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog } = buildConsumer();
+ postApprovalTxRoutine.mockRejectedValueOnce(new Error("The grant could not be written."));
+
+ const [result] = await consumer.handle([makeEvent({ isFinalAttempt })]);
+
- expect(result).toEqual({ id: "1", status, error: "The grant could not be written." });
++ expect(result).toEqual({ id: "event-1", status, error: "The grant could not be written." });
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.WaitingApproval);
+ expect(row()?.details.statusReason).toBe(statusReason);
+ expect(row()?.decisionReadRequestedAt).toEqual(isFinalAttempt ? null : DECISION_READ_REQUESTED_AT);
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);
+ expect(createAuditLog).not.toHaveBeenCalled();
+ }
+ );
+
+ test("reads different requests together", async () => {
+ const otherRequestId = "44444444-4444-4444-4444-444444444444";
+ let releaseFirst: () => void = () => {};
+ const firstHeld = new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+
+ fetchDecision.mockImplementation(async (input: { delegatedRequestId: string }) => {
+ if (input.delegatedRequestId === DELEGATED_REQUEST_ID) await firstHeld;
+ return { status: "pending", reason: "Not yet." };
+ });
+
+ const { consumer } = buildConsumer();
- const { payload } = makeEvent();
++ const { data } = makeEvent();
+ const pending = consumer.handle([
- makeEvent({ id: 1 }),
- makeEvent({ id: 2, payload: { ...(payload as Record<string, unknown>), delegatedRequestId: otherRequestId } })
++ makeEvent({ id: "event-1" }),
++ makeEvent({ id: "event-2", data: { ...(data as Record<string, unknown>), delegatedRequestId: otherRequestId } })
+ ]);
+
+ try {
+ await vi.waitFor(() => expect(fetchDecision).toHaveBeenCalledTimes(2));
+ } finally {
+ releaseFirst();
+ }
+
+ await expect(pending).resolves.toEqual([
- { id: "1", status: EventResultStatus.Retry, error: "Not yet." },
- { id: "2", status: EventResultStatus.Retry, error: "Not yet." }
++ { id: "event-1", status: EventResultStatus.Retry, error: "Not yet." },
++ { id: "event-2", status: EventResultStatus.Retry, error: "Not yet." }
+ ]);
+ });
+
+ test("reads 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;
+
+ fetchDecision.mockImplementation(async () => {
+ if (fetchDecision.mock.calls.length === 1) {
+ await firstHeld;
+ firstSettledAt = Date.now();
+ throw new Error("ServiceNow did not respond.");
+ }
+ secondStartedAt = Date.now();
+ return decided(DelegatedApprovalDecision.Approved);
+ });
+
+ 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(fetchDecision).toHaveBeenCalledTimes(1));
+ await new Promise((resolve) => {
+ setTimeout(resolve, 30);
+ });
+ expect(fetchDecision).toHaveBeenCalledTimes(1);
+ } finally {
+ releaseFirst();
+ }
+
+ const results = await pending;
+
+ expect(fetchDecision).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 callback payload");
+ expect(fetchDecision).not.toHaveBeenCalled();
+ });
+});
+
+// Why the read-back is an outbox consumer: a record whose decision is not stored yet is tried again
+// later, instead of being dropped by a callback that answered 200 before anything was read.
+describe("delegatedApprovalDecisionConsumer 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 record without a decision and applies it on a later flush", async () => {
+ fetchDecision
+ .mockResolvedValueOnce({ status: "pending", reason: "Not yet." })
+ .mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));
+ const built = buildConsumer();
+ const { service, rows, elapseBackoff } = buildOutbox(built.consumer);
- const { payload } = makeEvent();
++ const { data } = makeEvent();
+
- await service.emit({
- eventType: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
- payload: payload as Record<string, unknown>
- });
++ await service.emit([
++ {
++ id: EVENT_ID,
++ type: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
++ data: data as Record<string, unknown>
++ }
++ ]);
+ await service.drain({ consumer: built.consumer.name });
+
+ expect(rows[0]).toMatchObject({ status: EventOutboxStatus.Retry, attempts: 1, lastError: "Not yet." });
+ expect(built.row()?.status).toBe(DelegatedApprovalRequestStatus.WaitingApproval);
+
+ elapseBackoff();
+ await service.drain({ consumer: built.consumer.name });
+
+ expect(rows[0]).toMatchObject({ status: EventOutboxStatus.Delivered, attempts: 2 });
+ expect(built.row()?.status).toBe(DelegatedApprovalRequestStatus.Approved);
+ expect(fetchDecision).toHaveBeenCalledTimes(2);
+ });
+
+ test("leaves the request open and asks for the callback again once the outbox has used up its attempts", async () => {
+ fetchDecision.mockResolvedValue({ status: "pending", reason: "Not yet." });
+ const built = buildConsumer();
+ const { service, rows, elapseBackoff } = buildOutbox(built.consumer);
- const { payload } = makeEvent();
++ const { data } = makeEvent();
+
- await service.emit({
- eventType: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
- payload: payload as Record<string, unknown>
- });
++ await service.emit([
++ {
++ id: EVENT_ID,
++ type: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
++ data: data as Record<string, unknown>
++ }
++ ]);
+
+ 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: built.consumer.name });
+ expect(rows[0].status).toBe(EventOutboxStatus.Retry);
+ expect(built.row()?.details.statusReason).toBe(`Not yet. ${DELEGATED_APPROVAL_DECISION_RETRY_HINT}`);
+ elapseBackoff();
+ }
+
+ await service.drain({ consumer: built.consumer.name });
+
+ expect(fetchDecision).toHaveBeenCalledTimes(MAX_OUTBOX_ATTEMPTS);
+ expect(rows[0]).toMatchObject({ status: EventOutboxStatus.Failed, attempts: MAX_OUTBOX_ATTEMPTS });
+ expect(built.row()).toMatchObject({
+ status: DelegatedApprovalRequestStatus.WaitingApproval,
+ details: { statusReason: `Not yet. ${DELEGATED_APPROVAL_DECISION_STOPPED_HINT}` }
+ });
+ expect(built.approval()?.status).toBe(ApprovalRequestStatus.Pending);
+ });
+});
diff --cc backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.ts
index cfaae9a71c,0000000000..2be33b4283
mode 100644,000000..100644
--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.ts
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.ts
@@@ -1,52 -1,0 +1,50 @@@
+import {
+ DelegatedApprovalCallbackEventPayloadSchema,
+ isDelegatedApprovalCallbackEvent,
+ TDelegatedApprovalCallbackEventPayload
+} from "@app/services/delegated-approval-callback/delegated-approval-callback-events";
+import { parseEventPayload, runEventsConcurrentlyByKey } from "@app/services/event-outbox/event-outbox-fns";
+import { IEventConsumer, TEvent, TEventConsumerResult } from "@app/services/event-outbox/event-outbox-types";
+
+import {
+ DELEGATED_APPROVAL_DECISION_CONCURRENCY,
+ DELEGATED_APPROVAL_DECISION_CONSUMER
+} from "./delegated-approval-decision-constants";
+import { TDelegatedApprovalDecisionServiceFactory } from "./delegated-approval-decision-service";
+
+type TDelegatedApprovalDecisionConsumerDep = {
+ delegatedApprovalDecisionService: Pick<TDelegatedApprovalDecisionServiceFactory, "applyDecision">;
+};
+
+export const delegatedApprovalDecisionConsumerFactory = ({
+ delegatedApprovalDecisionService
+}: TDelegatedApprovalDecisionConsumerDep): IEventConsumer<TDelegatedApprovalCallbackEventPayload> => {
+ const $handleEvent = async (event: TEvent): Promise<TEventConsumerResult> => {
- const id = String(event.id);
-
+ const { data, failure } = parseEventPayload(
+ event,
+ DelegatedApprovalCallbackEventPayloadSchema,
+ "delegated approval callback"
+ );
+ if (failure) return failure;
+
+ const { delegatedRequestId, externalId } = data;
+ const outcome = await delegatedApprovalDecisionService.applyDecision({
+ delegatedRequestId,
+ externalId,
+ isFinalAttempt: event.isFinalAttempt
+ });
- return { id, ...outcome };
++ return { id: event.id, ...outcome };
+ };
+
+ return {
+ name: DELEGATED_APPROVAL_DECISION_CONSUMER,
- payloadSchema: DelegatedApprovalCallbackEventPayloadSchema,
++ dataSchema: DelegatedApprovalCallbackEventPayloadSchema,
+ subscribesTo: isDelegatedApprovalCallbackEvent,
+ handle: (events) =>
+ runEventsConcurrentlyByKey(events, {
- keyOf: (event) => DelegatedApprovalCallbackEventPayloadSchema.safeParse(event.payload).data?.delegatedRequestId,
++ keyOf: (event) => DelegatedApprovalCallbackEventPayloadSchema.safeParse(event.data).data?.delegatedRequestId,
+ concurrency: DELEGATED_APPROVAL_DECISION_CONCURRENCY,
+ handleEvent: $handleEvent
+ })
+ };
+};
diff --cc backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.test.ts
index dd46063c79,bd92e61c31..1eb94754c3
--- 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
@@@ -46,9 -50,10 +52,10 @@@ vi.mock("@app/services/app-connection/a
}));
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 RETRY_REASON = `ServiceNow did not respond. ${DELEGATED_APPROVAL_DISPATCH_RETRY_HINT}`;
+const SERVICENOW_RECORD = { type: DelegatedApprovalPolicyType.ServiceNow, recordNumber: "INFAR1000000" };
const pendingDelegatedRequest = {
id: DELEGATED_REQUEST_ID,
@@@ -155,26 -164,10 +164,26 @@@ describe("delegatedApprovalDispatchCons
approvalRequestId: "req-1",
callback: { token: "callback-token" }
});
- expect(row()).toMatchObject({
+ expect(row()).toEqual({
+ ...pendingDelegatedRequest,
status: DelegatedApprovalRequestStatus.WaitingApproval,
providerRequestId: "snow-1",
- statusReason: null
+ details: { statusReason: null, provider: SERVICENOW_RECORD }
+ });
+ });
+
+ test("delivers a request whose provider reported no record number", 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(row()).toEqual({
+ ...pendingDelegatedRequest,
+ status: DelegatedApprovalRequestStatus.WaitingApproval,
+ providerRequestId: "snow-1",
+ details: { statusReason: null }
});
});
@@@ -184,11 -177,8 +193,11 @@@
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 });
+ expect(row()).toMatchObject({
+ status: DelegatedApprovalRequestStatus.FailedDispatch,
+ details: { statusReason: RETRY_REASON }
+ });
});
test("fails terminally on an unrecoverable error without promising a retry", async () => {
@@@ -212,12 -202,12 +221,14 @@@
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.`
+ details: {
+ 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 },
diff --cc backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts
index aa6736d8ea,6a1e5d6098..2671c7e8c5
--- a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts
+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts
@@@ -290,29 -291,75 +290,28 @@@ export const delegatedApprovalDispatchC
};
const $handleEvent = async (event: TEvent): Promise<TEventConsumerResult> => {
- const { id } = event;
-
- 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(", ")}`
- };
- }
+ const { data, failure } = parseEventPayload(
+ event,
+ DelegatedApprovalDispatchRequestedPayloadSchema,
+ "delegated approval dispatch"
+ );
+ if (failure) return failure;
- return { id: String(event.id), ...(await $dispatch(data.delegatedRequestId, event.isFinalAttempt)) };
- return { id, ...(await $dispatch(payload.data.delegatedRequestId, event.isFinalAttempt)) };
++ return { id: event.id, ...(await $dispatch(data.delegatedRequestId, event.isFinalAttempt)) };
};
- const $runEvent = async (event: TEvent): Promise<TEventConsumerResult> => {
- try {
- return await $handleEvent(event);
- } catch (error) {
- return {
- 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.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);
- }
+ // Events for one request run serially, so two of them cannot both pass the providerRequestId check.
+ const handle = (events: TEvent[]): Promise<TEventConsumerResult[]> =>
+ runEventsConcurrentlyByKey(events, {
- keyOf: (event) =>
- DelegatedApprovalDispatchRequestedPayloadSchema.safeParse(event.payload).data?.delegatedRequestId,
++ keyOf: (event) => DelegatedApprovalDispatchRequestedPayloadSchema.safeParse(event.data).data?.delegatedRequestId,
+ concurrency: DELEGATED_APPROVAL_DISPATCH_CONCURRENCY,
+ handleEvent: $handleEvent
});
- 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-fns.ts
index 94bc771217,0000000000..03b6346ece
mode 100644,000000..100644
--- a/backend/src/services/event-outbox/event-outbox-fns.ts
+++ b/backend/src/services/event-outbox/event-outbox-fns.ts
@@@ -1,78 -1,0 +1,78 @@@
+import pLimit from "p-limit";
+import { z } from "zod";
+
+import { EventResultStatus, TEvent, TEventConsumerResult } from "./event-outbox-types";
+
+// A payload that fails the consumer's schema is a bug at the emit site, so the event is failed with
+// the issues named rather than retried.
+export const parseEventPayload = <T extends z.ZodTypeAny>(
+ event: TEvent,
+ schema: T,
+ label: string
+): { data: z.infer<T>; failure?: undefined } | { data?: undefined; failure: TEventConsumerResult } => {
- const parsed = schema.safeParse(event.payload);
++ const parsed = schema.safeParse(event.data);
+ if (parsed.success) return { data: parsed.data as z.infer<T> };
+
+ return {
+ failure: {
- id: String(event.id),
++ id: event.id,
+ status: EventResultStatus.Failed,
+ error: `Unreadable ${label} payload: ${parsed.error.issues.map((issue) => issue.message).join(", ")}`
+ }
+ };
+};
+
+// One event at a time, so two events for the same resource never race, and a throw costs only that
+// event a retry instead of the whole batch.
+export const runEventsSerially = async (
+ events: TEvent[],
+ handleEvent: (event: TEvent) => Promise<TEventConsumerResult>
+): Promise<TEventConsumerResult[]> => {
+ const results: TEventConsumerResult[] = [];
+
+ for (const event of events) {
+ try {
+ // eslint-disable-next-line no-await-in-loop -- ordering is the point
+ results.push(await handleEvent(event));
+ } catch (error) {
+ results.push({
- id: String(event.id),
++ id: event.id,
+ status: EventResultStatus.Retry,
+ error: error instanceof Error ? error.message : "Unknown error"
+ });
+ }
+ }
+
+ return results;
+};
+
+export const runEventsConcurrentlyByKey = async (
+ events: TEvent[],
+ {
+ keyOf,
+ concurrency,
+ handleEvent
+ }: {
+ keyOf: (event: TEvent) => string | undefined;
+ concurrency: number;
+ handleEvent: (event: TEvent) => Promise<TEventConsumerResult>;
+ }
+): Promise<TEventConsumerResult[]> => {
+ const groups: TEvent[][] = [];
+ const indexByKey = new Map<string, number>();
+
+ events.forEach((event) => {
- const key = keyOf(event) ?? `event:${String(event.id)}`;
++ const key = keyOf(event) ?? `event:${event.id}`;
+ const existing = indexByKey.get(key);
+ if (existing === undefined) {
+ indexByKey.set(key, groups.length);
+ groups.push([event]);
+ } else {
+ groups[existing].push(event);
+ }
+ });
+
+ const limit = pLimit(concurrency);
+ const groupResults = await Promise.all(groups.map((group) => limit(() => runEventsSerially(group, handleEvent))));
+ return groupResults.flat();
+};
diff --cc backend/src/services/membership-user/membership-user-service.ts
index 1506b6ef38,8ab98263d0..da2a40f46c
--- a/backend/src/services/membership-user/membership-user-service.ts
+++ b/backend/src/services/membership-user/membership-user-service.ts
@@@ -31,10 -32,9 +32,10 @@@ import { TAdditionalPrivilegeDALFactor
import { AuthMethod } from "../auth/auth-type";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TApplicationMembershipCleanupServiceFactory } from "../membership/application-membership-cleanup-service";
+import { lockMembershipsById } from "../membership/membership-dal";
import { assertProductWillRetainAdmin, assertSecretsTemporaryAccessAllowed } from "../membership/membership-fns";
import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
+ import { TProjectAccessRevokeServiceFactory } from "../membership/project-access-revoke-service";
import { TOrgDALFactory } from "../org/org-dal";
import { deleteOrgMembershipsFn } from "../org/org-fns";
import { isCustomOrgRole } from "../org/org-role-fns";