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(agent-vault): default storage for session logs (#8642)
Saif Ur Rahman7b00ff2434c4
diff --git a/CLAUDE.md b/CLAUDE.mdindex d94acb74b6..35f6f0eb92 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -148,6 +148,15 @@ for product vocabulary only: resolving the resource a request names, notificatioAny rule about what is *allowed* belongs in the resource, or the product's own API and the shared APIstop agreeing.+### Object Storage++New product files go to S3 through `backend/src/services/object-storage/`, not a product's own S3 client (PAM+recordings predate it and haven't moved). A product+registers a namespace (record-first path like `sessions/{sessionId}/logs/{file}`, checked for naming collisions at+boot) and the layer builds org-first keys, signs links, and applies the retention tag and, for default storage on Infisical Cloud, a daily upload cap. Storage is+`default` (the instance's bucket, `OBJECT_STORAGE_S3_*`) or `external` (the customer's, through an AWS connection);+use those two words everywhere.+### API Layer (Frontend)React Query + Axios with query key factories per domain. Each API domain in `frontend/src/hooks/api/` has `queries.tsx`, `mutations.tsx`, and `types.tsx` — see `frontend/CLAUDE.md` for conventions.diff --git a/backend/e2e-test/fakes/object-storage-default-fns.ts b/backend/e2e-test/fakes/object-storage-default-fns.tsnew file mode 100644index 0000000000..d77134a252--- /dev/null+++ b/backend/e2e-test/fakes/object-storage-default-fns.ts@@ -0,0 +1,41 @@+import type * as RealDefaultStorage from "../../src/services/object-storage/object-storage-default-fns";++// Stands in for the instance's default storage settings, which production reads from OBJECT_STORAGE_S3_* once at+// boot. Specs need both an instance with a bucket and one without, so this lets them switch. Unset by default, so+// specs that never mention default storage behave as on an instance without a bucket. Wired up by test.alias in+// vitest.e2e.config.mts; nothing under src/ references this file.++export const FAKE_DEFAULT_STORAGE: RealDefaultStorage.TDefaultStorage = {+ bucket: "instance-bucket",+ region: "us-east-1",+ prefix: "infisical"+};++type TFakeState = { defaultStorage: RealDefaultStorage.TDefaultStorage | null };++// On globalThis for the same reason as the S3 fake: the server and a spec can reach this module by different+// specifiers, and module state would then split into two copies.+const globalScope = globalThis as typeof globalThis & { infisicalFakeDefaultStorage?: TFakeState };+globalScope.infisicalFakeDefaultStorage ??= { defaultStorage: null };+const state = globalScope.infisicalFakeDefaultStorage;++export const fakeDefaultStorage = {+ set: (defaultStorage: RealDefaultStorage.TDefaultStorage = FAKE_DEFAULT_STORAGE) => {+ state.defaultStorage = defaultStorage;+ },+ unset: () => {+ state.defaultStorage = null;+ },+ reset: () => {+ state.defaultStorage = null;+ }+};++export const getDefaultStorage = () => state.defaultStorage;++export const isDefaultStorageConfigured = () => state.defaultStorage !== null;++export const assertFakeMatchesRealDefaultStorage: Pick<+ typeof RealDefaultStorage,+ "getDefaultStorage" | "isDefaultStorageConfigured"+> = { getDefaultStorage, isDefaultStorageConfigured };diff --git a/backend/e2e-test/fakes/s3.ts b/backend/e2e-test/fakes/s3.tsindex f04d2618a6..2e0353d146 100644--- a/backend/e2e-test/fakes/s3.ts+++ b/backend/e2e-test/fakes/s3.ts@@ -11,19 +11,21 @@ import type * as RealS3 from "../../src/lib/aws/s3";// upload filler bytes against a fixed digest. Listing follows S3: names in binary order, after// StartAfter, at most MaxKeys, with IsTruncated when more remain.-type TAccessFailure = "unreachable" | "unwritable";+type TAccessFailure = "unlistable" | "unwritable";type TFakeState = {objects: Map<string, Buffer>;+ tags: Map<string, string>;accessFailure: TAccessFailure | null;isListFailing: boolean;- presignedPuts: Map<string, { bucket: string; key: string; contentLength: number }>;+ presignedPuts: Map<string, { bucket: string; key: string; contentLength: number; tagging?: string }>;presignedGets: Map<string, { bucket: string; key: string }>;nextUrlId: number;};const freshState = (): TFakeState => ({objects: new Map(),+ tags: new Map(),accessFailure: null,isListFailing: false,presignedPuts: new Map(),@@ -44,7 +46,7 @@ export const fakeS3Bucket = {Object.assign(state, freshState());},- // Make checkAccess fail the way a bucket that can't be reached, or can't be written to, would.+ // Make the bucket check fail the way a bucket that can't be listed, or can't be written to, would.// Pass null to go back to accepting.failsAccessCheckWith: (failure: TAccessFailure | null) => {state.accessFailure = failure;@@ -71,8 +73,12 @@ export const fakeS3Bucket = {throw new Error(`Presigned PUT is create-only, and ${target.key} already exists`);}state.objects.set(id, body);+ // S3 applies the tag a link was signed with to the object it stores.+ if (target.tagging) state.tags.set(id, target.tagging);},+ objectTags: (bucket: string, key: string) => state.tags.get(objectId(bucket, key)) ?? null,+get: (url: string) => {const target = state.presignedGets.get(url);if (!target) throw new Error(`No presigned GET was minted for ${url}`);@@ -94,9 +100,17 @@ export const createS3Bucket = ({ bucket }: Parameters<typeof RealS3.createS3Buck};return {- presignCreateOnlyPut: ({ key, contentLength }: { key: string; contentLength: number }) => {+ presignCreateOnlyPut: ({+ key,+ contentLength,+ tagging+ }: {+ key: string;+ contentLength: number;+ tagging?: string;+ }) => {const url = mintUrl("put", key);- state.presignedPuts.set(url, { bucket, key, contentLength });+ state.presignedPuts.set(url, { bucket, key, contentLength, tagging });return Promise.resolve(url);},@@ -120,19 +134,36 @@ export const createS3Bucket = ({ bucket }: Parameters<typeof RealS3.createS3Buckreturn Promise.resolve({ objects: matching.slice(0, maxKeys), isTruncated: matching.length > maxKeys });},- checkReachable: (): Promise<{ ok: true } | { ok: false; error: unknown }> =>+ checkListAccess: (): Promise<RealS3.TS3Check> =>Promise.resolve(- state.accessFailure === "unreachable"- ? { ok: false, error: new Error("fake bucket is unreachable") }+ state.accessFailure === "unlistable"+ ? {+ ok: false,+ error: new S3ServiceException({+ name: "AccessDenied",+ $fault: "client",+ $metadata: { httpStatusCode: 403 },+ message: "Access Denied"+ })+ }: { ok: true }),- checkAccess: (): Promise<RealS3.TS3AccessCheck> =>- Promise.resolve(- state.accessFailure- ? { ok: false, failure: state.accessFailure, error: new Error(`fake bucket is ${state.accessFailure}`) }- : { ok: true }- )+ writeTestObject: (key: string): Promise<RealS3.TS3Check> => {+ if (state.accessFailure === "unwritable") {+ return Promise.resolve({+ ok: false,+ error: new S3ServiceException({+ name: "AccessDenied",+ $fault: "client",+ $metadata: { httpStatusCode: 403 },+ message: "Access Denied"+ })+ });+ }+ state.objects.set(objectId(bucket, key), Buffer.from("infisical-access-check"));+ return Promise.resolve({ ok: true });+ }};};@@ -144,6 +175,6 @@ export const assertFakeBucketShapeMatches: { [K in keyof RealS3.TS3Bucket]: unknpresignCreateOnlyPut: null,presignGet: null,listPage: null,- checkReachable: null,- checkAccess: null+ checkListAccess: null,+ writeTestObject: null};diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.tsindex 7d1c649129..e68c7e26a0 100644--- a/backend/e2e-test/mocks/keystore.ts+++ b/backend/e2e-test/mocks/keystore.ts@@ -86,6 +86,9 @@ export const mockKeyStore = (): TKeyStoreFactory => {incrementByAndRefreshExpiryIfUnderLimit: async () => {return 1;},+ incrementByIfUnderLimitWithFixedExpiry: async (_key, value) => {+ return value;+ },claimLeastLoaded: async (keys, baseOccupancies) => {if (keys.length === 0) return 0;if (keys.length !== baseOccupancies.length) {diff --git a/backend/e2e-test/object-storage-daily-bytes-keystore.spec.ts b/backend/e2e-test/object-storage-daily-bytes-keystore.spec.tsnew file mode 100644index 0000000000..261d2da514--- /dev/null+++ b/backend/e2e-test/object-storage-daily-bytes-keystore.spec.ts@@ -0,0 +1,61 @@+import { randomUUID } from "node:crypto";++import { Redis } from "ioredis";+import { beforeEach, describe, expect, test } from "vitest";++import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";++// This runs against the real Redis the e2e environment starts, because the daily cap is a Lua script, and what it+// promises (the cap holds under concurrent uploads, a refusal adds nothing, the expiry is fixed at the first write)+// only Redis can show.+declare const testRedis: Redis;+declare const testKeyStore: TKeyStoreFactory;++const LIMIT = 100;+const TTL_SECONDS = 2 * 24 * 60 * 60;++let key: string;++const admit = (value: number) => testKeyStore.incrementByIfUnderLimitWithFixedExpiry(key, value, LIMIT, TTL_SECONDS);++beforeEach(async () => {+ key = KeyStorePrefixes.ObjectStorageDailyBytes(randomUUID(), "2026-10-14");+ await testRedis.del(key);+});++describe("object storage daily byte counter", () => {+ test("adds up to the cap and refuses what would pass it", async () => {+ expect(await admit(60)).toBe(60);+ expect(await admit(40)).toBe(100);+ expect(await admit(1)).toBe(-1);+ });++ test("a refusal adds nothing, so a smaller upload still fits", async () => {+ expect(await admit(90)).toBe(90);+ expect(await admit(20)).toBe(-1);+ expect(await testRedis.get(key)).toBe("90");+ expect(await admit(10)).toBe(100);+ });++ test("concurrent uploads at the cap never take it past the limit", async () => {+ const results = await Promise.all(Array.from({ length: 30 }, () => admit(7)));+ const admitted = results.filter((total) => total !== -1);++ expect(admitted).toHaveLength(Math.floor(LIMIT / 7));+ expect(Number(await testRedis.get(key))).toBe(admitted.length * 7);+ });++ test("the expiry is set by the first write and later writes don't extend it", async () => {+ await admit(10);+ expect(await testRedis.ttl(key)).toBeGreaterThan(TTL_SECONDS - 5);++ await testRedis.expire(key, 60);+ await admit(10);+ expect(await testRedis.ttl(key)).toBeLessThanOrEqual(60);+ });++ test("a refused first write leaves no key behind", async () => {+ expect(await admit(LIMIT + 1)).toBe(-1);+ expect(await testRedis.exists(key)).toBe(0);+ });+});diff --git a/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts b/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.tsindex 93a411edf0..802a0e18e8 100644--- a/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts@@ -1,6 +1,7 @@import crypto from "node:crypto";import { fakeAwsConnection } from "e2e-test/fakes/aws-connection-fns";+import { FAKE_DEFAULT_STORAGE, fakeDefaultStorage } from "e2e-test/fakes/object-storage-default-fns";import { fakeS3Bucket } from "e2e-test/fakes/s3";import { createAwsAppConnection, deleteAwsAppConnection } from "e2e-test/testUtils/app-connections";import { v7 as uuidv7 } from "uuid";@@ -11,16 +12,20 @@ import {AGENT_VAULT_SESSION_LOG_FEED_MAX_ENTRIES,AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES} from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-constants";-import { AgentVaultSessionLogErrorName } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-enums";import {- chunkIdTimeMs,encodeHistoryCursor,- encodeTailCursor,- toRev-} from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-fns";+ encodeTailCursor+} from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-cursor-fns";+import { AgentVaultSessionLogErrorName } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-enums";+import { chunkIdTimeMs, toRev } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-fns";import { initLogger } from "@app/lib/logger";import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import {+ down as dropSessionLogStorageType,+ up as addSessionLogStorageType+} from "../../../src/db/migrations/20261014120000_agent-vault-session-log-storage-type";+initLogger();const authHeader = { authorization: `Bearer ${jwtAuthToken}` };@@ -148,11 +153,30 @@ const SETTINGS_URL = "/api/v1/agent-vault/settings/session-logs";const saveConfig = async (patch: Record<string, unknown>) => inject("PATCH", SETTINGS_URL, patch);+const ORG_ID = seedData1.organization.id;++// Every product's files sit under its org, then its own folder, then the namespace's record-first path.+const productFolder = (prefix: string | null = "logs") => `${prefix ? `${prefix}/` : ""}orgs/${ORG_ID}/agent-vault/`;+const sessionFolder = (sessionId: string, prefix: string | null = "logs") =>+ `${productFolder(prefix)}sessions/${sessionId}/logs/`;+describe("Agent Vault session logs", async () => {let connectionId: string;let connectionName: string;let projectId: string;+ const externalStorage = (fields: Record<string, unknown> = {}) => ({+ type: "external",+ appConnectionId: connectionId,+ bucket: BUCKET,+ region: "us-east-1",+ keyPrefix: "logs",+ ...fields+ });++ const configure = async (fields: Record<string, unknown> = {}) =>+ saveConfig({ enabled: true, storage: externalStorage(fields) });+beforeAll(async () => {projectId = await getProjectId();expect(@@ -175,18 +199,23 @@ describe("Agent Vault session logs", async () => {beforeEach(async () => {fakeS3Bucket.reset();fakeAwsConnection.reset();+ fakeDefaultStorage.reset();await testDb("agent_vault_session_log_configs").where({ projectId }).del();// Tests create their own proxies, and an org can hold only AGENT_VAULT_MAX_PROXIES_PER_ORG.await testDb("agent_vault_proxies").where({ projectId }).del();});describe("settings", () => {- test("reads as off, with no destination, before anything is configured", async () => {+ type TSettingsBody = {+ settings: { enabled: boolean; storage: Record<string, unknown> } | null;+ defaultStorage: { configured: boolean };+ };+ const settingsOf = (res: { payload: string }) => JSON.parse(res.payload) as TSettingsBody;++ test("with no instance bucket and nothing saved, there are no settings and nothing to check", async () => {const res = await inject("GET", SETTINGS_URL);expect(res.statusCode).toBe(200);-- const body = JSON.parse(res.payload) as { settings: Record<string, unknown> };- expect(body.settings).toMatchObject({ enabled: false, bucket: null, appConnectionId: null });+ expect(settingsOf(res)).toEqual({ settings: null, defaultStorage: { configured: false } });const health = await inject("GET", `${SETTINGS_URL}/health`);expect(health.statusCode).toBe(200);@@ -197,34 +226,100 @@ describe("Agent Vault session logs", async () => {expect(JSON.parse(probe.payload).probe).toBeNull();});- test("saving a destination validates the bucket, and the CORS probe then points at it", async () => {- const res = await saveConfig({- enabled: true,- appConnectionId: connectionId,- bucket: BUCKET,- region: "us-east-1",- keyPrefix: "logs"+ test("with an instance bucket and nothing saved, session logs are on in default storage", async () => {+ fakeDefaultStorage.set();+ const res = await inject("GET", SETTINGS_URL);+ expect(settingsOf(res)).toEqual({+ settings: { enabled: true, storage: { type: "default" } },+ defaultStorage: { configured: true }});- expect(res.statusCode, res.payload).toBe(200);+ expect(JSON.parse((await inject("GET", `${SETTINGS_URL}/cors-probe`)).payload).probe).toBeNull();+ });- const body = JSON.parse(res.payload) as { settings: Record<string, unknown> };- expect(body.settings).toMatchObject({ enabled: true, bucket: BUCKET, region: "us-east-1", keyPrefix: "logs" });+ test("saving external storage checks the bucket at the product folder, and the CORS probe points there", async () => {+ const res = await configure();+ expect(res.statusCode, res.payload).toBe(200);+ expect(settingsOf(res).settings).toEqual({ enabled: true, storage: externalStorage() });+ expect(fakeS3Bucket.objectKeys(BUCKET)).toEqual([`${productFolder()}.check`]);const probe = await inject("GET", `${SETTINGS_URL}/cors-probe`);expect(probe.statusCode).toBe(200);const probeBody = JSON.parse(probe.payload) as { probe: { url: string; expiresInSeconds: number } | null };- expect(new URL(probeBody.probe?.url as string).pathname).toBe("/logs/.cors-probe");+ expect(new URL(probeBody.probe?.url as string).pathname).toBe(`/${productFolder()}.cors-probe`);});- test("a bucket it cannot write to is refused with the actionable message, and nothing is saved", async () => {- fakeS3Bucket.failsAccessCheckWith("unwritable");+ test("default storage on an instance without a bucket is refused", async () => {+ const res = await saveConfig({ enabled: true, storage: { type: "default" } });+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res.payload).message).toBe("This instance doesn't offer default storage");+ });++ test("turning on without a storage is refused, and turning off sticks once the instance gets a bucket", async () => {+ expect((await saveConfig({ enabled: true })).statusCode).toBe(422);++ const off = await saveConfig({ enabled: false });+ expect(off.statusCode).toBe(200);+ expect(settingsOf(off).settings).toBeNull();++ fakeDefaultStorage.set();+ expect(settingsOf(await inject("GET", SETTINGS_URL)).settings).toEqual({+ enabled: false,+ storage: { type: "default" }+ });+ });++ test("default storage can be turned off and on again", async () => {+ fakeDefaultStorage.set();+ const off = await saveConfig({ enabled: false });+ expect(settingsOf(off).settings).toEqual({ enabled: false, storage: { type: "default" } });- const res = await saveConfig({+ const on = await saveConfig({ enabled: true, storage: { type: "default" } });+ expect(settingsOf(on).settings).toEqual({ enabled: true, storage: { type: "default" } });+ });++ test("switching to default storage drops the bucket and connection, and back again checks the bucket", async () => {+ fakeDefaultStorage.set();+ expect((await configure()).statusCode).toBe(200);++ const toDefault = await saveConfig({ enabled: true, storage: { type: "default" } });+ expect(settingsOf(toDefault).settings).toEqual({ enabled: true, storage: { type: "default" } });+ const row = await testDb("agent_vault_session_log_configs").where({ projectId }).first();+ expect(row).toMatchObject({ storageType: "default", appConnectionId: null, bucket: null, region: null });++ fakeS3Bucket.reset();+ expect((await configure()).statusCode).toBe(200);+ expect(fakeS3Bucket.objectKeys(BUCKET)).toEqual([`${productFolder()}.check`]);+ });++ test("a saved default choice reads as nothing once the operator removes the bucket, and returns with it", async () => {+ fakeDefaultStorage.set();+ expect((await saveConfig({ enabled: true, storage: { type: "default" } })).statusCode).toBe(200);++ fakeDefaultStorage.unset();+ expect(settingsOf(await inject("GET", SETTINGS_URL))).toEqual({+ settings: null,+ defaultStorage: { configured: false }+ });++ fakeDefaultStorage.set();+ expect(settingsOf(await inject("GET", SETTINGS_URL)).settings).toMatchObject({enabled: true,- appConnectionId: connectionId,- bucket: "nope",- region: "us-east-1"+ storage: { type: "default" }});+ });++ test("a saved default choice on an instance without a bucket can still be replaced", async () => {+ fakeDefaultStorage.set();+ expect((await saveConfig({ enabled: true, storage: { type: "default" } })).statusCode).toBe(200);+ fakeDefaultStorage.unset();++ expect((await configure()).statusCode).toBe(200);+ });++ test("a bucket it cannot write to is refused with the actionable message, and nothing is saved", async () => {+ fakeS3Bucket.failsAccessCheckWith("unwritable");++ const res = await configure({ bucket: "nope", keyPrefix: undefined });expect(res.statusCode).toBe(400);expect(JSON.parse(res.payload).message).toBe("Bucket 'nope' is reachable but writing to it failed. Grant s3:PutObject on the configured key prefix"@@ -234,44 +329,31 @@ describe("Agent Vault session logs", async () => {});test("turning session logs off is never blocked by a destination that has gone bad", async () => {- await saveConfig({- enabled: true,- appConnectionId: connectionId,- bucket: BUCKET,- region: "us-east-1"- });-- fakeS3Bucket.failsAccessCheckWith("unreachable");+ await configure();+ fakeS3Bucket.failsAccessCheckWith("unlistable");const res = await saveConfig({ enabled: false });expect(res.statusCode).toBe(200);- expect(JSON.parse(res.payload).settings.enabled).toBe(false);-- expect((await saveConfig({ enabled: true })).statusCode).toBe(400);+ // Off clears the storage, and this instance has no default storage, so nothing is left.+ expect(settingsOf(res).settings).toBeNull();});test("a connection that can't be used says why, on the page and when saving", async () => {- expect(- (await saveConfig({ enabled: true, appConnectionId: connectionId, bucket: BUCKET, region: "us-east-1" }))- .statusCode- ).toBe(200);+ expect((await configure()).statusCode).toBe(200);fakeAwsConnection.failsConfigWith("AWS refused to assume the role");const health = await inject("GET", `${SETTINGS_URL}/health`);const refused = `Couldn't use the AWS connection '${connectionName}' for session logs: AWS refused to assume the role`;expect(JSON.parse(health.payload).health.connectionError).toBe(refused);- const save = await saveConfig({ keyPrefix: "elsewhere" });+ const save = await configure({ keyPrefix: "elsewhere" });expect(save.statusCode).toBe(400);expect(JSON.parse(save.payload).message).toBe(refused);});- test("a bucket the connection can't reach shows as a connection error", async () => {- expect(- (await saveConfig({ enabled: true, appConnectionId: connectionId, bucket: BUCKET, region: "us-east-1" }))- .statusCode- ).toBe(200);- fakeS3Bucket.failsAccessCheckWith("unreachable");+ test("a bucket the connection can't list shows as a connection error", async () => {+ expect((await configure()).statusCode).toBe(200);+ fakeS3Bucket.failsAccessCheckWith("unlistable");const health = await inject("GET", `${SETTINGS_URL}/health`);expect(JSON.parse(health.payload).health.connectionError).toBe(@@ -279,91 +361,84 @@ describe("Agent Vault session logs", async () => {);});- test("turning session logs on without a complete destination names what is missing", async () => {- const res = await saveConfig({ enabled: true });- expect(res.statusCode).toBe(400);- expect(JSON.parse(res.payload).message).toContain("an AWS connection");- expect(JSON.parse(res.payload).message).toContain("a bucket");- });+ test("a connection session logs use cannot be deleted until session logs are turned off", async () => {+ const otherName = `session-logs-aws-other-${Date.now()}`;+ const otherId = await createAwsAppConnection({ name: otherName, authToken: jwtAuthToken });+ expect((await configure({ appConnectionId: otherId })).statusCode).toBe(200);- test("a connection session logs use cannot be deleted", async () => {- await saveConfig({ enabled: true, appConnectionId: connectionId, bucket: BUCKET, region: "us-east-1" });+ const deleteConnection = () =>+ testServer.inject({+ method: "DELETE",+ url: `/api/v1/app-connections/aws/${otherId}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` }+ });+ const blocked = await deleteConnection();+ expect(blocked.statusCode).toBe(400);+ expect(JSON.parse(blocked.payload).message).toContain("Cannot delete App Connection with existing connections");- const res = await testServer.inject({- method: "DELETE",- url: `/api/v1/app-connections/aws/${connectionId}`,- headers: { authorization: `Bearer ${jwtAuthToken}` }- });- expect(res.statusCode).toBe(400);- expect(JSON.parse(res.payload).message).toContain("Cannot delete App Connection with existing connections");+ const off = await saveConfig({ enabled: false });+ expect(off.statusCode, off.payload).toBe(200);+ expect(settingsOf(off)).toEqual({ settings: null, defaultStorage: { configured: false } });- const config = await testDb("agent_vault_session_log_configs").where({ projectId }).first();- expect(config.appConnectionId).toBe(connectionId);+ expect((await deleteConnection()).statusCode).toBe(200);});- test("the connection can be detached only with recording off, and the destination is kept", async () => {- await saveConfig({ enabled: true, appConnectionId: connectionId, bucket: BUCKET, region: "us-east-1" });-- const whileOn = await saveConfig({ appConnectionId: null });- expect(whileOn.statusCode).toBe(400);- expect(JSON.parse(whileOn.payload).message).toContain("Turn off session logs");-- const whileOff = await saveConfig({ enabled: false, appConnectionId: null });- expect(whileOff.statusCode).toBe(200);- expect(JSON.parse(whileOff.payload).settings).toMatchObject({- enabled: false,- appConnectionId: null,- bucket: BUCKET- });+ test("turning off external storage on an instance with a bucket leaves default storage off, not on", async () => {+ fakeDefaultStorage.set();+ await configure();+ const off = await saveConfig({ enabled: false });+ expect(settingsOf(off).settings).toEqual({ enabled: false, storage: { type: "default" } });});- test("a save that puts the connection to a new use checks it again; turning recording off does not", async () => {- await saveConfig({- enabled: true,- appConnectionId: connectionId,- bucket: BUCKET,- region: "us-east-1",- keyPrefix: "logs"- });+ test("turning off works while the connection can't be used, and turning back on checks it again", async () => {+ await configure();await testDb("app_connections").where({ id: connectionId }).update({ app: AppConnection.GCP });try {expect((await saveConfig({ enabled: false })).statusCode).toBe(200);- expect((await saveConfig({ enabled: false })).statusCode).toBe(200);- expect((await saveConfig({ enabled: true })).statusCode).toBe(400);- expect((await saveConfig({ bucket: "a-different-bucket" })).statusCode).toBe(400);- expect((await saveConfig({ region: "us-west-2" })).statusCode).toBe(400);- expect((await saveConfig({ keyPrefix: "elsewhere" })).statusCode).toBe(400);+ expect((await configure()).statusCode).toBe(400);} finally {await testDb("app_connections").where({ id: connectionId }).update({ app: AppConnection.AWS });}});- test("a patch leaves out what it does not name", async () => {- await saveConfig({+ test("the storage type migration keeps buckets that are on external, and turns every other row off", async () => {+ fakeDefaultStorage.set();+ const bucketColumns = { appConnectionId: connectionId, bucket: BUCKET, region: "us-east-1", keyPrefix: "logs" };+ // Rolls the migration back and applies it to one row shaped like those saved before it.+ const migrateRow = async (row: Record<string, unknown>) => {+ await testDb("agent_vault_session_log_configs").where({ projectId }).del();+ await dropSessionLogStorageType(testDb);+ await testDb("agent_vault_session_log_configs").insert({ projectId, ...row });+ await addSessionLogStorageType(testDb);+ return settingsOf(await inject("GET", SETTINGS_URL)).settings;+ };++ expect(await migrateRow({ enabled: true, ...bucketColumns })).toEqual({enabled: true,- appConnectionId: connectionId,- bucket: BUCKET,- region: "us-east-1",- keyPrefix: "logs"+ storage: externalStorage()});+ expect(await migrateRow({ enabled: false, ...bucketColumns })).toEqual({+ enabled: false,+ storage: { type: "default" }+ });+ expect(await migrateRow({ enabled: true })).toEqual({ enabled: false, storage: { type: "default" } });- const off = await saveConfig({ enabled: false });- expect(JSON.parse(off.payload).settings).toMatchObject({ enabled: false, bucket: BUCKET, keyPrefix: "logs" });+ // Once the column exists, applying it again leaves rows saved since alone.+ await testDb("agent_vault_session_log_configs").where({ projectId }).update({ enabled: true });+ await addSessionLogStorageType(testDb);+ expect(settingsOf(await inject("GET", SETTINGS_URL)).settings).toEqual({+ enabled: true,+ storage: { type: "default" }+ });});test("the key prefix is saved as typed, and one with a slash at either end is refused", async () => {- const saved = await saveConfig({- enabled: true,- appConnectionId: connectionId,- bucket: BUCKET,- region: "us-east-1",- keyPrefix: "logs/agent-vault"- });- expect(JSON.parse(saved.payload).settings.keyPrefix).toBe("logs/agent-vault");+ const saved = await configure({ keyPrefix: "logs/agent-vault" });+ expect(settingsOf(saved).settings?.storage.keyPrefix).toBe("logs/agent-vault");const refused = await Promise.all(- ["/logs", "logs/", "logs//agent-vault"].map((keyPrefix) => saveConfig({ keyPrefix }))+ ["/logs", "logs/", "logs//agent-vault"].map((keyPrefix) => configure({ keyPrefix })));expect(refused.map((res) => res.statusCode)).toEqual([422, 422, 422]);});@@ -381,16 +456,6 @@ describe("Agent Vault session logs", async () => {});describe("recording a chunk", () => {- const configure = async (patch: Record<string, unknown> = {}) =>- saveConfig({- enabled: true,- appConnectionId: connectionId,- bucket: BUCKET,- region: "us-east-1",- keyPrefix: "logs",- ...patch- });-const tailedChunks = async (sessionId: string) =>(await inject("GET", `/api/v1/agent-vault/sessions/${sessionId}/logs/tail`)).json().chunks as unknown[];@@ -403,12 +468,13 @@ describe("Agent Vault session logs", async () => {const chunk = chunkBody();const result = await requestUploadUrl(proxy, session.id, chunk);- expect(fakeS3Bucket.objectKeys(BUCKET)).toEqual([]);+ const chunkKey = `${sessionFolder(session.id)}${toRev(chunkIdTimeMs(chunk.chunkId))}_${chunk.chunkId}.${proxy.id}.json.enc`;+ expect(fakeS3Bucket.objectKeys(BUCKET)).not.toContain(chunkKey);fakeS3Bucket.put(result.uploadUrl, Buffer.alloc(CHUNK_BYTES));- expect(fakeS3Bucket.objectKeys(BUCKET)).toEqual([- `logs/${projectId}/${session.id}/${toRev(chunkIdTimeMs(chunk.chunkId))}_${chunk.chunkId}.${proxy.id}.json.enc`- ]);+ expect(fakeS3Bucket.objectKeys(BUCKET)).toContain(chunkKey);+ // A customer's bucket is theirs to manage, so nothing is tagged for deletion.+ expect(fakeS3Bucket.objectTags(BUCKET, chunkKey)).toBeNull();});test("a re-sent chunk is signed for the same name, which cannot replace what is already stored", async () => {@@ -430,7 +496,7 @@ describe("Agent Vault session logs", async () => {expect(fakeS3Bucket.get(only.presignedGetUrl)).toEqual(stored);});- test("with no key prefix, a chunk lands at the bucket root and reads back", async () => {+ test("with no key prefix, a chunk lands under the org at the bucket root and reads back", async () => {await configure({ keyPrefix: "" });const bundle = await createAccessBundle(`session-logs-root-${Date.now()}`);const session = await mintSession(bundle.name);@@ -440,8 +506,7 @@ describe("Agent Vault session logs", async () => {const stored = Buffer.alloc(CHUNK_BYTES, 3);fakeS3Bucket.put(uploadUrl, stored);- const [key] = fakeS3Bucket.objectKeys(BUCKET);- expect(key.startsWith(`${projectId}/${session.id}/`)).toBe(true);+ expect(fakeS3Bucket.objectKeys(BUCKET).some((key) => key.startsWith(sessionFolder(session.id, null)))).toBe(true);const read = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);const [only] = (JSON.parse(read.payload) as { chunks: { presignedGetUrl: string }[] }).chunks;@@ -481,7 +546,8 @@ describe("Agent Vault session logs", async () => {});test("is refused with the named error while session logs are off", async () => {- await configure({ enabled: false });+ await configure();+ expect((await saveConfig({ enabled: false })).statusCode).toBe(200);const bundle = await createAccessBundle(`session-logs-off-${Date.now()}`);const session = await mintSession(bundle.name);const proxy = await createProxy(`session-logs-off-${Date.now()}`);@@ -491,6 +557,40 @@ describe("Agent Vault session logs", async () => {expect(JSON.parse(res.payload).error).toBe(AgentVaultSessionLogErrorName.Disabled);});+ test("with default storage, a chunk lands in the instance bucket, tagged for deletion, and reads back", async () => {+ fakeDefaultStorage.set();+ const bundle = await createAccessBundle(`session-logs-default-${Date.now()}`);+ const session = await mintSession(bundle.name);+ const proxy = await createProxy(`session-logs-default-${Date.now()}`);++ const chunk = chunkBody();+ const { uploadUrl } = await requestUploadUrl(proxy, session.id, chunk);+ const stored = Buffer.alloc(CHUNK_BYTES, 4);+ fakeS3Bucket.put(uploadUrl, stored);++ const chunkKey = `${sessionFolder(session.id, FAKE_DEFAULT_STORAGE.prefix)}${toRev(chunkIdTimeMs(chunk.chunkId))}_${chunk.chunkId}.${proxy.id}.json.enc`;+ expect(fakeS3Bucket.objectKeys(FAKE_DEFAULT_STORAGE.bucket)).toEqual([chunkKey]);+ expect(fakeS3Bucket.objectTags(FAKE_DEFAULT_STORAGE.bucket, chunkKey)).toBe("retention=30d");++ const read = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);+ const [only] = (JSON.parse(read.payload) as { chunks: { presignedGetUrl: string }[] }).chunks;+ expect(fakeS3Bucket.get(only.presignedGetUrl)).toEqual(stored);+ });++ test("a saved default choice stops recording when the operator removes the instance bucket", async () => {+ fakeDefaultStorage.set();+ expect((await saveConfig({ enabled: true, storage: { type: "default" } })).statusCode).toBe(200);+ fakeDefaultStorage.unset();+ const bundle = await createAccessBundle(`session-logs-default-gone-${Date.now()}`);+ const session = await mintSession(bundle.name);+ const proxy = await createProxy(`session-logs-default-gone-${Date.now()}`);++ const res = await proxy.postChunk(session.id, chunkBody());+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res.payload).error).toBe(AgentVaultSessionLogErrorName.Disabled);+ expect(JSON.parse((await proxy.resolve(session.token, false)).payload).sessionLogs.enabled).toBe(false);+ });+test("a session in another organization is a 404 that reads like a missing one", async () => {await configure();const proxy = await createProxy(`session-logs-foreign-${Date.now()}`);@@ -529,16 +629,6 @@ describe("Agent Vault session logs", async () => {});describe("what resolve tells the proxy", () => {- const configure = async (patch: Record<string, unknown> = {}) =>- saveConfig({- enabled: true,- appConnectionId: connectionId,- bucket: BUCKET,- region: "us-east-1",- keyPrefix: "logs",- ...patch- });-const setup = async (label: string) => {const bundle = await createAccessBundle(`session-logs-resolve-${label}-${Date.now()}`);const session = await mintSession(bundle.name);@@ -622,15 +712,6 @@ describe("Agent Vault session logs", async () => {});describe("what the write endpoint refuses", () => {- const configure = async () =>- saveConfig({- enabled: true,- appConnectionId: connectionId,- bucket: BUCKET,- region: "us-east-1",- keyPrefix: "logs"- });-const setup = async (label: string) => {const bundle = await createAccessBundle(`session-logs-refuse-${label}-${Date.now()}`);const session = await mintSession(bundle.name);@@ -710,15 +791,6 @@ describe("Agent Vault session logs", async () => {});describe("reading a session's logs", () => {- const configure = async () =>- saveConfig({- enabled: true,- appConnectionId: connectionId,- bucket: BUCKET,- region: "us-east-1",- keyPrefix: "logs"- });-const uniqueLabel = () => `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;const seedSession = async () => {@@ -755,6 +827,7 @@ describe("Agent Vault session logs", async () => {type TPage = {sessionLogs: {enabled: boolean;+ disabledReason: "off" | "not-on-plan" | null;isRecordable: boolean;sessionKey: string | null;};@@ -878,7 +951,7 @@ describe("Agent Vault session logs", async () => {test("files someone else put in the session's folder are skipped", async () => {await configure();const { session, chunkIds } = await seedChunks(1);- fakeS3Bucket.putDirect(BUCKET, `logs/${projectId}/${session.id}/0000000000000_notes.txt`, Buffer.from("hi"));+ fakeS3Bucket.putDirect(BUCKET, `${sessionFolder(session.id)}0000000000000_notes.txt`, Buffer.from("hi"));expect((await read(session.id)).chunks.map((chunk) => chunk.chunkId)).toEqual(chunkIds);});@@ -957,10 +1030,10 @@ describe("Agent Vault session logs", async () => {await configure();const { session, chunkIds } = await seedChunks(1);- expect((await saveConfig({ bucket: "a-different-bucket" })).statusCode).toBe(200);+ expect((await configure({ bucket: "a-different-bucket" })).statusCode).toBe(200);expect((await read(session.id)).chunks).toEqual([]);- expect((await saveConfig({ bucket: BUCKET })).statusCode).toBe(200);+ expect((await configure()).statusCode).toBe(200);const page = await read(session.id);expect(page.chunks.map((chunk) => chunk.chunkId)).toEqual(chunkIds);expect(fakeS3Bucket.get(page.chunks[0].presignedGetUrl)).toEqual(Buffer.alloc(CHUNK_BYTES));@@ -970,10 +1043,10 @@ describe("Agent Vault session logs", async () => {await configure();const { session, chunkIds } = await seedChunks(1);- expect((await saveConfig({ keyPrefix: "other" })).statusCode).toBe(200);+ expect((await configure({ keyPrefix: "other" })).statusCode).toBe(200);expect((await read(session.id)).chunks).toEqual([]);- expect((await saveConfig({ keyPrefix: "logs" })).statusCode).toBe(200);+ expect((await configure()).statusCode).toBe(200);expect((await read(session.id)).chunks.map((chunk) => chunk.chunkId)).toEqual(chunkIds);});@@ -982,7 +1055,7 @@ describe("Agent Vault session logs", async () => {const { session, proxy } = await seedSession();await requestUploadUrl(proxy, session.id);- expect((await saveConfig({ bucket: "a-different-bucket" })).statusCode).toBe(200);+ expect((await configure({ bucket: "a-different-bucket" })).statusCode).toBe(200);const body = await tail(session.id);expect(body.chunks).toEqual([]);expect(body.nextCursor).not.toBe(encodeTailCursor("0-0"));@@ -1001,15 +1074,20 @@ describe("Agent Vault session logs", async () => {expect(res.payload).not.toContain("sessionKey");});- test("turning session logs off still serves what was already written", async () => {+ test("turning session logs off hides what was recorded, and setting up the same bucket shows it again", async () => {await configure();const { session } = await seedChunks(2);expect((await saveConfig({ enabled: false })).statusCode).toBe(200);-- const body = await read(session.id);- expect(body.sessionLogs.enabled).toBe(false);- expect(body.chunks).toHaveLength(2);+ const off = await read(session.id);+ expect(off.sessionLogs).toMatchObject({ enabled: false, disabledReason: "off" });+ expect(off.chunks).toEqual([]);+ expect((await tail(session.id)).sessionLogs.disabledReason).toBe("off");++ expect((await configure()).statusCode).toBe(200);+ const on = await read(session.id);+ expect(on.sessionLogs).toMatchObject({ enabled: true, disabledReason: null });+ expect(on.chunks).toHaveLength(2);});const readFails = async (sessionId: string, path = "logs") => {@@ -1017,23 +1095,6 @@ describe("Agent Vault session logs", async () => {return { statusCode: res.statusCode, body: JSON.parse(res.payload) as { error: string; message: string } };};- test("without a connection, a read and the tail fail with the named error and say why", async () => {- await configure();- const { session } = await seedChunks(2);-- expect((await saveConfig({ enabled: false, appConnectionId: null })).statusCode).toBe(200);-- for (const path of ["logs", "logs/tail"]) {- // eslint-disable-next-line no-await-in-loop- const { statusCode, body } = await readFails(session.id, path);- expect(statusCode).toBe(400);- expect(body).toMatchObject({- error: "AgentVaultSessionLogStorageUnavailable",- message: "No AWS connection is set for session logs. Choose one in Settings."- });- }- });-test("when the connection can't be used, a read fails with the named error and says why", async () => {await configure();const { session } = await seedChunks(1);diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex ca98f90fa9..2cc85f3e55 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -2907,6 +2907,7 @@ describe("Agent Vault V1 Router", async () => {findOne: () =>Promise.resolve({enabled,+ storageType: "external",appConnectionId: crypto.randomUUID(),bucket: "session-logs",region: "us-east-1",diff --git a/backend/e2e-test/setup/reset-fakes.ts b/backend/e2e-test/setup/reset-fakes.tsindex fd7f32e7de..66e2dc9d3d 100644--- a/backend/e2e-test/setup/reset-fakes.ts+++ b/backend/e2e-test/setup/reset-fakes.ts@@ -2,6 +2,7 @@ import { auditLogStreamOutboxTuning } from "e2e-test/fakes/audit-log-stream-outbimport { fakeAwsConnection } from "e2e-test/fakes/aws-connection-fns";import { fakeIamUserSecret } from "e2e-test/fakes/aws-iam-user-secret-rotation-fns";import { fakeParameterStore } from "e2e-test/fakes/aws-parameter-store-sync-fns";+import { fakeDefaultStorage } from "e2e-test/fakes/object-storage-default-fns";import { fakeS3Bucket } from "e2e-test/fakes/s3";// The fakes are module singletons shared with the server booted in this same process, and the@@ -18,6 +19,7 @@ beforeAll(() => {fakeParameterStore.reset();fakeAwsConnection.reset();fakeS3Bucket.reset();+ fakeDefaultStorage.reset();fakeIamUserSecret.reset();auditLogStreamOutboxTuning.reset();});diff --git a/backend/src/db/migrations/20261014120000_agent-vault-session-log-storage-type.ts b/backend/src/db/migrations/20261014120000_agent-vault-session-log-storage-type.tsnew file mode 100644index 0000000000..02d72eceb2--- /dev/null+++ b/backend/src/db/migrations/20261014120000_agent-vault-session-log-storage-type.ts@@ -0,0 +1,35 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasColumn(TableName.AgentVaultSessionLogConfig, "storageType"))) {+ await knex.schema.alterTable(TableName.AgentVaultSessionLogConfig, (t) => {+ t.string("storageType", 16).notNullable().defaultTo("default");+ });++ // Rows recording to a bucket so far point at the customer's own bucket.+ await knex(TableName.AgentVaultSessionLogConfig)+ .where({ enabled: true })+ .whereNotNull("appConnectionId")+ .whereNotNull("bucket")+ .whereNotNull("region")+ .update({ storageType: "external" });++ // Everything else was off: rows without a bucket never recorded, and turning off now forgets the bucket.+ await knex(TableName.AgentVaultSessionLogConfig)+ .whereNot({ storageType: "external" })+ .update({ enabled: false, appConnectionId: null, bucket: null, region: null, keyPrefix: null });+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasColumn(TableName.AgentVaultSessionLogConfig, "storageType")) {+ // The analytics view selects this column, and Postgres won't drop a column a view uses. The next regeneration+ // recreates the view without it.+ await knex.raw(`DROP VIEW IF EXISTS analytics.??`, [TableName.AgentVaultSessionLogConfig]);+ await knex.schema.alterTable(TableName.AgentVaultSessionLogConfig, (t) => {+ t.dropColumn("storageType");+ });+ }+}diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yamlindex 93f7b7a0f2..6e5563bc4a 100644--- a/backend/src/db/sanitized-schema.yaml+++ b/backend/src/db/sanitized-schema.yaml@@ -95,6 +95,7 @@ tables:- id- projectId- enabled+ - storageType- createdAt- updatedAtdiff --git a/backend/src/db/schemas/agent-vault-session-log-configs.ts b/backend/src/db/schemas/agent-vault-session-log-configs.tsindex 0322de6735..371e26ff9e 100644--- a/backend/src/db/schemas/agent-vault-session-log-configs.ts+++ b/backend/src/db/schemas/agent-vault-session-log-configs.ts@@ -16,7 +16,8 @@ export const AgentVaultSessionLogConfigsSchema = z.object({region: z.string().nullable().optional(),keyPrefix: z.string().nullable().optional(),createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ storageType: z.string().default("default")});export type TAgentVaultSessionLogConfigs = z.infer<typeof AgentVaultSessionLogConfigsSchema>;diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.tsindex 7d87a82bc2..770c9517d3 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts@@ -17,6 +17,7 @@ import {} from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";const ProxyConfigSchema = z.object({trafficPolicy: z.nativeEnum(AgentVaultTrafficPolicy).describe(AGENT_VAULT.PROXY.trafficPolicy),@@ -185,11 +186,27 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvi},onRequest: verifyAuth([AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN]),handler: async (req) => {- return server.services.agentVaultSessionLog.createChunkUploadUrl({+ const { orgId, storageType, ...upload } = await server.services.agentVaultSessionLog.createChunkUploadUrl({proxyId: req.permission.id,sessionId: req.params.sessionId,chunk: req.body});++ void server.services.telemetry+ .sendPostHogEvents({+ event: PostHogEventTypes.AgentVaultSessionLogChunkAccepted,+ distinctId: `agent-vault-proxy-${req.permission.id}`,+ organizationId: orgId,+ properties: {+ orgId,+ storageType,+ bytes: req.body.ciphertextBytes,+ ...(req.body.recordCount !== undefined && { records: req.body.recordCount })+ }+ })+ .catch(() => {});++ return upload;}});};diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-log-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-log-router.tsindex 6319f6d0b3..179fd2cb8f 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-log-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-log-router.ts@@ -15,6 +15,9 @@ import { AuthMode } from "@app/services/auth/auth-type";import { actorContext } from "./agent-vault-router-fns";+// Reads return no logs while session logs are off, or while the plan doesn't include the storage in use. Unlike most+// paid features, which read from Infisical's database, each read here is a billed S3 request for whoever owns the+// bucket, so reading needs the same plan as recording.export const registerAgentVaultSessionLogRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",@@ -24,7 +27,7 @@ export const registerAgentVaultSessionLogRouter = async (server: FastifyZodProvihide: false,operationId: "listAgentVaultSessionLogs",description:- "Lists a session's logs newest first, as encrypted chunks of [records](/documentation/platform/agent-vault/session-logs#what-gets-recorded). To decrypt them, follow [Reading session logs through the API](/documentation/platform/agent-vault/session-logs#reading-session-logs-through-the-api). To follow new logs as they arrive, use [the endpoint that tails session logs](/api-reference/endpoints/agent-vault-session-logs/tail). If Infisical can't read the bucket, the request fails with the error `AgentVaultSessionLogStorageUnavailable`.",+ "Lists a session's logs newest first, as encrypted chunks of [records](/documentation/platform/agent-vault/session-logs#what-gets-recorded). To decrypt them, follow [Reading session logs through the API](/documentation/platform/agent-vault/session-logs#reading-session-logs-through-the-api). To follow new logs as they arrive, use [the endpoint that tails session logs](/api-reference/endpoints/agent-vault-session-logs/tail). If Infisical can't read session logs, the request fails with the error `AgentVaultSessionLogStorageUnavailable`.",tags: [ApiDocsTags.AgentVaultSessionLogs],params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),querystring: AgentVaultSessionLogHistoryQuerySchema,@@ -52,7 +55,7 @@ export const registerAgentVaultSessionLogRouter = async (server: FastifyZodProvihide: false,operationId: "tailAgentVaultSessionLogs",description:- "Lists chunks added since your last call. Call it every few seconds with the previous `nextCursor`. Any call can return a chunk you already have, so skip any whose `chunkId` and `proxyId` you've read. The chunks decrypt the same way as the ones from [the endpoint that lists session logs](/api-reference/endpoints/agent-vault-session-logs/list). If the AWS connection for session logs can't be used, the request fails with the error `AgentVaultSessionLogStorageUnavailable`.",+ "Lists chunks added since your last call. Call it every few seconds with the previous `nextCursor`. Any call can return a chunk you already have, so skip any whose `chunkId` and `proxyId` you've read. The chunks decrypt the same way as the ones from [the endpoint that lists session logs](/api-reference/endpoints/agent-vault-session-logs/list). If Infisical can't read session logs, the request fails with the error `AgentVaultSessionLogStorageUnavailable`.",tags: [ApiDocsTags.AgentVaultSessionLogs],params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),querystring: AgentVaultSessionLogTailQuerySchema,diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-settings-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-settings-router.tsindex 40b27eeb7c..198ffcfe49 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-settings-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-settings-router.ts@@ -4,6 +4,7 @@ import {AgentVaultSessionLogSettingsResponseSchema,AgentVaultSessionLogSettingsUpdateSchema} from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-schemas";+import { buildSessionLogSettingsAuditMetadata } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { ApiDocsTags } from "@app/lib/api-docs/constants";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";@@ -49,39 +50,35 @@ export const registerAgentVaultSettingsRouter = async (server: FastifyZodProvide},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const { settings, appConnectionName } = await server.services.agentVaultSessionLog.updateSessionLogSettings({- projectId: req.internalAgentVaultProjectId,- ctx: actorContext(req),- actor: {- type: req.permission.type,- id: req.permission.id,- authMethod: req.permission.authMethod,- orgId: req.permission.orgId,- rootOrgId: req.permission.rootOrgId,- parentOrgId: req.permission.parentOrgId- },- ...req.body- });+ const { settings, defaultStorage, appConnectionName, previous } =+ await server.services.agentVaultSessionLog.updateSessionLogSettings({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ actor: {+ type: req.permission.type,+ id: req.permission.id,+ authMethod: req.permission.authMethod,+ orgId: req.permission.orgId,+ rootOrgId: req.permission.rootOrgId,+ parentOrgId: req.permission.parentOrgId+ },+ ...req.body+ });+ const metadata = buildSessionLogSettingsAuditMetadata({ settings, appConnectionName, previous });await server.services.auditLog.createAuditLog({...req.auditLogInfo,orgId: req.permission.orgId,projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE,- metadata: { ...settings, appConnectionName }- }+ event: { type: EventType.AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE, metadata }});emitAgentVaultTelemetry(server.services.telemetry, req, {event: PostHogEventTypes.AgentVaultSessionLogSettingsUpdated,- properties: {- enabled: settings.enabled,- hasDestination: Boolean(settings.bucket)- }+ properties: { enabled: metadata.enabled, storageType: metadata.storageType }});- return { settings };+ return { settings, defaultStorage };}});diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.tsindex 0eca1f7bce..e2cbdbcc07 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts@@ -33,10 +33,10 @@ import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fnsimport { TAgentVaultSessionLogConfigDALFactory } from "../agent-vault-session-log/agent-vault-session-log-config-dal";import {getSessionLogEntitlement,- isSessionLogIngestEnabled,TSessionLogLicenseService-} from "../agent-vault-session-log/agent-vault-session-log-fns";+} from "../agent-vault-session-log/agent-vault-session-log-license-fns";import { openSessionLogKey } from "../agent-vault-session-log/agent-vault-session-log-secrets";+import { getEffectiveSessionLogConfig } from "../agent-vault-session-log/agent-vault-session-log-storage-fns";import { TAgentVaultVariableDALFactory } from "../agent-vault-variable/agent-vault-variable-dal";import {mintAgentVaultProxyJwt,@@ -72,7 +72,7 @@ type TAgentVaultProxyServiceFactoryDep = {agentVaultServiceSubstitutionDAL: Pick<TAgentVaultServiceSubstitutionDALFactory, "findByServiceIds">;agentVaultVariableDAL: Pick<TAgentVaultVariableDALFactory, "findValuesForResolve">;agentVaultSessionDAL: Pick<TAgentVaultSessionDALFactory, "findByTokenHash">;- agentVaultSessionLogConfigDAL: Pick<TAgentVaultSessionLogConfigDALFactory, "findOne">;+ agentVaultSessionLogConfigDAL: Pick<TAgentVaultSessionLogConfigDALFactory, "findOne" | "findByProjectIdFromPrimary">;membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;@@ -600,10 +600,12 @@ export const agentVaultProxyServiceFactory = ({agentVaultServiceSubstitutionDAL.findByServiceIds(serviceIds)]);- const sessionLogConfig = await agentVaultSessionLogConfigDAL.findOne({ projectId: session.projectId });+ const sessionLogConfig = await getEffectiveSessionLogConfig({ agentVaultSessionLogConfigDAL }, session.projectId, {+ fromPrimary: false+ });const entitlement =- isSessionLogIngestEnabled(sessionLogConfig) && Boolean(session.encryptedSessionLogKey)- ? await getSessionLogEntitlement(licenseService, proxy.orgId)+ sessionLogConfig?.enabled && Boolean(session.encryptedSessionLogKey)+ ? (await getSessionLogEntitlement(licenseService, proxy.orgId, sessionLogConfig.storage.type)).entitlement: "unlicensed";// While the plan can't be confirmed, a proxy that already holds the key keeps recording, and no key goes out.const sessionLogsEnabled = entitlement === "licensed" || (entitlement === "unknown" && hasSessionLogKey);diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-constants.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-constants.tsindex 5395bc4bec..6ea2c11c4b 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-constants.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-constants.ts@@ -4,6 +4,8 @@ import RE2 from "re2";// than 8 MiB, or smaller than an empty one: 30 bytes, a 12-byte IV, 2 bytes of content and a 16-byte tag.export const AGENT_VAULT_SESSION_LOG_MIN_CHUNK_BYTES = 30; // the 12-byte IV, an empty "[]" and the 16-byte AES-GCM tagexport const AGENT_VAULT_SESSION_LOG_MAX_CHUNK_BYTES = 8 * 1024 * 1024; // 8 MiB+// Proxies seal at most 1,000 records per chunk; the bound only rejects nonsense, the count is never trusted for limits.+export const AGENT_VAULT_SESSION_LOG_MAX_CHUNK_RECORDS = 10_000;// Lowercase because the browser rebuilds the AAD from the id in the object name. v7 because the name orders chunks// by the time in the id.@@ -54,8 +56,20 @@ export const AGENT_VAULT_SESSION_LOG_FEED_TTL_SECONDS = 120; // 2 minutes// mention the AWS account, bucket and connection.export const AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE_MESSAGE ="Session logs can't be read right now. Try again in a bit, or ask an Agent Vault admin if it keeps happening.";+// Default storage belongs to whoever runs Infisical, so no org admin can fix it: Infisical on cloud, the server+// administrator when self-hosted.+export const AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_UNAVAILABLE_MESSAGE =+ "Session logs can't be read right now. Try again in a bit, or contact Infisical support if it keeps happening.";+export const AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_UNAVAILABLE_SELF_HOSTED_MESSAGE =+ "Session logs can't be read right now. Try again in a bit, or contact your server administrator if it keeps happening.";export const AGENT_VAULT_SESSION_LOG_STORAGE_NEEDS_ADMIN_MESSAGE ="Session logs can't be read. Ask an Agent Vault admin to check the session log settings.";-export const AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN =- "Session logs are not available on your current plan. Please upgrade to continue.";+export const AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_NOT_ON_PLAN =+ "Default storage for session logs isn't on your current plan. Upgrade your plan to use it.";+export const AGENT_VAULT_SESSION_LOG_EXTERNAL_STORAGE_NOT_ON_PLAN =+ "External storage for session logs isn't on your current plan. Upgrade your plan to use it.";++// How long default storage keeps session logs when the plan's retention is null. The instance's lifecycle rule for+// each retention tag is what deletes them.+export const AGENT_VAULT_SESSION_LOG_DEFAULT_RETENTION_DAYS = 30;diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-cursor-fns.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-cursor-fns.tsnew file mode 100644index 0000000000..dd81253eb8--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-cursor-fns.ts@@ -0,0 +1,78 @@+import RE2 from "re2";+import { z } from "zod";++const CURSOR_VERSION = 2;+// Large enough for any S3 key, which can be up to 1,024 bytes, after JSON and base64.+const MAX_CURSOR_LENGTH = 8192;++export const SESSION_LOG_FEED_START = "0-0";++const HistoryCursorPayloadSchema = z.object({+ v: z.literal(CURSOR_VERSION),+ m: z.literal("h"),+ after: z.string().min(1).max(1024)+});++const TailCursorPayloadSchema = z.object({+ v: z.literal(CURSOR_VERSION),+ m: z.literal("t"),+ id: z.string().regex(new RE2(/^\d{1,16}-\d{1,16}$/))+});++const encode = (payload: object) => Buffer.from(JSON.stringify(payload)).toString("base64url");++const decode = (cursor: string): unknown => {+ try {+ return JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));+ } catch {+ return undefined;+ }+};++// The name relative to the session folder, so a cursor can't point a list outside it.+export const encodeHistoryCursor = (after: string) => encode({ v: CURSOR_VERSION, m: "h", after });++export const encodeTailCursor = (feedEntryId: string) => encode({ v: CURSOR_VERSION, m: "t", id: feedEntryId });++const modeOf = (payload: unknown) =>+ payload && typeof payload === "object" && "m" in payload ? (payload as { m: unknown }).m : undefined;++export const HistoryCursorSchema = z+ .string()+ .trim()+ .max(MAX_CURSOR_LENGTH)+ .transform((cursor, ctx) => {+ const payload = decode(cursor);+ const parsed = HistoryCursorPayloadSchema.safeParse(payload);+ if (!parsed.success) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ modeOf(payload) === "t"+ ? "This cursor is for reading new logs as they arrive. Pass it to the session logs tail endpoint instead"+ : "Invalid cursor. Pass the nextCursor of a previous response unchanged"+ });+ return z.NEVER;+ }+ return parsed.data.after;+ });++export const TailCursorSchema = z+ .string()+ .trim()+ .max(MAX_CURSOR_LENGTH)+ .transform((cursor, ctx) => {+ const payload = decode(cursor);+ const parsed = TailCursorPayloadSchema.safeParse(payload);+ if (!parsed.success) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ modeOf(payload) === "h"+ ? "This cursor is for paging back through logs. Pass it to the session logs endpoint instead"+ : "Invalid cursor. Pass the nextCursor of a previous response unchanged"+ });+ return z.NEVER;+ }+ return parsed.data.id;+ });diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-fns.test.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-fns.test.tsindex d98beaabf1..18afd07067 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-fns.test.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-fns.test.ts@@ -1,37 +1,21 @@-import { S3ServiceException } from "@aws-sdk/client-s3";-import { describe, expect, test, vi } from "vitest";--import { AWSRegion } from "@app/services/app-connection/app-connection-enums";+import { describe, expect, test } from "vitest";import {- buildSessionLogFolder,- buildSessionLogObjectKey,+ buildSessionLogObjectName,chunkIdTimeMs,- describeListFailure,- getSessionLogEntitlement,parseSessionLogObjectKey,- resolveStorageConfig,- toRev,- TSessionLogLicenseService+ toRev} from "./agent-vault-session-log-fns";-vi.mock("@app/lib/logger", () => ({ logger: { warn: () => {} } }));-describe("session log object names", () => {- const projectId = "c4a1e0d2-5b7f-4c1e-9a3d-2f6b8e0c7a11";+ const orgId = "c4a1e0d2-5b7f-4c1e-9a3d-2f6b8e0c7a11";const sessionId = "5d2e9b41-0c3a-4f8e-b7d2-91a4c6e8f035";const proxyId = "e91f3c20-7d4b-4a8e-9f1c-3b5d7e2a6c48";const chunkId = "01a11226-9990-7a3f-8c21-4e6f9b2d1a07";- const folder = buildSessionLogFolder({ keyPrefix: "agent-vault-1", projectId, sessionId });-- test("lays out prefix, project, session, then rev, chunk and proxy", () => {- expect(buildSessionLogObjectKey({ folder, proxyId, chunkId })).toBe(- `agent-vault-1/${projectId}/${sessionId}/8208694117999_${chunkId}.${proxyId}.json.enc`- );- });+ const folder = `agent-vault-1/orgs/${orgId}/agent-vault/sessions/${sessionId}/logs/`;- test("omits the prefix segment entirely when there is no prefix", () => {- expect(buildSessionLogFolder({ keyPrefix: null, projectId, sessionId })).toBe(`${projectId}/${sessionId}/`);+ test("names a chunk by rev, chunk and proxy", () => {+ expect(buildSessionLogObjectName({ proxyId, chunkId })).toBe(`8208694117999_${chunkId}.${proxyId}.json.enc`);});test("reads the time out of the chunk id", () => {@@ -49,7 +33,7 @@ describe("session log object names", () => {});test("parses a name it built", () => {- expect(parseSessionLogObjectKey(folder, buildSessionLogObjectKey({ folder, proxyId, chunkId }))).toEqual({+ expect(parseSessionLogObjectKey(folder, `${folder}${buildSessionLogObjectName({ proxyId, chunkId })}`)).toEqual({chunkId,proxyId,lastRecordAt: new Date(1791305882000)@@ -59,7 +43,7 @@ describe("session log object names", () => {test.each([{why: "another session's folder",- key: `agent-vault-1/${projectId}/other/8208694117999_${chunkId}.${proxyId}.json.enc`+ key: `agent-vault-1/orgs/${orgId}/agent-vault/sessions/other/logs/8208694117999_${chunkId}.${proxyId}.json.enc`},{ why: "a nested folder", key: `${folder}${proxyId}/2026-09-16/${chunkId}.json.enc` },{ why: "a rev that disagrees with the chunk id", key: `${folder}8208694117998_${chunkId}.${proxyId}.json.enc` },@@ -69,131 +53,3 @@ describe("session log object names", () => {expect(parseSessionLogObjectKey(folder, key)).toBeNull();});});--describe("resolveStorageConfig", () => {- const complete = {- appConnectionId: "conn-1",- bucket: "my-bucket",- region: AWSRegion.US_EAST_1 as string,- keyPrefix: "logs"- };-- test("returns the coordinates when every required field is set", () => {- expect(resolveStorageConfig(complete)).toEqual({- appConnectionId: "conn-1",- bucket: "my-bucket",- region: AWSRegion.US_EAST_1,- keyPrefix: "logs"- });- });-- test("treats a missing keyPrefix as null rather than incomplete", () => {- expect(resolveStorageConfig({ ...complete, keyPrefix: null })?.keyPrefix).toBeNull();- });-- test.each(["appConnectionId", "bucket", "region"] as const)("is null when %s is missing", (field) => {- expect(resolveStorageConfig({ ...complete, [field]: null })).toBeNull();- });-});--describe("getSessionLogEntitlement", () => {- const licenseService = ({- paid,- fallback = false,- lastKnown = null- }: {- paid: boolean;- fallback?: boolean;- lastKnown?: { paid: boolean; ageMs: number } | null;- }) =>- ({- getPlan: async () => ({ agentVaultByoS3: paid }),- isServingFallbackPlan: async () => fallback,- getLastKnownPlan: async () =>- lastKnown ? { plan: { agentVaultByoS3: lastKnown.paid }, fetchedAt: Date.now() - lastKnown.ageMs } : null- }) as unknown as TSessionLogLicenseService;-- test.each([- { why: "a paid plan", service: { paid: true }, expected: "licensed" },- { why: "a real free plan", service: { paid: false }, expected: "unlicensed" },- {- why: "a fallback with a recent paid answer",- service: { paid: false, fallback: true, lastKnown: { paid: true, ageMs: 10 * 60_000 } },- expected: "licensed"- },- {- why: "a fallback with a recent free answer",- service: { paid: false, fallback: true, lastKnown: { paid: false, ageMs: 10 * 60_000 } },- expected: "unlicensed"- },- {- why: "a fallback whose last answer is over an hour old",- service: { paid: false, fallback: true, lastKnown: { paid: true, ageMs: 61 * 60_000 } },- expected: "unknown"- },- { why: "a fallback with no real answer on record", service: { paid: false, fallback: true }, expected: "unknown" }- ])("reads $why as $expected", async ({ service, expected }) => {- expect(await getSessionLogEntitlement(licenseService(service), "org-1")).toBe(expected);- });-});--describe("describeListFailure", () => {- const s3Error = (name: string, fault: "client" | "server" = "client") =>- new S3ServiceException({ name, $fault: fault, $metadata: {}, message: name });- const networkError = (code: string) => Object.assign(new Error(`connect ${code}`), { code });-- test.each([- { error: s3Error("InvalidAccessKeyId"), isTemporary: false, hint: "Check the AWS connection's credentials." },- { error: s3Error("ExpiredToken"), isTemporary: false, hint: "Check the AWS connection's credentials." },- {- error: s3Error("AccessDenied"),- isTemporary: false,- hint: "Check that the connection's credentials allow s3:ListBucket on it."- },- { error: s3Error("NoSuchBucket"), isTemporary: false, hint: "Check the bucket name and region in Settings." },- { error: s3Error("PermanentRedirect"), isTemporary: false, hint: "Check the bucket name and region in Settings." },- { error: s3Error("SlowDown"), isTemporary: true, hint: "S3 isn't responding. Try again in a bit." },- { error: s3Error("SomethingNew", "server"), isTemporary: true, hint: "S3 isn't responding. Try again in a bit." },- {- error: Object.assign(new Error("timed out"), { name: "TimeoutError" }),- isTemporary: true,- hint: "S3 isn't responding. Try again in a bit."- },- { error: networkError("ECONNREFUSED"), isTemporary: true, hint: "S3 isn't responding. Try again in a bit." },- {- error: Object.assign(new Error("XML parse error"), { $metadata: { httpStatusCode: 429 } }),- isTemporary: true,- hint: "S3 isn't responding. Try again in a bit."- },- {- error: Object.assign(new Error("XML parse error"), { $metadata: { httpStatusCode: 200 } }),- isTemporary: true,- hint: "S3 isn't responding. Try again in a bit."- },- {- error: Object.assign(new Error("XML parse error"), { $metadata: { httpStatusCode: 403 } }),- isTemporary: false,- hint: "Check the AWS connection and the bucket settings."- },- {- error: Object.assign(new Error("Request aborted"), { name: "AbortError" }),- isTemporary: true,- hint: "S3 isn't responding. Try again in a bit."- },- { error: s3Error("SomethingNew"), isTemporary: false, hint: "Check the AWS connection and the bucket settings." }- ])("$error.name ($error.message) reads as temporary: $isTemporary", ({ error, isTemporary, hint }) => {- const failure = describeListFailure(error, "my-bucket");- expect(failure.isTemporary).toBe(isTemporary);- expect(failure.message.startsWith("Infisical couldn't list session logs in bucket 'my-bucket' (")).toBe(true);- expect(failure.message.endsWith(hint)).toBe(true);- });-- test("a reply S3's client couldn't parse is labelled by its status", () => {- const error = Object.assign(new Error("XML parse error"), { $metadata: { httpStatusCode: 429 } });- expect(describeListFailure(error, "my-bucket").message).toContain("(HTTP 429)");- });-- test("a network error is labelled by its code, not its generic name", () => {- expect(describeListFailure(networkError("ENOTFOUND"), "my-bucket").message).toContain("(ENOTFOUND)");- });-});diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-fns.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-fns.tsindex a37e38953e..cb6670918a 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-fns.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-fns.ts@@ -1,19 +1,15 @@import RE2 from "re2";-import { z } from "zod";-import { TAgentVaultSessionLogConfigs } from "@app/db/schemas";-import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";-import { logger } from "@app/lib/logger";-import { AWSRegion } from "@app/services/app-connection/app-connection-enums";+import { ProjectType } from "@app/db/schemas";+import { defineStorageNamespace } from "@app/services/object-storage/object-storage-namespace-fns";-import {- AGENT_VAULT_SESSION_LOG_CHUNK_ID_PATTERN,- AGENT_VAULT_SESSION_LOG_LAST_KNOWN_PLAN_MAX_AGE_MS-} from "./agent-vault-session-log-constants";-import { TResolvedSessionLogStorageConfig } from "./agent-vault-session-log-types";+import { AGENT_VAULT_SESSION_LOG_CHUNK_ID_PATTERN } from "./agent-vault-session-log-constants";-export const withKeyPrefix = (keyPrefix: string | null | undefined, key: string) =>- keyPrefix ? `${keyPrefix}/${key}` : key;+export const AgentVaultSessionLogsNamespace = defineStorageNamespace({+ id: "agent-vault.session-logs",+ product: ProjectType.AgentVault,+ path: "sessions/{sessionId}/logs/{file}"+});const MAX_REV = 9_999_999_999_999;@@ -22,25 +18,8 @@ export const chunkIdTimeMs = (chunkId: string) => parseInt(chunkId.slice(0, 8) +// S3 lists names in ascending order only, so names start with the time counted down: newest first.export const toRev = (ms: number) => String(MAX_REV - Math.min(Math.max(Math.floor(ms), 0), MAX_REV)).padStart(13, "0");-export const buildSessionLogFolder = ({- keyPrefix,- projectId,- sessionId-}: {- keyPrefix?: string | null;- projectId: string;- sessionId: string;-}) => withKeyPrefix(keyPrefix, `${projectId}/${sessionId}/`);--export const buildSessionLogObjectKey = ({- folder,- proxyId,- chunkId-}: {- folder: string;- proxyId: string;- chunkId: string;-}) => `${folder}${toRev(chunkIdTimeMs(chunkId))}_${chunkId}.${proxyId}.json.enc`;+export const buildSessionLogObjectName = ({ proxyId, chunkId }: { proxyId: string; chunkId: string }) =>+ `${toRev(chunkIdTimeMs(chunkId))}_${chunkId}.${proxyId}.json.enc`;const UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";const SESSION_LOG_OBJECT_NAME_REGEX = new RE2(@@ -57,187 +36,3 @@ export const parseSessionLogObjectKey = (folder: string, key: string) => {if (rev !== toRev(lastRecordAtMs)) return null;return { chunkId, proxyId, lastRecordAt: new Date(lastRecordAtMs) };};--export const resolveStorageConfig = (- config: Pick<TAgentVaultSessionLogConfigs, "appConnectionId" | "bucket" | "region" | "keyPrefix"> | undefined-): TResolvedSessionLogStorageConfig | null => {- if (!config?.appConnectionId || !config.bucket || !config.region) return null;- return {- appConnectionId: config.appConnectionId,- bucket: config.bucket,- region: config.region as AWSRegion,- keyPrefix: config.keyPrefix ?? null- };-};--const TEMPORARY_AWS_ERRORS = new Set([- "SlowDown",- "InternalError",- "ServiceUnavailable",- "RequestTimeout",- "Throttling",- "ThrottlingException",- "TooManyRequestsException",- "RequestLimitExceeded",- "TimeoutError",- "AbortError"-]);-const NETWORK_ERROR_CODES = new Set(["ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN", "EPIPE"]);-const CREDENTIAL_ERRORS = new Set(["InvalidAccessKeyId", "SignatureDoesNotMatch", "ExpiredToken", "InvalidToken"]);-const ACCESS_ERRORS = new Set(["AccessDenied", "AllAccessDisabled"]);-const LOCATION_ERRORS = new Set([- "NoSuchBucket",- "PermanentRedirect",- "AuthorizationHeaderMalformed",- "IllegalLocationConstraintException"-]);--type TAwsError = Error & { $fault?: string; $metadata?: { httpStatusCode?: number }; code?: string };--// Whether an AWS call failed because AWS or the network didn't answer, so that trying again later can help.-export const isTemporaryAwsError = (error: unknown) => {- if (!(error instanceof Error)) return false;- const { $fault, $metadata, code } = error as TAwsError;- const status = $metadata?.httpStatusCode ?? 0;- // A reply the client couldn't parse that isn't a 4xx came from something in the network path, not the settings.- const isUnparsedReply = error.name === "Error" && $metadata?.httpStatusCode !== undefined && status < 400;- return (- $fault === "server" ||- status >= 500 ||- status === 429 ||- isUnparsedReply ||- TEMPORARY_AWS_ERRORS.has(error.name) ||- NETWORK_ERROR_CODES.has(code ?? "")- );-};--// Names the cause of a failed bucket listing for an admin, and whether trying again later can help.-export const describeListFailure = (error: Error, bucket: string) => {- const { $metadata, code } = error as TAwsError;- let label = error.name;- // A reply S3's client can't parse, such as plain text from a proxy in between, is a bare Error.- if (error.name === "Error") label = code ?? ($metadata?.httpStatusCode ? `HTTP ${$metadata.httpStatusCode}` : label);- const isTemporary = isTemporaryAwsError(error);-- let hint = "Check the AWS connection and the bucket settings.";- if (isTemporary) hint = "S3 isn't responding. Try again in a bit.";- else if (CREDENTIAL_ERRORS.has(error.name)) hint = "Check the AWS connection's credentials.";- else if (ACCESS_ERRORS.has(error.name)) hint = "Check that the connection's credentials allow s3:ListBucket on it.";- else if (LOCATION_ERRORS.has(error.name)) hint = "Check the bucket name and region in Settings.";-- return { isTemporary, message: `Infisical couldn't list session logs in bucket '${bucket}' (${label}). ${hint}` };-};--export const isSessionLogIngestEnabled = (config?: TAgentVaultSessionLogConfigs) =>- Boolean(config?.enabled && resolveStorageConfig(config));--export type TSessionLogEntitlement = "licensed" | "unlicensed" | "unknown";--export type TSessionLogLicenseService = Pick<- TLicenseServiceFactory,- "getPlan" | "isServingFallbackPlan" | "getLastKnownPlan"->;--const FALLBACK_LOG_INTERVAL_MS = 5 * 60_000;-const fallbackLoggedAt = new Map<string, number>();--// getPlan answers with the free plan while the License Server is down, which would otherwise read as a downgrade-// and stop recording. "unknown" is a fallback with no recent real answer to go on.-export const getSessionLogEntitlement = async (- licenseService: TSessionLogLicenseService,- orgId: string-): Promise<TSessionLogEntitlement> => {- if ((await licenseService.getPlan(orgId)).agentVaultByoS3) return "licensed";- if (!(await licenseService.isServingFallbackPlan(orgId))) return "unlicensed";-- const lastKnown = await licenseService.getLastKnownPlan(orgId);- let entitlement: TSessionLogEntitlement = "unknown";- if (lastKnown && Date.now() - lastKnown.fetchedAt <= AGENT_VAULT_SESSION_LOG_LAST_KNOWN_PLAN_MAX_AGE_MS) {- entitlement = lastKnown.plan.agentVaultByoS3 ? "licensed" : "unlicensed";- }-- const now = Date.now();- if (now - (fallbackLoggedAt.get(orgId) ?? 0) >= FALLBACK_LOG_INTERVAL_MS) {- fallbackLoggedAt.set(orgId, now);- logger.warn(- `agentVaultSessionLog: the plan is a License Server fallback, deciding session logs from the last known plan [orgId=${orgId}] [entitlement=${entitlement}] [lastKnownAgeMs=${lastKnown ? now - lastKnown.fetchedAt : "none"}]`- );- }- return entitlement;-};--const CURSOR_VERSION = 2;-// Large enough for any S3 key, which can be up to 1,024 bytes, after JSON and base64.-const MAX_CURSOR_LENGTH = 8192;--export const SESSION_LOG_FEED_START = "0-0";--const HistoryCursorPayloadSchema = z.object({- v: z.literal(CURSOR_VERSION),- m: z.literal("h"),- after: z.string().min(1).max(1024)-});--const TailCursorPayloadSchema = z.object({- v: z.literal(CURSOR_VERSION),- m: z.literal("t"),- id: z.string().regex(new RE2(/^\d{1,16}-\d{1,16}$/))-});--const encode = (payload: object) => Buffer.from(JSON.stringify(payload)).toString("base64url");--const decode = (cursor: string): unknown => {- try {- return JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));- } catch {- return undefined;- }-};--// The name relative to the session folder, so a cursor can't point a list outside it.-export const encodeHistoryCursor = (after: string) => encode({ v: CURSOR_VERSION, m: "h", after });--export const encodeTailCursor = (feedEntryId: string) => encode({ v: CURSOR_VERSION, m: "t", id: feedEntryId });--const modeOf = (payload: unknown) =>- payload && typeof payload === "object" && "m" in payload ? (payload as { m: unknown }).m : undefined;--export const HistoryCursorSchema = z- .string()- .trim()- .max(MAX_CURSOR_LENGTH)- .transform((cursor, ctx) => {- const payload = decode(cursor);- const parsed = HistoryCursorPayloadSchema.safeParse(payload);- if (!parsed.success) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message:- modeOf(payload) === "t"- ? "This cursor is for reading new logs as they arrive. Pass it to the session logs tail endpoint instead"- : "Invalid cursor. Pass the nextCursor of a previous response unchanged"- });- return z.NEVER;- }- return parsed.data.after;- });--export const TailCursorSchema = z- .string()- .trim()- .max(MAX_CURSOR_LENGTH)- .transform((cursor, ctx) => {- const payload = decode(cursor);- const parsed = TailCursorPayloadSchema.safeParse(payload);- if (!parsed.success) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message:- modeOf(payload) === "h"- ? "This cursor is for paging back through logs. Pass it to the session logs endpoint instead"- : "Invalid cursor. Pass the nextCursor of a previous response unchanged"- });- return z.NEVER;- }- return parsed.data.id;- });diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-license-fns.test.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-license-fns.test.tsnew file mode 100644index 0000000000..fdf5e07249--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-license-fns.test.ts@@ -0,0 +1,107 @@+import { describe, expect, test, vi } from "vitest";++import { ObjectStorageType } from "@app/services/object-storage/object-storage-types";++import {+ getSessionLogEntitlement,+ getSessionLogRetentionDays,+ TSessionLogLicenseService+} from "./agent-vault-session-log-license-fns";++vi.mock("@app/lib/logger", () => ({ logger: { warn: () => {} } }));++describe("getSessionLogEntitlement", () => {+ type TPlan = { hasExternal: boolean; hasDefault: boolean; retentionDays?: number | null };+ const toPlan = ({ hasExternal, hasDefault, retentionDays = null }: TPlan) => ({+ agentVaultByoS3: hasExternal,+ agentVaultManagedStorage: hasDefault,+ agentVaultSessionLogRetentionDays: retentionDays+ });+ const licenseService = ({+ plan,+ fallback = false,+ lastKnown = null+ }: {+ plan: TPlan;+ fallback?: boolean;+ lastKnown?: { plan: TPlan; ageMs: number } | null;+ }) =>+ ({+ getPlan: async () => toPlan(plan),+ isServingFallbackPlan: async () => fallback,+ getLastKnownPlan: async () =>+ lastKnown ? { plan: toPlan(lastKnown.plan), fetchedAt: Date.now() - lastKnown.ageMs } : null+ }) as unknown as TSessionLogLicenseService;++ const free = { hasExternal: false, hasDefault: true };+ const paid = { hasExternal: true, hasDefault: true, retentionDays: 365 };+ const none = { hasExternal: false, hasDefault: false };++ test.each([+ { why: "a paid plan", service: { plan: paid }, expected: "licensed" },+ { why: "a real free plan", service: { plan: free }, expected: "unlicensed" },+ {+ why: "a fallback with a recent paid answer",+ service: { plan: free, fallback: true, lastKnown: { plan: paid, ageMs: 10 * 60_000 } },+ expected: "licensed"+ },+ {+ why: "a fallback with a recent free answer",+ service: { plan: free, fallback: true, lastKnown: { plan: free, ageMs: 10 * 60_000 } },+ expected: "unlicensed"+ },+ {+ why: "a fallback whose last answer is over an hour old",+ service: { plan: free, fallback: true, lastKnown: { plan: paid, ageMs: 61 * 60_000 } },+ expected: "unknown"+ },+ { why: "a fallback with no real answer on record", service: { plan: free, fallback: true }, expected: "unknown" }+ ])("external storage: reads $why as $expected", async ({ service, expected }) => {+ expect(+ (await getSessionLogEntitlement(licenseService(service), "org-1", ObjectStorageType.External)).entitlement+ ).toBe(expected);+ });++ test.each([+ { why: "a plan with default storage", service: { plan: free }, expected: "licensed" },+ { why: "a plan without it", service: { plan: none }, expected: "unlicensed" },+ {+ why: "a fallback whose recent real answer leaves it out",+ service: { plan: free, fallback: true, lastKnown: { plan: none, ageMs: 10 * 60_000 } },+ expected: "unlicensed"+ },+ {+ why: "a fallback with no real answer, which includes it",+ service: { plan: free, fallback: true },+ expected: "licensed"+ }+ ])("default storage: reads $why as $expected", async ({ service, expected }) => {+ expect(+ (await getSessionLogEntitlement(licenseService(service), "org-1", ObjectStorageType.Default)).entitlement+ ).toBe(expected);+ });++ test("during an outage, uploads keep the retention of the last real plan", async () => {+ const { plan } = await getSessionLogEntitlement(+ licenseService({ plan: free, fallback: true, lastKnown: { plan: paid, ageMs: 10 * 60_000 } }),+ "org-1",+ ObjectStorageType.Default+ );+ expect(getSessionLogRetentionDays(plan)).toBe(365);+ });++ test("after the first hour of an outage, retention still comes from the last real plan", async () => {+ const { entitlement, plan } = await getSessionLogEntitlement(+ licenseService({ plan: free, fallback: true, lastKnown: { plan: paid, ageMs: 3 * 60 * 60_000 } }),+ "org-1",+ ObjectStorageType.Default+ );+ expect(entitlement).toBe("licensed");+ expect(getSessionLogRetentionDays(plan)).toBe(365);+ });++ test("retention is 30 days when the plan doesn't say", () => {+ expect(getSessionLogRetentionDays({ agentVaultSessionLogRetentionDays: null })).toBe(30);+ expect(getSessionLogRetentionDays(null)).toBe(30);+ });+});diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-license-fns.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-license-fns.tsnew file mode 100644index 0000000000..809bee5ad0--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-license-fns.ts@@ -0,0 +1,80 @@+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";+import { TFeatureSet } from "@app/ee/services/license/license-types";+import { logger } from "@app/lib/logger";+import { ObjectStorageType } from "@app/services/object-storage/object-storage-types";++import {+ AGENT_VAULT_SESSION_LOG_DEFAULT_RETENTION_DAYS,+ AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_NOT_ON_PLAN,+ AGENT_VAULT_SESSION_LOG_EXTERNAL_STORAGE_NOT_ON_PLAN,+ AGENT_VAULT_SESSION_LOG_LAST_KNOWN_PLAN_MAX_AGE_MS+} from "./agent-vault-session-log-constants";++export const getSessionLogNotOnPlanMessage = (storageType: ObjectStorageType) =>+ storageType === ObjectStorageType.Default+ ? AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_NOT_ON_PLAN+ : AGENT_VAULT_SESSION_LOG_EXTERNAL_STORAGE_NOT_ON_PLAN;++export type TSessionLogEntitlement = "licensed" | "unlicensed" | "unknown";++export type TSessionLogLicenseService = Pick<+ TLicenseServiceFactory,+ "getPlan" | "isServingFallbackPlan" | "getLastKnownPlan"+>;++const hasStorageOnPlan = (+ plan: Pick<TFeatureSet, "agentVaultManagedStorage" | "agentVaultByoS3">,+ type: ObjectStorageType+) => Boolean(type === ObjectStorageType.Default ? plan.agentVaultManagedStorage : plan.agentVaultByoS3);++const FALLBACK_LOG_INTERVAL_MS = 5 * 60_000;+const fallbackLoggedAt = new Map<string, number>();++// Whether the org's plan includes this storage type, and the plan to take retention from. While the License Server+// can't be reached, getPlan returns a stand-in plan that leaves out external storage and includes default storage.+// Trusting it would stop recording for orgs that pay for external storage, and for default storage it would hide a+// downgrade and tag uploads with the stand-in plan's retention. So in that case the last plan the License Server+// returned decides, if it's under an hour old. Without one the answer is "unknown", and each caller decides what that+// means.+export const getSessionLogEntitlement = async (+ licenseService: TSessionLogLicenseService,+ orgId: string,+ storageType: ObjectStorageType+): Promise<{+ entitlement: TSessionLogEntitlement;+ plan: Pick<TFeatureSet, "agentVaultSessionLogRetentionDays"> | null;+}> => {+ const plan = await licenseService.getPlan(orgId);+ const isOnPlan = hasStorageOnPlan(plan, storageType);+ if (isOnPlan && storageType !== ObjectStorageType.Default) return { entitlement: "licensed", plan };+ if (!(await licenseService.isServingFallbackPlan(orgId))) {+ return { entitlement: isOnPlan ? "licensed" : "unlicensed", plan };+ }++ const lastKnown = await licenseService.getLastKnownPlan(orgId);+ // Retention comes from the last real plan whenever one is cached, even one too old to decide yes or no. The tag is+ // fixed at upload, so tagging with the stand-in plan's retention would delete a longer plan's logs early.+ let decision: Awaited<ReturnType<typeof getSessionLogEntitlement>> = isOnPlan+ ? { entitlement: "licensed", plan: lastKnown?.plan ?? plan }+ : { entitlement: "unknown", plan: lastKnown?.plan ?? null };+ if (lastKnown && Date.now() - lastKnown.fetchedAt <= AGENT_VAULT_SESSION_LOG_LAST_KNOWN_PLAN_MAX_AGE_MS) {+ decision = {+ entitlement: hasStorageOnPlan(lastKnown.plan, storageType) ? "licensed" : "unlicensed",+ plan: lastKnown.plan+ };+ }++ const now = Date.now();+ if (now - (fallbackLoggedAt.get(orgId) ?? 0) >= FALLBACK_LOG_INTERVAL_MS) {+ fallbackLoggedAt.set(orgId, now);+ logger.warn(+ `agentVaultSessionLog: the License Server is unreachable, so session logs are decided from the last plan it returned [orgId=${orgId}] [storageType=${storageType}] [entitlement=${decision.entitlement}] [lastKnownAgeMs=${lastKnown ? now - lastKnown.fetchedAt : "none"}]`+ );+ }+ return decision;+};++// For other plan limits null means no limit, but here it still means the default number of days, so that a plan+// never keeps logs in default storage forever by accident. Make null mean "keep forever" here if that's ever wanted.+export const getSessionLogRetentionDays = (plan: Pick<TFeatureSet, "agentVaultSessionLogRetentionDays"> | null) =>+ plan?.agentVaultSessionLogRetentionDays ?? AGENT_VAULT_SESSION_LOG_DEFAULT_RETENTION_DAYS;diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-schemas.test.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-schemas.test.tsindex 23ad045d3c..2e1828e395 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-schemas.test.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-schemas.test.ts@@ -4,7 +4,7 @@ import {AGENT_VAULT_SESSION_LOG_MAX_CHUNK_BYTES,AGENT_VAULT_SESSION_LOG_MIN_CHUNK_BYTES} from "./agent-vault-session-log-constants";-import { encodeHistoryCursor, encodeTailCursor } from "./agent-vault-session-log-fns";+import { encodeHistoryCursor, encodeTailCursor } from "./agent-vault-session-log-cursor-fns";import {AgentVaultSessionLogChunkCreateSchema,AgentVaultSessionLogHistoryQuerySchema,@@ -122,12 +122,50 @@ describe("the session logs tail query", () => {});describe("the settings patch", () => {- test("every field is optional, so an empty patch is valid", () => {- expect(AgentVaultSessionLogSettingsUpdateSchema.parse({})).toEqual({});+ const external = {+ type: "external",+ appConnectionId: "6f1c7a52-3f7e-4c8e-9a40-0b2d6c1e9f11",+ bucket: "session-logs-bucket",+ region: "us-east-1"+ };+ const withStorage = (storage: Record<string, unknown>) =>+ AgentVaultSessionLogSettingsUpdateSchema.safeParse({ enabled: true, storage });+ const withExternal = (fields: Record<string, unknown>) => withStorage({ ...external, ...fields });++ test("is either turning off, or turning on with a storage", () => {+ expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ enabled: false }).success).toBe(true);+ expect(withStorage({ type: "default" }).success).toBe(true);+ });++ test.each([+ { body: {}, why: "an empty body" },+ { body: { enabled: true }, why: "turning on without a storage" },+ { body: { storage: { type: "default" } }, why: "a storage without enabled" },+ { body: { enabled: false, storage: { type: "default" } }, why: "turning off with a storage" }+ ])("rejects $why", ({ body }) => {+ expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse(body).success).toBe(false);+ });++ test("accepts each storage shape", () => {+ expect(withStorage({ type: "default" }).success).toBe(true);+ expect(withStorage(external).success).toBe(true);+ expect(withExternal({ keyPrefix: "logs" }).success).toBe(true);+ });++ test.each([+ { storage: { type: "default", bucket: "session-logs-bucket" }, why: "default storage with a bucket" },+ { storage: { ...external, type: "default" }, why: "default storage with every external field" },+ { storage: { type: "external" }, why: "external storage with no bucket" },+ { storage: { ...external, appConnectionId: undefined }, why: "external storage with no connection" },+ { storage: { ...external, appConnectionId: null }, why: "external storage with a null connection" },+ { storage: { type: "instance" }, why: "a storage type that doesn't exist" }+ ])("rejects $why", ({ storage }) => {+ expect(withStorage(storage).success).toBe(false);});- test("accepts null for the connection, which detaches it", () => {- expect(AgentVaultSessionLogSettingsUpdateSchema.parse({ appConnectionId: null }).appConnectionId).toBeNull();+ test("rejects the flat fields of the old body", () => {+ expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ bucket: "session-logs-bucket" }).success).toBe(false);+ expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ appConnectionId: null }).success).toBe(false);});test.each([@@ -144,24 +182,24 @@ describe("the settings patch", () => {{ value: "/", why: "only a slash" },{ value: "logs/\u0000", why: "a control character" },{ value: "team*", why: "an asterisk, which is a wildcard in the suggested IAM policy" },- { value: "a".repeat(513), why: "longer than 512 characters" }+ { value: "a".repeat(257), why: "longer than 256 characters" }])("rejects a key prefix: $why", ({ value }) => {- expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ keyPrefix: value }).success).toBe(false);+ expect(withExternal({ keyPrefix: value }).success).toBe(false);});test.each(["logs", "logs/agent-vault", "a.b-c_d", "", ".hidden/logs", "logs/...", "logs.v2"])("accepts the key prefix %s",(keyPrefix) => {- expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ keyPrefix }).success).toBe(true);+ expect(withExternal({ keyPrefix }).success).toBe(true);});- test("accepts a key prefix of exactly 512 characters", () => {- expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ keyPrefix: "a".repeat(512) }).success).toBe(true);+ test("accepts a key prefix of exactly 256 characters", () => {+ expect(withExternal({ keyPrefix: "a".repeat(256) }).success).toBe(true);});test("rejects a region that is not an AWS region", () => {- expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ region: "moon-base-1" }).success).toBe(false);+ expect(withExternal({ region: "moon-base-1" }).success).toBe(false);});test.each([@@ -172,10 +210,10 @@ describe("the settings patch", () => {{ value: "-bucket", why: "a leading hyphen" },{ value: "bucket.", why: "a trailing dot" }])("rejects a bucket name with $why", ({ value }) => {- expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ bucket: value }).success).toBe(false);+ expect(withExternal({ bucket: value }).success).toBe(false);});test.each(["session-logs-bucket", "a.b-c", "a".repeat(63)])("accepts the bucket name %s", (bucket) => {- expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ bucket }).success).toBe(true);+ expect(withExternal({ bucket }).success).toBe(true);});});diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-schemas.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-schemas.tsindex d1f1fb394f..2bf4a474da 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-schemas.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-schemas.ts@@ -2,16 +2,16 @@ import { z } from "zod";import { AGENT_VAULT } from "@app/lib/api-docs";import { AWSRegion } from "@app/services/app-connection/app-connection-enums";+import { keyPrefixSchema, s3BucketNameSchema } from "@app/services/object-storage/object-storage-path-fns";+import { ObjectStorageType } from "@app/services/object-storage/object-storage-types";import {AGENT_VAULT_SESSION_LOG_CHUNK_ID_REGEX,AGENT_VAULT_SESSION_LOG_MAX_CHUNK_BYTES,+ AGENT_VAULT_SESSION_LOG_MAX_CHUNK_RECORDS,AGENT_VAULT_SESSION_LOG_MIN_CHUNK_BYTES} from "./agent-vault-session-log-constants";-import { HistoryCursorSchema, TailCursorSchema } from "./agent-vault-session-log-fns";--const BUCKET_NAME_RULE =- "Must be 3 to 63 characters: lowercase letters, numbers, dots and hyphens, starting and ending with a letter or number";+import { HistoryCursorSchema, TailCursorSchema } from "./agent-vault-session-log-cursor-fns";const CiphertextSha256Schema = z.string()@@ -31,6 +31,13 @@ export const AgentVaultSessionLogChunkCreateSchema = z.object({.max(AGENT_VAULT_SESSION_LOG_MAX_CHUNK_BYTES).describe(AGENT_VAULT.SESSION_LOGS.ciphertextBytes),ciphertextSha256: CiphertextSha256Schema,+ recordCount: z+ .number()+ .int()+ .min(1)+ .max(AGENT_VAULT_SESSION_LOG_MAX_CHUNK_RECORDS)+ .optional()+ .describe(AGENT_VAULT.SESSION_LOGS.recordCount),iv: z.string().max(64).optional().describe(AGENT_VAULT.SESSION_LOGS.legacyIv)});@@ -57,11 +64,18 @@ export const AgentVaultSessionLogChunkViewSchema = z.object({presignedGetUrl: z.string().describe(AGENT_VAULT.SESSION_LOGS.presignedGetUrl)});+const AgentVaultSessionLogDisabledReasonSchema = z.enum(["off", "not-on-plan"]);+export type TAgentVaultSessionLogDisabledReason = z.infer<typeof AgentVaultSessionLogDisabledReasonSchema>;+const AgentVaultSessionLogSchema = z.object({enabled: z.boolean().describe(AGENT_VAULT.SESSION_LOGS.enabled),isRecordable: z.boolean().describe(AGENT_VAULT.SESSION_LOGS.isRecordable),- sessionKey: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.sessionKey)+ sessionKey: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.sessionKey),+ disabledReason: AgentVaultSessionLogDisabledReasonSchema.nullable().describe(+ AGENT_VAULT.SESSION_LOGS.disabledReason+ ),+ storageType: z.nativeEnum(ObjectStorageType).nullable().describe(AGENT_VAULT.SESSION_LOGS.storageType)}).describe(AGENT_VAULT.SESSION_LOGS.sessionLogs);@@ -77,16 +91,51 @@ export const AgentVaultSessionLogTailResponseSchema = z.object({nextCursor: z.string().describe(AGENT_VAULT.SESSION_LOGS.tailNextCursor)});+const DefaultStorageSchema = z+ .object({ type: z.literal(ObjectStorageType.Default) })+ .strict()+ .describe(JSON.stringify({ title: "Default Storage" }));++const ExternalStorageSchema = z+ .object({+ type: z.literal(ObjectStorageType.External),+ appConnectionId: z.string().uuid().describe(AGENT_VAULT.SESSION_LOGS.appConnectionId),+ bucket: s3BucketNameSchema.describe(AGENT_VAULT.SESSION_LOGS.bucket),+ region: z.nativeEnum(AWSRegion).describe(AGENT_VAULT.SESSION_LOGS.region),+ keyPrefix: keyPrefixSchema(256).optional().describe(AGENT_VAULT.SESSION_LOGS.keyPrefix)+ })+ .strict()+ .describe(JSON.stringify({ title: "External Storage" }));++const AgentVaultSessionLogStorageSchema = z+ .discriminatedUnion("type", [DefaultStorageSchema, ExternalStorageSchema])+ .describe(AGENT_VAULT.SESSION_LOGS.storage);++const AgentVaultSessionLogStorageViewSchema = z+ .discriminatedUnion("type", [+ z.object({ type: z.literal(ObjectStorageType.Default) }).describe(JSON.stringify({ title: "Default Storage" })),+ z+ .object({+ type: z.literal(ObjectStorageType.External),+ appConnectionId: z.string().uuid().describe(AGENT_VAULT.SESSION_LOGS.appConnectionId),+ bucket: z.string().describe(AGENT_VAULT.SESSION_LOGS.bucket),+ region: z.string().describe(AGENT_VAULT.SESSION_LOGS.region),+ keyPrefix: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.keyPrefix)+ })+ .describe(JSON.stringify({ title: "External Storage" }))+ ])+ .describe(AGENT_VAULT.SESSION_LOGS.storage);+export const AgentVaultSessionLogSettingsSchema = z.object({enabled: z.boolean().describe(AGENT_VAULT.SESSION_LOGS.configEnabled),- appConnectionId: z.string().uuid().nullable().describe(AGENT_VAULT.SESSION_LOGS.appConnectionId),- bucket: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.bucket),- region: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.region),- keyPrefix: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.keyPrefix)+ storage: AgentVaultSessionLogStorageViewSchema});export const AgentVaultSessionLogSettingsResponseSchema = z.object({- settings: AgentVaultSessionLogSettingsSchema+ settings: AgentVaultSessionLogSettingsSchema.nullable(),+ defaultStorage: z.object({+ configured: z.boolean().describe(AGENT_VAULT.SESSION_LOGS.defaultStorageConfigured)+ })});export const AgentVaultSessionLogHealthResponseSchema = z.object({@@ -104,30 +153,16 @@ export const AgentVaultSessionLogCorsProbeResponseSchema = z.object({.nullable()});-export const AgentVaultSessionLogSettingsUpdateSchema = z- .object({- enabled: z.boolean().describe(AGENT_VAULT.SESSION_LOGS.configEnabled),- appConnectionId: z.string().uuid().nullable().describe(AGENT_VAULT.SESSION_LOGS.appConnectionId),- bucket: z- .string()- .trim()- .max(63, BUCKET_NAME_RULE)- .regex(/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/, BUCKET_NAME_RULE)- .describe(AGENT_VAULT.SESSION_LOGS.bucket),- region: z.nativeEnum(AWSRegion).describe(AGENT_VAULT.SESSION_LOGS.region),- keyPrefix: z- .string()- .trim()- .max(512, "May be at most 512 characters")- .regex(/^[A-Za-z0-9!\-_.'()/]*$/, "May only contain letters, numbers and ! - _ . ' ( ) /")- .refine(- (v) => v === "" || v.split("/").every(Boolean),- "Must be folder names separated by single slashes, with no slash at the start or end, like 'logs/agent-vault'"- )- .refine(- (v) => !v.split("/").some((folder) => folder === "." || folder === ".."),- "May not use '.' or '..' as a folder name"- )- .describe(AGENT_VAULT.SESSION_LOGS.keyPrefix)- })- .partial();+export const AgentVaultSessionLogSettingsUpdateSchema = z.discriminatedUnion("enabled", [+ z+ .object({ enabled: z.literal(false).describe(AGENT_VAULT.SESSION_LOGS.configEnabled) })+ .strict()+ .describe(JSON.stringify({ title: "Turn Off" })),+ z+ .object({+ enabled: z.literal(true).describe(AGENT_VAULT.SESSION_LOGS.configEnabled),+ storage: AgentVaultSessionLogStorageSchema+ })+ .strict()+ .describe(JSON.stringify({ title: "Turn On" }))+]);diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.test.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.test.tsindex 5ec1b87dcd..2eef7f6663 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.test.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.test.ts@@ -1,5 +1,9 @@+import { createHash } from "node:crypto";+import { describe, expect, test, vi } from "vitest";+import { buildWrappedKeyPayload, openWrappedKey } from "@app/services/kms/kms-fns";+import {generateSessionLogKey,openSessionLogKey,@@ -11,10 +15,9 @@ vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn() } }));// The real KMS wrap is authenticated encryption; passing bytes through leaves only the label check under test.const passThroughKms = {- createCipherPairWithDataKey: async () => ({- encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: Buffer.from(plainText) }),- decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => Buffer.from(cipherTextBlob)- })+ wrapKey: async ({ label, key }: { label: string; key: Buffer }) => buildWrappedKeyPayload(label, key),+ unwrapKey: async ({ label, wrappedKey, keyBytes }: { label: string; wrappedKey: Buffer; keyBytes: number }) =>+ openWrappedKey({ label, payload: wrappedKey, keyBytes })} as never;describe("session log keys", () => {@@ -43,6 +46,15 @@ describe("session log keys", () => {).rejects.toMatchObject({ name: "InternalServerError" });});+ // An Agent Vault session can have no expiry, so a key stored by older code must still open. The layout is built here+ // by hand, so changing the label in the secrets module breaks this test.+ test("a key stored in the original layout, sha256(sessionId|v1) then the key, still opens", () => {+ const sessionId = "6f1c7a52-3f7e-4c8e-9a40-0b2d6c1e9f11";+ const sessionLogKey = generateSessionLogKey();+ const storedBefore = Buffer.concat([createHash("sha256").update(`${sessionId}|v1`).digest(), sessionLogKey]);+ expect(openSessionLogKey({ sessionId, payload: storedBefore }).equals(sessionLogKey)).toBe(true);+ });+test("a stored key without its session label is refused", () => {expect(() => openSessionLogKey({ sessionId: "sess-a", payload: generateSessionLogKey() })).toThrow();});diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.tsindex 6cf1dc1861..7061a24b47 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.ts@@ -1,56 +1,54 @@import { crypto } from "@app/lib/crypto/cryptography";import { InternalServerError } from "@app/lib/errors";import { logger } from "@app/lib/logger";+import { openWrappedKey } from "@app/services/kms/kms-fns";import { TKmsServiceFactory } from "@app/services/kms/kms-service";-import { KmsDataKey } from "@app/services/kms/kms-types";const AGENT_VAULT_SESSION_LOG_KEY_BYTES = 32;-const LABEL_BYTES = 32;--type TKmsDep = Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;--// The KMS wrap takes no context, so the session id travels inside the payload: a key copied onto another-// session's row fails to open there instead of being handed out.-const sessionLabel = (sessionId: string) => crypto.nativeCrypto.createHash("sha256").update(`${sessionId}|v1`).digest();+// The label names the session, so a key copied onto another session's row fails to open there instead of being+// handed out.+const sessionLabel = (sessionId: string) => `${sessionId}|v1`;export const generateSessionLogKey = () => crypto.randomBytes(AGENT_VAULT_SESSION_LOG_KEY_BYTES);export const wrapSessionLogKey = async ({ projectId, sessionId, sessionLogKey }: { projectId: string; sessionId: string; sessionLogKey: Buffer },- kmsService: TKmsDep-) => {- const { encryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId- });- return encryptor({ plainText: Buffer.concat([sessionLabel(sessionId), sessionLogKey]) }).cipherTextBlob;-};+ kmsService: Pick<TKmsServiceFactory, "wrapKey">+) => kmsService.wrapKey({ projectId, label: sessionLabel(sessionId), key: sessionLogKey });-export const openSessionLogKey = ({ sessionId, payload }: { sessionId: string; payload: Buffer }) => {- const belongs =- payload.length === LABEL_BYTES + AGENT_VAULT_SESSION_LOG_KEY_BYTES &&- crypto.nativeCrypto.timingSafeEqual(payload.subarray(0, LABEL_BYTES), sessionLabel(sessionId));- if (!belongs) {+const keyOrThrow = (sessionId: string, key: Buffer | null) => {+ if (!key) {logger.error(`agentVaultSessionLog: stored session log key does not belong to its session [sessionId=${sessionId}]`);throw new InternalServerError({ message: "This session's log key could not be used" });}- return payload.subarray(LABEL_BYTES);+ return key;};+// Opens a key the caller already decrypted with the project's data key. Proxy check-in uses it because it decrypts the+// service credentials with that same key.+export const openSessionLogKey = ({ sessionId, payload }: { sessionId: string; payload: Buffer }) =>+ keyOrThrow(+ sessionId,+ openWrappedKey({ label: sessionLabel(sessionId), payload, keyBytes: AGENT_VAULT_SESSION_LOG_KEY_BYTES })+ );+export const unwrapSessionLogKey = async ({projectId,sessionId,encryptedSessionLogKey}: { projectId: string; sessionId: string; encryptedSessionLogKey: Buffer },- kmsService: TKmsDep-) => {- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId- });- return openSessionLogKey({ sessionId, payload: decryptor({ cipherTextBlob: encryptedSessionLogKey }) });-};+ kmsService: Pick<TKmsServiceFactory, "unwrapKey">+) =>+ keyOrThrow(+ sessionId,+ await kmsService.unwrapKey({+ projectId,+ label: sessionLabel(sessionId),+ wrappedKey: encryptedSessionLogKey,+ keyBytes: AGENT_VAULT_SESSION_LOG_KEY_BYTES+ })+ );diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.test.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.test.tsindex 6d6e811074..e4a0515628 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.test.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.test.ts@@ -3,57 +3,68 @@ import { createMongoAbility } from "@casl/ability";import { v7 as uuidv7 } from "uuid";import { beforeEach, describe, expect, test, vi } from "vitest";-import { BadRequestError, DatabaseError, InternalServerError } from "@app/lib/errors";+import { BadRequestError, DailyQuotaExceededError, InternalServerError } from "@app/lib/errors";+import { ObjectStorageError, toObjectStorageError } from "@app/services/object-storage/object-storage-errors";+import { ObjectStorageErrorReason, ObjectStorageType } from "@app/services/object-storage/object-storage-types";import {+ AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_NOT_ON_PLAN,+ AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_UNAVAILABLE_MESSAGE,+ AGENT_VAULT_SESSION_LOG_EXTERNAL_STORAGE_NOT_ON_PLAN,AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES,AGENT_VAULT_SESSION_LOG_RANGE_MARGIN_MS,AGENT_VAULT_SESSION_LOG_STORAGE_NEEDS_ADMIN_MESSAGE,- AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE_MESSAGE,- AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN+ AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE_MESSAGE} from "./agent-vault-session-log-constants";+import { encodeHistoryCursor, encodeTailCursor } from "./agent-vault-session-log-cursor-fns";import {AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE,AgentVaultSessionLogErrorName} from "./agent-vault-session-log-enums";-import {- buildSessionLogFolder,- buildSessionLogObjectKey,- encodeHistoryCursor,- encodeTailCursor,- toRev-} from "./agent-vault-session-log-fns";+import { buildSessionLogObjectName, toRev } from "./agent-vault-session-log-fns";import { unwrapSessionLogKey } from "./agent-vault-session-log-secrets";import { agentVaultSessionLogServiceFactory } from "./agent-vault-session-log-service";-import { buildSessionLogStorage } from "./agent-vault-session-log-storage-fns";-import { TCreateChunkUploadUrlDTO } from "./agent-vault-session-log-types";+import { TCreateChunkUploadUrlDTO, TUpdateSessionLogSettingsDTO } from "./agent-vault-session-log-types";const PROJECT_ID = "c4a1e0d2-5b7f-4c1e-9a3d-2f6b8e0c7a11";const SESSION_ID = "5d2e9b41-0c3a-4f8e-b7d2-91a4c6e8f035";const PROXY_ID = "e91f3c20-7d4b-4a8e-9f1c-3b5d7e2a6c48";-const FOLDER = buildSessionLogFolder({ keyPrefix: "logs", projectId: PROJECT_ID, sessionId: SESSION_ID });+const CONNECTION_ID = "8a2f4c61-1d3e-4b5a-9c7f-0e6d2b8a4f13";+const folderFor = (sessionId: string) => `logs/orgs/org-1/agent-vault/sessions/${sessionId}/logs/`;+const FOLDER = folderFor(SESSION_ID);-const presignPut = vi.fn(async () => "https://bucket.s3.amazonaws.com/signed-put");-const presignGet = vi.fn(async (key: string) => `https://bucket.s3.amazonaws.com/${key}`);-const listChunks = vi.fn(async () => ({- objects: [] as { key: string; size: number }[],- isTruncated: false+const defaultStorage = vi.hoisted(() => ({ configured: false }));+vi.mock("@app/services/object-storage/object-storage-default-fns", () => ({+ isDefaultStorageConfigured: () => defaultStorage.configured}));-const assertReachable = vi.fn(async () => {});vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));+vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isCloud: true }) }));vi.mock("./agent-vault-session-log-secrets", () => ({ unwrapSessionLogKey: vi.fn(async () => Buffer.alloc(32, 7)) }));-vi.mock("./agent-vault-session-log-storage-fns", () => {- return {- buildSessionLogStorage: vi.fn(async () => ({++const presignPut = vi.fn(async ({ name }: { name: string }) => ({+ key: `${FOLDER}${name}`,+ url: "https://bucket.s3.amazonaws.com/signed-put"+}));+const presignGet = vi.fn(async (key: string) => `https://bucket.s3.amazonaws.com/${key}`);+const list = vi.fn(async () => ({ objects: [] as { key: string; size: number }[], isTruncated: false }));+const listAccess = vi.fn(async () => {});+const check = vi.fn(async () => {});+const presignCorsProbe = vi.fn(async () => "https://bucket.s3.amazonaws.com/probe");+const forOrg = vi.fn(async () => ({+ bucket: "my-bucket",+ namespace: () => ({+ listAccess,+ check,+ presignCorsProbe,+ folder: ({ sessionId }: { sessionId: string }) => ({+ prefix: folderFor(sessionId),presignPut,- presignGet,- listChunks,- assertReachable,- mintCorsProbeUrl: vi.fn(async () => "https://bucket.s3.amazonaws.com/probe"),- validate: vi.fn(async () => {})- }))- };-});+ list,+ presignGet+ })+ })+}));+const at = vi.fn(() => ({ forOrg }));const PROXY = { id: PROXY_ID, name: "proxy-one", projectId: PROJECT_ID, orgId: "org-1" };@@ -72,12 +83,33 @@ const enabledConfig = () => ({id: "cfg-1",projectId: PROJECT_ID,enabled: true,- appConnectionId: "conn-1",+ storageType: "external",+ appConnectionId: CONNECTION_ID,bucket: "my-bucket",region: "us-east-1",keyPrefix: "logs"});+const defaultRow = (enabled: boolean) => ({+ id: "cfg-1",+ projectId: PROJECT_ID,+ enabled,+ storageType: "default",+ appConnectionId: null,+ bucket: null,+ region: null,+ keyPrefix: null+});++const externalStorage = (fields: Record<string, unknown> = {}) => ({+ type: ObjectStorageType.External,+ appConnectionId: CONNECTION_ID,+ bucket: "my-bucket",+ region: "us-east-1",+ keyPrefix: "logs",+ ...fields+});+// The id carries the time of the chunk's last request, which Infisical checks against endedAt.const validChunk = (endedAt = new Date(Date.now() - 1_000)) => ({chunkId: uuidv7({ msecs: endedAt.getTime() }),@@ -88,10 +120,11 @@ const validChunk = (endedAt = new Date(Date.now() - 1_000)) => ({const objectFor = (lastRecordAtMs: number, proxyId = PROXY_ID) => {const chunkId = uuidv7({ msecs: lastRecordAtMs });- return { chunkId, key: buildSessionLogObjectKey({ folder: FOLDER, proxyId, chunkId }) };+ return { chunkId, key: `${FOLDER}${buildSessionLogObjectName({ proxyId, chunkId })}` };};type TFeedEntry = [string, string[]];+type TPlan = { hasExternal?: boolean; hasDefault?: boolean; retentionDays?: number | null };type TOverrides = {proxy?: unknown;@@ -101,21 +134,21 @@ type TOverrides = {feedAddFails?: boolean;feedAddHangs?: boolean;isAdmin?: boolean;- connection?: unknown;- configCreateThrows?: unknown;- licensed?: boolean;+ plan?: TPlan;planFallback?: boolean;- lastKnownPlan?: { plan: { agentVaultByoS3: boolean }; fetchedAt: number } | null;+ lastKnownPlan?: { plan: TPlan; ageMs: number } | null;};+const toPlan = ({ hasExternal = true, hasDefault = true, retentionDays = null }: TPlan = {}) => ({+ agentVaultByoS3: hasExternal,+ agentVaultManagedStorage: hasDefault,+ agentVaultSessionLogRetentionDays: retentionDays+});+const build = (overrides: TOverrides = {}) => {- const validateConnection = vi.fn(async () => ({}));- const findConnection = vi.fn(async () => overrides.connection);+ const validateConnection = vi.fn(async () => ({ name: "prod-logs" }));const config = "config" in overrides ? overrides.config : enabledConfig();- const updateConfig = vi.fn(async (_id: string, values: Record<string, unknown>) => ({- ...(config as object),- ...values- }));+ const upsertConfig = vi.fn(async ([values]: Record<string, unknown>[]) => [{ id: "cfg-1", ...values }]);const streamAdd = vi.fn(async () => {if (overrides.feedAddHangs) return new Promise<string>(() => {});return overrides.feedAddFails ? Promise.reject(new Error("redis is down")) : "1791278402731-0";@@ -127,19 +160,13 @@ const build = (overrides: TOverrides = {}) => {agentVaultSessionLogConfigDAL: {findOne: vi.fn(async () => config),findByProjectIdFromPrimary: vi.fn(async () => config),- updateById: updateConfig,- create: vi.fn(async (values: Record<string, unknown>) => {- if (overrides.configCreateThrows) return Promise.reject(overrides.configCreateThrows);- return { ...enabledConfig(), ...values };- })- } as never,- agentVaultSessionDAL: {- findOne: findSession+ upsert: upsertConfig} as never,+ agentVaultSessionDAL: { findOne: findSession } as never,agentVaultProxyDAL: {findByIdWithOrg: vi.fn(async () => ("proxy" in overrides ? overrides.proxy : PROXY))} as never,- appConnectionDAL: { findById: findConnection } as never,+ appConnectionDAL: { findById: vi.fn(async () => ({ name: "prod-logs" })) } as never,appConnectionService: { validateAppConnectionUsageById: validateConnection } as never,permissionService: {getProjectPermission: vi.fn(async () => ({@@ -147,16 +174,21 @@ const build = (overrides: TOverrides = {}) => {hasRole: () => overrides.isAdmin ?? true}))} as never,- kmsService: { createCipherPairWithDataKey: vi.fn() } as never,+ kmsService: {} as never,licenseService: {- getPlan: vi.fn(async () => ({ agentVaultByoS3: overrides.licensed ?? true })),+ getPlan: vi.fn(async () => toPlan(overrides.plan)),isServingFallbackPlan: vi.fn(async () => overrides.planFallback ?? false),- getLastKnownPlan: vi.fn(async () => overrides.lastKnownPlan ?? null)+ getLastKnownPlan: vi.fn(async () =>+ overrides.lastKnownPlan+ ? { plan: toPlan(overrides.lastKnownPlan.plan), fetchedAt: Date.now() - overrides.lastKnownPlan.ageMs }+ : null+ )} as never,- keyStore: { streamAdd, streamRange } as never+ keyStore: { streamAdd, streamRange } as never,+ objectStorage: { at } as never});- return { service, validateConnection, findConnection, updateConfig, streamAdd, streamRange, findSession };+ return { service, validateConnection, upsertConfig, streamAdd, streamRange, findSession };};const record = (@@ -164,19 +196,37 @@ const record = (chunk: TCreateChunkUploadUrlDTO["chunk"] = validChunk()) => service.createChunkUploadUrl({ proxyId: PROXY_ID, sessionId: SESSION_ID, chunk });-const scope = {- projectId: PROJECT_ID,- ctx: { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never,- sessionId: SESSION_ID-};+const ctx = { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never;+const actor = { type: "user", id: "user-1", orgId: "org-1", authMethod: null } as never;+const scope = { projectId: PROJECT_ID, ctx, sessionId: SESSION_ID };++// The route's schema already shapes the body, so tests pass plain objects.+const save = (service: ReturnType<typeof build>["service"], patch: Record<string, unknown>) =>+ service.updateSessionLogSettings({+ projectId: PROJECT_ID,+ ctx,+ actor,+ ...patch+ } as unknown as TUpdateSessionLogSettingsDTO);++const s3Error = (name: string, fault: "client" | "server" = "client") =>+ new S3ServiceException({ name, $fault: fault, $metadata: {}, message: name });+const storageError = (error: Error, storageType = ObjectStorageType.External) =>+ toObjectStorageError(error, { storageType, bucket: "my-bucket", region: "us-east-1", step: "list" });+const connectionUnusable = new ObjectStorageError({+ reason: ObjectStorageErrorReason.ConnectionInvalid,+ storageType: ObjectStorageType.External,+ details: { connectionName: "prod-logs", cause: "AccessDenied" }+});beforeEach(() => {vi.clearAllMocks();- listChunks.mockResolvedValue({ objects: [], isTruncated: false });+ defaultStorage.configured = false;+ list.mockResolvedValue({ objects: [], isTruncated: false });});describe("createChunkUploadUrl: who is allowed to write", () => {- test("a happy path signs the chunk's name and adds it to the live feed", async () => {+ test("a happy path signs the chunk's name in the session's folder and adds it to the live feed", async () => {const { service, streamAdd } = build();const chunk = validChunk();const result = await record(service, chunk);@@ -184,22 +234,41 @@ describe("createChunkUploadUrl: who is allowed to write", () => {expect(result.uploadUrl).toBe("https://bucket.s3.amazonaws.com/signed-put");expect(result.chunkId).toBe(chunk.chunkId);- const objectKey = buildSessionLogObjectKey({ folder: FOLDER, proxyId: PROXY_ID, chunkId: chunk.chunkId });+ expect(at).toHaveBeenCalledWith({+ storageType: ObjectStorageType.External,+ appConnectionId: CONNECTION_ID,+ bucket: "my-bucket",+ region: "us-east-1",+ keyPrefix: "logs",+ projectType: "agent-vault"+ });+ expect(forOrg).toHaveBeenCalledWith("org-1");+ const name = buildSessionLogObjectName({ proxyId: PROXY_ID, chunkId: chunk.chunkId });expect(presignPut).toHaveBeenCalledWith({- objectKey,- ciphertextBytes: 4096,- ciphertextSha256: chunk.ciphertextSha256+ name,+ bytes: 4096,+ sha256Base64: `${chunk.ciphertextSha256}=`,+ expiresInSeconds: 300,+ retentionDays: 30});expect(streamAdd).toHaveBeenCalledWith(`agent-vault-session-log-feed:${SESSION_ID}`,"*",- { key: objectKey, bucket: "my-bucket", bytes: "4096" },+ { key: `${FOLDER}${name}`, bucket: "my-bucket", bytes: "4096" },10,120,true);});+ test("with nothing saved and an instance bucket, a chunk goes to default storage with the plan's retention", async () => {+ defaultStorage.configured = true;+ const { service } = build({ config: undefined, plan: { retentionDays: 90 } });+ await record(service);+ expect(at).toHaveBeenCalledWith({ storageType: ObjectStorageType.Default });+ expect(presignPut).toHaveBeenCalledWith(expect.objectContaining({ retentionDays: 90 }));+ });+test("an unknown proxy is a 404 that says nothing about the session", async () => {const { service } = build({ proxy: undefined });await expect(record(service)).rejects.toMatchObject({ message: "Session not found" });@@ -262,15 +331,21 @@ describe("createChunkUploadUrl: the retirement grace window", () => {describe("createChunkUploadUrl: when session logs are off", () => {test.each([- { why: "there is no config row", config: undefined },+ { why: "nothing is saved and the instance has no bucket", config: undefined },{ why: "the switch is off", config: { ...enabledConfig(), enabled: false } },- { why: "no bucket is set", config: { ...enabledConfig(), bucket: null } },- { why: "the connection was detached", config: { ...enabledConfig(), appConnectionId: null } }+ { why: "a saved default choice has no instance bucket", config: defaultRow(true) },+ { why: "an external row has no bucket", config: { ...enabledConfig(), bucket: null } }])("refuses with the named error when $why", async ({ config }) => {const { service } = build({ config });await expect(record(service)).rejects.toMatchObject({ name: AgentVaultSessionLogErrorName.Disabled });expect(presignPut).not.toHaveBeenCalled();});++ test("a saved default choice that is off stays off when the instance has a bucket", async () => {+ defaultStorage.configured = true;+ const { service } = build({ config: defaultRow(false) });+ await expect(record(service)).rejects.toMatchObject({ name: AgentVaultSessionLogErrorName.Disabled });+ });});describe("createChunkUploadUrl: the proxy's clock", () => {@@ -284,8 +359,7 @@ describe("createChunkUploadUrl: the proxy's clock", () => {test("a small clock skew forward is tolerated", async () => {const { service } = build();- const soon = new Date(Date.now() + 60_000);- await expect(record(service, validChunk(soon))).resolves.toBeTruthy();+ await expect(record(service, validChunk(new Date(Date.now() + 60_000)))).resolves.toBeTruthy();});test("a proxy clock more than 30 days behind is refused with the named error", async () => {@@ -327,17 +401,16 @@ describe("createChunkUploadUrl: what the chunk says about itself", () => {expect(presignPut).not.toHaveBeenCalled();expect(streamAdd).not.toHaveBeenCalled();});-});-describe("createChunkUploadUrl: sending a chunk again", () => {test("a chunk id another proxy also used lands under that proxy's own name", async () => {const chunk = validChunk();const { service } = build();await record(service, chunk);- const { service: other } = build({ proxy: { ...PROXY, id: "0b5c8f2a-3d1e-4c7b-9a6f-2e8d4b1c7f30" } });- await other.createChunkUploadUrl({ proxyId: "0b5c8f2a-3d1e-4c7b-9a6f-2e8d4b1c7f30", sessionId: SESSION_ID, chunk });- const [first, second] = presignPut.mock.calls as unknown as [{ objectKey: string }][];- expect(first[0].objectKey).not.toBe(second[0].objectKey);+ const otherProxyId = "0b5c8f2a-3d1e-4c7b-9a6f-2e8d4b1c7f30";+ const { service: other } = build({ proxy: { ...PROXY, id: otherProxyId } });+ await other.createChunkUploadUrl({ proxyId: otherProxyId, sessionId: SESSION_ID, chunk });+ const [first, second] = presignPut.mock.calls.map(([args]) => args.name);+ expect(first).not.toBe(second);});});@@ -353,47 +426,111 @@ describe("createChunkUploadUrl: the live feed", () => {});});-describe("when the AWS connection can't be used", () => {- const unusable = new BadRequestError({ message: "Couldn't use the AWS connection 'prod-logs': AccessDenied" });-- test("a chunk is refused as a retryable 500 before it is signed, without the connection's details", async () => {- vi.mocked(buildSessionLogStorage).mockRejectedValueOnce(unusable);+describe("createChunkUploadUrl: when storage can't be used", () => {+ test("an unusable connection is a retryable 500 without the connection's details", async () => {+ forOrg.mockRejectedValueOnce(connectionUnusable);const { service } = build();const error = (await record(service).catch((err: unknown) => err)) as Error;- expect(error.name).toBe("InternalServerError");- expect(error.message).not.toContain("prod-logs");+ expect(error).toBeInstanceOf(InternalServerError);+ expect(error.message).toBe(+ "Session logs can't use their AWS connection right now. An Agent Vault admin can check it in Settings."+ );+ expect(presignPut).not.toHaveBeenCalled();+ });++ test("default storage that can't be reached is retryable too, and says so in its own words", async () => {+ defaultStorage.configured = true;+ forOrg.mockRejectedValueOnce(storageError(s3Error("AccessDenied"), ObjectStorageType.Default));+ const { service } = build({ config: undefined });+ await expect(record(service)).rejects.toMatchObject({+ name: "InternalServerError",+ message: "Session logs can't reach default storage right now. The proxy keeps the chunk and retries."+ });+ });++ test("the daily cap's 429 reaches the proxy as it is", async () => {+ presignPut.mockRejectedValueOnce(new DailyQuotaExceededError({}));+ const { service } = build();+ await expect(record(service)).rejects.toBeInstanceOf(DailyQuotaExceededError);+ });+});++describe("createChunkUploadUrl: the plan for the storage in use", () => {+ test("external storage without its flag tells the proxy logging is off", async () => {+ const { service } = build({ plan: { hasExternal: false } });+ await expect(record(service)).rejects.toMatchObject({+ name: AgentVaultSessionLogErrorName.Disabled,+ message: AGENT_VAULT_SESSION_LOG_EXTERNAL_STORAGE_NOT_ON_PLAN+ });expect(presignPut).not.toHaveBeenCalled();});+ test("default storage without its flag tells the proxy logging is off", async () => {+ defaultStorage.configured = true;+ const { service } = build({ config: undefined, plan: { hasDefault: false } });+ await expect(record(service)).rejects.toMatchObject({+ name: AgentVaultSessionLogErrorName.Disabled,+ message: AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_NOT_ON_PLAN+ });+ });++ test("while the License Server is down, a chunk from a paid org is accepted on its last known plan", async () => {+ const { service } = build({+ plan: { hasExternal: false },+ planFallback: true,+ lastKnownPlan: { plan: { hasExternal: true }, ageMs: 10 * 60_000 }+ });+ await record(service);+ expect(presignPut).toHaveBeenCalledTimes(1);+ });++ test("while the License Server is down, default storage keeps the retention of the last real plan", async () => {+ defaultStorage.configured = true;+ const { service } = build({+ config: undefined,+ planFallback: true,+ lastKnownPlan: { plan: { retentionDays: 365 }, ageMs: 10 * 60_000 }+ });+ await record(service);+ expect(presignPut).toHaveBeenCalledWith(expect.objectContaining({ retentionDays: 365 }));+ });++ test("a chunk is held, not refused, when there is no recent real answer", async () => {+ const { service } = build({+ plan: { hasExternal: false },+ planFallback: true,+ lastKnownPlan: { plan: { hasExternal: true }, ageMs: 2 * 60 * 60_000 }+ });+ await expect(record(service)).rejects.toMatchObject({ name: "InternalServerError" });+ expect(presignPut).not.toHaveBeenCalled();+ });+});++describe("reading logs when storage can't be used", () => {const storageUnavailable = (message: string): unknown =>expect.objectContaining({ name: AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE, message });test("a read fails with the named error and tells an admin why", async () => {- vi.mocked(buildSessionLogStorage).mockRejectedValueOnce(unusable);+ forOrg.mockRejectedValueOnce(connectionUnusable);const { service } = build();const error = await service.listSessionLogs(scope).catch((err: unknown) => err);expect(error).toBeInstanceOf(BadRequestError);- expect(error).toEqual(storageUnavailable(unusable.message));- });-- test("a read without a connection tells an admin to choose one", async () => {- const { service } = build({ config: { ...enabledConfig(), enabled: false, appConnectionId: null } });- await expect(service.listSessionLogs(scope)).rejects.toEqual(- storageUnavailable("No AWS connection is set for session logs. Choose one in Settings.")+ expect(error).toEqual(+ storageUnavailable("Couldn't use the AWS connection 'prod-logs' for session logs: AccessDenied"));});test("a live read fails too, so the caller keeps its cursor and nothing is skipped", async () => {- vi.mocked(buildSessionLogStorage).mockRejectedValueOnce(unusable);+ forOrg.mockRejectedValueOnce(connectionUnusable);const { key } = objectFor(Date.now());const { service } = build({ feed: [["1791278402731-0", ["key", key, "bucket", "my-bucket", "bytes", "4096"]]] });await expect(service.tailSessionLogs({ ...scope, cursor: "1791278402000-0" })).rejects.toEqual(- storageUnavailable(unusable.message)+ storageUnavailable("Couldn't use the AWS connection 'prod-logs' for session logs: AccessDenied"));});test("a member who isn't an admin is told to ask an admin, without the AWS error", async () => {- vi.mocked(buildSessionLogStorage).mockRejectedValueOnce(unusable);+ forOrg.mockRejectedValueOnce(connectionUnusable);const { service } = build({ isAdmin: false });await expect(service.listSessionLogs(scope)).rejects.toEqual(storageUnavailable(AGENT_VAULT_SESSION_LOG_STORAGE_NEEDS_ADMIN_MESSAGE)@@ -401,9 +538,7 @@ describe("when the AWS connection can't be used", () => {});test("a member who isn't an admin gets no bucket detail when listing fails", async () => {- listChunks.mockRejectedValueOnce(- new S3ServiceException({ name: "AccessDenied", $fault: "client", $metadata: {}, message: "Access Denied" })- );+ list.mockRejectedValueOnce(storageError(s3Error("AccessDenied")));const { service } = build({ isAdmin: false });await expect(service.listSessionLogs(scope)).rejects.toEqual(storageUnavailable(AGENT_VAULT_SESSION_LOG_STORAGE_NEEDS_ADMIN_MESSAGE)@@ -411,38 +546,15 @@ describe("when the AWS connection can't be used", () => {});test("a member who isn't an admin is told to try again when S3 isn't responding", async () => {- listChunks.mockRejectedValueOnce(- new S3ServiceException({ name: "SlowDown", $fault: "server", $metadata: {}, message: "Slow down" })- );+ list.mockRejectedValueOnce(storageError(s3Error("SlowDown", "server")));const { service } = build({ isAdmin: false });const error = await service.listSessionLogs(scope).catch((err: unknown) => err);expect(error).toBeInstanceOf(InternalServerError);expect(error).toEqual(storageUnavailable(AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE_MESSAGE));});- test("a connection AWS didn't answer for is a 500, so callers know to try again", async () => {- const unreachable = new InternalServerError({ message: "Couldn't reach AWS to use the connection 'prod-logs'" });- vi.mocked(buildSessionLogStorage).mockRejectedValueOnce(unreachable);- const { service } = build();- const error = await service.listSessionLogs(scope).catch((err: unknown) => err);- expect(error).toBeInstanceOf(InternalServerError);- expect(error).toEqual(storageUnavailable(unreachable.message));- });-- test("a reply S3's client couldn't parse is still the storage error, not a bare 500", async () => {- listChunks.mockRejectedValueOnce(- Object.assign(new Error("XML parse error"), { $metadata: { httpStatusCode: 429 } })- );- const { service } = build();- const error = await service.listSessionLogs(scope).catch((err: unknown) => err);- expect(error).toBeInstanceOf(InternalServerError);- expect((error as Error).message).toContain("(HTTP 429)");- });-test("a bucket that refuses to list is a 400 that points at s3:ListBucket", async () => {- listChunks.mockRejectedValueOnce(- new S3ServiceException({ name: "AccessDenied", $fault: "client", $metadata: {}, message: "Access Denied" })- );+ list.mockRejectedValueOnce(storageError(s3Error("AccessDenied")));const { service } = build();const error = await service.listSessionLogs(scope).catch((err: unknown) => err);expect(error).toBeInstanceOf(BadRequestError);@@ -450,9 +562,7 @@ describe("when the AWS connection can't be used", () => {});test("an S3 that isn't responding is a 500, so callers know to try again", async () => {- listChunks.mockRejectedValueOnce(- new S3ServiceException({ name: "SlowDown", $fault: "server", $metadata: {}, message: "Slow down" })- );+ list.mockRejectedValueOnce(storageError(s3Error("SlowDown", "server")));const { service } = build();const error = await service.listSessionLogs(scope).catch((err: unknown) => err);expect(error).toBeInstanceOf(InternalServerError);@@ -463,35 +573,72 @@ describe("when the AWS connection can't be used", () => {);});+ test.each([true, false])(+ "default storage that can't be read is a 500 pointing to Infisical support, for admins and others (admin: %s)",+ async (isAdmin) => {+ defaultStorage.configured = true;+ list.mockRejectedValueOnce(storageError(s3Error("AccessDenied"), ObjectStorageType.Default));+ const { service } = build({ config: undefined, isAdmin });+ const error = await service.listSessionLogs(scope).catch((err: unknown) => err);+ expect(error).toBeInstanceOf(InternalServerError);+ expect(error).toEqual(storageUnavailable(AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_UNAVAILABLE_MESSAGE));+ }+ );+test("anything else that goes wrong while listing stays an error", async () => {- listChunks.mockRejectedValueOnce(new TypeError("a bug"));+ list.mockRejectedValueOnce(new TypeError("a bug"));const { service } = build();await expect(service.listSessionLogs(scope)).rejects.toThrow("a bug");});});+describe("reading logs that are off or not on the plan", () => {+ test("off hides what was recorded, without reading the bucket", async () => {+ const { service } = build({ config: { ...enabledConfig(), enabled: false } });+ const page = await service.listSessionLogs(scope);+ expect(page.chunks).toEqual([]);+ expect(page.sessionLogs).toMatchObject({ enabled: false, disabledReason: "off" });+ expect(forOrg).not.toHaveBeenCalled();+ });++ test("with no settings at all, reads say logs are off", async () => {+ const { service } = build({ config: undefined });+ const page = await service.tailSessionLogs(scope);+ expect(page.sessionLogs.disabledReason).toBe("off");+ });++ test("without the plan for the storage in use, recorded logs are hidden", async () => {+ const { service } = build({ plan: { hasExternal: false } });+ const page = await service.listSessionLogs(scope);+ expect(page.chunks).toEqual([]);+ expect(page.sessionLogs).toMatchObject({ enabled: false, disabledReason: "not-on-plan" });+ expect(forOrg).not.toHaveBeenCalled();+ });++ test("while the License Server is down with no recent answer, logs can still be read", async () => {+ const { service } = build({ plan: { hasExternal: false }, planFallback: true });+ const page = await service.listSessionLogs(scope);+ expect(page.sessionLogs).toMatchObject({ enabled: true, disabledReason: null });+ expect(list).toHaveBeenCalledTimes(1);+ });+});+describe("listSessionLogs: paging through the bucket", () => {test("a session that was never recordable lists nothing and never calls S3", async () => {const { service } = build({ session: { ...liveSession(), encryptedSessionLogKey: null } });const page = await service.listSessionLogs(scope);expect(page.chunks).toEqual([]);- expect(listChunks).not.toHaveBeenCalled();+ expect(list).not.toHaveBeenCalled();});test("returns each chunk with its proxy, size and a download link", async () => {- const lastRecordAt = Date.now() - 60_000;- const { chunkId, key } = objectFor(lastRecordAt);- listChunks.mockResolvedValueOnce({ objects: [{ key, size: 4096 }], isTruncated: false });+ const { chunkId, key } = objectFor(Date.now() - 60_000);+ list.mockResolvedValueOnce({ objects: [{ key, size: 4096 }], isTruncated: false });const { service } = build();const page = await service.listSessionLogs(scope);expect(page.chunks).toEqual([- {- chunkId,- proxyId: PROXY_ID,- ciphertextBytes: 4096,- presignedGetUrl: `https://bucket.s3.amazonaws.com/${key}`- }+ { chunkId, proxyId: PROXY_ID, ciphertextBytes: 4096, presignedGetUrl: `https://bucket.s3.amazonaws.com/${key}` }]);expect(page.sessionLogs.sessionKey).toBe(Buffer.alloc(32, 7).toString("base64"));expect(page.nextCursor).toBeNull();@@ -501,7 +648,7 @@ describe("listSessionLogs: paging through the bucket", () => {const big = Math.floor(AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES * 0.6);const newer = objectFor(Date.now() - 1_000);const older = objectFor(Date.now() - 2_000);- listChunks.mockResolvedValueOnce({+ list.mockResolvedValueOnce({objects: [{ key: newer.key, size: big },{ key: older.key, size: big }@@ -517,7 +664,7 @@ describe("listSessionLogs: paging through the bucket", () => {test("always takes at least one chunk, however large", async () => {const huge = objectFor(Date.now());- listChunks.mockResolvedValueOnce({+ list.mockResolvedValueOnce({objects: [{ key: huge.key, size: AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES * 4 }],isTruncated: false});@@ -527,7 +674,7 @@ describe("listSessionLogs: paging through the bucket", () => {});test("skips files it didn't write, and still moves past them", async () => {- listChunks.mockResolvedValueOnce({ objects: [{ key: `${FOLDER}notes.txt`, size: 10 }], isTruncated: true });+ list.mockResolvedValueOnce({ objects: [{ key: `${FOLDER}notes.txt`, size: 10 }], isTruncated: true });const { service } = build();const page = await service.listSessionLogs(scope);expect(page.chunks).toEqual([]);@@ -535,7 +682,7 @@ describe("listSessionLogs: paging through the bucket", () => {});test("an empty page that says more remain ends the listing instead of failing", async () => {- listChunks.mockResolvedValueOnce({ objects: [], isTruncated: true });+ list.mockResolvedValueOnce({ objects: [], isTruncated: true });const { service } = build();const page = await service.listSessionLogs(scope);expect(page.chunks).toEqual([]);@@ -545,22 +692,22 @@ describe("listSessionLogs: paging through the bucket", () => {test("a cursor continues after the name it carries", async () => {const { service } = build();await service.listSessionLogs({ ...scope, cursor: "8208694117999_x" });- expect(listChunks).toHaveBeenCalledWith({ folder: FOLDER, startAfter: `${FOLDER}8208694117999_x` });+ expect(list).toHaveBeenCalledWith({ startAfter: `${FOLDER}8208694117999_x`, maxKeys: 200 });});test("a cursor wins over the end of a date range, so later pages keep moving back", async () => {const { service } = build();await service.listSessionLogs({ ...scope, cursor: "8208694117999_x", to: new Date() });- expect(listChunks).toHaveBeenCalledWith({ folder: FOLDER, startAfter: `${FOLDER}8208694117999_x` });+ expect(list).toHaveBeenCalledWith({ startAfter: `${FOLDER}8208694117999_x`, maxKeys: 200 });});test("a date range starts listing at its end plus the margin", async () => {const to = new Date("2026-10-07T10:00:00.000Z");const { service } = build();await service.listSessionLogs({ ...scope, from: new Date("2026-10-07T09:00:00.000Z"), to });- expect(listChunks).toHaveBeenCalledWith({- folder: FOLDER,- startAfter: `${FOLDER}${toRev(to.getTime() + AGENT_VAULT_SESSION_LOG_RANGE_MARGIN_MS)}`+ expect(list).toHaveBeenCalledWith({+ startAfter: `${FOLDER}${toRev(to.getTime() + AGENT_VAULT_SESSION_LOG_RANGE_MARGIN_MS)}`,+ maxKeys: 200});});@@ -568,7 +715,7 @@ describe("listSessionLogs: paging through the bucket", () => {const from = new Date(Date.now() - 60_000);const inside = objectFor(from.getTime() + 1_000);const before = objectFor(from.getTime() - 1_000);- listChunks.mockResolvedValueOnce({+ list.mockResolvedValueOnce({objects: [{ key: inside.key, size: 100 },{ key: before.key, size: 100 }@@ -623,10 +770,10 @@ describe("tailSessionLogs: reading the live feed", () => {expect(page.chunks).toHaveLength(2);});- test("skips entries from an earlier bucket or prefix, and still moves past them", async () => {+ test("skips entries from another bucket or folder, and still moves past them", async () => {const { key } = objectFor(Date.now());const { service } = build({- feed: [entry("100-0", key, "old-bucket"), entry("101-0", `old-prefix/${PROJECT_ID}/${SESSION_ID}/x.json.enc`)]+ feed: [entry("100-0", key, "old-bucket"), entry("101-0", `old-prefix/orgs/org-1/agent-vault/x.json.enc`)]});const page = await service.tailSessionLogs(scope);expect(page.chunks).toEqual([]);@@ -644,12 +791,11 @@ describe("tailSessionLogs: reading the live feed", () => {test("an uppercase session id reads the same folder and feed as the stored one", async () => {const upper = { ...scope, sessionId: SESSION_ID.toUpperCase() };const { key } = objectFor(Date.now() - 60_000);- listChunks.mockResolvedValueOnce({ objects: [{ key, size: 100 }], isTruncated: false });+ list.mockResolvedValueOnce({ objects: [{ key, size: 100 }], isTruncated: false });const { service, streamRange } = build();await service.tailSessionLogs(upper);const page = await service.listSessionLogs(upper);expect(streamRange).toHaveBeenCalledWith(`agent-vault-session-log-feed:${SESSION_ID}`, "(0-0", "+");- expect(listChunks).toHaveBeenCalledWith(expect.objectContaining({ folder: FOLDER }));expect(page.chunks).toHaveLength(1);expect(unwrapSessionLogKey).toHaveBeenCalledWith(expect.objectContaining({ sessionId: SESSION_ID }),@@ -657,202 +803,374 @@ describe("tailSessionLogs: reading the live feed", () => {);});- test("an empty feed keeps the cursor and never touches the AWS connection", async () => {+ test("an empty feed keeps the cursor and never touches storage", async () => {const { service } = build();const page = await service.tailSessionLogs({ ...scope, cursor: "99-0" });expect(page.chunks).toEqual([]);expect(page.nextCursor).toBe(encodeTailCursor("99-0"));- expect(buildSessionLogStorage).not.toHaveBeenCalled();+ expect(forOrg).not.toHaveBeenCalled();});});-describe("updateSessionLogSettings: when the connection is checked again", () => {- const ctx = { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never;- const actor = { type: "user", id: "user-1", orgId: "org-1", authMethod: null } as never;+describe("getSessionLogSettings", () => {+ test("with nothing saved and an instance bucket, reads as on in default storage", async () => {+ defaultStorage.configured = true;+ const { service } = build({ config: undefined });+ expect(await service.getSessionLogSettings({ projectId: PROJECT_ID, ctx })).toEqual({+ settings: { enabled: true, storage: { type: ObjectStorageType.Default } },+ defaultStorage: { configured: true }+ });+ });++ test("with nothing saved and no instance bucket, there are no settings", async () => {+ const { service } = build({ config: undefined });+ expect(await service.getSessionLogSettings({ projectId: PROJECT_ID, ctx })).toEqual({+ settings: null,+ defaultStorage: { configured: false }+ });+ });++ test("a saved default choice reads as nothing once the operator removes the bucket", async () => {+ const { service } = build({ config: defaultRow(true) });+ expect((await service.getSessionLogSettings({ projectId: PROJECT_ID, ctx })).settings).toBeNull();+ });++ test("a saved external choice reads back as saved", async () => {+ const { service } = build();+ expect((await service.getSessionLogSettings({ projectId: PROJECT_ID, ctx })).settings).toEqual({+ enabled: true,+ storage: externalStorage()+ });+ });+});++describe("updateSessionLogSettings: choosing storage", () => {+ test("default storage on an instance without a bucket is refused", async () => {+ const { service, upsertConfig } = build({ config: undefined });+ await expect(save(service, { enabled: true, storage: { type: "default" } })).rejects.toThrow(+ "This instance doesn't offer default storage"+ );+ expect(upsertConfig).not.toHaveBeenCalled();+ });++ test("turning off is saved even with nothing to turn off, so a bucket added later doesn't turn it on", async () => {+ const { service, upsertConfig } = build({ config: undefined });+ const result = await save(service, { enabled: false });+ expect(result).toMatchObject({ settings: null, previous: null });+ expect(upsertConfig).toHaveBeenCalledWith(+ [expect.objectContaining({ enabled: false, storageType: "default", bucket: null })],+ "projectId"+ );+ });++ test("turning off the default with nothing saved saves it off", async () => {+ defaultStorage.configured = true;+ const { service, upsertConfig } = build({ config: undefined });+ const { settings } = await save(service, { enabled: false });+ expect(settings).toEqual({ enabled: false, storage: { type: ObjectStorageType.Default } });+ expect(upsertConfig).toHaveBeenCalledWith(+ [expect.objectContaining({ enabled: false, storageType: "default", bucket: null })],+ "projectId"+ );+ });++ test("switching to default drops the bucket and frees the connection", async () => {+ defaultStorage.configured = true;+ const { service, upsertConfig, validateConnection } = build();+ await save(service, { enabled: true, storage: { type: "default" } });+ expect(upsertConfig).toHaveBeenCalledWith(+ [+ {+ projectId: PROJECT_ID,+ enabled: true,+ storageType: "default",+ appConnectionId: null,+ bucket: null,+ region: null,+ keyPrefix: null+ }+ ],+ "projectId"+ );+ expect(validateConnection).not.toHaveBeenCalled();+ });++ test("switching to external checks the connection and the bucket at the product folder", async () => {+ defaultStorage.configured = true;+ const { service, validateConnection } = build({ config: undefined });+ const { settings, appConnectionName } = await save(service, { enabled: true, storage: externalStorage() });+ expect(validateConnection).toHaveBeenCalledTimes(1);+ expect(check).toHaveBeenCalledTimes(1);+ expect(settings?.storage).toEqual(externalStorage());+ expect(appConnectionName).toBe("prod-logs");+ });++ test("a bucket check failure says what to fix, and nothing is saved", async () => {+ check.mockRejectedValueOnce(+ toObjectStorageError(s3Error("AccessDenied"), {+ storageType: ObjectStorageType.External,+ bucket: "other-bucket",+ region: "us-east-1",+ step: "write"+ })+ );+ const { service, upsertConfig } = build();+ await expect(+ save(service, { enabled: true, storage: externalStorage({ bucket: "other-bucket" }) })+ ).rejects.toThrow("Grant s3:PutObject");+ expect(upsertConfig).not.toHaveBeenCalled();+ });- const save = (service: ReturnType<typeof build>["service"], patch: Record<string, unknown>) =>- service.updateSessionLogSettings({ projectId: PROJECT_ID, ctx, actor, ...patch });+ test("a saved default choice on an instance that lost its bucket can still be replaced", async () => {+ const { service, upsertConfig } = build({ config: defaultRow(true) });+ await save(service, { enabled: true, storage: externalStorage() });+ expect(upsertConfig).toHaveBeenCalledTimes(1);+ });+});+describe("updateSessionLogSettings: when the connection is checked again", () => {test.each([- { use: "a different connection", patch: { appConnectionId: "5c6fd1a9-3c89-4a64-9e5f-6b7cfe0f1a2b" } },- { use: "a different bucket", patch: { bucket: "another-bucket" } },- { use: "a different region", patch: { region: "us-west-2" } },- { use: "a different prefix", patch: { keyPrefix: "elsewhere" } }- ])("checks it when the save points it at $use", async ({ patch }) => {+ { use: "a different connection", fields: { appConnectionId: "5c6fd1a9-3c89-4a64-9e5f-6b7cfe0f1a2b" } },+ { use: "a different bucket", fields: { bucket: "another-bucket" } },+ { use: "a different region", fields: { region: "us-west-2" } },+ { use: "a different prefix", fields: { keyPrefix: "elsewhere" } }+ ])("checks it when the save points it at $use", async ({ fields }) => {const { service, validateConnection } = build();- await save(service, patch);+ await save(service, { enabled: true, storage: externalStorage(fields) });expect(validateConnection).toHaveBeenCalledTimes(1);});- test("checks it when the save turns recording on", async () => {+ test("checks it, and the bucket, when the save turns recording back on", async () => {const { service, validateConnection } = build({ config: { ...enabledConfig(), enabled: false } });- await save(service, { enabled: true });+ await save(service, { enabled: true, storage: externalStorage() });expect(validateConnection).toHaveBeenCalledTimes(1);+ expect(check).toHaveBeenCalledTimes(1);});test("never checks it when the save turns recording off, so an unusable connection cannot block that", async () => {const { service, validateConnection } = build();await save(service, { enabled: false });expect(validateConnection).not.toHaveBeenCalled();+ expect(check).not.toHaveBeenCalled();});- test("skips it when the save leaves the destination as it was", async () => {- const { service, validateConnection } = build();- await save(service, {- enabled: true,- appConnectionId: "conn-1",- bucket: "my-bucket",- region: "us-east-1",- keyPrefix: "logs"- });+ test("skips it when the save repeats the storage as it was, with an empty prefix meaning none", async () => {+ const { service, validateConnection } = build({ config: { ...enabledConfig(), keyPrefix: null } });+ await save(service, { enabled: true, storage: externalStorage({ keyPrefix: "" }) });expect(validateConnection).not.toHaveBeenCalled();});-});--describe("updateSessionLogSettings: directory buckets", () => {- const ctx = { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never;- const actor = { type: "user", id: "user-1", orgId: "org-1", authMethod: null } as never;test("refuses a directory bucket, which can't list in order", async () => {- const { service, updateConfig } = build();+ const { service, upsertConfig } = build();await expect(- service.updateSessionLogSettings({ projectId: PROJECT_ID, ctx, actor, bucket: "logs--usw2-az1--x-s3" })+ save(service, { enabled: true, storage: externalStorage({ bucket: "logs--usw2-az1--x-s3" }) })).rejects.toThrow("Directory buckets");- expect(updateConfig).not.toHaveBeenCalled();+ expect(upsertConfig).not.toHaveBeenCalled();});test("a directory bucket already saved can still be turned off", async () => {- const { service, updateConfig } = build({ config: { ...enabledConfig(), bucket: "logs--usw2-az1--x-s3" } });- await service.updateSessionLogSettings({ projectId: PROJECT_ID, ctx, actor, enabled: false });- expect(updateConfig).toHaveBeenCalledTimes(1);+ const { service, upsertConfig } = build({ config: { ...enabledConfig(), bucket: "logs--usw2-az1--x-s3" } });+ await save(service, { enabled: false });+ expect(upsertConfig).toHaveBeenCalledTimes(1);});});-describe("updateSessionLogSettings: two first saves at once", () => {- test("the one that loses reads as a clash to retry, not a server error", async () => {- const { service } = build({- config: undefined,- configCreateThrows: new DatabaseError({ error: { code: "23505" }, name: "create" })+describe("updateSessionLogSettings: the plan", () => {+ test("turning external storage back on without its flag is refused before the connection is checked", async () => {+ const { service, validateConnection, upsertConfig } = build({+ plan: { hasExternal: false },+ config: { ...enabledConfig(), enabled: false }});+ await expect(save(service, { enabled: true, storage: externalStorage() })).rejects.toThrow(+ AGENT_VAULT_SESSION_LOG_EXTERNAL_STORAGE_NOT_ON_PLAN+ );+ expect(validateConnection).not.toHaveBeenCalled();+ expect(upsertConfig).not.toHaveBeenCalled();+ });++ test("changing the bucket without the flag is refused", async () => {+ const { service, upsertConfig } = build({ plan: { hasExternal: false } });await expect(- service.updateSessionLogSettings({- projectId: PROJECT_ID,- ctx: { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never,- actor: { type: "user", id: "user-1", orgId: "org-1", authMethod: null } as never,- enabled: false- })- ).rejects.toThrow("Session log settings were just changed. Reload and try again.");+ save(service, { enabled: true, storage: externalStorage({ bucket: "another-bucket" }) })+ ).rejects.toThrow(AGENT_VAULT_SESSION_LOG_EXTERNAL_STORAGE_NOT_ON_PLAN);+ expect(upsertConfig).not.toHaveBeenCalled();});-});-describe("without session logs on the plan", () => {- const ctx = { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never;- const actor = { type: "user", id: "user-1", orgId: "org-1", authMethod: null } as never;+ test("choosing default storage without its flag is refused", async () => {+ defaultStorage.configured = true;+ const { service } = build({ plan: { hasDefault: false } });+ await expect(save(service, { enabled: true, storage: { type: "default" } })).rejects.toThrow(+ AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_NOT_ON_PLAN+ );+ });- const save = (service: ReturnType<typeof build>["service"], patch: Record<string, unknown>) =>- service.updateSessionLogSettings({ projectId: PROJECT_ID, ctx, actor, ...patch });+ test.each([+ { why: "external storage after the plan lapsed", plan: { hasExternal: false }, config: enabledConfig() },+ { why: "default storage that was never on the plan", plan: { hasDefault: false }, config: undefined },+ { why: "a saved default choice after the plan lapsed", plan: { hasDefault: false }, config: defaultRow(true) }+ ])("turning off $why still works", async ({ plan, config }) => {+ defaultStorage.configured = true;+ const { service, upsertConfig } = build({ plan, config });+ const { settings } = await save(service, { enabled: false });+ expect(settings?.enabled).toBe(false);+ expect(upsertConfig).toHaveBeenCalledTimes(1);+ });- test("a save that turns recording on is refused before the connection is checked", async () => {- const { service, validateConnection, updateConfig } = build({- licensed: false,+ test("a save that needs the plan says when it couldn't be confirmed", async () => {+ const { service, upsertConfig } = build({+ plan: { hasExternal: false },+ planFallback: true,config: { ...enabledConfig(), enabled: false }});- await expect(save(service, { enabled: true })).rejects.toThrow(AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN);- expect(validateConnection).not.toHaveBeenCalled();- expect(updateConfig).not.toHaveBeenCalled();+ await expect(save(service, { enabled: true, storage: externalStorage() })).rejects.toThrow(+ "Infisical couldn't confirm your plan right now. Try again in a few minutes."+ );+ expect(upsertConfig).not.toHaveBeenCalled();});+});- test("a save that changes the bucket is refused", async () => {- const { service, updateConfig } = build({ licensed: false });- await expect(save(service, { bucket: "another-bucket" })).rejects.toThrow(AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN);- expect(updateConfig).not.toHaveBeenCalled();+describe("updateSessionLogSettings: turning off", () => {+ test("forgets the bucket and connection, so the connection can be deleted, and says what it replaced", async () => {+ const { service, upsertConfig } = build({ plan: { hasExternal: false, hasDefault: false } });+ const result = await save(service, { enabled: false });+ expect(upsertConfig).toHaveBeenCalledWith(+ [+ {+ projectId: PROJECT_ID,+ enabled: false,+ storageType: "default",+ appConnectionId: null,+ bucket: null,+ region: null,+ keyPrefix: null+ }+ ],+ "projectId"+ );+ expect(result.previous).toEqual({+ storageType: ObjectStorageType.External,+ appConnectionId: CONNECTION_ID,+ appConnectionName: "prod-logs",+ bucket: "my-bucket",+ region: "us-east-1",+ keyPrefix: "logs"+ });+ expect(result.settings).toBeNull();});- test("a save that turns recording off still works", async () => {- const { service, updateConfig } = build({ licensed: false });- const { settings } = await save(service, { enabled: false });- expect(settings.enabled).toBe(false);- expect(updateConfig).toHaveBeenCalledTimes(1);+ test("on an instance with a bucket, what's left reads as default storage, off", async () => {+ defaultStorage.configured = true;+ const { service } = build();+ const result = await save(service, { enabled: false });+ expect(result.settings).toEqual({ enabled: false, storage: { type: ObjectStorageType.Default } });+ });++ test("turning session logs back on from off records nothing as replaced, since off holds no storage", async () => {+ defaultStorage.configured = true;+ const { service } = build({ config: defaultRow(false) });+ const { settings, previous } = await save(service, { enabled: true, storage: externalStorage() });+ expect(settings?.enabled).toBe(true);+ expect(previous).toBeNull();+ });++ test("switching from default storage that was recording to a bucket records the default it replaced", async () => {+ defaultStorage.configured = true;+ const { service } = build({ config: defaultRow(true) });+ const { previous } = await save(service, { enabled: true, storage: externalStorage() });+ expect(previous).toEqual({+ storageType: ObjectStorageType.Default,+ appConnectionId: null,+ appConnectionName: null,+ bucket: null,+ region: null,+ keyPrefix: null+ });});- test("a save that turns recording off and removes the connection still works", async () => {- const { service, validateConnection } = build({ licensed: false });- const { settings } = await save(service, { enabled: false, appConnectionId: null });- expect(settings).toMatchObject({ enabled: false, appConnectionId: null });- expect(validateConnection).not.toHaveBeenCalled();+ test("switching from a bucket to default storage records the bucket it replaced", async () => {+ defaultStorage.configured = true;+ const { service } = build();+ const { previous } = await save(service, { enabled: true, storage: { type: "default" } });+ expect(previous).toMatchObject({ storageType: ObjectStorageType.External, bucket: "my-bucket" });});- test("a chunk is refused with the error that tells the proxy logging is off", async () => {- const { service } = build({ licensed: false });- await expect(record(service)).rejects.toMatchObject({- name: AgentVaultSessionLogErrorName.Disabled,- message: AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN- });- expect(presignPut).not.toHaveBeenCalled();+ test("saving the same storage again records nothing as replaced", async () => {+ const { service } = build();+ const { previous } = await save(service, { enabled: true, storage: externalStorage() });+ expect(previous).toBeNull();});+});- test("logs recorded while it was on can still be read, and read as not recording", async () => {- const { key } = objectFor(Date.now());- listChunks.mockResolvedValueOnce({ objects: [{ key, size: 4096 }], isTruncated: false });- const { service } = build({ licensed: false });- const page = await service.listSessionLogs({ projectId: PROJECT_ID, ctx, sessionId: SESSION_ID });- expect(page.chunks).toHaveLength(1);- expect(page.sessionLogs.enabled).toBe(false);+describe("getSessionLogHealth", () => {+ test("reports a bucket the connection can't list", async () => {+ listAccess.mockRejectedValueOnce(storageError(s3Error("AccessDenied")));+ const { service } = build();+ const { health } = await service.getSessionLogHealth({ projectId: PROJECT_ID, ctx });+ expect(health.connectionError).toBe(+ "Unable to reach bucket 'my-bucket'. Check the bucket name, the region, and that the connection's credentials allow s3:ListBucket on it"+ );});-});-describe("while the License Server can't be reached", () => {- const ctx = { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never;- const actor = { type: "user", id: "user-1", orgId: "org-1", authMethod: null } as never;- const unreachable = { licensed: false, planFallback: true } as const;+ test("never checks default storage, which is the operator's to fix and is checked at boot", async () => {+ defaultStorage.configured = true;+ const { service } = build({ config: undefined });+ const { health } = await service.getSessionLogHealth({ projectId: PROJECT_ID, ctx });+ expect(health.connectionError).toBeNull();+ expect(listAccess).not.toHaveBeenCalled();+ });- test("a chunk from a paid org is still accepted on its last known plan", async () => {- const { service } = build({- ...unreachable,- lastKnownPlan: { plan: { agentVaultByoS3: true }, fetchedAt: Date.now() - 10 * 60_000 }- });- await record(service);- expect(presignPut).toHaveBeenCalledTimes(1);+ test("is clear once storage answers", async () => {+ const { service } = build();+ const { health } = await service.getSessionLogHealth({ projectId: PROJECT_ID, ctx });+ expect(health.connectionError).toBeNull();+ expect(listAccess).toHaveBeenCalledTimes(1);});- test("a chunk is held, not refused, when there is no recent real answer", async () => {- const { service } = build({- ...unreachable,- lastKnownPlan: { plan: { agentVaultByoS3: true }, fetchedAt: Date.now() - 2 * 60 * 60_000 }- });- await expect(record(service)).rejects.toMatchObject({ name: "InternalServerError" });- expect(presignPut).not.toHaveBeenCalled();+ test.each([+ { why: "session logs are off", overrides: { config: { ...enabledConfig(), enabled: false } } },+ { why: "the plan doesn't include the storage", overrides: { plan: { hasExternal: false } } }+ ])("doesn't check storage while $why, since nothing is recorded", async ({ overrides }) => {+ const { service } = build(overrides);+ const { health } = await service.getSessionLogHealth({ projectId: PROJECT_ID, ctx });+ expect(health.connectionError).toBeNull();+ expect(listAccess).not.toHaveBeenCalled();});- test("a save that needs the plan says it couldn't be confirmed", async () => {- const { service, updateConfig } = build({ ...unreachable, config: { ...enabledConfig(), enabled: false } });- await expect(- service.updateSessionLogSettings({ projectId: PROJECT_ID, ctx, actor, enabled: true })- ).rejects.toThrow("Infisical couldn't confirm your plan right now. Try again in a few minutes.");- expect(updateConfig).not.toHaveBeenCalled();+ test("still checks while the plan can't be confirmed", async () => {+ const { service } = build({ plan: { hasExternal: false }, planFallback: true });+ await service.getSessionLogHealth({ projectId: PROJECT_ID, ctx });+ expect(listAccess).toHaveBeenCalledTimes(1);});- test("a page still reads as recording", async () => {- const { service } = build({ ...unreachable });- const page = await service.listSessionLogs({ projectId: PROJECT_ID, ctx, sessionId: SESSION_ID });- expect(page.sessionLogs.enabled).toBe(true);+ test("a failure that isn't from storage still answers, so health never becomes a 500", async () => {+ listAccess.mockRejectedValueOnce(new TypeError("a bug"));+ const { service } = build();+ const { health } = await service.getSessionLogHealth({ projectId: PROJECT_ID, ctx });+ expect(health.connectionError).toBe("Couldn't check the AWS connection. Try again.");});});-describe("getSessionLogHealth", () => {- test("reports a bucket the connection can't reach", async () => {- const unreachable =- "Unable to reach bucket 'my-bucket'. Check the bucket name, the region, and that the connection's credentials allow s3:ListBucket on it";- assertReachable.mockRejectedValueOnce(new BadRequestError({ message: unreachable }));- const { service } = build();- const { health } = await service.getSessionLogHealth({ projectId: PROJECT_ID, ctx: scope.ctx });- expect(health.connectionError).toBe(unreachable);+describe("getSessionLogCorsProbe", () => {+ test("default storage has nothing to probe", async () => {+ defaultStorage.configured = true;+ const { service } = build({ config: undefined });+ expect(await service.getSessionLogCorsProbe({ projectId: PROJECT_ID, ctx })).toEqual({ probe: null });+ expect(forOrg).not.toHaveBeenCalled();+ });++ test.each([+ { why: "session logs are off", overrides: { config: { ...enabledConfig(), enabled: false } } },+ { why: "the plan doesn't include the storage", overrides: { plan: { hasExternal: false } } }+ ])("has nothing to probe while $why, since nothing is shown", async ({ overrides }) => {+ const { service } = build(overrides);+ expect(await service.getSessionLogCorsProbe({ projectId: PROJECT_ID, ctx })).toEqual({ probe: null });+ expect(forOrg).not.toHaveBeenCalled();});- test("is clear once the connection works and the bucket answers", async () => {+ test("external storage gets a link to the probe file", async () => {const { service } = build();- const { health } = await service.getSessionLogHealth({ projectId: PROJECT_ID, ctx: scope.ctx });- expect(health.connectionError).toBeNull();- expect(assertReachable).toHaveBeenCalledTimes(1);+ expect(await service.getSessionLogCorsProbe({ projectId: PROJECT_ID, ctx })).toEqual({+ probe: { url: "https://bucket.s3.amazonaws.com/probe", expiresInSeconds: 300 }+ });});});diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.tsindex c9b14d06a3..30c48cd079 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts@@ -1,7 +1,5 @@-import { S3ServiceException } from "@aws-sdk/client-s3";import { ForbiddenError } from "@casl/ability";-import { TAgentVaultSessionLogConfigs } from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {ProjectPermissionAgentVaultSessionActions,@@ -20,8 +18,12 @@ import { TAppConnectionDALFactory } from "@app/services/app-connection/app-conneimport { AppConnection } from "@app/services/app-connection/app-connection-enums";import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { isDefaultStorageConfigured } from "@app/services/object-storage/object-storage-default-fns";+import { ObjectStorageError } from "@app/services/object-storage/object-storage-errors";+import { isS3DirectoryBucket } from "@app/services/object-storage/object-storage-path-fns";+import { TObjectStorageServiceFactory } from "@app/services/object-storage/object-storage-service";+import { ObjectStorageType } from "@app/services/object-storage/object-storage-types";-import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";import { getAgentVaultPermission } from "../agent-vault/agent-vault-permission";import { TAgentVaultProxyDALFactory } from "../agent-vault-proxy/agent-vault-proxy-dal";import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";@@ -35,33 +37,45 @@ import {AGENT_VAULT_SESSION_LOG_LATE_CHUNK_GRACE_MS,AGENT_VAULT_SESSION_LOG_MAX_CHUNK_AGE_MS,AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES,+ AGENT_VAULT_SESSION_LOG_MAX_PAGE_CHUNKS,AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS,AGENT_VAULT_SESSION_LOG_RANGE_MARGIN_MS,AGENT_VAULT_SESSION_LOG_STORAGE_NEEDS_ADMIN_MESSAGE,- AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE_MESSAGE,- AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN+ AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE_MESSAGE} from "./agent-vault-session-log-constants";+import { encodeHistoryCursor, encodeTailCursor, SESSION_LOG_FEED_START } from "./agent-vault-session-log-cursor-fns";import {AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE,AgentVaultSessionLogErrorName} from "./agent-vault-session-log-enums";import {- buildSessionLogFolder,- buildSessionLogObjectKey,+ AgentVaultSessionLogsNamespace,+ buildSessionLogObjectName,chunkIdTimeMs,- describeListFailure,- encodeHistoryCursor,- encodeTailCursor,- getSessionLogEntitlement,- isSessionLogIngestEnabled,parseSessionLogObjectKey,- resolveStorageConfig,- SESSION_LOG_FEED_START,- toRev,- TSessionLogLicenseService+ toRev} from "./agent-vault-session-log-fns";+import {+ getSessionLogEntitlement,+ getSessionLogNotOnPlanMessage,+ getSessionLogRetentionDays,+ TSessionLogLicenseService+} from "./agent-vault-session-log-license-fns";+import { TAgentVaultSessionLogDisabledReason } from "./agent-vault-session-log-schemas";import { unwrapSessionLogKey } from "./agent-vault-session-log-secrets";-import { buildSessionLogStorage, TAgentVaultSessionLogStorage } from "./agent-vault-session-log-storage-fns";+import {+ describeStorageFailure,+ getEffectiveSessionLogConfig,+ isSameSessionLogStorage,+ TEffectiveSessionLogConfig,+ toEffectiveSessionLogConfig,+ toSessionLogSettingsState,+ toSessionLogStorageColumns,+ toSessionLogStorageHttpError,+ toStorageConfig,+ TPreviousSessionLogStorage,+ TSessionLogStorage+} from "./agent-vault-session-log-storage-fns";import {TAgentVaultSessionLogScoped,TAgentVaultSessionScoped,@@ -72,19 +86,44 @@ import {} from "./agent-vault-session-log-types";type TAgentVaultSessionLogServiceFactoryDep = {- agentVaultSessionLogConfigDAL: TAgentVaultSessionLogConfigDALFactory;+ agentVaultSessionLogConfigDAL: Pick<+ TAgentVaultSessionLogConfigDALFactory,+ "findOne" | "findByProjectIdFromPrimary" | "upsert"+ >;agentVaultSessionDAL: Pick<TAgentVaultSessionDALFactory, "findOne">;agentVaultProxyDAL: Pick<TAgentVaultProxyDALFactory, "findByIdWithOrg">;appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey" | "decryptWithInputKey">;+ kmsService: Pick<TKmsServiceFactory, "unwrapKey">;licenseService: TSessionLogLicenseService;keyStore: Pick<TKeyStoreFactory, "streamAdd" | "streamRange">;+ objectStorage: Pick<TObjectStorageServiceFactory, "at">;};export type TAgentVaultSessionLogServiceFactory = ReturnType<typeof agentVaultSessionLogServiceFactory>;+const $openSessionLogLocation = async (+ objectStorage: TAgentVaultSessionLogServiceFactoryDep["objectStorage"],+ storage: TSessionLogStorage,+ orgId: string+) => {+ const location = await objectStorage.at(toStorageConfig(storage)).forOrg(orgId);+ return { bucket: location.bucket, namespace: location.namespace(AgentVaultSessionLogsNamespace) };+};++const $openSessionLogFolder = async (+ objectStorage: TAgentVaultSessionLogServiceFactoryDep["objectStorage"],+ storage: TSessionLogStorage,+ orgId: string,+ sessionId: string+) => {+ const { bucket, namespace } = await $openSessionLogLocation(objectStorage, storage, orgId);+ return { bucket, folder: namespace.folder({ sessionId }) };+};++type TSessionLogFolder = Awaited<ReturnType<typeof $openSessionLogFolder>>["folder"];+export const agentVaultSessionLogServiceFactory = ({agentVaultSessionLogConfigDAL,agentVaultSessionDAL,@@ -94,20 +133,9 @@ export const agentVaultSessionLogServiceFactory = ({permissionService,kmsService,licenseService,- keyStore+ keyStore,+ objectStorage}: TAgentVaultSessionLogServiceFactoryDep) => {- const $storageDeps = { appConnectionDAL, kmsService };-- const NO_SETTINGS = { enabled: false, appConnectionId: null, bucket: null, region: null, keyPrefix: null };-- const toSettingsView = (config: TAgentVaultSessionLogConfigs) => ({- enabled: config.enabled,- appConnectionId: config.appConnectionId ?? null,- bucket: config.bucket ?? null,- region: config.region ?? null,- keyPrefix: config.keyPrefix ?? null- });-const $requireAdmin = async ({ projectId, ctx }: TAgentVaultSessionLogScoped) => {const { isAdmin } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });if (!isAdmin) {@@ -117,6 +145,28 @@ export const agentVaultSessionLogServiceFactory = ({}};+ // The storage a save replaced, named for the audit log while its connection still exists.+ const $describePreviousStorage = async (storage: TSessionLogStorage): Promise<TPreviousSessionLogStorage> => {+ if (storage.type === ObjectStorageType.Default) {+ return {+ storageType: storage.type,+ appConnectionId: null,+ appConnectionName: null,+ bucket: null,+ region: null,+ keyPrefix: null+ };+ }+ return {+ storageType: storage.type,+ appConnectionId: storage.appConnectionId,+ appConnectionName: (await appConnectionDAL.findById(storage.appConnectionId))?.name ?? null,+ bucket: storage.bucket,+ region: storage.region,+ keyPrefix: storage.keyPrefix+ };+ };+const createChunkUploadUrl = async ({ proxyId, sessionId, chunk }: TCreateChunkUploadUrlDTO) => {// Older CLIs send the IV here instead of writing it into the object, so nothing they upload could be opened.if (chunk.iv !== undefined) {@@ -149,20 +199,21 @@ export const agentVaultSessionLogServiceFactory = ({throw new UnauthorizedError({ message: "Session ended too long ago to accept session logs" });}- const config = await agentVaultSessionLogConfigDAL.findByProjectIdFromPrimary(proxy.projectId);- const storage = resolveStorageConfig(config);- if (!config?.enabled || !storage) {+ const config = await getEffectiveSessionLogConfig({ agentVaultSessionLogConfigDAL }, proxy.projectId, {+ fromPrimary: true+ });+ if (!config?.enabled) {throw new BadRequestError({name: AgentVaultSessionLogErrorName.Disabled,message: "Session logs are disabled"});}- const entitlement = await getSessionLogEntitlement(licenseService, proxy.orgId);+ const { entitlement, plan } = await getSessionLogEntitlement(licenseService, proxy.orgId, config.storage.type);if (entitlement === "unlicensed") {throw new BadRequestError({name: AgentVaultSessionLogErrorName.Disabled,- message: AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN+ message: getSessionLogNotOnPlanMessage(config.storage.type)});}// A 5xx, so the proxy holds the chunk and retries instead of switching session logs off.@@ -192,44 +243,40 @@ export const agentVaultSessionLogServiceFactory = ({throw new BadRequestError({ message: "The chunk ID's time must match the chunk's endedAt" });}- let sessionLogStorage: TAgentVaultSessionLogStorage;+ let upload: { key: string; url: string };+ let bucket: string;try {- sessionLogStorage = await buildSessionLogStorage(storage, proxy.orgId, $storageDeps);+ const opened = await $openSessionLogFolder(objectStorage, config.storage, proxy.orgId, session.id);+ bucket = opened.bucket;+ upload = await opened.folder.presignPut({+ name: buildSessionLogObjectName({ proxyId, chunkId: chunk.chunkId }),+ bytes: chunk.ciphertextBytes,+ // The proxy sends it unpadded; S3 wants the padded form+ sha256Base64: `${chunk.ciphertextSha256}=`,+ expiresInSeconds: AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS,+ retentionDays: getSessionLogRetentionDays(plan)+ });} catch (error) {- // A 400 would read to the proxy as a malformed chunk to drop; a connection that can't be used is worth a retry.- // The detail can name the connection and AWS account, and whoever runs the proxy may not be an admin.- if (error instanceof BadRequestError || error instanceof InternalServerError) {- logger.warn(error, `agentVaultSessionLog: could not use the session log connection [proxyId=${proxyId}]`);- throw new InternalServerError({- message:- "Session logs can't use their AWS connection right now. An Agent Vault admin can check it in Settings."- });- }- throw error;+ // A 400 would read to the proxy as a malformed chunk to drop; storage that can't be used is worth a retry. The+ // detail can name the connection and AWS account, and whoever runs the proxy may not be an admin. The daily+ // cap's 429 passes through, and the proxy retries it the next minute.+ if (!(error instanceof ObjectStorageError)) throw error;+ logger.warn(error, `agentVaultSessionLog: could not use session log storage [proxyId=${proxyId}]`);+ throw new InternalServerError({+ message:+ config.storage.type === ObjectStorageType.Default+ ? "Session logs can't reach default storage right now. The proxy keeps the chunk and retries."+ : "Session logs can't use their AWS connection right now. An Agent Vault admin can check it in Settings."+ });}- const objectKey = buildSessionLogObjectKey({- folder: buildSessionLogFolder({- keyPrefix: storage.keyPrefix,- projectId: proxy.projectId,- sessionId: session.id- }),- proxyId,- chunkId: chunk.chunkId- });- const uploadUrl = await sessionLogStorage.presignPut({- objectKey,- ciphertextBytes: chunk.ciphertextBytes,- ciphertextSha256: chunk.ciphertextSha256- });-// Not awaited: the Redis client queues commands while Redis is down instead of failing, and an upload must// never wait on the live view. Started before returning, so the entry is sent ahead of the response.void keyStore.streamAdd(KeyStorePrefixes.AgentVaultSessionLogFeed(session.id),"*",- { key: objectKey, bucket: storage.bucket, bytes: String(chunk.ciphertextBytes) },+ { key: upload.key, bucket, bytes: String(chunk.ciphertextBytes) },AGENT_VAULT_SESSION_LOG_FEED_MAX_ENTRIES,AGENT_VAULT_SESSION_LOG_FEED_TTL_SECONDS,true@@ -240,8 +287,10 @@ export const agentVaultSessionLogServiceFactory = ({return {chunkId: chunk.chunkId,- uploadUrl,- expiresInSeconds: AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS+ uploadUrl: upload.url,+ expiresInSeconds: AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS,+ orgId: proxy.orgId,+ storageType: config.storage.type};};@@ -257,71 +306,54 @@ export const agentVaultSessionLogServiceFactory = ({throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });}- const config = await agentVaultSessionLogConfigDAL.findOne({ projectId });+ const config = await getEffectiveSessionLogConfig({ agentVaultSessionLogConfigDAL }, projectId, {+ fromPrimary: false+ });++ // Reads return no logs while session logs are off, or while the plan doesn't include the storage in use. Unlike+ // most paid features, which read from Infisical's database, each read here is a billed S3 request for whoever owns+ // the bucket, so reading needs the same plan as recording. While the License Server can't confirm the plan,+ // reading is still allowed, so an outage doesn't hide logs.+ let disabledReason: TAgentVaultSessionLogDisabledReason | null = null;+ if (!config?.enabled) disabledReason = "off";+ else if (+ (await getSessionLogEntitlement(licenseService, ctx.actorOrgId, config.storage.type)).entitlement === "unlicensed"+ ) {+ disabledReason = "not-on-plan";+ }+const sessionLogs = {- enabled:- isSessionLogIngestEnabled(config) &&- (await getSessionLogEntitlement(licenseService, ctx.actorOrgId)) !== "unlicensed",+ enabled: disabledReason === null,+ disabledReason,+ storageType: config?.storage.type ?? null,isRecordable: Boolean(session.encryptedSessionLogKey),sessionKey: null as string | null};- return { session, config, isAdmin, sessionLogs };+ return { session, config: disabledReason ? null : config, isAdmin, sessionLogs };};- type TLoadedSessionLogs = Awaited<ReturnType<typeof $loadSessionLogs>>;-- // A 500 when trying again later can help, a 400 when the settings or the AWS side need fixing.- const $storageUnavailable = ({- isAdmin,- adminMessage,- isTemporary = false- }: {- isAdmin: boolean;- adminMessage: string;- isTemporary?: boolean;- }) => {- let message = adminMessage;- if (!isAdmin) {- message = isTemporary+ // An external storage failure names the bucket and connection, so only admins see the cause. Default storage's+ // message is the same for everyone, since no org admin can fix it.+ const $toStorageUnavailable = (error: unknown, isAdmin: boolean, sessionId: string) => {+ if (!(error instanceof ObjectStorageError)) return error;+ logger.warn(error, `agentVaultSessionLog: could not read session logs [sessionId=${sessionId}]`);+ const { isTemporary, message } = describeStorageFailure(error, "read");+ let shownMessage = message;+ if (!isAdmin && error.storageType === ObjectStorageType.External) {+ shownMessage = isTemporary? AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE_MESSAGE: AGENT_VAULT_SESSION_LOG_STORAGE_NEEDS_ADMIN_MESSAGE;}- const error = { name: AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE, message };- return isTemporary ? new InternalServerError(error) : new BadRequestError(error);- };-- // Reading doesn't check the plan or whether session logs are on, so logs recorded before a downgrade or before they- // were turned off can still be read.- const $openStorage = async ({- ctx,- config,- isAdmin- }: Pick<TLoadedSessionLogs, "config" | "isAdmin"> & { ctx: TAgentVaultSessionScoped["ctx"] }) => {- const storage = resolveStorageConfig(config);- if (!storage) {- throw $storageUnavailable({- isAdmin,- adminMessage: "No AWS connection is set for session logs. Choose one in Settings."- });- }- try {- return {- storage: await buildSessionLogStorage(storage, ctx.actorOrgId, $storageDeps),- bucket: storage.bucket,- keyPrefix: storage.keyPrefix- };- } catch (error) {- if (error instanceof InternalServerError) {- throw $storageUnavailable({ isAdmin, adminMessage: error.message, isTemporary: true });- }- if (!(error instanceof BadRequestError)) throw error;- throw $storageUnavailable({ isAdmin, adminMessage: error.message });- }+ return toSessionLogStorageHttpError({+ isTemporary,+ message: shownMessage,+ name: AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE+ });};const $presignChunks = async (keyScope: { projectId: string; sessionId: string; encryptedSessionLogKey: Buffer },- storage: TAgentVaultSessionLogStorage,+ folder: TSessionLogFolder,found: { key: string; chunkId: string; proxyId: string; ciphertextBytes: number }[]) => {const chunks = await Promise.all(@@ -329,18 +361,13 @@ export const agentVaultSessionLogServiceFactory = ({chunkId,proxyId,ciphertextBytes,- presignedGetUrl: await storage.presignGet(key)+ presignedGetUrl: await folder.presignGet(key, AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS)})));const sessionKey = await unwrapSessionLogKey(keyScope, kmsService);return { chunks, sessionKey: sessionKey.toString("base64") };};- // S3 errors, network failures and replies S3's client couldn't parse; anything else is a bug and stays a 500.- const isStorageError = (error: unknown) =>- error instanceof S3ServiceException ||- (error instanceof Error && ("code" in error || "$metadata" in error || error.name === "TimeoutError"));-const listSessionLogs = async ({ cursor, from, to, ...scope }: TListSessionLogsDTO) => {if (from && to && from > to) {throw new BadRequestError({ message: "The 'from' time must be before the 'to' time" });@@ -349,60 +376,53 @@ export const agentVaultSessionLogServiceFactory = ({const { session, config, isAdmin, sessionLogs } = await $loadSessionLogs(scope);if (!config || !session.encryptedSessionLogKey) return { sessionLogs, chunks: [], nextCursor: null };- const opened = await $openStorage({ ctx: scope.ctx, config, isAdmin });-- // The stored id, not the route's: Postgres matches a uuid in any case, but S3 keys and the key's scope don't.- const folder = buildSessionLogFolder({- keyPrefix: opened.keyPrefix,- projectId: scope.projectId,- sessionId: session.id- });- let startAfter: string | undefined;- if (cursor !== undefined) startAfter = `${folder}${cursor}`;- else if (to) startAfter = `${folder}${toRev(to.getTime() + AGENT_VAULT_SESSION_LOG_RANGE_MARGIN_MS)}`;-- let listed: Awaited<ReturnType<TAgentVaultSessionLogStorage["listChunks"]>>;try {- listed = await opened.storage.listChunks({ folder, startAfter });- } catch (error) {- if (!isStorageError(error)) throw error;- logger.warn(error, `agentVaultSessionLog: could not list session logs [sessionId=${session.id}]`);- const failure = describeListFailure(error as Error, opened.bucket);- throw $storageUnavailable({ isAdmin, adminMessage: failure.message, isTemporary: failure.isTemporary });- }-- const found: Parameters<typeof $presignChunks>[2] = [];- let pageBytes = 0;- let consumed = 0;- let isBeforeRange = false;- for (const object of listed.objects) {- if (found.length && pageBytes + object.size > AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES) break;- const parsed = parseSessionLogObjectKey(folder, object.key);- if (parsed && from && parsed.lastRecordAt < from) {- isBeforeRange = true;- break;- }- consumed += 1;- if (parsed) {- found.push({ ...parsed, key: object.key, ciphertextBytes: object.size });- pageBytes += object.size;+ // The stored id, not the route's: Postgres matches a uuid in any case, but S3 keys and the key's scope don't.+ const { folder } = await $openSessionLogFolder(objectStorage, config.storage, scope.ctx.actorOrgId, session.id);++ let startAfter: string | undefined;+ if (cursor !== undefined) startAfter = `${folder.prefix}${cursor}`;+ else if (to) startAfter = `${folder.prefix}${toRev(to.getTime() + AGENT_VAULT_SESSION_LOG_RANGE_MARGIN_MS)}`;++ const listed = await folder.list({ startAfter, maxKeys: AGENT_VAULT_SESSION_LOG_MAX_PAGE_CHUNKS });++ const found: Parameters<typeof $presignChunks>[2] = [];+ let pageBytes = 0;+ let consumed = 0;+ let isBeforeRange = false;+ for (const object of listed.objects) {+ if (found.length && pageBytes + object.size > AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES) break;+ const parsed = parseSessionLogObjectKey(folder.prefix, object.key);+ if (parsed && from && parsed.lastRecordAt < from) {+ isBeforeRange = true;+ break;+ }+ consumed += 1;+ if (parsed) {+ found.push({ ...parsed, key: object.key, ciphertextBytes: object.size });+ pageBytes += object.size;+ }}- }- const hasMore = !isBeforeRange && consumed > 0 && (consumed < listed.objects.length || listed.isTruncated);- const nextCursor = hasMore ? encodeHistoryCursor(listed.objects[consumed - 1].key.slice(folder.length)) : null;- if (!found.length) return { sessionLogs, chunks: [], nextCursor };-- const { chunks, sessionKey } = await $presignChunks(- {- projectId: scope.projectId,- sessionId: session.id,- encryptedSessionLogKey: session.encryptedSessionLogKey- },- opened.storage,- found- );- return { sessionLogs: { ...sessionLogs, sessionKey }, chunks, nextCursor };+ const hasMore = !isBeforeRange && consumed > 0 && (consumed < listed.objects.length || listed.isTruncated);+ const nextCursor = hasMore+ ? encodeHistoryCursor(listed.objects[consumed - 1].key.slice(folder.prefix.length))+ : null;+ if (!found.length) return { sessionLogs, chunks: [], nextCursor };++ const { chunks, sessionKey } = await $presignChunks(+ {+ projectId: scope.projectId,+ sessionId: session.id,+ encryptedSessionLogKey: session.encryptedSessionLogKey+ },+ folder,+ found+ );+ return { sessionLogs: { ...sessionLogs, sessionKey }, chunks, nextCursor };+ } catch (error) {+ throw $toStorageUnavailable(error, isAdmin, session.id);+ }};const tailSessionLogs = async ({ cursor = SESSION_LOG_FEED_START, ...scope }: TTailSessionLogsDTO) => {@@ -419,65 +439,78 @@ export const agentVaultSessionLogServiceFactory = ({// Fails rather than advancing, so the caller's cursor stays put and a short outage loses nothing. After a longer// one the feed has moved on, and the chunks show on the next full read.- const opened = await $openStorage({ ctx: scope.ctx, config, isAdmin });+ try {+ const { bucket, folder } = await $openSessionLogFolder(+ objectStorage,+ config.storage,+ scope.ctx.actorOrgId,+ session.id+ );- const folder = buildSessionLogFolder({- keyPrefix: opened.keyPrefix,- projectId: scope.projectId,- sessionId: session.id- });- // Every entry, repeats included: the browser reads a full feed from the count, and dedupes by chunk itself.- const found: Parameters<typeof $presignChunks>[2] = [];- entries.forEach(([, fieldValues]) => {- const fields = new Map<string, string>();- for (let i = 0; i + 1 < fieldValues.length; i += 2) fields.set(fieldValues[i], fieldValues[i + 1]);- const key = fields.get("key");- if (!key || fields.get("bucket") !== opened.bucket) return;- const parsed = parseSessionLogObjectKey(folder, key);- const ciphertextBytes = Number(fields.get("bytes"));- if (parsed && Number.isSafeInteger(ciphertextBytes)) found.push({ ...parsed, key, ciphertextBytes });- });+ // Every entry, repeats included: the browser reads a full feed from the count, and dedupes by chunk itself.+ // Entries from another bucket or folder are from before a storage change, and reads only show current storage.+ const found: Parameters<typeof $presignChunks>[2] = [];+ entries.forEach(([, fieldValues]) => {+ const fields = new Map<string, string>();+ for (let i = 0; i + 1 < fieldValues.length; i += 2) fields.set(fieldValues[i], fieldValues[i + 1]);+ const key = fields.get("key");+ if (!key || fields.get("bucket") !== bucket) return;+ const parsed = parseSessionLogObjectKey(folder.prefix, key);+ const ciphertextBytes = Number(fields.get("bytes"));+ if (parsed && Number.isSafeInteger(ciphertextBytes)) found.push({ ...parsed, key, ciphertextBytes });+ });- const nextCursor = encodeTailCursor(entries[entries.length - 1][0]);- if (!found.length) return { sessionLogs, chunks: [], nextCursor };-- const { chunks, sessionKey } = await $presignChunks(- {- projectId: scope.projectId,- sessionId: session.id,- encryptedSessionLogKey: session.encryptedSessionLogKey- },- opened.storage,- found- );- return { sessionLogs: { ...sessionLogs, sessionKey }, chunks, nextCursor };+ const nextCursor = encodeTailCursor(entries[entries.length - 1][0]);+ if (!found.length) return { sessionLogs, chunks: [], nextCursor };++ const { chunks, sessionKey } = await $presignChunks(+ {+ projectId: scope.projectId,+ sessionId: session.id,+ encryptedSessionLogKey: session.encryptedSessionLogKey+ },+ folder,+ found+ );+ return { sessionLogs: { ...sessionLogs, sessionKey }, chunks, nextCursor };+ } catch (error) {+ throw $toStorageUnavailable(error, isAdmin, session.id);+ }};const getSessionLogSettings = async ({ projectId, ctx }: TAgentVaultSessionLogScoped) => {await $requireAdmin({ projectId, ctx });- const config = await agentVaultSessionLogConfigDAL.findOne({ projectId });- return {- settings: config ? toSettingsView(config) : NO_SETTINGS- };+ return toSessionLogSettingsState(+ await getEffectiveSessionLogConfig({ agentVaultSessionLogConfigDAL }, projectId, { fromPrimary: false })+ );};+ // Health and the CORS probe only run for external storage that's on and on the plan, or whose plan can't be confirmed+ // right now. Otherwise nothing is recorded or shown, so a storage problem isn't something an admin needs to fix.+ // Default storage belongs to whoever runs the instance, so its problems are logged at boot and never shown to an org.+ const $isExternalStorageInUse = async (config: TEffectiveSessionLogConfig, orgId: string) =>+ config.storage.type === ObjectStorageType.External &&+ config.enabled &&+ (await getSessionLogEntitlement(licenseService, orgId, config.storage.type)).entitlement !== "unlicensed";+const getSessionLogHealth = async ({ projectId, ctx }: TAgentVaultSessionLogScoped) => {await $requireAdmin({ projectId, ctx });- const config = await agentVaultSessionLogConfigDAL.findOne({ projectId });- const storage = resolveStorageConfig(config);+ const config = await getEffectiveSessionLogConfig({ agentVaultSessionLogConfigDAL }, projectId, {+ fromPrimary: false+ });let connectionError: string | null = null;- if (storage) {+ if (config && (await $isExternalStorageInUse(config, ctx.actorOrgId))) {try {- const sessionLogStorage = await buildSessionLogStorage(storage, ctx.actorOrgId, $storageDeps);- await sessionLogStorage.assertReachable();+ const { namespace } = await $openSessionLogLocation(objectStorage, config.storage, ctx.actorOrgId);+ await namespace.listAccess();} catch (error) {- logger.warn(error, `agentVaultSessionLog: could not use the session log connection [projectId=${projectId}]`);+ logger.warn(error, `agentVaultSessionLog: session log storage check failed [projectId=${projectId}]`);connectionError =- error instanceof BadRequestError || error instanceof InternalServerError- ? error.message+ error instanceof ObjectStorageError+ ? describeStorageFailure(error, "check").message: "Couldn't check the AWS connection. Try again.";}}@@ -492,116 +525,111 @@ export const agentVaultSessionLogServiceFactory = ({const getSessionLogCorsProbe = async ({ projectId, ctx }: TAgentVaultSessionLogScoped) => {await $requireAdmin({ projectId, ctx });- const config = await agentVaultSessionLogConfigDAL.findOne({ projectId });- const storage = resolveStorageConfig(config);- if (!storage) return { probe: null };+ const config = await getEffectiveSessionLogConfig({ agentVaultSessionLogConfigDAL }, projectId, {+ fromPrimary: false+ });+ if (!config || !(await $isExternalStorageInUse(config, ctx.actorOrgId))) return { probe: null };- const sessionLogStorage = await buildSessionLogStorage(storage, ctx.actorOrgId, $storageDeps);- return {- probe: {- url: await sessionLogStorage.mintCorsProbeUrl(),- expiresInSeconds: AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS- }- };+ try {+ const { namespace } = await $openSessionLogLocation(objectStorage, config.storage, ctx.actorOrgId);+ return {+ probe: {+ url: await namespace.presignCorsProbe(AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS),+ expiresInSeconds: AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS+ }+ };+ } catch (error) {+ if (!(error instanceof ObjectStorageError)) throw error;+ throw toSessionLogStorageHttpError(describeStorageFailure(error, "check"));+ }};- const updateSessionLogSettings = async ({ projectId, ctx, actor, ...patch }: TUpdateSessionLogSettingsDTO) => {+ const updateSessionLogSettings = async ({ projectId, ctx, actor, ...body }: TUpdateSessionLogSettingsDTO) => {await $requireAdmin({ projectId, ctx });- const existing = await agentVaultSessionLogConfigDAL.findByProjectIdFromPrimary(projectId);- const current = existing ?? NO_SETTINGS;-- const next = {- enabled: patch.enabled ?? current.enabled,- appConnectionId: patch.appConnectionId === undefined ? (current.appConnectionId ?? null) : patch.appConnectionId,- bucket: patch.bucket ?? current.bucket ?? null,- region: patch.region ?? current.region ?? null,- keyPrefix: patch.keyPrefix === undefined ? (current.keyPrefix ?? null) : patch.keyPrefix || null- };+ const current = await getEffectiveSessionLogConfig({ agentVaultSessionLogConfigDAL }, projectId, {+ fromPrimary: true+ });- // Turning off and removing the connection stay open without the plan: the config's foreign key would- // otherwise block deleting a connection the customer can no longer use.- const needsLicence =- (next.enabled && !current.enabled) ||- next.bucket !== (current.bucket ?? null) ||- next.region !== (current.region ?? null) ||- next.keyPrefix !== (current.keyPrefix ?? null) ||- (next.appConnectionId !== null && next.appConnectionId !== (current.appConnectionId ?? null));- // Only on a change, so a saved directory bucket can still be turned off.- if (next.bucket !== (current.bucket ?? null) && next.bucket?.endsWith("--x-s3")) {- throw new BadRequestError({- message:- "Session logs need a general purpose S3 bucket. Directory buckets (names ending in --x-s3) aren't supported."- });+ // Turning off forgets the storage, which frees an AWS connection to be deleted. The row stays, saying off: with+ // nothing saved, session logs are on in default storage. Turning off is never gated by the plan.+ if (!body.enabled) {+ const [saved] = await agentVaultSessionLogConfigDAL.upsert(+ [{ projectId, enabled: false, ...toSessionLogStorageColumns({ type: ObjectStorageType.Default }) }],+ "projectId"+ );+ const previous = current?.enabled ? await $describePreviousStorage(current.storage) : null;+ return {+ ...toSessionLogSettingsState(toEffectiveSessionLogConfig(saved, isDefaultStorageConfigured())),+ appConnectionName: null,+ previous+ };}- const entitlement = needsLicence ? await getSessionLogEntitlement(licenseService, ctx.actorOrgId) : "licensed";- if (entitlement === "unknown") {- throw new BadRequestError({- message: "Infisical couldn't confirm your plan right now. Try again in a few minutes."- });+ const nextStorage: TSessionLogStorage =+ body.storage.type === ObjectStorageType.External+ ? { ...body.storage, keyPrefix: body.storage.keyPrefix || null }+ : { type: ObjectStorageType.Default };+ if (nextStorage.type === ObjectStorageType.Default && !isDefaultStorageConfigured()) {+ throw new BadRequestError({ message: "This instance doesn't offer default storage" });}- if (entitlement === "unlicensed") {- throw new BadRequestError({ message: AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN });- }-- // Any new use of the connection is revalidated, destination changes included, or an admin who may not use- // it could point it at their own bucket. Never on turn-off: that must work even with a broken connection.- const usesConnectionAnew =- next.appConnectionId !== current.appConnectionId ||- next.bucket !== (current.bucket ?? null) ||- next.region !== (current.region ?? null) ||- next.keyPrefix !== (current.keyPrefix ?? null) ||- (next.enabled && !current.enabled);- const validatedConnection =- next.appConnectionId && usesConnectionAnew- ? await appConnectionService.validateAppConnectionUsageById(- AppConnection.AWS,- { connectionId: next.appConnectionId, projectId },- actor- )- : null;- if (next.enabled) {- if (!next.appConnectionId && current.enabled && current.appConnectionId) {- throw new BadRequestError({ message: "Turn off session logs before removing their AWS connection." });- }- const missing = (- [- ["appConnectionId", "an AWS connection"],- ["bucket", "a bucket"],- ["region", "a region"]- ] as const- )- .filter(([field]) => !next[field])- .map(([, label]) => label);- if (missing.length) {- throw new BadRequestError({- message: `Session logs need ${missing.join(", ").replace(/, ([^,]*)$/, " and $1")}.`+ // Choosing, changing or turning on a storage needs that storage on the plan.+ const isStorageChange = !isSameSessionLogStorage(nextStorage, current?.storage);+ const isTurningOn = !(current?.isSaved && current.enabled);+ if (isStorageChange || isTurningOn) {+ const { entitlement } = await getSessionLogEntitlement(licenseService, ctx.actorOrgId, nextStorage.type);+ if (entitlement === "unknown") {+ throw new InternalServerError({+ message: "Infisical couldn't confirm your plan right now. Try again in a few minutes."});}+ if (entitlement === "unlicensed")+ throw new BadRequestError({ message: getSessionLogNotOnPlanMessage(nextStorage.type) });}- const storage = next.enabled ? resolveStorageConfig(next) : null;- const sessionLogStorage = storage ? await buildSessionLogStorage(storage, ctx.actorOrgId, $storageDeps) : null;- if (sessionLogStorage) await sessionLogStorage.validate();-- const values = { ...next, projectId };+ let validatedConnection: { name: string } | null = null;+ if (nextStorage.type === ObjectStorageType.External) {+ const currentExternal = current?.storage.type === ObjectStorageType.External ? current.storage : null;+ // Only when the bucket changes, so settings that already hold a directory bucket can still be saved.+ if (nextStorage.bucket !== currentExternal?.bucket && isS3DirectoryBucket(nextStorage.bucket)) {+ throw new BadRequestError({+ message:+ "Session logs need a general purpose S3 bucket. Directory buckets (names ending in --x-s3) aren't supported."+ });+ }- let saved: TAgentVaultSessionLogConfigs;- if (existing) {- saved = await agentVaultSessionLogConfigDAL.updateById(existing.id, values);- } else {- try {- saved = await agentVaultSessionLogConfigDAL.create(values);- } catch (err) {- if (isUniqueViolation(err)) {- throw new BadRequestError({ message: "Session log settings were just changed. Reload and try again." });+ // Any new use of the connection is revalidated, destination changes included, or an admin who may not use it+ // could point it at their own bucket.+ const usesConnectionAnew = isStorageChange || !current?.enabled;+ if (usesConnectionAnew) {+ validatedConnection = await appConnectionService.validateAppConnectionUsageById(+ AppConnection.AWS,+ { connectionId: nextStorage.appConnectionId, projectId },+ actor+ );++ try {+ const { namespace } = await $openSessionLogLocation(objectStorage, nextStorage, ctx.actorOrgId);+ await namespace.check();+ } catch (error) {+ if (!(error instanceof ObjectStorageError)) throw error;+ logger.warn(error, `agentVaultSessionLog: session log bucket check failed [projectId=${projectId}]`);+ throw toSessionLogStorageHttpError(describeStorageFailure(error, "check"));}- throw err;}}+ // Only storage that was on counts as replaced: an off row holds default columns but no storage.+ const previous = isStorageChange && current?.enabled ? await $describePreviousStorage(current.storage) : null;++ // An upsert, not a create or update chosen from the effective settings: a saved default row on an instance that+ // lost its bucket has no effective settings but still holds the project's unique row.+ const [saved] = await agentVaultSessionLogConfigDAL.upsert(+ [{ projectId, enabled: true, ...toSessionLogStorageColumns(nextStorage) }],+ "projectId"+ );+let appConnectionName: string | null = null;if (validatedConnection) {appConnectionName = validatedConnection.name;@@ -609,7 +637,11 @@ export const agentVaultSessionLogServiceFactory = ({appConnectionName = (await appConnectionDAL.findById(saved.appConnectionId))?.name ?? null;}- return { settings: toSettingsView(saved), appConnectionName };+ return {+ ...toSessionLogSettingsState(toEffectiveSessionLogConfig(saved, isDefaultStorageConfigured())),+ appConnectionName,+ previous+ };};return {diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns.test.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns.test.tsindex 5dad4370fe..9e3fb3cce2 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns.test.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns.test.ts@@ -1,126 +1,309 @@-import { STSServiceException } from "@aws-sdk/client-sts";-import { describe, expect, test, vi } from "vitest";--import { ProjectType } from "@app/db/schemas";-import { AppConnection, AWSRegion } from "@app/services/app-connection/app-connection-enums";-import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-fns";--import { buildSessionLogStorage } from "./agent-vault-session-log-storage-fns";--vi.mock("@app/lib/logger", () => ({- logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }-}));-vi.mock("@app/services/app-connection/app-connection-fns", () => ({- decryptAppConnection: vi.fn(async (raw: unknown) => raw)-}));-vi.mock("@app/services/app-connection/aws/aws-connection-fns", () => ({- getAwsConnectionConfig: vi.fn()-}));-vi.mock("@app/lib/aws/s3", async (importOriginal) => ({- ...(await importOriginal<typeof import("@app/lib/aws/s3")>()),- createS3Bucket: vi.fn(() => ({}))-}));--describe("buildSessionLogStorage", () => {- const config = { appConnectionId: "conn-1", bucket: "logs", region: AWSRegion.US_EAST_1, keyPrefix: null };- const deps = {- appConnectionDAL: {- findById: vi.fn(async () => ({ id: "conn-1", name: "prod-logs", orgId: "org-1", app: AppConnection.AWS }))- },- kmsService: {}- } as unknown as Parameters<typeof buildSessionLogStorage>[2];-- test("says which connection could not be used and what AWS said", async () => {- vi.mocked(getAwsConnectionConfig).mockRejectedValueOnce(- new STSServiceException({- name: "AccessDenied",- $fault: "client",- $metadata: { httpStatusCode: 403 },- message: "User is not authorized to perform: sts:AssumeRole"- })- );- await expect(buildSessionLogStorage(config, "org-1", deps)).rejects.toMatchObject({- name: "BadRequest",- message:- "Couldn't use the AWS connection 'prod-logs' for session logs: User is not authorized to perform: sts:AssumeRole"+import { S3ServiceException } from "@aws-sdk/client-s3";+import { beforeEach, describe, expect, test, vi } from "vitest";++import { AWSRegion } from "@app/services/app-connection/app-connection-enums";+import { ObjectStorageError, toObjectStorageError } from "@app/services/object-storage/object-storage-errors";+import { ObjectStorageErrorReason, ObjectStorageType } from "@app/services/object-storage/object-storage-types";++import {+ AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_UNAVAILABLE_MESSAGE,+ AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_UNAVAILABLE_SELF_HOSTED_MESSAGE+} from "./agent-vault-session-log-constants";+import {+ buildSessionLogSettingsAuditMetadata,+ describeStorageFailure,+ toEffectiveSessionLogConfig+} from "./agent-vault-session-log-storage-fns";++const instance = vi.hoisted(() => ({ isCloud: true }));+vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isCloud: instance.isCloud }) }));++beforeEach(() => {+ instance.isCloud = true;+});++describe("toEffectiveSessionLogConfig", () => {+ const external = {+ enabled: true,+ storageType: "external",+ appConnectionId: "conn-1",+ bucket: "my-bucket",+ region: AWSRegion.US_EAST_1 as string,+ keyPrefix: "logs"+ };+ const savedDefault = {+ enabled: false,+ storageType: "default",+ appConnectionId: null,+ bucket: null,+ region: null,+ keyPrefix: null+ };++ test("a saved external row is used as it is, with or without an instance bucket", () => {+ const expected = {+ enabled: true,+ isSaved: true,+ storage: {+ type: ObjectStorageType.External,+ appConnectionId: "conn-1",+ bucket: "my-bucket",+ region: AWSRegion.US_EAST_1,+ keyPrefix: "logs"+ }+ };+ expect(toEffectiveSessionLogConfig(external, true)).toEqual(expected);+ expect(toEffectiveSessionLogConfig(external, false)).toEqual(expected);+ });++ test("an empty key prefix reads as none", () => {+ const config = toEffectiveSessionLogConfig({ ...external, keyPrefix: "" }, false);+ expect(config?.storage).toMatchObject({ keyPrefix: null });+ });++ test("with nothing saved and an instance bucket, session logs are on in default storage", () => {+ expect(toEffectiveSessionLogConfig(undefined, true)).toEqual({+ enabled: true,+ isSaved: false,+ storage: { type: ObjectStorageType.Default }+ });+ });++ test("a saved default row keeps its on or off", () => {+ expect(toEffectiveSessionLogConfig(savedDefault, true)).toEqual({+ enabled: false,+ isSaved: true,+ storage: { type: ObjectStorageType.Default }});+ expect(toEffectiveSessionLogConfig({ ...savedDefault, enabled: true }, true)?.enabled).toBe(true);});+ test("without an instance bucket, nothing saved and a saved default both mean no settings", () => {+ expect(toEffectiveSessionLogConfig(undefined, false)).toBeNull();+ expect(toEffectiveSessionLogConfig({ ...savedDefault, enabled: true }, false)).toBeNull();+ });++ test.each(["appConnectionId", "bucket", "region"] as const)(+ "an external row missing its %s reads as off in default storage",+ (field) => {+ expect(toEffectiveSessionLogConfig({ ...external, [field]: null }, true)).toEqual({+ enabled: false,+ isSaved: true,+ storage: { type: ObjectStorageType.Default }+ });+ expect(toEffectiveSessionLogConfig({ ...external, [field]: null }, false)).toBeNull();+ }+ );+});++describe("describeStorageFailure", () => {+ const s3Error = (name: string, fault: "client" | "server" = "client") =>+ new S3ServiceException({ name, $fault: fault, $metadata: {}, message: name });+ const networkError = (code: string) => Object.assign(new Error(`connect ${code}`), { code });+ const external = (error: Error, step?: "list" | "write") =>+ toObjectStorageError(error, {+ storageType: ObjectStorageType.External,+ bucket: "my-bucket",+ region: "us-east-1",+ step+ }) as ObjectStorageError;+test.each([+ { error: s3Error("InvalidAccessKeyId"), isTemporary: false, hint: "Check the AWS connection's credentials." },+ { error: s3Error("ExpiredToken"), isTemporary: false, hint: "Check the AWS connection's credentials." },{- why: "AWS throttles the call",- error: new STSServiceException({- name: "Throttling",- $fault: "client",- $metadata: { httpStatusCode: 400 },- message: "Rate exceeded"- })+ error: s3Error("AccessDenied"),+ isTemporary: false,+ hint: "Check that the connection's credentials allow s3:ListBucket on it."},- { why: "the network drops it", error: Object.assign(new Error("connect ETIMEDOUT"), { code: "ETIMEDOUT" }) }- ])("is a 500 to try again when $why", async ({ error }) => {- vi.mocked(getAwsConnectionConfig).mockRejectedValueOnce(error);- await expect(buildSessionLogStorage(config, "org-1", deps)).rejects.toMatchObject({- name: "InternalServerError",- message: "Couldn't reach AWS to use the connection 'prod-logs' for session logs. Try again in a bit."- });+ { error: s3Error("NoSuchBucket"), isTemporary: false, hint: "Check the bucket name and region in Settings." },+ { error: s3Error("PermanentRedirect"), isTemporary: false, hint: "Check the bucket name and region in Settings." },+ { error: s3Error("SlowDown"), isTemporary: true, hint: "S3 isn't responding. Try again in a bit." },+ { error: s3Error("SomethingNew", "server"), isTemporary: true, hint: "S3 isn't responding. Try again in a bit." },+ {+ error: Object.assign(new Error("timed out"), { name: "TimeoutError" }),+ isTemporary: true,+ hint: "S3 isn't responding. Try again in a bit."+ },+ { error: networkError("ECONNREFUSED"), isTemporary: true, hint: "S3 isn't responding. Try again in a bit." },+ {+ error: Object.assign(new Error("XML parse error"), { $metadata: { httpStatusCode: 429 } }),+ isTemporary: true,+ hint: "S3 isn't responding. Try again in a bit."+ },+ {+ error: Object.assign(new Error("XML parse error"), { $metadata: { httpStatusCode: 200 } }),+ isTemporary: true,+ hint: "S3 isn't responding. Try again in a bit."+ },+ {+ error: Object.assign(new Error("XML parse error"), { $metadata: { httpStatusCode: 403 } }),+ isTemporary: false,+ hint: "Check the AWS connection and the bucket settings."+ },+ { error: s3Error("SomethingNew"), isTemporary: false, hint: "Check the AWS connection and the bucket settings." }+ ])("a read failing with $error.name ($error.message) is temporary: $isTemporary", ({ error, isTemporary, hint }) => {+ const failure = describeStorageFailure(external(error, "list"), "read");+ expect(failure.isTemporary).toBe(isTemporary);+ expect(failure.message.startsWith("Infisical couldn't list session logs in bucket 'my-bucket' (")).toBe(true);+ expect(failure.message.endsWith(hint)).toBe(true);});- test("assumes the role with Agent Vault's External ID and timeouts, for its own connections too", async () => {- vi.mocked(getAwsConnectionConfig).mockClear();- vi.mocked(getAwsConnectionConfig).mockResolvedValueOnce({- region: AWSRegion.US_EAST_1,- credentials: { accessKeyId: "access-key", secretAccessKey: "secret-key", sessionToken: undefined }- });- vi.mocked(deps.appConnectionDAL.findById).mockResolvedValueOnce({- id: "conn-1",- name: "av-logs",- orgId: "org-1",- projectId: "av-proj",- app: AppConnection.AWS- } as never);- await buildSessionLogStorage(config, "org-1", deps);- expect(getAwsConnectionConfig).toHaveBeenCalledWith(- expect.objectContaining({ projectType: ProjectType.AgentVault }),- config.region,- { stsRequestHandler: { connectionTimeout: 5_000, requestTimeout: 15_000, throwOnRequestTimeout: true } }- );+ test("a reply S3's client couldn't parse is labelled by its status", () => {+ const error = Object.assign(new Error("XML parse error"), { $metadata: { httpStatusCode: 429 } });+ expect(describeStorageFailure(external(error), "read").message).toContain("(HTTP 429)");+ });++ test("a network error is labelled by its code, not its generic name", () => {+ expect(describeStorageFailure(external(networkError("ENOTFOUND")), "read").message).toContain("(ENOTFOUND)");});- test("keeps anything that is not from AWS out of the message", async () => {- vi.mocked(getAwsConnectionConfig).mockRejectedValueOnce(new Error("kms_keys row missing"));- await expect(buildSessionLogStorage(config, "org-1", deps)).rejects.toMatchObject({- message: "Couldn't use the AWS connection 'prod-logs' for session logs: Infisical could not load its credentials"+ test("a bucket check that S3 answers with a temporary error is worth a retry, not an IAM change", () => {+ expect(describeStorageFailure(external(s3Error("SlowDown", "server"), "list"), "check")).toEqual({+ isTemporary: true,+ message: "Couldn't reach bucket 'my-bucket' just now. Try again in a bit."});});test.each([- { why: "no longer exists", row: undefined },+ { step: "list" as const, message: "Unable to reach bucket 'my-bucket'" },+ { step: "write" as const, message: "Grant s3:PutObject on the configured key prefix" }+ ])("a bucket check failing at the $step step says what to fix", ({ step, message }) => {+ const failure = describeStorageFailure(external(s3Error("AccessDenied"), step), "check");+ expect(failure.isTemporary).toBe(false);+ expect(failure.message).toContain(message);+ });++ const connectionError = (+ details: ObjectStorageError["details"],+ reason = ObjectStorageErrorReason.ConnectionInvalid+ ) => new ObjectStorageError({ reason, storageType: ObjectStorageType.External, details });++ test.each([+ {+ why: "a missing connection",+ error: connectionError({ isConnectionMissing: true }),+ message: "The AWS connection used for session logs no longer exists. Choose another on the Settings page.",+ isTemporary: false+ },+ {+ why: "a connection that isn't AWS",+ error: connectionError({ connectionName: "gh", connectionApp: "github" }),+ message: "The connection used for session logs is a github connection. Session logs require an AWS connection",+ isTemporary: false+ },+ {+ why: "a role AWS refused",+ error: connectionError({ connectionName: "aws-prod", cause: "Not authorized to perform sts:AssumeRole" }),+ message: "Couldn't use the AWS connection 'aws-prod' for session logs: Not authorized to perform sts:AssumeRole",+ isTemporary: false+ },{- why: "belongs to another organization",- row: { id: "conn-1", name: "theirs", orgId: "org-2", app: AppConnection.AWS }+ why: "AWS not answering",+ error: connectionError({ connectionName: "aws-prod" }, ObjectStorageErrorReason.Temporary),+ message: "Couldn't reach AWS to use the connection 'aws-prod' for session logs. Try again in a bit.",+ isTemporary: true}- ])("treats a connection that $why as missing", async ({ row }) => {- vi.mocked(getAwsConnectionConfig).mockClear();- vi.mocked(deps.appConnectionDAL.findById).mockResolvedValueOnce(row as never);- await expect(buildSessionLogStorage(config, "org-1", deps)).rejects.toMatchObject({- name: "BadRequest",- message: "The AWS connection used for session logs no longer exists. Choose another on the Settings page."+ ])("names $why", ({ error, message, isTemporary }) => {+ expect(describeStorageFailure(error, "read")).toEqual({ message, isTemporary });+ expect(describeStorageFailure(error, "check")).toEqual({ message, isTemporary });+ });++ test("default storage gets the generic message, never its bucket, and is always worth a retry", () => {+ const error = toObjectStorageError(s3Error("AccessDenied"), {+ storageType: ObjectStorageType.Default,+ bucket: "instance-bucket",+ region: "us-east-1"+ }) as ObjectStorageError;+ for (const use of ["read", "check"] as const) {+ const failure = describeStorageFailure(error, use);+ expect(failure).toEqual({+ isTemporary: true,+ message: AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_UNAVAILABLE_MESSAGE+ });+ }+ });++ test("on a self-hosted instance, default storage problems point at the server administrator", () => {+ instance.isCloud = false;+ const error = toObjectStorageError(s3Error("AccessDenied"), {+ storageType: ObjectStorageType.Default,+ bucket: "instance-bucket",+ region: "us-east-1"+ }) as ObjectStorageError;+ expect(describeStorageFailure(error, "read")).toEqual({+ isTemporary: true,+ message: AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_UNAVAILABLE_SELF_HOSTED_MESSAGE});- expect(getAwsConnectionConfig).not.toHaveBeenCalled();});+});- test("refuses a connection that is not AWS", async () => {- vi.mocked(getAwsConnectionConfig).mockClear();- vi.mocked(deps.appConnectionDAL.findById).mockResolvedValueOnce({- id: "conn-1",- name: "github",- orgId: "org-1",- app: AppConnection.GitHub- } as never);- await expect(buildSessionLogStorage(config, "org-1", deps)).rejects.toMatchObject({- name: "BadRequest",- message: `The connection used for session logs is a ${AppConnection.GitHub} connection. Session logs require an AWS connection`+describe("buildSessionLogSettingsAuditMetadata", () => {+ const externalSettings = {+ enabled: true,+ storage: {+ type: ObjectStorageType.External as const,+ appConnectionId: "6f1c7a52-3f7e-4c8e-9a40-0b2d6c1e9f11",+ bucket: "globex-audit",+ region: AWSRegion.US_EAST_1,+ keyPrefix: "logs"+ }+ };++ test("records the saved bucket and the storage it replaced", () => {+ expect(+ buildSessionLogSettingsAuditMetadata({+ settings: externalSettings,+ appConnectionName: "globex-aws",+ previous: {+ storageType: ObjectStorageType.Default,+ appConnectionId: null,+ appConnectionName: null,+ bucket: null,+ region: null,+ keyPrefix: null+ }+ })+ ).toEqual({+ enabled: true,+ storageType: ObjectStorageType.External,+ appConnectionId: "6f1c7a52-3f7e-4c8e-9a40-0b2d6c1e9f11",+ appConnectionName: "globex-aws",+ bucket: "globex-audit",+ region: AWSRegion.US_EAST_1,+ keyPrefix: "logs",+ previousStorageType: ObjectStorageType.Default,+ previousAppConnectionId: null,+ previousAppConnectionName: null,+ previousBucket: null,+ previousRegion: null,+ previousKeyPrefix: null+ });+ });++ test("records turning off with no storage when the settings read back as none", () => {+ expect(+ buildSessionLogSettingsAuditMetadata({+ settings: null,+ appConnectionName: null,+ previous: {+ storageType: ObjectStorageType.External,+ appConnectionId: "6f1c7a52-3f7e-4c8e-9a40-0b2d6c1e9f11",+ appConnectionName: "globex-aws",+ bucket: "globex-audit",+ region: "eu-west-1",+ keyPrefix: "logs"+ }+ })+ ).toMatchObject({+ enabled: false,+ storageType: null,+ bucket: null,+ previousStorageType: ObjectStorageType.External,+ previousAppConnectionName: "globex-aws",+ previousBucket: "globex-audit",+ previousRegion: "eu-west-1",+ previousKeyPrefix: "logs"});- expect(getAwsConnectionConfig).not.toHaveBeenCalled();});});diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns.tsindex 4e2bcb99d9..02e4bfe4be 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns.ts@@ -1,132 +1,239 @@-import { STSServiceException } from "@aws-sdk/client-sts";--import { ProjectType } from "@app/db/schemas";-import { AWS_REQUEST_TIMEOUTS, createS3Bucket } from "@app/lib/aws/s3";+import { ProjectType, TAgentVaultSessionLogConfigs } from "@app/db/schemas";+import { getConfig } from "@app/lib/config/env";import { BadRequestError, InternalServerError } from "@app/lib/errors";-import { logger } from "@app/lib/logger";-import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";-import { AppConnection } from "@app/services/app-connection/app-connection-enums";-import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";-import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-fns";-import { TAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-types";-import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { AWSRegion } from "@app/services/app-connection/app-connection-enums";+import { isDefaultStorageConfigured } from "@app/services/object-storage/object-storage-default-fns";+import { ObjectStorageError } from "@app/services/object-storage/object-storage-errors";+import {+ ObjectStorageErrorReason,+ ObjectStorageType,+ TStorageConfig+} from "@app/services/object-storage/object-storage-types";+import { TAgentVaultSessionLogConfigDALFactory } from "./agent-vault-session-log-config-dal";import {- AGENT_VAULT_SESSION_LOG_MAX_PAGE_CHUNKS,- AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS+ AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_UNAVAILABLE_MESSAGE,+ AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_UNAVAILABLE_SELF_HOSTED_MESSAGE} from "./agent-vault-session-log-constants";-import { isTemporaryAwsError, withKeyPrefix } from "./agent-vault-session-log-fns";-import { TResolvedSessionLogStorageConfig } from "./agent-vault-session-log-types";-type TStorageDeps = {- appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey" | "decryptWithInputKey">;+export type TSessionLogStorage =+ | { type: ObjectStorageType.Default }+ | {+ type: ObjectStorageType.External;+ appConnectionId: string;+ bucket: string;+ region: AWSRegion;+ keyPrefix: string | null;+ };++export type TEffectiveSessionLogConfig = { enabled: boolean; isSaved: boolean; storage: TSessionLogStorage };++// What session logs do for a project, from its saved row and whether the instance has a bucket. With nothing saved,+// session logs are on in default storage. Without an instance bucket there is no default storage, so a saved+// default choice, or nothing saved, means there are no settings. It never looks at the plan.+export const toEffectiveSessionLogConfig = (+ row:+ | Pick<+ TAgentVaultSessionLogConfigs,+ "enabled" | "storageType" | "appConnectionId" | "bucket" | "region" | "keyPrefix"+ >+ | null+ | undefined,+ hasDefaultStorage: boolean+): TEffectiveSessionLogConfig | null => {+ if (row?.storageType === ObjectStorageType.External && row.appConnectionId && row.bucket && row.region) {+ return {+ enabled: row.enabled,+ isSaved: true,+ storage: {+ type: ObjectStorageType.External,+ appConnectionId: row.appConnectionId,+ bucket: row.bucket,+ region: row.region as AWSRegion,+ keyPrefix: row.keyPrefix || null+ }+ };+ }+ if (!hasDefaultStorage) return null;+ const enabled = row ? row.storageType === ObjectStorageType.Default && row.enabled : true;+ return { enabled, isSaved: Boolean(row), storage: { type: ObjectStorageType.Default } };};-export type TAgentVaultSessionLogStorage = Awaited<ReturnType<typeof buildSessionLogStorage>>;--export const buildSessionLogStorage = async (- config: TResolvedSessionLogStorageConfig,- orgId: string,- { appConnectionDAL, kmsService }: TStorageDeps+export const getEffectiveSessionLogConfig = async (+ {+ agentVaultSessionLogConfigDAL+ }: {+ agentVaultSessionLogConfigDAL: Pick<+ TAgentVaultSessionLogConfigDALFactory,+ "findOne" | "findByProjectIdFromPrimary"+ >;+ },+ projectId: string,+ { fromPrimary }: { fromPrimary: boolean }) => {- const raw = await appConnectionDAL.findById(config.appConnectionId);- if (raw && raw.orgId !== orgId) {- logger.error(- `Agent Vault session log connection is in another organization [appConnectionId=${raw.id}] [orgId=${orgId}]`- );- }- if (!raw || raw.orgId !== orgId) {- throw new BadRequestError({- message: "The AWS connection used for session logs no longer exists. Choose another on the Settings page."- });- }- if (raw.app !== AppConnection.AWS) {- throw new BadRequestError({- message: `The connection used for session logs is a ${raw.app} connection. Session logs require an AWS connection`- });+ const row = fromPrimary+ ? await agentVaultSessionLogConfigDAL.findByProjectIdFromPrimary(projectId)+ : await agentVaultSessionLogConfigDAL.findOne({ projectId });+ return toEffectiveSessionLogConfig(row, isDefaultStorageConfigured());+};++// The storage a settings save replaced: what the audit log records as "previous".+export type TPreviousSessionLogStorage = {+ storageType: ObjectStorageType;+ appConnectionId: string | null;+ appConnectionName: string | null;+ bucket: string | null;+ region: string | null;+ keyPrefix: string | null;+};++// Turning off on an instance without default storage reads back as no settings, and is still recorded as off. Off has no+// storage, so its storage type is null rather than the default columns an off row is saved with.+export const buildSessionLogSettingsAuditMetadata = ({+ settings,+ appConnectionName,+ previous+}: {+ settings: Pick<TEffectiveSessionLogConfig, "enabled" | "storage"> | null;+ appConnectionName: string | null;+ previous: TPreviousSessionLogStorage | null;+}) => {+ const external = settings?.storage.type === ObjectStorageType.External ? settings.storage : null;+ return {+ enabled: settings?.enabled ?? false,+ storageType: settings?.enabled ? settings.storage.type : null,+ appConnectionId: external?.appConnectionId ?? null,+ appConnectionName,+ bucket: external?.bucket ?? null,+ region: external?.region ?? null,+ keyPrefix: external?.keyPrefix ?? null,+ previousStorageType: previous?.storageType ?? null,+ previousAppConnectionId: previous?.appConnectionId ?? null,+ previousAppConnectionName: previous?.appConnectionName ?? null,+ previousBucket: previous?.bucket ?? null,+ previousRegion: previous?.region ?? null,+ previousKeyPrefix: previous?.keyPrefix ?? null+ };+};++export const toStorageConfig = (storage: TSessionLogStorage): TStorageConfig =>+ storage.type === ObjectStorageType.Default+ ? { storageType: ObjectStorageType.Default }+ : {+ storageType: ObjectStorageType.External,+ appConnectionId: storage.appConnectionId,+ bucket: storage.bucket,+ region: storage.region,+ keyPrefix: storage.keyPrefix,+ projectType: ProjectType.AgentVault+ };++const UNREACHABLE_BUCKET_MESSAGE = (bucket: string) =>+ `Unable to reach bucket '${bucket}'. Check the bucket name, the region, and that the connection's credentials allow s3:ListBucket on it`;++// The message an admin sees for a storage failure, and whether trying again later can help (a 500) or the settings+// need fixing (a 400). Default storage always gets the generic message and counts as temporary: its bucket belongs to+// whoever runs the instance, who finds the cause in the server logs, and an org admin can't fix it in settings.+export const describeStorageFailure = (error: ObjectStorageError, use: "read" | "check") => {+ if (error.storageType === ObjectStorageType.Default) {+ return {+ isTemporary: true,+ message: getConfig().isCloud+ ? AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_UNAVAILABLE_MESSAGE+ : AGENT_VAULT_SESSION_LOG_DEFAULT_STORAGE_UNAVAILABLE_SELF_HOSTED_MESSAGE+ };}- let credentials: Awaited<ReturnType<typeof getAwsConnectionConfig>>["credentials"];- try {- const connection = await decryptAppConnection(raw, kmsService as Parameters<typeof decryptAppConnection>[1]);- // Session logs only accept org connections or Agent Vault's own, and both assume the role with the org ID.- ({ credentials } = await getAwsConnectionConfig(- { ...connection, projectType: ProjectType.AgentVault } as unknown as TAwsConnectionConfig,- config.region,- { stsRequestHandler: AWS_REQUEST_TIMEOUTS }- ));- } catch (err) {- logger.warn({ err }, `Agent Vault session logs could not use their AWS connection [appConnectionId=${raw.id}]`);- if (isTemporaryAwsError(err)) {- throw new InternalServerError({- message: `Couldn't reach AWS to use the connection '${raw.name}' for session logs. Try again in a bit.`- });+ const { reason, details } = error;+ const bucket = details.bucket ?? "";+ const isTemporary = reason === ObjectStorageErrorReason.Temporary;++ if (reason === ObjectStorageErrorReason.ConnectionInvalid) {+ if (details.isConnectionMissing) {+ return {+ isTemporary,+ message: "The AWS connection used for session logs no longer exists. Choose another on the Settings page."+ };}- const reason =- err instanceof STSServiceException || err instanceof BadRequestError- ? err.message- : "Infisical could not load its credentials";- throw new BadRequestError({- message: `Couldn't use the AWS connection '${raw.name}' for session logs: ${reason}`- });+ if (details.connectionApp) {+ return {+ isTemporary,+ message: `The connection used for session logs is a ${details.connectionApp} connection. Session logs require an AWS connection`+ };+ }+ return {+ isTemporary,+ message: `Couldn't use the AWS connection '${details.connectionName ?? ""}' for session logs: ${details.cause ?? "Infisical could not load its credentials"}`+ };+ }+ if (isTemporary && details.connectionName && !details.awsErrorCode) {+ return {+ isTemporary,+ message: `Couldn't reach AWS to use the connection '${details.connectionName}' for session logs. Try again in a bit.`+ };}- const { bucket, keyPrefix } = config;- const s3 = createS3Bucket({ region: config.region, bucket, credentials });+ if (isTemporary && use === "check") {+ return { isTemporary, message: `Couldn't reach bucket '${bucket}' just now. Try again in a bit.` };+ }- const presignPut = async ({- objectKey,- ciphertextBytes,- ciphertextSha256- }: {- objectKey: string;- ciphertextBytes: number;- ciphertextSha256: string;- }) =>- s3.presignCreateOnlyPut({- key: objectKey,- contentLength: ciphertextBytes,- // The proxy sends it unpadded; S3 wants the padded form- sha256Base64: `${ciphertextSha256}=`,- expiresInSeconds: AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS- });-- const presignGet = async (objectKey: string) =>- s3.presignGet(objectKey, AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS);-- const listChunks = async ({ folder, startAfter }: { folder: string; startAfter?: string }) =>- s3.listPage({ prefix: folder, startAfter, maxKeys: AGENT_VAULT_SESSION_LOG_MAX_PAGE_CHUNKS });-- const mintCorsProbeUrl = async () => presignGet(withKeyPrefix(keyPrefix, ".cors-probe"));-- const unreachableMessage = `Unable to reach bucket '${bucket}'. Check the bucket name, the region, and that the connection's credentials allow s3:ListBucket on it`;-- const validate = async () => {- const testKey = withKeyPrefix(keyPrefix, ".test/write-check");- const access = await s3.checkAccess(testKey);- if (access.ok) return;-- logger.warn(- { err: access.error, bucket, testKey },- `Agent Vault session logs bucket check failed [bucket=${bucket}] [failure=${access.failure}]`- );- throw new BadRequestError({+ if (use === "check") {+ return {+ isTemporary: false,message:- access.failure === "unreachable"- ? unreachableMessage- : `Bucket '${bucket}' is reachable but writing to it failed. Grant s3:PutObject on the configured key prefix`- });- };-- // Read-only, so it is safe to call often: it can't tell whether writes still work.- const assertReachable = async () => {- const reachable = await s3.checkReachable();- if (reachable.ok) return;+ details.step === "write"+ ? `Bucket '${bucket}' is reachable but writing to it failed. Grant s3:PutObject on the configured key prefix`+ : UNREACHABLE_BUCKET_MESSAGE(bucket)+ };+ }- logger.warn({ err: reachable.error, bucket }, `Agent Vault session logs bucket is unreachable [bucket=${bucket}]`);- throw new BadRequestError({ message: unreachableMessage });+ const code = details.awsErrorCode ?? "";+ let hint = "Check the AWS connection and the bucket settings.";+ if (isTemporary) hint = "S3 isn't responding. Try again in a bit.";+ else if (reason === ObjectStorageErrorReason.CredentialsInvalid) hint = "Check the AWS connection's credentials.";+ else if (reason === ObjectStorageErrorReason.AccessDenied) {+ hint = "Check that the connection's credentials allow s3:ListBucket on it.";+ } else if (reason === ObjectStorageErrorReason.BucketNotFound) hint = "Check the bucket name and region in Settings.";+ return {+ isTemporary,+ message: `Infisical couldn't list session logs in bucket '${bucket}'${code ? ` (${code})` : ""}. ${hint}`};+};- return { presignPut, presignGet, listChunks, mintCorsProbeUrl, validate, assertReachable };+// A 500 when trying again later can help, a 400 when the settings or the storage need fixing.+export const toSessionLogStorageHttpError = ({+ isTemporary,+ message,+ name+}: {+ isTemporary: boolean;+ message: string;+ name?: string;+}) => (isTemporary ? new InternalServerError({ name, message }) : new BadRequestError({ name, message }));++export const isSameSessionLogStorage = (a: TSessionLogStorage, b?: TSessionLogStorage) => {+ if (!b || a.type !== b.type) return false;+ if (a.type === ObjectStorageType.Default || b.type === ObjectStorageType.Default) return true;+ return (+ a.appConnectionId === b.appConnectionId &&+ a.bucket === b.bucket &&+ a.region === b.region &&+ (a.keyPrefix || null) === (b.keyPrefix || null)+ );};++export const toSessionLogSettingsState = (settings: TEffectiveSessionLogConfig | null) => ({+ settings: settings && { enabled: settings.enabled, storage: settings.storage },+ defaultStorage: { configured: isDefaultStorageConfigured() }+});++export const toSessionLogStorageColumns = (storage: TSessionLogStorage) =>+ storage.type === ObjectStorageType.Default+ ? { storageType: storage.type, appConnectionId: null, bucket: null, region: null, keyPrefix: null }+ : {+ storageType: storage.type,+ appConnectionId: storage.appConnectionId,+ bucket: storage.bucket,+ region: storage.region,+ keyPrefix: storage.keyPrefix || null+ };diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-types.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-types.tsindex 34aae64834..ab628d5b48 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-types.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-types.ts@@ -1,7 +1,6 @@import { z } from "zod";import { OrgServiceActor, TGenericPermission } from "@app/lib/types";-import { AWSRegion } from "@app/services/app-connection/app-connection-enums";import type {AgentVaultSessionLogChunkCreateSchema,@@ -31,10 +30,3 @@ export type TTailSessionLogsDTO = TAgentVaultSessionScoped & {export type TUpdateSessionLogSettingsDTO = TAgentVaultSessionLogScoped & {actor: OrgServiceActor;} & z.infer<typeof AgentVaultSessionLogSettingsUpdateSchema>;--export type TResolvedSessionLogStorageConfig = {- appConnectionId: string;- bucket: string;- region: AWSRegion;- keyPrefix: string | null;-};diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-service.tsindex ba5276358a..637e46ee1a 100644--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts@@ -35,7 +35,7 @@ type TAgentVaultSessionServiceFactoryDep = {agentVaultAccessBundleDAL: Pick<TAgentVaultAccessBundleDALFactory, "find">;membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ kmsService: Pick<TKmsServiceFactory, "wrapKey">;};export type TAgentVaultSessionServiceFactory = ReturnType<typeof agentVaultSessionServiceFactory>;diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex bc6d5847cb..56c08dc6c8 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -260,15 +260,22 @@ path decides what a service can reach, so it stays literal.Metadata only (method, host, path, status, decision), never bodies, headers or the query string. The agent ishostile input: nothing it sends may erase or hide its own records, so the proxy logs every request it drops.-- **Bytes go proxy to the customer's bucket to the browser, and S3 is the index.** Infisical stores nothing per- chunk and never seals or opens one. A chunk is `{prefix}/{projectId}/{sessionId}/{rev}_{chunkId}.{proxyId}.json.enc`- holding `IV ‖ ciphertext ‖ tag`; `rev` counts the chunk id's time down, because S3 lists names ascending only.+- **Bytes go proxy to the bucket to the browser, and S3 is the index.** Infisical stores nothing per chunk and never+ seals or opens one. The bucket is default storage (the instance's, `OBJECT_STORAGE_S3_*`) or external storage (the+ customer's, through an AWS connection); both go through the shared layer in `services/object-storage/`, which builds+ `{prefix}/orgs/{orgId}/agent-vault/sessions/{sessionId}/logs/{rev}_{chunkId}.{proxyId}.json.enc` holding+ `IV ‖ ciphertext ‖ tag`. `rev` counts the chunk id's time down, because S3 lists names ascending only.+- **Effective settings come from `toEffectiveSessionLogConfig`**, reached through `getEffectiveSessionLogConfig`+ unless the caller already holds the row. No row plus an instance bucket means on in default storage; no instance+ bucket means a saved `default` row reads as nothing (the row is kept). Writes upsert on `projectId`, because a row+ can exist while the effective settings are null.- **PAM session recording is a separate product.** The overlap with `pam-session-recording` is deliberate; don'tshare code with it.-- **Keys.** Mint wraps a per-session log key with the project data key, even while session logs are off, and- puts `sha256(sessionId|v1)` in front because the KMS wrap takes no context. Unwrap only through- `openSessionLogKey`, so a key copied onto another row is refused. A key that won't open turns logs off for- that session on resolve: session logs must never break brokering.+- **Keys.** Mint wraps a per-session log key with `kmsService.wrapKey` (label `{sessionId}|v1`), even while session+ logs are off. The layout, `sha256(label) || key` under the project data key, must not change: a session can have+ no expiry, so a key wrapped by older code may still need to open. Unwrap only through `openSessionLogKey` or+ `unwrapSessionLogKey` (`agent-vault-session-log-secrets.ts`), so a key copied onto another row is refused. A key+ that won't open turns logs off for that session on resolve: session logs must never break brokering.- **The AAD is `sha256("{sessionId}|{chunkId}|v1")`**, pinned by one vector in the CLI's`session_log_crypto_test.go` and `sessionLogDecrypt.test.ts`. Chunk ids are lowercase UUIDv7s because thebrowser rebuilds the AAD from the id in the object name. A change here is a change in all three places.@@ -279,8 +286,10 @@ hostile input: nothing it sends may erase or hide its own records, so the proxyminutes apart in one chunk, so a date range lists from 11 minutes past its end and stops at the first chunk whoselast request is before its start. The upload link is refused when the id's time is more than a second off`endedAt`, and when the body still carries `iv` (CLIs from before the IV moved into the object).-- **Reads list only the current bucket and prefix**, so changing either hides older logs until it is switched- back. One LIST per request, never a loop, so a folder full of other files can't make a request walk the bucket.+- **Reads list only the current storage, bucket and prefix**, so changing any of them hides older logs until it is+ switched back. Off hides logs too, so Infisical doesn't read the bucket while logs are off (every read is a billed+ S3 request): reads return `disabledReason` and no chunks. One LIST per request, never a loop, so a folder full of+ other files can't make a request walk the bucket.- **A read that can't reach the bucket fails with `AgentVaultSessionLogStorageUnavailable`**: 400 when thesettings or AWS side need fixing, 500 when S3 isn't responding. Never a 200 with no chunks, which callers readas "no logs". Only admins see the cause.@@ -293,12 +302,29 @@ hostile input: nothing it sends may erase or hide its own records, so the proxywhile they may still be uploading. When a poll comes late or returns a full feed, the panel also merges in thenewest history page, at most once a minute, since the feed may have dropped names it never saw. If thatpage doesn't reach the rows already shown, the panel says some requests may be missing and offers Reload.-- **There's no per-org chunk limit.** Infisical stores nothing per chunk, and the customer's bucket is theirs; the- upload-link rate limit and the proxy cap per org bound the work a proxy can cause.-- **Nothing deletes from the bucket**, so the IAM policy asks for no `s3:DeleteObject`.-- **Session logs are a paid feature (`agentVaultByoS3`).** Without it, nothing new is recorded, but saved logs- stay readable. That breaks the License Checks rule in `CODE_QUALITY.md` on purpose. Turning session logs off- and removing their connection stay allowed, or the connection could never be deleted.+- **The shared layer caps default storage on Infisical Cloud at 1 GiB per org per UTC day** (each upload counts as at+ least 16 KiB, 429 over it, allowed if Redis doesn't answer in 250 ms). External buckets and self-hosted instances+ aren't capped, since the bucket is the customer's. It's internal: no UI and no docs.+- **Default storage deletes by tag**: each upload is signed with `retention={n}d` from the plan+ (`agentVaultSessionLogRetentionDays`, 30 by default) and the operator's lifecycle rules delete. Unlike other plan+ limits, `null` here still means 30, so a plan never keeps logs forever by accident. Nothing ever deletes from+ external storage.+- **Default storage problems go to the server logs, never to an org.** The operator, not an org admin, owns that+ bucket: at boot, API pods list it, write a tagged test file, read it back and send a CORS preflight for `SITE_URL`,+ and log what failed; health skips default storage, and failed reads tell everyone, admins too, to contact support.+- **Each storage type has its own plan flag**: `agentVaultManagedStorage` (default on) and `agentVaultByoS3`. The flag+ for the storage in use gates uploads and reads, so an org without it can't record or view session logs: unlike+ most paid features, which read from Infisical's database, each read is a billed S3 request. Keep the read check.+ Turning off is never gated, and turning off clears the saved storage, so it always frees the connection. The row+ stays, saying off: with no row, session logs are on in default storage. It's written even when nothing reads as+ saved, so a bucket the operator adds later doesn't turn logs back on. Health and the CORS probe only run while+ external storage is on and on the plan, since nothing else is recorded or shown.+- **Usage is counted on the way out, not from the cap counter.** Each upload link sends the aggregated PostHog event+ `Agent Vault Session Log Chunk Accepted` (`bytes`, `storageType`, and `records`, the proxy's own unchecked count), and+ the layer counts links on `infisical.object_storage.upload.*` for operators. The cap counter floors at 16 KiB, mixes+ storage types and stops at the cap, so it isn't a usage number.+- **The settings body is `{ enabled: false }` or `{ enabled: true, storage }`.** Turning on always names the+ storage, so nothing guesses which one an `enabled: true` meant after an off cleared it.- **`/agent-vault/app-connections/aws/*` are the shared builders in `app-connection-endpoints.ts` called witha `resolveScope`.** The project comes from the server, a connection outside Agent Vault is a 404 before anypermission check, and responses leave out `projectId`. `createAppConnection` refuses any app but AWS in thisdiff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex e2698c99a6..f2e4666955 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -59,6 +59,7 @@ import {TOidcAuthDetails} from "@app/services/identity-access-token/identity-access-token-types";import { TAllowedFields } from "@app/services/identity-ldap-auth/identity-ldap-auth-types";+import { ObjectStorageType } from "@app/services/object-storage/object-storage-types";import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";import { PkiItemType } from "@app/services/pki-collection/pki-collection-types";import { THealthCheckCommandResult } from "@app/services/pki-sync/pki-sync-health-check-command-fns";@@ -6494,11 +6495,20 @@ interface AgentVaultSessionLogSettingsUpdateEvent {type: EventType.AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE;metadata: {enabled: boolean;+ // Null when session logs are off.+ storageType: ObjectStorageType | null;appConnectionId: string | null;appConnectionName: string | null;bucket: string | null;region: string | null;keyPrefix: string | null;+ // The storage that was recording before this change, when it changed the storage or turned session logs off.+ previousStorageType?: ObjectStorageType | null;+ previousAppConnectionId?: string | null;+ previousAppConnectionName?: string | null;+ previousBucket?: string | null;+ previousRegion?: string | null;+ previousKeyPrefix?: string | null;};}diff --git a/backend/src/ee/services/license/__mocks__/license-fns.ts b/backend/src/ee/services/license/__mocks__/license-fns.tsindex 27f7e46097..8ba9fa9519 100644--- a/backend/src/ee/services/license/__mocks__/license-fns.ts+++ b/backend/src/ee/services/license/__mocks__/license-fns.ts@@ -59,6 +59,8 @@ export const getDefaultOnPremFeatures = () => {honeyTokenLimit: 0,secretsBrokering: true,agentVaultByoS3: true,+ agentVaultManagedStorage: true,+ agentVaultSessionLogRetentionDays: 30,secretSyncLimit: null,maxPamAccounts: null,// PKI / Cert Managerdiff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.tsindex 9ebf8b0763..f90a1b95e4 100644--- a/backend/src/ee/services/license/license-fns.ts+++ b/backend/src/ee/services/license/license-fns.ts@@ -110,6 +110,9 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({honeyTokenLimit: 0,secretsBrokering: true,agentVaultByoS3: false,+ // On by default, like secretsBrokering, until the License Server sets it per plan.+ agentVaultManagedStorage: true,+ agentVaultSessionLogRetentionDays: 30,secretSyncLimit: null,maxPamAccounts: null,// PKI / Cert Managerdiff --git a/backend/src/ee/services/license/license-service.ts b/backend/src/ee/services/license/license-service.tsindex ea53e69db4..73138df163 100644--- a/backend/src/ee/services/license/license-service.ts+++ b/backend/src/ee/services/license/license-service.ts@@ -306,6 +306,8 @@ export const licenseServiceFactory = ({// Whether the plan getPlan serves for this org is the fallback above rather than a real answer.const isServingFallbackPlan = async (orgId: string) => {+ // Only a failed cloud plan fetch writes the marker, so off cloud there's nothing to ask Redis.+ if (instanceType !== InstanceType.Cloud) return false;const [marker] = await keyStore.getItems([KeyStorePrefixes.LicenseCloudPlanFallback(orgId)]);return Boolean(marker);};diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.tsindex 069be5623e..80169c94d4 100644--- a/backend/src/ee/services/license/license-types.ts+++ b/backend/src/ee/services/license/license-types.ts@@ -114,6 +114,8 @@ export type TFeatureSet = {honeyTokenLimit: 0;secretsBrokering: true;agentVaultByoS3: false;+ agentVaultManagedStorage: true;+ agentVaultSessionLogRetentionDays: number | null;secretSyncLimit: null;maxPamAccounts: null;diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex aecdef75d6..a963ba652e 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -171,6 +171,8 @@ export const KeyStorePrefixes = {AgentVaultDefaultProject: (orgId: string) => `agent-vault-default-project:${orgId}` as const,// The live view's Redis stream for a session: the newest chunk file names, with their bucket and size.AgentVaultSessionLogFeed: (sessionId: string) => `agent-vault-session-log-feed:${sessionId}` as const,+ // Bytes an org has been allowed to upload to object storage on one UTC day (YYYY-MM-DD).+ ObjectStorageDailyBytes: (orgId: string, day: string) => `object-storage:daily-bytes:${orgId}:${day}` as const,CertDashboardStats: (projectId: string) => `cert-dashboard-stats:${projectId}` as const,OrgSecretScanningFindingsCount: (orgId: string) => `org-secret-scanning-findings-count:${orgId}` as const,@@ -357,6 +359,12 @@ export type TKeyStoreFactory = {deleteItems: (arg: TDeleteItems) => Promise<number>;incrementBy: (key: string, value: number) => Promise<number>;incrementByAndRefreshExpiryIfUnderLimit: (key: string, limit: number, expiryInSeconds: number) => Promise<number>;+ incrementByIfUnderLimitWithFixedExpiry: (+ key: string,+ value: number,+ limit: number,+ expiryInSeconds: number+ ) => Promise<number>;decrementByOrDelete: (key: string) => Promise<number>;decrementIfExists: (key: string) => Promise<number | null>;claimLeastLoaded: (keys: string[], baseOccupancies: number[], expiryInSeconds: number) => Promise<number>;@@ -535,6 +543,22 @@ export const keyStoreFactory = (return count`;+ // Adds the value only if the total stays within the limit, in one atomic step, and otherwise returns -1 without+ // adding. The expiry is set only when the key has none, so it counts from the first write and retries can't push it+ // back.+ const INCREMENT_BY_IF_UNDER_LIMIT_WITH_FIXED_EXPIRY_SCRIPT = `+ local current = tonumber(redis.call("GET", KEYS[1]) or "0")+ local value = tonumber(ARGV[1])+ if current + value > tonumber(ARGV[2]) then+ return -1+ end+ local total = redis.call("INCRBY", KEYS[1], value)+ if redis.call("TTL", KEYS[1]) == -1 then+ redis.call("EXPIRE", KEYS[1], ARGV[3])+ end+ return total+ `;+// Atomic release: DECR but never below 0, and never leave a no-TTL key behind. If// the counter is missing or already ≤ 1, DEL so the next admit creates a fresh// key with a fresh TTL. Does NOT touch EXPIRE — the slot is being released.@@ -570,6 +594,23 @@ export const keyStoreFactory = (return Number(result);};+ const incrementByIfUnderLimitWithFixedExpiry = async (+ key: string,+ value: number,+ limit: number,+ expiryInSeconds: number+ ): Promise<number> => {+ const result = await primaryRedis.eval(+ INCREMENT_BY_IF_UNDER_LIMIT_WITH_FIXED_EXPIRY_SCRIPT,+ 1,+ key,+ value,+ limit,+ expiryInSeconds+ );+ return Number(result);+ };+const decrementByOrDelete = async (key: string): Promise<number> => {const result = await primaryRedis.eval(DECREMENT_OR_DELETE_SCRIPT, 1, key);return Number(result);@@ -900,6 +941,7 @@ export const keyStoreFactory = (deleteItems,incrementBy,incrementByAndRefreshExpiryIfUnderLimit,+ incrementByIfUnderLimitWithFixedExpiry,decrementByOrDelete,decrementIfExists,claimLeastLoaded,diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.tsindex d490bfc30c..ea55f8d22a 100644--- a/backend/src/keystore/memory.ts+++ b/backend/src/keystore/memory.ts@@ -137,6 +137,12 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {store[key] = String(next);return next;},+ incrementByIfUnderLimitWithFixedExpiry: async (key, value, limit) => {+ const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;+ if (current + value > limit) return -1;+ store[key] = String(current + value);+ return current + value;+ },claimLeastLoaded: async (keys, baseOccupancies) => {if (keys.length === 0) return 0;if (keys.length !== baseOccupancies.length) {diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex e737af736f..1b74a79888 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4647,6 +4647,7 @@ export const AGENT_VAULT = {ciphertextBytes: "The size of the encrypted chunk in bytes.",ciphertextSha256:"The SHA-256 digest of the encrypted chunk, including its IV, as base64 without padding. The bucket refuses an upload with a different digest.",+ recordCount: "The number of requests recorded in the chunk.",legacyIv:"Sent only by Infisical CLI versions that can't record session logs. A request that includes it is refused.",uploadUrl:@@ -4666,13 +4667,19 @@ export const AGENT_VAULT = {from: "Return only chunks with records at or after this time. A chunk can also hold earlier records, so filter records by `ts`.",to: "Return only chunks with records at or before this time. A chunk can also hold later records, so filter records by `ts`.",enabled: "Whether session logs are on.",- configEnabled: "Whether session logs are on. Turning them off stops recording but keeps what's already recorded.",+ configEnabled: "Whether session logs are on. Turning them off hides recorded logs.",+ disabledReason:+ "Why no logs are returned: `off` when session logs are off, `not-on-plan` when the plan doesn't include the storage they use. Null when logs are returned.",+ storageType: "Where this session's logs are read from: `default` or `external`. Null when session logs are off.",+ storage:+ "Where session logs are stored: `default`, stored by Infisical, or `external`, an S3 bucket you own. Required when turning session logs on.",+ defaultStorageConfigured: "Whether default storage is available. Using it also needs a plan that includes it.",appConnectionId: "The ID of the AWS connection Infisical uses to write to and read from the bucket.",bucket:"The name of the S3 bucket. 3 to 63 characters: lowercase letters, numbers, dots and hyphens, starting and ending with a letter or number.",region: "The AWS region of the bucket.",keyPrefix:- "The folder in the bucket to store session logs in, such as `logs/agent-vault`. Up to 512 characters: letters, numbers and `! - _ . ' ( ) /`, with no slash at the start or end, no empty folder name, and no folder named `.` or `..`.",+ "The folder in the bucket to store session logs in, such as `logs/agent-vault`. Up to 256 characters: letters, numbers and `! - _ . ' ( ) /`, with no slash at the start or end, no empty folder name, and no folder named `.` or `..`.",corsProbeUrl: "A URL that fails to load in a browser if the bucket's CORS rule doesn't allow Infisical.",connectionError:"The error Infisical got when it tried to use the AWS connection, for example because AWS refused to let it assume the role. Null if there's no error or no connection.",diff --git a/backend/src/lib/aws/s3.test.ts b/backend/src/lib/aws/s3.test.tsindex 4c7106b299..42340bab9c 100644--- a/backend/src/lib/aws/s3.test.ts+++ b/backend/src/lib/aws/s3.test.ts@@ -28,4 +28,22 @@ describe("presignCreateOnlyPut", () => {expect(signed).toContain("x-amz-checksum-sha256");expect(url.searchParams.has("x-amz-checksum-sha256")).toBe(false);});++ test("carries a tag in the query, so an uploader sending only its usual headers still matches the signature", async () => {+ const presign = async (tagging?: string) =>+ new URL(+ await bucket.presignCreateOnlyPut({+ key: "logs/a.json.enc",+ contentLength: 42,+ sha256Base64: "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",+ expiresInSeconds: 300,+ tagging+ })+ );+ const untagged = await presign();+ const tagged = await presign("retention=30d");++ expect(tagged.searchParams.get("x-amz-tagging")).toBe("retention=30d");+ expect(tagged.searchParams.get("X-Amz-SignedHeaders")).toBe(untagged.searchParams.get("X-Amz-SignedHeaders"));+ });});diff --git a/backend/src/lib/aws/s3.ts b/backend/src/lib/aws/s3.tsindex 4cc3f62033..6ef8b37f9f 100644--- a/backend/src/lib/aws/s3.ts+++ b/backend/src/lib/aws/s3.ts@@ -1,19 +1,13 @@import type { Agent } from "node:https";-import {- GetObjectCommand,- HeadBucketCommand,- ListObjectsV2Command,- PutObjectCommand,- S3Client-} from "@aws-sdk/client-s3";+import { GetObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";import { getSignedUrl } from "@aws-sdk/s3-request-presigner";import { crypto } from "@app/lib/crypto/cryptography";import { CustomAWSHasher } from "./hashing";-type TS3Credentials = { accessKeyId: string; secretAccessKey: string; sessionToken?: string };+export type TS3Credentials = { accessKeyId: string; secretAccessKey: string; sessionToken?: string };// Without these the SDK waits on a stalled AWS endpoint indefinitely, past the point Infisical drops the request.export const AWS_REQUEST_TIMEOUTS = { connectionTimeout: 5_000, requestTimeout: 15_000, throwOnRequestTimeout: true };@@ -21,18 +15,20 @@ export const AWS_REQUEST_TIMEOUTS = { connectionTimeout: 5_000, requestTimeout:// Three attempts at the 15s request timeout fit inside this, and it stays under Infisical's 100s request cut-off.const S3_CALL_TIMEOUT_MS = 45_000;-export type TS3AccessCheck = { ok: true } | { ok: false; failure: "unreachable" | "unwritable"; error: unknown };+export type TS3Check = { ok: true } | { ok: false; error: unknown };export type TS3Bucket = ReturnType<typeof createS3Bucket>;-export const createS3Client = ({+// Without credentials, the SDK runs as the server's own AWS identity. createS3Client takes a customer's connection, so+// it requires them; only default storage goes without, by passing null to createS3Bucket.+const buildS3Client = ({region,credentials,endpoint,httpsAgent}: {region: string;- credentials: TS3Credentials;+ credentials?: TS3Credentials;endpoint?: string;httpsAgent?: Agent;}) =>@@ -52,6 +48,13 @@ export const createS3Client = ({: { useFipsEndpoint: crypto.isFipsModeEnabled() })});+export const createS3Client = (args: {+ region: string;+ credentials: TS3Credentials;+ endpoint?: string;+ httpsAgent?: Agent;+}) => buildS3Client(args);+export const createS3Bucket = ({region,bucket,@@ -59,9 +62,11 @@ export const createS3Bucket = ({}: {region: string;bucket: string;- credentials: TS3Credentials;+ // Null runs as the server's own AWS identity (the environment, the shared config file, or the pod's role), so it has to+ // be passed on purpose. Only default storage does.+ credentials: TS3Credentials | null;}) => {- const client = createS3Client({ region, credentials });+ const client = buildS3Client({ region, credentials: credentials ?? undefined });// The request timeout stops once the headers arrive, so a reply that stalls after them needs an overall limit.const sendOptions = () => ({ abortSignal: AbortSignal.timeout(S3_CALL_TIMEOUT_MS) });@@ -71,12 +76,14 @@ export const createS3Bucket = ({key,contentLength,sha256Base64,- expiresInSeconds+ expiresInSeconds,+ tagging}: {key: string;contentLength: number;sha256Base64: string;expiresInSeconds: number;+ tagging?: string;}) =>getSignedUrl(client,@@ -86,8 +93,11 @@ export const createS3Bucket = ({ContentLength: contentLength,ContentType: "application/octet-stream",IfNoneMatch: "*",- ChecksumSHA256: sha256Base64+ ChecksumSHA256: sha256Base64,+ Tagging: tagging}),+ // Tagging isn't in unhoistableHeaders, so the signer moves x-amz-tagging into the URL's query string. The uploader+ // sends only the headers above, and can't change the tag without breaking the signature.{expiresIn: expiresInSeconds,unhoistableHeaders: new Set(["content-length", "if-none-match", "x-amz-checksum-sha256"])@@ -118,33 +128,34 @@ export const createS3Bucket = ({return { objects, isTruncated: Boolean(res.IsTruncated) };};- const checkReachable = async (): Promise<{ ok: true } | { ok: false; error: unknown }> => {+ // Lists under the prefix instead of using HeadBucket: the IAM policy allows s3:ListBucket only under the prefix, and+ // AWS refuses HeadBucket under that condition.+ const checkListAccess = async (prefix: string): Promise<TS3Check> => {try {- await client.send(new HeadBucketCommand({ Bucket: bucket }), sendOptions());+ await client.send(new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, MaxKeys: 1 }), sendOptions());return { ok: true };} catch (error) {return { ok: false, error };}};- const checkAccess = async (testKey: string): Promise<TS3AccessCheck> => {- const reachable = await checkReachable();- if (!reachable.ok) return { ok: false, failure: "unreachable", error: reachable.error };+ const writeTestObject = async (key: string, tagging?: string): Promise<TS3Check> => {try {await client.send(new PutObjectCommand({Bucket: bucket,- Key: testKey,+ Key: key,Body: Buffer.from("infisical-access-check"),- ContentType: "application/octet-stream"+ ContentType: "application/octet-stream",+ Tagging: tagging}),sendOptions());+ return { ok: true };} catch (error) {- return { ok: false, failure: "unwritable", error };+ return { ok: false, error };}- return { ok: true };};- return { presignCreateOnlyPut, presignGet, listPage, checkReachable, checkAccess };+ return { presignCreateOnlyPut, presignGet, listPage, checkListAccess, writeTestObject };};diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.tsindex 6c7b89b807..27d4d73efc 100644--- a/backend/src/lib/config/env.ts+++ b/backend/src/lib/config/env.ts@@ -1,3 +1,4 @@+import RE2 from "re2";import { z } from "zod";import { THsmServiceFactory } from "@app/ee/services/hsm/hsm-service";@@ -5,6 +6,11 @@ import { crypto } from "@app/lib/crypto/cryptography";import { initializePqcSupport } from "@app/lib/crypto/pqc";import { RunMode } from "@app/lib/types";import { TKmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";+import {+ isS3DirectoryBucket,+ keyPrefixSchema,+ s3BucketNameSchema+} from "@app/services/object-storage/object-storage-path-fns";import { TSuperAdminDALFactory } from "@app/services/super-admin/super-admin-dal";import { BadRequestError } from "../errors";@@ -153,6 +159,46 @@ export const secretScanningTimeoutsSchema = z.object({export const getSecretScanningStuckScanTimeout = (data: z.infer<typeof secretScanningTimeoutsSchema>) =>getSecretScanningScanBudgetMs(data);+// The instance's own bucket for default storage. All optional: without a bucket, the instance offers none.+export const objectStorageEnvSchema = z.object({+ OBJECT_STORAGE_S3_BUCKET: zpStr(+ s3BucketNameSchema+ .refine((bucket) => !isS3DirectoryBucket(bucket), "Must be a general purpose bucket, not a directory bucket")+ .optional()+ ),+ OBJECT_STORAGE_S3_PREFIX: zpStr(keyPrefixSchema(256).optional()),+ // Any region-shaped name, so regions newer than the app connection list work. A region that doesn't exist fails the+ // startup bucket check, which logs it.+ OBJECT_STORAGE_S3_REGION: zpStr(+ z+ .string()+ .regex(new RE2(/^[a-z]{2}(-gov)?-[a-z]+-\d+$/), "Must be an AWS region, like us-east-1")+ .optional()+ ),+ OBJECT_STORAGE_S3_ACCESS_KEY_ID: zpStr(z.string().max(128).optional()),+ OBJECT_STORAGE_S3_SECRET_ACCESS_KEY: zpStr(z.string().max(256).optional())+});++// A half-set group stops the backend at startup, so a typo shows at deploy time rather than as uploads that never land.+export const checkObjectStorageEnv = (data: z.infer<typeof objectStorageEnvSchema>, ctx: z.RefinementCtx) => {+ const requireWith = (+ present: keyof z.infer<typeof objectStorageEnvSchema>,+ missing: keyof z.infer<typeof objectStorageEnvSchema>+ ) => {+ if (data[present] && !data[missing]) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: [missing],+ message: `${missing} must be set when ${present} is set.`+ });+ }+ };+ requireWith("OBJECT_STORAGE_S3_BUCKET", "OBJECT_STORAGE_S3_REGION");+ requireWith("OBJECT_STORAGE_S3_REGION", "OBJECT_STORAGE_S3_BUCKET");+ requireWith("OBJECT_STORAGE_S3_ACCESS_KEY_ID", "OBJECT_STORAGE_S3_SECRET_ACCESS_KEY");+ requireWith("OBJECT_STORAGE_S3_SECRET_ACCESS_KEY", "OBJECT_STORAGE_S3_ACCESS_KEY_ID");+};+const databaseReadReplicaSchema = z.object({DB_CONNECTION_URI: z.string().describe("Postgres read replica database connection string"),@@ -462,6 +508,7 @@ const envSchema = zSECRET_SCANNING_ORG_WHITELIST: zpStr(z.string().optional()),SECRET_SCANNING_GIT_APP_SLUG: zpStr(z.string().default("infisical-radar")),...secretScanningTimeoutsSchema.shape,+ ...objectStorageEnvSchema.shape,SECRET_SCANNING_MEMORY_LIMIT_MB: z.coerce.number().int()@@ -697,6 +744,7 @@ const envSchema = z"Either REDIS_URL, REDIS_SENTINEL_HOSTS or REDIS_CLUSTER_HOSTS must be defined.").superRefine((data, ctx) => {+ checkObjectStorageEnv(data, ctx);([["DB_POOL_MIN", "DB_POOL_MAX"],diff --git a/backend/src/lib/config/object-storage-env.test.ts b/backend/src/lib/config/object-storage-env.test.tsnew file mode 100644index 0000000000..a8d76b4328--- /dev/null+++ b/backend/src/lib/config/object-storage-env.test.ts@@ -0,0 +1,70 @@+import { describe, expect, test } from "vitest";++import { checkObjectStorageEnv, objectStorageEnvSchema } from "./env";++const parse = (env: Record<string, string | undefined>) =>+ objectStorageEnvSchema.superRefine(checkObjectStorageEnv).safeParse(env);++const messages = (result: ReturnType<typeof parse>) =>+ result.success ? [] : result.error.issues.map((issue) => issue.message);++describe("default storage env", () => {+ test("nothing set means the instance offers no default storage", () => {+ expect(parse({}).success).toBe(true);+ });++ test("a bucket and region, with or without keys, is complete", () => {+ expect(parse({ OBJECT_STORAGE_S3_BUCKET: "infisical-logs", OBJECT_STORAGE_S3_REGION: "us-east-1" }).success).toBe(+ true+ );+ expect(+ parse({+ OBJECT_STORAGE_S3_BUCKET: "infisical-logs",+ OBJECT_STORAGE_S3_REGION: "us-east-1",+ OBJECT_STORAGE_S3_ACCESS_KEY_ID: "AKIAEXAMPLE",+ OBJECT_STORAGE_S3_SECRET_ACCESS_KEY: "secret"+ }).success+ ).toBe(true);+ });++ test.each([+ [{ OBJECT_STORAGE_S3_BUCKET: "infisical-logs" }, "OBJECT_STORAGE_S3_REGION must be set"],+ [{ OBJECT_STORAGE_S3_REGION: "us-east-1" }, "OBJECT_STORAGE_S3_BUCKET must be set"],+ [+ {+ OBJECT_STORAGE_S3_BUCKET: "infisical-logs",+ OBJECT_STORAGE_S3_REGION: "us-east-1",+ OBJECT_STORAGE_S3_ACCESS_KEY_ID: "AKIAEXAMPLE"+ },+ "OBJECT_STORAGE_S3_SECRET_ACCESS_KEY must be set"+ ],+ [+ {+ OBJECT_STORAGE_S3_BUCKET: "infisical-logs",+ OBJECT_STORAGE_S3_REGION: "us-east-1",+ OBJECT_STORAGE_S3_SECRET_ACCESS_KEY: "secret"+ },+ "OBJECT_STORAGE_S3_ACCESS_KEY_ID must be set"+ ]+ ])("a half-set group names what is missing", (env, expected) => {+ expect(messages(parse(env)).join(" ")).toContain(expected);+ });++ test.each(["il-central-1", "ap-southeast-7", "us-gov-west-1"])("accepts the region %s", (region) => {+ expect(parse({ OBJECT_STORAGE_S3_BUCKET: "infisical-logs", OBJECT_STORAGE_S3_REGION: region }).success).toBe(true);+ });++ test.each([+ { OBJECT_STORAGE_S3_BUCKET: "infisical-logs", OBJECT_STORAGE_S3_REGION: "US-EAST-1" },+ { OBJECT_STORAGE_S3_BUCKET: "Not_A_Bucket", OBJECT_STORAGE_S3_REGION: "us-east-1" },+ { OBJECT_STORAGE_S3_BUCKET: "logs--x-s3", OBJECT_STORAGE_S3_REGION: "us-east-1" },+ { OBJECT_STORAGE_S3_BUCKET: "infisical-logs", OBJECT_STORAGE_S3_REGION: "moon-1" },+ {+ OBJECT_STORAGE_S3_BUCKET: "infisical-logs",+ OBJECT_STORAGE_S3_REGION: "us-east-1",+ OBJECT_STORAGE_S3_PREFIX: "/a"+ }+ ])("refuses a value S3 would not accept", (env) => {+ expect(parse(env).success).toBe(false);+ });+});diff --git a/backend/src/lib/errors/classify.ts b/backend/src/lib/errors/classify.tsindex c9dfd02f9b..9535e59eee 100644--- a/backend/src/lib/errors/classify.ts+++ b/backend/src/lib/errors/classify.ts@@ -8,6 +8,7 @@ import {BadRequestError,ClientClosedRequestError,CryptographyError,+ DailyQuotaExceededError,DatabaseError,ForbiddenRequestError,GatewayTimeoutError,@@ -67,7 +68,7 @@ export const classifyError = (err: unknown): ErrorType => {if (err instanceof UnauthorizedError) return "auth";if (err instanceof ForbiddenError || err instanceof ForbiddenRequestError || err instanceof PermissionBoundaryError)return "permission";- if (err instanceof RateLimitError) return "rate_limit";+ if (err instanceof RateLimitError || err instanceof DailyQuotaExceededError) return "rate_limit";if (err instanceof NotFoundError) return "not_found";if (err instanceof BadRequestError) return "validation";// A varchar(n) overflow is a rejected input, so it should not inflate the db-error rate.diff --git a/backend/src/lib/errors/index.ts b/backend/src/lib/errors/index.tsindex 4b8004b4f5..b74861633a 100644--- a/backend/src/lib/errors/index.ts+++ b/backend/src/lib/errors/index.ts@@ -168,6 +168,15 @@ export class RateLimitError extends Error {}}+// A usage quota for the day is used up. A 429 so a client retries later, kept apart from RateLimitError, which counts+// toward the API rate-limit metric.+export class DailyQuotaExceededError extends Error {+ constructor({ message }: { message?: string }) {+ super(message || "The daily quota has been used up. Try again after 00:00 UTC.");+ this.name = "DailyQuotaExceeded";+ }+}+export class NotFoundError extends Error {name: string;diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.tsindex b8de478613..551a78b59c 100644--- a/backend/src/lib/telemetry/metrics.ts+++ b/backend/src/lib/telemetry/metrics.ts@@ -800,6 +800,41 @@ export const recordAlertDispatchOutcomeMetric = (params: { resourceType: string;});};+// -- Object storage (InfisicalCore meter) -------------------------------------------------------------+// Upload links the shared object storage layer gave out, or refused at the daily cap. Instance totals only: a per-org+// split would need org ids as labels.++export enum ObjectStorageUploadOutcome {+ Admitted = "admitted",+ Capped = "capped"+}++export const objectStorageUploadCounter = infisicalCoreMeter.createCounter("infisical.object_storage.upload.count", {+ description:+ "Upload links the object storage layer gave out or refused at the daily cap, by storage type and outcome.",+ unit: "{upload}"+});++export const objectStorageUploadBytesCounter = infisicalCoreMeter.createCounter(+ "infisical.object_storage.upload.bytes",+ {+ description: "Bytes the object storage layer's upload links allow, by storage type and outcome.",+ unit: "By"+ }+);++export const recordObjectStorageUploadMetric = (params: {+ storageType: string;+ outcome: ObjectStorageUploadOutcome;+ bytes: number;+}) =>+ safely(() => {+ if (!isTelemetryEnabled()) return;+ const attributes = { type: params.storageType, outcome: params.outcome };+ objectStorageUploadCounter.add(1, attributes);+ objectStorageUploadBytesCounter.add(params.bytes, attributes);+ });+// -- Event outbox (InfisicalCore meter) --------------------------------------------------------------// Outbox health, not what consumers do with events. The main canary is the oldest-pending-age gauge// in event-outbox-queue.ts, fed by the relay tick.diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.tsindex cb28431800..51690315e4 100644--- a/backend/src/server/plugins/error-handler.ts+++ b/backend/src/server/plugins/error-handler.ts@@ -12,6 +12,7 @@ import {ClientClosedRequestError,ConflictError,CryptographyError,+ DailyQuotaExceededError,DatabaseError,ForbiddenRequestError,GatewayTimeoutError,@@ -112,6 +113,7 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProviderisBodyParserError(error) ||(error instanceof OauthTokenError && error.statusCode < HttpStatusCodes.InternalServerError) ||error instanceof RateLimitError ||+ error instanceof DailyQuotaExceededError ||error instanceof PolicyViolationError ||(error instanceof ScimRequestError && error.status < 500) ||(error instanceof AcmeError && error.status < 500) ||@@ -343,6 +345,13 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvidermessage: error.message,error: error.name});+ } else if (error instanceof DailyQuotaExceededError) {+ void res.status(HttpStatusCodes.TooManyRequests).send({+ reqId: req.id,+ statusCode: HttpStatusCodes.TooManyRequests,+ message: error.message,+ error: error.name+ });} else if (error instanceof ScimRequestError) {void res.status(error.status).send({reqId: req.id,diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex cf08e3c006..1582f3cf54 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -40,6 +40,7 @@ import { agentVaultSessionAccessBundleDALFactory } from "@app/ee/services/agent-import { agentVaultSessionDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-dal";import { agentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";import { agentVaultSessionLogConfigDALFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-config-dal";+import { AgentVaultSessionLogsNamespace } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-fns";import { agentVaultSessionLogServiceFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-service";import { agentVaultVariableDALFactory } from "@app/ee/services/agent-vault-variable/agent-vault-variable-dal";import { agentVaultVariableServiceFactory } from "@app/ee/services/agent-vault-variable/agent-vault-variable-service";@@ -466,6 +467,7 @@ import { notificationServiceFactory } from "@app/services/notification/notificatimport { userNotificationDALFactory } from "@app/services/notification/user-notification-dal";import { oauthClientDALFactory } from "@app/services/oauth-client/oauth-client-dal";import { oauthClientServiceFactory } from "@app/services/oauth-client/oauth-client-service";+import { objectStorageServiceFactory } from "@app/services/object-storage/object-storage-service";import { offlineUsageReportDALFactory } from "@app/services/offline-usage-report/offline-usage-report-dal";import { offlineUsageReportServiceFactory } from "@app/services/offline-usage-report/offline-usage-report-service";import { incidentContactDALFactory } from "@app/services/org/incident-contacts-dal";@@ -3316,6 +3318,16 @@ export const registerRoutes = async (keyStore});+ const objectStorageService = objectStorageServiceFactory({ appConnectionDAL, kmsService, keyStore });+ objectStorageService.registerNamespaces([AgentVaultSessionLogsNamespace]);+ // Not awaited: a misconfigured instance bucket is logged, and must not hold up boot. Only pods that serve the API use+ // default storage, so only they check it.+ if (envConfig.isApiRunModeEnabled) {+ void objectStorageService+ .checkDefaultStorage()+ .catch((error) => logger.error(error, "objectStorage: could not check default storage"));+ }+const agentVaultSessionLogService = agentVaultSessionLogServiceFactory({agentVaultSessionLogConfigDAL,agentVaultSessionDAL,@@ -3325,7 +3337,8 @@ export const registerRoutes = async (permissionService,kmsService,licenseService,- keyStore+ keyStore,+ objectStorage: objectStorageService});const hsmConnectorService = hsmConnectorServiceFactory({diff --git a/backend/src/services/kms/kms-fns.test.ts b/backend/src/services/kms/kms-fns.test.tsindex 29510103d8..9b45137b1e 100644--- a/backend/src/services/kms/kms-fns.test.ts+++ b/backend/src/services/kms/kms-fns.test.ts@@ -1,10 +1,10 @@-import { generateKeyPairSync } from "crypto";+import { createHash, generateKeyPairSync } from "crypto";import { describe, expect, it } from "vitest";import { AsymmetricKeyAlgorithm } from "@app/lib/crypto/sign";import { BadRequestError } from "@app/lib/errors";-import { validateClassicalKeyMaterial } from "./kms-fns";+import { buildWrappedKeyPayload, openWrappedKey, validateClassicalKeyMaterial } from "./kms-fns";const pkcs8Pem = (key: { export: (o: { format: "pem"; type: "pkcs8" }) => string | Buffer }) =>Buffer.from(key.export({ format: "pem", type: "pkcs8" }));@@ -43,3 +43,27 @@ describe("validateClassicalKeyMaterial", () => {expect(() => validateClassicalKeyMaterial(ed25519, AsymmetricKeyAlgorithm.ML_DSA_44)).not.toThrow();});});++describe("wrapped keys", () => {+ const key = Buffer.alloc(32, 7);++ // An Agent Vault session can have no expiry, so keys wrapped before this helper existed must keep opening.+ it("opens a key in the layout Agent Vault session keys were always stored in", () => {+ const sessionId = "6f1c7a52-3f7e-4c8e-9a40-0b2d6c1e9f11";+ const storedBefore = Buffer.concat([createHash("sha256").update(`${sessionId}|v1`).digest(), key]);++ expect(buildWrappedKeyPayload(`${sessionId}|v1`, key).equals(storedBefore)).toBe(true);+ expect(openWrappedKey({ label: `${sessionId}|v1`, payload: storedBefore, keyBytes: 32 })?.equals(key)).toBe(true);+ });++ it("refuses a key wrapped for another label", () => {+ const payload = buildWrappedKeyPayload("session-a|v1", key);+ expect(openWrappedKey({ label: "session-b|v1", payload, keyBytes: 32 })).toBeNull();+ });++ it("refuses a payload of the wrong size", () => {+ expect(openWrappedKey({ label: "session-a|v1", payload: key, keyBytes: 32 })).toBeNull();+ const payload = buildWrappedKeyPayload("session-a|v1", key);+ expect(openWrappedKey({ label: "session-a|v1", payload, keyBytes: 16 })).toBeNull();+ });+});diff --git a/backend/src/services/kms/kms-fns.ts b/backend/src/services/kms/kms-fns.tsindex 9c5b0b6ea9..57b3d64797 100644--- a/backend/src/services/kms/kms-fns.ts+++ b/backend/src/services/kms/kms-fns.ts@@ -52,6 +52,23 @@ export const resolveInstanceEncryptionKeyBuffer = (envCfg: {return buffer;};+const WRAPPED_KEY_LABEL_BYTES = 32;++const hashWrappedKeyLabel = (label: string) => crypto.nativeCrypto.createHash("sha256").update(label).digest();++// The data key wrap takes no context, so the label travels inside the payload: a key copied onto a row with another+// label fails to open there instead of being handed out. The layout, sha256(label) || key, is what Agent Vault+// session keys have always used, so existing keys keep opening.+export const buildWrappedKeyPayload = (label: string, key: Buffer) => Buffer.concat([hashWrappedKeyLabel(label), key]);++// Null when the payload wasn't wrapped for this label or isn't the expected size; the caller decides what that means.+export const openWrappedKey = ({ label, payload, keyBytes }: { label: string; payload: Buffer; keyBytes: number }) => {+ const belongs =+ payload.length === WRAPPED_KEY_LABEL_BYTES + keyBytes &&+ crypto.nativeCrypto.timingSafeEqual(payload.subarray(0, WRAPPED_KEY_LABEL_BYTES), hashWrappedKeyLabel(label));+ return belongs ? payload.subarray(WRAPPED_KEY_LABEL_BYTES) : null;+};+const KEK_LABEL_DOMAIN = "infisical:kek-fingerprint:v1";/**diff --git a/backend/src/services/kms/kms-service.ts b/backend/src/services/kms/kms-service.tsindex 948225f14f..12b198deee 100644--- a/backend/src/services/kms/kms-service.ts+++ b/backend/src/services/kms/kms-service.ts@@ -31,12 +31,14 @@ import { alphaNumericNanoId } from "@app/lib/nanoid";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";import {+ buildWrappedKeyPayload,getByteLengthForSymmetricEncryptionAlgorithm,getKekLabel,KMS_LEGACY_ENCRYPTION_KEY_UUID,KMS_ROOT_CONFIG_UUID,MAX_HMAC_IMPORT_KEY_BYTE_LENGTH,MIN_HMAC_IMPORT_KEY_BYTE_LENGTH,+ openWrappedKey,resolveInstanceEncryptionKeyBuffer,validateClassicalKeyMaterial,verifyKeyTypeAndAlgorithm@@ -1290,6 +1292,28 @@ export const kmsServiceFactory = ({};};+ // Wraps a key with the project's SecretManager data key, bound to a label (see buildWrappedKeyPayload).+ const wrapKey = async ({ projectId, label, key }: { projectId: string; label: string; key: Buffer }) => {+ const { encryptor } = await createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });+ return encryptor({ plainText: buildWrappedKeyPayload(label, key) }).cipherTextBlob;+ };++ // Null when the key wasn't wrapped for this label. Throws when the ciphertext doesn't decrypt.+ const unwrapKey = async ({+ projectId,+ label,+ wrappedKey,+ keyBytes+ }: {+ projectId: string;+ label: string;+ wrappedKey: Buffer;+ keyBytes: number;+ }) => {+ const { decryptor } = await createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });+ return openWrappedKey({ label, payload: decryptor({ cipherTextBlob: wrappedKey }), keyBytes });+ };+const updateProjectSecretManagerKmsKey = async ({ projectId, kms }: TUpdateProjectSecretManagerKmsKeyDTO) => {// a stale cached id from a previous rotation whose invalidation failed would point at a deleted key row here.const { kmsKeyId } = await $getProjectSecretManagerKmsKeyIdAndProject(projectId, undefined, true);@@ -1905,6 +1929,8 @@ export const kmsServiceFactory = ({loadProjectKeyBackup,getKmsById,createCipherPairWithDataKey,+ wrapKey,+ unwrapKey,getKeyMaterial,getBulkKeyMaterial,importKeyMaterial,diff --git a/backend/src/services/license-client/feature-mapping.ts b/backend/src/services/license-client/feature-mapping.tsindex 9659981a29..9a803bc186 100644--- a/backend/src/services/license-client/feature-mapping.ts+++ b/backend/src/services/license-client/feature-mapping.ts@@ -366,11 +366,20 @@ const pamMappings: TFeatureMapping[] = [}];-// Agent Vault: session logs written to the customer's own bucket.+// Agent Vault session logs: external storage (the customer's own bucket), default storage (the instance's bucket),+// and how many days default storage keeps them. The last two keys are placeholders until the License Server has them.const agentVaultMappings: TFeatureMapping[] = [{v2Key: "agent_vault_byo_s3",v1Field: "agentVaultByoS3"+ },+ {+ v2Key: "agent_vault_managed_storage",+ v1Field: "agentVaultManagedStorage"+ },+ {+ v2Key: "agent_vault_session_log_retention_days",+ v1Field: "agentVaultSessionLogRetentionDays"}];diff --git a/backend/src/services/object-storage/object-storage-default-fns.ts b/backend/src/services/object-storage/object-storage-default-fns.tsnew file mode 100644index 0000000000..16d4ee22d1--- /dev/null+++ b/backend/src/services/object-storage/object-storage-default-fns.ts@@ -0,0 +1,30 @@+import { TS3Credentials } from "@app/lib/aws/s3";+import { getConfig } from "@app/lib/config/env";++export type TDefaultStorage = {+ bucket: string;+ region: string;+ prefix: string | null;+ credentials?: TS3Credentials;+};++// The instance's own bucket, or null when the operator hasn't set one. Read on every call rather than once, and+// every reader goes through this one module, so "is there default storage" has a single answer.+export const getDefaultStorage = (): TDefaultStorage | null => {+ const cfg = getConfig();+ if (!cfg.OBJECT_STORAGE_S3_BUCKET || !cfg.OBJECT_STORAGE_S3_REGION) return null;+ return {+ bucket: cfg.OBJECT_STORAGE_S3_BUCKET,+ region: cfg.OBJECT_STORAGE_S3_REGION,+ prefix: cfg.OBJECT_STORAGE_S3_PREFIX || null,+ credentials:+ cfg.OBJECT_STORAGE_S3_ACCESS_KEY_ID && cfg.OBJECT_STORAGE_S3_SECRET_ACCESS_KEY+ ? {+ accessKeyId: cfg.OBJECT_STORAGE_S3_ACCESS_KEY_ID,+ secretAccessKey: cfg.OBJECT_STORAGE_S3_SECRET_ACCESS_KEY+ }+ : undefined+ };+};++export const isDefaultStorageConfigured = () => getDefaultStorage() !== null;diff --git a/backend/src/services/object-storage/object-storage-errors.test.ts b/backend/src/services/object-storage/object-storage-errors.test.tsnew file mode 100644index 0000000000..a76b8be136--- /dev/null+++ b/backend/src/services/object-storage/object-storage-errors.test.ts@@ -0,0 +1,50 @@+import { S3ServiceException } from "@aws-sdk/client-s3";+import { describe, expect, test } from "vitest";++import { ObjectStorageError, toObjectStorageError } from "./object-storage-errors";+import { ObjectStorageErrorReason, ObjectStorageType } from "./object-storage-types";++const wrap = (error: unknown, storageType = ObjectStorageType.External) =>+ toObjectStorageError(error, { storageType, bucket: "logs", region: "us-east-1" });+const s3Error = (name: string, fault: "client" | "server" = "client", httpStatusCode?: number) =>+ new S3ServiceException({ name, $fault: fault, $metadata: { httpStatusCode }, message: name });++describe("toObjectStorageError", () => {+ test.each([+ { error: s3Error("SlowDown"), reason: ObjectStorageErrorReason.Temporary },+ { error: s3Error("SomethingNew", "server", 503), reason: ObjectStorageErrorReason.Temporary },+ { error: Object.assign(new Error("connect"), { code: "ECONNRESET" }), reason: ObjectStorageErrorReason.Temporary },+ { error: s3Error("AccessDenied", "client", 403), reason: ObjectStorageErrorReason.AccessDenied },+ { error: s3Error("InvalidAccessKeyId"), reason: ObjectStorageErrorReason.CredentialsInvalid },+ { error: s3Error("NoSuchBucket", "client", 404), reason: ObjectStorageErrorReason.BucketNotFound },+ { error: s3Error("SomethingNew", "client", 400), reason: ObjectStorageErrorReason.Rejected }+ ])("reads $error.name as $reason", ({ error, reason }) => {+ const wrapped = wrap(error) as ObjectStorageError;+ expect(wrapped).toBeInstanceOf(ObjectStorageError);+ expect(wrapped.reason).toBe(reason);+ const label = (error as { code?: string }).code ?? error.name;+ expect(wrapped.details).toMatchObject({ bucket: "logs", region: "us-east-1", awsErrorCode: label });+ });++ test("leaves an error that didn't come from storage as it is", () => {+ const bug = new TypeError("a bug");+ expect(wrap(bug)).toBe(bug);+ });++ test("reads default storage with no usable credentials as invalid credentials, not a bug", () => {+ const missing = Object.assign(new Error("Could not load credentials from any providers"), {+ name: "CredentialsProviderError"+ });+ const wrapped = wrap(missing, ObjectStorageType.Default) as ObjectStorageError;+ expect(wrapped.reason).toBe(ObjectStorageErrorReason.CredentialsInvalid);+ expect(wrapped.storageType).toBe(ObjectStorageType.Default);+ });++ test("keeps an error that is already a storage error", () => {+ const existing = new ObjectStorageError({+ reason: ObjectStorageErrorReason.ConnectionInvalid,+ storageType: ObjectStorageType.External+ });+ expect(wrap(existing)).toBe(existing);+ });+});diff --git a/backend/src/services/object-storage/object-storage-errors.ts b/backend/src/services/object-storage/object-storage-errors.tsnew file mode 100644index 0000000000..7cabc9d56d--- /dev/null+++ b/backend/src/services/object-storage/object-storage-errors.ts@@ -0,0 +1,122 @@+import { S3ServiceException } from "@aws-sdk/client-s3";++import { ObjectStorageErrorReason, ObjectStorageType, TObjectStorageErrorDetails } from "./object-storage-types";++// Says what went wrong with the storage, never in a product's words. The reason tells a product whether trying again+// can help and whether the connection is the problem; for a more specific hint, a product may read the AWS error code+// in the details. Each product writes its own message, and decides what of the details its caller may see.+export class ObjectStorageError extends Error {+ reason: ObjectStorageErrorReason;++ storageType: ObjectStorageType;++ details: TObjectStorageErrorDetails;++ constructor({+ reason,+ storageType,+ details = {}+ }: {+ reason: ObjectStorageErrorReason;+ storageType: ObjectStorageType;+ details?: TObjectStorageErrorDetails;+ }) {+ super(`Object storage failed [reason=${reason}] [storageType=${storageType}]`);+ this.name = "ObjectStorageError";+ this.reason = reason;+ this.storageType = storageType;+ this.details = details;+ }+}++const TEMPORARY_AWS_ERRORS = new Set([+ "SlowDown",+ "InternalError",+ "ServiceUnavailable",+ "RequestTimeout",+ "Throttling",+ "ThrottlingException",+ "TooManyRequestsException",+ "RequestLimitExceeded",+ "TimeoutError",+ "AbortError"+]);+const NETWORK_ERROR_CODES = new Set(["ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN", "EPIPE"]);+const AWS_CREDENTIAL_ERRORS = new Set(["InvalidAccessKeyId", "SignatureDoesNotMatch", "ExpiredToken", "InvalidToken"]);+const AWS_ACCESS_ERRORS = new Set(["AccessDenied", "AllAccessDisabled"]);+const AWS_LOCATION_ERRORS = new Set([+ "NoSuchBucket",+ "PermanentRedirect",+ "AuthorizationHeaderMalformed",+ "IllegalLocationConstraintException"+]);++type TAwsError = Error & { $fault?: string; $metadata?: { httpStatusCode?: number }; code?: string };++// Whether an AWS call failed because AWS or the network didn't answer, so that trying again later can help.+export const isTemporaryAwsError = (error: unknown) => {+ if (!(error instanceof Error)) return false;+ const { $fault, $metadata, code } = error as TAwsError;+ const status = $metadata?.httpStatusCode ?? 0;+ // A reply the client couldn't parse that isn't a 4xx came from something in the network path, not the settings.+ const isUnparsedReply = error.name === "Error" && $metadata?.httpStatusCode !== undefined && status < 400;+ return (+ $fault === "server" ||+ status >= 500 ||+ status === 429 ||+ isUnparsedReply ||+ TEMPORARY_AWS_ERRORS.has(error.name) ||+ NETWORK_ERROR_CODES.has(code ?? "")+ );+};++// S3 errors, network failures and replies S3's client couldn't parse. Anything else is a bug and stays a 500.+const isStorageError = (error: unknown) =>+ error instanceof S3ServiceException ||+ (error instanceof Error && ("code" in error || "$metadata" in error || error.name === "TimeoutError"));++// The name an admin can look up: the S3 error code, or for a reply S3's client couldn't parse (plain text from a+// proxy in between, say), the network code or HTTP status.+export const awsErrorLabel = (error: Error) => {+ const { $metadata, code } = error as TAwsError;+ if (error.name !== "Error") return error.name;+ return code ?? ($metadata?.httpStatusCode ? `HTTP ${$metadata.httpStatusCode}` : error.name);+};++const reasonFor = (error: Error) => {+ if (isTemporaryAwsError(error)) return ObjectStorageErrorReason.Temporary;+ if (AWS_CREDENTIAL_ERRORS.has(error.name)) return ObjectStorageErrorReason.CredentialsInvalid;+ if (AWS_ACCESS_ERRORS.has(error.name)) return ObjectStorageErrorReason.AccessDenied;+ if (AWS_LOCATION_ERRORS.has(error.name)) return ObjectStorageErrorReason.BucketNotFound;+ return ObjectStorageErrorReason.Rejected;+};++// Wraps a failed S3 call. Errors that didn't come from S3 or the network are returned unchanged, so a bug isn't+// reported as a storage problem.+export const toObjectStorageError = (+ error: unknown,+ {+ storageType,+ bucket,+ region,+ step+ }: { storageType: ObjectStorageType; bucket: string; region: string; step?: "list" | "write" }+): Error => {+ if (error instanceof ObjectStorageError) return error;+ // The SDK's default credential chain fails with no code or metadata when the instance has no usable credentials.+ const isMissingCredentials = error instanceof Error && error.name === "CredentialsProviderError";+ if (!isStorageError(error) && !isMissingCredentials) return error instanceof Error ? error : new Error(String(error));++ const awsError = error as TAwsError;+ return new ObjectStorageError({+ reason: isMissingCredentials ? ObjectStorageErrorReason.CredentialsInvalid : reasonFor(awsError),+ storageType,+ details: {+ bucket,+ region,+ step,+ awsErrorCode: awsErrorLabel(awsError),+ httpStatus: awsError.$metadata?.httpStatusCode+ }+ });+};diff --git a/backend/src/services/object-storage/object-storage-namespace-fns.test.ts b/backend/src/services/object-storage/object-storage-namespace-fns.test.tsnew file mode 100644index 0000000000..f1a438e9e2--- /dev/null+++ b/backend/src/services/object-storage/object-storage-namespace-fns.test.ts@@ -0,0 +1,76 @@+import { describe, expect, test } from "vitest";++import { ProjectType } from "@app/db/schemas";++import { assertNamespacesValid, defineStorageNamespace } from "./object-storage-namespace-fns";++const ns = (id: string, path: string, product = ProjectType.AgentVault) =>+ defineStorageNamespace({ id, product, path });++describe("defining a namespace", () => {+ test("its path must end in {file}", () => {+ expect(() => ns("a", "sessions/{sessionId}/logs")).toThrow("must end in /{file}");+ });++ test("its pieces are fixed words or {ids}", () => {+ expect(() => ns("a", "sessions/{session id}/logs/{file}")).toThrow();+ expect(ns("a", "sessions/{sessionId}/logs/{file}").segments).toEqual([+ { kind: "word", value: "sessions" },+ { kind: "id", name: "sessionId" },+ { kind: "word", value: "logs" }+ ]);+ });+});++describe("the startup checks", () => {+ test.each([+ { why: "words and ids take turns", path: "sessions/{sessionId}/logs/{file}" },+ { why: "many ids may follow the last word", path: "monthly/{year}/{month}/{day}/{file}" },+ { why: "a single word", path: "exports/{file}" }+ ])("accepts a path where $why", ({ path }) => {+ expect(() => assertNamespacesValid([ns("a", path)])).not.toThrow();+ });++ test.each([+ {+ why: "two words in a row, so an id could equal the second word",+ path: "requests/exports/{exportId}/{file}"+ },+ { why: "an id before any word", path: "{sessionId}/logs/{file}" },+ { why: "two ids before the last word", path: "sessions/{a}/{b}/logs/{file}" },+ { why: "no fixed word at all", path: "{file}" }+ ])("refuses a path with $why", ({ path }) => {+ expect(() => assertNamespacesValid([ns("a", path)])).toThrow();+ });++ test("refuses a namespace whose last word another namespace of the product uses", () => {+ expect(() =>+ assertNamespacesValid([+ ns("agent-vault.session-logs", "sessions/{sessionId}/logs/{file}"),+ ns("agent-vault.attachments", "sessions/{sessionId}/{file}")+ ])+ ).toThrow('ends in "sessions"');+ });++ test("allows a word of its own beside another namespace", () => {+ expect(() =>+ assertNamespacesValid([+ ns("agent-vault.session-logs", "sessions/{sessionId}/logs/{file}"),+ ns("agent-vault.attachments", "sessions/{sessionId}/attachments/{file}")+ ])+ ).not.toThrow();+ });++ test("products don't constrain each other", () => {+ expect(() =>+ assertNamespacesValid([+ ns("agent-vault.session-logs", "sessions/{sessionId}/logs/{file}"),+ ns("pam.recordings", "sessions/{sessionId}/{file}", ProjectType.PAM)+ ])+ ).not.toThrow();+ });++ test("refuses the same id twice", () => {+ expect(() => assertNamespacesValid([ns("a", "x/{file}"), ns("a", "y/{file}")])).toThrow("registered twice");+ });+});diff --git a/backend/src/services/object-storage/object-storage-namespace-fns.ts b/backend/src/services/object-storage/object-storage-namespace-fns.tsnew file mode 100644index 0000000000..1e1229b150--- /dev/null+++ b/backend/src/services/object-storage/object-storage-namespace-fns.ts@@ -0,0 +1,92 @@+import RE2 from "re2";++import { ProjectType } from "@app/db/schemas";++import { TStorageNamespace } from "./object-storage-types";++const WORD_REGEX = new RE2(/^[A-Za-z0-9_-]+$/);+const ID_REGEX = new RE2(/^\{([A-Za-z][A-Za-z0-9]*)\}$/);+const FILE_SEGMENT = "{file}";++type TParsedSegment = { kind: "word"; value: string } | { kind: "id"; name: string; value: string };++const parsePath = (id: string, path: string): TParsedSegment[] =>+ path.split("/").map((part) => {+ const idMatch = ID_REGEX.exec(part);+ if (idMatch) return { kind: "id", name: idMatch[1], value: part };+ if (!WORD_REGEX.test(part)) {+ throw new Error(+ `Storage namespace "${id}": "${part}" must be a fixed word (letters, digits, - and _) or an {id}`+ );+ }+ return { kind: "word", value: part };+ });++const lastWordIndex = (segments: TParsedSegment[]) => segments.map((segment) => segment.kind).lastIndexOf("word");++export const defineStorageNamespace = ({+ id,+ product,+ path+}: {+ id: string;+ product: ProjectType;+ path: string;+}): TStorageNamespace => {+ if (!path.endsWith(`/${FILE_SEGMENT}`)) {+ throw new Error(`Storage namespace "${id}": its path must end in /${FILE_SEGMENT}`);+ }+ const segments = parsePath(id, path).slice(0, -1);+ return {+ id,+ product,+ path,+ segments: segments.map((segment) =>+ segment.kind === "word" ? { kind: "word", value: segment.value } : { kind: "id", name: segment.name }+ )+ };+};++// Rule 1: fixed words and ids take turns until the last fixed word, and only ids follow it. Otherwise an id could+// equal a fixed word, and two namespaces' files would land in one folder.+const checkTakesTurns = (namespace: TStorageNamespace) => {+ const segments = parsePath(namespace.id, namespace.path);+ const last = lastWordIndex(segments);+ if (last === -1) throw new Error(`Storage namespace "${namespace.id}" needs at least one fixed word in its path`);+ segments.forEach((segment, i) => {+ const expected = i > last || i % 2 === 1 ? "id" : "word";+ if (segment.kind !== expected) {+ throw new Error(+ `Storage namespace "${namespace.id}": "${segment.value}" is in a place where an ${expected} should be`+ );+ }+ });+};++// Rule 2: a namespace's last fixed word is its name in the path, so no other namespace of the product may use it+// anywhere, or that namespace's folder would hold the other's files.+const checkOwnLastWord = (namespaces: TStorageNamespace[]) => {+ namespaces.forEach((namespace) => {+ const segments = parsePath(namespace.id, namespace.path);+ const lastWord = segments[lastWordIndex(segments)].value;+ namespaces.forEach((other) => {+ if (other === namespace || other.product !== namespace.product) return;+ const otherWords = parsePath(other.id, other.path)+ .filter((segment) => segment.kind === "word")+ .map((segment) => segment.value);+ if (otherWords.includes(lastWord)) {+ throw new Error(`Storage namespace "${namespace.id}" ends in "${lastWord}", which "${other.id}" also uses`);+ }+ });+ });+};++export const assertNamespacesValid = (namespaces: TStorageNamespace[]) => {+ const ids = new Set<string>();+ namespaces.forEach((namespace) => {+ if (ids.has(namespace.id)) throw new Error(`Storage namespace "${namespace.id}" is registered twice`);+ ids.add(namespace.id);+ checkTakesTurns(namespace);+ });+ checkOwnLastWord(namespaces);+};diff --git a/backend/src/services/object-storage/object-storage-path-fns.test.ts b/backend/src/services/object-storage/object-storage-path-fns.test.tsnew file mode 100644index 0000000000..54045c5669--- /dev/null+++ b/backend/src/services/object-storage/object-storage-path-fns.test.ts@@ -0,0 +1,51 @@+import { describe, expect, test } from "vitest";++import { ProjectType } from "@app/db/schemas";++import { defineStorageNamespace } from "./object-storage-namespace-fns";+import { assertSafePiece, buildNamespaceFolder, buildObjectKey, buildProductFolder } from "./object-storage-path-fns";++const ORG_ID = "c4a1e0d2-5b7f-4c1e-9a3d-2f6b8e0c7a11";+const logs = defineStorageNamespace({+ id: "agent-vault.session-logs",+ product: ProjectType.AgentVault,+ path: "sessions/{sessionId}/logs/{file}"+});++describe("object paths", () => {+ test("a product folder starts with the prefix and the org, so no product can write into another org's files", () => {+ expect(buildProductFolder({ prefix: "infisical", orgId: ORG_ID, product: "agent-vault" })).toBe(+ `infisical/orgs/${ORG_ID}/agent-vault/`+ );+ expect(buildProductFolder({ prefix: null, orgId: ORG_ID, product: "agent-vault" })).toBe(+ `orgs/${ORG_ID}/agent-vault/`+ );+ });++ test("a namespace folder fills in its ids after the product folder", () => {+ const productFolder = buildProductFolder({ orgId: ORG_ID, product: "agent-vault" });+ expect(buildNamespaceFolder(productFolder, logs, { sessionId: "sess-1" })).toBe(+ `orgs/${ORG_ID}/agent-vault/sessions/sess-1/logs/`+ );+ });++ test("a missing id is refused", () => {+ expect(() => buildNamespaceFolder("orgs/x/agent-vault/", logs, {})).toThrow("Missing 'sessionId'");+ });++ test.each(["..", ".", "a/b", "", "a".repeat(129), "sess 1", "sess.1"])("refuses the id %j", (id) => {+ expect(() => assertSafePiece(id, "id")).toThrow();+ });++ test.each(["..", ".", "a/b", "", "a".repeat(129)])("refuses the file name %j", (name) => {+ expect(() => assertSafePiece(name, "file")).toThrow();+ });++ test("a file name may have dots inside it", () => {+ expect(() => assertSafePiece("8208694117999_abc.def.json.enc", "file")).not.toThrow();+ });++ test("a full path over 1,024 bytes is refused", () => {+ expect(() => buildObjectKey(`${"a/".repeat(500)}`, "a".repeat(100))).toThrow("longer than 1024 bytes");+ });+});diff --git a/backend/src/services/object-storage/object-storage-path-fns.ts b/backend/src/services/object-storage/object-storage-path-fns.tsnew file mode 100644index 0000000000..e728a93d98--- /dev/null+++ b/backend/src/services/object-storage/object-storage-path-fns.ts@@ -0,0 +1,85 @@+import RE2 from "re2";+import { z } from "zod";++import { TStorageNamespace } from "./object-storage-types";++const MAX_PIECE_LENGTH = 128;+const MAX_KEY_BYTES = 1024;++const ID_REGEX = new RE2(/^[A-Za-z0-9_-]+$/);+const FILE_NAME_REGEX = new RE2(/^[A-Za-z0-9._-]+$/);++// Every id and file name in a path is checked here rather than trusted: a "/" or ".." would move the object out of the+// folder the storage layer built. They come from Infisical's own code, never straight from a request, so a bad one is+// a bug, not a bad request.+export const assertSafePiece = (value: string, kind: "id" | "file") => {+ const pattern = kind === "id" ? ID_REGEX : FILE_NAME_REGEX;+ if (!value || value.length > MAX_PIECE_LENGTH || value === "." || value === ".." || !pattern.test(value)) {+ throw new Error(`Invalid object ${kind === "id" ? "id" : "name"} '${value}'`);+ }+};++const BUCKET_NAME_RULE =+ "Must be 3 to 63 characters: lowercase letters, numbers, dots and hyphens, starting and ending with a letter or number";++export const s3BucketNameSchema = z+ .string()+ .trim()+ .max(63, BUCKET_NAME_RULE)+ .regex(new RE2(/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/), BUCKET_NAME_RULE);++export const isS3DirectoryBucket = (bucket: string) => bucket.endsWith("--x-s3");++// The same rules for an external bucket's key prefix and the instance's OBJECT_STORAGE_S3_PREFIX.+export const keyPrefixSchema = (max: number) =>+ z+ .string()+ .trim()+ .max(max, `May be at most ${max} characters`)+ .regex(new RE2(/^[A-Za-z0-9!\-_.'()/]*$/), "May only contain letters, numbers and ! - _ . ' ( ) /")+ .refine(+ (v) => v === "" || v.split("/").every(Boolean),+ "Must be folder names separated by single slashes, with no slash at the start or end, like 'logs/agent-vault'"+ )+ .refine(+ (v) => !v.split("/").some((folder) => folder === "." || folder === ".."),+ "May not use '.' or '..' as a folder name"+ );++// The folder that holds every org's files in a bucket.+export const buildOrgsFolder = (prefix?: string | null) => `${prefix ? `${prefix}/` : ""}orgs/`;++export const buildProductFolder = ({+ prefix,+ orgId,+ product+}: {+ prefix?: string | null;+ orgId: string;+ product: string;+}) => {+ assertSafePiece(orgId, "id");+ return `${buildOrgsFolder(prefix)}${orgId}/${product}/`;+};++export const buildNamespaceFolder = (+ productFolder: string,+ namespace: TStorageNamespace,+ ids: Record<string, string>+) => {+ const pieces = namespace.segments.map((segment) => {+ if (segment.kind === "word") return segment.value;+ const value = Object.hasOwn(ids, segment.name) ? ids[segment.name] : undefined;+ if (value === undefined) throw new Error(`Missing '${segment.name}' for the object path`);+ assertSafePiece(value, "id");+ return value;+ });+ return `${productFolder}${pieces.join("/")}/`;+};++export const buildObjectKey = (folder: string, name: string) => {+ assertSafePiece(name, "file");+ const key = `${folder}${name}`;+ if (Buffer.byteLength(key) > MAX_KEY_BYTES) throw new Error(`The object path is longer than ${MAX_KEY_BYTES} bytes`);+ return key;+};diff --git a/backend/src/services/object-storage/object-storage-service.test.ts b/backend/src/services/object-storage/object-storage-service.test.tsnew file mode 100644index 0000000000..0a2e54ff29--- /dev/null+++ b/backend/src/services/object-storage/object-storage-service.test.ts@@ -0,0 +1,423 @@+import { S3ServiceException } from "@aws-sdk/client-s3";+import { beforeEach, describe, expect, test, vi } from "vitest";++import { ProjectType } from "@app/db/schemas";+import { createS3Bucket } from "@app/lib/aws/s3";+import { DailyQuotaExceededError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { AppConnection, AWSRegion } from "@app/services/app-connection/app-connection-enums";+import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-fns";++import { ObjectStorageError } from "./object-storage-errors";+import { defineStorageNamespace } from "./object-storage-namespace-fns";+import { objectStorageServiceFactory } from "./object-storage-service";+import { ObjectStorageErrorReason, ObjectStorageType } from "./object-storage-types";++const ORG_ID = "c4a1e0d2-5b7f-4c1e-9a3d-2f6b8e0c7a11";+const CONNECTION_ID = "8a2f4c61-1d3e-4b5a-9c7f-0e6d2b8a4f13";++const instance = vi.hoisted(() => ({+ storage: null as null | { bucket: string; region: string; prefix: string | null; credentials?: unknown }+}));+vi.mock("@app/services/object-storage/object-storage-default-fns", () => ({+ getDefaultStorage: () => instance.storage,+ isDefaultStorageConfigured: () => instance.storage !== null+}));+vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));+vi.mock("@app/services/app-connection/app-connection-fns", () => ({+ decryptAppConnection: vi.fn(async (raw: object) => raw)+}));+vi.mock("@app/services/app-connection/aws/aws-connection-fns", () => ({+ getAwsConnectionConfig: vi.fn(async () => ({ credentials: { accessKeyId: "ASIA", secretAccessKey: "s" } }))+}));++const bucketClient = {+ presignCreateOnlyPut: vi.fn(async ({ key }: { key: string }) => `https://signed/${key}`),+ presignGet: vi.fn(async (key: string) => `https://signed/${key}`),+ listPage: vi.fn(async () => ({ objects: [], isTruncated: false })),+ checkListAccess: vi.fn(async (): Promise<{ ok: true } | { ok: false; error: unknown }> => ({ ok: true })),+ writeTestObject: vi.fn(async (): Promise<{ ok: true } | { ok: false; error: unknown }> => ({ ok: true }))+};+vi.mock("@app/lib/aws/s3", () => ({+ AWS_REQUEST_TIMEOUTS: { requestTimeout: 15_000 },+ createS3Bucket: vi.fn(() => bucketClient)+}));++const site = vi.hoisted(() => ({ url: "https://app.example.com" as string | undefined, isCloud: true }));+vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ SITE_URL: site.url, isCloud: site.isCloud }) }));++const preflight = vi.hoisted(() => ({+ options: vi.fn(async () => ({+ status: 200,+ headers: { "access-control-allow-origin": "https://app.example.com" } as Record<string, string>+ })),+ get: vi.fn(async () => ({ status: 200 }))+}));+vi.mock("@app/lib/config/request", () => ({ request: preflight }));++const logs = defineStorageNamespace({+ id: "agent-vault.session-logs",+ product: ProjectType.AgentVault,+ path: "sessions/{sessionId}/logs/{file}"+});++const external = {+ storageType: ObjectStorageType.External as const,+ appConnectionId: CONNECTION_ID,+ bucket: "customer-bucket",+ region: AWSRegion.EU_WEST_1,+ keyPrefix: "inf-logs",+ projectType: ProjectType.AgentVault+};++const build = (opts: { connection?: unknown; admit?: (key: string, value: number) => Promise<number> } = {}) => {+ const connection =+ "connection" in opts+ ? opts.connection+ : { id: CONNECTION_ID, orgId: ORG_ID, app: AppConnection.AWS, name: "prod-logs" };+ const incrementByIfUnderLimitWithFixedExpiry = vi.fn(opts.admit ?? (async (_key: string, value: number) => value));+ const service = objectStorageServiceFactory({+ appConnectionDAL: { findById: vi.fn(async () => connection) } as never,+ kmsService: {} as never,+ keyStore: { incrementByIfUnderLimitWithFixedExpiry } as never+ });+ service.registerNamespaces([logs]);+ return { service, incrementByIfUnderLimitWithFixedExpiry };+};++const put = { name: "chunk.json.enc", bytes: 4096, sha256Base64: "abc=", expiresInSeconds: 300 };++beforeEach(() => {+ vi.clearAllMocks();+ site.url = "https://app.example.com";+ site.isCloud = true;+ instance.storage = { bucket: "instance-bucket", region: "us-east-1", prefix: "infisical" };+});++describe("default storage", () => {+ test("signs an upload under the instance prefix, the org and the product, tagged with the retention", async () => {+ const { service } = build();+ const location = await service.at({ storageType: ObjectStorageType.Default }).forOrg(ORG_ID);+ const { key } = await location+ .namespace(logs)+ .folder({ sessionId: "sess-1" })+ .presignPut({ ...put, retentionDays: 90 });++ expect(key).toBe(`infisical/orgs/${ORG_ID}/agent-vault/sessions/sess-1/logs/chunk.json.enc`);+ expect(createS3Bucket).toHaveBeenCalledWith({+ region: "us-east-1",+ bucket: "instance-bucket",+ credentials: null+ });+ expect(bucketClient.presignCreateOnlyPut).toHaveBeenCalledWith({+ key,+ contentLength: 4096,+ sha256Base64: "abc=",+ expiresInSeconds: 300,+ tagging: "retention=90d"+ });+ });++ test.each([undefined, null, 0, -3, 1.5])("retention %j falls back to 30 days", async (retentionDays) => {+ const { service } = build();+ const location = await service.at({ storageType: ObjectStorageType.Default }).forOrg(ORG_ID);+ await location+ .namespace(logs)+ .folder({ sessionId: "sess-1" })+ .presignPut({ ...put, retentionDays });+ expect(bucketClient.presignCreateOnlyPut).toHaveBeenCalledWith(+ expect.objectContaining({ tagging: "retention=30d" })+ );+ });++ test("reuses one client for the instance bucket", async () => {+ const { service } = build();+ await service.at({ storageType: ObjectStorageType.Default }).forOrg(ORG_ID);+ await service.at({ storageType: ObjectStorageType.Default }).forOrg("another-org");+ expect(createS3Bucket).toHaveBeenCalledTimes(1);+ });++ test("an instance without a bucket has no default storage", async () => {+ instance.storage = null;+ const { service } = build();+ await expect(service.at({ storageType: ObjectStorageType.Default }).forOrg(ORG_ID)).rejects.toMatchObject({+ reason: ObjectStorageErrorReason.Unconfigured+ });+ });++ test("has no bucket check or CORS probe, since the bucket is the operator's", async () => {+ const { service } = build();+ const namespace = (await service.at({ storageType: ObjectStorageType.Default }).forOrg(ORG_ID)).namespace(logs);+ await expect(namespace.check()).rejects.toThrow();+ await expect(namespace.presignCorsProbe(300)).rejects.toThrow();+ });+});++describe("external storage", () => {+ test("signs under the customer's prefix with no tag, and assumes the role with the product's external id", async () => {+ const { service } = build();+ const location = await service.at(external).forOrg(ORG_ID);+ const { key } = await location.namespace(logs).folder({ sessionId: "sess-1" }).presignPut(put);++ expect(key).toBe(`inf-logs/orgs/${ORG_ID}/agent-vault/sessions/sess-1/logs/chunk.json.enc`);+ expect(bucketClient.presignCreateOnlyPut).toHaveBeenCalledWith(expect.objectContaining({ tagging: undefined }));+ expect(getAwsConnectionConfig).toHaveBeenCalledWith(+ expect.objectContaining({ projectType: ProjectType.AgentVault }),+ AWSRegion.EU_WEST_1,+ { stsRequestHandler: { requestTimeout: 15_000 } }+ );+ });++ test.each([+ { why: "a missing connection", connection: undefined },+ { why: "another org's connection", connection: { id: CONNECTION_ID, orgId: "other-org", app: AppConnection.AWS } }+ ])("$why reads as missing", async ({ connection }) => {+ const { service } = build({ connection });+ await expect(service.at(external).forOrg(ORG_ID)).rejects.toMatchObject({+ reason: ObjectStorageErrorReason.ConnectionInvalid,+ details: expect.objectContaining({ isConnectionMissing: true }) as unknown+ });+ });++ test("a connection that isn't AWS is refused, naming its app", async () => {+ const { service } = build({+ connection: { id: CONNECTION_ID, orgId: ORG_ID, app: AppConnection.GitHub, name: "gh" }+ });+ await expect(service.at(external).forOrg(ORG_ID)).rejects.toMatchObject({+ reason: ObjectStorageErrorReason.ConnectionInvalid,+ details: expect.objectContaining({ connectionApp: AppConnection.GitHub }) as unknown+ });+ });++ test("AWS not answering while assuming the role is temporary", async () => {+ vi.mocked(getAwsConnectionConfig).mockRejectedValueOnce(+ Object.assign(new Error("timed out"), { name: "TimeoutError" })+ );+ const { service } = build();+ await expect(service.at(external).forOrg(ORG_ID)).rejects.toMatchObject({+ reason: ObjectStorageErrorReason.Temporary+ });+ });++ test("any other failure loading the connection says it couldn't load its credentials", async () => {+ vi.mocked(getAwsConnectionConfig).mockRejectedValueOnce(new TypeError("bad blob"));+ const { service } = build();+ await expect(service.at(external).forOrg(ORG_ID)).rejects.toMatchObject({+ reason: ObjectStorageErrorReason.ConnectionInvalid,+ details: expect.objectContaining({ cause: "Infisical could not load its credentials" }) as unknown+ });+ });++ test("the bucket check lists the product folder, then writes .check there", async () => {+ const { service } = build();+ const namespace = (await service.at(external).forOrg(ORG_ID)).namespace(logs);+ await namespace.check();+ expect(bucketClient.checkListAccess).toHaveBeenCalledWith(`inf-logs/orgs/${ORG_ID}/agent-vault/`);+ expect(bucketClient.writeTestObject).toHaveBeenCalledWith(`inf-logs/orgs/${ORG_ID}/agent-vault/.check`);+ });++ test("a bucket check that can't write says which step failed", async () => {+ bucketClient.writeTestObject.mockResolvedValueOnce({+ ok: false,+ error: new S3ServiceException({ name: "AccessDenied", $fault: "client", $metadata: {}, message: "denied" })+ });+ const { service } = build();+ const namespace = (await service.at(external).forOrg(ORG_ID)).namespace(logs);+ await expect(namespace.check()).rejects.toMatchObject({+ reason: ObjectStorageErrorReason.AccessDenied,+ details: expect.objectContaining({ step: "write" }) as unknown+ });+ });++ test("the CORS probe is a link to .cors-probe in the product folder", async () => {+ const { service } = build();+ const namespace = (await service.at(external).forOrg(ORG_ID)).namespace(logs);+ expect(await namespace.presignCorsProbe(300)).toBe(+ `https://signed/inf-logs/orgs/${ORG_ID}/agent-vault/.cors-probe`+ );+ });+});++describe("folders", () => {+ test("refuses a namespace that was never registered", async () => {+ const { service } = build();+ const location = await service.at(external).forOrg(ORG_ID);+ const stray = defineStorageNamespace({ id: "stray", product: ProjectType.AgentVault, path: "stray/{file}" });+ expect(() => location.namespace(stray)).toThrow("without being registered");+ });++ test("won't sign a download outside the folder", async () => {+ const { service } = build();+ const folder = (await service.at(external).forOrg(ORG_ID)).namespace(logs).folder({ sessionId: "sess-1" });+ await expect(+ folder.presignGet(`inf-logs/orgs/${ORG_ID}/agent-vault/sessions/sess-2/logs/x`, 300)+ ).rejects.toThrow();+ });++ test("a listing that S3 refuses becomes a storage error", async () => {+ bucketClient.listPage.mockRejectedValueOnce(+ new S3ServiceException({ name: "NoSuchBucket", $fault: "client", $metadata: {}, message: "gone" })+ );+ const { service } = build();+ const folder = (await service.at(external).forOrg(ORG_ID)).namespace(logs).folder({ sessionId: "sess-1" });+ const error = await folder.list({ maxKeys: 10 }).catch((err: unknown) => err);+ expect(error).toBeInstanceOf(ObjectStorageError);+ expect(error).toMatchObject({ reason: ObjectStorageErrorReason.BucketNotFound });+ });++ test("registering a namespace that breaks the naming rules fails", () => {+ const { service } = build();+ expect(() =>+ service.registerNamespaces([+ defineStorageNamespace({+ id: "agent-vault.attachments",+ product: ProjectType.AgentVault,+ path: "sessions/{sessionId}/{file}"+ })+ ])+ ).toThrow('ends in "sessions"');+ });+});++describe("the daily cap", () => {+ const presign = async (+ service: ReturnType<typeof build>["service"],+ bytes: number,+ config: Parameters<ReturnType<typeof build>["service"]["at"]>[0] = { storageType: ObjectStorageType.Default }+ ) =>+ (await service.at(config).forOrg(ORG_ID))+ .namespace(logs)+ .folder({ sessionId: "sess-1" })+ .presignPut({ ...put, bytes });++ test("counts each upload as at least 16 KiB against the org's UTC day", async () => {+ const { service, incrementByIfUnderLimitWithFixedExpiry } = build();+ await presign(service, 100);+ const day = new Date().toISOString().slice(0, 10);+ expect(incrementByIfUnderLimitWithFixedExpiry).toHaveBeenCalledWith(+ `object-storage:daily-bytes:${ORG_ID}:${day}`,+ 16 * 1024,+ 1024 * 1024 * 1024,+ 2 * 24 * 60 * 60+ );+ await presign(service, 5_000_000);+ expect(incrementByIfUnderLimitWithFixedExpiry).toHaveBeenLastCalledWith(+ expect.any(String),+ 5_000_000,+ expect.any(Number),+ expect.any(Number)+ );+ });++ test("over the cap, the link is refused with a 429", async () => {+ const { service } = build({ admit: async () => -1 });+ await expect(presign(service, 4096)).rejects.toBeInstanceOf(DailyQuotaExceededError);+ });++ test("a link that fails to sign is not counted against the cap", async () => {+ const { service, incrementByIfUnderLimitWithFixedExpiry } = build();+ bucketClient.presignCreateOnlyPut.mockRejectedValueOnce(new Error("Could not load credentials"));+ await expect(presign(service, 4096)).rejects.toThrow();+ expect(incrementByIfUnderLimitWithFixedExpiry).not.toHaveBeenCalled();+ });++ test("when Redis doesn't answer within 250 ms, the upload is allowed", async () => {+ const { service } = build({ admit: () => new Promise<number>(() => {}) });+ const started = Date.now();+ await expect(presign(service, 4096)).resolves.toHaveProperty("url");+ expect(Date.now() - started).toBeLessThan(2_000);+ });++ test("when Redis fails, the upload is allowed", async () => {+ const { service } = build({ admit: async () => Promise.reject(new Error("redis is down")) });+ await expect(presign(service, 4096)).resolves.toHaveProperty("url");+ });++ test("an external bucket belongs to the customer, so it isn't counted", async () => {+ const { service, incrementByIfUnderLimitWithFixedExpiry } = build({ admit: async () => -1 });+ await expect(presign(service, 4096, external)).resolves.toHaveProperty("url");+ expect(incrementByIfUnderLimitWithFixedExpiry).not.toHaveBeenCalled();+ });++ test("a self-hosted instance's default storage is its own bucket, so it isn't counted", async () => {+ site.isCloud = false;+ const { service, incrementByIfUnderLimitWithFixedExpiry } = build({ admit: async () => -1 });+ await expect(presign(service, 4096)).resolves.toHaveProperty("url");+ expect(incrementByIfUnderLimitWithFixedExpiry).not.toHaveBeenCalled();+ });+});++describe("the startup check of default storage", () => {+ const denied = new S3ServiceException({+ name: "AccessDenied",+ $fault: "client",+ $metadata: { httpStatusCode: 403 },+ message: "denied"+ });++ test("does nothing on an instance without a bucket", async () => {+ instance.storage = null;+ const { service } = build();+ await service.checkDefaultStorage();+ expect(bucketClient.checkListAccess).not.toHaveBeenCalled();+ expect(logger.error).not.toHaveBeenCalled();+ });++ test("lists the orgs folder, writes a tagged test file there, reads it back and checks browsers may download", async () => {+ const { service } = build();+ await service.checkDefaultStorage();+ expect(bucketClient.checkListAccess).toHaveBeenCalledWith("infisical/orgs/");+ expect(bucketClient.writeTestObject).toHaveBeenCalledWith("infisical/orgs/.check", "retention=30d");+ expect(preflight.get).toHaveBeenCalledWith("https://signed/infisical/orgs/.check", expect.anything());+ expect(preflight.options).toHaveBeenCalledWith(+ "https://signed/infisical/orgs/.cors-probe",+ expect.objectContaining({+ headers: { Origin: "https://app.example.com", "Access-Control-Request-Method": "GET" }+ })+ );+ expect(logger.error).not.toHaveBeenCalled();+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining("default storage is ready"));+ });++ test("logs a missing CORS rule, which nothing else would ever report", async () => {+ preflight.options.mockResolvedValueOnce({ status: 403, headers: {} });+ const { service } = build();+ await service.checkDefaultStorage();+ expect(logger.error).toHaveBeenCalledWith(+ expect.stringContaining("doesn't allow browsers at https://app.example.com")+ );+ expect(logger.info).not.toHaveBeenCalledWith(expect.stringContaining("default storage is ready"));+ });++ test("logs a missing s3:GetObject, which would otherwise only show as refused downloads", async () => {+ preflight.get.mockResolvedValueOnce({ status: 403 });+ const { service } = build();+ await service.checkDefaultStorage();+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining("grant s3:GetObject"));+ expect(logger.info).not.toHaveBeenCalledWith(expect.stringContaining("default storage is ready"));+ });++ test("skips the CORS check without a SITE_URL to check for", async () => {+ site.url = undefined;+ const { service } = build();+ await service.checkDefaultStorage();+ expect(preflight.options).not.toHaveBeenCalled();+ expect(logger.error).not.toHaveBeenCalled();+ });++ test("logs which step failed, so the operator can fix the IAM policy", async () => {+ bucketClient.writeTestObject.mockResolvedValueOnce({ ok: false, error: denied });+ const { service } = build();+ await service.checkDefaultStorage();+ expect(logger.error).toHaveBeenCalledWith(denied, expect.stringContaining("refused a tagged test write"));+ expect(logger.error).toHaveBeenCalledWith(denied, expect.stringContaining("[error=AccessDenied]"));+ });++ test("stops at a bucket it can't list", async () => {+ bucketClient.checkListAccess.mockResolvedValueOnce({ ok: false, error: denied });+ const { service } = build();+ await service.checkDefaultStorage();+ expect(logger.error).toHaveBeenCalledWith(denied, expect.stringContaining("can't be listed"));+ expect(bucketClient.writeTestObject).not.toHaveBeenCalled();+ });+});diff --git a/backend/src/services/object-storage/object-storage-service.ts b/backend/src/services/object-storage/object-storage-service.tsnew file mode 100644index 0000000000..07ddaf89b7--- /dev/null+++ b/backend/src/services/object-storage/object-storage-service.ts@@ -0,0 +1,372 @@+import { STSServiceException } from "@aws-sdk/client-sts";++import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { AWS_REQUEST_TIMEOUTS, createS3Bucket, TS3Bucket } from "@app/lib/aws/s3";+import { getConfig } from "@app/lib/config/env";+import { request } from "@app/lib/config/request";+import { BadRequestError, DailyQuotaExceededError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { ObjectStorageUploadOutcome, recordObjectStorageUploadMetric } from "@app/lib/telemetry/metrics";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";+import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-fns";+import { TAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-types";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { getDefaultStorage } from "@app/services/object-storage/object-storage-default-fns";++import { awsErrorLabel, isTemporaryAwsError, ObjectStorageError, toObjectStorageError } from "./object-storage-errors";+import { assertNamespacesValid } from "./object-storage-namespace-fns";+import { buildNamespaceFolder, buildObjectKey, buildOrgsFolder, buildProductFolder } from "./object-storage-path-fns";+import { ObjectStorageErrorReason, ObjectStorageType, TStorageConfig, TStorageNamespace } from "./object-storage-types";++// An org may upload this much a UTC day to default storage on Infisical Cloud, across every product. Each upload counts+// as at least 16 KiB, so many tiny files cost as much as a few large ones. It stops a modified client from filling+// Infisical's bucket; an external bucket or a self-hosted instance's bucket belongs to the customer, so neither is+// capped. It is internal and not shown anywhere.+const DAILY_BYTES_CAP = 1024 * 1024 * 1024; // 1 GiB+const MIN_COUNTED_BYTES = 16 * 1024; // 16 KiB+const DAILY_COUNTER_TTL_SECONDS = 2 * 24 * 60 * 60; // 2 days, so the counter outlives its UTC day wherever it began+// The Redis client queues commands while Redis is down instead of failing, so without a deadline uploads would hang.+const DAILY_CAP_CHECK_TIMEOUT_MS = 250;++const DEFAULT_RETENTION_DAYS = 30;+const CORS_CHECK_TIMEOUT_MS = 15_000;++type TObjectStorageServiceFactoryDep = {+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ keyStore: Pick<TKeyStoreFactory, "incrementByIfUnderLimitWithFixedExpiry">;+};++export type TObjectStorageServiceFactory = ReturnType<typeof objectStorageServiceFactory>;++export const objectStorageServiceFactory = ({+ appConnectionDAL,+ kmsService,+ keyStore+}: TObjectStorageServiceFactoryDep) => {+ const registeredNamespaces = new Map<string, TStorageNamespace>();++ // Throws at startup on a broken path, so a namespace that would share a folder never ships.+ const registerNamespaces = (namespaces: TStorageNamespace[]) => {+ assertNamespacesValid([...registeredNamespaces.values(), ...namespaces]);+ namespaces.forEach((namespace) => registeredNamespaces.set(namespace.id, namespace));+ };++ // One client for the instance bucket, so the SDK's default credential chain (a pod role, say) isn't resolved again+ // on every request. The instance's settings can't change while it runs.+ let defaultClient: TS3Bucket | null = null;++ const $findDefault = () => {+ const defaultStorage = getDefaultStorage();+ if (!defaultStorage) return null;+ const { bucket, region, prefix, credentials } = defaultStorage;+ defaultClient ??= createS3Bucket({ region, bucket, credentials: credentials ?? null });+ return { s3: defaultClient, bucket, region, prefix };+ };++ const $openDefault = () => {+ const location = $findDefault();+ if (!location) {+ throw new ObjectStorageError({+ reason: ObjectStorageErrorReason.Unconfigured,+ storageType: ObjectStorageType.Default+ });+ }+ return location;+ };++ const $openExternal = async (+ config: Extract<TStorageConfig, { storageType: ObjectStorageType.External }>,+ orgId: string+ ) => {+ const { bucket, region } = config;+ const fail = (reason: ObjectStorageErrorReason, details: ObjectStorageError["details"] = {}) =>+ new ObjectStorageError({+ reason,+ storageType: ObjectStorageType.External,+ details: { bucket, region, ...details }+ });++ const raw = await appConnectionDAL.findById(config.appConnectionId);+ if (raw && raw.orgId !== orgId) {+ logger.error(+ `objectStorage: the storage connection is in another organization [appConnectionId=${raw.id}] [orgId=${orgId}]`+ );+ }+ // Another org's connection reads exactly like a missing one, so its id can't be probed.+ if (!raw || raw.orgId !== orgId)+ throw fail(ObjectStorageErrorReason.ConnectionInvalid, { isConnectionMissing: true });+ if (raw.app !== AppConnection.AWS) {+ throw fail(ObjectStorageErrorReason.ConnectionInvalid, { connectionName: raw.name, connectionApp: raw.app });+ }++ let credentials: Awaited<ReturnType<typeof getAwsConnectionConfig>>["credentials"];+ try {+ const connection = await decryptAppConnection(raw, kmsService);+ ({ credentials } = await getAwsConnectionConfig(+ { ...connection, projectType: config.projectType } as unknown as TAwsConnectionConfig,+ region,+ { stsRequestHandler: AWS_REQUEST_TIMEOUTS }+ ));+ } catch (err) {+ logger.warn({ err }, `objectStorage: could not use the AWS connection [appConnectionId=${raw.id}]`);+ if (isTemporaryAwsError(err)) throw fail(ObjectStorageErrorReason.Temporary, { connectionName: raw.name });+ throw fail(ObjectStorageErrorReason.ConnectionInvalid, {+ connectionName: raw.name,+ cause:+ err instanceof STSServiceException || err instanceof BadRequestError+ ? err.message+ : "Infisical could not load its credentials"+ });+ }++ return { s3: createS3Bucket({ region, bucket, credentials }), bucket, region, prefix: config.keyPrefix ?? null };+ };++ const capWarnedOn = new Map<string, string>();++ // Counts an upload against the org's day. Allows it when Redis doesn't answer in time: a missed count only+ // over-allows, while a stuck check would stop every upload.+ const $admitDailyBytes = async (orgId: string, bytes: number) => {+ const day = new Date().toISOString().slice(0, 10);+ let timer: NodeJS.Timeout | undefined;+ let total: number | "timeout";+ try {+ total = await Promise.race([+ keyStore.incrementByIfUnderLimitWithFixedExpiry(+ KeyStorePrefixes.ObjectStorageDailyBytes(orgId, day),+ Math.max(bytes, MIN_COUNTED_BYTES),+ DAILY_BYTES_CAP,+ DAILY_COUNTER_TTL_SECONDS+ ),+ new Promise<"timeout">((resolve) => {+ timer = setTimeout(() => resolve("timeout"), DAILY_CAP_CHECK_TIMEOUT_MS);+ })+ ]);+ } catch (error) {+ logger.warn(+ error,+ `objectStorage: could not count the upload against the daily cap, allowing it [orgId=${orgId}]`+ );+ return;+ } finally {+ clearTimeout(timer);+ }++ if (total === "timeout") {+ logger.warn(`objectStorage: the daily cap check timed out, allowing the upload [orgId=${orgId}]`);+ return;+ }+ if (total !== -1) return;++ if (capWarnedOn.get(orgId) !== day) {+ capWarnedOn.forEach((warnedDay, warnedOrgId) => {+ if (warnedDay !== day) capWarnedOn.delete(warnedOrgId);+ });+ capWarnedOn.set(orgId, day);+ logger.warn(`objectStorage: organization reached its daily upload cap [orgId=${orgId}] [day=${day}]`);+ }+ throw new DailyQuotaExceededError({+ message: "This organization has uploaded as much as it can today. Uploads resume after 00:00 UTC."+ });+ };++ const $retentionTag = (retentionDays?: number | null) => {+ let days = retentionDays ?? DEFAULT_RETENTION_DAYS;+ if (!Number.isSafeInteger(days) || days < 1) {+ logger.warn(`objectStorage: retention days '${String(retentionDays)}' isn't a positive whole number, using 30`);+ days = DEFAULT_RETENTION_DAYS;+ }+ return `retention=${days}d`;+ };++ // Browsers download files straight from the bucket, which needs a CORS rule for the instance's address. A preflight+ // is what a browser sends before downloading, and S3 answers it without credentials, so the server can send one too.+ const $checkBrowserAccess = async (s3: TS3Bucket, key: string, describeBucket: string) => {+ const { SITE_URL } = getConfig();+ if (!SITE_URL) {+ logger.info(`objectStorage: SITE_URL isn't set, so default storage's CORS rule isn't checked ${describeBucket}`);+ return true;+ }+ const { origin } = new URL(SITE_URL);+ try {+ const url = new URL(await s3.presignGet(key, 60));+ url.search = "";+ const res = await request.options(url.toString(), {+ headers: { Origin: origin, "Access-Control-Request-Method": "GET" },+ timeout: CORS_CHECK_TIMEOUT_MS,+ validateStatus: () => true+ });+ const allowedOrigin = res.headers["access-control-allow-origin"] as string | undefined;+ if (res.status < 300 && (allowedOrigin === origin || allowedOrigin === "*")) return true;+ logger.error(+ `objectStorage: default storage doesn't allow browsers at ${origin} to download files; add the CORS rule from the setup guide ${describeBucket} [status=${res.status}]`+ );+ } catch (error) {+ logger.error(error, `objectStorage: couldn't check default storage's CORS rule ${describeBucket}`);+ }+ return false;+ };++ // Browsers download files through links Infisical signs, which need s3:GetObject. Nothing else would show it missing.+ const $checkReadAccess = async (s3: TS3Bucket, key: string, describeBucket: string) => {+ try {+ const res = await request.get(await s3.presignGet(key, 60), {+ timeout: CORS_CHECK_TIMEOUT_MS,+ responseType: "arraybuffer",+ validateStatus: () => true+ });+ if (res.status === 200) return true;+ logger.error(+ `objectStorage: default storage refused to return its test file, so files can't be downloaded; grant s3:GetObject ${describeBucket} [status=${res.status}]`+ );+ } catch (error) {+ logger.error(error, `objectStorage: couldn't read back default storage's test file ${describeBucket}`);+ }+ return false;+ };++ // The instance's bucket is the operator's to set up, so problems with it go to the server logs at boot rather than to+ // any org admin. A tagged write is what uploads need, and the step most often missing from an IAM policy.+ const checkDefaultStorage = async () => {+ const location = $findDefault();+ if (!location) return;+ const { s3, bucket, region, prefix } = location;+ const folder = buildOrgsFolder(prefix);+ const describeBucket = `[bucket=${bucket}] [region=${region}] [prefix=${folder}]`;+ const describe = (error: unknown) => (error instanceof Error ? awsErrorLabel(error) : String(error));++ const listed = await s3.checkListAccess(folder);+ if (!listed.ok) {+ logger.error(+ listed.error,+ `objectStorage: default storage can't be listed, so files can't be read ${describeBucket} [error=${describe(listed.error)}]`+ );+ return;+ }+ const written = await s3.writeTestObject(`${folder}.check`, $retentionTag(DEFAULT_RETENTION_DAYS));+ if (!written.ok) {+ logger.error(+ written.error,+ `objectStorage: default storage refused a tagged test write, so uploads will fail; grant s3:PutObject and s3:PutObjectTagging ${describeBucket} [error=${describe(written.error)}]`+ );+ }+ const isReadable = written.ok && (await $checkReadAccess(s3, `${folder}.check`, describeBucket));+ const isBrowserReadable = await $checkBrowserAccess(s3, `${folder}.cors-probe`, describeBucket);+ if (isReadable && isBrowserReadable) logger.info(`objectStorage: default storage is ready ${describeBucket}`);+ };++ const at = (config: TStorageConfig) => ({+ forOrg: async (orgId: string) => {+ const { storageType } = config;+ const { s3, bucket, region, prefix } =+ config.storageType === ObjectStorageType.Default ? $openDefault() : await $openExternal(config, orgId);+ const isDefault = storageType === ObjectStorageType.Default;++ const wrap = (error: unknown, step?: "list" | "write") =>+ toObjectStorageError(error, { storageType, bucket, region, step });++ const namespace = (ns: TStorageNamespace) => {+ if (registeredNamespaces.get(ns.id) !== ns) {+ throw new Error(`Storage namespace "${ns.id}" was used without being registered`);+ }+ const productFolder = buildProductFolder({ prefix, orgId, product: ns.product });++ // Read-only and cheap, for health checks: lists the product's folder, where a prefix-scoped IAM policy allows.+ const listAccess = async () => {+ const listed = await s3.checkListAccess(productFolder);+ if (!listed.ok) throw wrap(listed.error, "list");+ };++ // Only for a customer's bucket, when they set it up: the instance's bucket is the operator's to check.+ const check = async () => {+ if (isDefault) throw new Error("Only external storage is checked on save");+ await listAccess();+ const written = await s3.writeTestObject(`${productFolder}.check`);+ if (!written.ok) throw wrap(written.error, "write");+ };++ const presignCorsProbe = async (expiresInSeconds: number) => {+ if (isDefault) throw new Error("Only external storage has a CORS probe");+ try {+ return await s3.presignGet(`${productFolder}.cors-probe`, expiresInSeconds);+ } catch (error) {+ throw wrap(error);+ }+ };++ const folder = (ids: Record<string, string>) => {+ const folderPrefix = buildNamespaceFolder(productFolder, ns, ids);++ const presignPut = async ({+ name,+ bytes,+ sha256Base64,+ expiresInSeconds,+ retentionDays+ }: {+ name: string;+ bytes: number;+ sha256Base64: string;+ expiresInSeconds: number;+ retentionDays?: number | null;+ }) => {+ const key = buildObjectKey(folderPrefix, name);+ // Signed before the cap is counted, so a link that fails to sign (the server's AWS identity can't get+ // credentials) costs the org none of its daily allowance. Signing is local, so a capped request loses little.+ let url: string;+ try {+ url = await s3.presignCreateOnlyPut({+ key,+ contentLength: bytes,+ sha256Base64,+ expiresInSeconds,+ // Default storage deletes by an S3 lifecycle rule on this tag; a customer's bucket is theirs to manage.+ tagging: isDefault ? $retentionTag(retentionDays) : undefined+ });+ } catch (error) {+ throw wrap(error);+ }+ try {+ if (isDefault && getConfig().isCloud) await $admitDailyBytes(orgId, bytes);+ } catch (error) {+ if (error instanceof DailyQuotaExceededError) {+ recordObjectStorageUploadMetric({ storageType, outcome: ObjectStorageUploadOutcome.Capped, bytes });+ }+ throw error;+ }+ recordObjectStorageUploadMetric({ storageType, outcome: ObjectStorageUploadOutcome.Admitted, bytes });+ return { key, url };+ };++ const list = async ({ startAfter, maxKeys }: { startAfter?: string; maxKeys: number }) => {+ try {+ return await s3.listPage({ prefix: folderPrefix, startAfter, maxKeys });+ } catch (error) {+ throw wrap(error, "list");+ }+ };++ const presignGet = async (key: string, expiresInSeconds: number) => {+ if (!key.startsWith(folderPrefix)) throw new Error("Refusing to sign a link outside the folder");+ try {+ return await s3.presignGet(key, expiresInSeconds);+ } catch (error) {+ throw wrap(error);+ }+ };++ return { prefix: folderPrefix, presignPut, list, presignGet };+ };++ return { listAccess, check, presignCorsProbe, folder };+ };++ return { bucket, namespace };+ }+ });++ return { registerNamespaces, at, checkDefaultStorage };+};diff --git a/backend/src/services/object-storage/object-storage-types.ts b/backend/src/services/object-storage/object-storage-types.tsnew file mode 100644index 0000000000..1db77bcb99--- /dev/null+++ b/backend/src/services/object-storage/object-storage-types.ts@@ -0,0 +1,50 @@+import { ProjectType } from "@app/db/schemas";+import { AWSRegion } from "@app/services/app-connection/app-connection-enums";++export enum ObjectStorageType {+ Default = "default",+ External = "external"+}++export type TStorageConfig =+ | { storageType: ObjectStorageType.Default }+ | {+ storageType: ObjectStorageType.External;+ appConnectionId: string;+ bucket: string;+ region: AWSRegion;+ keyPrefix?: string | null;+ // The product using the connection. It decides the external ID Infisical sends when it assumes the customer's IAM+ // role, which has to match the external ID in that role's trust policy.+ projectType: ProjectType;+ };++export type TStorageNamespace = {+ id: string;+ product: ProjectType;+ path: string;+ // The path's pieces in order: a fixed word, or the name of an id the caller fills in.+ segments: ({ kind: "word"; value: string } | { kind: "id"; name: string })[];+};++export enum ObjectStorageErrorReason {+ Temporary = "temporary",+ CredentialsInvalid = "credentials-invalid",+ AccessDenied = "access-denied",+ BucketNotFound = "bucket-not-found",+ Rejected = "rejected",+ ConnectionInvalid = "connection-invalid",+ Unconfigured = "unconfigured"+}++export type TObjectStorageErrorDetails = {+ bucket?: string;+ region?: string;+ awsErrorCode?: string;+ httpStatus?: number;+ connectionName?: string;+ connectionApp?: string;+ isConnectionMissing?: boolean;+ step?: "list" | "write";+ cause?: string;+};diff --git a/backend/src/services/telemetry/telemetry-service.ts b/backend/src/services/telemetry/telemetry-service.tsindex f15131e560..f4587db971 100644--- a/backend/src/services/telemetry/telemetry-service.ts+++ b/backend/src/services/telemetry/telemetry-service.ts@@ -38,6 +38,7 @@ export const POSTHOG_AGGREGATED_EVENTS = [PostHogEventTypes.CertificateRequestCreated,PostHogEventTypes.CmekEncrypt,PostHogEventTypes.CmekDecrypt,+ PostHogEventTypes.AgentVaultSessionLogChunkAccepted,PostHogEventTypes.SecretScanningScanCompleted];@@ -49,6 +50,7 @@ const AGGREGATION_BREAKDOWN_DIMENSIONS: Partial<Record<PostHogEventTypes, string[PostHogEventTypes.PkiSyncExecuted]: ["projectId", "destination"],[PostHogEventTypes.CertificateRequestCreated]: ["projectId"],[PostHogEventTypes.IssueCert]: ["projectId", "enrollmentType", "operation"],+ [PostHogEventTypes.AgentVaultSessionLogChunkAccepted]: ["storageType"],[PostHogEventTypes.SecretScanningScanCompleted]: ["type", "scanType"]};diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex 3fb5ab6357..3a38c00491 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -34,6 +34,7 @@ import { EnforcementLevel, SecretSharingAccessType } from "@app/lib/types";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { ActorType, AuthMethod } from "@app/services/auth/auth-type";import { CertificateIssuanceOperation } from "@app/services/certificate-common/certificate-constants";+import { ObjectStorageType } from "@app/services/object-storage/object-storage-types";import { WebhookType } from "@app/services/webhook/webhook-types";export type HubSpotSignupMethod = AuthMethod | "invite";@@ -337,6 +338,7 @@ export enum PostHogEventTypes {AgentVaultProxyDeleted = "Agent Vault Proxy Deleted",AgentVaultProxyAccessRevoked = "Agent Vault Proxy Access Revoked",AgentVaultProxyTokenRotated = "Agent Vault Proxy Token Rotated",+ AgentVaultSessionLogChunkAccepted = "Agent Vault Session Log Chunk Accepted",AgentVaultProductMemberAdded = "Agent Vault Product Member Added",AgentVaultProductMemberUpdated = "Agent Vault Product Member Updated",AgentVaultProductMemberRemoved = "Agent Vault Product Member Removed",@@ -2541,7 +2543,8 @@ export type TAgentVaultSessionLogSettingsUpdatedEvent = {event: PostHogEventTypes.AgentVaultSessionLogSettingsUpdated;properties: TAgentVaultEventBase & {enabled: boolean;- hasDestination: boolean;+ // Null when session logs are turned off.+ storageType: ObjectStorageType | null;};};@@ -2578,6 +2581,18 @@ export type TAgentVaultProxyTokenRotatedEvent = {properties: TAgentVaultEventBase & { proxyId: string };};+// Sent per upload link a proxy is given, and aggregated (POSTHOG_AGGREGATED_EVENTS), so bytes and records sum per org.+// records is the proxy's own count, unchecked, and missing from CLIs that don't send it.+export type TAgentVaultSessionLogChunkAcceptedEvent = {+ event: PostHogEventTypes.AgentVaultSessionLogChunkAccepted;+ properties: {+ orgId: string;+ storageType: ObjectStorageType;+ bytes: number;+ records?: number;+ };+};+export type TAgentVaultProductMemberAddedEvent = {event: PostHogEventTypes.AgentVaultProductMemberAdded;properties: TAgentVaultEventBase & { memberType: AgentVaultMemberType; role: string };@@ -2613,11 +2628,12 @@ export type TAgentVaultPostHogEvent =| TAgentVaultProxyDeletedEvent| TAgentVaultProxyAccessRevokedEvent| TAgentVaultProxyTokenRotatedEvent+ | TAgentVaultSessionLogChunkAcceptedEvent| TAgentVaultProductMemberAddedEvent| TAgentVaultProductMemberUpdatedEvent| TAgentVaultProductMemberRemovedEvent;-export type TAgentVaultActorPostHogEvent = TAgentVaultPostHogEvent;+export type TAgentVaultActorPostHogEvent = Exclude<TAgentVaultPostHogEvent, TAgentVaultSessionLogChunkAcceptedEvent>;// A trial is burned per PRODUCT, not per (product, plan): the trial-history gate discards plan_key// (see licenseV2Service.getOverview), and the license server 409s a repeat. So TrialStarted fires atdiff --git a/backend/vitest.e2e.config.mts b/backend/vitest.e2e.config.mtsindex b8cb8ffa3f..e615271c55 100644--- a/backend/vitest.e2e.config.mts+++ b/backend/vitest.e2e.config.mts@@ -89,6 +89,12 @@ export default defineConfig({find: /^@app\/lib\/aws\/s3$/,replacement: path.resolve(__dirname, "./e2e-test/fakes/s3")},+ // Every file under src/ imports this module by exactly this specifier, so one entry swaps it everywhere. A relative+ // import would bypass the fake.+ {+ find: /^@app\/services\/object-storage\/object-storage-default-fns$/,+ replacement: path.resolve(__dirname, "./e2e-test/fakes/object-storage-default-fns")+ },// Pass-through wrappers that hand a spec the real job, to run on demand. Only// server/routes/index.ts imports either specifier.{diff --git a/docs/docs.json b/docs/docs.jsonindex a9cb937d9f..8fa528b230 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -1215,7 +1215,8 @@"self-hosting/guides/custom-certificates","self-hosting/guides/hsm-integration","self-hosting/guides/automated-bootstrapping",- "self-hosting/guides/cdn-caching"+ "self-hosting/guides/cdn-caching",+ "self-hosting/guides/session-log-storage"]},{diff --git a/docs/documentation/platform/agent-vault/guides/custom-agent.mdx b/docs/documentation/platform/agent-vault/guides/custom-agent.mdxindex a42928c5bd..d315c6796f 100644--- a/docs/documentation/platform/agent-vault/guides/custom-agent.mdx+++ b/docs/documentation/platform/agent-vault/guides/custom-agent.mdx@@ -228,7 +228,7 @@ Keep the session token out of logs. Anyone who can reach the proxy with the tokeMake a request from the agent to an API in the session's access bundle. For example, if the bundle has a GitHub service, request `https://api.github.com/user`. GitHub returns the account that the service's token belongs to, even though the agent doesn't have a GitHub token.-If you've [set up session logs](/documentation/platform/agent-vault/session-logs#setting-up-session-logs), [view the session's logs](/documentation/platform/agent-vault/sessions#view-session-logs) to check which requests the agent made. Requests that got a credential have the outcome **Brokered**.+[View the session's logs](/documentation/platform/agent-vault/sessions#view-session-logs) to check which requests the agent made. Requests that got a credential have the outcome **Brokered**.<Check>Your agent now calls APIs through the proxy. The only credential the agent has is the session token, and if you revoke the session, the proxy stops attaching credentials to the agent's requests.diff --git a/docs/documentation/platform/agent-vault/overview.mdx b/docs/documentation/platform/agent-vault/overview.mdxindex 2bf91a8d42..1bdc3aa5c9 100644--- a/docs/documentation/platform/agent-vault/overview.mdx+++ b/docs/documentation/platform/agent-vault/overview.mdx@@ -60,7 +60,7 @@ Set up Agent Vault for the agent you use, or for an agent you wrote yourself.Create a session for each agent run from your own code.</Card><Card title="Session logs" icon="list" href="/documentation/platform/agent-vault/session-logs">- A record of every request an AI agent makes, stored encrypted in your own Amazon S3 bucket.+ A record of every request an AI agent makes, stored encrypted.</Card><Card title="Proxies" icon="server" href="/documentation/platform/agent-vault/proxies">Forward proxies that intercept an AI agent's requests and attach real credentials on the way out.diff --git a/docs/documentation/platform/agent-vault/plan-your-setup.mdx b/docs/documentation/platform/agent-vault/plan-your-setup.mdxindex c2f0174d91..df2aae0fe2 100644--- a/docs/documentation/platform/agent-vault/plan-your-setup.mdx+++ b/docs/documentation/platform/agent-vault/plan-your-setup.mdx@@ -161,7 +161,7 @@ Configure the following options to get custom guidance and best practices tailor</AgentVaultSetupStep><AgentVaultSetupStep step="forward">- The [real credential](/documentation/platform/agent-vault/services#credential-types) is added to the request at the proxy, so it never passes through the agent. If you've [set up session logs](/documentation/platform/agent-vault/session-logs#setting-up-session-logs), the request appears in the session's logs.+ The [real credential](/documentation/platform/agent-vault/services#credential-types) is added to the request at the proxy, so it never passes through the agent. The request appears in the session's [logs](/documentation/platform/agent-vault/session-logs).The proxy only attaches credentials for the services in the access bundle. Requests to any other host go out without a credential, unless the proxy's [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy) blocks them.</AgentVaultSetupStep>diff --git a/docs/documentation/platform/agent-vault/session-logs.mdx b/docs/documentation/platform/agent-vault/session-logs.mdxindex 568a47f2d5..a71535fc92 100644--- a/docs/documentation/platform/agent-vault/session-logs.mdx+++ b/docs/documentation/platform/agent-vault/session-logs.mdx@@ -1,129 +1,20 @@---title: "Session logs"sidebarTitle: "Logs"-description: "Keep an encrypted record of every request an AI agent makes, stored in your own Amazon S3 bucket."+description: "Keep an encrypted record of every request an AI agent makes, stored by Infisical or in your own Amazon S3 bucket."---import SelfHostedInstance from "/snippets/app-connections/aws/self-hosted-instance.mdx";import CreateIamRole from "/snippets/app-connections/aws/create-iam-role.mdx";import AgentVaultSessionLogsCorsRule from "/snippets/app-connections/aws/agent-vault-session-logs-cors-rule.mdx";-<Info>- Session logs are a paid feature.-- If you're using Infisical Cloud, they're available under the **Enterprise Tier**. If you're self-hosting Infisical, contact [email protected] to purchase an enterprise license to use them.-</Info>-A session log is a record of every request an agent makes during a [session](/documentation/platform/agent-vault/sessions): the method, host, path, status code, and whether the proxy attached a credential. The [proxy](/documentation/platform/agent-vault/proxies) adds every request it receives to the session log, including requests to hosts that no [access bundle](/documentation/platform/agent-vault/access-bundles) covers.-The proxy encrypts the records before they leave your network and uploads them to an Amazon S3 bucket you own.--## Setting up session logs--Infisical reaches your bucket through an [AWS app connection](/integrations/app-connections/aws/), which signs in to AWS by assuming an IAM role you create.--You'll switch between Infisical and AWS during setup: Infisical generates the AWS policy for your bucket, you set up the bucket and role in AWS, and then you create the connection in Infisical with the role's ARN.--### Prerequisites--- The [Admin role](/documentation/platform/agent-vault/access-control) in Agent Vault-- An [Amazon S3 bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html) to store the records in-- Permission in AWS to edit the bucket's CORS configuration, create IAM roles, and attach policies to them--### Step 1: Start in Infisical--<Steps>- <Step>- In Agent Vault, go to **Administration** > **Settings** and select **Set Up Session Logs**.- </Step>- <Step>- Enter the **Region** and **Bucket** of your S3 bucket.- </Step>- <Step>- Optionally, enter a **Key Prefix** to store session logs under one path in a bucket you also use for other data.- </Step>- <Step>- Select **View AWS Setup**. Infisical shows an **IAM policy** with your bucket and key prefix already filled in, so you can paste it into AWS as it is.- </Step>-</Steps>--Leave the **Session Logs** dialog open. You'll fill in **AWS Connection** in [Step 3](#step-3-finish-in-infisical), after you create the role it uses. Open AWS in another browser tab.--### Step 2: Set up in AWS--#### Add a CORS rule to the bucket--Your browser downloads session logs directly from your bucket, so the bucket has to accept requests from Infisical. Add a CORS rule for Infisical to the bucket.--<Steps>- <AgentVaultSessionLogsCorsRule />-</Steps>--#### Create an IAM role for Infisical--<Note>- If you already have an AWS app connection you want to use, skip to [Attach the IAM policy](#attach-the-iam-policy).-</Note>--Infisical assumes this role to write session logs to the bucket.--<SelfHostedInstance />--<Steps>- <CreateIamRole externalId="organization" />-</Steps>--#### Attach the IAM policy--Attach the **IAM policy** from [Step 1](#step-1-start-in-infisical) to the IAM role, or to the role or user your existing connection signs in as.--<Steps>- <Step>- In the IAM console, open the role or user. On the **Permissions** tab, select **Add permissions** > **Create inline policy**, switch to the **JSON** editor, and paste the policy.- </Step>- <Step>- Select **Next**, enter a **Policy name**, then select **Create policy**.- </Step>- <Step>- If you created a new role, copy its **ARN** from the **Summary** section.-- - </Step>-</Steps>--### Step 3: Finish in Infisical--Go back to the **Session Logs** dialog.--<Steps>- <Step>- Under **AWS Connection**, select **Create New Connection**.-- <Note>- If you already have an AWS app connection you want to use, select it here instead. Then, select **Save** and skip the remaining steps.- </Note>- </Step>- <Step>- Enter a **Name**, keep the **Assume Role (Recommended)** method, paste the role's ARN into **Role ARN**, and select **Connect to AWS**. Infisical creates the connection in Agent Vault and selects it.- </Step>- <Step>- Select **Save**.- </Step>-</Steps>--<Frame>- <img src="/images/platform/agent-vault/session-logs-setup.png" alt="The Session Logs dialog with Enable turned on and an AWS connection, region, bucket, and key prefix filled in" />-</Frame>--When you save, Infisical checks that the bucket exists and that the IAM user or role can write to it. If either check fails, Infisical shows the error and doesn't save the settings. If your browser can't read from the bucket, the **Session Logs** card shows a warning after you save.--<Check>- You've successfully set up session logs within Agent Vault.-</Check>+The proxy encrypts the records before they leave your network, and Infisical stores them for you. If you self-host Infisical, your server administrator [sets up where Infisical stores them](/self-hosting/guides/session-log-storage).## Viewing session logs-You can view a session's logs if you created the session or you're an Agent Vault admin.+You can view a session's logs if you created the session or you're an Agent Vault admin, for up to 30 days after they're recorded if Infisical stores them (see [Retention](#retention)).<Tabs><Tab title="In Infisical">@@ -134,14 +25,14 @@ You can view a session's logs if you created the session or you're an Agent Vaul</Frame></Tab><Tab title="Through the API" id="reading-session-logs-through-the-api">- The API returns a session's logs as chunks. A chunk is one encrypted batch of [records](#what-gets-recorded) that a proxy uploaded to your bucket.+ The API returns a session's logs as chunks. A chunk is one encrypted batch of [records](#what-gets-recorded) that a proxy uploaded.<Steps><Step>Call [the endpoint that lists session logs](/api-reference/endpoints/agent-vault-session-logs/list). It returns the newest chunks first. To get older chunks, call it again with the response's `nextCursor` as `cursor`.<Note>- If Infisical can't read the bucket, the request fails with the error `AgentVaultSessionLogStorageUnavailable`, and the message says why.+ If Infisical can't read session logs, the request fails with the error `AgentVaultSessionLogStorageUnavailable`, and the message says why.</Note></Step><Step>@@ -202,7 +93,7 @@ You can view a session's logs if you created the session or you're an Agent Vaul```<Note>- The script runs outside a browser, so the bucket's CORS rule doesn't apply to it.+ The script runs outside a browser, so CORS rules don't apply to it.</Note>To receive new logs as they arrive, call [the endpoint that tails session logs](/api-reference/endpoints/agent-vault-session-logs/tail) without a cursor, then call it every few seconds with the previous response's `nextCursor`. Any response can repeat a chunk you already read, so skip any chunk whose `chunkId` and `proxyId` you've already read. If a chunk's download returns 404, the proxy may still be uploading it, so try again a few seconds later. If the download still returns 404 after about 2 minutes, stop retrying. If the proxy finishes the upload later, [the endpoint that lists session logs](/api-reference/endpoints/agent-vault-session-logs/list) returns the chunk.@@ -234,11 +125,134 @@ The outcome is one of four:Request and response bodies, headers, and query strings aren't recorded.+## Storing session logs in your own S3 bucket++To keep session logs longer than 30 days, or in your own AWS account, store them in an Amazon S3 bucket you own. This is called external storage.++<Info>+ External storage is a paid feature.++ If you're using Infisical Cloud, it's available under the **Enterprise Tier**. If you're self-hosting Infisical, contact [email protected] to purchase an enterprise license to use it.+</Info>++Infisical reaches your bucket through an [AWS app connection](/integrations/app-connections/aws/), which signs in to AWS by assuming an IAM role you create.++You'll switch between Infisical and AWS during setup: Infisical generates the AWS policy for your bucket, you set up the bucket and role in AWS, and then you create the connection in Infisical with the role's ARN.++### Prerequisites++- The [Admin role](/documentation/platform/agent-vault/access-control) in Agent Vault+- An [Amazon S3 bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html) to store the records in+- Permission in AWS to edit the bucket's CORS configuration, create IAM roles, and attach policies to them++### Step 1: Start in Infisical++<Steps>+ <Step>+ In Agent Vault, go to **Administration** > **Settings** and select **Configure** or **Set Up Session Logs** on the **Session Logs** card.+ </Step>+ <Step>+ Turn on **Enable**, then under **Storage**, select **External storage**.+ </Step>+ <Step>+ Enter the **Region** and **Bucket** of your S3 bucket.+ </Step>+ <Step>+ Optionally, enter a **Key Prefix** to store session logs under one path in a bucket you also use for other data.+ </Step>+ <Step>+ Select **View AWS Setup**. Infisical shows an **IAM policy** with your bucket and key prefix already filled in, so you can paste it into AWS as it is.+ </Step>+</Steps>++Leave the **Session Logs** dialog open. You'll fill in **AWS Connection** in [Step 3](#step-3-finish-in-infisical), after you create the role it uses. Open AWS in another browser tab.++### Step 2: Set up in AWS++#### Add a CORS rule to the bucket++Your browser downloads session logs directly from your bucket, so the bucket has to accept requests from Infisical. Add a CORS rule for Infisical to the bucket.++<Steps>+ <AgentVaultSessionLogsCorsRule />+</Steps>++#### Create an IAM role for Infisical++<Note>+ If you already have an AWS app connection you want to use, skip to [Attach the IAM policy](#attach-the-iam-policy).+</Note>++Infisical assumes this role to write session logs to the bucket.++<SelfHostedInstance />++<Steps>+ <CreateIamRole externalId="organization" />+</Steps>++#### Attach the IAM policy++Attach the **IAM policy** from [Step 1](#step-1-start-in-infisical) to the IAM role, or to the role or user your existing connection signs in as.++<Steps>+ <Step>+ In the IAM console, open the role or user. On the **Permissions** tab, select **Add permissions** > **Create inline policy**, switch to the **JSON** editor, and paste the policy.+ </Step>+ <Step>+ Select **Next**, enter a **Policy name**, then select **Create policy**.+ </Step>+ <Step>+ If you created a new role, copy its **ARN** from the **Summary** section.++ + </Step>+</Steps>++### Step 3: Finish in Infisical++Go back to the **Session Logs** dialog.++<Steps>+ <Step>+ Under **AWS Connection**, select **Create New Connection**.++ <Note>+ If you already have an AWS app connection you want to use, select it here instead. Then, select **Save** and skip the remaining steps.+ </Note>+ </Step>+ <Step>+ Enter a **Name**, keep the **Assume Role (Recommended)** method, paste the role's ARN into **Role ARN**, and select **Connect to AWS**. Infisical creates the connection in Agent Vault and selects it.+ </Step>+ <Step>+ Select **Save**.+ </Step>+</Steps>++<Frame>+ <img src="/images/platform/agent-vault/session-logs-setup.png" alt="The Session Logs dialog with Enable turned on and an AWS connection, region, bucket, and key prefix filled in" />+</Frame>++When you save, Infisical checks that the bucket exists and that the IAM user or role can write to it. If either check fails, Infisical shows the error and doesn't save the settings. If your browser can't read from the bucket, the **Session Logs** card shows a warning after you save.++<Check>+ You've successfully set up external storage for session logs.+</Check>+## Managing session logs+### Turning session logs off++Session logs are on unless an admin turns them off. To stop recording, turn off **Enable** in the **Session Logs** dialog and select **Save**.++Turning session logs off also hides the logs already recorded:++- With default storage, turning session logs back on shows those logs again, as long as they're less than 30 days old+- With external storage, Infisical forgets the bucket and its AWS connection (to see the logs again, set up the same bucket and key prefix)+### Connections-Session logs use one AWS connection at a time, which you select in the **Session Logs** dialog.+If you use external storage, session logs use one AWS connection at a time, which you select in the **Session Logs** dialog.To update the connection's AWS credentials, open the menu next to **Configure** on the **Session Logs** card and select **Edit AWS Credentials**. If the connection belongs to your organization, update its credentials under **Integrations** in your organization instead.@@ -248,18 +262,25 @@ To add or delete Agent Vault's AWS connections, select **Manage Connections** fr<img src="/images/platform/agent-vault/session-logs-connections.png" alt="The Manage Connections sheet listing Agent Vault's AWS connections, with the one session logs use marked In Use" /></Frame>-You can't delete a connection while session logs use it. To delete the connection, select a different one in the **Session Logs** dialog first.+You can't delete a connection while session logs use it. To delete the connection, first turn session logs off, select a different connection, or switch to default storage in the **Session Logs** dialog.-### Changing the bucket or prefix+### Changing where session logs are stored-Infisical doesn't copy existing records when you change the bucket or the key prefix. Records written before the change don't show in Infisical until you switch back to that bucket and prefix.+Infisical doesn't copy existing records when you switch storage or change the bucket or key prefix. Records written before the change don't show in Infisical until you switch back.++If you switch away from default storage, logs already in default storage still expire after 30 days.### Retention-Infisical never deletes sessions or their session logs. To delete older logs automatically, add an [S3 Lifecycle rule](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html) to the bucket.+How long session logs are kept depends on where they're stored:++- **Default storage**: you can look back at the last 30 days of session logs, unless your plan sets a different period+- **External storage**: Infisical never deletes session logs from your bucket (to delete older logs automatically, add an [S3 Lifecycle rule](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html) to the bucket)-Don't modify or add files under the key prefix or bucket that session logs use. Restrict who in your AWS account can delete or overwrite these files.+If you use external storage, don't modify or add files in the folder that session logs use. Restrict who in your AWS account can delete or overwrite these files.## TroubleshootingIf the AWS connection returns an error, a red alert icon appears next to **Settings** in the Agent Vault sidebar, and the **Settings** page shows the error.++If you use default storage and session logs can't be read, contact Infisical support, or your server administrator if you self-host.diff --git a/docs/documentation/platform/agent-vault/sessions-api.mdx b/docs/documentation/platform/agent-vault/sessions-api.mdxindex 99f858aac6..903570a77c 100644--- a/docs/documentation/platform/agent-vault/sessions-api.mdx+++ b/docs/documentation/platform/agent-vault/sessions-api.mdx@@ -127,7 +127,7 @@ Revoke the session even if the agent fails, for example in a `finally` block orIn Agent Vault, go to **Sessions** and select **All Sessions**. The **Identity** column shows the machine identity's name for the session you created. The session's **Status** is **Active** while the agent runs, and **Revoked** after [Step 5](#step-5-revoke-the-session).-If you've [set up session logs](/documentation/platform/agent-vault/session-logs#setting-up-session-logs), [view the session's logs](/documentation/platform/agent-vault/sessions#view-session-logs) to check which requests the agent made during the session.+[View the session's logs](/documentation/platform/agent-vault/sessions#view-session-logs) to check which requests the agent made during the session.<Check>Your code now creates a session for each agent run, and the agent's credentials stop working when you revoke the session or its `ttl` runs out.diff --git a/docs/documentation/platform/agent-vault/sessions-cli.mdx b/docs/documentation/platform/agent-vault/sessions-cli.mdxindex 4f05426cca..7efefd04eb 100644--- a/docs/documentation/platform/agent-vault/sessions-cli.mdx+++ b/docs/documentation/platform/agent-vault/sessions-cli.mdx@@ -158,7 +158,7 @@ To run agents on many machines, give every machine the same command and point thAfter the agent runs, go to **Sessions** in Agent Vault and select **All Sessions**. Each run has its own session, with the machine identity's name in the **Identity** column. A session's **Status** is **Active** while the agent runs, and **Revoked** after the agent exits.-If you've [set up session logs](/documentation/platform/agent-vault/session-logs#setting-up-session-logs), [view a session's logs](/documentation/platform/agent-vault/sessions#view-session-logs) to check which requests the agent made during that run.+[View a session's logs](/documentation/platform/agent-vault/sessions#view-session-logs) to check which requests the agent made during that run.<Check>Your agent now runs on its own with a new session each time, and each session ends when the agent exits.diff --git a/docs/documentation/platform/agent-vault/sessions.mdx b/docs/documentation/platform/agent-vault/sessions.mdxindex 2aa7c65233..7dc84700e8 100644--- a/docs/documentation/platform/agent-vault/sessions.mdx+++ b/docs/documentation/platform/agent-vault/sessions.mdx@@ -77,7 +77,7 @@ Anyone granted at least one access bundle can create a session. Admins can creat## View session logs-Session logs record every request an agent makes during a session. If you haven't already, [set up session logs](/documentation/platform/agent-vault/session-logs#setting-up-session-logs). Then go to **Sessions** and select **View Session Logs** on the session's row. You can filter and search the requests, and while the session is active, new logs keep appearing.+[Session logs](/documentation/platform/agent-vault/session-logs) record every request an agent makes during a session. To view them, go to **Sessions** and select **View Session Logs** on the session's row. You can filter and search the requests, and while the session is active, new logs keep appearing.<Frame><img src="/images/platform/agent-vault/session-logs-view.png" alt="The Session Logs sheet for an active session, listing each request's time, method, host, path, upstream status, and outcome" />diff --git a/docs/integrations/app-connections/aws.mdx b/docs/integrations/app-connections/aws.mdxindex 28a483dfea..0eee9a8460 100644--- a/docs/integrations/app-connections/aws.mdx+++ b/docs/integrations/app-connections/aws.mdx@@ -87,7 +87,7 @@ Next, add the required policies to the IAM role or user from [Step 1](#step-1-cr</UseCase><UseCase use="agent-vault-session-logs" hideWhenEmpty>- - `<session-logs-bucket>` and `<key-prefix>`: the bucket and key prefix you'll enter in the **Session Logs** dialog in Agent Vault (if you won't set a key prefix, delete `<key-prefix>/`)+ - `<session-logs-bucket>` and `<key-prefix>`: the bucket and key prefix you'll enter in the **Session Logs** dialog in Agent Vault (if you won't set a key prefix, delete `<key-prefix>/` in both places)</UseCase><UseCase use="private-ca" hideWhenEmpty>diff --git a/docs/self-hosting/configuration/envars.mdx b/docs/self-hosting/configuration/envars.mdxindex 2be05368ba..1fd45bf029 100644--- a/docs/self-hosting/configuration/envars.mdx+++ b/docs/self-hosting/configuration/envars.mdx@@ -494,6 +494,32 @@ NODE_EXTRA_CA_CERTS=/path/to/ca.crtFor Redis Sentinel or Cluster mode, use the `REDIS_SENTINEL_ENABLE_TLS` or `REDIS_CLUSTER_ENABLE_TLS` environment variables respectively.+### Object storage (optional)++Set these variables to give the instance an Amazon S3 bucket for Agent Vault session logs, called default storage. Without it, organizations can only store session logs in their own bucket. To create the bucket and its IAM policy, see [Default storage for session logs](/self-hosting/guides/session-log-storage).++If you set only some of these variables, such as a bucket without a region, Infisical doesn't start.++<ParamField query="OBJECT_STORAGE_S3_BUCKET" type="string" optional>+ The name of a general purpose S3 bucket. Requires `OBJECT_STORAGE_S3_REGION`.+</ParamField>++<ParamField query="OBJECT_STORAGE_S3_REGION" type="string" optional>+ The AWS region of the bucket, such as `us-east-1`. Requires `OBJECT_STORAGE_S3_BUCKET`.+</ParamField>++<ParamField query="OBJECT_STORAGE_S3_PREFIX" type="string" optional>+ The folder in the bucket to store files under, such as `infisical`. Up to 256 characters: letters, numbers, and `! - _ . ' ( ) /`, with no slash at the start or end.+</ParamField>++<ParamField query="OBJECT_STORAGE_S3_ACCESS_KEY_ID" type="string" optional>+ The access key ID of an IAM user that can use the bucket. Set it together with `OBJECT_STORAGE_S3_SECRET_ACCESS_KEY`. If you leave out both, Infisical finds credentials the way the AWS SDK does by default, for example from the instance's role.+</ParamField>++<ParamField query="OBJECT_STORAGE_S3_SECRET_ACCESS_KEY" type="string" optional>+ The secret access key for `OBJECT_STORAGE_S3_ACCESS_KEY_ID`.+</ParamField>+## Email serviceWithout email configuration, Infisical's core functions like sign-up/login and secret operations work, but this disables multi-factor authentication, email invites for projects, alerts for suspicious logins, and all other email-dependent features.diff --git a/docs/self-hosting/guides/session-log-storage.mdx b/docs/self-hosting/guides/session-log-storage.mdxnew file mode 100644index 0000000000..449c1da21b--- /dev/null+++ b/docs/self-hosting/guides/session-log-storage.mdx@@ -0,0 +1,128 @@+---+title: "Default storage for session logs"+sidebarTitle: "Session log storage"+description: "Give your instance an Amazon S3 bucket so organizations can record Agent Vault session logs without a bucket of their own"+---++Agent Vault [session logs](/documentation/platform/agent-vault/session-logs) record every request an AI agent makes. Organizations can store them in their own S3 bucket, called external storage, or in default storage: one S3 bucket that you set up for the whole instance.++After you set up default storage, organizations on your instance can record session logs with nothing to set up.++## Prerequisites++- An AWS account where you can create an [S3 bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html), an IAM policy, and [S3 Lifecycle rules](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html)+- Access to the [environment variables](/self-hosting/configuration/envars) of your Infisical instances++## Step 1: Create the bucket++Create a [general purpose S3 bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html) for session logs. Directory buckets don't work. Keep **Block all public access** turned on, because browsers download session logs through signed links that don't need public access.++## Step 2: Add a CORS rule++Browsers download session logs directly from the bucket, so the bucket has to accept requests from your Infisical URL.++<Steps>+ <Step>+ In the Amazon S3 console, open the bucket, go to **Permissions**, and select **Edit** under **Cross-origin resource sharing (CORS)**.+ </Step>+ <Step>+ Paste this rule with your instance's URL in `AllowedOrigins`, then select **Save changes**:++ ```json+ [+ {+ "AllowedHeaders": ["*"],+ "AllowedMethods": ["GET"],+ "AllowedOrigins": ["https://<your-infisical-url>"],+ "MaxAgeSeconds": 3000+ }+ ]+ ```+ </Step>+</Steps>++## Step 3: Add lifecycle rules++Infisical tags each session log with the retention period of the organization's plan, as `retention=<days>d`. The retention period is 30 days unless your license sets a different one. Infisical doesn't delete files itself: an S3 Lifecycle rule for each tag deletes them.++Add one rule for `retention=30d`, and one more rule for each other retention period your license uses. If no rule matches a tag, the files with that tag are never deleted.++<Steps>+ <Step>+ In the Amazon S3 console, open the bucket, go to **Management**, and select **Create lifecycle rule**.+ </Step>+ <Step>+ Enter a **Lifecycle rule name**, such as `session-logs-30d`, and select **Limit the scope of this rule using one or more filters**.+ </Step>+ <Step>+ Under **Object tags**, select **Add tag**, and enter `retention` as the key and `30d` as the value.+ </Step>+ <Step>+ Under **Lifecycle rule actions**, select **Expire current versions of objects**, and enter `30` in **Days after object creation**.++ If the bucket has versioning turned on, also select **Permanently delete noncurrent versions of objects**, or expired session logs stay in the bucket as noncurrent versions.+ </Step>+ <Step>+ Select **Create rule**.+ </Step>+</Steps>++## Step 4: Give Infisical access to the bucket++Infisical stores session logs under `<prefix>/` in the bucket, where `<prefix>` is the optional `OBJECT_STORAGE_S3_PREFIX` you set in [Step 5](#step-5-configure-infisical). Create this IAM policy, with your bucket and prefix in place of the placeholders:++```json+{+ "Version": "2012-10-17",+ "Statement": [+ {+ "Sid": "AllowSessionLogObjects",+ "Effect": "Allow",+ "Action": ["s3:PutObject", "s3:PutObjectTagging", "s3:GetObject"],+ "Resource": "arn:aws:s3:::<bucket>/<prefix>/*"+ },+ {+ "Sid": "AllowSessionLogBucket",+ "Effect": "Allow",+ "Action": "s3:ListBucket",+ "Resource": "arn:aws:s3:::<bucket>",+ "Condition": { "StringLike": { "s3:prefix": "<prefix>/*" } }+ }+ ]+}+```++If you won't set a prefix, delete `<prefix>/` in both places. Infisical needs `s3:PutObjectTagging` to add the retention tag to each upload.++Attach the policy to the identity Infisical uses for default storage:++- The role your Infisical instances already run as, such as an EC2 instance profile or an EKS service account role+- An IAM user whose access key you set in [Step 5](#step-5-configure-infisical)++## Step 5: Configure Infisical++Set these [environment variables](/self-hosting/configuration/envars#object-storage-optional) on every Infisical instance, then restart the instances:++```bash+OBJECT_STORAGE_S3_BUCKET=<bucket>+OBJECT_STORAGE_S3_REGION=<region>+# Optional: the folder in the bucket to store session logs under+OBJECT_STORAGE_S3_PREFIX=<prefix>+# Optional: only if Infisical doesn't run as a role with the policy from Step 4+OBJECT_STORAGE_S3_ACCESS_KEY_ID=<access-key-id>+OBJECT_STORAGE_S3_SECRET_ACCESS_KEY=<secret-access-key>+```++If you leave out the access key variables, Infisical finds credentials the way the AWS SDK does by default, for example from the instance's role.++If you set only some of the variables, such as a bucket without a region or an access key ID without its secret, Infisical doesn't start, and its log names the missing variable.++<Note>+ If your instance runs in FIPS mode, Infisical reaches the bucket through the [S3 FIPS endpoint](https://aws.amazon.com/compliance/fips/) of the bucket's region, so choose a region that has one.+</Note>++## Check default storage++In an organization on your instance, go to Agent Vault, then **Administration** > **Settings**. The **Session Logs** card shows that session logs are on in default storage.++When Infisical starts, it checks that it can list the bucket, write a tagged test file under `<prefix>/` and read it back, and that the bucket's CORS rule allows downloads from your `SITE_URL`. If a check fails, Infisical logs an error that names the step, such as a missing `s3:PutObjectTagging`, a missing `s3:GetObject` or a missing CORS rule. Organizations don't see this error, so check the Infisical logs after you set up the bucket.diff --git a/docs/snippets/app-connections/aws/use-cases.jsx b/docs/snippets/app-connections/aws/use-cases.jsxindex 8c47ab2f2e..26ceec9f61 100644--- a/docs/snippets/app-connections/aws/use-cases.jsx+++ b/docs/snippets/app-connections/aws/use-cases.jsx@@ -326,7 +326,10 @@ export const awsUseCaseGroups = [Sid: "AllowAgentVaultSessionLogBucket",Effect: "Allow",Action: ["s3:ListBucket"],- Resource: "arn:aws:s3:::<session-logs-bucket>"+ Resource: "arn:aws:s3:::<session-logs-bucket>",+ Condition: {+ StringLike: { "s3:prefix": "<key-prefix>/*" }+ }}]}diff --git a/frontend/src/components/agent-vault/AgentVaultSessionLogUpgradeModal.tsx b/frontend/src/components/agent-vault/AgentVaultSessionLogUpgradeModal.tsxindex b32ac05d11..1150e1eb96 100644--- a/frontend/src/components/agent-vault/AgentVaultSessionLogUpgradeModal.tsx+++ b/frontend/src/components/agent-vault/AgentVaultSessionLogUpgradeModal.tsx@@ -1,20 +1,33 @@import {+ AgentVaultSessionLogDefaultStorageUpgradeIntent,AgentVaultSessionLogsUpgradeIntent,UpgradeGate} from "@app/components/license/UpgradeGate";+import { AgentVaultSessionLogStorageType } from "@app/hooks/api/agentVault/enums";type Props = {isOpen: boolean;onOpenChange: (isOpen: boolean) => void;+ storageType?: AgentVaultSessionLogStorageType;};-export const AgentVaultSessionLogUpgradeModal = ({ isOpen, onOpenChange }: Props) => (+export const AgentVaultSessionLogUpgradeModal = ({+ isOpen,+ onOpenChange,+ storageType = AgentVaultSessionLogStorageType.External+}: Props) => (<UpgradeGate- paywallKey="agent-vault.session-logs"+ paywallKey={+ storageType === AgentVaultSessionLogStorageType.Default+ ? "agent-vault.session-logs.default-storage"+ : "agent-vault.session-logs"+ }isOpen={isOpen}onOpenChange={onOpenChange}intent={{- ...AgentVaultSessionLogsUpgradeIntent,+ ...(storageType === AgentVaultSessionLogStorageType.Default+ ? AgentVaultSessionLogDefaultStorageUpgradeIntent+ : AgentVaultSessionLogsUpgradeIntent),isEnterpriseFeature: true}}/>diff --git a/frontend/src/components/license/UpgradeGate/capability-upgrade-intents.ts b/frontend/src/components/license/UpgradeGate/capability-upgrade-intents.tsindex 2235eadabd..5f8c93367b 100644--- a/frontend/src/components/license/UpgradeGate/capability-upgrade-intents.ts+++ b/frontend/src/components/license/UpgradeGate/capability-upgrade-intents.ts@@ -24,7 +24,8 @@ export type CapabilityUpgradeIntent = {| "sso_enforcement"| "machine_identity_auth_templates"| "identity_auth"- | "agent_vault_byo_s3";+ | "agent_vault_byo_s3"+ | "agent_vault_managed_storage";productName?: string;title: string;description: string;@@ -248,3 +249,12 @@ export const AgentVaultSessionLogsUpgradeIntent = {description: "Record agent requests in your own storage for review and investigation.",isEnterpriseFeature: true} satisfies CapabilityUpgradeIntent;++export const AgentVaultSessionLogDefaultStorageUpgradeIntent = {+ scope: "product",+ productName: "Agent Vault",+ featureKey: "agent_vault_managed_storage",+ title: "Unlock Agent Vault Session Logs",+ description: "Record what your agents do, with nothing to set up.",+ isEnterpriseFeature: true+} satisfies CapabilityUpgradeIntent;diff --git a/frontend/src/components/license/UpgradeGate/index.ts b/frontend/src/components/license/UpgradeGate/index.tsindex 631b599a9b..a9e2114a39 100644--- a/frontend/src/components/license/UpgradeGate/index.ts+++ b/frontend/src/components/license/UpgradeGate/index.ts@@ -1,5 +1,6 @@export type { CapabilityUpgradeIntent } from "./capability-upgrade-intents";export {+ AgentVaultSessionLogDefaultStorageUpgradeIntent,AgentVaultSessionLogsUpgradeIntent,AuditLogStreamsUpgradeIntent,AuditLogsUpgradeIntent,diff --git a/frontend/src/helpers/agentVaultSessionLogs.test.ts b/frontend/src/helpers/agentVaultSessionLogs.test.tsnew file mode 100644index 0000000000..62024179fb--- /dev/null+++ b/frontend/src/helpers/agentVaultSessionLogs.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from "vitest";++import { AgentVaultSessionLogStorageType } from "@app/hooks/api/agentVault/enums";+import { TAgentVaultSessionLogSettings } from "@app/hooks/api/agentVault/types";++import {+ canTurnOnAgentVaultSessionLogs,+ getAgentVaultSessionLogRetentionDays,+ isAgentVaultSessionLogBlockedByPlan,+ isAgentVaultSessionLogStorageOnPlan+} from "./agentVaultSessionLogs";++const defaultStorage = { type: AgentVaultSessionLogStorageType.Default } as const;+const externalStorage = {+ type: AgentVaultSessionLogStorageType.External,+ appConnectionId: "4c7a3a1e-7b2f-4b9e-9f0d-1a2b3c4d5e6f",+ bucket: "globex-audit",+ region: "eu-west-1",+ keyPrefix: null+} as const;++const settings = (+ storage: TAgentVaultSessionLogSettings["storage"],+ overrides: Partial<TAgentVaultSessionLogSettings> = {}+): TAgentVaultSessionLogSettings => ({ enabled: true, storage, ...overrides });++const fullPlan = { agentVaultManagedStorage: true, agentVaultByoS3: true };+const noPlan = { agentVaultManagedStorage: false, agentVaultByoS3: false };+const defaultOnly = { agentVaultManagedStorage: true, agentVaultByoS3: false };+const externalOnly = { agentVaultManagedStorage: false, agentVaultByoS3: true };++describe("agent vault session log helpers", () => {+ it("reads each storage type's own plan flag", () => {+ expect(+ isAgentVaultSessionLogStorageOnPlan(AgentVaultSessionLogStorageType.Default, defaultOnly)+ ).toBe(true);+ expect(+ isAgentVaultSessionLogStorageOnPlan(AgentVaultSessionLogStorageType.External, defaultOnly)+ ).toBe(false);+ expect(+ isAgentVaultSessionLogStorageOnPlan(AgentVaultSessionLogStorageType.External, externalOnly)+ ).toBe(true);+ });++ it("uses 30 days when the plan doesn't set a retention", () => {+ expect(getAgentVaultSessionLogRetentionDays({ agentVaultSessionLogRetentionDays: null })).toBe(+ 30+ );+ expect(getAgentVaultSessionLogRetentionDays({ agentVaultSessionLogRetentionDays: 365 })).toBe(+ 365+ );+ });++ it.each([+ ["default storage on, not on the plan", settings(defaultStorage), externalOnly, true],+ ["external storage on, not on the plan", settings(externalStorage), defaultOnly, true],+ ["on and on the plan", settings(externalStorage), externalOnly, false],+ ["default storage on, on the plan", settings(defaultStorage), fullPlan, false],+ ["off", settings(defaultStorage, { enabled: false }), noPlan, false]+ ])("blocked by plan: %s", (_, value, plan, expected) => {+ expect(isAgentVaultSessionLogBlockedByPlan(value, plan)).toBe(expected);+ });++ it.each([+ ["instance bucket and default storage on the plan", true, defaultOnly, true],+ ["no instance bucket, only default storage on the plan", false, defaultOnly, false],+ ["no instance bucket, external storage on the plan", false, externalOnly, true],+ ["neither on the plan", true, noPlan, false]+ ])("can turn on: %s", (_, isConfigured, plan, expected) => {+ expect(canTurnOnAgentVaultSessionLogs(isConfigured, plan)).toBe(expected);+ });+});diff --git a/frontend/src/helpers/agentVaultSessionLogs.ts b/frontend/src/helpers/agentVaultSessionLogs.tsindex 4ba76846a0..b46edb9241 100644--- a/frontend/src/helpers/agentVaultSessionLogs.ts+++ b/frontend/src/helpers/agentVaultSessionLogs.ts@@ -1,10 +1,40 @@+import { AgentVaultSessionLogStorageType } from "@app/hooks/api/agentVault/enums";import { TAgentVaultSessionLogSettings } from "@app/hooks/api/agentVault/types";import { SubscriptionPlan } from "@app/hooks/api/subscriptions/types";-export const areAgentVaultSessionLogsOn = (settings: TAgentVaultSessionLogSettings) =>- Boolean(settings.enabled && settings.appConnectionId && settings.bucket && settings.region);+type TSessionLogPlan = Pick<+ SubscriptionPlan,+ "agentVaultManagedStorage" | "agentVaultByoS3" | "agentVaultSessionLogRetentionDays"+>;-export const isAgentVaultSessionLogPlanLapsed = (- settings: TAgentVaultSessionLogSettings,- subscription: Pick<SubscriptionPlan, "agentVaultByoS3">-) => Boolean(settings.bucket) && !subscription.agentVaultByoS3;+const DEFAULT_RETENTION_DAYS = 30;++export const isAgentVaultSessionLogStorageOnPlan = (+ type: AgentVaultSessionLogStorageType,+ plan: Pick<TSessionLogPlan, "agentVaultManagedStorage" | "agentVaultByoS3">+) =>+ Boolean(+ type === AgentVaultSessionLogStorageType.Default+ ? plan.agentVaultManagedStorage+ : plan.agentVaultByoS3+ );++export const getAgentVaultSessionLogRetentionDays = (+ plan: Pick<TSessionLogPlan, "agentVaultSessionLogRetentionDays">+) => plan.agentVaultSessionLogRetentionDays ?? DEFAULT_RETENTION_DAYS;++// On, but not recording because the plan doesn't include the storage, saved or not.+export const isAgentVaultSessionLogBlockedByPlan = (+ settings: TAgentVaultSessionLogSettings | null | undefined,+ plan: Pick<TSessionLogPlan, "agentVaultManagedStorage" | "agentVaultByoS3">+) =>+ Boolean(settings?.enabled && !isAgentVaultSessionLogStorageOnPlan(settings.storage.type, plan));++// Whether any storage this instance offers is on the plan, so session logs can be turned on at all.+export const canTurnOnAgentVaultSessionLogs = (+ isDefaultStorageConfigured: boolean,+ plan: Pick<TSessionLogPlan, "agentVaultManagedStorage" | "agentVaultByoS3">+) =>+ (isDefaultStorageConfigured &&+ isAgentVaultSessionLogStorageOnPlan(AgentVaultSessionLogStorageType.Default, plan)) ||+ isAgentVaultSessionLogStorageOnPlan(AgentVaultSessionLogStorageType.External, plan);diff --git a/frontend/src/hooks/api/agentVault/enums.ts b/frontend/src/hooks/api/agentVault/enums.tsindex 75d997b948..c78aa575a9 100644--- a/frontend/src/hooks/api/agentVault/enums.ts+++ b/frontend/src/hooks/api/agentVault/enums.ts@@ -57,3 +57,8 @@ export enum AgentVaultVariableReferenceField {CustomHeader = "custom-header",Substitution = "substitution"}++export enum AgentVaultSessionLogStorageType {+ Default = "default",+ External = "external"+}diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsxindex 71f11582cc..b2fc8a2080 100644--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@ -18,7 +18,7 @@ import {TAgentVaultProxySettingsDTO,TAgentVaultProxyWithToken,TAgentVaultService,- TAgentVaultSessionLogSettings,+ TAgentVaultSessionLogSettingsState,TAgentVaultVariable,TAgentVaultWrittenMember,TCreateAgentVaultAccessBundleDTO,@@ -378,14 +378,14 @@ export const useUpdateAgentVaultSessionLogSettings = () => {return useMutation({mutationFn: async (params: TUpdateAgentVaultSessionLogSettingsDTO) => {- const { data } = await apiRequest.patch<{ settings: TAgentVaultSessionLogSettings }>(+ const { data } = await apiRequest.patch<TAgentVaultSessionLogSettingsState>("/api/v1/agent-vault/settings/session-logs",params);- return data.settings;+ return data;},- onSuccess: (settings) => {- queryClient.setQueryData(agentVaultKeys.sessionLogSettings(currentOrg.id), settings);+ onSuccess: (state) => {+ queryClient.setQueryData(agentVaultKeys.sessionLogSettings(currentOrg.id), state);// Reset, not invalidate: the cached result may be for the previous bucket.queryClient.resetQueries({queryKey: agentVaultKeys.sessionLogCorsProbe(currentOrg.id)diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsxindex d21cda2c84..b966ee4e69 100644--- a/frontend/src/hooks/api/agentVault/queries.tsx+++ b/frontend/src/hooks/api/agentVault/queries.tsx@@ -32,7 +32,7 @@ import {TAgentVaultSessionLogHealth,TAgentVaultSessionLogHistoryPage,TAgentVaultSessionLogReadCheck,- TAgentVaultSessionLogSettings,+ TAgentVaultSessionLogSettingsState,TAgentVaultSessionLogTailPage,TAgentVaultVariable,TListAgentVaultAccessBundlesDTO,@@ -277,10 +277,10 @@ export const useGetAgentVaultSessionLogSettings = (enabled = true) => {return useQuery({queryKey: agentVaultKeys.sessionLogSettings(currentOrg.id),queryFn: async () => {- const { data } = await apiRequest.get<{ settings: TAgentVaultSessionLogSettings }>(+ const { data } = await apiRequest.get<TAgentVaultSessionLogSettingsState>("/api/v1/agent-vault/settings/session-logs");- return data.settings;+ return data;},enabled});diff --git a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.tsindex 7573114aaa..f718bc6cca 100644--- a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts+++ b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts@@ -67,6 +67,8 @@ describe("decryptSessionLogPage", () => {const page: TAgentVaultSessionLogPage = {sessionLogs: {enabled: true,+ disabledReason: null,+ storageType: null,isRecordable: true,sessionKey: btoa("\0".repeat(32))},@@ -91,6 +93,8 @@ describe("decryptSessionLogPage", () => {const vectorPage: TAgentVaultSessionLogPage = {sessionLogs: {enabled: true,+ disabledReason: null,+ storageType: null,isRecordable: true,sessionKey: "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="},@@ -285,7 +289,13 @@ describe("mergeSessionLogPages", () => {presignedGetUrl: `https://bucket.example/${proxyId}`});const decryptedPage = (proxyId: string, path: string) => ({- sessionLogs: { enabled: true, isRecordable: true, sessionKey: null },+ sessionLogs: {+ enabled: true,+ disabledReason: null,+ storageType: null,+ isRecordable: true,+ sessionKey: null+ },chunks: [chunk(proxyId)],decrypted: {[sessionLogChunkKey(chunk(proxyId))]: {diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex eb315ee841..fe2b4f5377 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -3,6 +3,7 @@ import {AgentVaultHttpMethod,AgentVaultMemberType,AgentVaultSessionLogDecision,+ AgentVaultSessionLogStorageType,AgentVaultSessionScope,AgentVaultSessionStatus,AgentVaultSubstitutionSurface,@@ -306,12 +307,27 @@ export type TAgentVaultProxySettingsDTO = {pollInterval?: number;};+export type TAgentVaultSessionLogExternalStorage = {+ type: AgentVaultSessionLogStorageType.External;+ appConnectionId: string;+ bucket: string;+ region: string;+ keyPrefix: string | null;+};++export type TAgentVaultSessionLogStorage =+ | { type: AgentVaultSessionLogStorageType.Default }+ | TAgentVaultSessionLogExternalStorage;+export type TAgentVaultSessionLogSettings = {enabled: boolean;- appConnectionId: string | null;- bucket: string | null;- region: string | null;- keyPrefix: string | null;+ storage: TAgentVaultSessionLogStorage;+};++// settings is null when the instance has no default storage and no external bucket is saved.+export type TAgentVaultSessionLogSettingsState = {+ settings: TAgentVaultSessionLogSettings | null;+ defaultStorage: { configured: boolean };};export type TAgentVaultSessionLogHealth = {@@ -334,13 +350,13 @@ export type TAgentVaultSessionLogReadCheck = {host: string;};-export type TUpdateAgentVaultSessionLogSettingsDTO = {- enabled?: boolean;- appConnectionId?: string | null;- bucket?: string;- region?: string;- keyPrefix?: string;-};+export type TAgentVaultSessionLogStorageInput =+ | { type: AgentVaultSessionLogStorageType.Default }+ | (Omit<TAgentVaultSessionLogExternalStorage, "keyPrefix"> & { keyPrefix?: string });++export type TUpdateAgentVaultSessionLogSettingsDTO =+ | { enabled: false }+ | { enabled: true; storage: TAgentVaultSessionLogStorageInput };export type TAgentVaultSessionLogChunk = {chunkId: string;@@ -349,8 +365,12 @@ export type TAgentVaultSessionLogChunk = {presignedGetUrl: string;};+export type TAgentVaultSessionLogDisabledReason = "off" | "not-on-plan";+export type TAgentVaultSessionLog = {enabled: boolean;+ disabledReason: TAgentVaultSessionLogDisabledReason | null;+ storageType: AgentVaultSessionLogStorageType | null;isRecordable: boolean;sessionKey: string | null;};diff --git a/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.test.ts b/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.test.tsindex 8d557655c3..58fdbb6d8a 100644--- a/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.test.ts+++ b/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.test.ts@@ -22,7 +22,13 @@ const record = {} as TAgentVaultDecryptedChunk["records"][number];const pageWith = (result: TAgentVaultDecryptedChunk): TAgentVaultDecryptedSessionLogPage => ({- sessionLogs: { enabled: true, isRecordable: true, sessionKey: null },+ sessionLogs: {+ enabled: true,+ disabledReason: null,+ storageType: null,+ isRecordable: true,+ sessionKey: null+ },chunks: [{chunkId,diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.tsindex 4133131256..355435d8df 100644--- a/frontend/src/hooks/api/subscriptions/types.ts+++ b/frontend/src/hooks/api/subscriptions/types.ts@@ -118,6 +118,9 @@ export type SubscriptionPlan = {honeyTokenLimit: number;secretsBrokering: boolean;agentVaultByoS3: boolean;+ agentVaultManagedStorage: boolean;+ // null means 30 days.+ agentVaultSessionLogRetentionDays: number | null;pam?: boolean | null;enterprisePamAccount?: boolean | null;maxPamAccounts?: number | null;diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsxindex ed64de560d..17282d97a7 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx@@ -8,10 +8,7 @@ import {SidebarMenuItem} from "@app/components/v3";import { useProjectPermission, useSubscription } from "@app/context";-import {- areAgentVaultSessionLogsOn,- isAgentVaultSessionLogPlanLapsed-} from "@app/helpers/agentVaultSessionLogs";+import { isAgentVaultSessionLogBlockedByPlan } from "@app/helpers/agentVaultSessionLogs";import {useGetAgentVaultSessionLogHealth,useGetAgentVaultSessionLogSettings@@ -25,7 +22,8 @@ export const AgentVaultNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submconst { hasProjectRole } = useProjectPermission();const { setOpen: setIsIntroOpen } = useAgentVaultIntro();const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);- const { data: sessionLogSettings } = useGetAgentVaultSessionLogSettings(isAdmin);+ const { data: sessionLogState } = useGetAgentVaultSessionLogSettings(isAdmin);+ const sessionLogSettings = sessionLogState?.settings ?? null;const { data: sessionLogHealth } = useGetAgentVaultSessionLogHealth(isAdmin);const { subscription } = useSubscription();@@ -42,9 +40,8 @@ export const AgentVaultNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submlet settingsAlert: NavItem["alertVariant"];if (sessionLogHealth?.connectionError) settingsAlert = "danger";else if (- sessionLogSettings?.bucket &&- (!areAgentVaultSessionLogsOn(sessionLogSettings) ||- isAgentVaultSessionLogPlanLapsed(sessionLogSettings, subscription))+ (sessionLogSettings && !sessionLogSettings.enabled) ||+ isAgentVaultSessionLogBlockedByPlan(sessionLogSettings, subscription))settingsAlert = "warning";diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsxindex e86c29b533..a9a9ee948a 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx@@ -64,10 +64,7 @@ import {TooltipTrigger} from "@app/components/v3";import { useOrganization, useProjectPermission, useSubscription } from "@app/context";-import {- areAgentVaultSessionLogsOn,- isAgentVaultSessionLogPlanLapsed-} from "@app/helpers/agentVaultSessionLogs";+import { isAgentVaultSessionLogBlockedByPlan } from "@app/helpers/agentVaultSessionLogs";import {getUserTablePreference,PreferenceKey,@@ -84,6 +81,7 @@ import {useListAgentVaultAccessBundles,useListAgentVaultSessions} from "@app/hooks/api/agentVault";+import { AgentVaultSessionLogStorageType } from "@app/hooks/api/agentVault/enums";import { TAgentVaultMintedSession, TAgentVaultSession } from "@app/hooks/api/agentVault/types";import { ProjectType } from "@app/hooks/api/projects/types";import { ProjectMembershipRole } from "@app/hooks/api/roles/types";@@ -140,12 +138,15 @@ export const AgentVaultSessionsPage = () => {offset: (page - 1) * perPage});const { data: accessBundles } = useListAgentVaultAccessBundles({ limit: 1 });- const { data: sessionLogSettings } = useGetAgentVaultSessionLogSettings(isAdmin);+ const { data: sessionLogState } = useGetAgentVaultSessionLogSettings(isAdmin);const { data: sessionLogHealth } = useGetAgentVaultSessionLogHealth(isAdmin);const { subscription } = useSubscription();const [isUpgradeOpen, setIsUpgradeOpen] = useState(false);- const isSessionLogPlanLapsed = Boolean(- sessionLogSettings && isAgentVaultSessionLogPlanLapsed(sessionLogSettings, subscription)+ const sessionLogSettings = sessionLogState?.settings ?? null;+ // Covers a saved choice the plan dropped and the unsaved default the plan never included.+ const isSessionLogBlockedByPlan = isAgentVaultSessionLogBlockedByPlan(+ sessionLogSettings,+ subscription);const sessions = data?.sessions ?? [];@@ -193,9 +194,8 @@ export const AgentVaultSessionsPage = () => {<div className="flex flex-col gap-8">{sessionLogHealth?.connectionError &&- sessionLogSettings &&- areAgentVaultSessionLogsOn(sessionLogSettings) &&- !isSessionLogPlanLapsed && (+ sessionLogSettings?.enabled &&+ !isSessionLogBlockedByPlan && (<Alert variant="danger"><CircleAlertIcon /><AlertDescription>@@ -214,12 +214,14 @@ export const AgentVaultSessionsPage = () => {</Alert>)}- {isSessionLogPlanLapsed && (+ {isSessionLogBlockedByPlan && (<Alert variant="warning"><TriangleAlertIcon /><AlertDescription><p>- Your plan no longer includes session logs, so new requests aren't recorded.+ {sessionLogSettings?.storage.type === AgentVaultSessionLogStorageType.External+ ? "Your plan no longer includes external storage. Upgrade to see recorded logs and keep recording. Recorded logs stay in your bucket."+ : "Your plan doesn't include default storage, so session logs aren't being recorded. Upgrade to record and view them."}</p><AlertAction><Button variant="outline" size="sm" onClick={() => setIsUpgradeOpen(true)}>@@ -230,30 +232,27 @@ export const AgentVaultSessionsPage = () => {</Alert>)}- {sessionLogSettings &&- Boolean(sessionLogSettings.bucket) &&- !isSessionLogPlanLapsed &&- !areAgentVaultSessionLogsOn(sessionLogSettings) && (- <Alert variant="warning">- <TriangleAlertIcon />- <AlertDescription>- <p>- Sessions aren't being logged, so there is no record of what your agents- reached.- </p>- <AlertAction>- <Button variant="outline" size="sm" asChild>- <Link- to="/organizations/$orgId/agent-vault/settings"- params={{ orgId: currentOrg.id }}- >- Go to Settings- </Link>- </Button>- </AlertAction>- </AlertDescription>- </Alert>- )}+ {sessionLogSettings && !sessionLogSettings.enabled && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ <p>+ Sessions aren't being logged, so there is no record of what your agents+ reached.+ </p>+ <AlertAction>+ <Button variant="outline" size="sm" asChild>+ <Link+ to="/organizations/$orgId/agent-vault/settings"+ params={{ orgId: currentOrg.id }}+ >+ Go to Settings+ </Link>+ </Button>+ </AlertAction>+ </AlertDescription>+ </Alert>+ )}{isAdmin && !sessionLogHealth?.connectionError && <SessionLogReadAccessAlert />}@@ -552,7 +551,11 @@ export const AgentVaultSessionsPage = () => {onRevoke={setSessionToRevoke}/>- <AgentVaultSessionLogUpgradeModal isOpen={isUpgradeOpen} onOpenChange={setIsUpgradeOpen} />+ <AgentVaultSessionLogUpgradeModal+ isOpen={isUpgradeOpen}+ onOpenChange={setIsUpgradeOpen}+ storageType={sessionLogSettings?.storage.type}+ /></div>);};diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsxindex fb6772f5f5..e340a72cb2 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx@@ -33,14 +33,17 @@ import {TableHeader,TableRow} from "@app/components/v3";-import { useOrganization, useProjectPermission, useSubscription } from "@app/context";+import { useOrganization, useProjectPermission } from "@app/context";+import { isInfisicalCloud } from "@app/helpers/platform";import {AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS,AgentVaultSessionLogDecision,+ AgentVaultSessionLogStorageType,getSessionLogStorageError,sessionLogRecordKey,useAgentVaultSessionLogTimeline,- useGetAgentVaultSessionLogs+ useGetAgentVaultSessionLogs,+ useGetAgentVaultSessionLogSettings} from "@app/hooks/api/agentVault";import { sessionLogChunkKey } from "@app/hooks/api/agentVault/sessionLogDecrypt";import {@@ -101,8 +104,9 @@ export const SessionLogsPanel = ({ session }: Props) => {const { currentOrg } = useOrganization();const { hasProjectRole } = useProjectPermission();const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);- const { subscription } = useSubscription();const [isUpgradeOpen, setIsUpgradeOpen] = useState(false);+ // Only admins can read the settings; they need the storage type to show the right upgrade.+ const { data: sessionLogState } = useGetAgentVaultSessionLogSettings(isAdmin);// A session holds one bundle (AGENT_VAULT_MAX_SESSION_BUNDLES). Raising that cap needs a bundle// picker here: the rows offering Add Service matched no service, so they name no bundle.const accessBundle = session.accessBundles[0];@@ -172,6 +176,12 @@ export const SessionLogsPanel = ({ session }: Props) => {const isLoadError = isError && !data;const isEnabled = pages?.[0]?.sessionLogs.enabled ?? false;+ const disabledReason = pages?.[0]?.sessionLogs.disabledReason ?? null;+ // Default storage belongs to whoever runs Infisical, so nothing in Settings or the bucket's CORS rule is the reader's to+ // fix. A failed read returns no page, so admins fall back to the settings they already load.+ const isDefaultStorage =+ (pages?.[0]?.sessionLogs.storageType ?? sessionLogState?.settings?.storage.type) ===+ AgentVaultSessionLogStorageType.Default;const isRecordable = pages?.[0]?.sessionLogs.isRecordable ?? true;// Nothing new can arrive while session logs are off or for a session that can't be recorded, so the panel// doesn't go live, and an ended session doesn't promise logs that won't come.@@ -392,7 +402,7 @@ export const SessionLogsPanel = ({ session }: Props) => {</EmptyHeader><div className="flex gap-2">{retryButton}- {isAdmin && (+ {isAdmin && !isDefaultStorage && (<Button variant="av" asChild><Linkto="/organizations/$orgId/agent-vault/settings"@@ -407,24 +417,17 @@ export const SessionLogsPanel = ({ session }: Props) => {);}- // Only a running session is offered Settings or an upgrade; turning logs on can't record one that ended.- if (- !isPending &&- !isPlaceholderData &&- !isLoadError &&- isActive &&- !isEnabled &&- !hasChunks &&- !range- ) {- if (!subscription.agentVaultByoS3) {+ // Off and off-plan hide recorded logs, for ended sessions too. Upgrading shows them again, so every admin is offered+ // it; only a running session is offered Settings, since turning logs on can't record one that ended.+ if (!isPending && !isPlaceholderData && !isLoadError && disabledReason) {+ if (disabledReason === "not-on-plan") {return (<Empty className="border"><EmptyHeader><EmptyTitle>Session logs aren't on your plan</EmptyTitle><EmptyDescription>{isAdmin- ? "Upgrade to record what your agents reach."+ ? "Upgrade to see recorded logs and record what your agents reach.": "Ask an Agent Vault administrator about upgrading."}</EmptyDescription></EmptyHeader>@@ -436,14 +439,15 @@ export const SessionLogsPanel = ({ session }: Props) => {<AgentVaultSessionLogUpgradeModalisOpen={isUpgradeOpen}onOpenChange={setIsUpgradeOpen}+ storageType={sessionLogState?.settings?.storage.type}/></Empty>);}const offDescription = isAdmin- ? "Point Agent Vault at a bucket under Settings to start recording what your agents reach."- : "Ask an Agent Vault administrator to turn it on.";+ ? "Turn them on in Settings to record what your agents do."+ : "Ask an Agent Vault administrator to turn them on.";return (<Empty className="border">@@ -451,7 +455,7 @@ export const SessionLogsPanel = ({ session }: Props) => {<EmptyTitle>Session logs are off</EmptyTitle><EmptyDescription>{offDescription}</EmptyDescription></EmptyHeader>- {isAdmin && (+ {isAdmin && isActive && (<Button variant="av" asChild><Link to="/organizations/$orgId/agent-vault/settings" params={{ orgId: currentOrg.id }}>Go to Settings@@ -549,19 +553,28 @@ export const SessionLogsPanel = ({ session }: Props) => {<Alert variant="warning"><TriangleAlertIcon /><AlertDescription>- <div className="flex flex-col gap-1">+ {isDefaultStorage ? (<p>- None of this session's logs could be downloaded from the bucket. The- bucket's CORS rule may not allow this origin, or this network may block the- bucket.+ Your browser couldn't download this session's logs. Your network may be+ blocking them. Try again, or contact{" "}+ {isInfisicalCloud() ? "Infisical support" : "your server administrator"} if it keeps+ happening.</p>- {!isAdmin && (- <p>Ask an Agent Vault administrator to check the bucket's CORS rule.</p>- )}- </div>+ ) : (+ <div className="flex flex-col gap-1">+ <p>+ None of this session's logs could be downloaded from the bucket. The+ bucket's CORS rule may not allow this origin, or this network may block the+ bucket.+ </p>+ {!isAdmin && (+ <p>Ask an Agent Vault administrator to check the bucket's CORS rule.</p>+ )}+ </div>+ )}<AlertAction className="flex gap-2">{retryButton}- {isAdmin && (+ {isAdmin && !isDefaultStorage && (<Button variant="outline" size="sm" asChild><Linkto="/organizations/$orgId/agent-vault/settings"diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/AwsSetupDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/AwsSetupDialog.tsxindex 169b44895a..3df6014d31 100644--- a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/AwsSetupDialog.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/AwsSetupDialog.tsx@@ -24,7 +24,7 @@ import { useOrganization } from "@app/context";import { agentVaultKeys, useGetAgentVaultSessionLogCorsProbe } from "@app/hooks/api/agentVault";const iamPolicyFor = (bucket: string, keyPrefix: string) => {- const objects = `arn:aws:s3:::${bucket || "<bucket>"}/${keyPrefix ? `${keyPrefix}/` : ""}*`;+ const folder = keyPrefix ? `${keyPrefix}/` : "";return JSON.stringify({Version: "2012-10-17",@@ -32,12 +32,13 @@ const iamPolicyFor = (bucket: string, keyPrefix: string) => {{Effect: "Allow",Action: ["s3:PutObject", "s3:GetObject"],- Resource: objects+ Resource: `arn:aws:s3:::${bucket || "<bucket>"}/${folder}*`},{Effect: "Allow",Action: ["s3:ListBucket"],- Resource: `arn:aws:s3:::${bucket || "<bucket>"}`+ Resource: `arn:aws:s3:::${bucket || "<bucket>"}`,+ ...(folder && { Condition: { StringLike: { "s3:prefix": [`${folder}*`] } } })}]},diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogAlerts.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogAlerts.tsxindex 1058c97c5c..19dda7c8ba 100644--- a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogAlerts.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogAlerts.tsx@@ -4,40 +4,35 @@ import { CircleAlertIcon, TriangleAlertIcon } from "lucide-react";import { AgentVaultSessionLogUpgradeModal } from "@app/components/agent-vault/AgentVaultSessionLogUpgradeModal";import { Alert, AlertAction, AlertDescription, Button } from "@app/components/v3";import { useSubscription } from "@app/context";+import { isAgentVaultSessionLogBlockedByPlan } from "@app/helpers/agentVaultSessionLogs";import {- areAgentVaultSessionLogsOn,- isAgentVaultSessionLogPlanLapsed-} from "@app/helpers/agentVaultSessionLogs";-import {- useGetAgentVaultSessionLogCorsProbe,useGetAgentVaultSessionLogHealth,useGetAgentVaultSessionLogSettings} from "@app/hooks/api/agentVault";+import { AgentVaultSessionLogStorageType } from "@app/hooks/api/agentVault/enums";import { SessionLogReadAccessAlert } from "./SessionLogReadAccessAlert";export const SessionLogAlerts = () => {- const { data: config, isPending: isSettingsPending } = useGetAgentVaultSessionLogSettings();- const { data: health, isPending: isHealthPending } = useGetAgentVaultSessionLogHealth();- const { data: readCheck } = useGetAgentVaultSessionLogCorsProbe();+ const { data: state } = useGetAgentVaultSessionLogSettings();+ const { data: health } = useGetAgentVaultSessionLogHealth();const { subscription } = useSubscription();const [isUpgradeOpen, setIsUpgradeOpen] = useState(false);- const hasDestination = Boolean(config?.bucket);- const isLapsed = Boolean(config && isAgentVaultSessionLogPlanLapsed(config, subscription));- const isRecording = config ? areAgentVaultSessionLogsOn(config) : false;- const isReadBlocked = Boolean(readCheck && readCheck.status !== "readable");+ const settings = state?.settings ?? null;+ const storageType = settings?.storage.type;+ const isDefaultStorage = storageType === AgentVaultSessionLogStorageType.Default;+ const isBlockedByPlan = isAgentVaultSessionLogBlockedByPlan(settings, subscription);- const notRecordingReason = (() => {- if (!config?.enabled) {- if (!config?.appConnectionId) {- return "Session logs are off, and without an AWS connection the logs already in the bucket can't be read.";- }- if (isReadBlocked) return "Session logs are off, so nothing new is being stored.";- return "Session logs are off. Logs already in the bucket are still readable, but nothing new is being stored.";- }- return "Session logs are on, but Storage isn't complete, so nothing is being written to the bucket.";- })();+ let planMessage: string | null = null;+ // Default storage can be on without anyone choosing it, so its message can't say the plan "no longer" includes it.+ if (isBlockedByPlan && isDefaultStorage) {+ planMessage =+ "Your plan doesn't include default storage, so session logs aren't being recorded. Upgrade to record and view them.";+ } else if (isBlockedByPlan) {+ planMessage =+ "Your plan no longer includes external storage. Upgrade to see recorded logs and keep recording. Recorded logs stay in your bucket.";+ }return (<>@@ -48,14 +43,11 @@ export const SessionLogAlerts = () => {</Alert>)}- {isLapsed && (+ {planMessage && (<Alert variant="warning"><TriangleAlertIcon /><AlertDescription>- <p>- Your plan no longer includes session logs, so new requests aren't recorded.- {config?.appConnectionId && " Saved logs stay viewable."}- </p>+ <p>{planMessage}</p><AlertAction><Button variant="outline" size="sm" onClick={() => setIsUpgradeOpen(true)}>Upgrade@@ -65,25 +57,14 @@ export const SessionLogAlerts = () => {</Alert>)}- {/* While the connection is broken, fixing it comes first, so its error shows alone. */}- {!health?.connectionError && (- <>- {!isSettingsPending &&- !isHealthPending &&- hasDestination &&- !isLapsed &&- !isRecording && (- <Alert variant="warning">- <TriangleAlertIcon />- <AlertDescription>{notRecordingReason}</AlertDescription>- </Alert>- )}-- <SessionLogReadAccessAlert />- </>- )}+ {/* While the storage is broken, fixing it comes first, so its error shows alone. */}+ {!health?.connectionError && <SessionLogReadAccessAlert />}- <AgentVaultSessionLogUpgradeModal isOpen={isUpgradeOpen} onOpenChange={setIsUpgradeOpen} />+ <AgentVaultSessionLogUpgradeModal+ isOpen={isUpgradeOpen}+ onOpenChange={setIsUpgradeOpen}+ storageType={storageType}+ /></>);};diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogConnectionsSheet.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogConnectionsSheet.tsxindex 3e05a8e9ac..0b5c177448 100644--- a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogConnectionsSheet.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogConnectionsSheet.tsx@@ -45,7 +45,11 @@ import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermiimport { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";import { usePopUp } from "@app/hooks";import { useGetAgentVaultSessionLogSettings } from "@app/hooks/api/agentVault";-import { useListAppConnections } from "@app/hooks/api/appConnections";+import { AgentVaultSessionLogStorageType } from "@app/hooks/api/agentVault/enums";+import {+ useListAppConnections,+ useListAvailableAppConnections+} from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";import { DeleteAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components/DeleteAppConnectionModal";@@ -64,8 +68,21 @@ type Props = {export const SessionLogConnectionsSheet = ({ isOpen, onOpenChange }: Props) => {const { currentProject } = useProject();const { permission } = useProjectPermission();- const { data: settings } = useGetAgentVaultSessionLogSettings();+ const { data: state } = useGetAgentVaultSessionLogSettings();+ const sessionLogStorage = state?.settings?.storage;+ const sessionLogConnectionId =+ sessionLogStorage?.type === AgentVaultSessionLogStorageType.External+ ? sessionLogStorage.appConnectionId+ : null;const { data: connections = [], isPending } = useListAppConnections(currentProject.id);+ // Organization connections aren't listed here, so the one session logs use is named when the list is empty.+ const { data: availableConnections } = useListAvailableAppConnections(+ AppConnection.AWS,+ currentProject.id+ );+ const orgConnectionInUse = availableConnections?.find(+ ({ id, projectId }) => id === sessionLogConnectionId && !projectId+ );const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["addConnection","editDetails",@@ -117,7 +134,9 @@ export const SessionLogConnectionsSheet = ({ isOpen, onOpenChange }: Props) => {<EmptyHeader><EmptyTitle>No connections yet</EmptyTitle><EmptyDescription>- Add an AWS connection, then choose it when you set up session logs.+ {orgConnectionInUse+ ? `Session logs use ${orgConnectionInUse.name}, an organization connection. Edit it under Integrations.`+ : "Add an AWS connection, then choose it when you set up session logs."}</EmptyDescription></EmptyHeader></Empty>@@ -136,7 +155,7 @@ export const SessionLogConnectionsSheet = ({ isOpen, onOpenChange }: Props) => {{connections.map((connection) => {const method = getAppConnectionMethodDetails(connection.method);const MethodIcon = method.icon;- const isInUse = connection.id === settings?.appConnectionId;+ const isInUse = connection.id === sessionLogConnectionId;const connectionSubject = subject(ProjectPermissionSub.AppConnections, {connectionId: connection.id});@@ -221,8 +240,8 @@ export const SessionLogConnectionsSheet = ({ isOpen, onOpenChange }: Props) => {</TooltipTrigger>{isInUse && (<TooltipContent side="left">- Session logs use this connection. Choose another one in Configure- before deleting it.+ Session logs use this connection. Turn session logs off, or choose+ another storage in Configure, before deleting it.</TooltipContent>)}</Tooltip>diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.tsxindex 9a935d9d8a..a90c99a26b 100644--- a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.tsx@@ -1,8 +1,9 @@-import { useEffect } from "react";+import { useEffect, useState } from "react";import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { z } from "zod";+import { CloudIcon, TriangleAlertIcon } from "lucide-react";+import { AgentVaultSessionLogUpgradeModal } from "@app/components/agent-vault/AgentVaultSessionLogUpgradeModal";import { AppConnectionOptionContent } from "@app/components/app-connections";import { createNotification } from "@app/components/notifications";import { AwsRegionSelect } from "@app/components/secret-syncs/forms/SecretSyncDestinationFields/shared";@@ -10,6 +11,15 @@ import {Alert,AlertAction,AlertDescription,+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ Badge,Button,Combobox,Dialog,@@ -26,113 +36,73 @@ import {FieldError,FieldGroup,FieldLabel,- FieldLegend,FieldSet,Input,Label,ProviderIcon,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,Toggle} from "@app/components/v3";-import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";+import {+ ProjectPermissionSub,+ useProject,+ useProjectPermission,+ useSubscription+} from "@app/context";import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";+import {+ canTurnOnAgentVaultSessionLogs,+ getAgentVaultSessionLogRetentionDays,+ isAgentVaultSessionLogBlockedByPlan,+ isAgentVaultSessionLogStorageOnPlan+} from "@app/helpers/agentVaultSessionLogs";import { APP_CONNECTION_MAP, AWS_REGIONS } from "@app/helpers/appConnections";import { useDiscardChangesGuard, usePopUp } from "@app/hooks";import {useGetAgentVaultSessionLogSettings,useUpdateAgentVaultSessionLogSettings} from "@app/hooks/api/agentVault";-import { TAgentVaultSessionLogSettings } from "@app/hooks/api/agentVault/types";+import { AgentVaultSessionLogStorageType } from "@app/hooks/api/agentVault/enums";+import {+ TAgentVaultSessionLogSettings,+ TUpdateAgentVaultSessionLogSettingsDTO+} from "@app/hooks/api/agentVault/types";import { AppConnection } from "@app/hooks/api/appConnections/enums";import { useListAvailableAppConnections } from "@app/hooks/api/appConnections/queries";import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";import { AgentVaultDocsUrls } from "../../agent-vault-docs-urls";import { AwsSetupDialog } from "./AwsSetupDialog";+import {+ buildSessionLogSchema,+ needsSessionLogUpgrade,+ S3_BUCKET_NAME,+ toStorage,+ TSessionLogFormValues+} from "./SessionLogModal.utils";-const NO_CONNECTION = "none";const CREATE_CONNECTION = "_create";const AWS_CONNECTION = APP_CONNECTION_MAP[AppConnection.AWS];-const S3_BUCKET_NAME = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;--const buildSchema = (savedBucket: string | null) =>- z- .object({- enabled: z.boolean(),- appConnectionId: z.string(),- bucket: z.string().trim().max(255),- region: z.string(),- keyPrefix: z- .string()- .trim()- .max(512, "At most 512 characters")- .regex(/^[A-Za-z0-9!\-_.'()/]*$/, "Use only letters, numbers and ! - _ . ' ( ) /")- .refine(- (value) => value === "" || value.split("/").every(Boolean),- "Use folder names separated by single slashes, with no slash at the start or end"- )- .refine(- (value) => !value.split("/").some((segment) => segment === "." || segment === ".."),- "Cannot use '.' or '..' as a folder name"- )- })- .refine((values) => !values.enabled || values.appConnectionId !== NO_CONNECTION, {- message: "Session logs need an AWS connection",- path: ["appConnectionId"]- })- .superRefine((values, ctx) => {- const { length } = values.bucket;- if (length === 0 && savedBucket) {- ctx.addIssue({- code: "custom",- path: ["bucket"],- message: "A bucket can be replaced, not removed"- });- } else if (length === 0 && values.enabled) {- ctx.addIssue({- code: "custom",- path: ["bucket"],- message: "Session logs need a bucket"- });- } else if (length > 0 && !S3_BUCKET_NAME.test(values.bucket)) {- ctx.addIssue({- code: "custom",- path: ["bucket"],- message:- "Use 3 to 63 lowercase letters, numbers, dots or hyphens, starting and ending with a letter or number"- });- } else if (values.bucket.endsWith("--x-s3") && values.bucket !== savedBucket) {- ctx.addIssue({- code: "custom",- path: ["bucket"],- message:- "Session logs need a general purpose S3 bucket. Directory buckets (names ending in --x-s3) aren't supported."- });- }- });--type FormData = z.infer<ReturnType<typeof buildSchema>>;-type Props = {isOpen: boolean;onOpenChange: (isOpen: boolean) => void;- onSaved: (settings: TAgentVaultSessionLogSettings) => void;+ onSaved: (settings: TAgentVaultSessionLogSettings | null) => void;onEditCredentials?: () => void;- // Without the plan, recording can only be switched off and the connection removed.- isCleanupOnly?: boolean;};-export const SessionLogModal = ({- isOpen,- onOpenChange,- onSaved,- onEditCredentials,- isCleanupOnly = false-}: Props) => {+export const SessionLogModal = ({ isOpen, onOpenChange, onSaved, onEditCredentials }: Props) => {const { currentProject } = useProject();const { permission } = useProjectPermission();- const { data: settings } = useGetAgentVaultSessionLogSettings();+ const { subscription } = useSubscription();+ const { data: state } = useGetAgentVaultSessionLogSettings();+ const settings = state?.settings ?? null;+ const isDefaultStorageConfigured = Boolean(state?.defaultStorage.configured);const { data: connections, isPending: isLoadingConnections } = useListAvailableAppConnections(AppConnection.AWS,currentProject.id@@ -142,6 +112,19 @@ export const SessionLogModal = ({"addConnection","awsSetup"] as const);+ const [upgradeFor, setUpgradeFor] = useState<AgentVaultSessionLogStorageType | null>(null);+ const [isConfirmOffOpen, setIsConfirmOffOpen] = useState(false);++ const retentionDays = getAgentVaultSessionLogRetentionDays(subscription);+ const isOnPlan = (type: AgentVaultSessionLogStorageType) =>+ isAgentVaultSessionLogStorageOnPlan(type, subscription);+ const savedExternal =+ settings?.storage.type === AgentVaultSessionLogStorageType.External ? settings.storage : null;+ // Without the plan and with nothing saved, the bucket fields could never be saved, so they aren't shown.+ const isExternalUsable =+ isOnPlan(AgentVaultSessionLogStorageType.External) || Boolean(savedExternal);+ const isDefaultUsable =+ isDefaultStorageConfigured && isOnPlan(AgentVaultSessionLogStorageType.Default);const {control,@@ -150,28 +133,45 @@ export const SessionLogModal = ({setValue,watch,formState: { isSubmitting, isDirty }- } = useForm<FormData>({ resolver: zodResolver(buildSchema(settings?.bucket ?? null)) });+ } = useForm<TSessionLogFormValues>({+ resolver: zodResolver(buildSessionLogSchema(settings, isExternalUsable))+ });const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =useDiscardChangesGuard({ isDirty, onDiscard: () => onOpenChange(false) });useEffect(() => {- if (!isOpen || !settings) return;+ if (!isOpen || !state) return;+ const saved = state.settings;+ const external =+ saved?.storage.type === AgentVaultSessionLogStorageType.External ? saved.storage : null;+ // While on, the dialog opens on the storage in use, even one the plan leaves out, so it matches the card and the+ // plan warning. An off row holds default storage without anyone picking it, so off starts on what the plan allows.+ const unchosenStorageType = isDefaultUsable+ ? AgentVaultSessionLogStorageType.Default+ : AgentVaultSessionLogStorageType.External;reset({- enabled: settings.bucket ? settings.enabled : true,- appConnectionId: settings.appConnectionId ?? NO_CONNECTION,- bucket: settings.bucket ?? "",- region: settings.region ?? AWS_REGIONS[0].slug,- keyPrefix: settings.keyPrefix ?? ""+ enabled: saved?.enabled ?? false,+ storageType: saved?.enabled ? saved.storage.type : unchosenStorageType,+ appConnectionId: external?.appConnectionId ?? "",+ bucket: external?.bucket ?? "",+ region: external?.region ?? AWS_REGIONS[0].slug,+ keyPrefix: external?.keyPrefix ?? ""});- }, [isOpen, settings, reset]);+ }, [isOpen, state, reset, isDefaultUsable]);const bucket = watch("bucket") ?? "";const keyPrefix = watch("keyPrefix") ?? "";+ const storageType = watch("storageType");const isEnabled = watch("enabled");- const isDetaching =- watch("appConnectionId") === NO_CONNECTION && Boolean(settings?.appConnectionId);+ const isExternal = storageType === AgentVaultSessionLogStorageType.External;++ // The saved bucket stays visible after the plan lapses, but only turning off or switching is allowed.+ const isExternalReadOnly =+ Boolean(savedExternal) && !isOnPlan(AgentVaultSessionLogStorageType.External);+ const isBlockedByPlan = isAgentVaultSessionLogBlockedByPlan(settings, subscription);+ const canTurnOn = canTurnOnAgentVaultSessionLogs(isDefaultStorageConfigured, subscription);const canCreateConnection = permission.can(ProjectPermissionAppConnectionActions.Create,@@ -179,42 +179,83 @@ export const SessionLogModal = ({);const connectionOptions = [- ...(canCreateConnection && !isCleanupOnly+ ...(canCreateConnection && !isExternalReadOnly? [{ id: CREATE_CONNECTION, name: "Create New Connection" }]: []),- ...(isEnabled ? [] : [{ id: NO_CONNECTION, name: "None" }]),- ...(connections ?? []).filter(- (connection) => !isCleanupOnly || connection.id === settings?.appConnectionId- )+ ...(connections ?? [])];const typedBucket = bucket.trim();const isBucketChange =- Boolean(settings?.bucket) &&+ isExternal &&+ Boolean(savedExternal) &&S3_BUCKET_NAME.test(typedBucket) &&- typedBucket !== settings?.bucket;+ typedBucket !== savedExternal?.bucket;const isPrefixOnlyChange =- Boolean(settings?.bucket) &&+ isExternal &&+ Boolean(savedExternal) &&!isBucketChange &&- keyPrefix.trim() !== (settings?.keyPrefix ?? "");+ keyPrefix.trim() !== (savedExternal?.keyPrefix ?? "");+ const isRecording = Boolean(settings?.enabled && isOnPlan(settings.storage.type));+ const isSwitchingStorage = isRecording && storageType !== settings?.storage.type;- const onSubmit = async (values: FormData) => {+ const saveSettings = async (request: TUpdateAgentVaultSessionLogSettingsDTO) => {try {- const result = await updateConfig.mutateAsync({- enabled: values.enabled,- appConnectionId: values.appConnectionId === NO_CONNECTION ? null : values.appConnectionId,- bucket: values.bucket || undefined,- region: values.region,- keyPrefix: values.keyPrefix- });+ const result = await updateConfig.mutateAsync(request);createNotification({ text: "Session log settings saved", type: "success" });+ setIsConfirmOffOpen(false);onOpenChange(false);- onSaved(result);+ onSaved(result.settings);} catch {// MutationCache.onError already reports the failure.}};+ const onSubmit = async (values: TSessionLogFormValues) => {+ // Turning off forgets the storage, and an external bucket is easy to lose track of, so that one is confirmed.+ if (!values.enabled) {+ if (savedExternal) {+ setIsConfirmOffOpen(true);+ return;+ }+ await saveSettings({ enabled: false });+ return;+ }++ if (needsSessionLogUpgrade(values, settings, isOnPlan)) {+ setUpgradeFor(values.storageType);+ return;+ }+ await saveSettings({ enabled: true, storage: toStorage(values) });+ };++ // Both are always listed so they can be found. Default storage the instance hasn't set up can't be picked; one the+ // plan leaves out opens the upgrade instead.+ const storageOptions = [+ {+ type: AgentVaultSessionLogStorageType.Default,+ title: "Default storage",+ icon: <CloudIcon />,+ isUnavailable: !isDefaultStorageConfigured,+ description: isDefaultStorageConfigured+ ? `Kept ${retentionDays} days. Nothing to set up.`+ : "Not set up on this instance. Contact your server administrator."+ },+ {+ type: AgentVaultSessionLogStorageType.External,+ title: "External storage",+ icon: (+ <ProviderIcon+ alt={`${AWS_CONNECTION.name} connection`}+ icon={AWS_CONNECTION.image}+ className="w-4"+ />+ ),+ isUnavailable: false,+ description: "Your own S3 bucket. You keep logs as long as you like."+ }+ ];+return (<Dialog open={isOpen} onOpenChange={(open) => (open ? onOpenChange(true) : requestDiscard())}><DialogContent className="max-w-xl">@@ -224,16 +265,53 @@ export const SessionLogModal = ({Session Logs<DocumentationLinkBadge href={AgentVaultDocsUrls.sessionLogs} /></DialogTitle>- <DialogDescription>- The bucket records are written to, and the credentials that reach it.- </DialogDescription>+ <DialogDescription>Choose where to record what your agents do.</DialogDescription></DialogHeader>- {isCleanupOnly && (+ {isBlockedByPlan &&+ settings?.storage.type === AgentVaultSessionLogStorageType.Default && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ <p>+ Your plan doesn't include default storage, so session logs aren't+ being recorded. Upgrade to record and view them. You can turn session logs off+ {isOnPlan(AgentVaultSessionLogStorageType.External)+ ? ", or switch to external storage."+ : "."}+ </p>+ <AlertAction>+ <Button+ variant="outline"+ size="sm"+ type="button"+ onClick={() => setUpgradeFor(AgentVaultSessionLogStorageType.Default)}+ >+ Upgrade+ </Button>+ </AlertAction>+ </AlertDescription>+ </Alert>+ )}+ {isBlockedByPlan && savedExternal && (<Alert variant="warning">+ <TriangleAlertIcon /><AlertDescription>- Your plan no longer includes session logs. You can turn them off and remove the AWS- connection.+ <p>+ Your plan no longer includes external storage. Upgrade to see recorded logs and+ keep recording. Recorded logs stay in your bucket. You can turn session logs off+ {isDefaultUsable ? ", or switch to default storage." : "."}+ </p>+ <AlertAction>+ <Button+ variant="outline"+ size="sm"+ type="button"+ onClick={() => setUpgradeFor(AgentVaultSessionLogStorageType.External)}+ >+ Upgrade+ </Button>+ </AlertAction></AlertDescription></Alert>)}@@ -247,223 +325,274 @@ export const SessionLogModal = ({<Field orientation="horizontal"><FieldContent><Label htmlFor="agent-vault-session-log-enabled">Enable</Label>- <FieldDescription>- When enabled, requests made by the agents are saved to the bucket below.- </FieldDescription>+ <FieldDescription>Records every request your agents make.</FieldDescription></FieldContent><Toggleid="agent-vault-session-log-enabled"variant="av"checked={field.value ?? false}- onCheckedChange={field.onChange}- disabled={isCleanupOnly && !settings?.enabled}+ onCheckedChange={(checked) => {+ if (checked && !canTurnOn) {+ setUpgradeFor(+ isDefaultStorageConfigured+ ? AgentVaultSessionLogStorageType.Default+ : AgentVaultSessionLogStorageType.External+ );+ return;+ }+ field.onChange(checked);+ }}/></Field>)}/></FieldSet>- <FieldSet>- <FieldLegend variant="label">Storage</FieldLegend>-- <Controller- control={control}- name="appConnectionId"- render={({ field, fieldState }) => (- <Field>- <div className="flex items-center justify-between gap-2">- <FieldLabel>AWS Connection</FieldLabel>- <Button- variant="link"- size="xs"- type="button"- onClick={() => handlePopUpOpen("awsSetup")}- >- View AWS Setup- </Button>- </div>- <FieldContent>- <Combobox- value={connectionOptions.find((option) => option.id === field.value)}- isClearable={false}- onValueChange={(option) => {- if (option.id === CREATE_CONNECTION) {- handlePopUpOpen("addConnection");+ {isEnabled && (+ <FieldSet>+ <Controller+ control={control}+ name="storageType"+ render={({ field }) => (+ <Field>+ <FieldLabel htmlFor="agent-vault-session-log-storage">Storage</FieldLabel>+ <Select+ value={+ isOnPlan(field.value) ||+ (settings?.enabled && settings.storage.type === field.value)+ ? field.value+ : ""+ }+ onValueChange={(value) => {+ const type = value as AgentVaultSessionLogStorageType;+ if (!isOnPlan(type)) {+ setUpgradeFor(type);return;}- field.onChange(option.id);+ field.onChange(type);}}- isLoading={isLoadingConnections}- isError={Boolean(fieldState.error)}- isDisabled={isCleanupOnly && isEnabled}- options={connectionOptions}- placeholder="Select a connection..."- getOptionLabel={(option) => option.name}- getOptionValue={(option) => option.id}- renderOption={(option) => (- <span className="flex min-w-0 items-center gap-2">- {option.id !== CREATE_CONNECTION && option.id !== NO_CONNECTION && (- <ProviderIcon- alt={`${AWS_CONNECTION.name} connection`}- icon={AWS_CONNECTION.image}- className="w-4 shrink-0"- />- )}- <span className="min-w-0 flex-1">- {option.id === NO_CONNECTION ? (- option.name- ) : (- <AppConnectionOptionContent- data={option}- isOnlyOption={- option.id === CREATE_CONNECTION &&- connectionOptions.length === 1- }- />+ >+ <SelectTrigger id="agent-vault-session-log-storage" className="w-full">+ <SelectValue placeholder="Choose where to store session logs" />+ </SelectTrigger>+ <SelectContent position="popper">+ {storageOptions.map((option) => (+ <SelectItem+ key={option.type}+ value={option.type}+ disabled={option.isUnavailable}+ description={<span className="pl-6">{option.description}</span>}+ >+ <span className="flex items-center gap-2">+ {option.icon}+ {option.title}+ {!option.isUnavailable && !isOnPlan(option.type) && (+ <Badge variant="av">Upgrade</Badge>+ )}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ )}+ />++ {isExternal && isExternalUsable && (+ <>+ <Controller+ control={control}+ name="appConnectionId"+ render={({ field, fieldState }) => (+ <Field>+ <div className="flex items-center justify-between gap-2">+ <FieldLabel>AWS Connection</FieldLabel>+ <Button+ variant="link"+ size="xs"+ type="button"+ onClick={() => handlePopUpOpen("awsSetup")}+ >+ View AWS Setup+ </Button>+ </div>+ <FieldContent>+ <Combobox+ value={connectionOptions.find((option) => option.id === field.value)}+ isClearable={false}+ onValueChange={(option) => {+ if (option.id === CREATE_CONNECTION) {+ handlePopUpOpen("addConnection");+ return;+ }+ field.onChange(option.id);+ }}+ isLoading={isLoadingConnections}+ isError={Boolean(fieldState.error)}+ isDisabled={isExternalReadOnly}+ options={connectionOptions}+ placeholder="Select a connection..."+ getOptionLabel={(option) => option.name}+ getOptionValue={(option) => option.id}+ renderOption={(option) => (+ <span className="flex min-w-0 items-center gap-2">+ {option.id !== CREATE_CONNECTION && (+ <ProviderIcon+ alt={`${AWS_CONNECTION.name} connection`}+ icon={AWS_CONNECTION.image}+ className="w-4 shrink-0"+ />+ )}+ <span className="min-w-0 flex-1">+ <AppConnectionOptionContent+ data={option}+ isOnlyOption={+ option.id === CREATE_CONNECTION &&+ connectionOptions.length === 1+ }+ />+ </span>+ </span>)}- </span>- </span>+ renderValue={(option) => (+ <span className="flex min-w-0 items-center gap-2">+ <ProviderIcon+ alt={`${AWS_CONNECTION.name} connection`}+ icon={AWS_CONNECTION.image}+ className="w-4 shrink-0"+ />+ <span className="truncate">{option.name}</span>+ </span>+ )}+ modal+ />+ <FieldDescription>+ Its credentials write the records, and read them back when you open a+ session's logs.+ </FieldDescription>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />++ <Controller+ control={control}+ name="region"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel+ id="agent-vault-session-log-region-label"+ htmlFor="agent-vault-session-log-region"+ >+ Region+ </FieldLabel>+ <FieldContent>+ <AwsRegionSelect+ id="agent-vault-session-log-region"+ value={field.value}+ onChange={field.onChange}+ isError={Boolean(fieldState.error)}+ isDisabled={isExternalReadOnly}+ aria-labelledby="agent-vault-session-log-region-label"+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />++ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <Controller+ control={control}+ name="bucket"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Bucket</FieldLabel>+ <FieldContent>+ <Input+ {...field}+ placeholder="acme-agent-vault-session-logs"+ isError={Boolean(fieldState.error)}+ disabled={isExternalReadOnly}+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>)}- renderValue={(option) => (- <span className="flex min-w-0 items-center gap-2">- {option.id !== NO_CONNECTION && (- <ProviderIcon- alt={`${AWS_CONNECTION.name} connection`}- icon={AWS_CONNECTION.image}- className="w-4 shrink-0"+ />+ <Controller+ control={control}+ name="keyPrefix"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>+ Key Prefix <span className="text-muted">(optional)</span>+ </FieldLabel>+ <FieldContent>+ <Input+ {...field}+ placeholder="agent-vault"+ isError={Boolean(fieldState.error)}+ disabled={isExternalReadOnly}/>- )}- <span className="truncate">{option.name}</span>- </span>+ <FieldDescription>+ Session logs are written under this prefix.+ </FieldDescription>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>)}- modal/>- <FieldDescription>- {isDetaching- ? "Without a connection, session logs can't be read. The bucket is kept, so attaching a connection later brings the history back."- : "Its credentials write the records, and read them back when you open a session's logs."}- </FieldDescription>- <FieldError>{fieldState.error?.message}</FieldError>- </FieldContent>- </Field>+ </div>+ </>)}- />- <Controller- control={control}- name="region"- render={({ field, fieldState }) => (- <Field>- <FieldLabel- id="agent-vault-session-log-region-label"- htmlFor="agent-vault-session-log-region"- >- Region- </FieldLabel>- <FieldContent>- <AwsRegionSelect- id="agent-vault-session-log-region"- value={field.value}- onChange={field.onChange}- isError={Boolean(fieldState.error)}- isDisabled={isCleanupOnly}- aria-labelledby="agent-vault-session-log-region-label"- />- <FieldError>{fieldState.error?.message}</FieldError>- </FieldContent>- </Field>+ {isSwitchingStorage && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ {settings?.storage.type === AgentVaultSessionLogStorageType.Default+ ? `Logs in default storage won't show after switching, and keep their ${retentionDays}-day retention.`+ : "Logs in your bucket won't show after switching. They stay in the bucket."}+ </AlertDescription>+ </Alert>)}- />- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">- <Controller- control={control}- name="bucket"- render={({ field, fieldState }) => (- <Field>- <FieldLabel>Bucket</FieldLabel>- <FieldContent>- <Input- {...field}- placeholder="acme-agent-vault-session-logs"- isError={Boolean(fieldState.error)}- disabled={isCleanupOnly}- />- <FieldError>{fieldState.error?.message}</FieldError>- </FieldContent>- </Field>- )}- />- <Controller- control={control}- name="keyPrefix"- render={({ field, fieldState }) => (- <Field>- <FieldLabel>- Key Prefix <span className="text-muted">(optional)</span>- </FieldLabel>- <FieldContent>- <Input- {...field}- placeholder="agent-vault"- isError={Boolean(fieldState.error)}- disabled={isCleanupOnly}- />- <FieldDescription>- Session logs are written under this prefix.- </FieldDescription>- <FieldError>{fieldState.error?.message}</FieldError>- </FieldContent>- </Field>- )}- />- </div>-- {isBucketChange && (- <Alert variant="warning">- <AlertDescription>- <p>- Everything already recorded stays in{" "}- <span className="font-mono">{settings?.bucket}</span> and won't show in- Infisical until you switch back to it. To rotate credentials, update the AWS- connection instead of moving the bucket.- </p>- {onEditCredentials && (- <AlertAction>- <Button- variant="outline"- size="sm"- type="button"- onClick={onEditCredentials}- >- Edit AWS Credentials- </Button>- </AlertAction>- )}- </AlertDescription>- </Alert>- )}-- {isPrefixOnlyChange && (- <Alert variant="info">- <AlertDescription>- {settings?.keyPrefix ? (+ {!isSwitchingStorage && isBucketChange && (+ <Alert variant="warning">+ <AlertDescription><p>- Logs already recorded stay under{" "}- <span className="font-mono">{settings.keyPrefix}/</span> and won't show- in Infisical until you switch back to that prefix.+ Everything already recorded stays in{" "}+ <span className="font-mono">{savedExternal?.bucket}</span> and won't+ show in Infisical until you switch back to it. To rotate credentials, update+ the AWS connection instead of moving the bucket.</p>- ) : (- <p>- Logs already recorded stay at the top level of{" "}- <span className="font-mono">{settings?.bucket}</span> and won't show in- Infisical until you remove the prefix again.- </p>- )}- </AlertDescription>- </Alert>- )}- </FieldSet>+ {onEditCredentials && (+ <AlertAction>+ <Button+ variant="outline"+ size="sm"+ type="button"+ onClick={onEditCredentials}+ >+ Edit AWS Credentials+ </Button>+ </AlertAction>+ )}+ </AlertDescription>+ </Alert>+ )}++ {!isSwitchingStorage && isPrefixOnlyChange && (+ <Alert variant="info">+ <AlertDescription>+ Older logs won't show until you change the prefix back.+ </AlertDescription>+ </Alert>+ )}+ </FieldSet>+ )}</FieldGroup><DialogFooter>@@ -498,6 +627,39 @@ export const SessionLogModal = ({isUnsaved/>+ <AgentVaultSessionLogUpgradeModal+ isOpen={upgradeFor !== null}+ onOpenChange={(open) => !open && setUpgradeFor(null)}+ storageType={upgradeFor ?? undefined}+ />++ <AlertDialog+ open={isConfirmOffOpen}+ onOpenChange={(open) => !updateConfig.isPending && setIsConfirmOffOpen(open)}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Turn Off Session Logs?</AlertDialogTitle>+ <AlertDialogDescription>+ Turning off forgets <span className="font-mono">{savedExternal?.bucket}</span>. To see+ its logs again, set up the same bucket and prefix.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel isDisabled={updateConfig.isPending}>Cancel</AlertDialogCancel>+ <AlertDialogAction+ isPending={updateConfig.isPending}+ onClick={(event) => {+ event.preventDefault();+ saveSettings({ enabled: false }).catch(() => undefined);+ }}+ >+ Turn Off+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+<DiscardChangesAlertDialogopen={isDiscardDialogOpen}onOpenChange={setIsDiscardDialogOpen}diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.utils.test.ts b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.utils.test.tsnew file mode 100644index 0000000000..3b6da5f9fe--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.utils.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it } from "vitest";++import { AgentVaultSessionLogStorageType } from "@app/hooks/api/agentVault/enums";+import { TAgentVaultSessionLogSettings } from "@app/hooks/api/agentVault/types";++import {+ buildSessionLogSchema,+ needsSessionLogUpgrade,+ toStorage,+ TSessionLogFormValues+} from "./SessionLogModal.utils";++const external: TSessionLogFormValues = {+ enabled: true,+ storageType: AgentVaultSessionLogStorageType.External,+ appConnectionId: "6f1c7a52-3f7e-4c8e-9a40-0b2d6c1e9f11",+ bucket: "globex-audit",+ region: "us-east-1",+ keyPrefix: "logs"+};++const savedExternal: TAgentVaultSessionLogSettings = {+ enabled: true,+ storage: {+ type: AgentVaultSessionLogStorageType.External,+ appConnectionId: external.appConnectionId,+ bucket: external.bucket,+ region: external.region,+ keyPrefix: "logs"+ }+};++const errorPaths = (+ values: TSessionLogFormValues,+ saved = null as TAgentVaultSessionLogSettings | null+) => {+ const result = buildSessionLogSchema(saved, true).safeParse(values);+ return result.success ? [] : result.error.issues.map((issue) => issue.path.join("."));+};++describe("the session log form", () => {+ it("checks the bucket fields only for external storage that's being turned on", () => {+ const blank = { ...external, appConnectionId: "", bucket: "", keyPrefix: "/logs" };+ expect(errorPaths(blank)).toEqual(["appConnectionId", "bucket", "keyPrefix"]);+ expect(errorPaths({ ...blank, enabled: false })).toEqual([]);+ expect(errorPaths({ ...blank, storageType: AgentVaultSessionLogStorageType.Default })).toEqual(+ []+ );+ });++ it("skips the bucket fields when external storage can't be used", () => {+ const blank = { ...external, appConnectionId: "", bucket: "" };+ expect(buildSessionLogSchema(null, false).safeParse(blank).success).toBe(true);+ });++ it("refuses a new directory bucket, but keeps one that is already saved", () => {+ const directory = { ...external, bucket: "logs--usw2-az1--x-s3" };+ expect(errorPaths(directory)).toEqual(["bucket"]);+ const saved = {+ ...savedExternal,+ storage: { ...savedExternal.storage, bucket: directory.bucket }+ };+ expect(errorPaths(directory, saved as TAgentVaultSessionLogSettings)).toEqual([]);+ });++ it("refuses a key prefix longer than 256 characters", () => {+ expect(errorPaths({ ...external, keyPrefix: "a".repeat(257) })).toEqual(["keyPrefix"]);+ expect(errorPaths({ ...external, keyPrefix: "a".repeat(256) })).toEqual([]);+ });++ it("sends only the type for default storage, and trimmed fields for external", () => {+ expect(+ toStorage({ ...external, storageType: AgentVaultSessionLogStorageType.Default })+ ).toEqual({+ type: AgentVaultSessionLogStorageType.Default+ });+ expect(toStorage({ ...external, bucket: " globex-audit ", keyPrefix: " logs " })).toMatchObject(+ {+ bucket: "globex-audit",+ keyPrefix: "logs"+ }+ );+ });+});++describe("needsSessionLogUpgrade", () => {+ const notOnPlan = () => false;++ it("asks for the plan when the save would choose, change or turn on a storage", () => {+ expect(needsSessionLogUpgrade(external, null, notOnPlan)).toBe(true);+ expect(needsSessionLogUpgrade({ ...external, bucket: "other" }, savedExternal, notOnPlan)).toBe(+ true+ );+ expect(needsSessionLogUpgrade(external, { ...savedExternal, enabled: false }, notOnPlan)).toBe(+ true+ );+ });++ it("lets an unchanged save of a lapsed bucket through", () => {+ expect(needsSessionLogUpgrade(external, savedExternal, notOnPlan)).toBe(false);+ });++ it("always asks for default storage, which can be on without anyone saving it", () => {+ const defaultValues = { ...external, storageType: AgentVaultSessionLogStorageType.Default };+ const defaultOn: TAgentVaultSessionLogSettings = {+ enabled: true,+ storage: { type: AgentVaultSessionLogStorageType.Default }+ };+ expect(needsSessionLogUpgrade(defaultValues, defaultOn, notOnPlan)).toBe(true);+ });++ it("never asks when the storage is on the plan", () => {+ expect(needsSessionLogUpgrade(external, null, () => true)).toBe(false);+ });+});diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.utils.ts b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.utils.tsnew file mode 100644index 0000000000..1e5541d287--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.utils.ts@@ -0,0 +1,125 @@+import { z } from "zod";++import { AgentVaultSessionLogStorageType } from "@app/hooks/api/agentVault/enums";+import {+ TAgentVaultSessionLogSettings,+ TAgentVaultSessionLogStorage,+ TAgentVaultSessionLogStorageInput+} from "@app/hooks/api/agentVault/types";++export const S3_BUCKET_NAME = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;++export type TSessionLogFormValues = {+ enabled: boolean;+ storageType: AgentVaultSessionLogStorageType;+ appConnectionId: string;+ bucket: string;+ region: string;+ keyPrefix: string;+};++export const toStorage = (values: TSessionLogFormValues): TAgentVaultSessionLogStorageInput =>+ values.storageType === AgentVaultSessionLogStorageType.Default+ ? { type: AgentVaultSessionLogStorageType.Default }+ : {+ type: AgentVaultSessionLogStorageType.External,+ appConnectionId: values.appConnectionId,+ bucket: values.bucket.trim(),+ region: values.region,+ keyPrefix: values.keyPrefix.trim()+ };++const isSameStorage = (values: TSessionLogFormValues, saved?: TAgentVaultSessionLogStorage) => {+ if (!saved || saved.type !== values.storageType) return false;+ if (saved.type === AgentVaultSessionLogStorageType.Default) return true;+ return (+ saved.appConnectionId === values.appConnectionId &&+ saved.bucket === values.bucket.trim() &&+ saved.region === values.region &&+ (saved.keyPrefix ?? "") === values.keyPrefix.trim()+ );+};++const getKeyPrefixIssue = (value: string) => {+ if (value.length > 256) return "At most 256 characters";+ if (!/^[A-Za-z0-9!\-_.'()/]*$/.test(value))+ return "Use only letters, numbers and ! - _ . ' ( ) /";+ if (value !== "" && !value.split("/").every(Boolean)) {+ return "Use folder names separated by single slashes, with no slash at the start or end";+ }+ if (value.split("/").some((segment) => segment === "." || segment === "..")) {+ return "Cannot use '.' or '..' as a folder name";+ }+ return null;+};++export const buildSessionLogSchema = (+ saved: TAgentVaultSessionLogSettings | null,+ isExternalUsable: boolean+) =>+ z+ .object({+ enabled: z.boolean(),+ storageType: z.nativeEnum(AgentVaultSessionLogStorageType),+ appConnectionId: z.string(),+ bucket: z.string().trim(),+ region: z.string(),+ keyPrefix: z.string().trim()+ })+ .superRefine((values, ctx) => {+ // Only external storage that's being turned on sends these fields, so they're only checked then.+ if (+ !values.enabled ||+ values.storageType !== AgentVaultSessionLogStorageType.External ||+ !isExternalUsable+ )+ return;++ const savedBucket =+ saved?.storage.type === AgentVaultSessionLogStorageType.External+ ? saved.storage.bucket+ : null;+ if (!values.appConnectionId) {+ ctx.addIssue({+ code: "custom",+ path: ["appConnectionId"],+ message: "Session logs need an AWS connection"+ });+ }+ if (values.bucket.length === 0) {+ ctx.addIssue({ code: "custom", path: ["bucket"], message: "Session logs need a bucket" });+ } else if (!S3_BUCKET_NAME.test(values.bucket)) {+ ctx.addIssue({+ code: "custom",+ path: ["bucket"],+ message:+ "Use 3 to 63 lowercase letters, numbers, dots or hyphens, starting and ending with a letter or number"+ });+ } else if (values.bucket.endsWith("--x-s3") && values.bucket !== savedBucket) {+ ctx.addIssue({+ code: "custom",+ path: ["bucket"],+ message:+ "Session logs need a general purpose S3 bucket. Directory buckets (names ending in --x-s3) aren't supported."+ });+ }++ const keyPrefixIssue = getKeyPrefixIssue(values.keyPrefix);+ if (keyPrefixIssue)+ ctx.addIssue({ code: "custom", path: ["keyPrefix"], message: keyPrefixIssue });+ });++// Saving a storage that isn't on the plan opens the upgrade dialog instead, but only when the save would choose,+// change or turn on that storage: an unchanged save of a lapsed bucket is still allowed. Default storage can be on with+// nothing saved, which the server still treats as turning it on, so it always asks.+export const needsSessionLogUpgrade = (+ values: TSessionLogFormValues,+ saved: TAgentVaultSessionLogSettings | null,+ isOnPlan: (type: AgentVaultSessionLogStorageType) => boolean+) => {+ const isStorageChange = !isSameStorage(values, saved?.storage);+ const isBucketAlreadyOn = Boolean(+ saved?.enabled && saved.storage.type === AgentVaultSessionLogStorageType.External+ );+ return (isStorageChange || !isBucketAlreadyOn) && !isOnPlan(values.storageType);+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogReadAccessAlert.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogReadAccessAlert.tsxindex 0e8a39a1a1..2c14f67be1 100644--- a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogReadAccessAlert.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogReadAccessAlert.tsx@@ -6,6 +6,7 @@ import {useGetAgentVaultSessionLogCorsProbe,useGetAgentVaultSessionLogSettings} from "@app/hooks/api/agentVault";+import { AgentVaultSessionLogStorageType } from "@app/hooks/api/agentVault/enums";import { TAgentVaultSessionLogReadAccess } from "@app/hooks/api/agentVault/types";import { AwsSetupDialog, HostBlockedMessage } from "./AwsSetupDialog";@@ -31,7 +32,11 @@ const READ_ACCESS_ALERTS: Record<export const SessionLogReadAccessAlert = () => {const [isAwsSetupOpen, setIsAwsSetupOpen] = useState(false);- const { data: config } = useGetAgentVaultSessionLogSettings();+ const { data: state } = useGetAgentVaultSessionLogSettings();+ const external =+ state?.settings?.storage.type === AgentVaultSessionLogStorageType.External+ ? state.settings.storage+ : null;const { data: readCheck } = useGetAgentVaultSessionLogCorsProbe();const readAlert =readCheck && readCheck.status !== "readable" ? READ_ACCESS_ALERTS[readCheck.status] : null;@@ -57,8 +62,8 @@ export const SessionLogReadAccessAlert = () => {<AwsSetupDialogisOpen={isAwsSetupOpen}onOpenChange={setIsAwsSetupOpen}- bucket={config?.bucket ?? null}- keyPrefix={config?.keyPrefix ?? null}+ bucket={external?.bucket ?? null}+ keyPrefix={external?.keyPrefix ?? null}/></>);diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogSection.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogSection.tsxindex b2586b0d2b..58cfee346d 100644--- a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogSection.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogSection.tsx@@ -3,7 +3,6 @@ import { subject } from "@casl/ability";import { useQueryClient } from "@tanstack/react-query";import { AsteriskIcon, ChevronDownIcon, PlugIcon } from "lucide-react";-import { AgentVaultSessionLogUpgradeModal } from "@app/components/agent-vault/AgentVaultSessionLogUpgradeModal";import {Badge,Button,@@ -38,13 +37,14 @@ import {useSubscription} from "@app/context";import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";-import { areAgentVaultSessionLogsOn } from "@app/helpers/agentVaultSessionLogs";+import { isAgentVaultSessionLogStorageOnPlan } from "@app/helpers/agentVaultSessionLogs";import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";import {agentVaultKeys,fetchAgentVaultSessionLogReadAccess,useGetAgentVaultSessionLogSettings} from "@app/hooks/api/agentVault";+import { AgentVaultSessionLogStorageType } from "@app/hooks/api/agentVault/enums";import { TAgentVaultSessionLogSettings } from "@app/hooks/api/agentVault/types";import { AppConnection } from "@app/hooks/api/appConnections/enums";import {@@ -67,31 +67,32 @@ export const SessionLogSection = () => {const { subscription } = useSubscription();const queryClient = useQueryClient();const [isModalOpen, setIsModalOpen] = useState(false);- const [isUpgradeOpen, setIsUpgradeOpen] = useState(false);const [isConnectionsSheetOpen, setIsConnectionsSheetOpen] = useState(false);const [isEditCredentialsOpen, setIsEditCredentialsOpen] = useState(false);const [awsSetup, setAwsSetup] = useState<{bucket: string | null;keyPrefix: string | null;} | null>(null);- const { data: config, isPending } = useGetAgentVaultSessionLogSettings();+ const { data: state, isPending } = useGetAgentVaultSessionLogSettings();const { data: connections } = useListAvailableAppConnections(AppConnection.AWS,currentProject.id);const { data: agentVaultConnections = [] } = useListAppConnections(currentProject.id);- const hasDestination = Boolean(config?.bucket);- const isEnabled = Boolean(config?.enabled) && subscription.agentVaultByoS3;- // Without the plan, Configure still opens for an existing setup so an admin can switch it off and- // detach the connection; there is nothing to clean up otherwise, so it offers the upgrade.- const isCleanupOnly =- !subscription.agentVaultByoS3 && Boolean(config?.enabled || config?.appConnectionId);+ const settings = state?.settings ?? null;+ const external =+ settings?.storage.type === AgentVaultSessionLogStorageType.External ? settings.storage : null;+ // Not on the plan means nothing is recorded, so the card says Disabled even while the setting is on.+ const isEnabled = Boolean(+ settings?.enabled && isAgentVaultSessionLogStorageOnPlan(settings.storage.type, subscription)+ );// Saving with session logs on already proved Infisical can write, so the dialog only opens for a// step the read check finds missing.- const offerAwsSetup = async (settings: TAgentVaultSessionLogSettings) => {- if (!areAgentVaultSessionLogsOn(settings)) return;+ const offerAwsSetup = async (saved: TAgentVaultSessionLogSettings | null) => {+ if (!saved?.enabled || saved.storage.type !== AgentVaultSessionLogStorageType.External) return;+ const { bucket, keyPrefix } = saved.storage;const readCheck = await queryClient.fetchQuery({queryKey: agentVaultKeys.sessionLogCorsProbe(currentOrg.id),@@ -99,23 +100,25 @@ export const SessionLogSection = () => {}).catch(() => null);if (readCheck?.status === "cors-missing" || readCheck?.status === "access-denied") {- setAwsSetup({ bucket: settings.bucket, keyPrefix: settings.keyPrefix });+ setAwsSetup({ bucket, keyPrefix });}};- const connection = connections?.find(({ id }) => id === config?.appConnectionId);+ const connection = connections?.find(({ id }) => id === external?.appConnectionId);const connectionName = connection?.name ?? null;const isOrgConnection = Boolean(connection && !connection.projectId);// The available list holds only names and IDs, and the credentials editor needs the full// connection, which only Agent Vault's own list returns.- const editableConnection = agentVaultConnections.find(({ id }) => id === config?.appConnectionId);+ const editableConnection = agentVaultConnections.find(+ ({ id }) => id === external?.appConnectionId+ );const canEditConnection = editableConnection? permission.can(ProjectPermissionAppConnectionActions.Edit,subject(ProjectPermissionSub.AppConnections, { connectionId: editableConnection.id })): false;- const hasConnectionMenu = Boolean(config?.appConnectionId) || agentVaultConnections.length > 0;+ const hasConnectionMenu = Boolean(external?.appConnectionId) || agentVaultConnections.length > 0;return (<>@@ -126,20 +129,13 @@ export const SessionLogSection = () => {<DocumentationLinkBadge href={AgentVaultDocsUrls.sessionLogs} /></CardTitle><CardDescription>- Requests your agents make through a proxy, encrypted and written to a bucket you own.+ Requests your agents make through a proxy, encrypted and kept in default storage or in a+ bucket you own.</CardDescription><CardAction><ButtonGroup>- <Button- variant="av"- isDisabled={isPending}- onClick={() =>- subscription.agentVaultByoS3 || isCleanupOnly- ? setIsModalOpen(true)- : setIsUpgradeOpen(true)- }- >- {!config || hasDestination ? "Configure" : "Set Up Session Logs"}+ <Button variant="av" isDisabled={isPending} onClick={() => setIsModalOpen(true)}>+ {settings ? "Configure" : "Set Up Session Logs"}</Button>{hasConnectionMenu && (<DropdownMenu>@@ -153,7 +149,7 @@ export const SessionLogSection = () => {</IconButton></DropdownMenuTrigger><DropdownMenuContent align="end" sideOffset={4} className="min-w-48">- {config?.appConnectionId && (+ {external?.appConnectionId && (<Tooltip><TooltipTrigger asChild><div>@@ -185,11 +181,11 @@ export const SessionLogSection = () => {</CardAction></CardHeader>- {(isPending || (hasDestination && config)) && (+ {(isPending || settings) && (<CardContent>{isPending && <Skeleton className="h-10 w-full" />}- {!isPending && hasDestination && config && (+ {!isPending && settings && (<DetailGroup className="flex-row flex-wrap gap-x-8"><Detail><DetailLabel>Status</DetailLabel>@@ -199,31 +195,41 @@ export const SessionLogSection = () => {</Badge></DetailValue></Detail>- <Detail>- <DetailLabel>Connection</DetailLabel>- <DetailValue className="flex items-center gap-2">- {connectionName && (- <ProviderIcon- alt={`${AWS_CONNECTION.name} connection`}- icon={AWS_CONNECTION.image}- className="w-4 shrink-0"- />- )}- {connectionName ?? "None"}- </DetailValue>- </Detail>- <Detail>- <DetailLabel>Region</DetailLabel>- <DetailValue>{config.region}</DetailValue>- </Detail>- <Detail>- <DetailLabel>Bucket</DetailLabel>- <DetailValue>{config.bucket}</DetailValue>- </Detail>- <Detail>- <DetailLabel>Key Prefix</DetailLabel>- <DetailValue>{config.keyPrefix || "None"}</DetailValue>- </Detail>+ {settings.enabled && (+ <Detail>+ <DetailLabel>Storage</DetailLabel>+ <DetailValue>{external ? "External storage" : "Default storage"}</DetailValue>+ </Detail>+ )}+ {external && (+ <>+ <Detail>+ <DetailLabel>Connection</DetailLabel>+ <DetailValue className="flex items-center gap-2">+ {connectionName && (+ <ProviderIcon+ alt={`${AWS_CONNECTION.name} connection`}+ icon={AWS_CONNECTION.image}+ className="w-4 shrink-0"+ />+ )}+ {connectionName ?? "None"}+ </DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Region</DetailLabel>+ <DetailValue>{external.region}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Bucket</DetailLabel>+ <DetailValue>{external.bucket}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Key Prefix</DetailLabel>+ <DetailValue>{external.keyPrefix || "None"}</DetailValue>+ </Detail>+ </>+ )}</DetailGroup>)}</CardContent>@@ -235,11 +241,8 @@ export const SessionLogSection = () => {onOpenChange={setIsModalOpen}onSaved={offerAwsSetup}onEditCredentials={canEditConnection ? () => setIsEditCredentialsOpen(true) : undefined}- isCleanupOnly={isCleanupOnly}/>- <AgentVaultSessionLogUpgradeModal isOpen={isUpgradeOpen} onOpenChange={setIsUpgradeOpen} />-<AwsSetupDialogisOpen={Boolean(awsSetup)}onOpenChange={(isOpen) => !isOpen && setAwsSetup(null)}