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
feat: refactoring and new endpoint to return the users and identities that have folder rbac permissions
adilsonad5e9500ecb3
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex b024f1e00b..61e15a2f5d 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with coThis is the **backend** package of the Infisical monorepo — a Fastify 4 API server with TypeScript, PostgreSQL via Knex, and BullMQ queues.-The backend code quality guide is imported below, so it is always in context for work in this package. **Check every 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.+The backend code quality guide is imported below, so it is always in context for work in this package. **Check every 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.@CODE_QUALITY.md@@ -49,7 +49,7 @@ pull the toolchain instead of spending ~15min compiling it. Consequences worth kimage blobs there evicts the `node_modules` caches of every workflow.- **The published image is an internal CI build cache, not a supported artifact.** It ispublic 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`,+ 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 commitSHA (tags are mutable); both OpenSSL tarballs and the Oracle Instant Client zip are@@ -111,6 +111,7 @@ Path alias: `@app/*` maps to `./src/*`.## ESLint & Import OrderingConfig in `.eslintrc.js`. Uses `simple-import-sort` with this group order:+1. Side-effect imports2. `node:` builtins3. Third-party packages@@ -126,6 +127,7 @@ Config in `.eslintrc.js`. Uses `simple-import-sort` with this group order:No IoC container. Every service is a factory function that receives explicit dependencies as a typed object and returns an object of methods. Dependencies are narrowed with TypeScript `Pick` to define minimal interface contracts.The entire dependency graph is manually wired in `src/server/routes/index.ts`:+- **~line 480-646**: DAL instantiation — each DAL factory receives the `db` client- **~line 649-2800**: Service instantiation — each factory receives its DALs + other services- **~line 2831-2972**: `server.decorate("services", {...})` exposes ~100+ services as `server.services.*`@@ -148,6 +150,7 @@ See `src/services/secret/secret-dal.ts` for a DAL that overrides the base `updat### Service Module StructureServices live in `src/services/` (100+ modules). Each typically contains:+- `*-dal.ts` — data access via `ormify()` + custom queries- `*-service.ts` — business logic factory- `*-types.ts` — DTOs and type definitions@@ -163,6 +166,7 @@ See `src/server/routes/v4/secret-router.ts` for a representative router file.### Auth SystemAuth 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@@ -170,11 +174,13 @@ Auth extraction happens in `src/server/plugins/auth/`:- `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**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.@@ -185,6 +191,7 @@ Token detection logic in `inject-identity.ts` checks `x-api-key` header first, t### Permission System (CASL)Uses CASL (`@casl/ability`) with MongoDB-style rules. Permission logic lives in `src/ee/services/permission/`:+- `permission-service.ts` — factory that builds CASL abilities from user/identity roles- `project-permission.ts` — defines project-level permission actions and subjects- `org-permission.ts` — defines org-level permission actions and subjects@@ -194,6 +201,7 @@ Uses CASL (`@casl/ability`) with MongoDB-style rules. Permission logic lives inBuilt-in roles: `Admin`, `Member`, `Viewer`, `NoAccess`. Custom roles use unpacked CASL rules stored in the database. Rules can include conditions with operators `$IN`, `$EQ`, `$NEQ`, `$GLOB` (for pattern matching like `prod-*`). See `PermissionConditionSchema` in `permission-types.ts`.**Project permission caching** uses a fingerprint-based two-tier cache (`withCacheFingerprint` in `src/lib/cache/with-cache.ts`):+- **Short-lived marker** (10s TTL) in Redis — while present, cached data is served with 0 DB reads.- **Long-lived data payload** (10m TTL) in Redis — holds the full permission blob plus a fingerprint hash.- On marker expiry, a lightweight **fingerprint query** (`getPermissionFingerprint` in `permission-dal.ts`) runs (1 DB read). If the fingerprint matches the cached payload, the marker is reset; otherwise, a full data re-fetch occurs.@@ -202,7 +210,7 @@ Built-in roles: `Admin`, `Member`, `Viewer`, `NoAccess`. Custom roles use unpack- **No explicit cache invalidation calls exist.** The fingerprint self-corrects within the marker TTL (10s eventual consistency for access granting). The old `invalidateProjectPermissionCache` / DAL version counter pattern has been removed.- Cache helpers (`cacheGet`, `cacheSet`, `applyReviver`) in `src/lib/cache/with-cache.ts` are shared between the simple `withCache` and the fingerprint-based `withCacheFingerprint`.-**Folder RBAC (folder-scoped privileges)**: `additional_privileges` rows with a `folderId` + `role` (`SecretFolderRole` tiers in `default-roles.ts`) are fetched in `getProjectPermission` through a second, longer-lived fingerprint cache (15m data / 15s marker) whose fingerprint is a Postgres version counter bumped by `permissionService.invalidateProjectFolderPermissionCache` (any future grant/revoke API and every folder rename/move/delete path MUST call it). When an actor holds folder grants, `buildProjectPermissionRules` appends per-grant CASL rules built by `buildFolderScopedPrivilegeRules` (`permission-fns.ts`): a deny of every secretPath-capable subject conditioned on `{ environment, secretPath }` (exact path, folder-only, subfolders fall back to base roles), followed by the folder role's allows with the same conditions. CASL gives the last matching rule precedence, so the folder role fully replaces base permissions at the granted path and nowhere else. The deny list `FOLDER_SCOPED_DENY_RULES` (`default-roles.ts`) is deliberately literal: `folder-scoped-privilege-rules.test.ts` enumerates `ProjectPermissionV2Schema` and fails when a new secretPath-scoped subject or action is added, forcing a human to extend the deny list and reconsider the role tiers. Only `getProjectPermission` evaluates folder grants; audits and `getProjectPermissions` do not yet.+**Folder RBAC (folder-scoped privileges)**: `additional_privileges` rows with a `folderId` + `role` (`SecretFolderRole` tiers in `folder-roles.ts`) are fetched in `getProjectPermission` through a second, longer-lived fingerprint cache (15m data / 15s marker) whose fingerprint is a Postgres version counter bumped by `permissionService.invalidateProjectFolderPermissionCache` (any future grant/revoke API and every folder rename/move/delete path MUST call it). When an actor holds folder grants, `buildProjectPermissionRules` appends per-grant CASL rules built by `buildFolderScopedPrivilegeRules` (`permission-fns.ts`): a deny of every secretPath-capable subject conditioned on `{ environment, secretPath }` (exact path, folder-only, subfolders fall back to base roles), followed by the folder role's allows with the same conditions. CASL gives the last matching rule precedence, so the folder role fully replaces base permissions at the granted path and nowhere else. The deny list `FOLDER_SCOPED_DENY_RULES` (`folder-roles.ts`) is deliberately literal: `folder-scoped-privilege-rules.test.ts` enumerates `ProjectPermissionV2Schema` and fails when a new secretPath-scoped subject or action is added, forcing a human to extend the deny list and reconsider the role tiers. Only `getProjectPermission` evaluates folder grants; audits and `getProjectPermissions` do not yet.### Request-Scoped Memoization@@ -211,29 +219,30 @@ A per-request in-memory cache that eliminates redundant DB reads within a single**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**:+```tsimport { 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)-);+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.@@ -253,7 +262,7 @@ Queue handler factories (e.g., `src/services/secret/secret-queue.ts`) follow the`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.-**`QUEUE_WORKER_PROFILE` gates the consumer, never the producer.** Whenever workers are enabled, `start()` creates the BullMQ `Queue` for every queue and only skips creating the `Worker` when the queue isn't in this pod's profile. This invariant is what makes splitting the fleet by profile safe: a pod that doesn't consume a queue must still be able to enqueue onto it, since `queue()` silently no-ops on an uninitialized queue (`await q?.add(...)`) and would otherwise drop every job destined for another profile's worker. `QUEUE_WORKERS_ENABLED=false` is the one exception and is deliberately absolute — it returns before the `Queue` is created (`src/queue/queue-service.ts:786`), so such a pod neither consumes *nor* produces, and both `queue()` and `upsertJobScheduler` are no-ops or throw. Code that schedules work at boot must branch on that flag rather than swallowing the failure, so a genuine Redis/BullMQ error still surfaces (see `src/ee/services/audit-log/audit-log-queue.ts`).+**`QUEUE_WORKER_PROFILE` gates the consumer, never the producer.** Whenever workers are enabled, `start()` creates the BullMQ `Queue` for every queue and only skips creating the `Worker` when the queue isn't in this pod's profile. This invariant is what makes splitting the fleet by profile safe: a pod that doesn't consume a queue must still be able to enqueue onto it, since `queue()` silently no-ops on an uninitialized queue (`await q?.add(...)`) and would otherwise drop every job destined for another profile's worker. `QUEUE_WORKERS_ENABLED=false` is the one exception and is deliberately absolute — it returns before the `Queue` is created (`src/queue/queue-service.ts:786`), so such a pod neither consumes _nor_ produces, and both `queue()` and `upsertJobScheduler` are no-ops or throw. Code that schedules work at boot must branch on that flag rather than swallowing the failure, so a genuine Redis/BullMQ error still surfaces (see `src/ee/services/audit-log/audit-log-queue.ts`).### Scheduled Jobs (Cron Manager)@@ -273,11 +282,13 @@ Recurring work runs through the cron manager in `src/lib/cron/cron-job.ts` (`croconst init = () => {cronJob.register({name: CronJobName.MyJob,- pattern: "*/5 * * * *", // standard cron, UTC- runHashTtlS: 60 * 60, // how long the run hash lives in Redis+ pattern: "*/5 * * * *", // standard cron, UTC+ runHashTtlS: 60 * 60, // how long the run hash lives in Redisenabled: !appCfg.isSecondaryInstance, // gate per-deploy if needed- maxAttempts: 3, // optional, default 3- handler: async () => { /* work */ }+ maxAttempts: 3, // optional, default 3+ handler: async () => {+ /* work */+ }});};return { init };@@ -287,15 +298,17 @@ Recurring work runs through the cron manager in `src/lib/cron/cron-job.ts` (`cro3. Add a corresponding alarm in the infrastructure repo so the new job is monitored. Follow the existing pattern in `infisical-shared-cloud/modules/redis_alarms/main.tf` — every cron job must have an alarm defined there. Don't ship a new cron job without wiring up its alarm.**Handler contract**:+- Each scheduled fire runs exactly once across the fleet: pods race for a per-run redlock, the winner executes the handler, and the others no-op. You don't need in-handler locking to guard against concurrent pods.- Handlers must be idempotent at the boundary of `handlerTimeoutMs` (default 5 min). A timeout marks the run failed-final and waits for the next fire — it does NOT retry the same fire, because the timed-out handler may still be running.- Failures (non-timeout) retry with exponential backoff (base 30 s, max 5 min) up to `maxAttempts`, but only if the retry would still fit before the next scheduled fire. Otherwise the next fire is treated as the natural retry.- Long-running handlers should override `handlerTimeoutMs` / `leaseDurationMs` per-entry (must satisfy `handlerTimeoutMs <= leaseDurationMs`).**When to use cron vs. queue**:+- Scheduled/recurring (every N minutes, daily at X, cron pattern) → `cronJob.register(...)`.- One-shot or event-triggered work (enqueued from a request handler or another job) → BullMQ queue + worker.-- A cron handler that fans out per-tenant work typically *enqueues BullMQ jobs* for each unit of work rather than doing the work inline — keep the cron tick fast and let the queue worker handle parallelism and retries for the actual payload.+- A cron handler that fans out per-tenant work typically _enqueues BullMQ jobs_ for each unit of work rather than doing the work inline — keep the cron tick fast and let the queue worker handle parallelism and retries for the actual payload.See `src/services/health-alert/health-alert-queue.ts` for a minimal example, `src/services/resource-cleanup/resource-cleanup-queue.ts` for a service with multiple registrations, and `src/ee/services/secret-rotation-v2/secret-rotation-v2-queue.ts` for a cron-tick that fans out into a BullMQ queue.@@ -319,6 +332,7 @@ Invariants worth knowing before extending it:- **Channel configs are encrypted** with the org/project KMS cipher (`alert-channel-crypto-fns.ts`) — never store or return them in plaintext.- **`findDueTargets` must return most-urgent-first.** The engine's per-channel `maxTargetsPerRun` cap keeps the head of the list and defers the tail, so ordering is what guarantees the closest-to-expiry targets are never the dropped ones.- **Deleting an alertable resource does NOT delete its alerts. You have to reap them yourself.** `alerts.resourceId` is a plain string column with **no foreign key** to the resource's table (a provider's `resourceType` can point at anything), so nothing cascades. Skip the reap and the row survives as a dangling alert whose `findDueTargets` matches nothing and whose "view" link 404s. Two helpers on `alertService`, and picking the wrong one is the bug:+- **`deleteAlertsForDeletedResource({ resourceType, resourceId })`** when the resource **row is gone**. It has **no scope filter** and reaps across every org and project. This is required, not just tidier: the same resource can be watched from another org (a root-org identity invited into a child org), so an `orgId`-filtered reap leaves those rows orphaned.- **`deleteAlertsForResource({ orgId, projectId?, resourceType, resourceId })`** when the resource merely **left a scope** (removed from a project, removed from an org) but still exists. Narrow on purpose: leaving one project must not drop the org-level alert, and leaving one org must not touch another org's alerts. Omitting `projectId` reaps the whole org, which is what org-membership removal wants since it cascades the project memberships.@@ -329,18 +343,20 @@ Invariants worth knowing before extending it: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).+- **`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.- **Only manually chunk-delete a table whose inbound FKs are all `CASCADE`/`SET NULL`.** A table with a `DEFERRABLE NO ACTION` inbound FK (e.g. `secret_rotation_v2_secret_mappings.secretId → secrets_v2`) must be left to the final `deleteById` cascade, which resolves the deferred check at COMMIT across the whole tree; deleting its parent outside that tree fails the check. Use `SET LOCAL statement_timeout` per batch so the bound can't leak to pooled connections. (Example: `secret_versions_v2` is chunked by `folderId` because all its inbound FKs are CASCADE/SET NULL and it has no `folderId`/`secretId` FK back to the project, so the project cascade would otherwise orphan it.)-- **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.+- **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.### Error HandlingCustom error classes in `src/lib/errors/index.ts`:+- `BadRequestError` (400) — with optional `details` field- `UnauthorizedError` (401)- `ForbiddenRequestError` (403) — with optional `details`@@ -376,6 +392,7 @@ Note that `logger.ts` also has a `redactedKeys` list applied to structured-objec### Enterprise (EE) FeaturesEnterprise code lives in `src/ee/`:+- `src/ee/services/` — 60+ service modules (access approval, audit log, dynamic secrets, external KMS, gateway, KMIP, LDAP, OIDC, PAM, PKI, SAML, SCIM, secret approval/rotation/replication, etc.)- `src/ee/routes/v1/` — 63 EE route files; `src/ee/routes/v2/` — 10 v2 route files@@ -386,6 +403,7 @@ EE routes register before community routes so they can override/extend endpoints### Server PluginsKey plugins in `src/server/plugins/`:+- `error-handler.ts` — global error handling with OpenTelemetry metrics- `fastify-zod.ts` — in-house Zod-to-OpenAPI transformation- `audit-log.ts` — request audit logging to queue@@ -402,14 +420,16 @@ Key plugins in `src/server/plugins/`:OpenTelemetry metric setup lives in `src/lib/telemetry/`. Instruments are defined in `metrics.ts` (resolved lazily so they bind to the real MeterProvider installed by `instrumentation.ts` after boot).**Meter split by cardinality:**+- **`InfisicalCore`** — the meter for all new metrics. A strict attribute allowlist (`INFISICAL_CORE_METER_ATTRIBUTES` in `telemetry-attributes.ts`) is applied via an SDK View, so **only bounded labels survive** — HTTP method, parameterized `http.route` template, and low-cardinality enums. This is the single choke point: any attribute passed at a call site that isn't in the allowlist is silently dropped.- **Legacy `Infisical` / `API` / `SecretSyncs` / `PkiSyncs` / `Integrations`** — carry unbounded per-actor labels (`HIGH_CARDINALITY_METER_NAMES`). Disabled wholesale via `OTEL_DROP_HIGH_CARDINALITY_METERS=true` in multi-tenant/cloud.**A new instrument goes on `InfisicalCore` and carries only bounded attributes.** The per-actor labels on the legacy meters are a deliberate exception, not a precedent: they are allowed only through `highCardinalityMeter`, so that `OTEL_DROP_HIGH_CARDINALITY_METERS` can switch them off. Do not put unbounded attributes on any other meter, and do not acquire a meter outside `src/lib/telemetry/` — ESLint blocks both `@opentelemetry/*` imports and `getMeter` access there, so use `highCardinalityMeter` for per-actor instruments and `resolveCoreMeter` for `InfisicalCore` observable gauges.-The gate has to sit at the call site because **a `DROP` aggregation does not bound memory; only an attributes processor does.** The SDK filters attributes *before* hashing them (so the allowlist View is bounded) but consults the aggregator *after* (so a dropped data point has already been keyed by its full attribute set). Under cumulative temporality — which `OTEL_EXPORT_TYPE=prometheus` mandates — `TemporalMetricProcessor` then retains one entry per distinct attribute set, with no cardinality cap, for the lifetime of the process. A meter whose data points are dropped therefore still leaks heap if anything records to it, which is why the flag stops the recording (`shouldRecordHighCardinalityMetrics` in `metrics.ts`) *and* the View strips attributes. With the flag off — the self-hosted default — that retention is the operator's informed choice; the tradeoff is documented in the monitoring guide.+The gate has to sit at the call site because **a `DROP` aggregation does not bound memory; only an attributes processor does.** The SDK filters attributes _before_ hashing them (so the allowlist View is bounded) but consults the aggregator _after_ (so a dropped data point has already been keyed by its full attribute set). Under cumulative temporality — which `OTEL_EXPORT_TYPE=prometheus` mandates — `TemporalMetricProcessor` then retains one entry per distinct attribute set, with no cardinality cap, for the lifetime of the process. A meter whose data points are dropped therefore still leaks heap if anything records to it, which is why the flag stops the recording (`shouldRecordHighCardinalityMetrics` in `metrics.ts`) _and_ the View strips attributes. With the flag off — the self-hosted default — that retention is the operator's informed choice; the tradeoff is documented in the monitoring guide.**Rules for InfisicalCore metrics:**+- **No per-tenant / per-actor identifiers** as labels — no org id, user id/email, identity id, ip, user agent, request id, or free-form values (e.g. environment slug). These scale series count with customer count, which breaks CloudWatch's 1000-datapoint-per-OTLP-request limit and drives per-GB ingestion cost. Use the **audit log table** for per-org / per-actor breakdowns.- Adding a new label means adding it to the allowlist in `telemetry-attributes.ts`. Only add **bounded** keys (fixed enums / static route templates), and document why.- `http.route` must be the parameterized template (`req.routeOptions.url`), never the raw request path.diff --git a/backend/e2e-test/routes/v1/user-folder-access.spec.ts b/backend/e2e-test/routes/v1/user-folder-access.spec.tsindex d15f76c232..75d7975892 100644--- a/backend/e2e-test/routes/v1/user-folder-access.spec.ts+++ b/backend/e2e-test/routes/v1/user-folder-access.spec.ts@@ -1,7 +1,17 @@-import { SecretFolderRole, TableName, TemporaryPermissionMode } from "@app/db/schemas";+import {+ AccessScope,+ OrgMembershipRole,+ OrgMembershipStatus,+ ProjectMembershipRole,+ SecretFolderRole,+ TableName,+ TemporaryPermissionMode+} from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";import { KeyStorePrefixes } from "@app/keystore/keystore";import { ms } from "@app/lib/ms";+import { alphaNumericNanoId } from "@app/lib/nanoid";+import { AuthMethod } from "@app/services/auth/auth-type";const projectId = seedData1.project.id;const userId = seedData1.id;@@ -11,6 +21,9 @@ const folderAccessUrl = (folderId?: string) =>folderId ? `/${folderId}` : ""}`;+const folderAccessUsersUrl = (folderId: string, query = "") =>+ `/api/v1/user-project-additional-privilege/projects/${projectId}/folder-access/${folderId}/users${query}`;+const authHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });const createFolder = async (dto: { path: string; name: string }) => {@@ -173,26 +186,6 @@ describe("User folder access CRUD", () => {expect(deleteAgainRes.statusCode).toBe(404);});- test("rejects a grant on the root folder", async () => {- const rootFolder = await testDb(TableName.SecretFolder)- .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)- .where(`${TableName.Environment}.projectId`, projectId)- .where(`${TableName.Environment}.slug`, seedData1.environment.slug)- .whereNull(`${TableName.SecretFolder}.parentId`)- .select(`${TableName.SecretFolder}.id`)- .first();- expect(rootFolder).toBeDefined();-- const res = await testServer.inject({- method: "POST",- url: folderAccessUrl(rootFolder!.id as string),- headers: authHeaders(),- body: { permission: SecretFolderRole.Read }- });- expect(res.statusCode).toBe(400);- expect(res.json().message).toContain("root folder");- });-test("returns 404 for a folder outside the project", async () => {const res = await testServer.inject({method: "POST",@@ -222,4 +215,228 @@ describe("User folder access CRUD", () => {});expect(res.statusCode).toBe(422);});++ describe("roster", () => {+ const listUsers = async (+ query = ""+ ): Promise<{+ users: { userId: string; username: string; folderAccess: Record<string, unknown> | null }[];+ totalCount: number;+ }> => {+ const res = await testServer.inject({+ method: "GET",+ url: folderAccessUsersUrl(folder.id, query),+ headers: authHeaders()+ });+ expect(res.statusCode).toBe(200);+ return res.json();+ };++ test("lists project users without a grant as folderAccess null", async () => {+ const { users, totalCount } = await listUsers();++ expect(totalCount).toBeGreaterThan(0);+ const seedUser = users.find((user) => user.userId === userId);+ expect(seedUser).toBeDefined();+ expect(seedUser!.folderAccess).toBeNull();+ expect(seedUser).not.toHaveProperty("roles");+ expect(seedUser).not.toHaveProperty("membershipId");+ });++ test("annotates the granted user and clears the annotation on revoke", async () => {+ const createRes = await testServer.inject({+ method: "POST",+ url: folderAccessUrl(folder.id),+ headers: authHeaders(),+ body: { permission: SecretFolderRole.Manage }+ });+ expect(createRes.statusCode).toBe(200);++ const { users } = await listUsers();+ const granted = users.find((user) => user.userId === userId);+ expect(granted!.folderAccess).toEqual(+ expect.objectContaining({+ projectId,+ folderId: folder.id,+ permission: SecretFolderRole.Manage,+ environment: seedData1.environment.slug,+ secretPath: "/user-folder-access",+ isTemporary: false+ })+ );+ expect(granted!.folderAccess).not.toHaveProperty("name");+ expect(granted!.folderAccess).not.toHaveProperty("permissions");++ const deleteRes = await testServer.inject({+ method: "DELETE",+ url: folderAccessUrl(folder.id),+ headers: authHeaders()+ });+ expect(deleteRes.statusCode).toBe(200);++ const { users: afterRevoke } = await listUsers();+ const revoked = afterRevoke.find((user) => user.userId === userId);+ expect(revoked).toBeDefined();+ expect(revoked!.folderAccess).toBeNull();+ });++ test("keeps totalCount stable across pages and past the end", async () => {+ const { totalCount } = await listUsers();++ const firstPage = await listUsers("?limit=1&offset=0");+ expect(firstPage.users).toHaveLength(Math.min(1, totalCount));+ expect(firstPage.totalCount).toBe(totalCount);++ const pastTheEnd = await listUsers(`?limit=1&offset=${totalCount + 10}`);+ expect(pastTheEnd.users).toEqual([]);+ expect(pastTheEnd.totalCount).toBe(totalCount);+ });++ test("filters by search", async () => {+ const matching = await listUsers(`?search=${encodeURIComponent(seedData1.email)}`);+ expect(matching.users.map((user) => user.userId)).toContain(userId);++ const nonMatching = await listUsers("?search=zzz-no-such-member");+ expect(nonMatching.users).toEqual([]);+ expect(nonMatching.totalCount).toBe(0);+ });++ test("rejects a folder outside the project", async () => {+ const outsideRes = await testServer.inject({+ method: "GET",+ url: folderAccessUsersUrl("00000000-0000-0000-0000-000000000000"),+ headers: authHeaders()+ });+ expect(outsideRes.statusCode).toBe(404);+ });++ test("rejects an out-of-range limit", async () => {+ const res = await testServer.inject({+ method: "GET",+ url: folderAccessUsersUrl(folder.id, "?limit=500"),+ headers: authHeaders()+ });+ expect(res.statusCode).toBe(422);+ });++ describe("group-derived users", () => {+ const orgId = seedData1.organization.id;+ let groupUserId: string;+ let groupId: string;+ let secondGroupId: string;++ const createGroupInProject = async (slug: string) => {+ const [group] = await testDb(TableName.Groups)+ .insert({ orgId, name: slug, slug })+ .returning("*");++ for (const scope of [AccessScope.Organization, AccessScope.Project] as const) {+ // eslint-disable-next-line no-await-in-loop+ const [membership] = await testDb(TableName.Membership)+ .insert({+ scope,+ scopeOrgId: orgId,+ scopeProjectId: scope === AccessScope.Project ? projectId : null,+ actorGroupId: group.id+ })+ .returning("*");+ // eslint-disable-next-line no-await-in-loop+ await testDb(TableName.MembershipRole).insert({+ membershipId: membership.id,+ role: scope === AccessScope.Project ? ProjectMembershipRole.Member : OrgMembershipRole.Member+ });+ }++ return group.id as string;+ };++ beforeAll(async () => {+ const username = `group-only-${alphaNumericNanoId(8)}@example.com`;+ const [user] = await testDb(TableName.Users)+ .insert({ username, email: username, isGhost: false, isAccepted: true, authMethods: [AuthMethod.EMAIL] })+ .returning("*");+ groupUserId = user.id as string;++ // org membership only; the project is reached purely through the group+ const [orgMembership] = await testDb(TableName.Membership)+ .insert({+ scope: AccessScope.Organization,+ scopeOrgId: orgId,+ actorUserId: groupUserId,+ status: OrgMembershipStatus.Accepted,+ isActive: true+ })+ .returning("*");+ await testDb(TableName.MembershipRole).insert({+ membershipId: orgMembership.id,+ role: OrgMembershipRole.Member+ });++ groupId = await createGroupInProject(`folder-access-grp-${alphaNumericNanoId(8)}`.toLowerCase());+ secondGroupId = await createGroupInProject(`folder-access-grp2-${alphaNumericNanoId(8)}`.toLowerCase());++ // the new user reaches the project through two groups; the seed admin is both a direct+ // member and a group member+ await testDb(TableName.UserGroupMembership).insert([+ { userId: groupUserId, groupId },+ { userId: groupUserId, groupId: secondGroupId },+ { userId, groupId }+ ]);+ });++ afterAll(async () => {+ await testDb(TableName.UserGroupMembership)+ .whereIn("groupId", [groupId, secondGroupId])+ .del();+ await testDb(TableName.Membership).whereIn("actorGroupId", [groupId, secondGroupId]).del();+ await testDb(TableName.Groups).whereIn("id", [groupId, secondGroupId]).del();+ await testDb(TableName.Membership).where({ actorUserId: groupUserId }).del();+ await testDb(TableName.Users).where({ id: groupUserId }).del();+ });++ test("lists a user whose only project access is a group", async () => {+ const { users } = await listUsers();+ const groupUser = users.find((user) => user.userId === groupUserId);++ expect(groupUser).toBeDefined();+ expect(groupUser!.folderAccess).toBeNull();+ });++ test("counts an actor once however many memberships reach them", async () => {+ const { users, totalCount } = await listUsers("?limit=100");++ // groupUserId is in two groups, userId is direct + in a group+ expect(users.filter((user) => user.userId === groupUserId)).toHaveLength(1);+ expect(users.filter((user) => user.userId === userId)).toHaveLength(1);+ expect(totalCount).toBe(users.length);+ expect(new Set(users.map((user) => user.userId)).size).toBe(users.length);+ });++ test("grants folder access to a group-derived user and shows it on the roster", async () => {+ const grantUrl = `/api/v1/user-project-additional-privilege/projects/${projectId}/users/${groupUserId}/folder-access/${folder.id}`;++ const createRes = await testServer.inject({+ method: "POST",+ url: grantUrl,+ headers: authHeaders(),+ body: { permission: SecretFolderRole.Read }+ });+ expect(createRes.statusCode).toBe(200);++ const { users } = await listUsers("?limit=100");+ const granted = users.find((user) => user.userId === groupUserId);+ expect(granted!.folderAccess).toEqual(+ expect.objectContaining({ folderId: folder.id, permission: SecretFolderRole.Read })+ );++ const deleteRes = await testServer.inject({ method: "DELETE", url: grantUrl, headers: authHeaders() });+ expect(deleteRes.statusCode).toBe(200);+ });++ test("finds a group-derived user by search", async () => {+ const { users } = await listUsers(`?search=group-only`);+ expect(users.map((user) => user.userId)).toContain(groupUserId);+ });+ });+ });});diff --git a/backend/e2e-test/routes/v2/identity-folder-access.spec.ts b/backend/e2e-test/routes/v2/identity-folder-access.spec.tsindex 642932f0ad..1449d0b2fc 100644--- a/backend/e2e-test/routes/v2/identity-folder-access.spec.ts+++ b/backend/e2e-test/routes/v2/identity-folder-access.spec.ts@@ -1,6 +1,14 @@-import { SecretFolderRole, TableName, TemporaryPermissionMode } from "@app/db/schemas";+import {+ AccessScope,+ OrgMembershipRole,+ ProjectMembershipRole,+ SecretFolderRole,+ TableName,+ TemporaryPermissionMode+} from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";import { ms } from "@app/lib/ms";+import { alphaNumericNanoId } from "@app/lib/nanoid";const projectId = seedData1.project.id;const identityId = seedData1.machineIdentity.id;@@ -10,6 +18,9 @@ const folderAccessUrl = (folderId?: string) =>folderId ? `/${folderId}` : ""}`;+const folderAccessIdentitiesUrl = (folderId: string, query = "") =>+ `/api/v2/identity-project-additional-privilege/projects/${projectId}/folder-access/${folderId}/identities${query}`;+const authHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });const createFolder = async (dto: { path: string; name: string }) => {@@ -87,9 +98,9 @@ describe("Identity folder access CRUD", () => {}));expect(new Date(created.temporaryAccessStartTime).toISOString()).toBe(temporaryAccessStartTime);- expect(new Date(created.temporaryAccessEndTime).getTime() - new Date(created.temporaryAccessStartTime).getTime()).toBe(- ms("1d")- );+ expect(+ new Date(created.temporaryAccessEndTime).getTime() - new Date(created.temporaryAccessStartTime).getTime()+ ).toBe(ms("1d"));const conflictRes = await testServer.inject({method: "POST",@@ -122,4 +133,153 @@ describe("Identity folder access CRUD", () => {expect(await testDb(TableName.AdditionalPrivilege).where({ id: created.id })).toEqual([]);});++ describe("roster", () => {+ const listIdentities = async (query = "") => {+ const res = await testServer.inject({+ method: "GET",+ url: folderAccessIdentitiesUrl(folder.id, query),+ headers: authHeaders()+ });+ expect(res.statusCode).toBe(200);+ return res.json() as {+ identities: { identityId: string; name: string; folderAccess: Record<string, unknown> | null }[];+ totalCount: number;+ };+ };++ test("lists project identities and annotates only the granted one", async () => {+ const before = await listIdentities();+ expect(before.totalCount).toBeGreaterThan(0);+ const seedIdentityBefore = before.identities.find((identity) => identity.identityId === identityId);+ expect(seedIdentityBefore).toBeDefined();+ expect(seedIdentityBefore!.folderAccess).toBeNull();+ expect(seedIdentityBefore).not.toHaveProperty("roles");++ const createRes = await testServer.inject({+ method: "POST",+ url: folderAccessUrl(folder.id),+ headers: authHeaders(),+ body: { permission: SecretFolderRole.Edit }+ });+ expect(createRes.statusCode).toBe(200);++ const after = await listIdentities();+ const granted = after.identities.find((identity) => identity.identityId === identityId);+ expect(granted!.folderAccess).toEqual(+ expect.objectContaining({+ projectId,+ folderId: folder.id,+ permission: SecretFolderRole.Edit,+ environment: seedData1.environment.slug,+ isTemporary: false+ })+ );+ expect(after.totalCount).toBe(before.totalCount);++ const deleteRes = await testServer.inject({+ method: "DELETE",+ url: folderAccessUrl(folder.id),+ headers: authHeaders()+ });+ expect(deleteRes.statusCode).toBe(200);++ const afterRevoke = await listIdentities();+ expect(afterRevoke.identities.find((identity) => identity.identityId === identityId)!.folderAccess).toBeNull();+ });++ test("filters by search and keeps totalCount stable past the end", async () => {+ const { totalCount } = await listIdentities();++ const pastTheEnd = await listIdentities(`?limit=1&offset=${totalCount + 10}`);+ expect(pastTheEnd.identities).toEqual([]);+ expect(pastTheEnd.totalCount).toBe(totalCount);++ const nonMatching = await listIdentities("?search=zzz-no-such-identity");+ expect(nonMatching.identities).toEqual([]);+ expect(nonMatching.totalCount).toBe(0);+ });++ describe("group-derived identities", () => {+ const orgId = seedData1.organization.id;+ let groupIdentityId: string;+ let groupId: string;++ beforeAll(async () => {+ const [identity] = await testDb(TableName.Identity)+ .insert({ name: `group-only-identity-${alphaNumericNanoId(8)}`, orgId })+ .returning("*");+ groupIdentityId = identity.id as string;++ const slug = `identity-folder-grp-${alphaNumericNanoId(8)}`.toLowerCase();+ const [group] = await testDb(TableName.Groups).insert({ orgId, name: slug, slug }).returning("*");+ groupId = group.id as string;++ for (const scope of [AccessScope.Organization, AccessScope.Project] as const) {+ // eslint-disable-next-line no-await-in-loop+ const [membership] = await testDb(TableName.Membership)+ .insert({+ scope,+ scopeOrgId: orgId,+ scopeProjectId: scope === AccessScope.Project ? projectId : null,+ actorGroupId: groupId+ })+ .returning("*");+ // eslint-disable-next-line no-await-in-loop+ await testDb(TableName.MembershipRole).insert({+ membershipId: membership.id,+ role: scope === AccessScope.Project ? ProjectMembershipRole.Member : OrgMembershipRole.Member+ });+ }++ // the new identity reaches the project only through the group; the seed identity is both a+ // direct member and a group member+ await testDb(TableName.IdentityGroupMembership).insert([+ { identityId: groupIdentityId, groupId },+ { identityId, groupId }+ ]);+ });++ afterAll(async () => {+ await testDb(TableName.IdentityGroupMembership).where({ groupId }).del();+ await testDb(TableName.Membership).where({ actorGroupId: groupId }).del();+ await testDb(TableName.Groups).where({ id: groupId }).del();+ await testDb(TableName.Identity).where({ id: groupIdentityId }).del();+ });++ test("lists an identity whose only project access is a group, once", async () => {+ const { identities, totalCount } = await listIdentities("?limit=100");++ const groupIdentity = identities.find((identity) => identity.identityId === groupIdentityId);+ expect(groupIdentity).toBeDefined();+ expect(groupIdentity!.folderAccess).toBeNull();++ // the seed identity is reachable directly and via the group, and must not be duplicated+ expect(identities.filter((identity) => identity.identityId === identityId)).toHaveLength(1);+ expect(new Set(identities.map((identity) => identity.identityId)).size).toBe(identities.length);+ expect(totalCount).toBe(identities.length);+ });++ test("grants folder access to a group-derived identity and shows it on the roster", async () => {+ const grantUrl = `/api/v2/identity-project-additional-privilege/projects/${projectId}/identities/${groupIdentityId}/folder-access/${folder.id}`;++ const createRes = await testServer.inject({+ method: "POST",+ url: grantUrl,+ headers: authHeaders(),+ body: { permission: SecretFolderRole.Read }+ });+ expect(createRes.statusCode).toBe(200);++ const { identities } = await listIdentities("?limit=100");+ const granted = identities.find((identity) => identity.identityId === groupIdentityId);+ expect(granted!.folderAccess).toEqual(+ expect.objectContaining({ folderId: folder.id, permission: SecretFolderRole.Read })+ );++ const deleteRes = await testServer.inject({ method: "DELETE", url: grantUrl, headers: authHeaders() });+ expect(deleteRes.statusCode).toBe(200);+ });+ });+ });});diff --git a/backend/scripts/dev-folder-rbac.ts b/backend/scripts/dev-folder-rbac.tsdeleted file mode 100644index 56745d4259..0000000000--- a/backend/scripts/dev-folder-rbac.ts+++ /dev/null@@ -1,491 +0,0 @@-/* eslint-disable no-console */-// ############################################################################-// # TEMPORARY DEV SCRIPT — DELETE THIS FILE BEFORE MERGING. #-// # #-// # Scaffolding for testing the folder RBAC roles by hand while the feature #-// # is being built. It writes folder-scoped rows to `additional_privileges` #-// # directly, because there is no API for them yet. Once the folder-grant #-// # endpoints exist, this file has no reason to exist — remove it rather than #-// # maintaining it, and do not build anything on top of it. #-// ############################################################################-//-// Nothing evaluates `additional_privileges.role` yet: the permission queries-// deliberately filter folder-scoped rows out (see permission-dal.ts), and the-// rules are appended at the end of CASL evaluation in a later change. So today-// this script is for creating fixtures and eyeballing them; a granted role will-// not change what the user can actually do until that wiring lands.-//-// Usage (from backend/):-// npx tsx scripts/dev-folder-rbac.ts <command> [flags]-//-// projects list projects (id, slug, version)-// folders --project <slug|id> [--env <slug>]-// list folders with their paths and ids-// add-user --email <email> [--password <pw>] [--no-login]-// [--org <slug|id>] [--project <slug|id>] [--project-role <role>]-// create (or reuse) a user, org membership-// and project membership-// grant --email <email> --project <slug|id> --env <slug> --path </a/b>-// --role <list|read|edit|manage|full-access>-// revoke --email <email> [--project <slug|id> --env <slug> --path </a/b>] [--all]-// show --email <email> memberships + folder grants-//-// Example: a user whose only access to a project is one folder role.-// npx tsx scripts/dev-folder-rbac.ts add-user --email [email protected] \-// --project first-project-v2-// npx tsx scripts/dev-folder-rbac.ts grant --email [email protected] \-// --project first-project-v2 --env dev --path / --role manage--import dotenv from "dotenv";-import knexLib, { Knex } from "knex";-import path from "path";--import {- AccessScope,- OrgMembershipRole,- OrgMembershipStatus,- ProjectMembershipRole,- SecretFolderRole,- TableName-} from "@app/db/schemas";--dotenv.config({ path: path.join(__dirname, "../../.env.migration") });-dotenv.config({ path: path.join(__dirname, "../../.env") });--const GRANT_NAME_PREFIX = "dev-folder-rbac";--type TFlags = Record<string, string | boolean>;--const parseFlags = (argv: string[]): TFlags => {- const flags: TFlags = {};- for (let i = 0; i < argv.length; i += 1) {- const token = argv[i];- if (!token.startsWith("--")) continue;- const key = token.slice(2);- const next = argv[i + 1];- if (!next || next.startsWith("--")) {- flags[key] = true;- } else {- flags[key] = next;- i += 1;- }- }- return flags;-};--const requireFlag = (flags: TFlags, name: string): string => {- const value = flags[name];- if (typeof value !== "string" || !value.length) {- throw new Error(`Missing required flag --${name}`);- }- return value;-};--// Creating users and grants against a shared database is not something to do by-// accident, so anything that is not obviously a local DB has to be forced.-const assertLocalDatabase = (flags: TFlags) => {- const uri = process.env.DB_CONNECTION_URI;- if (!uri) {- throw new Error(- "DB_CONNECTION_URI is not set. Create .env.migration at the repo root from .env.migration.example."- );- }- const isLocal = /@(localhost|127\.0\.0\.1|db)[:/]/.test(uri);- if (!isLocal && flags.force !== true) {- throw new Error("DB_CONNECTION_URI does not look local. Re-run with --force if you really mean it.");- }-};--const resolveProject = async (db: Knex, ref: string) => {- const project = await db(TableName.Project)- .where((qb) => {- void qb.where("slug", ref).orWhere("id", ref);- })- .whereNull("deleteAfter")- .first();- if (!project) throw new Error(`No project found with slug or id '${ref}'`);- return project;-};--const resolveUser = async (db: Knex, email: string) => {- const user = await db(TableName.Users)- .where((qb) => {- void qb.where("username", email).orWhere("email", email);- })- .first();- if (!user) throw new Error(`No user found with email '${email}'. Create one with add-user first.`);- return user;-};--// Folder paths are not stored, so they are rebuilt by walking parentId. The root-// folder of an environment is named "root" and represents "/".-type TFolderNode = { id: string; name: string; parentId: string | null; envId: string };--const buildFolderPaths = (folders: TFolderNode[]) => {- const byId = new Map(folders.map((f) => [f.id, f]));- const pathOf = (folder: TFolderNode): string => {- const segments: string[] = [];- let cursor: TFolderNode | undefined = folder;- while (cursor && cursor.parentId) {- segments.unshift(cursor.name);- cursor = byId.get(cursor.parentId);- }- return `/${segments.join("/")}`;- };- return new Map(folders.map((f) => [f.id, pathOf(f)]));-};--const loadFolders = async (db: Knex, projectId: string, envSlug?: string) => {- const envQuery = db(TableName.Environment).where("projectId", projectId).whereNull("deleteAfter");- if (envSlug) void envQuery.where("slug", envSlug);- const environments = await envQuery.orderBy("position");-- if (!environments.length) {- throw new Error(envSlug ? `Project has no environment '${envSlug}'` : "Project has no environments");- }-- const folders: TFolderNode[] = await db(TableName.SecretFolder)- .whereIn(- "envId",- environments.map((e) => e.id)- )- .whereNull("isReserved")- .orWhere("isReserved", false)- .whereIn(- "envId",- environments.map((e) => e.id)- )- .select("id", "name", "parentId", "envId");-- const paths = buildFolderPaths(folders);- const envById = new Map(environments.map((e) => [e.id, e]));-- return folders- .map((folder) => ({- ...folder,- path: paths.get(folder.id) as string,- envSlug: envById.get(folder.envId)?.slug as string- }))- .sort((a, b) => a.envSlug.localeCompare(b.envSlug) || a.path.localeCompare(b.path));-};--const resolveFolder = async (db: Knex, projectId: string, envSlug: string, folderPath: string) => {- const normalized = folderPath === "/" ? "/" : `/${folderPath.split("/").filter(Boolean).join("/")}`;- const folders = await loadFolders(db, projectId, envSlug);- const match = folders.find((f) => f.path === normalized);- if (!match) {- const available = folders.map((f) => f.path).join(", ") || "(none)";- throw new Error(`No folder at '${normalized}' in environment '${envSlug}'. Available: ${available}`);- }- return match;-};--const cmdProjects = async (db: Knex) => {- const projects = await db(TableName.Project)- .whereNull("deleteAfter")- .select("id", "name", "slug", "version", "type", "orgId")- .orderBy("name");- if (!projects.length) {- console.log("No projects found. Run `npm run seed-dev` first.");- return;- }- projects.forEach((p) => {- console.log(`${p.slug}\t${p.id}\tv${p.version}\t${p.type}\t${p.name}`);- });-};--const cmdFolders = async (db: Knex, flags: TFlags) => {- const project = await resolveProject(db, requireFlag(flags, "project"));- const envSlug = typeof flags.env === "string" ? flags.env : undefined;- const folders = await loadFolders(db, project.id, envSlug);- folders.forEach((f) => {- console.log(`${f.envSlug}\t${f.path}\t${f.id}`);- });-};--const cmdAddUser = async (db: Knex, flags: TFlags) => {- const email = requireFlag(flags, "email");- const withLogin = flags["no-login"] !== true;- const password = typeof flags.password === "string" ? flags.password : "testInfisical@1";-- let user = await db(TableName.Users)- .where((qb) => {- void qb.where("username", email).orWhere("email", email);- })- .first();-- if (user) {- console.log(`user exists id=${user.id} (${email})`);- } else {- [user] = await db(TableName.Users)- .insert({- username: email,- email,- firstName: email.split("@")[0],- lastName: "",- authMethods: ["email"],- isAccepted: true,- isEmailVerified: true,- isMfaEnabled: false- })- .returning("*");- console.log(`created user id=${user.id} (${email})`);- }-- if (withLogin) {- // Password + SRP material is what makes the user able to log in. Both need the- // FIPS-aware crypto module, which needs the env config bootstrapped first —- // same sequence as src/db/seeds/1-user.ts. Imported lazily so the read-only- // commands work in an environment that cannot bootstrap it.- const existingKeys = await db(TableName.UserEncryptionKey).where("userId", user.id).first();- if (existingKeys) {- console.log("login credentials already present, leaving them alone");- } else {- const { initializeHsmModule } = await import("@app/ee/services/hsm/hsm-fns");- const { hsmServiceFactory } = await import("@app/ee/services/hsm/hsm-service");- const { getHsmConfig, initEnvConfig } = await import("@app/lib/config/env");- const { crypto } = await import("@app/lib/crypto/cryptography");- const { initLogger, logger } = await import("@app/lib/logger");- const { kmsRootConfigDALFactory } = await import("@app/services/kms/kms-root-config-dal");- const { superAdminDALFactory } = await import("@app/services/super-admin/super-admin-dal");- const { generateUserSrpKeys } = await import("../src/db/seed-data");-- initLogger();- const hsmConfig = getHsmConfig(logger);- const hsmModule = initializeHsmModule(hsmConfig);- hsmModule.initialize();- const hsmService = hsmServiceFactory({ hsmModule: hsmModule.getModule(), envConfig: hsmConfig });- await hsmService.startService();- await initEnvConfig(hsmService, kmsRootConfigDALFactory(db), superAdminDALFactory(db), logger);-- const hashedPassword = await crypto.hashing().createHash(password, 10);- await db(TableName.Users).where("id", user.id).update({ hashedPassword });-- const encKeys = await generateUserSrpKeys(password);- await db(TableName.UserEncryptionKey).insert({- encryptionVersion: 2,- protectedKey: encKeys.protectedKey,- protectedKeyIV: encKeys.protectedKeyIV,- protectedKeyTag: encKeys.protectedKeyTag,- publicKey: encKeys.publicKey,- encryptedPrivateKey: encKeys.encryptedPrivateKey,- iv: encKeys.encryptedPrivateKeyIV,- tag: encKeys.encryptedPrivateKeyTag,- salt: encKeys.salt,- verifier: encKeys.verifier,- userId: user.id- });- console.log(`set login password=${password}`);- }- }-- const orgRef = typeof flags.org === "string" ? flags.org : undefined;- const projectRef = typeof flags.project === "string" ? flags.project : undefined;-- let orgId: string | undefined;- if (projectRef) {- orgId = (await resolveProject(db, projectRef)).orgId;- } else if (orgRef) {- const org = await db(TableName.Organization)- .where((qb) => {- void qb.where("slug", orgRef).orWhere("id", orgRef);- })- .first();- if (!org) throw new Error(`No organization found with slug or id '${orgRef}'`);- orgId = org.id;- }-- if (!orgId) {- console.log("no --org or --project given, skipping memberships");- return;- }-- let orgMembership = await db(TableName.Membership)- .where({ scope: AccessScope.Organization, scopeOrgId: orgId, actorUserId: user.id })- .first();- if (!orgMembership) {- [orgMembership] = await db(TableName.Membership)- .insert({- scope: AccessScope.Organization,- scopeOrgId: orgId,- actorUserId: user.id,- isActive: true,- status: OrgMembershipStatus.Accepted- })- .returning("*");- await db(TableName.MembershipRole).insert({ membershipId: orgMembership.id, role: OrgMembershipRole.Member });- console.log(`created org membership id=${orgMembership.id} role=member`);- } else {- console.log(`org membership exists id=${orgMembership.id}`);- }-- if (!projectRef) return;-- const project = await resolveProject(db, projectRef);- // no-access by default on purpose: it makes the folder grant the only thing- // giving this user access, so the role under test is what you are observing.- const projectRole =- typeof flags["project-role"] === "string" ? flags["project-role"] : ProjectMembershipRole.NoAccess;-- let projectMembership = await db(TableName.Membership)- .where({ scope: AccessScope.Project, scopeProjectId: project.id, actorUserId: user.id })- .first();- if (!projectMembership) {- [projectMembership] = await db(TableName.Membership)- .insert({- scope: AccessScope.Project,- scopeProjectId: project.id,- scopeOrgId: project.orgId,- actorUserId: user.id,- isActive: true- })- .returning("*");- await db(TableName.MembershipRole).insert({ membershipId: projectMembership.id, role: projectRole });- console.log(`created project membership id=${projectMembership.id} role=${projectRole} project=${project.slug}`);- } else {- console.log(`project membership exists id=${projectMembership.id} project=${project.slug}`);- }-};--const cmdGrant = async (db: Knex, flags: TFlags) => {- const role = requireFlag(flags, "role");- const validRoles = Object.values(SecretFolderRole) as string[];- if (!validRoles.includes(role)) {- throw new Error(`Invalid --role '${role}'. Expected one of: ${validRoles.join(", ")}`);- }-- const user = await resolveUser(db, requireFlag(flags, "email"));- const project = await resolveProject(db, requireFlag(flags, "project"));- const folder = await resolveFolder(db, project.id, requireFlag(flags, "env"), requireFlag(flags, "path"));-- // Unique index additional_privileges_unique_user_folder forbids a second row for- // the same actor+folder, so update in place instead of inserting a duplicate.- const existing = await db(TableName.AdditionalPrivilege).where({ actorUserId: user.id, folderId: folder.id }).first();-- if (existing) {- await db(TableName.AdditionalPrivilege).where("id", existing.id).update({ role });- console.log(`updated grant id=${existing.id} ${existing.role} -> ${role} on ${folder.envSlug}:${folder.path}`);- return;- }-- const [created] = await db(TableName.AdditionalPrivilege)- .insert({- name: `${GRANT_NAME_PREFIX}-${folder.envSlug}-${Date.now()}`,- actorUserId: user.id,- projectId: project.id,- folderId: folder.id,- role,- permissions: null,- isTemporary: false- })- .returning("*");- console.log(`created grant id=${created.id} role=${role} on ${folder.envSlug}:${folder.path}`);-};--const cmdRevoke = async (db: Knex, flags: TFlags) => {- const user = await resolveUser(db, requireFlag(flags, "email"));-- if (flags.all === true) {- const deleted = await db(TableName.AdditionalPrivilege)- .where("actorUserId", user.id)- .whereNotNull("folderId")- .del();- console.log(`revoked ${deleted} folder grant(s)`);- return;- }-- const project = await resolveProject(db, requireFlag(flags, "project"));- const folder = await resolveFolder(db, project.id, requireFlag(flags, "env"), requireFlag(flags, "path"));- const deleted = await db(TableName.AdditionalPrivilege).where({ actorUserId: user.id, folderId: folder.id }).del();- console.log(`revoked ${deleted} grant(s) on ${folder.envSlug}:${folder.path}`);-};--const cmdShow = async (db: Knex, flags: TFlags) => {- const user = await resolveUser(db, requireFlag(flags, "email"));- console.log(`user id=${user.id} username=${user.username}`);-- const memberships = await db(TableName.Membership)- .leftJoin(TableName.MembershipRole, `${TableName.Membership}.id`, `${TableName.MembershipRole}.membershipId`)- .leftJoin(TableName.Project, `${TableName.Membership}.scopeProjectId`, `${TableName.Project}.id`)- .where(`${TableName.Membership}.actorUserId`, user.id)- .select(- db.ref("scope").withSchema(TableName.Membership),- db.ref("isActive").withSchema(TableName.Membership),- db.ref("role").withSchema(TableName.MembershipRole),- db.ref("slug").withSchema(TableName.Project).as("projectSlug")- );-- console.log("\nmemberships:");- if (!memberships.length) console.log(" (none)");- memberships.forEach((m) => {- console.log(` ${m.scope}${m.projectSlug ? `:${m.projectSlug}` : ""}\trole=${m.role}\tactive=${m.isActive}`);- });-- const grants = await db(TableName.AdditionalPrivilege)- .where("actorUserId", user.id)- .whereNotNull("folderId")- .select("id", "role", "folderId", "projectId", "name");-- console.log("\nfolder grants:");- if (!grants.length) {- console.log(" (none)");- return;- }-- // folderId and projectId are nullable columns, and the folder_requires_project check means a- // folder grant always has both. Narrow explicitly rather than asserting.- const locatable = grants.filter(- (grant): grant is typeof grant & { folderId: string; projectId: string } =>- Boolean(grant.folderId) && Boolean(grant.projectId)- );-- const pathCache = new Map<string, { path: string; envSlug: string }>();- const loadedProjects = new Set<string>();- for (const grant of locatable) {- if (!loadedProjects.has(grant.projectId)) {- loadedProjects.add(grant.projectId);- // eslint-disable-next-line no-await-in-loop- const folders = await loadFolders(db, grant.projectId);- folders.forEach((f) => pathCache.set(f.id, { path: f.path, envSlug: f.envSlug }));- }- const location = pathCache.get(grant.folderId);- console.log(- ` ${grant.role}\t${location ? `${location.envSlug}:${location.path}` : `folderId=${grant.folderId}`}\tid=${grant.id}`- );- }-};--const COMMANDS: Record<string, (db: Knex, flags: TFlags) => Promise<void>> = {- projects: cmdProjects,- folders: cmdFolders,- "add-user": cmdAddUser,- grant: cmdGrant,- revoke: cmdRevoke,- show: cmdShow-};--const main = async () => {- const [command, ...rest] = process.argv.slice(2);- const flags = parseFlags(rest);-- if (!command || !COMMANDS[command]) {- console.log(- `Usage: npx tsx scripts/dev-folder-rbac.ts <${Object.keys(COMMANDS).join("|")}> [flags]\nSee the header of this file for examples.`- );- process.exit(command ? 1 : 0);- }-- assertLocalDatabase(flags);-- const db = knexLib({ client: "pg", connection: process.env.DB_CONNECTION_URI });- try {- await COMMANDS[command](db, flags);- } finally {- await db.destroy();- }-};--main().catch((err: unknown) => {- console.error(`\n${err instanceof Error ? err.message : String(err)}`);- process.exit(1);-});diff --git a/backend/src/ee/routes/v1/user-additional-privilege-router.ts b/backend/src/ee/routes/v1/user-additional-privilege-router.tsindex 0252b07fee..6a4357f940 100644--- a/backend/src/ee/routes/v1/user-additional-privilege-router.ts+++ b/backend/src/ee/routes/v1/user-additional-privilege-router.ts@@ -10,7 +10,10 @@ import { alphaNumericNanoId } from "@app/lib/nanoid";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { slugSchema, temporaryPermissionTypeSchema } from "@app/server/lib/schemas";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";-import { SanitizedFolderAccessSchema } from "@app/server/routes/sanitizedSchema/folder-access";+import {+ SanitizedFolderAccessSchema,+ SanitizedFolderAccessUserSchema+} from "@app/server/routes/sanitizedSchema/folder-access";import { SanitizedUserProjectAdditionalPrivilegeSchema } from "@app/server/routes/sanitizedSchema/user-additional-privilege";import { ActorType, AuthMode } from "@app/services/auth/auth-type";@@ -437,4 +440,48 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPrreturn { folderAccess: { ...folderAccess, userId: req.params.userId } };}});++ server.route({+ method: "GET",+ url: "/projects/:projectId/folder-access/:folderId/users",+ config: {+ rateLimit: readLimit+ },+ schema: {+ hide: false,+ operationId: "listFolderAccessUsers",+ tags: [ApiDocsTags.FolderAccess],+ description: "List every user in a project with the access they have on a folder.",+ security: [+ {+ bearerAuth: []+ }+ ],+ params: z.object({+ projectId: z.string().trim().min(1).max(64).describe(FOLDER_ACCESS.LIST_USERS.projectId),+ folderId: z.string().uuid().describe(FOLDER_ACCESS.LIST_USERS.folderId)+ }),+ querystring: z.object({+ offset: z.coerce.number().int().min(0).default(0).describe(FOLDER_ACCESS.LIST_USERS.offset),+ limit: z.coerce.number().int().min(1).max(100).default(50).describe(FOLDER_ACCESS.LIST_USERS.limit),+ search: z.string().trim().max(64).optional().describe(FOLDER_ACCESS.LIST_USERS.search)+ }),+ response: {+ 200: z.object({+ users: SanitizedFolderAccessUserSchema.array(),+ totalCount: z.number()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) =>+ server.services.folderPermission.listFolderAccessUsers({+ permission: req.permission,+ projectId: req.params.projectId,+ folderId: req.params.folderId,+ limit: req.query.limit,+ offset: req.query.offset,+ search: req.query.search+ })+ });};diff --git a/backend/src/ee/routes/v2/identity-project-additional-privilege-router.ts b/backend/src/ee/routes/v2/identity-project-additional-privilege-router.tsindex cb383fa0c1..caa9e888bb 100644--- a/backend/src/ee/routes/v2/identity-project-additional-privilege-router.ts+++ b/backend/src/ee/routes/v2/identity-project-additional-privilege-router.ts@@ -10,7 +10,10 @@ import { alphaNumericNanoId } from "@app/lib/nanoid";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { slugSchema, temporaryPermissionTypeSchema } from "@app/server/lib/schemas";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";-import { SanitizedFolderAccessSchema } from "@app/server/routes/sanitizedSchema/folder-access";+import {+ SanitizedFolderAccessIdentitySchema,+ SanitizedFolderAccessSchema+} from "@app/server/routes/sanitizedSchema/folder-access";import { SanitizedIdentityPrivilegeSchema } from "@app/server/routes/sanitizedSchema/identitiy-additional-privilege";import { ActorType, AuthMode } from "@app/services/auth/auth-type";@@ -515,4 +518,48 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: Freturn { folderAccess: { ...folderAccess, identityId: req.params.identityId } };}});++ server.route({+ method: "GET",+ url: "/projects/:projectId/folder-access/:folderId/identities",+ config: {+ rateLimit: readLimit+ },+ schema: {+ hide: false,+ operationId: "listFolderAccessIdentities",+ tags: [ApiDocsTags.FolderAccess],+ description: "List every machine identity in a project with the access it has on a folder.",+ security: [+ {+ bearerAuth: []+ }+ ],+ params: z.object({+ projectId: z.string().trim().min(1).max(64).describe(FOLDER_ACCESS.LIST_IDENTITIES.projectId),+ folderId: z.string().uuid().describe(FOLDER_ACCESS.LIST_IDENTITIES.folderId)+ }),+ querystring: z.object({+ offset: z.coerce.number().int().min(0).default(0).describe(FOLDER_ACCESS.LIST_IDENTITIES.offset),+ limit: z.coerce.number().int().min(1).max(100).default(50).describe(FOLDER_ACCESS.LIST_IDENTITIES.limit),+ search: z.string().trim().max(64).optional().describe(FOLDER_ACCESS.LIST_IDENTITIES.search)+ }),+ response: {+ 200: z.object({+ identities: SanitizedFolderAccessIdentitySchema.array(),+ totalCount: z.number()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) =>+ server.services.folderPermission.listFolderAccessIdentities({+ permission: req.permission,+ projectId: req.params.projectId,+ folderId: req.params.folderId,+ limit: req.query.limit,+ offset: req.query.offset,+ search: req.query.search+ })+ });};diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.tsindex 3dafc31e1c..02c68fbbde 100644--- a/backend/src/ee/services/permission/default-roles.ts+++ b/backend/src/ee/services/permission/default-roles.ts@@ -1,6 +1,5 @@-import { AbilityBuilder, createMongoAbility, MongoAbility, RawRuleOf } from "@casl/ability";+import { AbilityBuilder, createMongoAbility, MongoAbility } from "@casl/ability";-import { SecretFolderRole } from "@app/db/schemas";import {ProjectPermissionActions,ProjectPermissionAppConnectionActions,@@ -801,233 +800,6 @@ export const projectNoAccessPermissions = buildNoAccessProjectPermission();// KMSexport const cryptographicOperatorPermissions = buildCryptographicOperatorPermissionRules();-// Folder RBAC. These are project-subject rules scoped to one folder by-// additional_privileges.folderId rather than by CASL conditions, so they carry no subject fields.-// The tiers are cumulative, and each apply* helper chains to the one below it so that relationship-// lives in one place instead of being re-listed five times.-type TProjectCan = AbilityBuilder<MongoAbility<ProjectPermissionSet>>["can"];--// See what exists, without exposing any secret values.-const applyFolderListRules = (can: TProjectCan) => {- can([ProjectPermissionSecretActions.DescribeSecret], ProjectPermissionSub.Secrets);- can([ProjectPermissionActions.Read], ProjectPermissionSub.Tags);- can([ProjectPermissionActions.Read], ProjectPermissionSub.SecretImports);- can([ProjectPermissionSecretSyncActions.Read], ProjectPermissionSub.SecretSyncs);- can([ProjectPermissionSecretRotationActions.Read], ProjectPermissionSub.SecretRotation);- can([ProjectPermissionHoneyTokenActions.Read], ProjectPermissionSub.HoneyTokens);-};--const applyFolderReadRules = (can: TProjectCan) => {- applyFolderListRules(can);-- can([ProjectPermissionSecretActions.ReadValue], ProjectPermissionSub.Secrets);- can([ProjectPermissionCommitsActions.Read], ProjectPermissionSub.Commits);- can([ProjectPermissionDynamicSecretActions.Lease], ProjectPermissionSub.DynamicSecrets);- can(- [- ProjectPermissionSecretEventActions.SubscribeToCreationEvents,- ProjectPermissionSecretEventActions.SubscribeToUpdateEvents,- ProjectPermissionSecretEventActions.SubscribeToDeleteEvents,- ProjectPermissionSecretEventActions.SubscribeToImportMutationEvents- ],- ProjectPermissionSub.SecretEventSubscriptions- );-};--const applyFolderEditRules = (can: TProjectCan) => {- applyFolderReadRules(can);-- can(- [ProjectPermissionSecretActions.Create, ProjectPermissionSecretActions.Edit, ProjectPermissionSecretActions.Delete],- ProjectPermissionSub.Secrets- );- can([ProjectPermissionActions.Create, ProjectPermissionActions.Edit], ProjectPermissionSub.SecretFolders);- can(- [ProjectPermissionActions.Create, ProjectPermissionActions.Edit, ProjectPermissionActions.Delete],- ProjectPermissionSub.SecretImports- );- can(- [ProjectPermissionActions.Create, ProjectPermissionActions.Edit, ProjectPermissionActions.Delete],- ProjectPermissionSub.Tags- );-};--const applyFolderManageRules = (can: TProjectCan) => {- applyFolderEditRules(can);-- can(- [- ProjectPermissionSecretRotationActions.Create,- ProjectPermissionSecretRotationActions.Edit,- ProjectPermissionSecretRotationActions.Delete,- ProjectPermissionSecretRotationActions.RotateSecrets,- ProjectPermissionSecretRotationActions.ReadGeneratedCredentials- ],- ProjectPermissionSub.SecretRotation- );- can(- [- ProjectPermissionDynamicSecretActions.ReadRootCredential,- ProjectPermissionDynamicSecretActions.CreateRootCredential,- ProjectPermissionDynamicSecretActions.EditRootCredential,- ProjectPermissionDynamicSecretActions.DeleteRootCredential- ],- ProjectPermissionSub.DynamicSecrets- );- can(- [- ProjectPermissionHoneyTokenActions.Create,- ProjectPermissionHoneyTokenActions.Edit,- ProjectPermissionHoneyTokenActions.Reset,- ProjectPermissionHoneyTokenActions.Revoke,- ProjectPermissionHoneyTokenActions.ReadCredentials- ],- ProjectPermissionSub.HoneyTokens- );- can(- [- ProjectPermissionSecretSyncActions.Create,- ProjectPermissionSecretSyncActions.Edit,- ProjectPermissionSecretSyncActions.Delete,- ProjectPermissionSecretSyncActions.SyncSecrets,- ProjectPermissionSecretSyncActions.ImportSecrets,- ProjectPermissionSecretSyncActions.RemoveSecrets- ],- ProjectPermissionSub.SecretSyncs- );-};--const applyFolderFullAccessRules = (can: TProjectCan) => {- applyFolderManageRules(can);-- can([ProjectPermissionSecretFolderActions.ManageAccess], ProjectPermissionSub.SecretFolders);- can([ProjectPermissionActions.Delete], ProjectPermissionSub.SecretFolders);-};--const buildFolderRoleRules = (applyRules: (can: TProjectCan) => void) => {- const { can, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);- applyRules(can);- return rules;-};--export const folderListPermissions = buildFolderRoleRules(applyFolderListRules);-export const folderReadPermissions = buildFolderRoleRules(applyFolderReadRules);-export const folderEditPermissions = buildFolderRoleRules(applyFolderEditRules);-export const folderManagePermissions = buildFolderRoleRules(applyFolderManageRules);-export const folderFullAccessPermissions = buildFolderRoleRules(applyFolderFullAccessRules);--export const SECRET_FOLDER_ROLE_PERMISSIONS: Record<SecretFolderRole, RawRuleOf<MongoAbility<ProjectPermissionSet>>[]> =- {- [SecretFolderRole.List]: folderListPermissions,- [SecretFolderRole.Read]: folderReadPermissions,- [SecretFolderRole.Edit]: folderEditPermissions,- [SecretFolderRole.Manage]: folderManagePermissions,- [SecretFolderRole.FullAccess]: folderFullAccessPermissions- };--const buildFolderScopedDenyRules = () => {- const { cannot, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);-- cannot(- [- ProjectPermissionSecretActions.DescribeAndReadValue,- ProjectPermissionSecretActions.DescribeSecret,- ProjectPermissionSecretActions.ReadValue,- ProjectPermissionSecretActions.Create,- ProjectPermissionSecretActions.Edit,- ProjectPermissionSecretActions.Delete- ],- ProjectPermissionSub.Secrets- );- cannot(- [- ProjectPermissionActions.Create,- ProjectPermissionActions.Edit,- ProjectPermissionActions.Delete,- ProjectPermissionSecretFolderActions.ManageAccess- ],- ProjectPermissionSub.SecretFolders- );- cannot(- [- ProjectPermissionActions.Read,- ProjectPermissionActions.Create,- ProjectPermissionActions.Edit,- ProjectPermissionActions.Delete- ],- ProjectPermissionSub.SecretImports- );- cannot(- [- ProjectPermissionDynamicSecretActions.ReadRootCredential,- ProjectPermissionDynamicSecretActions.CreateRootCredential,- ProjectPermissionDynamicSecretActions.EditRootCredential,- ProjectPermissionDynamicSecretActions.DeleteRootCredential,- ProjectPermissionDynamicSecretActions.Lease- ],- ProjectPermissionSub.DynamicSecrets- );- cannot(- [- ProjectPermissionSecretSyncActions.Read,- ProjectPermissionSecretSyncActions.Create,- ProjectPermissionSecretSyncActions.Edit,- ProjectPermissionSecretSyncActions.Delete,- ProjectPermissionSecretSyncActions.SyncSecrets,- ProjectPermissionSecretSyncActions.ImportSecrets,- ProjectPermissionSecretSyncActions.RemoveSecrets- ],- ProjectPermissionSub.SecretSyncs- );- cannot(- [- ProjectPermissionSecretRotationActions.Read,- ProjectPermissionSecretRotationActions.ReadGeneratedCredentials,- ProjectPermissionSecretRotationActions.Create,- ProjectPermissionSecretRotationActions.Edit,- ProjectPermissionSecretRotationActions.Delete,- ProjectPermissionSecretRotationActions.RotateSecrets- ],- ProjectPermissionSub.SecretRotation- );- cannot(- [- ProjectPermissionSecretEventActions.SubscribeToCreationEvents,- ProjectPermissionSecretEventActions.SubscribeToUpdateEvents,- ProjectPermissionSecretEventActions.SubscribeToDeleteEvents,- ProjectPermissionSecretEventActions.SubscribeToImportMutationEvents- ],- ProjectPermissionSub.SecretEventSubscriptions- );- cannot(- [ProjectPermissionCommitsActions.Read, ProjectPermissionCommitsActions.PerformRollback],- ProjectPermissionSub.Commits- );- cannot(- [- ProjectPermissionHoneyTokenActions.Read,- ProjectPermissionHoneyTokenActions.ReadCredentials,- ProjectPermissionHoneyTokenActions.Create,- ProjectPermissionHoneyTokenActions.Edit,- ProjectPermissionHoneyTokenActions.Reset,- ProjectPermissionHoneyTokenActions.Revoke- ],- ProjectPermissionSub.HoneyTokens- );- cannot(- [- ProjectPermissionProjectFolderGrantActions.ReadGrant,- ProjectPermissionProjectFolderGrantActions.CreateGrant,- ProjectPermissionProjectFolderGrantActions.RevokeGrant- ],- ProjectPermissionSub.ProjectFolderGrant- );-- return rules;-};--export const FOLDER_SCOPED_DENY_RULES = buildFolderScopedDenyRules();-const buildApplicationAdminPermissionRules = () => {const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);diff --git a/backend/src/ee/services/permission/folder-roles.test.ts b/backend/src/ee/services/permission/folder-roles.test.tsindex 7ffe721d75..7144febc16 100644--- a/backend/src/ee/services/permission/folder-roles.test.ts+++ b/backend/src/ee/services/permission/folder-roles.test.ts@@ -2,7 +2,7 @@ import { createMongoAbility, MongoAbility } from "@casl/ability";import { SecretFolderRole } from "@app/db/schemas";-import { SECRET_FOLDER_ROLE_PERMISSIONS } from "./default-roles";+import { SECRET_FOLDER_ROLE_PERMISSIONS } from "./folder-roles";import {ProjectPermissionActions,ProjectPermissionCommitsActions,diff --git a/backend/src/ee/services/permission/folder-roles.ts b/backend/src/ee/services/permission/folder-roles.tsnew file mode 100644index 0000000000..6f9e5873f0--- /dev/null+++ b/backend/src/ee/services/permission/folder-roles.ts@@ -0,0 +1,231 @@+import { AbilityBuilder, createMongoAbility, MongoAbility, RawRuleOf } from "@casl/ability";++import { SecretFolderRole } from "@app/db/schemas";+import {+ ProjectPermissionActions,+ ProjectPermissionCommitsActions,+ ProjectPermissionDynamicSecretActions,+ ProjectPermissionHoneyTokenActions,+ ProjectPermissionSecretActions,+ ProjectPermissionSecretEventActions,+ ProjectPermissionSecretFolderActions,+ ProjectPermissionSecretRotationActions,+ ProjectPermissionSecretSyncActions,+ ProjectPermissionSet,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";++// Folder RBAC. These are project-subject rules scoped to one folder by+// additional_privileges.folderId rather than by CASL conditions, so they carry no subject fields.+// The tiers are cumulative, and each apply* helper chains to the one below it so that relationship+// lives in one place instead of being re-listed five times.+type TProjectCan = AbilityBuilder<MongoAbility<ProjectPermissionSet>>["can"];++// See what exists, without exposing any secret values.+const applyFolderListRules = (can: TProjectCan) => {+ can([ProjectPermissionSecretActions.DescribeSecret], ProjectPermissionSub.Secrets);+ can([ProjectPermissionActions.Read], ProjectPermissionSub.Tags);+ can([ProjectPermissionActions.Read], ProjectPermissionSub.SecretImports);+ can([ProjectPermissionSecretSyncActions.Read], ProjectPermissionSub.SecretSyncs);+ can([ProjectPermissionSecretRotationActions.Read], ProjectPermissionSub.SecretRotation);+ can([ProjectPermissionHoneyTokenActions.Read], ProjectPermissionSub.HoneyTokens);+};++const applyFolderReadRules = (can: TProjectCan) => {+ applyFolderListRules(can);++ can([ProjectPermissionSecretActions.ReadValue], ProjectPermissionSub.Secrets);+ can([ProjectPermissionCommitsActions.Read], ProjectPermissionSub.Commits);+ can([ProjectPermissionDynamicSecretActions.Lease], ProjectPermissionSub.DynamicSecrets);+ can(+ [+ ProjectPermissionSecretEventActions.SubscribeToCreationEvents,+ ProjectPermissionSecretEventActions.SubscribeToUpdateEvents,+ ProjectPermissionSecretEventActions.SubscribeToDeleteEvents,+ ProjectPermissionSecretEventActions.SubscribeToImportMutationEvents+ ],+ ProjectPermissionSub.SecretEventSubscriptions+ );+};++const applyFolderEditRules = (can: TProjectCan) => {+ applyFolderReadRules(can);++ can(+ [ProjectPermissionSecretActions.Create, ProjectPermissionSecretActions.Edit, ProjectPermissionSecretActions.Delete],+ ProjectPermissionSub.Secrets+ );+ can([ProjectPermissionActions.Create, ProjectPermissionActions.Edit], ProjectPermissionSub.SecretFolders);+ can(+ [ProjectPermissionActions.Create, ProjectPermissionActions.Edit, ProjectPermissionActions.Delete],+ ProjectPermissionSub.SecretImports+ );+ can(+ [ProjectPermissionActions.Create, ProjectPermissionActions.Edit, ProjectPermissionActions.Delete],+ ProjectPermissionSub.Tags+ );+};++const applyFolderManageRules = (can: TProjectCan) => {+ applyFolderEditRules(can);++ can(+ [+ ProjectPermissionSecretRotationActions.Create,+ ProjectPermissionSecretRotationActions.Edit,+ ProjectPermissionSecretRotationActions.Delete,+ ProjectPermissionSecretRotationActions.RotateSecrets,+ ProjectPermissionSecretRotationActions.ReadGeneratedCredentials+ ],+ ProjectPermissionSub.SecretRotation+ );+ can(+ [+ ProjectPermissionDynamicSecretActions.ReadRootCredential,+ ProjectPermissionDynamicSecretActions.CreateRootCredential,+ ProjectPermissionDynamicSecretActions.EditRootCredential,+ ProjectPermissionDynamicSecretActions.DeleteRootCredential+ ],+ ProjectPermissionSub.DynamicSecrets+ );+ can(+ [+ ProjectPermissionHoneyTokenActions.Create,+ ProjectPermissionHoneyTokenActions.Edit,+ ProjectPermissionHoneyTokenActions.Reset,+ ProjectPermissionHoneyTokenActions.Revoke,+ ProjectPermissionHoneyTokenActions.ReadCredentials+ ],+ ProjectPermissionSub.HoneyTokens+ );+ can(+ [+ ProjectPermissionSecretSyncActions.Create,+ ProjectPermissionSecretSyncActions.Edit,+ ProjectPermissionSecretSyncActions.Delete,+ ProjectPermissionSecretSyncActions.SyncSecrets,+ ProjectPermissionSecretSyncActions.ImportSecrets,+ ProjectPermissionSecretSyncActions.RemoveSecrets+ ],+ ProjectPermissionSub.SecretSyncs+ );+};++const applyFolderFullAccessRules = (can: TProjectCan) => {+ applyFolderManageRules(can);++ can([ProjectPermissionSecretFolderActions.ManageAccess], ProjectPermissionSub.SecretFolders);+ can([ProjectPermissionActions.Delete], ProjectPermissionSub.SecretFolders);+};++const buildFolderRoleRules = (applyRules: (can: TProjectCan) => void) => {+ const { can, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);+ applyRules(can);+ return rules;+};++export const folderListPermissions = buildFolderRoleRules(applyFolderListRules);+export const folderReadPermissions = buildFolderRoleRules(applyFolderReadRules);+export const folderEditPermissions = buildFolderRoleRules(applyFolderEditRules);+export const folderManagePermissions = buildFolderRoleRules(applyFolderManageRules);+export const folderFullAccessPermissions = buildFolderRoleRules(applyFolderFullAccessRules);++export const SECRET_FOLDER_ROLE_PERMISSIONS: Record<SecretFolderRole, RawRuleOf<MongoAbility<ProjectPermissionSet>>[]> =+ {+ [SecretFolderRole.List]: folderListPermissions,+ [SecretFolderRole.Read]: folderReadPermissions,+ [SecretFolderRole.Edit]: folderEditPermissions,+ [SecretFolderRole.Manage]: folderManagePermissions,+ [SecretFolderRole.FullAccess]: folderFullAccessPermissions+ };++const buildFolderScopedDenyRules = () => {+ const { cannot, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);++ cannot(+ [+ ProjectPermissionSecretActions.DescribeAndReadValue,+ ProjectPermissionSecretActions.DescribeSecret,+ ProjectPermissionSecretActions.ReadValue,+ ProjectPermissionSecretActions.Create,+ ProjectPermissionSecretActions.Edit,+ ProjectPermissionSecretActions.Delete+ ],+ ProjectPermissionSub.Secrets+ );+ cannot(+ [+ ProjectPermissionActions.Create,+ ProjectPermissionActions.Edit,+ ProjectPermissionActions.Delete,+ ProjectPermissionSecretFolderActions.ManageAccess+ ],+ ProjectPermissionSub.SecretFolders+ );+ cannot(+ [+ ProjectPermissionActions.Read,+ ProjectPermissionActions.Create,+ ProjectPermissionActions.Edit,+ ProjectPermissionActions.Delete+ ],+ ProjectPermissionSub.SecretImports+ );+ cannot(+ [+ ProjectPermissionDynamicSecretActions.ReadRootCredential,+ ProjectPermissionDynamicSecretActions.CreateRootCredential,+ ProjectPermissionDynamicSecretActions.EditRootCredential,+ ProjectPermissionDynamicSecretActions.DeleteRootCredential,+ ProjectPermissionDynamicSecretActions.Lease+ ],+ ProjectPermissionSub.DynamicSecrets+ );+ cannot(+ [+ ProjectPermissionSecretSyncActions.Read,+ ProjectPermissionSecretSyncActions.Create,+ ProjectPermissionSecretSyncActions.Edit,+ ProjectPermissionSecretSyncActions.Delete,+ ProjectPermissionSecretSyncActions.SyncSecrets,+ ProjectPermissionSecretSyncActions.ImportSecrets,+ ProjectPermissionSecretSyncActions.RemoveSecrets+ ],+ ProjectPermissionSub.SecretSyncs+ );+ cannot(+ [+ ProjectPermissionSecretRotationActions.Read,+ ProjectPermissionSecretRotationActions.ReadGeneratedCredentials,+ ProjectPermissionSecretRotationActions.Create,+ ProjectPermissionSecretRotationActions.Edit,+ ProjectPermissionSecretRotationActions.Delete,+ ProjectPermissionSecretRotationActions.RotateSecrets+ ],+ ProjectPermissionSub.SecretRotation+ );+ cannot(+ [+ ProjectPermissionSecretEventActions.SubscribeToCreationEvents,+ ProjectPermissionSecretEventActions.SubscribeToUpdateEvents,+ ProjectPermissionSecretEventActions.SubscribeToDeleteEvents,+ ProjectPermissionSecretEventActions.SubscribeToImportMutationEvents+ ],+ ProjectPermissionSub.SecretEventSubscriptions+ );+ cannot(+ [+ ProjectPermissionHoneyTokenActions.Read,+ ProjectPermissionHoneyTokenActions.ReadCredentials,+ ProjectPermissionHoneyTokenActions.Create,+ ProjectPermissionHoneyTokenActions.Edit,+ ProjectPermissionHoneyTokenActions.Reset,+ ProjectPermissionHoneyTokenActions.Revoke+ ],+ ProjectPermissionSub.HoneyTokens+ );++ return rules;+};++export const FOLDER_SCOPED_DENY_RULES = buildFolderScopedDenyRules();diff --git a/backend/src/ee/services/permission/folder-scoped-privilege-rules.test.ts b/backend/src/ee/services/permission/folder-scoped-privilege-rules.test.tsindex ae6ba5b689..3826681b3b 100644--- a/backend/src/ee/services/permission/folder-scoped-privilege-rules.test.ts+++ b/backend/src/ee/services/permission/folder-scoped-privilege-rules.test.ts@@ -5,7 +5,7 @@ import { ProjectMembershipRole, ProjectType, SecretFolderRole } from "@app/db/scimport { conditionsMatcher } from "@app/lib/casl";import { NotFoundError } from "@app/lib/errors";-import { FOLDER_SCOPED_DENY_RULES } from "./default-roles";+import { FOLDER_SCOPED_DENY_RULES } from "./folder-roles";import { buildFolderScopedPrivilegeRules } from "./permission-fns";import { buildProjectPermissionRules } from "./permission-service";import { TProjectFolderScopedPrivilege } from "./permission-service-types";@@ -79,7 +79,7 @@ describe("folder-scoped privilege deny coverage", () => {test("every secretPath-scoped subject is denied at the granted folder path", () => {expect([...new Set(Object.keys(deniedActionsBySubject))].sort(),- "A subject that supports a secretPath condition was added or removed. Update FOLDER_SCOPED_DENY_RULES in default-roles.ts and review whether the SECRET_FOLDER_ROLE_PERMISSIONS tiers should grant the new subject's actions."+ "A subject that supports a secretPath condition was added or removed. Update FOLDER_SCOPED_DENY_RULES in folder-roles.ts and review whether the SECRET_FOLDER_ROLE_PERMISSIONS tiers should grant the new subject's actions.").toEqual([...new Set(secretPathScopedSubjects)].sort());});@@ -102,7 +102,7 @@ describe("folder-scoped privilege deny coverage", () => {(deniedSubject) => {expect([...(deniedActionsBySubject[deniedSubject] ?? [])].sort(),- `A new action was added to the '${deniedSubject}' subject. Add it to FOLDER_SCOPED_DENY_RULES in default-roles.ts and review whether the SECRET_FOLDER_ROLE_PERMISSIONS tiers should grant it.`+ `A new action was added to the '${deniedSubject}' subject. Add it to FOLDER_SCOPED_DENY_RULES in folder-roles.ts and review whether the SECRET_FOLDER_ROLE_PERMISSIONS tiers should grant it.`).toEqual([...(ALL_ACTIONS_BY_SUBJECT[deniedSubject] ?? [])].sort());});diff --git a/backend/src/ee/services/permission/permission-fns.ts b/backend/src/ee/services/permission/permission-fns.tsindex 101802c464..65507ad50d 100644--- a/backend/src/ee/services/permission/permission-fns.ts+++ b/backend/src/ee/services/permission/permission-fns.ts@@ -18,7 +18,7 @@ import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privileimport { ActorAuthMethod, ActorType, AuthMethod } from "@app/services/auth/auth-type";import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";-import { FOLDER_SCOPED_DENY_RULES, SECRET_FOLDER_ROLE_PERMISSIONS } from "./default-roles";+import { FOLDER_SCOPED_DENY_RULES, SECRET_FOLDER_ROLE_PERMISSIONS } from "./folder-roles";import { OrgPermissionSet } from "./org-permission";import { TCachedFolderScopedPrivileges, TProjectFolderScopedPrivilege } from "./permission-service-types";import {diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 5dddfaf858..48dffc2afe 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -1763,6 +1763,20 @@ export const FOLDER_ACCESS = {folderId: "The ID of the folder the access is on.",userId: "The ID of the user whose folder access to revoke.",identityId: "The ID of the machine identity whose folder access to revoke."+ },+ LIST_USERS: {+ projectId: "The ID of the project the folder is in.",+ folderId: "The ID of the folder to list access for.",+ offset: "The offset to start from. If you enter 10, it will start from the 10th user.",+ limit: "The number of users to return.",+ search: "The text string that user names and email addresses will be filtered by."+ },+ LIST_IDENTITIES: {+ projectId: "The ID of the project the folder is in.",+ folderId: "The ID of the folder to list access for.",+ offset: "The offset to start from. If you enter 10, it will start from the 10th machine identity.",+ limit: "The number of machine identities to return.",+ search: "The text string that machine identity names will be filtered by."}};diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 70ad6f07b9..90fa5586e1 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -309,6 +309,7 @@ import { folderCommitDALFactory } from "@app/services/folder-commit/folder-commiimport { folderCommitQueueServiceFactory } from "@app/services/folder-commit/folder-commit-queue";import { folderCommitServiceFactory } from "@app/services/folder-commit/folder-commit-service";import { folderCommitChangesDALFactory } from "@app/services/folder-commit-changes/folder-commit-changes-dal";+import { folderPermissionDALFactory } from "@app/services/folder-permission/folder-permission-dal";import { folderPermissionServiceFactory } from "@app/services/folder-permission/folder-permission-service";import { folderTreeCheckpointDALFactory } from "@app/services/folder-tree-checkpoint/folder-tree-checkpoint-dal";import { folderTreeCheckpointResourcesDALFactory } from "@app/services/folder-tree-checkpoint-resources/folder-tree-checkpoint-resources-dal";@@ -743,6 +744,7 @@ export const registerRoutes = async (const membershipIdentityDAL = membershipIdentityDALFactory(db);const membershipGroupDAL = membershipGroupDALFactory(db);const additionalPrivilegeDAL = additionalPrivilegeDALFactory(db);+ const folderPermissionDAL = folderPermissionDALFactory(db);const membershipRoleDAL = membershipRoleDALFactory(db);const approvalPolicyDAL = approvalPolicyDALFactory(db);const roleDAL = roleDALFactory(db);@@ -934,7 +936,7 @@ export const registerRoutes = async (additionalPrivilegeDAL,secretFolderDAL: folderDAL,permissionService,- membershipDAL+ folderPermissionDAL});const kmsService = kmsServiceFactory({diff --git a/backend/src/server/routes/sanitizedSchema/folder-access.ts b/backend/src/server/routes/sanitizedSchema/folder-access.tsindex 717826466d..b58615ccb2 100644--- a/backend/src/server/routes/sanitizedSchema/folder-access.ts+++ b/backend/src/server/routes/sanitizedSchema/folder-access.ts@@ -17,3 +17,18 @@ export const SanitizedFolderAccessSchema = z.object({createdAt: z.date(),updatedAt: z.date()});++export const SanitizedFolderAccessUserSchema = z.object({+ userId: z.string().uuid(),+ username: z.string(),+ email: z.string().nullable(),+ firstName: z.string().nullable(),+ lastName: z.string().nullable(),+ folderRBACAccess: SanitizedFolderAccessSchema.nullable()+});++export const SanitizedFolderAccessIdentitySchema = z.object({+ identityId: z.string().uuid(),+ name: z.string(),+ folderRBACAccess: SanitizedFolderAccessSchema.nullable()+});diff --git a/backend/src/services/folder-permission/folder-permission-dal.ts b/backend/src/services/folder-permission/folder-permission-dal.tsnew file mode 100644index 0000000000..4a4037bb4a--- /dev/null+++ b/backend/src/services/folder-permission/folder-permission-dal.ts@@ -0,0 +1,317 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { AccessScope, TableName, TAdditionalPrivileges } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { sanitizeSqlLikeString } from "@app/lib/fn";++import { ActorType } from "../auth/auth-type";++export type TFolderPermissionDALFactory = ReturnType<typeof folderPermissionDALFactory>;++// UNION (not UNION ALL): a single actor can be reached both directly and through several groups.+type TFindFolderAccessActorsDAL = {+ projectId: string;+ orgId: string;+ folderId: string;+ search?: string;+ limit: number;+ offset: number;+};++// Nullable columns come back from knex as `T | null | undefined` because the generated table types+// mark them optional, so every field here has to tolerate undefined and be normalized below.+type TMaybe<T> = T | null | undefined;++const $folderAccessSelect = (db: Knex) => [+ db.ref("id").withSchema(TableName.AdditionalPrivilege).as("folderAccessId"),+ db.ref("role").withSchema(TableName.AdditionalPrivilege).as("folderAccessRole"),+ db.ref("isTemporary").withSchema(TableName.AdditionalPrivilege).as("folderAccessIsTemporary"),+ db.ref("temporaryMode").withSchema(TableName.AdditionalPrivilege).as("folderAccessTemporaryMode"),+ db.ref("temporaryRange").withSchema(TableName.AdditionalPrivilege).as("folderAccessTemporaryRange"),+ db+ .ref("temporaryAccessStartTime")+ .withSchema(TableName.AdditionalPrivilege)+ .as("folderAccessTemporaryAccessStartTime"),+ db.ref("temporaryAccessEndTime").withSchema(TableName.AdditionalPrivilege).as("folderAccessTemporaryAccessEndTime"),+ db.ref("createdAt").withSchema(TableName.AdditionalPrivilege).as("folderAccessCreatedAt"),+ db.ref("updatedAt").withSchema(TableName.AdditionalPrivilege).as("folderAccessUpdatedAt")+];++type TFolderAccessRow = {+ folderAccessId: TMaybe<string>;+ folderAccessRole: TMaybe<string>;+ folderAccessIsTemporary: TMaybe<boolean>;+ folderAccessTemporaryMode: TMaybe<string>;+ folderAccessTemporaryRange: TMaybe<string>;+ folderAccessTemporaryAccessStartTime: TMaybe<Date>;+ folderAccessTemporaryAccessEndTime: TMaybe<Date>;+ folderAccessCreatedAt: TMaybe<Date>;+ folderAccessUpdatedAt: TMaybe<Date>;+};++type TFolderAccessGrantRow = Pick<+ TAdditionalPrivileges,+ | "id"+ | "role"+ | "isTemporary"+ | "temporaryMode"+ | "temporaryRange"+ | "temporaryAccessStartTime"+ | "temporaryAccessEndTime"+ | "createdAt"+ | "updatedAt"+>;++type TUserFolderAccessQueryRow = TFolderAccessRow & {+ userId: string;+ username: string;+ email: TMaybe<string>;+ firstName: TMaybe<string>;+ lastName: TMaybe<string>;+};++type TIdentityFolderAccessQueryRow = TFolderAccessRow & {+ identityId: string;+ name: string;+};++const $mapFolderAccess = (el: TFolderAccessRow): TFolderAccessGrantRow | null => {+ if (!el.folderAccessId || !el.folderAccessCreatedAt || !el.folderAccessUpdatedAt) return null;+ return {+ id: el.folderAccessId,+ role: el.folderAccessRole ?? null,+ isTemporary: Boolean(el.folderAccessIsTemporary),+ temporaryMode: el.folderAccessTemporaryMode ?? null,+ temporaryRange: el.folderAccessTemporaryRange ?? null,+ temporaryAccessStartTime: el.folderAccessTemporaryAccessStartTime ?? null,+ temporaryAccessEndTime: el.folderAccessTemporaryAccessEndTime ?? null,+ createdAt: el.folderAccessCreatedAt,+ updatedAt: el.folderAccessUpdatedAt+ };+};++const $projectScoped = (projectId: string, orgId: string) => (qb: Knex.QueryBuilder) => {+ void qb+ .where(`${TableName.Membership}.scope`, AccessScope.Project)+ .where(`${TableName.Membership}.scopeProjectId`, projectId)+ .where(`${TableName.Membership}.scopeOrgId`, orgId);+};++export const folderPermissionDALFactory = (db: TDbClient) => {+ // Bound to the user/identity id, not Membership.actor*Id, which is NULL on a group membership row.+ // permission-dal.ts documents the same bug: the column-to-column form silently dropped privileges+ // for every actor whose only project access came through a group.+ const $joinFolderGrant = (actorTable: TableName.Users | TableName.Identity, folderId: string) => {+ const privilegeActorColumn = actorTable === TableName.Users ? "actorUserId" : "actorIdentityId";++ return (qb: Knex.QueryBuilder) => {+ void qb.leftJoin(TableName.AdditionalPrivilege, (bd) => {+ void bd+ .on(`${TableName.AdditionalPrivilege}.${privilegeActorColumn}`, `${actorTable}.id`)+ .andOn(`${TableName.AdditionalPrivilege}.folderId`, "=", db.raw("?", [folderId]));+ });+ };+ };++ const $userSelect = () => [+ db.ref("id").withSchema(TableName.Users).as("userId"),+ db.ref("username").withSchema(TableName.Users).as("username"),+ db.ref("email").withSchema(TableName.Users).as("email"),+ db.ref("firstName").withSchema(TableName.Users).as("firstName"),+ db.ref("lastName").withSchema(TableName.Users).as("lastName"),+ ...$folderAccessSelect(db)+ ];++ const $searchUsers = (search?: string) => (qb: Knex.QueryBuilder) => {+ if (!search) return;+ const term = `%${sanitizeSqlLikeString(search)}%`;+ // grouped so the ORs cannot escape the project scope predicates+ void qb.where((bd) => {+ void bd+ .whereILike(`${TableName.Users}.username`, term)+ .orWhereILike(`${TableName.Users}.email`, term)+ .orWhereILike(`${TableName.Users}.firstName`, term)+ .orWhereILike(`${TableName.Users}.lastName`, term);+ });+ };++ const $identitySelect = () => [+ db.ref("id").withSchema(TableName.Identity).as("identityId"),+ db.ref("name").withSchema(TableName.Identity).as("name"),+ ...$folderAccessSelect(db)+ ];++ const $searchIdentities = (search?: string) => (qb: Knex.QueryBuilder) => {+ if (!search) return;+ void qb.whereILike(`${TableName.Identity}.name`, `%${sanitizeSqlLikeString(search)}%`);+ };++ const $toUserRow = (el: TUserFolderAccessQueryRow) => ({+ userId: el.userId,+ username: el.username,+ email: el.email ?? null,+ firstName: el.firstName ?? null,+ lastName: el.lastName ?? null,+ folderAccess: $mapFolderAccess(el)+ });++ const $toIdentityRow = (el: TIdentityFolderAccessQueryRow) => ({+ identityId: el.identityId,+ name: el.name,+ folderAccess: $mapFolderAccess(el)+ });++ const $usersUnion = (+ conn: Knex,+ { projectId, orgId, folderId, search }: Omit<TFindFolderAccessActorsDAL, "limit" | "offset">+ ) => {+ const direct = conn(TableName.Membership)+ .join(TableName.Users, `${TableName.Users}.id`, `${TableName.Membership}.actorUserId`)+ .modify($projectScoped(projectId, orgId))+ .whereNotNull(`${TableName.Membership}.actorUserId`)+ .where(`${TableName.Users}.isGhost`, false)+ .modify($joinFolderGrant(TableName.Users, folderId))+ .modify($searchUsers(search))+ .select($userSelect());++ // isPending is deliberately not filtered: permission-dal.getPermission grants access on group+ // membership alone and the flag is no longer cleared when a user is accepted, so filtering it+ // would hide real access. membership_unique_group_project is partial on `actorGroupId IS NOT+ // NULL`, so without that predicate the planner has no usable index and seq-scans memberships.+ const viaGroup = conn(TableName.UserGroupMembership)+ .join(TableName.Membership, `${TableName.UserGroupMembership}.groupId`, `${TableName.Membership}.actorGroupId`)+ .join(TableName.Users, `${TableName.Users}.id`, `${TableName.UserGroupMembership}.userId`)+ .modify($projectScoped(projectId, orgId))+ .whereNotNull(`${TableName.Membership}.actorGroupId`)+ .where(`${TableName.Users}.isGhost`, false)+ .modify($joinFolderGrant(TableName.Users, folderId))+ .modify($searchUsers(search))+ .select($userSelect());++ return direct.union([viaGroup], true);+ };++ const $identitiesUnion = (+ conn: Knex,+ { projectId, orgId, folderId, search }: Omit<TFindFolderAccessActorsDAL, "limit" | "offset">+ ) => {+ const direct = conn(TableName.Membership)+ .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Membership}.actorIdentityId`)+ .modify($projectScoped(projectId, orgId))+ .whereNotNull(`${TableName.Membership}.actorIdentityId`)+ .modify($joinFolderGrant(TableName.Identity, folderId))+ .modify($searchIdentities(search))+ .select($identitySelect());++ const viaGroup = conn(TableName.IdentityGroupMembership)+ .join(+ TableName.Membership,+ `${TableName.IdentityGroupMembership}.groupId`,+ `${TableName.Membership}.actorGroupId`+ )+ .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.IdentityGroupMembership}.identityId`)+ .modify($projectScoped(projectId, orgId))+ .whereNotNull(`${TableName.Membership}.actorGroupId`)+ .modify($joinFolderGrant(TableName.Identity, folderId))+ .modify($searchIdentities(search))+ .select($identitySelect());++ return direct.union([viaGroup], true);+ };++ const findUsersWithFolderAccess = async (+ { projectId, orgId, folderId, search, limit, offset }: TFindFolderAccessActorsDAL,+ tx?: Knex+ ) => {+ try {+ const conn = tx || db.replicaNode();+ const selector = { projectId, orgId, folderId, search };++ const [docs, countRow] = (await Promise.all([+ conn+ .from($usersUnion(conn, selector).as("folder_access_users"))+ .orderByRaw("lower(coalesce(??, ''))", ["username"])+ .orderBy("userId")+ .limit(limit)+ .offset(offset),+ conn.from($usersUnion(conn, selector).as("folder_access_users")).count("* as count").first()+ ])) as [TUserFolderAccessQueryRow[], { count?: string | number } | undefined];++ return {+ users: docs.map($toUserRow),+ totalCount: Number(countRow?.count ?? 0)+ };+ } catch (error) {+ throw new DatabaseError({ error, name: "FindUsersWithFolderAccess" });+ }+ };++ const findIdentitiesWithFolderAccess = async (+ { projectId, orgId, folderId, search, limit, offset }: TFindFolderAccessActorsDAL,+ tx?: Knex+ ) => {+ try {+ const conn = tx || db.replicaNode();+ const selector = { projectId, orgId, folderId, search };++ const [docs, countRow] = (await Promise.all([+ conn+ .from($identitiesUnion(conn, selector).as("folder_access_identities"))+ .orderByRaw("lower(coalesce(??, ''))", ["name"])+ .orderBy("identityId")+ .limit(limit)+ .offset(offset),+ conn.from($identitiesUnion(conn, selector).as("folder_access_identities")).count("* as count").first()+ ])) as [TIdentityFolderAccessQueryRow[], { count?: string | number } | undefined];++ return {+ identities: docs.map($toIdentityRow),+ totalCount: Number(countRow?.count ?? 0)+ };+ } catch (error) {+ throw new DatabaseError({ error, name: "FindIdentitiesWithFolderAccess" });+ }+ };++ // Access can be inherited from a group, so this is two lookups rather than one membership read.+ // The direct check runs first because it is the common case and short-circuits.+ const hasProjectAccess = async (+ {+ projectId,+ orgId,+ actorId,+ actorType+ }: { projectId: string; orgId: string; actorId: string; actorType: ActorType.USER | ActorType.IDENTITY },+ tx?: Knex+ ) => {+ try {+ const conn = tx || db.replicaNode();+ const isIdentity = actorType === ActorType.IDENTITY;+ const groupTable = isIdentity ? TableName.IdentityGroupMembership : TableName.UserGroupMembership;+ const groupActorColumn = isIdentity ? "identityId" : "userId";++ const direct = (await conn(TableName.Membership)+ .modify($projectScoped(projectId, orgId))+ .where(`${TableName.Membership}.${isIdentity ? "actorIdentityId" : "actorUserId"}`, actorId)+ .first(`${TableName.Membership}.id`)) as unknown as { id: string } | undefined;+ if (direct) return true;++ const viaGroup = (await conn(groupTable)+ .join(TableName.Membership, `${groupTable}.groupId`, `${TableName.Membership}.actorGroupId`)+ .modify($projectScoped(projectId, orgId))+ .where(`${groupTable}.${groupActorColumn}`, actorId)+ .first(`${TableName.Membership}.id`)) as unknown as { id: string } | undefined;++ return Boolean(viaGroup);+ } catch (error) {+ throw new DatabaseError({ error, name: "FolderPermissionHasProjectAccess" });+ }+ };++ return {+ findUsersWithFolderAccess,+ findIdentitiesWithFolderAccess,+ hasProjectAccess+ };+};diff --git a/backend/src/services/folder-permission/folder-permission-fns.ts b/backend/src/services/folder-permission/folder-permission-fns.tsindex ab82049a49..a2025d264d 100644--- a/backend/src/services/folder-permission/folder-permission-fns.ts+++ b/backend/src/services/folder-permission/folder-permission-fns.ts@@ -11,8 +11,8 @@ import { ms } from "@app/lib/ms";import { OrgServiceActor } from "@app/lib/types";import { ActorType } from "../auth/auth-type";-import { TMembershipDALFactory } from "../membership/membership-dal";import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";+import { TFolderPermissionDALFactory } from "./folder-permission-dal";import { TFolderGrant, TFolderGrantActor, TFolderGrantTypeInput, TResolvedFolder } from "./folder-permission-types";export const computeTemporaryFields = (type: TFolderGrantTypeInput | undefined) => {@@ -47,11 +47,6 @@ export const resolveFolder = async (message: `Folder with ID '${folderId}' not found in project with ID '${projectId}'`});}- if (folder.parentId === null) {- throw new BadRequestError({- message: "Folder access cannot be granted on the root folder. Grant a project role instead, or pick a subfolder."- });- }if (folder.isReserved) {throw new BadRequestError({ message: "Folder access cannot be granted on a reserved system folder." });}@@ -81,18 +76,22 @@ export const assertManageFolderAccess = async ();};+// Access can be inherited from a group, so this cannot be a membership lookup on+// actorUserId/actorIdentityId: a group-derived actor has no such row and would be rejected despite+// holding real access to the project.export const assertTargetMembership = async (orgId: string,projectId: string,target: TFolderGrantActor,- membershipDAL: Pick<TMembershipDALFactory, "findOne">+ folderPermissionDAL: Pick<TFolderPermissionDALFactory, "hasProjectAccess">) => {- const membership = await membershipDAL.findOne({- scopeOrgId: orgId,- scopeProjectId: projectId,- [target.actorType === ActorType.USER ? "actorUserId" : "actorIdentityId"]: target.actorId+ const hasAccess = await folderPermissionDAL.hasProjectAccess({+ orgId,+ projectId,+ actorId: target.actorId,+ actorType: target.actorType});- if (!membership) {+ if (!hasAccess) {throw new NotFoundError({message:target.actorType === ActorType.USERdiff --git a/backend/src/services/folder-permission/folder-permission-service.ts b/backend/src/services/folder-permission/folder-permission-service.tsindex 8a7119f007..eccbd155d8 100644--- a/backend/src/services/folder-permission/folder-permission-service.ts+++ b/backend/src/services/folder-permission/folder-permission-service.ts@@ -6,8 +6,8 @@ import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";import { alphaNumericNanoId } from "@app/lib/nanoid";import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";-import { TMembershipDALFactory } from "../membership/membership-dal";import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";+import { TFolderPermissionDALFactory } from "./folder-permission-dal";import {assertManageFolderAccess,assertTargetMembership,@@ -17,7 +17,12 @@ import {targetLabel,toFolderGrant} from "./folder-permission-fns";-import { TCreateFolderGrantDTO, TDeleteFolderGrantDTO, TUpdateFolderGrantDTO } from "./folder-permission-types";+import {+ TCreateFolderGrantDTO,+ TDeleteFolderGrantDTO,+ TListFolderAccessActorsDTO,+ TUpdateFolderGrantDTO+} from "./folder-permission-types";type TFolderPermissionServiceFactoryDep = {additionalPrivilegeDAL: Pick<@@ -26,7 +31,10 @@ type TFolderPermissionServiceFactoryDep = {>;secretFolderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "invalidateProjectFolderPermissionCache">;- membershipDAL: Pick<TMembershipDALFactory, "findOne">;+ folderPermissionDAL: Pick<+ TFolderPermissionDALFactory,+ "findUsersWithFolderAccess" | "findIdentitiesWithFolderAccess" | "hasProjectAccess"+ >;};export type TFolderPermissionServiceFactory = ReturnType<typeof folderPermissionServiceFactory>;@@ -35,13 +43,13 @@ export const folderPermissionServiceFactory = ({additionalPrivilegeDAL,secretFolderDAL,permissionService,- membershipDAL+ folderPermissionDAL}: TFolderPermissionServiceFactoryDep) => {const createFolderGrant = async (dto: TCreateFolderGrantDTO) => {const { projectId, folderId, target } = dto;const folder = await resolveFolder(projectId, folderId, secretFolderDAL);await assertManageFolderAccess(dto.permission, projectId, folder, permissionService);- await assertTargetMembership(dto.permission.orgId, projectId, target, membershipDAL);+ await assertTargetMembership(dto.permission.orgId, projectId, target, folderPermissionDAL);const actorField = targetActorField(target);const alreadyExistsError = () =>@@ -84,7 +92,7 @@ export const folderPermissionServiceFactory = ({const { projectId, folderId, target } = dto;const folder = await resolveFolder(projectId, folderId, secretFolderDAL);await assertManageFolderAccess(dto.permission, projectId, folder, permissionService);- await assertTargetMembership(dto.permission.orgId, projectId, target, membershipDAL);+ await assertTargetMembership(dto.permission.orgId, projectId, target, folderPermissionDAL);const actorField = targetActorField(target);const grant = await additionalPrivilegeDAL.transaction(async (tx) => {@@ -134,9 +142,57 @@ export const folderPermissionServiceFactory = ({return { folderAccess: toFolderGrant(grant, projectId, folderId, folder) };};+ const listFolderAccessUsers = async (dto: TListFolderAccessActorsDTO) => {+ const { projectId, folderId, limit, offset, search } = dto;+ const folder = await resolveFolder(projectId, folderId, secretFolderDAL);+ await assertManageFolderAccess(dto.permission, projectId, folder, permissionService);++ const { users, totalCount } = await folderPermissionDAL.findUsersWithFolderAccess({+ projectId,+ orgId: dto.permission.orgId,+ folderId,+ search,+ limit,+ offset+ });++ return {+ users: users.map(({ folderAccess, ...user }) => ({+ ...user,+ folderRBACAccess: folderAccess ? toFolderGrant(folderAccess, projectId, folderId, folder) : null+ })),+ totalCount+ };+ };++ const listFolderAccessIdentities = async (dto: TListFolderAccessActorsDTO) => {+ const { projectId, folderId, limit, offset, search } = dto;+ const folder = await resolveFolder(projectId, folderId, secretFolderDAL);+ await assertManageFolderAccess(dto.permission, projectId, folder, permissionService);++ const { identities, totalCount } = await folderPermissionDAL.findIdentitiesWithFolderAccess({+ projectId,+ orgId: dto.permission.orgId,+ folderId,+ search,+ limit,+ offset+ });++ return {+ identities: identities.map(({ folderAccess, ...identity }) => ({+ ...identity,+ folderRBACAccess: folderAccess ? toFolderGrant(folderAccess, projectId, folderId, folder) : null+ })),+ totalCount+ };+ };+return {createFolderGrant,updateFolderGrant,- deleteFolderGrant+ deleteFolderGrant,+ listFolderAccessUsers,+ listFolderAccessIdentities};};diff --git a/backend/src/services/folder-permission/folder-permission-types.ts b/backend/src/services/folder-permission/folder-permission-types.tsindex 56bc6c9412..2ec6f3c569 100644--- a/backend/src/services/folder-permission/folder-permission-types.ts+++ b/backend/src/services/folder-permission/folder-permission-types.ts@@ -50,6 +50,15 @@ export type TDeleteFolderGrantDTO = {target: TFolderGrantActor;};+export type TListFolderAccessActorsDTO = {+ permission: OrgServiceActor;+ projectId: string;+ folderId: string;+ limit: number;+ offset: number;+ search?: string;+};+export type TFolderGrant = {id: string;projectId: string;