Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
chore: keep root and backend AGENTS.md under the Codex instruction budget
andrewhuhh8f98c993b617
diff --git a/.codex/config.toml b/.codex/config.tomlnew file mode 100644index 0000000000..f58330e8f0--- /dev/null+++ b/.codex/config.toml@@ -0,0 +1,3 @@+# Codex stops loading AGENTS.md files once their combined size reaches this many bytes.+# The default (32 KiB) cuts off the subsystem files under backend/src/.+project_doc_max_bytes = 98304diff --git a/AGENTS.md b/AGENTS.mdindex 8ebaeb8b9c..e0d8d42339 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,6 +1,6 @@# AGENTS.md-Repository-wide guidance for coding agents working in Infisical. Packages and subsystems have their own `AGENTS.md` files, listed in [Where guidance lives](#where-guidance-lives). Read the ones that cover the code you are changing.+Repository-wide guidance for coding agents working in Infisical. Packages and subsystems have their own `AGENTS.md` files. Read the ones that cover the code you are changing, starting from the table below.## Essential Commands@@ -14,46 +14,19 @@ 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.+Infisical is an open-source secret management platform. Each package below has its own `AGENTS.md`; read it before working there.++| Directory | What it is |+|---|---|+| [`backend/`](backend/AGENTS.md) | Fastify 4 API server, TypeScript, PostgreSQL via Knex, BullMQ queues. Its `AGENTS.md` links the subsystem files under `backend/src/`. |+| [`backend-go/`](backend-go/AGENTS.md) | Go API server (partial rewrite), chi + chita, raw pgx queries, same PostgreSQL database. |+| [`frontend/`](frontend/AGENTS.md) | React 19 SPA, Vite 8, TanStack Router + React Query, Tailwind CSS v4. |+| `wasm/<crate>/` | Rust crates compiled to WASM for the frontend, with bindings committed under `frontend/src/lib/<crate>/`. Run the rebuild command in the crate's `AGENTS.md` (e.g. [`wasm/ironrdp-decoder/AGENTS.md`](wasm/ironrdp-decoder/AGENTS.md)) after any change to its `src/` or `Cargo.toml`. |+| [`e2e/`](e2e/AGENTS.md) | Playwright suite against a deployed gamma; a failure blocks every prod deploy. Distinct from `backend/e2e-test/` (in-process Vitest). |+| [`tests/`](tests/AGENTS.md) | Go blackbox suite: a real Infisical in Docker, HTTP only, so it runs against the Node and Go servers unchanged. |+| [`docs/`](docs/AGENTS.md) | Mintlify documentation site, with its own Dockerfile. Reference it for up-to-date feature descriptions and API usage. |++Also at the root: `build-versions.env` (see Dependency Policy), `docker-compose.{dev,prod,bdd,e2e-dbs}.yml`, `Dockerfile.standalone-infisical` and its FIPS variant (see the self-hosting notes in `backend/AGENTS.md`), and `.github/` (CI workflows, PR template). Skills live in `.agents/skills/`: `docs-style` (any work under `docs/`) and `testing-secrets-ui` (end-to-end checks of the secrets UI).### Dependency Policy@@ -65,51 +38,11 @@ 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>`).--## Where guidance lives+## Cross-Cutting Patterns-Agents that load `AGENTS.md` files only for the directories they work in will not see a nested file until they open code under it. Use this table to find the one that applies.+### Backend Code Quality-| Area | Read |-|---|---|-| Node backend: commands, testing, architecture, wiring | [`backend/AGENTS.md`](backend/AGENTS.md) |-| Backend minimum quality bar, for every backend change | [`backend/CODE_QUALITY.md`](backend/CODE_QUALITY.md) |-| Alerting (shared module) | [`backend/src/services/alert/AGENTS.md`](backend/src/services/alert/AGENTS.md) |-| Event outbox | [`backend/src/services/event-outbox/AGENTS.md`](backend/src/services/event-outbox/AGENTS.md) |-| Permissions (CASL) | [`backend/src/ee/services/permission/AGENTS.md`](backend/src/ee/services/permission/AGENTS.md) |-| Delegated OAuth tokens | [`backend/src/services/oauth-client/AGENTS.md`](backend/src/services/oauth-client/AGENTS.md) |-| Provisioning identifiers and IdP profile sync | [`backend/src/services/user-alias/AGENTS.md`](backend/src/services/user-alias/AGENTS.md) |-| Scheduled jobs (cron manager) | [`backend/src/lib/cron/AGENTS.md`](backend/src/lib/cron/AGENTS.md) |-| Audit log storage and event classes | [`backend/src/ee/services/audit-log/AGENTS.md`](backend/src/ee/services/audit-log/AGENTS.md) |-| OpenTelemetry metrics | [`backend/src/lib/telemetry/AGENTS.md`](backend/src/lib/telemetry/AGENTS.md) |-| PostHog product analytics (backend) | [`backend/src/services/telemetry/AGENTS.md`](backend/src/services/telemetry/AGENTS.md) and [`ANALYTICS.md`](ANALYTICS.md) |-| Internal CA revocation (CRL, OCSP) and key sources | [`backend/src/services/certificate-authority/AGENTS.md`](backend/src/services/certificate-authority/AGENTS.md) |-| Instance root encryption key | [`backend/src/services/kms/AGENTS.md`](backend/src/services/kms/AGENTS.md) |-| PAM backend | [`backend/src/ee/services/pam/AGENTS.md`](backend/src/ee/services/pam/AGENTS.md) |-| Agent Vault backend | [`backend/src/ee/services/agent-vault/AGENTS.md`](backend/src/ee/services/agent-vault/AGENTS.md) |-| Go backend | [`backend-go/AGENTS.md`](backend-go/AGENTS.md) |-| Frontend | [`frontend/AGENTS.md`](frontend/AGENTS.md) |-| UI design system and product voice | [`DESIGN.md`](DESIGN.md) |-| Shared frontend component deprecations | [`frontend/src/components/COMPONENT_LIFECYCLE.md`](frontend/src/components/COMPONENT_LIFECYCLE.md) |-| WASM crates | `wasm/<crate>/AGENTS.md`, for example [`wasm/ironrdp-decoder/AGENTS.md`](wasm/ironrdp-decoder/AGENTS.md) |-| Playwright suite against gamma | [`e2e/AGENTS.md`](e2e/AGENTS.md) |-| Go blackbox API suite | [`tests/AGENTS.md`](tests/AGENTS.md) |-| Documentation | the `docs-style` skill and [`docs/STYLE_GUIDE.md`](docs/STYLE_GUIDE.md) |--Skills live in `.agents/skills/`: `docs-style` (any work under `docs/`) and `testing-secrets-ui` (end-to-end checks of the secrets UI).--## 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, 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.--Some of it needs judgment rather than a mechanical check. The deadlock rules cannot be caught by testing one request at a time. And a design that breaks REST should be raised with the author, with the conforming alternative proposed, rather than implemented silently or quietly "fixed" (some deviations are deliberate).--## Cross-Cutting Patterns+**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. `backend/AGENTS.md` explains how to apply it.### Code Comments@@ -125,17 +58,11 @@ Read [`ANALYTICS.md`](ANALYTICS.md) before adding or changing product analytics.### 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. Before changing a shared frontend component's lifecycle, read the [shared component lifecycle ledger](frontend/src/components/COMPONENT_LIFECYCLE.md) for current deprecations, blockers, and replacement decisions. Frontend conventions, including inline creation in entity pickers, are in [`frontend/AGENTS.md`](frontend/AGENTS.md).+Read [`DESIGN.md`](DESIGN.md) before producing new UI or user-visible copy, and the [shared component lifecycle ledger](frontend/src/components/COMPONENT_LIFECYCLE.md) before changing a shared frontend component's lifecycle.### 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. A clean run is not a substitute for reading the guide: the judgment calls it cannot check are the ones that matter most.+**Use the `docs-style` skill for any work under `docs/`** (`.agents/skills/docs-style/`), and read [`docs/AGENTS.md`](docs/AGENTS.md) for the review pass and `make lint-docs-branch`. 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.### Auth & Permissions@@ -174,4 +101,4 @@ Alerting (`backend/src/services/alert/`) and approvals (`backend/src/services/ap## Keeping AGENTS.md Files Up to Date-When a change adds a service, a pattern, or an invariant an agent would otherwise get wrong, update the `AGENTS.md` closest to that code. Put cross-cutting rules here, package rules in the package file, and subsystem detail in a file next to the subsystem's code, then add it to [Where guidance lives](#where-guidance-lives). Keep each file a map rather than a spec: concepts, where things live, and non-obvious invariants. Leave signatures, field lists, and step-by-step mechanics to the code.+When a change adds a service, a pattern, or an invariant an agent would otherwise get wrong, update the `AGENTS.md` closest to that code. Put cross-cutting rules here, package rules in the package file, and subsystem detail in a file next to the subsystem's code, then link it from its package's `AGENTS.md`. Keep each file a map rather than a spec: concepts, where things live, and non-obvious invariants. Leave signatures, field lists, and step-by-step mechanics to the code.diff --git a/backend/AGENTS.md b/backend/AGENTS.mdindex c9228b3f28..f0811b9b01 100644--- a/backend/AGENTS.md+++ b/backend/AGENTS.md@@ -4,6 +4,8 @@ This is the **backend** package of the Infisical monorepo — a Fastify 4 API se**Read [`CODE_QUALITY.md`](CODE_QUALITY.md) before any change in this package, and check the change against it, whatever the change is, before calling the task done.** This file covers *where* code goes and *which* pattern to follow; the quality guide covers the minimum any implementation has to handle. It is a deliberately non-exhaustive floor, so the topics it happens to cover are not a filter for whether it applies.+Some of it needs judgment rather than a mechanical check. The deadlock rules cannot be caught by testing one request at a time. And a design that breaks REST should be raised with the author, with the conforming alternative proposed, rather than implemented silently or quietly "fixed" (some deviations are deliberate).+## Essential CommandsAll commands run from the `backend/` directory:@@ -37,149 +39,7 @@ relative paths itself. Invariants that a config change can silently break:### Testing-Run both suites from the repo root, which is the same entry point CI uses:--- `make test-api-unit` — unit tests matching `./src/**/*.test.ts`-- `make test-api-e2e` — e2e tests matching `./e2e-test/**/*.spec.ts`-- `make test-api-e2e SPEC=<pattern>` — narrow to one spec, e.g. `SPEC=secret-sync`-- `make up-rotation-databases` — start the databases the secret rotation specs need, required- only for a full run (`docker-compose.e2e-dbs.yml`, and the Oracle image is large)-- `make down-test-suite-containers` — stop everything when finished--The secret rotation specs reach their databases by compose service name, so-`docker-compose.e2e-dbs.yml` pins the same compose project as the test stack and shares its-network. Without `make up-rotation-databases`, those specs fail on connection; the rest pass.--Both run inside the FIPS image (`Dockerfile.dev.fips`), which carries the native dependencies-the suites need (SoftHSM2, the Oracle client, the FIPS OpenSSL build) and pins the Node-version, so the host's does not matter. `docker-compose.test.yml` declares the image,-environment, mounts and services; `src`, `e2e-test` and both vitest configs are mounted, so-editing a test needs no rebuild but changing `package.json` or `tsconfig.json` does.--**`npm run test:e2e` directly is possible but destructive if misconfigured.** The Vitest-environment runs `DROP SCHEMA public CASCADE` on whatever database `.env.test` points at,-before every run. Copy `.env.test.example`, which targets the throwaway stack, and start it-with `make up-test-suite-containers`. Never point it at the dev database.--Unit tests go next to source as `*.test.ts` and test pure functions with Vitest globals (`describe`, `test`, `expect`).--E2E tests live in `e2e-test/routes/`. The custom Vitest environment (`e2e-test/vitest-environment-knex.ts`) bootstraps a full server with DB, Redis, and encryption. Tests use injected globals: `testServer` (Fastify instance), `jwtAuthToken` (pre-authenticated JWT). Use `testServer.inject()` for HTTP assertions. Test helpers in `e2e-test/testUtils/` provide CRUD wrappers for secrets, folders, and secret imports. See `e2e-test/routes/v1/org.spec.ts` for a representative e2e test.--#### Writing e2e tests with `testUtils`--**Build test state with the helpers in `e2e-test/testUtils/`, not by hand.** Before writing a-`testServer.inject` call or a `testDb` insert to set something up, check `testUtils/` for a helper-that already does it. If none exists, add one there rather than a local helper in the spec: two-specs had each written their own `createTargetUser` before `testUtils/users.ts` existed, and every-copy drifts on its own.--- **Isolate each test.** `createIsolatedOrgAndProject` (`fixtures.ts`) gives a test its own org and- project, a token scoped to it, and a `cleanup` that deletes the org. Prefer it over the shared- `seedData1` org and project, whose state leaks between tests and files.-- **Don't lean on the seed user as a participant.** When a test needs someone other than the caller- (a recipient, a member, a target), create them with `createUser` and `addUserMembership`- (`users.ts`). Those write rows directly because signup needs SRP, so the user can be named but- cannot log in.-- **Go through the API for everything else**, with the domain helpers (`secrets.ts`, `folders.ts`,- `alerts.ts`, `reminders.ts`, `identities.ts`, ...). Write a helper with `request()` (`request.ts`)- so a call is sent when made and a caller can `.expect()` a non-200 or take the `.raw()` response.-- **Assert on outcomes a user would see**: an API response, an email in `testSmtp`, a message at a- fake destination. Read `testDb` only when the API cannot show the thing under test (eg an alert- orphaned by a cascade), and say why in a comment.-- **Wait with `pollUntil`** (`poll.ts`) for anything asynchronous, never a fixed sleep.-- **Run background jobs on demand** through a pass-through wrapper in `e2e-test/fakes/` (eg- `reminder-queue.ts` and `event-outbox-queue.ts`, driven by `runDailyReminders` in `reminders.ts`).--#### Faking a third-party provider--**Never add test-only code to `src/`** — no test-mode enum members, no lookup map entries, no-`isTestMode` branches. Replace the module instead, from `test.alias` in-`vitest.e2e.config.mts`, with a double under `e2e-test/fakes/`. Production code stays unaware-a fake exists. `e2e-test/fakes/aws-parameter-store-sync-fns.ts` and its connection counterpart-are the worked examples, and the pre-existing `./license-fns` alias is the precedent.--Four things decide whether this works:--- **Alias the narrowest specifier.** Entries match the import string, so aliasing one a single- file imports (a barrel's `./x-fns` re-export) swaps that seam and leaves the constants,- schemas, types, router and lookup maps real.-- **`test.alias` must stay an array.** Vite's `mergeAlias` concatenates arrays with- `test.alias` first, but merges two objects, where the generic `@app` prefix matches before a- specific `@app/...` entry and the fake silently stops applying with no error.-- **Re-export whatever you do not replace.** The alias swaps the whole module, so an export you- omit stops existing for every importer of it.-- **Assert the fake still matches.** Nothing otherwise checks it against the module it- replaces. Export an assignment typed as `Pick<typeof RealModule, …>` so a signature change- fails type-checking rather than leaving the fake quietly wrong.--A fake must reproduce the contract under test, not merely record its input. The Parameter Store-fake reimplements the real reconciliation rules (skip empty writes, delete absent keys unless-deletion is disabled, respect the key schema), because those rules are the behavior the specs-exist to pin.--#### FIPS test image and the prebuilt toolchain--CI (`.github/workflows/run-backend-tests.yml`) runs the e2e suite inside a FIPS image built-from `Dockerfile.dev.fips`. The expensive, rarely-changing parts of that image (SoftHSM2,-Oracle Instant Client, the FIPS OpenSSL 3.1.2 build and the PQC OpenSSL 3.5.6 build) live in-**`Dockerfile.fips-toolchain`**, which is published to-`ghcr.io/infisical/backend-fips-toolchain` for amd64 and arm64 by-`.github/workflows/publish-fips-toolchain.yml` on pushes to `main`.--`Dockerfile.dev.fips` consumes it via the `TOOLCHAIN_IMAGE` build arg, so CI and local dev-pull the toolchain instead of spending ~15min compiling it. Consequences worth knowing:--- **Editing `Dockerfile.fips-toolchain` is expensive.** CI pins the image by the content hash- of that file, so a PR touching it has no published tag and rebuilds from source (the old,- slow path). It publishes once the PR lands on `main`. Keep app-level changes in- `Dockerfile.dev.fips`.-- **Don't add `cache-to: type=gha` back to the image build.** GHA cache is PR-scoped (so it- never hits on a PR's first run) and the repo's 10GB cache budget is already full; writing- image blobs there evicts the `node_modules` caches of every workflow.-- **The published image is an internal CI build cache, not a supported artifact.** It is- public only so CI and local dev can pull it; it carries no support or compatibility- guarantee. It is *not* the FIPS product image; that one is `infisical/infisical-fips`,- built from `Dockerfile.fips.standalone-infisical`. OCI labels on the image say the same.-- **Keep every third-party fetch pinned and checksummed.** SoftHSM2 is pinned to a commit- SHA (tags are mutable); both OpenSSL tarballs and the Oracle Instant Client zip are- SHA256-verified; the Infisical CLI apt package is version-pinned. Oracle Instant Client- is redistributed under the Oracle Free Distribution, Hosting, and Use Terms, which- require the license to travel with it, so `/opt/oracle/instantclient_23_26/BASIC_LICENSE`- must not be removed.--##### Building the dev stack without GHCR--`docker compose -f docker-compose.dev.yml build backend` pulls the toolchain from GHCR by-default. If GHCR is down, the package is private, you're offline, or you're iterating on the-toolchain itself, build it locally once and point the compose build at it:--```bash-# 1. Build the toolchain from source (~15min, or ~2min if your layer cache is warm)-docker build -f backend/Dockerfile.fips-toolchain -t fips-toolchain:local backend--# 2. Prefer .env, so it survives every compose invocation (see the warning below)-echo 'TOOLCHAIN_IMAGE=fips-toolchain:local' >> .env--# ...or pass it per-invocation. Both forms work but are easy to forget:-TOOLCHAIN_IMAGE=fips-toolchain:local docker compose -f docker-compose.dev.yml build backend-docker compose -f docker-compose.dev.yml build --build-arg TOOLCHAIN_IMAGE=fips-toolchain:local backend-```--**Use `.env` rather than a one-off env var.** The documented start command in-`docs/contributing/platform/developing.mdx` is `up --build`, which rebuilds the backend and-re-resolves the `TOOLCHAIN_IMAGE` default, so a per-invocation override silently stops-applying and you're back to a failing GHCR pull. Compose interpolates the project `.env` for-every invocation, so putting it there sticks.--Notes:--- Step 1 is only needed once per change to `Dockerfile.fips-toolchain`. The local tag name is- arbitrary; it just has to match what you point `TOOLCHAIN_IMAGE` at.-- An already-built `backend` image keeps working if GHCR is unreachable, as long as you don't- pass `--build`. This only bites on a rebuild.-- This is not an offline story. The toolchain build itself still fetches Debian packages, both- OpenSSL tarballs, SoftHSM sources, and the Oracle client. With no network at all, neither- path works and you need a previously built image.+Run `make test-api-unit` and `make test-api-e2e` (narrow with `SPEC=<pattern>`) from the repo root, the same entry point CI uses. **Never point `npm run test:e2e` at the dev database**: the Vitest environment runs `DROP SCHEMA public CASCADE` on whatever `.env.test` targets. Unit tests go next to source as `*.test.ts`. Never add test-only code to `src/`. Read [`e2e-test/AGENTS.md`](e2e-test/AGENTS.md) before writing or running tests; it covers `testUtils`, faking third-party providers, and the FIPS test image.### Database@@ -197,6 +57,16 @@ Notes:Path alias: `@app/*` maps to `./src/*`.+## Self-Hosting and Dependencies++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.++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>`).+## ESLint & Import OrderingConfig in `.eslintrc.js`. Uses `simple-import-sort` with this group order:@@ -260,27 +130,7 @@ See `src/server/routes/v4/secret-router.ts` for a representative router file.### Auth System-Auth extraction happens in `src/server/plugins/auth/`:-- `inject-identity.ts` — detects auth mode from request headers and attaches identity to request-- `verify-auth.ts` — middleware that checks if the request's auth mode is in the route's allowed strategies-- `inject-permission.ts` — attaches permission context-- `inject-assume-privilege.ts` — privilege escalation support-- `superAdmin.ts` — super admin flag injection--**Auth modes** (defined in `AuthMode` enum):-- **JWT** — user browser sessions (decoded from `Authorization: Bearer` header)-- **IDENTITY_ACCESS_TOKEN** — machine-to-machine identity tokens-- **SCIM_TOKEN** — SCIM provisioning tokens-- **OAUTH** — delegated user tokens from the `oauth-client` module. Same JWT shape and session binding as- `JWT`, told apart by an `oauthClientId` claim. See [Delegated OAuth tokens](src/services/oauth-client/AGENTS.md).--**Deprecated auth modes (do not use in new code):**-- **API_KEY** — user API keys (from `x-api-key` header). Deprecated — use identity access tokens instead.-- **SERVICE_TOKEN** — service tokens (Bearer tokens starting with `st.` prefix). Deprecated — use identity access tokens instead.--If you encounter `API_KEY` or `SERVICE_TOKEN` in existing code, do not replicate them in new routes or services. All new machine authentication should use `IDENTITY_ACCESS_TOKEN`.--Token detection logic in `inject-identity.ts` checks `x-api-key` header first, then parses `Authorization: Bearer` and inspects JWT `authTokenType` field to determine mode.+Auth modes are detected in `src/server/plugins/auth/` (`AuthMode`: JWT, IDENTITY_ACCESS_TOKEN, SCIM_TOKEN, OAUTH). **`API_KEY` and `SERVICE_TOKEN` are deprecated: never use them in new routes or services**; new machine authentication uses `IDENTITY_ACCESS_TOKEN`. Read [`src/server/plugins/auth/AGENTS.md`](src/server/plugins/auth/AGENTS.md) before changing how a route authenticates.**Delegated OAuth tokens** (`AuthMode.OAUTH`) are opt-in per route. Before listing it on a route, read [`src/services/oauth-client/AGENTS.md`](src/services/oauth-client/AGENTS.md): administration writes must not accept it (read-only administration routes may, with the credential-read exceptions listed there), and the handler must check a CASL ability, because that check is what applies the token's scopes.@@ -299,58 +149,11 @@ Read [`src/ee/services/permission/AGENTS.md`](src/ee/services/permission/AGENTS.### Request-Scoped Memoization-A per-request in-memory cache that eliminates redundant DB reads within a single HTTP request. Defined in `src/lib/request-context/request-memoizer.ts`, attached to Fastify's `@fastify/request-context` as the `memoizer` field (initialized in `src/server/app.ts`). Cache is automatically garbage-collected when the request ends — zero staleness risk, zero infrastructure.--**How it works**: `RequestMemoizer` wraps a `Map<string, unknown>` with an async `getOrSet(key, fetcher)` method. Concurrent calls for the same key coalesce onto a single fetcher invocation (in-flight deduplication). The `requestMemoize(key, fetcher)` helper reads the memoizer from request context and falls back to direct execution when no context exists (e.g. queue workers).--**Currently memoized**:-- `getProjectPermission` — full-function result (keyed by projectId + actor + actorId + actorOrgId + actorAuthMethod + actionProjectType). Eliminates redundant permission checks in batch secret operations (50 secrets → 1 DB round-trip instead of 50).-- `getOrgPermission` — full-function result (keyed by orgId + actor + actorId + actorOrgId + actorAuthMethod + scope).-- `projectDAL.findById` — in permission-service.ts and project-bot-fns.ts. Deduplicates 4 of the 5 redundant project lookups seen per secret read request.-- `userDAL.findById` / `identityDAL.findById` — in permission-service.ts. Eliminates the redundant actor lookup during permission resolution.--**Usage pattern**:-```ts-import { requestMemoize } from "@app/lib/request-context/request-memoizer";--// In a service or function called during request handling:-const project = await requestMemoize(- `project:findById:${projectId}`,- () => projectDAL.findById(projectId)-);-```--**When to add more items to request-scoped memoization**:-- The data is **read-only within the request** — no mutations to the same record happen between reads.-- The same DAL call (same table, same ID) is made **2+ times in the same request** across different services or functions. Check with Datadog traces or by searching for the DAL method across call sites in the hot path.-- The call does **NOT use a DB transaction** (`trx` parameter). Transactional reads may see different data than read-replica results; memoizing them could return stale data.-- The call is on a **hot path** (auth, permissions, secret CRUD). Low-frequency admin endpoints don't benefit enough to justify the added indirection.--**When NOT to use**:-- Inside DB transactions — pass `trx` directly, skip memoization.-- For data mutated within the request and re-read (e.g. KMS key creation writes to the project row, then re-reads it).-- In queue workers or background jobs — the helper falls back gracefully, but there's no request lifecycle to scope the cache.-- For write operations — only memoize reads.--**Key format convention**: `<entity>:<method>:<id>` for DAL calls (e.g. `project:findById:${projectId}`), `permission:<scope>:<id>:...` for permission results.+`requestMemoize(key, fetcher)` (`src/lib/request-context/`) dedupes repeated read-only DAL calls within one request. Never memoize a transactional read or a record the request mutates. Read [`src/lib/request-context/AGENTS.md`](src/lib/request-context/AGENTS.md) before adding a memoized call.### Queue System (BullMQ)-Queue infrastructure in `src/queue/queue-service.ts`. Defines 30+ named queues via `QueueName` enum (e.g., `SecretRotation`, `AuditLog`, `IntegrationSync`, `SecretReplication`, `SecretSync`, `DynamicSecretRevocation`). Each queue has typed payloads defined in `TQueueJobTypes`.--Queue jobs support: delays, attempts with exponential/fixed backoff, and completion/failure cleanup. **Use BullMQ only for event-driven, payload-carrying work** — jobs enqueued in response to a request or another job (audit log writes, integration syncs, secret replication, webhook fan-out, etc.).--**Do NOT use BullMQ repeatable jobs or `JobScheduler` for recurring/cron-pattern work.** All scheduled/periodic tasks must use the cron manager (see Scheduled Jobs below). The previous BullMQ-repeatable pattern has been migrated off, and `queueServiceFactory` actively cleans up stale repeatable queues and schedulers on boot (`src/queue/queue-service.ts:585-650`) — re-introducing a BullMQ repeatable will collide with that cleanup and cause double execution.--Queue handler factories (e.g., `src/services/secret/secret-queue.ts`) follow the same DI pattern as services — they receive DALs and services as dependencies.--`queueService.start(name, handler, opts)` accepts `concurrency` (per-worker parallelism ceiling) and BullMQ's `limiter: { max, duration }` (fleet-wide throughput cap, coordinated via Redis). Use both to **rate-shape DB-heavy background work** so a large backlog drains as an even plateau instead of a burst — see `src/services/project/project-cleanup-queue.ts`. The cron cadence must not be the pacer; load is bounded by `concurrency × per-job cost`, and the limiter caps steady throughput.--**`INFISICAL_RUN_MODES` gates the consumer, never the producer.** `start()` creates the BullMQ `Queue` for every queue in every run mode, and only skips creating the `Worker` when the queue isn't consumed by this pod: `secret-scanning` covers `SECRET_SCANNING_QUEUES`, `general-workers` covers everything else. This invariant is what makes splitting the fleet safe — an API-only pod runs no workers at all but must still be able to enqueue, since `queue()` silently no-ops on an uninitialized queue (`await q?.add(...)`) and would otherwise drop every job destined for another pod's worker. It also means `upsertJobScheduler` works from any pod, so boot-time scheduling needs no run-mode branch.--`QUEUE_WORKERS_ENABLED` and `QUEUE_WORKER_PROFILE` were replaced by `INFISICAL_RUN_MODES` and no longer exist.--**Worker heartbeats detect a fleet nobody deployed**, since an ungated producer means an `api`-only deployment silently queues work nothing consumes. In `src/lib/worker-heartbeat/worker-heartbeat.ts`: a `general-workers` pod `startReporting`s itself into a per-worker-type sorted set scored by its heartbeat deadline (60s beat, 5-minute TTL), and an `api` pod that doesn't run the fleet `startMonitoring`s it, logging an error while no instance reports. Observation only — never wire it into `/api/status`; a deployment missing its workers must still serve API traffic.+Use BullMQ only for event-driven, payload-carrying work. **Never use repeatable jobs or `JobScheduler` for recurring work**; that goes through the cron manager. `INFISICAL_RUN_MODES` gates the consumer, never the producer. Read [`src/queue/AGENTS.md`](src/queue/AGENTS.md) before adding a queue or changing its concurrency or rate limit.### Scheduled Jobs (Cron Manager)@@ -364,20 +167,7 @@ All user-facing "notify me when X happens" features share one module: `src/servi### Approvals-All "someone has to approve this before it happens" features share one module:-`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.+All "someone has to approve this before it happens" features share `src/services/approval-policy/`, and a policy type plugs in through one `TApprovalResource`. **Do not stand up a per-product approval service, request table, or review endpoint.** Read [`src/services/approval-policy/AGENTS.md`](src/services/approval-policy/AGENTS.md) before adding a policy type or an approval rule.### Event Outbox@@ -385,21 +175,7 @@ stop agreeing.### Soft-Delete + Async Cleanup-Resources whose deletion cascades across many/large tables use a **soft-delete + paced async hard-delete** pattern instead of a synchronous cascade in the request path.--Pattern:-- **Soft-delete columns** on the table: `deleteAfter`, `softDeletedAt`, `deletedByActorType`, `deletedByActorId`, plus a **partial index** `WHERE deleteAfter IS NOT NULL` (tiny, ~zero write cost on the live path). The DELETE handler sets `deleteAfter` (one UPDATE) and returns immediately. Set `deleteAfter = now()` for "real delete" UX (reaped on the next worker tick) or `now + grace` for a restore window. The actor pair follows the same `(actorType, actorId)` pattern used by audit logs — extensible to any `ActorType` without schema changes.-- **Hide soft-deleted rows from every read.** Override the `ormify` base `findById`/`findOne`/`find` to append `.whereNull("deleteAfter")`, and add explicit `*IncludingExpired` escape hatches used only by the cleanup worker/restore. Patch all custom read queries too — **especially any count feeding a plan/quota limit** (e.g. `countOfOrgProjects`), or soft-deleted rows wrongly count against limits. Free unique columns (e.g. the project slug) on soft-delete so the resource can be recreated immediately.-- **`Environment.deleteAfter` ≠ `Project.deleteAfter` — filter both.** The two soft-deletes are independent: soft-deleting a project does NOT soft-delete its environments. Many DALs already filter `Environment.deleteAfter` (from the env soft-delete) — that does **not** exclude a soft-deleted *project*'s data. So any **cron / cross-project enumeration** must also filter `Project.deleteAfter`: the rotation/sync/reminder queue queries, and cross-project listings (project/identity memberships, group projects, org product stats). External side effects are the dangerous case — without it, a soft-deleted project's secrets get rotated, synced, or reminded on during the cleanup window. Per-project reads resolved through `projectDAL.findById` are protected upstream (it returns nothing for a soft-deleted project).-- **Cron discovery + paced worker** (cron fans out to BullMQ): the cron selects the oldest `LIMIT N` expired rows (`ORDER BY deleteAfter ASC`) and enqueues one job each with a deterministic `jobId` (dedupe → queue stays bounded at ~N; never enqueue the whole backlog). The worker (`concurrency` + `limiter`) does the actual delete, re-reading via the **primary** under a per-resource lock to defeat replica-lag/restore races.-- **Chunk-deleting child rows: check inbound FKs first.** Reference implementation: `services/secret-v2-bridge/secret-tree-hard-delete-fns.ts` (project/env hard-delete workers).- - `CASCADE` / `SET NULL` inbound FKs → safe to chunk.- - `DEFERRABLE NO ACTION` → only if you delete the referencing rows in the **same transaction**; hard-delete paths only (never live deletes).- - Non-deferrable `NO ACTION` / `RESTRICT` → neither path is safe: it breaks the final cascade too (next bullet). Migrate the FK to `DEFERRABLE INITIALLY DEFERRED` first.- - Each batch: own transaction + `SET LOCAL statement_timeout`.-- **A non-deferrable `NO ACTION`/`RESTRICT` inbound FK is unsafe under cascading deletes; make it `DEFERRABLE INITIALLY DEFERRED`.** It is checked at end of *statement*, so within one cascading `DELETE` a parent branch can be processed before a sibling branch deletes the referencer, raising "update or delete on X violates FK on Y". When a CASCADE child of the deleted root is itself referenced by `NO ACTION`/`RESTRICT` FKs, declare those FKs `.deferrable("deferred")` so the check runs at COMMIT after the cascade completes (a *direct* parent delete is still blocked while a referencer remains). Audit **all** inbound `NO ACTION`/`RESTRICT` FKs of such a parent, not just one.-- **Index every FK referencing column that participates in a cascade.** Postgres does **not** auto-index FK columns. A cascade fires a **per-row** RI trigger on each child, so an unindexed child means one seq-scan *per deleted parent row*, which blows past `statement_timeout` on a chunked delete. Before chunk-deleting a large table, enumerate **every** inbound FK, including helper-generated ones: `createJunctionTable` (`src/db/utils.ts`) creates CASCADE FK columns with **no index** on either side, so every junction table needs explicit FK indexes. For a mostly-NULL nullable FK, a partial index `WHERE col IS NOT NULL` serves the cascade lookup at a fraction of the size/write cost.-- **Observe the backlog, not just the queue.** Queue depth caps at the discovery batch size, so it can't reveal the true backlog. Record the discovery result from the cron tick itself (e.g. `infisical.project_cleanup.discovered` / `infisical.project_env_cleanup.discovered` on the `InfisicalCore` meter: last batch size, capped at the discovery LIMIT). **Alert when the gauge stays at the cap** — it means the drain rate can't keep up (raise concurrency/limiter) or a mass-delete is in progress.+Resources whose deletion cascades across large tables are soft-deleted and hard-deleted later by a paced worker. Hide soft-deleted rows from every read, and filter both `Environment.deleteAfter` and `Project.deleteAfter`, because the two are independent. Read [`src/services/resource-cleanup/AGENTS.md`](src/services/resource-cleanup/AGENTS.md) before adding a soft-delete, a cascading foreign key, or a hard-delete worker.### Error Handling@@ -414,39 +190,17 @@ Custom error classes in `src/lib/errors/index.ts`:- `InternalServerError` (500)- `RateLimitError`- `ScimRequestError` — SCIM-specific formatting with schemas and status-- `ClientClosedRequestError` (499, nginx convention) — the client disconnected before the response was written; see below+- `ClientClosedRequestError` (499, nginx convention) — the client disconnected before the response was written; see "Stopping work after a client disconnect"Global error handler in `src/server/plugins/error-handler.ts` maps these to HTTP status codes and records OpenTelemetry error metrics.#### Stopping work after a client disconnect-Node keeps running a handler after its client has gone, and a disconnected client usually retries, so a CPU-heavy request that outlives its caller does the full cost again on another pod. Routes whose work can run long after the database reads finish (fan-out over folders, references, or imports) should stop when the connection closes. `GET /api/v3/secrets/raw` and `GET /api/v4/secrets` are examples.--- **Route:** pass `abortSignal: getClientDisconnectSignal(reply)` (`src/server/lib/client-disconnect.ts`) into the service. It aborts only when the socket closes before the response was written, so a normal completion never trips it.-- **Service:** call `throwIfClientDisconnected(abortSignal)` at fan-out points only: before each unit of work that triggers more reads (each reference, each import level, a shared folder load). Don't add one after every `await`; a check that saves a single query for a client that has already left is noise. Checks are cooperative, so an in-flight query or synchronous block still finishes, and a long synchronous block delays noticing the disconnect. Keep the per-item work linear.-- **`Promise.allSettled` fan-outs:** they swallow the rejection, so scan the results with `throwIfAnySettledClientClosed(results)` instead of rechecking the signal. A disconnect mid-fan-out means the result is partial and must not be cached or returned as reference errors; a result that completed before the client left should still be cached so the retry is a hit.-- **Catch blocks** that turn failures into an empty result (a folder that failed to load, a skipped cross-project read) must rethrow `ClientClosedRequestError` first, or the partial state gets cached.--The 499 never reaches the caller. It exists for logs (warn, no stack) and the `error.type="client_closed"` label on `infisical.core.http.error.count`. This is disconnect handling, not a request deadline: a slow client that stays connected is still bounded only by Fastify's 100s socket `connectionTimeout` in `src/server/app.ts`.+Long read fan-outs take `abortSignal: getClientDisconnectSignal(reply)` (`src/server/lib/client-disconnect.ts`) and stop when the client goes away, so a partial result is never cached. Read [`src/server/lib/AGENTS.md`](src/server/lib/AGENTS.md) before adding one.### Logging-Uses Pino via `@app/lib/logger`. Always include key identifiers in the message string using `[key=value]` format for log searchability. You may also pass a structured object as the first argument for programmatic access, but the message must be self-contained:--```ts-// Preferred: identifiers in message + structured object-logger.error({ sessionId, err }, `Failed to get connection details [sessionId=${sessionId}]`);--// Also acceptable: identifiers in message only-logger.info(`getPlan: Process done for [orgId=${orgId}] [projectId=${projectId}]`);--// NOT preferred: identifiers only in structured object, not in message-logger.error({ sessionId, err }, "Failed to get connection details");-```--**Never log an outbound URL verbatim — a URL is often itself a credential.** Incoming-webhook providers put the bearer secret in the path (`https://hooks.slack.com/services/T…/B…/<secret>`, Discord, Teams, Telegram) and many APIs accept a token as a query param, so a raw URL in a log line ships a working credential to the log sink. Pass it through `sanitizeUrlForLog` from `@app/lib/logger` first (`src/lib/logger/sanitize-url.ts`): it keeps only the origin, strips userinfo and the fragment, redacts the entire path, and redacts every query value. Token formats can't be recognised reliably, so the path is redacted by default for every host rather than sniffed with heuristics. The global axios response interceptor (`src/lib/config/request.ts`) and `safeRequest`'s dispatch log already do this.--Note that `logger.ts` also has a `redactedKeys` list applied to structured-object fields up to depth three. It only matches by key name, so it does **not** help with a secret embedded in a `url` field.+**Never log an outbound URL verbatim, because a URL is often itself a credential.** Read [`src/lib/logger/AGENTS.md`](src/lib/logger/AGENTS.md) before logging a URL, a header, or a provider response.### Internal CAs: revocation and key sources@@ -466,31 +220,9 @@ EE routes register before community routes so they can override/extend endpoints**Secret Scanning** is single-project (see the root `AGENTS.md`): `secret-scanning-v2-project-bootstrap.ts` creates the project with the org when it has a creator to make admin (like PAM and Agent Vault), `secret-scanning-v2-project-resolver.ts` picks the active project and lazily creates it, with every org admin as project admin, for older orgs and for orgs created from the admin console, whose admins are only invited after the org exists, and routes that take `projectId` read `req.internalSecretScanningProjectId`. A data source covers the resources it has rows for (added by a user or discovered from a push); its `config` only says where to look (Bitbucket workspace, GitLab group), never which resources, so scans, "included" state and GitLab account-scope webhooks all key off rows. Stored configs may still carry the old `includeRepos` / `includeProjects` keys, which nothing reads.-**Dynamic secret lease secrets needed at revoke time go in `dynamic_secret_leases.encryptedLeaseData`**, never in `externalEntityId` or `config` (both plaintext, and `externalEntityId` is returned by every lease route and logged in audit events). A provider opts in by listing the `create()` `data` keys in `persistedLeaseFields`; the lease service encrypts them with the project's SecretManager key and every revoke path passes them back as `metadata.leaseData`. Lease routes return `SanitizedDynamicSecretLeaseSchema` so the column never reaches a response. Secret *config* fields are listed separately in `DYNAMIC_SECRET_SECRET_FIELDS` (`providers/redact.ts`), as dotted paths so nested secrets work (`clientAuth.clientSecret`): reads strip them via `redactStoredInputs`, and an update that omits one keeps the stored value via `restoreOmittedSecretFields`, because the update merge is shallow.--**Gateways: there is only one generation.** Gateway v1 (`ee/services/gateway`, `lib/gateway`, the QUIC-transport over `@infisical/quic`, and `/api/v1/gateways`) is gone; `gateway-v2` and `gateway-pool` are the-whole story, and `lib/gateway-v2/types.ts` owns `GatewayProxyProtocol` / `GatewayHttpProxyActions`. What-survives is DB-only, and deliberately: the `gateways`, `org_gateway_config` and `project_gateways` tables-and the `gatewayId` columns on `dynamic_secrets`, `identity_kubernetes_auths` and-`identity_auth_templates` are still populated but never read or written, so the removal stays revertible.-Those three tables' `TableName` members exist for that reason alone.--Two consequences when touching a gateway dial path. Resolve the gateway with-`gatewayV2Service.getPlatformConnectionDetailsByGatewayId`, and when it returns nothing **throw**-(`getMissingGatewayMessage` in `lib/gateway-v2/gateway-errors.ts`) rather than continuing: every one of-these call sites sits in front of an `if (gatewayId)` guard whose else-branch dials the target host-directly, so falling through turns a dangling gateway reference into a silent bypass of the network-boundary the gateway exists to enforce. And `app_connections.gatewayId` is **not** a v1 column — unlike the-three above it never grew a `gatewayV2Id`, so that one column carries v2 ids and must stay.--**Any new path that attaches an individual gateway must call `assertIndividualGatewayAllowed`**-(`ee/services/gateway-pool/gateway-pool-policy-fns.ts`) next to its `AttachGateways` check. It enforces the-org-level `requireGatewayPools` setting. Pass the gateway the resource already had as `previousGatewayId`,-because clients re-send unchanged values on every save and resources created before the setting was turned-on must stay editable. The check reads the setting, not the plan, so it keeps applying after a downgrade.-Only exempt a mode that refuses pools outright, the way gateway Kubernetes auth in Gateway review mode does-(`$assertCanAttachProxy` in `resource-auth-method-service.ts`), or the policy removes that mode entirely.+**Dynamic secrets:** lease data needed at revoke time goes in `dynamic_secret_leases.encryptedLeaseData`, never in a plaintext column. See [`src/ee/services/dynamic-secret/AGENTS.md`](src/ee/services/dynamic-secret/AGENTS.md).++**Gateways:** only `gateway-v2` and `gateway-pool` are live. A missing gateway must throw, never fall through to a direct dial, and any new path that attaches a gateway must call `assertIndividualGatewayAllowed`. See [`src/ee/services/gateway-v2/AGENTS.md`](src/ee/services/gateway-v2/AGENTS.md).### Audit Logsdiff --git a/backend/e2e-test/AGENTS.md b/backend/e2e-test/AGENTS.mdnew file mode 100644index 0000000000..906eb52ff5--- /dev/null+++ b/backend/e2e-test/AGENTS.md@@ -0,0 +1,149 @@+# Backend testing++Paths are relative to `backend/`. Read [`backend/AGENTS.md`](../AGENTS.md) and [`backend/CODE_QUALITY.md`](../CODE_QUALITY.md) first.++## Testing++Run both suites from the repo root, which is the same entry point CI uses:++- `make test-api-unit` — unit tests matching `./src/**/*.test.ts`+- `make test-api-e2e` — e2e tests matching `./e2e-test/**/*.spec.ts`+- `make test-api-e2e SPEC=<pattern>` — narrow to one spec, e.g. `SPEC=secret-sync`+- `make up-rotation-databases` — start the databases the secret rotation specs need, required+ only for a full run (`docker-compose.e2e-dbs.yml`, and the Oracle image is large)+- `make down-test-suite-containers` — stop everything when finished++The secret rotation specs reach their databases by compose service name, so+`docker-compose.e2e-dbs.yml` pins the same compose project as the test stack and shares its+network. Without `make up-rotation-databases`, those specs fail on connection; the rest pass.++Both run inside the FIPS image (`Dockerfile.dev.fips`), which carries the native dependencies+the suites need (SoftHSM2, the Oracle client, the FIPS OpenSSL build) and pins the Node+version, so the host's does not matter. `docker-compose.test.yml` declares the image,+environment, mounts and services; `src`, `e2e-test` and both vitest configs are mounted, so+editing a test needs no rebuild but changing `package.json` or `tsconfig.json` does.++**`npm run test:e2e` directly is possible but destructive if misconfigured.** The Vitest+environment runs `DROP SCHEMA public CASCADE` on whatever database `.env.test` points at,+before every run. Copy `.env.test.example`, which targets the throwaway stack, and start it+with `make up-test-suite-containers`. Never point it at the dev database.++Unit tests go next to source as `*.test.ts` and test pure functions with Vitest globals (`describe`, `test`, `expect`).++E2E tests live in `e2e-test/routes/`. The custom Vitest environment (`e2e-test/vitest-environment-knex.ts`) bootstraps a full server with DB, Redis, and encryption. Tests use injected globals: `testServer` (Fastify instance), `jwtAuthToken` (pre-authenticated JWT). Use `testServer.inject()` for HTTP assertions. Test helpers in `e2e-test/testUtils/` provide CRUD wrappers for secrets, folders, and secret imports. See `e2e-test/routes/v1/org.spec.ts` for a representative e2e test.++### Writing e2e tests with `testUtils`++**Build test state with the helpers in `e2e-test/testUtils/`, not by hand.** Before writing a+`testServer.inject` call or a `testDb` insert to set something up, check `testUtils/` for a helper+that already does it. If none exists, add one there rather than a local helper in the spec: two+specs had each written their own `createTargetUser` before `testUtils/users.ts` existed, and every+copy drifts on its own.++- **Isolate each test.** `createIsolatedOrgAndProject` (`fixtures.ts`) gives a test its own org and+ project, a token scoped to it, and a `cleanup` that deletes the org. Prefer it over the shared+ `seedData1` org and project, whose state leaks between tests and files.+- **Don't lean on the seed user as a participant.** When a test needs someone other than the caller+ (a recipient, a member, a target), create them with `createUser` and `addUserMembership`+ (`users.ts`). Those write rows directly because signup needs SRP, so the user can be named but+ cannot log in.+- **Go through the API for everything else**, with the domain helpers (`secrets.ts`, `folders.ts`,+ `alerts.ts`, `reminders.ts`, `identities.ts`, ...). Write a helper with `request()` (`request.ts`)+ so a call is sent when made and a caller can `.expect()` a non-200 or take the `.raw()` response.+- **Assert on outcomes a user would see**: an API response, an email in `testSmtp`, a message at a+ fake destination. Read `testDb` only when the API cannot show the thing under test (eg an alert+ orphaned by a cascade), and say why in a comment.+- **Wait with `pollUntil`** (`poll.ts`) for anything asynchronous, never a fixed sleep.+- **Run background jobs on demand** through a pass-through wrapper in `e2e-test/fakes/` (eg+ `reminder-queue.ts` and `event-outbox-queue.ts`, driven by `runDailyReminders` in `reminders.ts`).++### Faking a third-party provider++**Never add test-only code to `src/`** — no test-mode enum members, no lookup map entries, no+`isTestMode` branches. Replace the module instead, from `test.alias` in+`vitest.e2e.config.mts`, with a double under `e2e-test/fakes/`. Production code stays unaware+a fake exists. `e2e-test/fakes/aws-parameter-store-sync-fns.ts` and its connection counterpart+are the worked examples, and the pre-existing `./license-fns` alias is the precedent.++Four things decide whether this works:++- **Alias the narrowest specifier.** Entries match the import string, so aliasing one a single+ file imports (a barrel's `./x-fns` re-export) swaps that seam and leaves the constants,+ schemas, types, router and lookup maps real.+- **`test.alias` must stay an array.** Vite's `mergeAlias` concatenates arrays with+ `test.alias` first, but merges two objects, where the generic `@app` prefix matches before a+ specific `@app/...` entry and the fake silently stops applying with no error.+- **Re-export whatever you do not replace.** The alias swaps the whole module, so an export you+ omit stops existing for every importer of it.+- **Assert the fake still matches.** Nothing otherwise checks it against the module it+ replaces. Export an assignment typed as `Pick<typeof RealModule, …>` so a signature change+ fails type-checking rather than leaving the fake quietly wrong.++A fake must reproduce the contract under test, not merely record its input. The Parameter Store+fake reimplements the real reconciliation rules (skip empty writes, delete absent keys unless+deletion is disabled, respect the key schema), because those rules are the behavior the specs+exist to pin.++### FIPS test image and the prebuilt toolchain++CI (`.github/workflows/run-backend-tests.yml`) runs the e2e suite inside a FIPS image built+from `Dockerfile.dev.fips`. The expensive, rarely-changing parts of that image (SoftHSM2,+Oracle Instant Client, the FIPS OpenSSL 3.1.2 build and the PQC OpenSSL 3.5.6 build) live in+**`Dockerfile.fips-toolchain`**, which is published to+`ghcr.io/infisical/backend-fips-toolchain` for amd64 and arm64 by+`.github/workflows/publish-fips-toolchain.yml` on pushes to `main`.++`Dockerfile.dev.fips` consumes it via the `TOOLCHAIN_IMAGE` build arg, so CI and local dev+pull the toolchain instead of spending ~15min compiling it. Consequences worth knowing:++- **Editing `Dockerfile.fips-toolchain` is expensive.** CI pins the image by the content hash+ of that file, so a PR touching it has no published tag and rebuilds from source (the old,+ slow path). It publishes once the PR lands on `main`. Keep app-level changes in+ `Dockerfile.dev.fips`.+- **Don't add `cache-to: type=gha` back to the image build.** GHA cache is PR-scoped (so it+ never hits on a PR's first run) and the repo's 10GB cache budget is already full; writing+ image blobs there evicts the `node_modules` caches of every workflow.+- **The published image is an internal CI build cache, not a supported artifact.** It is+ public only so CI and local dev can pull it; it carries no support or compatibility+ guarantee. It is *not* the FIPS product image; that one is `infisical/infisical-fips`,+ built from `Dockerfile.fips.standalone-infisical`. OCI labels on the image say the same.+- **Keep every third-party fetch pinned and checksummed.** SoftHSM2 is pinned to a commit+ SHA (tags are mutable); both OpenSSL tarballs and the Oracle Instant Client zip are+ SHA256-verified; the Infisical CLI apt package is version-pinned. Oracle Instant Client+ is redistributed under the Oracle Free Distribution, Hosting, and Use Terms, which+ require the license to travel with it, so `/opt/oracle/instantclient_23_26/BASIC_LICENSE`+ must not be removed.++##### Building the dev stack without GHCR++`docker compose -f docker-compose.dev.yml build backend` pulls the toolchain from GHCR by+default. If GHCR is down, the package is private, you're offline, or you're iterating on the+toolchain itself, build it locally once and point the compose build at it:++```bash+# 1. Build the toolchain from source (~15min, or ~2min if your layer cache is warm)+docker build -f backend/Dockerfile.fips-toolchain -t fips-toolchain:local backend++# 2. Prefer .env, so it survives every compose invocation (see the warning below)+echo 'TOOLCHAIN_IMAGE=fips-toolchain:local' >> .env++# ...or pass it per-invocation. Both forms work but are easy to forget:+TOOLCHAIN_IMAGE=fips-toolchain:local docker compose -f docker-compose.dev.yml build backend+docker compose -f docker-compose.dev.yml build --build-arg TOOLCHAIN_IMAGE=fips-toolchain:local backend+```++**Use `.env` rather than a one-off env var.** The documented start command in+`docs/contributing/platform/developing.mdx` is `up --build`, which rebuilds the backend and+re-resolves the `TOOLCHAIN_IMAGE` default, so a per-invocation override silently stops+applying and you're back to a failing GHCR pull. Compose interpolates the project `.env` for+every invocation, so putting it there sticks.++Notes:++- Step 1 is only needed once per change to `Dockerfile.fips-toolchain`. The local tag name is+ arbitrary; it just has to match what you point `TOOLCHAIN_IMAGE` at.+- An already-built `backend` image keeps working if GHCR is unreachable, as long as you don't+ pass `--build`. This only bites on a rebuild.+- This is not an offline story. The toolchain build itself still fetches Debian packages, both+ OpenSSL tarballs, SoftHSM sources, and the Oracle client. With no network at all, neither+ path works and you need a previously built image.diff --git a/backend/src/ee/services/dynamic-secret/AGENTS.md b/backend/src/ee/services/dynamic-secret/AGENTS.mdnew file mode 100644index 0000000000..a3f49f3ba2--- /dev/null+++ b/backend/src/ee/services/dynamic-secret/AGENTS.md@@ -0,0 +1,5 @@+# Dynamic secrets++Paths are relative to `backend/`. Read [`backend/AGENTS.md`](../../../../AGENTS.md) and [`backend/CODE_QUALITY.md`](../../../../CODE_QUALITY.md) first.++**Dynamic secret lease secrets needed at revoke time go in `dynamic_secret_leases.encryptedLeaseData`**, never in `externalEntityId` or `config` (both plaintext, and `externalEntityId` is returned by every lease route and logged in audit events). A provider opts in by listing the `create()` `data` keys in `persistedLeaseFields`; the lease service encrypts them with the project's SecretManager key and every revoke path passes them back as `metadata.leaseData`. Lease routes return `SanitizedDynamicSecretLeaseSchema` so the column never reaches a response. Secret *config* fields are listed separately in `DYNAMIC_SECRET_SECRET_FIELDS` (`providers/redact.ts`), as dotted paths so nested secrets work (`clientAuth.clientSecret`): reads strip them via `redactStoredInputs`, and an update that omits one keeps the stored value via `restoreOmittedSecretFields`, because the update merge is shallow.diff --git a/backend/src/ee/services/gateway-v2/AGENTS.md b/backend/src/ee/services/gateway-v2/AGENTS.mdnew file mode 100644index 0000000000..4504056fa8--- /dev/null+++ b/backend/src/ee/services/gateway-v2/AGENTS.md@@ -0,0 +1,27 @@+# Gateways++Paths are relative to `backend/`. Read [`backend/AGENTS.md`](../../../../AGENTS.md) and [`backend/CODE_QUALITY.md`](../../../../CODE_QUALITY.md) first.++**Gateways: there is only one generation.** Gateway v1 (`ee/services/gateway`, `lib/gateway`, the QUIC+transport over `@infisical/quic`, and `/api/v1/gateways`) is gone; `gateway-v2` and `gateway-pool` are the+whole story, and `lib/gateway-v2/types.ts` owns `GatewayProxyProtocol` / `GatewayHttpProxyActions`. What+survives is DB-only, and deliberately: the `gateways`, `org_gateway_config` and `project_gateways` tables+and the `gatewayId` columns on `dynamic_secrets`, `identity_kubernetes_auths` and+`identity_auth_templates` are still populated but never read or written, so the removal stays revertible.+Those three tables' `TableName` members exist for that reason alone.++Two consequences when touching a gateway dial path. Resolve the gateway with+`gatewayV2Service.getPlatformConnectionDetailsByGatewayId`, and when it returns nothing **throw**+(`getMissingGatewayMessage` in `lib/gateway-v2/gateway-errors.ts`) rather than continuing: every one of+these call sites sits in front of an `if (gatewayId)` guard whose else-branch dials the target host+directly, so falling through turns a dangling gateway reference into a silent bypass of the network+boundary the gateway exists to enforce. And `app_connections.gatewayId` is **not** a v1 column — unlike the+three above it never grew a `gatewayV2Id`, so that one column carries v2 ids and must stay.++**Any new path that attaches an individual gateway must call `assertIndividualGatewayAllowed`**+(`ee/services/gateway-pool/gateway-pool-policy-fns.ts`) next to its `AttachGateways` check. It enforces the+org-level `requireGatewayPools` setting. Pass the gateway the resource already had as `previousGatewayId`,+because clients re-send unchanged values on every save and resources created before the setting was turned+on must stay editable. The check reads the setting, not the plan, so it keeps applying after a downgrade.+Only exempt a mode that refuses pools outright, the way gateway Kubernetes auth in Gateway review mode does+(`$assertCanAttachProxy` in `resource-auth-method-service.ts`), or the policy removes that mode entirely.diff --git a/backend/src/lib/logger/AGENTS.md b/backend/src/lib/logger/AGENTS.mdnew file mode 100644index 0000000000..acc504f006--- /dev/null+++ b/backend/src/lib/logger/AGENTS.md@@ -0,0 +1,22 @@+# Logging++Paths are relative to `backend/`. Read [`backend/AGENTS.md`](../../../AGENTS.md) and [`backend/CODE_QUALITY.md`](../../../CODE_QUALITY.md) first.++## Logging++Uses Pino via `@app/lib/logger`. Always include key identifiers in the message string using `[key=value]` format for log searchability. You may also pass a structured object as the first argument for programmatic access, but the message must be self-contained:++```ts+// Preferred: identifiers in message + structured object+logger.error({ sessionId, err }, `Failed to get connection details [sessionId=${sessionId}]`);++// Also acceptable: identifiers in message only+logger.info(`getPlan: Process done for [orgId=${orgId}] [projectId=${projectId}]`);++// NOT preferred: identifiers only in structured object, not in message+logger.error({ sessionId, err }, "Failed to get connection details");+```++**Never log an outbound URL verbatim — a URL is often itself a credential.** Incoming-webhook providers put the bearer secret in the path (`https://hooks.slack.com/services/T…/B…/<secret>`, Discord, Teams, Telegram) and many APIs accept a token as a query param, so a raw URL in a log line ships a working credential to the log sink. Pass it through `sanitizeUrlForLog` from `@app/lib/logger` first (`src/lib/logger/sanitize-url.ts`): it keeps only the origin, strips userinfo and the fragment, redacts the entire path, and redacts every query value. Token formats can't be recognised reliably, so the path is redacted by default for every host rather than sniffed with heuristics. The global axios response interceptor (`src/lib/config/request.ts`) and `safeRequest`'s dispatch log already do this.++Note that `logger.ts` also has a `redactedKeys` list applied to structured-object fields up to depth three. It only matches by key name, so it does **not** help with a secret embedded in a `url` field.diff --git a/backend/src/lib/request-context/AGENTS.md b/backend/src/lib/request-context/AGENTS.mdnew file mode 100644index 0000000000..dbec1f54ad--- /dev/null+++ b/backend/src/lib/request-context/AGENTS.md@@ -0,0 +1,40 @@+# Request-scoped memoization++Paths are relative to `backend/`. Read [`backend/AGENTS.md`](../../../AGENTS.md) and [`backend/CODE_QUALITY.md`](../../../CODE_QUALITY.md) first.++## Request-Scoped Memoization++A per-request in-memory cache that eliminates redundant DB reads within a single HTTP request. Defined in `src/lib/request-context/request-memoizer.ts`, attached to Fastify's `@fastify/request-context` as the `memoizer` field (initialized in `src/server/app.ts`). Cache is automatically garbage-collected when the request ends — zero staleness risk, zero infrastructure.++**How it works**: `RequestMemoizer` wraps a `Map<string, unknown>` with an async `getOrSet(key, fetcher)` method. Concurrent calls for the same key coalesce onto a single fetcher invocation (in-flight deduplication). The `requestMemoize(key, fetcher)` helper reads the memoizer from request context and falls back to direct execution when no context exists (e.g. queue workers).++**Currently memoized**:+- `getProjectPermission` — full-function result (keyed by projectId + actor + actorId + actorOrgId + actorAuthMethod + actionProjectType). Eliminates redundant permission checks in batch secret operations (50 secrets → 1 DB round-trip instead of 50).+- `getOrgPermission` — full-function result (keyed by orgId + actor + actorId + actorOrgId + actorAuthMethod + scope).+- `projectDAL.findById` — in permission-service.ts and project-bot-fns.ts. Deduplicates 4 of the 5 redundant project lookups seen per secret read request.+- `userDAL.findById` / `identityDAL.findById` — in permission-service.ts. Eliminates the redundant actor lookup during permission resolution.++**Usage pattern**:+```ts+import { requestMemoize } from "@app/lib/request-context/request-memoizer";++// In a service or function called during request handling:+const project = await requestMemoize(+ `project:findById:${projectId}`,+ () => projectDAL.findById(projectId)+);+```++**When to add more items to request-scoped memoization**:+- The data is **read-only within the request** — no mutations to the same record happen between reads.+- The same DAL call (same table, same ID) is made **2+ times in the same request** across different services or functions. Check with Datadog traces or by searching for the DAL method across call sites in the hot path.+- The call does **NOT use a DB transaction** (`trx` parameter). Transactional reads may see different data than read-replica results; memoizing them could return stale data.+- The call is on a **hot path** (auth, permissions, secret CRUD). Low-frequency admin endpoints don't benefit enough to justify the added indirection.++**When NOT to use**:+- Inside DB transactions — pass `trx` directly, skip memoization.+- For data mutated within the request and re-read (e.g. KMS key creation writes to the project row, then re-reads it).+- In queue workers or background jobs — the helper falls back gracefully, but there's no request lifecycle to scope the cache.+- For write operations — only memoize reads.++**Key format convention**: `<entity>:<method>:<id>` for DAL calls (e.g. `project:findById:${projectId}`), `permission:<scope>:<id>:...` for permission results.diff --git a/backend/src/queue/AGENTS.md b/backend/src/queue/AGENTS.mdnew file mode 100644index 0000000000..5303421b4e--- /dev/null+++ b/backend/src/queue/AGENTS.md@@ -0,0 +1,21 @@+# Queue system (BullMQ)++Paths are relative to `backend/`. Read [`backend/AGENTS.md`](../../AGENTS.md) and [`backend/CODE_QUALITY.md`](../../CODE_QUALITY.md) first.++## Queue System (BullMQ)++Queue infrastructure in `src/queue/queue-service.ts`. Defines 30+ named queues via `QueueName` enum (e.g., `SecretRotation`, `AuditLog`, `IntegrationSync`, `SecretReplication`, `SecretSync`, `DynamicSecretRevocation`). Each queue has typed payloads defined in `TQueueJobTypes`.++Queue jobs support: delays, attempts with exponential/fixed backoff, and completion/failure cleanup. **Use BullMQ only for event-driven, payload-carrying work** — jobs enqueued in response to a request or another job (audit log writes, integration syncs, secret replication, webhook fan-out, etc.).++**Do NOT use BullMQ repeatable jobs or `JobScheduler` for recurring/cron-pattern work.** All scheduled/periodic tasks must use the cron manager (see [`src/lib/cron/AGENTS.md`](../lib/cron/AGENTS.md)). The previous BullMQ-repeatable pattern has been migrated off, and `queueServiceFactory` actively cleans up stale repeatable queues and schedulers on boot (`src/queue/queue-service.ts:585-650`) — re-introducing a BullMQ repeatable will collide with that cleanup and cause double execution.++Queue handler factories (e.g., `src/services/secret/secret-queue.ts`) follow the same DI pattern as services — they receive DALs and services as dependencies.++`queueService.start(name, handler, opts)` accepts `concurrency` (per-worker parallelism ceiling) and BullMQ's `limiter: { max, duration }` (fleet-wide throughput cap, coordinated via Redis). Use both to **rate-shape DB-heavy background work** so a large backlog drains as an even plateau instead of a burst — see `src/services/project/project-cleanup-queue.ts`. The cron cadence must not be the pacer; load is bounded by `concurrency × per-job cost`, and the limiter caps steady throughput.++**`INFISICAL_RUN_MODES` gates the consumer, never the producer.** `start()` creates the BullMQ `Queue` for every queue in every run mode, and only skips creating the `Worker` when the queue isn't consumed by this pod: `secret-scanning` covers `SECRET_SCANNING_QUEUES`, `general-workers` covers everything else. This invariant is what makes splitting the fleet safe — an API-only pod runs no workers at all but must still be able to enqueue, since `queue()` silently no-ops on an uninitialized queue (`await q?.add(...)`) and would otherwise drop every job destined for another pod's worker. It also means `upsertJobScheduler` works from any pod, so boot-time scheduling needs no run-mode branch.++`QUEUE_WORKERS_ENABLED` and `QUEUE_WORKER_PROFILE` were replaced by `INFISICAL_RUN_MODES` and no longer exist.++**Worker heartbeats detect a fleet nobody deployed**, since an ungated producer means an `api`-only deployment silently queues work nothing consumes. In `src/lib/worker-heartbeat/worker-heartbeat.ts`: a `general-workers` pod `startReporting`s itself into a per-worker-type sorted set scored by its heartbeat deadline (60s beat, 5-minute TTL), and an `api` pod that doesn't run the fleet `startMonitoring`s it, logging an error while no instance reports. Observation only — never wire it into `/api/status`; a deployment missing its workers must still serve API traffic.diff --git a/backend/src/server/lib/AGENTS.md b/backend/src/server/lib/AGENTS.mdnew file mode 100644index 0000000000..9be19e61f8--- /dev/null+++ b/backend/src/server/lib/AGENTS.md@@ -0,0 +1,14 @@+# Stopping work after a client disconnect++Paths are relative to `backend/`. Read [`backend/AGENTS.md`](../../../AGENTS.md) and [`backend/CODE_QUALITY.md`](../../../CODE_QUALITY.md) first.++## Stopping work after a client disconnect++Node keeps running a handler after its client has gone, and a disconnected client usually retries, so a CPU-heavy request that outlives its caller does the full cost again on another pod. Routes whose work can run long after the database reads finish (fan-out over folders, references, or imports) should stop when the connection closes. `GET /api/v3/secrets/raw` and `GET /api/v4/secrets` are examples.++- **Route:** pass `abortSignal: getClientDisconnectSignal(reply)` (`src/server/lib/client-disconnect.ts`) into the service. It aborts only when the socket closes before the response was written, so a normal completion never trips it.+- **Service:** call `throwIfClientDisconnected(abortSignal)` at fan-out points only: before each unit of work that triggers more reads (each reference, each import level, a shared folder load). Don't add one after every `await`; a check that saves a single query for a client that has already left is noise. Checks are cooperative, so an in-flight query or synchronous block still finishes, and a long synchronous block delays noticing the disconnect. Keep the per-item work linear.+- **`Promise.allSettled` fan-outs:** they swallow the rejection, so scan the results with `throwIfAnySettledClientClosed(results)` instead of rechecking the signal. A disconnect mid-fan-out means the result is partial and must not be cached or returned as reference errors; a result that completed before the client left should still be cached so the retry is a hit.+- **Catch blocks** that turn failures into an empty result (a folder that failed to load, a skipped cross-project read) must rethrow `ClientClosedRequestError` first, or the partial state gets cached.++The 499 never reaches the caller. It exists for logs (warn, no stack) and the `error.type="client_closed"` label on `infisical.core.http.error.count`. This is disconnect handling, not a request deadline: a slow client that stays connected is still bounded only by Fastify's 100s socket `connectionTimeout` in `src/server/app.ts`.diff --git a/backend/src/server/plugins/auth/AGENTS.md b/backend/src/server/plugins/auth/AGENTS.mdnew file mode 100644index 0000000000..3c76e6d7ac--- /dev/null+++ b/backend/src/server/plugins/auth/AGENTS.md@@ -0,0 +1,25 @@+# Auth system++Paths are relative to `backend/`. Read [`backend/AGENTS.md`](../../../../AGENTS.md) and [`backend/CODE_QUALITY.md`](../../../../CODE_QUALITY.md) first.++Auth extraction happens in `src/server/plugins/auth/`:+- `inject-identity.ts` — detects auth mode from request headers and attaches identity to request+- `verify-auth.ts` — middleware that checks if the request's auth mode is in the route's allowed strategies+- `inject-permission.ts` — attaches permission context+- `inject-assume-privilege.ts` — privilege escalation support+- `superAdmin.ts` — super admin flag injection++**Auth modes** (defined in `AuthMode` enum):+- **JWT** — user browser sessions (decoded from `Authorization: Bearer` header)+- **IDENTITY_ACCESS_TOKEN** — machine-to-machine identity tokens+- **SCIM_TOKEN** — SCIM provisioning tokens+- **OAUTH** — delegated user tokens from the `oauth-client` module. Same JWT shape and session binding as+ `JWT`, told apart by an `oauthClientId` claim. See [Delegated OAuth tokens](../../../services/oauth-client/AGENTS.md).++**Deprecated auth modes (do not use in new code):**+- **API_KEY** — user API keys (from `x-api-key` header). Deprecated — use identity access tokens instead.+- **SERVICE_TOKEN** — service tokens (Bearer tokens starting with `st.` prefix). Deprecated — use identity access tokens instead.++If you encounter `API_KEY` or `SERVICE_TOKEN` in existing code, do not replicate them in new routes or services. All new machine authentication should use `IDENTITY_ACCESS_TOKEN`.++Token detection logic in `inject-identity.ts` checks `x-api-key` header first, then parses `Authorization: Bearer` and inspects JWT `authTokenType` field to determine mode.diff --git a/backend/src/services/approval-policy/AGENTS.md b/backend/src/services/approval-policy/AGENTS.mdnew file mode 100644index 0000000000..82b69c72a0--- /dev/null+++ b/backend/src/services/approval-policy/AGENTS.md@@ -0,0 +1,20 @@+# Approvals++Paths are relative to `backend/`. Read [`backend/AGENTS.md`](../../../AGENTS.md) and [`backend/CODE_QUALITY.md`](../../../CODE_QUALITY.md) first.++## Approvals++All "someone has to approve this before it happens" features share one module:+`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.diff --git a/backend/src/services/resource-cleanup/AGENTS.md b/backend/src/services/resource-cleanup/AGENTS.mdnew file mode 100644index 0000000000..36d6fc46ee--- /dev/null+++ b/backend/src/services/resource-cleanup/AGENTS.md@@ -0,0 +1,21 @@+# Soft-delete and async cleanup++Paths are relative to `backend/`. Read [`backend/AGENTS.md`](../../../AGENTS.md) and [`backend/CODE_QUALITY.md`](../../../CODE_QUALITY.md) first.++## Soft-Delete + Async Cleanup++Resources whose deletion cascades across many/large tables use a **soft-delete + paced async hard-delete** pattern instead of a synchronous cascade in the request path.++Pattern:+- **Soft-delete columns** on the table: `deleteAfter`, `softDeletedAt`, `deletedByActorType`, `deletedByActorId`, plus a **partial index** `WHERE deleteAfter IS NOT NULL` (tiny, ~zero write cost on the live path). The DELETE handler sets `deleteAfter` (one UPDATE) and returns immediately. Set `deleteAfter = now()` for "real delete" UX (reaped on the next worker tick) or `now + grace` for a restore window. The actor pair follows the same `(actorType, actorId)` pattern used by audit logs — extensible to any `ActorType` without schema changes.+- **Hide soft-deleted rows from every read.** Override the `ormify` base `findById`/`findOne`/`find` to append `.whereNull("deleteAfter")`, and add explicit `*IncludingExpired` escape hatches used only by the cleanup worker/restore. Patch all custom read queries too — **especially any count feeding a plan/quota limit** (e.g. `countOfOrgProjects`), or soft-deleted rows wrongly count against limits. Free unique columns (e.g. the project slug) on soft-delete so the resource can be recreated immediately.+- **`Environment.deleteAfter` ≠ `Project.deleteAfter` — filter both.** The two soft-deletes are independent: soft-deleting a project does NOT soft-delete its environments. Many DALs already filter `Environment.deleteAfter` (from the env soft-delete) — that does **not** exclude a soft-deleted *project*'s data. So any **cron / cross-project enumeration** must also filter `Project.deleteAfter`: the rotation/sync/reminder queue queries, and cross-project listings (project/identity memberships, group projects, org product stats). External side effects are the dangerous case — without it, a soft-deleted project's secrets get rotated, synced, or reminded on during the cleanup window. Per-project reads resolved through `projectDAL.findById` are protected upstream (it returns nothing for a soft-deleted project).+- **Cron discovery + paced worker** (cron fans out to BullMQ): the cron selects the oldest `LIMIT N` expired rows (`ORDER BY deleteAfter ASC`) and enqueues one job each with a deterministic `jobId` (dedupe → queue stays bounded at ~N; never enqueue the whole backlog). The worker (`concurrency` + `limiter`) does the actual delete, re-reading via the **primary** under a per-resource lock to defeat replica-lag/restore races.+- **Chunk-deleting child rows: check inbound FKs first.** Reference implementation: `services/secret-v2-bridge/secret-tree-hard-delete-fns.ts` (project/env hard-delete workers).+ - `CASCADE` / `SET NULL` inbound FKs → safe to chunk.+ - `DEFERRABLE NO ACTION` → only if you delete the referencing rows in the **same transaction**; hard-delete paths only (never live deletes).+ - Non-deferrable `NO ACTION` / `RESTRICT` → neither path is safe: it breaks the final cascade too (next bullet). Migrate the FK to `DEFERRABLE INITIALLY DEFERRED` first.+ - Each batch: own transaction + `SET LOCAL statement_timeout`.+- **A non-deferrable `NO ACTION`/`RESTRICT` inbound FK is unsafe under cascading deletes; make it `DEFERRABLE INITIALLY DEFERRED`.** It is checked at end of *statement*, so within one cascading `DELETE` a parent branch can be processed before a sibling branch deletes the referencer, raising "update or delete on X violates FK on Y". When a CASCADE child of the deleted root is itself referenced by `NO ACTION`/`RESTRICT` FKs, declare those FKs `.deferrable("deferred")` so the check runs at COMMIT after the cascade completes (a *direct* parent delete is still blocked while a referencer remains). Audit **all** inbound `NO ACTION`/`RESTRICT` FKs of such a parent, not just one.+- **Index every FK referencing column that participates in a cascade.** Postgres does **not** auto-index FK columns. A cascade fires a **per-row** RI trigger on each child, so an unindexed child means one seq-scan *per deleted parent row*, which blows past `statement_timeout` on a chunked delete. Before chunk-deleting a large table, enumerate **every** inbound FK, including helper-generated ones: `createJunctionTable` (`src/db/utils.ts`) creates CASCADE FK columns with **no index** on either side, so every junction table needs explicit FK indexes. For a mostly-NULL nullable FK, a partial index `WHERE col IS NOT NULL` serves the cascade lookup at a fraction of the size/write cost.+- **Observe the backlog, not just the queue.** Queue depth caps at the discovery batch size, so it can't reveal the true backlog. Record the discovery result from the cron tick itself (e.g. `infisical.project_cleanup.discovered` / `infisical.project_env_cleanup.discovered` on the `InfisicalCore` meter: last batch size, capped at the discovery LIMIT). **Alert when the gauge stays at the cap** — it means the drain rate can't keep up (raise concurrency/limiter) or a mass-delete is in progress.diff --git a/docs/AGENTS.md b/docs/AGENTS.mdnew file mode 100644index 0000000000..c69d671091--- /dev/null+++ b/docs/AGENTS.md@@ -0,0 +1,9 @@+# Documentation++**Use the `docs-style` skill for any work under `docs/`** (`.agents/skills/docs-style/`). It carries the procedure for the [Documentation Style Guide](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](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. A clean run is not a substitute for reading the guide: the judgment calls it cannot check are the ones that matter most.