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
improvement(agent-vault): serve session logs from S3 instead of a chunks table (#8497)
Saif Ur Rahman95e7341a2b36
diff --git a/backend/e2e-test/fakes/s3.ts b/backend/e2e-test/fakes/s3.tsindex 64e386747b..74ed084125 100644--- a/backend/e2e-test/fakes/s3.ts+++ b/backend/e2e-test/fakes/s3.ts@@ -1,3 +1,5 @@+import { S3ServiceException } from "@aws-sdk/client-s3";+import type * as RealS3 from "../../src/lib/aws/s3";// Stands in for the S3 bucket helper so the specs can drive uploads and downloads through presigned@@ -6,13 +8,15 @@ import type * as RealS3 from "../../src/lib/aws/s3";//// It keeps the two rules the real links sign and S3 enforces: the body is the declared size, and an// upload never overwrites an object already stored. The SHA-256 is not checked, because the specs-// upload filler bytes against a fixed digest.+// 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 TFakeState = {objects: Map<string, Buffer>;accessFailure: TAccessFailure | null;+ isListFailing: boolean;presignedPuts: Map<string, { bucket: string; key: string; contentLength: number }>;presignedGets: Map<string, { bucket: string; key: string }>;nextUrlId: number;@@ -21,6 +25,7 @@ type TFakeState = {const freshState = (): TFakeState => ({objects: new Map(),accessFailure: null,+ isListFailing: false,presignedPuts: new Map(),presignedGets: new Map(),nextUrlId: 0@@ -45,6 +50,16 @@ export const fakeS3Bucket = {state.accessFailure = failure;},+ // Make listPage fail the way S3 does when the role can't list the bucket.+ failsListWith: (isFailing: boolean) => {+ state.isListFailing = isFailing;+ },++ // Store an object no link was minted for, as someone with access to the bucket could.+ putDirect: (bucket: string, key: string, body: Buffer) => {+ state.objects.set(objectId(bucket, key), body);+ },+put: (url: string, body: Buffer) => {const target = state.presignedPuts.get(url);if (!target) throw new Error(`No presigned PUT was minted for ${url}`);@@ -91,6 +106,27 @@ export const createS3Bucket = ({ bucket }: Parameters<typeof RealS3.createS3Buckreturn Promise.resolve(url);},+ listPage: ({ prefix, startAfter, maxKeys }: { prefix: string; startAfter?: string; maxKeys: number }) => {+ if (state.isListFailing) {+ return Promise.reject(+ new S3ServiceException({ name: "AccessDenied", $fault: "client", $metadata: {}, message: "Access Denied" })+ );+ }+ const matching = [...state.objects.entries()]+ .filter(([id]) => id.startsWith(`${bucket}/`))+ .map(([id, body]) => ({ key: id.slice(bucket.length + 1), size: body.length }))+ .filter(({ key }) => key.startsWith(prefix) && (startAfter === undefined || key > startAfter))+ .sort((a, b) => Buffer.compare(Buffer.from(a.key), Buffer.from(b.key)));+ return Promise.resolve({ objects: matching.slice(0, maxKeys), isTruncated: matching.length > maxKeys });+ },++ checkReachable: (): Promise<{ ok: true } | { ok: false; error: unknown }> =>+ Promise.resolve(+ state.accessFailure === "unreachable"+ ? { ok: false, error: new Error("fake bucket is unreachable") }+ : { ok: true }+ ),+checkAccess: (): Promise<RealS3.TS3AccessCheck> =>Promise.resolve(state.accessFailure@@ -105,5 +141,7 @@ export const assertFakeMatchesRealS3: Pick<typeof RealS3, "createS3Bucket"> = {export const assertFakeBucketShapeMatches: { [K in keyof RealS3.TS3Bucket]: unknown } = {presignCreateOnlyPut: null,presignGet: null,+ listPage: null,+ checkReachable: null,checkAccess: null};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 d62d42b523..e8e4784ed2 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@@ -8,11 +8,16 @@ import { v7 as uuidv7 } from "uuid";import { OrgMembershipRole, ProjectMembershipRole, ProjectType } from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";-import { AGENT_VAULT_SESSION_LOG_MAX_STORED_CHUNKS } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-constants";+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+ encodeTailCursor,+ 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";@@ -136,21 +141,19 @@ const nextChunkId = () => uuidv7();const CHUNK_BYTES = 1024;const CHUNK_SHA256 = "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU";-const chunkBody = (overrides: Record<string, unknown> = {}) => ({- chunkId: nextChunkId(),- startedAt: new Date(Date.now() - 60_000),- endedAt: new Date(Date.now() - 1_000),- firstSeq: 0,- lastSeq: 9,- recordCount: 10,- droppedCount: 0,- ciphertextBytes: CHUNK_BYTES,- iv: "qrvM3e7/ABEiM0RV",- ciphertextSha256: CHUNK_SHA256,- ...overrides-});+// Infisical refuses a chunk whose id time doesn't match its endedAt, so endedAt defaults to the id's time.+const chunkBody = (overrides: Record<string, unknown> = {}) => {+ const chunkId = (overrides.chunkId as string | undefined) ?? uuidv7({ msecs: Date.now() - 1_000 });+ return {+ chunkId,+ endedAt: new Date(chunkIdTimeMs(chunkId)),+ ciphertextBytes: CHUNK_BYTES,+ ciphertextSha256: CHUNK_SHA256,+ ...overrides+ };+};-const recordChunk = async (+const requestUploadUrl = async (proxy: Awaited<ReturnType<typeof createProxy>>,sessionId: string,chunk: Record<string, unknown> = chunkBody()@@ -182,7 +185,6 @@ describe("Agent Vault session logs", async () => {// This file sorts before agent-vault.spec.ts, which asserts the Agent Vault project bootstraps with no members.afterAll(async () => {- await testDb("agent_vault_session_log_chunks").where({ projectId }).del();await testDb("agent_vault_session_log_configs").where({ projectId }).del();await testDb("agent_vault_sessions").where({ projectId }).del();await testDb("agent_vault_proxies").where({ projectId }).del();@@ -194,7 +196,6 @@ describe("Agent Vault session logs", async () => {beforeEach(async () => {fakeS3Bucket.reset();fakeAwsConnection.reset();- await testDb("agent_vault_session_log_chunks").where({ projectId }).del();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();@@ -207,11 +208,10 @@ describe("Agent Vault session logs", async () => {const body = JSON.parse(res.payload) as { settings: Record<string, unknown> };expect(body.settings).toMatchObject({ enabled: false, bucket: null, appConnectionId: null });- expect(body).not.toHaveProperty("usage");const health = await inject("GET", `${SETTINGS_URL}/health`);expect(health.statusCode).toBe(200);- expect(JSON.parse(health.payload).health).toMatchObject({ isStorageFull: false });+ expect(JSON.parse(health.payload).health).toMatchObject({ connectionError: null });const probe = await inject("GET", `${SETTINGS_URL}/cors-probe`);expect(probe.statusCode).toBe(200);@@ -287,6 +287,19 @@ describe("Agent Vault session logs", async () => {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");++ const health = await inject("GET", `${SETTINGS_URL}/health`);+ expect(JSON.parse(health.payload).health.connectionError).toBe(+ `Unable to reach bucket '${BUCKET}'. Check the bucket name, the region, and that the connection's credentials allow s3:ListBucket on it`+ );+ });+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);@@ -399,70 +412,38 @@ describe("Agent Vault session logs", async () => {...patch});- test("writes the row before the object exists, then presigns an upload for exactly that many bytes", async () => {+ const tailedChunks = async (sessionId: string) =>+ (await inject("GET", `/api/v1/agent-vault/sessions/${sessionId}/logs/tail`)).json().chunks as unknown[];++ test("presigns an upload for exactly that many bytes, named under the session's folder", async () => {await configure();const bundle = await createAccessBundle(`session-logs-write-${Date.now()}`);const session = await mintSession(bundle.name);const proxy = await createProxy(`session-logs-write-${Date.now()}`);const chunk = chunkBody();- const result = await recordChunk(proxy, session.id, chunk);-- const row = await testDb("agent_vault_session_log_chunks").where({ sessionId: session.id }).first();- expect(row).toMatchObject({ chunkId: chunk.chunkId, proxyId: proxy.id, proxyName: proxy.name, recordCount: 10 });- expect(row.objectKey).toMatch(/^logs\/.+\/\d{4}-\d{2}-\d{2}\/.+\.json\.enc$/);+ const result = await requestUploadUrl(proxy, session.id, chunk);expect(fakeS3Bucket.objectKeys(BUCKET)).toEqual([]);fakeS3Bucket.put(result.uploadUrl, Buffer.alloc(CHUNK_BYTES));- expect(fakeS3Bucket.objectKeys(BUCKET)).toEqual([row.objectKey]);-- expect(() => fakeS3Bucket.put(result.uploadUrl, Buffer.alloc(CHUNK_BYTES + 1))).toThrow();- });-- test("counts each chunk once against the org, whatever it holds", async () => {- await configure();- const bundle = await createAccessBundle(`session-logs-count-${Date.now()}`);- const session = await mintSession(bundle.name);- const proxy = await createProxy(`session-logs-count-${Date.now()}`);- await recordChunk(proxy, session.id);- await recordChunk(proxy, session.id, chunkBody({ firstSeq: 10, lastSeq: 19 }));-- const config = await testDb("agent_vault_session_log_configs").where({ projectId }).first();- expect(Number(config.storedChunkCount)).toBe(2);- });-- test("re-sending a chunk replays the same row and counts nothing twice", async () => {- await configure();- const bundle = await createAccessBundle(`session-logs-replay-${Date.now()}`);- const session = await mintSession(bundle.name);- const proxy = await createProxy(`session-logs-replay-${Date.now()}`);- const chunk = chunkBody();- const first = await recordChunk(proxy, session.id, chunk);- const second = await recordChunk(proxy, session.id, chunk);-- expect(second.chunkId).toBe(first.chunkId);- expect(second.uploadUrl).not.toBe(first.uploadUrl);- expect(await testDb("agent_vault_session_log_chunks").where({ sessionId: session.id }).count()).toEqual([- { count: "1" }+ expect(fakeS3Bucket.objectKeys(BUCKET)).toEqual([+ `logs/${projectId}/${session.id}/${toRev(chunkIdTimeMs(chunk.chunkId))}_${chunk.chunkId}.${proxy.id}.json.enc`]);- expect(- Number((await testDb("agent_vault_session_log_configs").where({ projectId }).first()).storedChunkCount)- ).toBe(1);});- test("a re-sent chunk gets a fresh upload link that cannot replace what is already stored", async () => {+ test("a re-sent chunk is signed for the same name, which cannot replace what is already stored", async () => {await configure();const bundle = await createAccessBundle(`session-logs-overwrite-${Date.now()}`);const session = await mintSession(bundle.name);const proxy = await createProxy(`session-logs-overwrite-${Date.now()}`);const chunk = chunkBody();- const first = await recordChunk(proxy, session.id, chunk);+ const first = await requestUploadUrl(proxy, session.id, chunk);const stored = Buffer.alloc(CHUNK_BYTES, 1);fakeS3Bucket.put(first.uploadUrl, stored);- const second = await recordChunk(proxy, session.id, chunk);+ const second = await requestUploadUrl(proxy, session.id, chunk);expect(() => fakeS3Bucket.put(second.uploadUrl, Buffer.alloc(CHUNK_BYTES, 2))).toThrow(/create-only/);const read = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);@@ -470,72 +451,44 @@ describe("Agent Vault session logs", async () => {expect(fakeS3Bucket.get(only.presignedGetUrl)).toEqual(stored);});- test("a chunk re-sent after the destination moved is uploaded to the new one and reads back", async () => {- await configure();- const bundle = await createAccessBundle(`session-logs-moved-${Date.now()}`);+ test("with no key prefix, a chunk lands 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);- const proxy = await createProxy(`session-logs-moved-${Date.now()}`);- const chunk = chunkBody();- await recordChunk(proxy, session.id, chunk);-- const movedBucket = `${BUCKET}-moved`;- await configure({ bucket: movedBucket, keyPrefix: "moved" });+ const proxy = await createProxy(`session-logs-root-${Date.now()}`);- const resent = await recordChunk(proxy, session.id, chunk);+ const { uploadUrl } = await requestUploadUrl(proxy, session.id, chunkBody());const stored = Buffer.alloc(CHUNK_BYTES, 3);- fakeS3Bucket.put(resent.uploadUrl, stored);+ fakeS3Bucket.put(uploadUrl, stored);- const row = await testDb("agent_vault_session_log_chunks").where({ sessionId: session.id }).first();- expect(row.bucket).toBe(movedBucket);- expect(row.objectKey).toMatch(/^moved\//);- expect(fakeS3Bucket.objectKeys(movedBucket)).toEqual([row.objectKey]);+ const [key] = fakeS3Bucket.objectKeys(BUCKET);+ expect(key.startsWith(`${projectId}/${session.id}/`)).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 | null }[] }).chunks;- expect(fakeS3Bucket.get(only.presignedGetUrl as string)).toEqual(stored);- });-- test("a chunk re-sent after the destination moved to a bucket with no prefix is uploaded to its root", async () => {- await configure();- const bundle = await createAccessBundle(`session-logs-moved-bare-${Date.now()}`);- const session = await mintSession(bundle.name);- const proxy = await createProxy(`session-logs-moved-bare-${Date.now()}`);- const chunk = chunkBody();- await recordChunk(proxy, session.id, chunk);-- const movedBucket = `${BUCKET}-bare`;- expect((await configure({ bucket: movedBucket, keyPrefix: "" })).statusCode).toBe(200);-- const resent = await recordChunk(proxy, session.id, chunk);- fakeS3Bucket.put(resent.uploadUrl, Buffer.alloc(CHUNK_BYTES));-- const row = await testDb("agent_vault_session_log_chunks").where({ sessionId: session.id }).first();- expect(row.bucket).toBe(movedBucket);- expect(row.objectKey.startsWith(`${projectId}/${session.id}/${proxy.id}/`)).toBe(true);- expect(fakeS3Bucket.objectKeys(movedBucket)).toEqual([row.objectKey]);+ const [only] = (JSON.parse(read.payload) as { chunks: { presignedGetUrl: string }[] }).chunks;+ expect(fakeS3Bucket.get(only.presignedGetUrl)).toEqual(stored);});- test("two proxies can write to one session, and a chunk id is only unique within it", async () => {+ test("two proxies can send the same chunk id to one session, and each lands under its own name", async () => {await configure();const bundle = await createAccessBundle(`session-logs-two-${Date.now()}`);- const sessionA = await mintSession(bundle.name);- const sessionB = await mintSession(bundle.name);+ const session = await mintSession(bundle.name);const proxyOne = await createProxy(`session-logs-two-a-${Date.now()}`);const proxyTwo = await createProxy(`session-logs-two-b-${Date.now()}`);const sharedId = nextChunkId();- await recordChunk(proxyOne, sessionA.id, chunkBody({ chunkId: sharedId }));- await recordChunk(proxyTwo, sessionA.id);- await recordChunk(proxyTwo, sessionB.id, chunkBody({ chunkId: sharedId }));- const claimed = await proxyTwo.postChunk(sessionA.id, chunkBody({ chunkId: sharedId }));- expect(claimed.statusCode, claimed.payload).toBe(409);- await recordChunk(proxyOne, sessionA.id, chunkBody({ chunkId: sharedId }));+ const one = await requestUploadUrl(proxyOne, session.id, chunkBody({ chunkId: sharedId }));+ const two = await requestUploadUrl(proxyTwo, session.id, chunkBody({ chunkId: sharedId }));+ fakeS3Bucket.put(one.uploadUrl, Buffer.alloc(CHUNK_BYTES));+ fakeS3Bucket.put(two.uploadUrl, Buffer.alloc(CHUNK_BYTES));- expect(await testDb("agent_vault_session_log_chunks").where({ sessionId: sessionA.id })).toHaveLength(2);- expect(await testDb("agent_vault_session_log_chunks").where({ sessionId: sessionB.id })).toHaveLength(1);+ const read = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);+ const { chunks } = JSON.parse(read.payload) as { chunks: { chunkId: string; proxyId: string }[] };+ expect(chunks.map((chunk) => chunk.proxyId).sort()).toEqual([proxyOne.id, proxyTwo.id].sort());+ expect(chunks.every((chunk) => chunk.chunkId === sharedId)).toBe(true);});- test("a connection that can't be used refuses the chunk as retryable and writes no row", async () => {+ test("a connection that can't be used refuses the chunk as retryable and records nothing", async () => {await configure();fakeAwsConnection.failsConfigWith("AWS refused to assume the role");const bundle = await createAccessBundle(`session-logs-unusable-${Date.now()}`);@@ -544,7 +497,8 @@ describe("Agent Vault session logs", async () => {const res = await proxy.postChunk(session.id, chunkBody());expect(res.statusCode).toBe(500);- expect(await testDb("agent_vault_session_log_chunks").where({ sessionId: session.id })).toHaveLength(0);+ fakeAwsConnection.reset();+ expect(await tailedChunks(session.id)).toEqual([]);});test("is refused with the named error while session logs are off", async () => {@@ -558,24 +512,6 @@ describe("Agent Vault session logs", async () => {expect(JSON.parse(res.payload).error).toBe(AgentVaultSessionLogErrorName.Disabled);});- test("a chunk past the organization's limit is refused, and neither the row nor the count is kept", async () => {- await configure();- const bundle = await createAccessBundle(`session-logs-full-${Date.now()}`);- const session = await mintSession(bundle.name);- const proxy = await createProxy(`session-logs-full-${Date.now()}`);- await testDb("agent_vault_session_log_configs")- .where({ projectId })- .update({ storedChunkCount: AGENT_VAULT_SESSION_LOG_MAX_STORED_CHUNKS });-- const res = await proxy.postChunk(session.id, chunkBody());- expect(res.statusCode, res.payload).toBe(400);- expect(JSON.parse(res.payload).error).toBe(AgentVaultSessionLogErrorName.CeilingReached);-- expect(await testDb("agent_vault_session_log_chunks").where({ sessionId: session.id })).toHaveLength(0);- const config = await testDb("agent_vault_session_log_configs").where({ projectId }).first();- expect(Number(config.storedChunkCount)).toBe(AGENT_VAULT_SESSION_LOG_MAX_STORED_CHUNKS);- });-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()}`);@@ -607,7 +543,6 @@ describe("Agent Vault session logs", async () => {expect([foreign.statusCode, missing.statusCode]).toEqual([404, 404]);expect(JSON.parse(foreign.payload).message).toBe(JSON.parse(missing.payload).message);- expect(await testDb("agent_vault_session_log_chunks").where({ sessionId: foreignSession.id })).toHaveLength(0);} finally {await testDb("organizations").where({ id: foreignOrg.id }).delete();}@@ -727,9 +662,6 @@ describe("Agent Vault session logs", async () => {test.each([{ why: "the chunk id is not a UUID", patch: { chunkId: "nope" } },{ why: "the chunk id is a v4 UUID", patch: { chunkId: crypto.randomUUID() } },- { why: "the record count is over the slice size", patch: { recordCount: 1001 } },- { why: "the record count is zero", patch: { recordCount: 0 } },- { why: "the IV is the wrong width", patch: { iv: "short" } },{ why: "the digest is not a SHA-256", patch: { ciphertextSha256: "short" } },{ why: "the ciphertext is smaller than an empty sealed array", patch: { ciphertextBytes: 4 } }])("rejects a malformed chunk when $why", async ({ patch }) => {@@ -741,16 +673,18 @@ describe("Agent Vault session logs", async () => {});test.each([- { why: "endedAt precedes startedAt", patch: { startedAt: new Date(), endedAt: new Date(Date.now() - 60_000) } },{ why: "endedAt is far in the future", patch: { endedAt: new Date(Date.now() + 10 * 60_000) } },- { why: "the sequence range cannot hold the records", patch: { firstSeq: 0, lastSeq: 2, recordCount: 10 } }- ])("rejects a chunk that cannot be true when $why", async ({ patch }) => {+ { why: "endedAt is more than 30 days ago", patch: { endedAt: new Date(Date.now() - 31 * 24 * 60 * 60_000) } },+ { why: "endedAt is minutes off the chunk id's time", patch: { endedAt: new Date(Date.now() - 6 * 60_000) } },+ { why: "it comes from a CLI that still sends the IV", patch: { iv: "AAAAAAAAAAAAAAAA" } }+ ])("rejects a chunk it can't accept when $why", async ({ patch }) => {await configure();const { session, proxy } = await setup("semantic");const res = await proxy.postChunk(session.id, chunkBody(patch));expect(res.statusCode).toBe(400);- expect(await testDb("agent_vault_session_log_chunks").where({ sessionId: session.id })).toHaveLength(0);+ const tailed = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs/tail`);+ expect(tailed.json().chunks).toEqual([]);});test("refuses a session that retired more than a day ago", async () => {@@ -806,330 +740,273 @@ describe("Agent Vault session logs", async () => {keyPrefix: "logs"});- const seedChunks = async (count: number) => {- const bundle = await createAccessBundle(- `session-logs-read-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`- );+ const uniqueLabel = () => `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;++ const seedSession = async () => {+ const bundle = await createAccessBundle(`session-logs-read-${uniqueLabel()}`);const session = await mintSession(bundle.name);- const proxy = await createProxy(`session-logs-read-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);+ const proxy = await createProxy(`session-logs-read-${uniqueLabel()}`);+ return { session, proxy };+ };++ // A millisecond apart, oldest first, so the order they list in is fixed.+ const upload = async (+ proxy: Awaited<ReturnType<typeof createProxy>>,+ sessionId: string,+ count: number,+ { lastRecordFrom = Date.now() - count, bytes = CHUNK_BYTES }: { lastRecordFrom?: number; bytes?: number } = {}+ ) => {+ const chunkIds: string[] = [];for (let i = 0; i < count; i += 1) {+ const chunkId = uuidv7({ msecs: lastRecordFrom + i });// eslint-disable-next-line no-await-in-loop- const { uploadUrl } = await recordChunk(- proxy,- session.id,- chunkBody({ firstSeq: i * 10, lastSeq: i * 10 + 9 })- );- fakeS3Bucket.put(uploadUrl, Buffer.alloc(CHUNK_BYTES));+ const { uploadUrl } = await requestUploadUrl(proxy, sessionId, chunkBody({ chunkId, ciphertextBytes: bytes }));+ fakeS3Bucket.put(uploadUrl, Buffer.alloc(bytes));+ chunkIds.push(chunkId);}- return { session, proxy };+ return chunkIds;+ };++ const seedChunks = async (count: number) => {+ const { session, proxy } = await seedSession();+ const chunkIds = await upload(proxy, session.id, count);+ return { session, proxy, chunkIds };+ };++ type TPage = {+ sessionLogs: {+ enabled: boolean;+ isRecordable: boolean;+ sessionKey: string | null;+ };+ chunks: {+ chunkId: string;+ proxyId: string;+ ciphertextBytes: number;+ presignedGetUrl: string;+ }[];+ nextCursor: string | null;+ };++ const read = async (sessionId: string, query = "") => {+ const res = await inject("GET", `/api/v1/agent-vault/sessions/${sessionId}/logs${query}`);+ expect(res.statusCode, res.payload).toBe(200);+ return JSON.parse(res.payload) as TPage;+ };++ const tail = async (sessionId: string, cursor?: string) => {+ const res = await inject(+ "GET",+ `/api/v1/agent-vault/sessions/${sessionId}/logs/tail${cursor ? `?cursor=${cursor}` : ""}`+ );+ expect(res.statusCode, res.payload).toBe(200);+ return JSON.parse(res.payload) as Omit<TPage, "nextCursor"> & { nextCursor: string };};test("returns the newest chunks first, each with a presigned url and the key to open them, and is never cached", async () => {await configure();- const { session, proxy } = await seedChunks(3);+ const { session, proxy, chunkIds } = await seedChunks(3);const res = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);expect(res.statusCode).toBe(200);expect(res.headers["cache-control"]).toBe("no-store, no-cache, must-revalidate, proxy-revalidate");- const body = JSON.parse(res.payload) as {- sessionLogs: { enabled: boolean; isRecordable: boolean; sessionKey: string };- chunks: {- chunkId: string;- proxyId: string;- presignedGetUrl: string | null;- recordCount: number;- ciphertextSha256: string;- createdAt: string;- }[];- nextCursor: string | null;- };-+ const body = JSON.parse(res.payload) as TPage;expect(body.sessionLogs.enabled).toBe(true);expect(body.sessionLogs.isRecordable).toBe(true);- expect(body.chunks.every((chunk) => Math.abs(Date.parse(chunk.createdAt) - Date.now()) < 60_000)).toBe(true);- expect(body.chunks.every((chunk) => chunk.ciphertextSha256 === CHUNK_SHA256)).toBe(true);- expect(Buffer.from(body.sessionLogs.sessionKey, "base64")).toHaveLength(32);- expect(body.chunks).toHaveLength(3);+ expect(Buffer.from(body.sessionLogs.sessionKey as string, "base64")).toHaveLength(32);+ expect(body.chunks.map((chunk) => chunk.chunkId)).toEqual([...chunkIds].reverse());expect(body.chunks.every((chunk) => chunk.proxyId === proxy.id)).toBe(true);-- const ids = body.chunks.map((chunk) => chunk.chunkId);- expect([...ids].sort().reverse()).toEqual(ids);+ expect(body.chunks.every((chunk) => chunk.ciphertextBytes === CHUNK_BYTES)).toBe(true);+ expect(body.nextCursor).toBeNull();body.chunks.forEach((chunk) => {- expect(fakeS3Bucket.get(chunk.presignedGetUrl!)).toHaveLength(CHUNK_BYTES);+ expect(fakeS3Bucket.get(chunk.presignedGetUrl)).toHaveLength(CHUNK_BYTES);});});+ test("a chunk that was registered but never uploaded is not listed", async () => {+ await configure();+ const { session, proxy } = await seedSession();+ await requestUploadUrl(proxy, session.id);++ expect((await read(session.id)).chunks).toEqual([]);+ });+test("a session created before session logs reads as not recordable, on the list and the tail", async () => {await configure();const bundle = await createAccessBundle(`session-logs-keyless-${Date.now()}`);const session = await mintSession(bundle.name);await testDb("agent_vault_sessions").where({ id: session.id }).update({ encryptedSessionLogKey: null });- const listed = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);- expect(listed.statusCode, listed.payload).toBe(200);- expect(JSON.parse(listed.payload).sessionLogs).toMatchObject({ enabled: true, isRecordable: false });-- const tailed = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs/tail`);- expect(tailed.statusCode, tailed.payload).toBe(200);- expect(JSON.parse(tailed.payload).sessionLogs).toMatchObject({ enabled: true, isRecordable: false });+ expect((await read(session.id)).sessionLogs).toMatchObject({ enabled: true, isRecordable: false });+ expect((await tail(session.id)).sessionLogs).toMatchObject({ enabled: true, isRecordable: false });});- test("a time window narrows the chunks without disturbing the cursor", async () => {+ test("a time window lists the chunks whose last request is in it, and those just after its end", async () => {await configure();- const bundle = await createAccessBundle(`session-logs-range-${Date.now()}`);- const session = await mintSession(bundle.name);- const proxy = await createProxy(`session-logs-range-${Date.now()}`);+ const { session, proxy } = await seedSession();const hour = 60 * 60 * 1000;- const startedAts = [new Date(Date.now() - 3 * hour), new Date(Date.now() - 2 * hour), new Date()];- for (const startedAt of startedAts) {- // eslint-disable-next-line no-await-in-loop- const { uploadUrl } = await recordChunk(proxy, session.id, chunkBody({ startedAt, endedAt: startedAt }));- fakeS3Bucket.put(uploadUrl, Buffer.alloc(CHUNK_BYTES));- }+ const [threeHoursAgo] = await upload(proxy, session.id, 1, { lastRecordFrom: Date.now() - 3 * hour });+ const [twoHoursAgo] = await upload(proxy, session.id, 1, { lastRecordFrom: Date.now() - 2 * hour });+ const [justAfter] = await upload(proxy, session.id, 1, { lastRecordFrom: Date.now() - 1.5 * hour + 60_000 });+ await upload(proxy, session.id, 1, { lastRecordFrom: Date.now() });- const windowed = await inject(- "GET",- `/api/v1/agent-vault/sessions/${session.id}/logs` +- `?from=${new Date(Date.now() - 2.5 * hour).toISOString()}` +- `&to=${new Date(Date.now() - 1.5 * hour).toISOString()}`- );- expect(windowed.statusCode).toBe(200);- const body = JSON.parse(windowed.payload) as { chunks: { startedAt: string }[] };- expect(body.chunks).toHaveLength(1);- expect(new Date(body.chunks[0].startedAt).getTime()).toBe(startedAts[1].getTime());-- const straddling = await recordChunk(- proxy,+ const windowed = await read(session.id,- chunkBody({- startedAt: new Date(Date.now() - 5 * hour),- endedAt: new Date(Date.now() - 2 * hour)- })- );- fakeS3Bucket.put(straddling.uploadUrl, Buffer.alloc(CHUNK_BYTES));-- const overlapping = await inject(- "GET",- `/api/v1/agent-vault/sessions/${session.id}/logs` +- `?from=${new Date(Date.now() - 2.5 * hour).toISOString()}` +- `&to=${new Date(Date.now() - 1.5 * hour).toISOString()}`+ `?from=${new Date(Date.now() - 2.5 * hour).toISOString()}&to=${new Date(Date.now() - 1.5 * hour).toISOString()}`);- expect((JSON.parse(overlapping.payload) as { chunks: unknown[] }).chunks).toHaveLength(2);+ expect(windowed.chunks.map((chunk) => chunk.chunkId)).toEqual([justAfter, twoHoursAgo]);+ expect(windowed.chunks.map((chunk) => chunk.chunkId)).not.toContain(threeHoursAgo);+ expect(windowed.nextCursor).toBeNull();- const all = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);- expect((JSON.parse(all.payload) as { chunks: unknown[] }).chunks).toHaveLength(4);+ expect((await read(session.id)).chunks).toHaveLength(4);});- test("pages with a cursor, and the last page reports no more", async () => {+ test("refuses a time window that ends before it starts", async () => {await configure();- const { session } = await seedChunks(5);-- const budget = 20;-- const first = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs?limit=${budget}`);- const firstBody = JSON.parse(first.payload) as { chunks: { chunkId: string }[]; nextCursor: string | null };- expect(firstBody.chunks).toHaveLength(2);- expect(firstBody.nextCursor).toBe(encodeHistoryCursor(firstBody.chunks[1].chunkId));-- const second = await inject(+ const { session } = await seedSession();+ const res = await inject("GET",- `/api/v1/agent-vault/sessions/${session.id}/logs?limit=${budget}&cursor=${firstBody.nextCursor}`+ `/api/v1/agent-vault/sessions/${session.id}/logs?from=${new Date().toISOString()}&to=${new Date(Date.now() - 60_000).toISOString()}`);- const secondBody = JSON.parse(second.payload) as { chunks: { chunkId: string }[]; nextCursor: string | null };- expect(secondBody.chunks).toHaveLength(2);- expect(secondBody.chunks.map((c) => c.chunkId)).not.toContain(firstBody.chunks[1].chunkId);-- const third = await inject(- "GET",- `/api/v1/agent-vault/sessions/${session.id}/logs?limit=${budget}&cursor=${secondBody.nextCursor}`- );- const thirdBody = JSON.parse(third.payload) as { chunks: unknown[]; nextCursor: string | null };- expect(thirdBody.chunks).toHaveLength(1);- expect(thirdBody.nextCursor).toBeNull();+ expect(res.statusCode).toBe(400);});- test("a page stops at its byte budget as well as its record budget", async () => {+ test("pages by size with a cursor, newest first, and the last page reports no more", async () => {await configure();- const bundle = await createAccessBundle(`session-logs-bytes-${Date.now()}`);- const session = await mintSession(bundle.name);- const proxy = await createProxy(`session-logs-bytes-${Date.now()}`);+ const { session, proxy } = await seedSession();+ const bytes = Math.floor(AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES * 0.6);+ const chunkIds = await upload(proxy, session.id, 3, { bytes });- for (let i = 0; i < 3; i += 1) {+ const seen: string[] = [];+ let cursor: string | null = null;+ let pages = 0;+ do {// eslint-disable-next-line no-await-in-loop- await recordChunk(- proxy,- session.id,- chunkBody({ firstSeq: i, lastSeq: i, recordCount: 1, ciphertextBytes: 8 * 1024 * 1024 })- );- }-- const res = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);- expect(res.statusCode).toBe(200);- const body = JSON.parse(res.payload) as { chunks: unknown[]; nextCursor: string | null };- expect(body.chunks).toHaveLength(2);- expect(body.nextCursor).not.toBeNull();+ const page: TPage = await read(session.id, cursor ? `?cursor=${cursor}` : "");+ expect(page.chunks).toHaveLength(1);+ seen.push(...page.chunks.map((chunk) => chunk.chunkId));+ cursor = page.nextCursor;+ pages += 1;+ } while (cursor && pages < 5);++ expect(pages).toBe(3);+ expect(seen).toEqual([...chunkIds].reverse());});- test("pages cover every chunk when seal order and record order disagree", async () => {+ test("files someone else put in the session's folder are skipped", async () => {await configure();- const bundle = await createAccessBundle(`session-logs-order-${Date.now()}`);- const session = await mintSession(bundle.name);- const slow = await createProxy(`session-logs-order-slow-${Date.now()}`);- const quick = await createProxy(`session-logs-order-quick-${Date.now()}`);+ const { session, chunkIds } = await seedChunks(1);+ fakeS3Bucket.putDirect(BUCKET, `logs/${projectId}/${session.id}/0000000000000_notes.txt`, Buffer.from("hi"));- const hoursAgo = (h: number) => new Date(Date.now() - h * 60 * 60 * 1000);+ expect((await read(session.id)).chunks.map((chunk) => chunk.chunkId)).toEqual(chunkIds);+ });- const written: string[] = [];- for (let i = 0; i < 6; i += 1) {- const startedAt = hoursAgo(i + 1);- // eslint-disable-next-line no-await-in-loop- const { chunkId } = await recordChunk(- i % 2 === 0 ? slow : quick,- session.id,- chunkBody({ startedAt, endedAt: startedAt, firstSeq: i * 10, lastSeq: i * 10 + 9 })- );- written.push(chunkId);- }+ test("the tail starts from the recent feed, so a chunk registered before the page opened still arrives", async () => {+ await configure();+ const { session, proxy } = await seedSession();+ const registered = await requestUploadUrl(proxy, session.id);- const seen: string[] = [];- let cursor: string | undefined;- for (let page = 0; page < 6; page += 1) {- // eslint-disable-next-line no-await-in-loop- const res = await inject(- "GET",- `/api/v1/agent-vault/sessions/${session.id}/logs?limit=1${cursor ? `&cursor=${cursor}` : ""}`- );- const body = JSON.parse(res.payload) as { chunks: { chunkId: string }[]; nextCursor: string | null };- seen.push(...body.chunks.map((chunk) => chunk.chunkId));- if (!body.nextCursor) break;- cursor = body.nextCursor;- }+ expect((await read(session.id)).chunks).toEqual([]);- expect(seen.sort()).toEqual([...written].sort());- expect(new Set(seen).size).toBe(written.length);+ fakeS3Bucket.put(registered.uploadUrl, Buffer.alloc(CHUNK_BYTES));+ const first = await tail(session.id);+ expect(first.chunks.map((chunk) => chunk.chunkId)).toEqual([registered.chunkId]);+ expect(fakeS3Bucket.get(first.chunks[0].presignedGetUrl)).toHaveLength(CHUNK_BYTES);+ expect(Buffer.from(first.sessionLogs.sessionKey as string, "base64")).toHaveLength(32);});- type THistoryBody = {- chunks: { chunkId: string }[];- nextCursor: string | null;- liveCursor: string;- };+ test("each tail continues after the last entry it returned", async () => {+ await configure();+ const { session, proxy } = await seedSession();+ await requestUploadUrl(proxy, session.id);- type TTailBody = {- chunks: { chunkId: string }[];- nextCursor: string;- hasMore: boolean;- };+ const first = await tail(session.id);+ expect(first.chunks).toHaveLength(1);- test("the tail returns a late chunk that a page would sort among old ones", async () => {- await configure();- const { session, proxy } = await seedChunks(3);+ const quiet = await tail(session.id, first.nextCursor);+ expect(quiet.chunks).toEqual([]);+ expect(quiet.nextCursor).toBe(first.nextCursor);- const first = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs?limit=20`);- const firstBody = JSON.parse(first.payload) as THistoryBody;- expect(firstBody.chunks).toHaveLength(2);- expect(typeof firstBody.liveCursor).toBe("string");+ const next = await requestUploadUrl(proxy, session.id);+ const later = await tail(session.id, quiet.nextCursor);+ expect(later.chunks.map((chunk) => chunk.chunkId)).toEqual([next.chunkId]);+ });- const late = await recordChunk(+ test("the tail returns a chunk from long ago that asked for its upload link now", async () => {+ await configure();+ const { session, proxy } = await seedSession();+ const late = await requestUploadUrl(proxy,session.id,chunkBody({ chunkId: uuidv7({ msecs: Date.now() - 60 * 60_000 }) }));- fakeS3Bucket.put(late.uploadUrl, Buffer.alloc(CHUNK_BYTES));-- const newest = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs?limit=20`);- expect((JSON.parse(newest.payload) as THistoryBody).chunks.map((c) => c.chunkId)).not.toContain(late.chunkId);- const received = await inject(- "GET",- `/api/v1/agent-vault/sessions/${session.id}/logs/tail?cursor=${firstBody.liveCursor}`- );- expect(received.statusCode).toBe(200);- const body = JSON.parse(received.payload) as TTailBody;- const ids = body.chunks.map((c) => c.chunkId);-- expect(ids[ids.length - 1]).toBe(late.chunkId);- expect(ids).toEqual(expect.arrayContaining(firstBody.chunks.map((c) => c.chunkId)));- expect(typeof body.nextCursor).toBe("string");- expect(body.hasMore).toBe(false);+ expect((await tail(session.id)).chunks.map((chunk) => chunk.chunkId)).toEqual([late.chunkId]);});- test("a tail read cut short resumes after its last chunk, so a backlog is worked through", async () => {+ test("the feed keeps only the most recent chunks", async () => {await configure();- const { session } = await seedChunks(3);-- let cursor = encodeTailCursor(new Date(Date.now() - 60 * 60 * 1000));- const seen = new Set<string>();- let reads = 0;- let hasMore = true;- while (hasMore && reads < 10) {+ const { session, proxy } = await seedSession();+ for (let i = 0; i < AGENT_VAULT_SESSION_LOG_FEED_MAX_ENTRIES + 2; i += 1) {// eslint-disable-next-line no-await-in-loop- const res = await inject(- "GET",- `/api/v1/agent-vault/sessions/${session.id}/logs/tail?limit=10&cursor=${cursor}`- );- const body = JSON.parse(res.payload) as TTailBody;- body.chunks.forEach((chunk) => seen.add(chunk.chunkId));- ({ hasMore } = body);- cursor = body.nextCursor;- reads += 1;+ await requestUploadUrl(proxy, session.id);}- expect(hasMore).toBe(false);- expect(seen.size).toBe(3);- expect(reads).toBeLessThan(10);- });-- test("the tail can start without a cursor", async () => {- await configure();- const { session } = await seedChunks(1);-- const res = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs/tail`);- expect(res.statusCode).toBe(200);- expect(typeof (JSON.parse(res.payload) as TTailBody).nextCursor).toBe("string");+ expect((await tail(session.id)).chunks).toHaveLength(AGENT_VAULT_SESSION_LOG_FEED_MAX_ENTRIES);});test.each([- { why: "a live cursor passed to history", path: "logs", cursor: () => encodeTailCursor(new Date()) },+ { why: "a live cursor passed to history", path: "logs", cursor: () => encodeTailCursor("1791278402731-0") },{why: "a history cursor passed to the tail",path: "logs/tail",- cursor: () => encodeHistoryCursor(nextChunkId())+ cursor: () => encodeHistoryCursor("8208694117999_x")},{ why: "a garbage cursor passed to history", path: "logs", cursor: () => "not-a-cursor" },{ why: "a garbage cursor passed to the tail", path: "logs/tail", cursor: () => "not-a-cursor" }])("rejects $why", async ({ path, cursor }) => {await configure();- const { session } = await seedChunks(1);+ const { session } = await seedSession();const res = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/${path}?cursor=${cursor()}`);expect(res.statusCode).toBe(422);});- const readLink = async (sessionId: string) => {- const res = await inject("GET", `/api/v1/agent-vault/sessions/${sessionId}/logs`);- return (JSON.parse(res.payload) as { chunks: { presignedGetUrl: string | null }[] }).chunks[0].presignedGetUrl;- };-- test("a chunk in a bucket the project no longer uses is not presigned, and is again once the bucket is switched back", async () => {+ test("after a bucket change, older logs don't show until the bucket is switched back", async () => {await configure();- const { session } = await seedChunks(1);+ const { session, chunkIds } = await seedChunks(1);expect((await saveConfig({ bucket: "a-different-bucket" })).statusCode).toBe(200);- expect(await readLink(session.id)).toBeNull();+ expect((await read(session.id)).chunks).toEqual([]);expect((await saveConfig({ bucket: BUCKET })).statusCode).toBe(200);- expect(fakeS3Bucket.get((await readLink(session.id)) as string)).toEqual(Buffer.alloc(CHUNK_BYTES));+ 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));});- test("a chunk keeps its link after only the prefix changes", async () => {+ test("after a prefix change, older logs don't show until the prefix is switched back", async () => {await configure();- const { session } = await seedChunks(1);+ const { session, chunkIds } = await seedChunks(1);expect((await saveConfig({ keyPrefix: "other" })).statusCode).toBe(200);- expect(fakeS3Bucket.get((await readLink(session.id)) as string)).toEqual(Buffer.alloc(CHUNK_BYTES));+ expect((await read(session.id)).chunks).toEqual([]);++ expect((await saveConfig({ keyPrefix: "logs" })).statusCode).toBe(200);+ expect((await read(session.id)).chunks.map((chunk) => chunk.chunkId)).toEqual(chunkIds);+ });++ test("the tail skips chunks registered before a bucket change, and still moves past them", async () => {+ await configure();+ const { session, proxy } = await seedSession();+ await requestUploadUrl(proxy, session.id);++ expect((await saveConfig({ 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"));});test("a key copied from another session is refused rather than handed out", async () => {@@ -1151,62 +1028,55 @@ describe("Agent Vault session logs", async () => {expect((await saveConfig({ enabled: false })).statusCode).toBe(200);- const res = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);- const body = JSON.parse(res.payload) as { sessionLogs: { enabled: boolean }; chunks: unknown[] };+ const body = await read(session.id);expect(body.sessionLogs.enabled).toBe(false);expect(body.chunks).toHaveLength(2);});- test("without a connection, a session lists what it recorded as unreadable rather than as nothing", async () => {+ const readFails = async (sessionId: string, path = "logs") => {+ const res = await inject("GET", `/api/v1/agent-vault/sessions/${sessionId}/${path}`);+ 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);- const res = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);- expect(res.statusCode).toBe(200);- const body = JSON.parse(res.payload) as {- sessionLogs: {- sessionKey: string | null;- storageUnavailable: { reason: string; message: string | null } | null;- };- chunks: { presignedGetUrl: string | null }[];- };- expect(body.sessionLogs.storageUnavailable).toEqual({ reason: "no-connection", message: null });- expect(body.sessionLogs.sessionKey).toBeNull();- expect(body.chunks.map((chunk) => chunk.presignedGetUrl)).toEqual([null, null]);-- const since = new Date(Date.now() - 60 * 60_000);- const live = await inject(- "GET",- `/api/v1/agent-vault/sessions/${session.id}/logs/tail?cursor=${encodeTailCursor(since)}`- );- const liveBody = JSON.parse(live.payload) as {- sessionLogs: { storageUnavailable: { reason: string } | null };- chunks: unknown[];- nextCursor: string;- };- expect(liveBody.chunks).toEqual([]);- expect(liveBody.nextCursor).toBe(encodeTailCursor(since));- expect(liveBody.sessionLogs.storageUnavailable?.reason).toBe("no-connection");+ 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 session lists what it recorded and says why", async () => {+ 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);fakeAwsConnection.failsConfigWith("AWS refused to assume the role");- const res = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);- expect(res.statusCode).toBe(200);- const body = JSON.parse(res.payload) as {- sessionLogs: { storageUnavailable: { reason: string; message: string | null } | null };- chunks: { presignedGetUrl: string | null }[];- };- expect(body.sessionLogs.storageUnavailable).toEqual({- reason: "connection-unusable",+ const { statusCode, body } = await readFails(session.id);+ expect(statusCode).toBe(400);+ expect(body).toMatchObject({+ error: "AgentVaultSessionLogStorageUnavailable",message: `Couldn't use the AWS connection '${connectionName}' for session logs: AWS refused to assume the role`});- expect(body.chunks.map((chunk) => chunk.presignedGetUrl)).toEqual([null]);+ });++ test("when the bucket refuses to list, a read fails with the named error instead of looking empty", async () => {+ await configure();+ const { session } = await seedChunks(1);+ fakeS3Bucket.failsListWith(true);++ const { statusCode, body } = await readFails(session.id);+ expect(statusCode).toBe(400);+ expect(body.error).toBe("AgentVaultSessionLogStorageUnavailable");+ expect(body.message).toContain("s3:ListBucket");});test("a session with no logs comes back empty rather than erroring", async () => {@@ -1214,9 +1084,7 @@ describe("Agent Vault session logs", async () => {const bundle = await createAccessBundle(`session-logs-empty-${Date.now()}`);const session = await mintSession(bundle.name);- const res = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);- expect(res.statusCode).toBe(200);- expect(JSON.parse(res.payload)).toMatchObject({+ expect(await read(session.id)).toMatchObject({chunks: [],nextCursor: null,sessionLogs: { sessionKey: null }@@ -1252,7 +1120,7 @@ describe("Agent Vault session logs", async () => {const ownSession = minted.json().session as { id: string };const proxy = await createProxy(`session-logs-reader-${Date.now()}`);- const { uploadUrl } = await recordChunk(proxy, ownSession.id);+ const { uploadUrl } = await requestUploadUrl(proxy, ownSession.id);fakeS3Bucket.put(uploadUrl, Buffer.alloc(CHUNK_BYTES));const own = await member.as("GET", `/api/v1/agent-vault/sessions/${ownSession.id}/logs`);@@ -1263,23 +1131,5 @@ describe("Agent Vault session logs", async () => {await member.cleanup();}});-- test("an unknown session is a 404", async () => {- await configure();- const res = await inject("GET", `/api/v1/agent-vault/sessions/${crypto.randomUUID()}/logs`);- expect(res.statusCode).toBe(404);- });-- test.each([- { limit: "0", why: "below the floor" },- { limit: "5001", why: "above the ceiling" },- { limit: "abc", why: "not a number" }- ])("rejects a limit that is $why", async ({ limit }) => {- await configure();- const bundle = await createAccessBundle(`session-logs-limit-${Date.now()}-${limit}`);- const session = await mintSession(bundle.name);- const res = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs?limit=${limit}`);- expect(res.statusCode).toBe(422);- });});});diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex ba6df351d4..f5ccfd7fcc 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -41,9 +41,6 @@ import {TAgentVaultSessionAccessBundles,TAgentVaultSessionAccessBundlesInsert,TAgentVaultSessionAccessBundlesUpdate,- TAgentVaultSessionLogChunks,- TAgentVaultSessionLogChunksInsert,- TAgentVaultSessionLogChunksUpdate,TAgentVaultSessionLogConfigs,TAgentVaultSessionLogConfigsInsert,TAgentVaultSessionLogConfigsUpdate,@@ -1862,11 +1859,6 @@ declare module "knex/types/tables" {TAgentVaultSessionLogConfigsInsert,TAgentVaultSessionLogConfigsUpdate>;- [TableName.AgentVaultSessionLogChunk]: KnexOriginal.CompositeTableType<- TAgentVaultSessionLogChunks,- TAgentVaultSessionLogChunksInsert,- TAgentVaultSessionLogChunksUpdate- >;[TableName.PamAccountPolicy]: KnexOriginal.CompositeTableType<TPamAccountPolicies,TPamAccountPoliciesInsert,diff --git a/backend/src/db/migrations/20261007120000_drop-agent-vault-session-log-chunks.ts b/backend/src/db/migrations/20261007120000_drop-agent-vault-session-log-chunks.tsnew file mode 100644index 0000000000..4b21e1e5cc--- /dev/null+++ b/backend/src/db/migrations/20261007120000_drop-agent-vault-session-log-chunks.ts@@ -0,0 +1,66 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ await dropOnUpdateTrigger(knex, TableName.AgentVaultSessionLogChunk);+ await knex.schema.dropTableIfExists(TableName.AgentVaultSessionLogChunk);++ if (await knex.schema.hasColumn(TableName.AgentVaultSessionLogConfig, "storedChunkCount")) {+ await knex.schema.alterTable(TableName.AgentVaultSessionLogConfig, (t) => {+ t.dropColumn("storedChunkCount");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasColumn(TableName.AgentVaultSessionLogConfig, "storedChunkCount"))) {+ await knex.schema.alterTable(TableName.AgentVaultSessionLogConfig, (t) => {+ t.bigint("storedChunkCount").notNullable().defaultTo(0);+ });+ }++ if (await knex.schema.hasTable(TableName.AgentVaultSessionLogChunk)) return;++ await knex.schema.createTable(TableName.AgentVaultSessionLogChunk, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("chunkId").notNullable();++ t.uuid("sessionId").notNullable();+ t.foreign("sessionId").references("id").inTable(TableName.AgentVaultSession).onDelete("CASCADE");++ t.string("projectId", 36).notNullable();+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");++ t.string("proxyId", 36).notNullable();+ t.string("proxyName", 64).notNullable();++ t.timestamp("startedAt", { useTz: true }).notNullable();+ t.timestamp("endedAt", { useTz: true }).notNullable();++ t.bigint("firstSeq").notNullable();+ t.bigint("lastSeq").notNullable();++ t.integer("recordCount").notNullable();+ t.bigint("droppedCount").notNullable().defaultTo(0);++ t.string("bucket", 255).notNullable();++ t.string("objectKey", 1024).notNullable();+ t.integer("ciphertextBytes").notNullable();+ t.string("iv", 24).notNullable();+ t.string("ciphertextSha256", 43).notNullable();++ t.timestamps(true, true, true);++ t.unique(["sessionId", "chunkId"]);++ t.index(["sessionId", "createdAt"]);+ t.index(["sessionId", "startedAt"]);+ t.index(["projectId"]);+ });++ await createOnUpdateTrigger(knex, TableName.AgentVaultSessionLogChunk);+}diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yamlindex 1adb6e3f8d..3d0fa20fdd 100644--- a/backend/src/db/sanitized-schema.yaml+++ b/backend/src/db/sanitized-schema.yaml@@ -89,27 +89,12 @@ tables:- accessBundleId- createdAt- - name: agent_vault_session_log_chunks- source: public.agent_vault_session_log_chunks- columns:- - id- - sessionId- - projectId- - proxyId- - startedAt- - endedAt- - recordCount- - droppedCount- - ciphertextBytes- - createdAt-- name: agent_vault_session_log_configssource: public.agent_vault_session_log_configscolumns:- id- projectId- enabled- - storedChunkCount- createdAt- updatedAtdiff --git a/backend/src/db/schemas/agent-vault-session-log-chunks.ts b/backend/src/db/schemas/agent-vault-session-log-chunks.tsdeleted file mode 100644index 9e8c271b1c..0000000000--- a/backend/src/db/schemas/agent-vault-session-log-chunks.ts+++ /dev/null@@ -1,39 +0,0 @@-// Code generated by automation script, DO NOT EDIT.-// Automated by pulling database and generating zod schema-// To update. Just run npm run generate:schema-// Written by akhilmhdh.--import { z } from "zod";--import { TImmutableDBKeys } from "./models";--export const AgentVaultSessionLogChunksSchema = z.object({- id: z.string().uuid(),- chunkId: z.string().uuid(),- sessionId: z.string().uuid(),- projectId: z.string(),- proxyId: z.string(),- proxyName: z.string(),- startedAt: z.date(),- endedAt: z.date(),- firstSeq: z.coerce.number(),- lastSeq: z.coerce.number(),- recordCount: z.number(),- droppedCount: z.coerce.number().default(0),- bucket: z.string(),- objectKey: z.string(),- ciphertextBytes: z.number(),- iv: z.string(),- ciphertextSha256: z.string(),- createdAt: z.date(),- updatedAt: z.date()-});--export type TAgentVaultSessionLogChunks = z.infer<typeof AgentVaultSessionLogChunksSchema>;-export type TAgentVaultSessionLogChunksInsert = Omit<- z.input<typeof AgentVaultSessionLogChunksSchema>,- TImmutableDBKeys->;-export type TAgentVaultSessionLogChunksUpdate = Partial<- Omit<z.input<typeof AgentVaultSessionLogChunksSchema>, TImmutableDBKeys>->;diff --git a/backend/src/db/schemas/agent-vault-session-log-configs.ts b/backend/src/db/schemas/agent-vault-session-log-configs.tsindex 770754202f..0322de6735 100644--- a/backend/src/db/schemas/agent-vault-session-log-configs.ts+++ b/backend/src/db/schemas/agent-vault-session-log-configs.ts@@ -15,7 +15,6 @@ export const AgentVaultSessionLogConfigsSchema = z.object({bucket: z.string().nullable().optional(),region: z.string().nullable().optional(),keyPrefix: z.string().nullable().optional(),- storedChunkCount: z.coerce.number().default(0),createdAt: z.date(),updatedAt: z.date()});diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex b215512f88..e7638966b9 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -11,7 +11,6 @@ export * from "./agent-vault-service-substitutions";export * from "./agent-vault-service-variable-references";export * from "./agent-vault-services";export * from "./agent-vault-session-access-bundles";-export * from "./agent-vault-session-log-chunks";export * from "./agent-vault-session-log-configs";export * from "./agent-vault-sessions";export * from "./agent-vault-variables";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex a59bc1ce05..44d0893d7b 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -285,6 +285,7 @@ export enum TableName {AgentVaultSessionAccessBundle = "agent_vault_session_access_bundles",AgentVaultProxy = "agent_vault_proxies",AgentVaultSessionLogConfig = "agent_vault_session_log_configs",+ // Dropped; kept only for the migrations that create and drop it.AgentVaultSessionLogChunk = "agent_vault_session_log_chunks",ExternalMigrationConfig = "external_migration_configs",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 1a946c86c5..80c17f6e36 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@@ -210,9 +210,9 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProviconfig: { rateLimit: agentVaultSessionLogChunkLimit },schema: {hide: true,- operationId: "createAgentVaultSessionLogChunk",+ operationId: "createAgentVaultSessionLogChunkUploadUrl",description:- "Records an encrypted session log chunk and returns a presigned URL to upload the chunk to. If you send the same `chunkId` again, you get a new URL for the same chunk.",+ "Returns a presigned URL to upload an encrypted session log chunk to, and shows the chunk in the live view. If you send the same `chunkId` again, you get a new URL for the same object.",tags: [ApiDocsTags.AgentVaultSessionLogs],params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),body: AgentVaultSessionLogChunkCreateSchema,@@ -220,7 +220,7 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvi},onRequest: verifyAuth([AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN]),handler: async (req) => {- return server.services.agentVaultSessionLog.recordChunk({+ return server.services.agentVaultSessionLog.createChunkUploadUrl({proxyId: req.permission.id,sessionId: req.params.sessionId,chunk: req.bodydiff --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 d1618f0566..6319f6d0b3 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@@ -24,7 +24,7 @@ export const registerAgentVaultSessionLogRouter = async (server: FastifyZodProvihide: false,operationId: "listAgentVaultSessionLogs",description:- "Lists a session's logs in chunks, newest first. A chunk is an encrypted batch of [records](/documentation/platform/agent-vault/session-logs#what-gets-recorded) that a proxy uploaded. To decrypt the chunks, follow [Reading session logs through the API](/documentation/platform/agent-vault/session-logs#reading-session-logs-through-the-api). To keep receiving new logs, pass `liveCursor` to [the endpoint that tails session logs](/api-reference/endpoints/agent-vault-session-logs/tail).",+ "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`.",tags: [ApiDocsTags.AgentVaultSessionLogs],params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),querystring: AgentVaultSessionLogHistoryQuerySchema,@@ -37,8 +37,7 @@ export const registerAgentVaultSessionLogRouter = async (server: FastifyZodProviprojectId: req.internalAgentVaultProjectId,ctx: actorContext(req),sessionId: req.params.sessionId,- limit: req.query.limit,- before: req.query.cursor,+ cursor: req.query.cursor,from: req.query.from,to: req.query.to});@@ -53,7 +52,7 @@ export const registerAgentVaultSessionLogRouter = async (server: FastifyZodProvihide: false,operationId: "tailAgentVaultSessionLogs",description:- "Lists a session's new logs since your last call, oldest first. The same chunk can appear in more than one response, so skip any `chunkId` you've already 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).",+ "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`.",tags: [ApiDocsTags.AgentVaultSessionLogs],params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),querystring: AgentVaultSessionLogTailQuerySchema,@@ -66,8 +65,7 @@ export const registerAgentVaultSessionLogRouter = async (server: FastifyZodProviprojectId: req.internalAgentVaultProjectId,ctx: actorContext(req),sessionId: req.params.sessionId,- limit: req.query.limit,- receivedAfter: req.query.cursor+ cursor: req.query.cursor});}});diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.tsindex 341bde9d3f..3195db7c30 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-router.ts@@ -41,14 +41,8 @@ const SessionSchema = z.object({createdAt: z.date()});-const SessionWithLogCountsSchema = SessionSchema.extend({- accessBundles: SessionAccessBundleSchema.array(),- recentSessionLogCounts: z- .object({- recordedCount: z.number().describe(AGENT_VAULT.SESSION.recentRecordedCount),- droppedCount: z.number().describe(AGENT_VAULT.SESSION.recentDroppedCount)- })- .describe(AGENT_VAULT.SESSION.recentSessionLogCounts)+const SessionWithAccessBundlesSchema = SessionSchema.extend({+ accessBundles: SessionAccessBundleSchema.array()});export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider) => {@@ -86,7 +80,7 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider}),response: {200: z.object({- sessions: SessionWithLogCountsSchema.array(),+ sessions: SessionWithAccessBundlesSchema.array(),totalCount: z.number()})}@@ -114,7 +108,7 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvidertags: [ApiDocsTags.AgentVaultSessions],params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),response: {- 200: z.object({ session: SessionWithLogCountsSchema })+ 200: z.object({ session: SessionWithAccessBundlesSchema })}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),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 a0784e1d92..40b27eeb7c 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@@ -92,8 +92,7 @@ export const registerAgentVaultSettingsRouter = async (server: FastifyZodProvideschema: {hide: true,operationId: "getAgentVaultSessionLogHealth",- description:- "Gets whether session logs have reached their storage limit, and whether Infisical can use the AWS connection",+ description: "Gets whether Infisical can use the AWS connection for session logs",tags: [ApiDocsTags.AgentVaultSettings],response: { 200: AgentVaultSessionLogHealthResponseSchema }},diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-chunk-dal.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-chunk-dal.tsdeleted file mode 100644index 37d638d4d9..0000000000--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-chunk-dal.ts+++ /dev/null@@ -1,200 +0,0 @@-import { Knex } from "knex";--import { TDbClient } from "@app/db";-import { TableName, TAgentVaultSessionLogChunks, TAgentVaultSessionLogChunksInsert } from "@app/db/schemas";-import { DatabaseError } from "@app/lib/errors";-import { ormify } from "@app/lib/knex";--export type TAgentVaultSessionLogChunkDALFactory = ReturnType<typeof agentVaultSessionLogChunkDALFactory>;--export const agentVaultSessionLogChunkDALFactory = (db: TDbClient) => {- const orm = ormify(db, TableName.AgentVaultSessionLogChunk);-- // Ordered and cursored on chunkId, never startedAt: proxies seal out of order, so mixing the two skips rows.- const findForSessionPage = async (- {- sessionId,- recordBudget,- byteBudget,- maxChunks,- before,- from,- to- }: {- sessionId: string;- recordBudget: number;- byteBudget: number;- maxChunks: number;- before?: string;- from?: Date;- to?: Date;- },- tx?: Knex- ): Promise<{ chunks: TAgentVaultSessionLogChunks[]; hasMore: boolean }> => {- try {- const query = (tx || db.replicaNode())(TableName.AgentVaultSessionLogChunk)- .where({ sessionId })- .orderBy("chunkId", "desc")- .limit(maxChunks);-- if (before) void query.andWhere("chunkId", "<", before);-- if (from) void query.andWhere("endedAt", ">=", from);- if (to) void query.andWhere("startedAt", "<=", to);-- const rows = (await query) as TAgentVaultSessionLogChunks[];-- let taken = 0;- let bytes = 0;- const page: TAgentVaultSessionLogChunks[] = [];- for (const row of rows) {- page.push(row);- taken += row.recordCount;- bytes += row.ciphertextBytes;- if (taken >= recordBudget || bytes >= byteBudget) break;- }-- return { chunks: page, hasMore: page.length < rows.length || rows.length === maxChunks };- } catch (error) {- throw new DatabaseError({ error, name: "Find agent vault session log chunks" });- }- };-- const findReceivedForSession = async (- {- sessionId,- receivedAfter,- recordBudget,- byteBudget,- maxChunks- }: { sessionId: string; receivedAfter: Date; recordBudget: number; byteBudget: number; maxChunks: number },- tx?: Knex- ): Promise<{ chunks: TAgentVaultSessionLogChunks[]; hasMore: boolean }> => {- try {- const rows = (await (tx || db.replicaNode())(TableName.AgentVaultSessionLogChunk)- .where({ sessionId })- .andWhere("createdAt", ">=", receivedAfter)- .orderBy([- { column: "createdAt", order: "asc" },- { column: "chunkId", order: "asc" }- ])- .limit(maxChunks)) as TAgentVaultSessionLogChunks[];-- let taken = 0;- let bytes = 0;- const page: TAgentVaultSessionLogChunks[] = [];- for (const row of rows) {- page.push(row);- // The chunk exactly at receivedAfter resends the last read's; counting it could stall paging forever.- if (row.createdAt.getTime() > receivedAfter.getTime()) {- taken += row.recordCount;- bytes += row.ciphertextBytes;- }- if (taken >= recordBudget || bytes >= byteBudget) break;- }-- return { chunks: page, hasMore: page.length < rows.length || rows.length === maxChunks };- } catch (error) {- throw new DatabaseError({ error, name: "Find received agent vault session log chunks" });- }- };-- const sumRecentCounts = async (- { sessionIds, windowMs }: { sessionIds: string[]; windowMs: number },- tx?: Knex- ): Promise<Map<string, { recordedCount: number; droppedCount: number }>> => {- try {- const conn = tx || db.replicaNode();- const rows = (await conn(TableName.AgentVaultSessionLogChunk)- .join(- conn(TableName.AgentVaultSessionLogChunk)- .whereIn("sessionId", sessionIds)- .groupBy("sessionId")- .select("sessionId", db.raw(`MAX("startedAt") AS "latestStartedAt"`))- .as("latest"),- "latest.sessionId",- `${TableName.AgentVaultSessionLogChunk}.sessionId`- )- .whereIn(`${TableName.AgentVaultSessionLogChunk}.sessionId`, sessionIds)- .whereRaw(`?? >= "latest"."latestStartedAt" - (? * interval '1 millisecond')`, [- `${TableName.AgentVaultSessionLogChunk}.startedAt`,- windowMs- ])- .groupBy(`${TableName.AgentVaultSessionLogChunk}.sessionId`)- .select(- `${TableName.AgentVaultSessionLogChunk}.sessionId`,- db.raw(`SUM(??) AS "recordedCount"`, [`${TableName.AgentVaultSessionLogChunk}.recordCount`]),- db.raw(`SUM(??) AS "droppedCount"`, [`${TableName.AgentVaultSessionLogChunk}.droppedCount`])- )) as { sessionId: string; recordedCount: string; droppedCount: string }[];-- return new Map(- rows.map((row) => [- row.sessionId,- { recordedCount: Number(row.recordedCount), droppedCount: Number(row.droppedCount) }- ])- );- } catch (error) {- throw new DatabaseError({ error, name: "Sum recent agent vault session log counts" });- }- };-- const createIfAbsent = async (- values: TAgentVaultSessionLogChunksInsert,- tx?: Knex- ): Promise<TAgentVaultSessionLogChunks | undefined> => {- try {- const [row] = (await (tx || db)(TableName.AgentVaultSessionLogChunk)- .insert(values)- .onConflict(["sessionId", "chunkId"])- .ignore()- .returning("*")) as TAgentVaultSessionLogChunks[];- return row;- } catch (error) {- throw new DatabaseError({ error, name: "Create agent vault session log chunk" });- }- };-- // Checks the destination in the same statement as the move, so a settings save that lands first isn't undone.- const moveToDestinationIfCurrent = async (- {- id,- projectId,- bucket,- keyPrefix,- objectKey- }: { id: string; projectId: string; bucket: string; keyPrefix: string | null; objectKey: string },- tx?: Knex- ): Promise<TAgentVaultSessionLogChunks | undefined> => {- try {- const result = await (tx || db).raw<{ rows: TAgentVaultSessionLogChunks[] }>(- `UPDATE ?? SET "bucket" = ?, "objectKey" = ?- WHERE "id" = ? AND EXISTS (- SELECT 1 FROM ?? cfg WHERE cfg."projectId" = ? AND cfg."bucket" = ? AND cfg."keyPrefix" IS NOT DISTINCT FROM ?- )- RETURNING *`,- [- TableName.AgentVaultSessionLogChunk,- bucket,- objectKey,- id,- TableName.AgentVaultSessionLogConfig,- projectId,- bucket,- keyPrefix- ]- );- return result.rows[0];- } catch (error) {- throw new DatabaseError({ error, name: "Move agent vault session log chunk" });- }- };-- return {- ...orm,- findForSessionPage,- findReceivedForSession,- sumRecentCounts,- createIfAbsent,- moveToDestinationIfCurrent- };-};diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-config-dal.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-config-dal.tsindex fdac272d8b..6679f5d451 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-config-dal.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-config-dal.ts@@ -23,18 +23,5 @@ export const agentVaultSessionLogConfigDALFactory = (db: TDbClient) => {}};- // One UPDATE, never read-modify-write: its row lock is what keeps the ceiling check correct under load.- const recordStoredChunk = async (id: string, tx?: Knex): Promise<number> => {- try {- const result = await (tx || db).raw<{ rows: { storedChunkCount: string }[] }>(- `UPDATE ?? SET "storedChunkCount" = "storedChunkCount" + 1 WHERE "id" = ? RETURNING "storedChunkCount"`,- [TableName.AgentVaultSessionLogConfig, id]- );- return Number(result.rows[0]?.storedChunkCount ?? 0);- } catch (error) {- throw new DatabaseError({ error, name: "Record agent vault session log stored chunk" });- }- };-- return { ...orm, findByProjectIdFromPrimary, recordStoredChunk };+ return { ...orm, findByProjectIdFromPrimary };};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 6077c4a913..5395bc4bec 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@@ -1,35 +1,25 @@-// A proxy uploads session logs in encrypted chunks. A record is one request an agent made. A chunk can't have more-// than 1,000 records (the Go proxy uploads once it has 1,000, sessionLogFlushRecords), and it can't be bigger than-// 8 MiB. Infisical also refuses a chunk that's too small to be real:-// - Any chunk under 18 bytes, the size of an empty chunk (2 bytes of content plus 16 bytes of encryption overhead)-// - A chunk under 60 bytes for each record it claims to hold. A chunk that claims 100 records must be at least-// 6,000 bytes, because no real record is smaller than 60 bytes, so a smaller chunk has a wrong count.-export const AGENT_VAULT_SESSION_LOG_MAX_CHUNK_RECORDS = 1000;-export const AGENT_VAULT_SESSION_LOG_MIN_CHUNK_BYTES = 18; // an empty "[]" plus the 16-byte AES-GCM tag+import RE2 from "re2";++// A proxy uploads session logs in encrypted chunks. A record is one request an agent made. A chunk can't be bigger+// 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-export const AGENT_VAULT_SESSION_LOG_MIN_BYTES_PER_RECORD = 60; // well under the smallest real record, so only a lying count trips it--// Lowercase because Postgres returns uuids that way and the browser rebuilds the AAD from that string. v7 because-// history pages in chunk id order.-export const AGENT_VAULT_SESSION_LOG_CHUNK_ID_REGEX =- /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;--// Infisical checks each chunk's timestamps, which come from the proxy's clock. If a chunk says it ended more than-// 5 minutes in the future, Infisical refuses it, because the proxy's clock is ahead. A session ends when it's-// revoked, when it expires, or when the user or machine identity that created it is deleted. From the first of-// those, its proxy has 24 hours to upload any chunks it still has, and later uploads are refused. A chunk that-// started more than 30 days ago is always refused, even for a session that's still running.++// 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.+export const AGENT_VAULT_SESSION_LOG_CHUNK_ID_PATTERN =+ "[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";+export const AGENT_VAULT_SESSION_LOG_CHUNK_ID_REGEX = new RE2(`^${AGENT_VAULT_SESSION_LOG_CHUNK_ID_PATTERN}$`);++// Infisical checks when each chunk ended, which comes from the proxy's clock. If a chunk says it ended more than+// 5 minutes in the future, Infisical refuses it, because the proxy's clock is ahead. A proxy holds chunks only in+// memory, so one that says it ended more than 30 days ago means the clock is behind, and is refused the same way.+// A session ends when it's revoked, when it expires, or when the user or machine identity that created it is+// deleted. From the first of those, its proxy has 24 hours to upload any chunks it still has, and later uploads+// are refused.export const AGENT_VAULT_SESSION_LOG_CLOCK_SKEW_MS = 5 * 60_000; // 5 minutesexport const AGENT_VAULT_SESSION_LOG_LATE_CHUNK_GRACE_MS = 24 * 60 * 60_000; // 24 hours: after a session ends, its proxy has one more day to upload what it still holds-export const AGENT_VAULT_SESSION_LOG_MAX_CHUNK_AGE_MS = 30 * 24 * 60 * 60_000; // 30 days: logs older than a month are never accepted, ended session or not--// Each organization can store up to 100,000 chunks, which is up to about 100 million requests. Once it reaches-// that, Infisical refuses new chunks and the error asks the customer to contact support. The limit isn't-// published, so the error doesn't state it.-export const AGENT_VAULT_SESSION_LOG_MAX_STORED_CHUNKS = 100_000;--// A session's recorded and dropped counts cover the 24 hours before its latest chunk, so an ended session keeps them.-export const AGENT_VAULT_SESSION_LOG_RECENT_COUNTS_WINDOW_MS = 24 * 60 * 60_000; // 24 hours+export const AGENT_VAULT_SESSION_LOG_MAX_CHUNK_AGE_MS = 30 * 24 * 60 * 60_000; // 30 days: a chunk that ended longer ago than this means the proxy's clock is behind// While the License Server can't be reached, the last plan it returned decides for this long, so a downgrade// still lands within an hour of an outage starting.@@ -38,14 +28,34 @@ export const AGENT_VAULT_SESSION_LOG_LAST_KNOWN_PLAN_MAX_AGE_MS = 60 * 60_000; /// A link to upload or download a chunk expires after 5 minutes.export const AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS = 300; // 5 minutes-// A page of session logs has 1,000 records by default, and the caller can ask for up to 5,000. A page can end-// sooner if it reaches 200 chunks or 16 MiB, and the next page picks up where it stopped. A live tail reads the-// last 2 minutes again each time, so a chunk that a proxy uploaded late still shows up.-export const AGENT_VAULT_SESSION_LOG_DEFAULT_PAGE_RECORDS = 1000;-export const AGENT_VAULT_SESSION_LOG_MAX_PAGE_RECORDS = 5000;+// Reading a session's logs (the logs panel, or GET .../logs) returns them a page at a time. For each page,+// Infisical lists the session's folder in S3 once and adds chunks until the page holds 48 KiB of them (about 200+// requests) or 200 chunks, but always at least one. The browser then downloads every chunk on the page, so a small+// page keeps opening the logs fast and cheap. The next page continues after the last file this one read.export const AGENT_VAULT_SESSION_LOG_MAX_PAGE_CHUNKS = 200;-export const AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES = 16 * 1024 * 1024; // 16 MiB of ciphertext-export const AGENT_VAULT_SESSION_LOG_RECEIVE_OVERLAP_MS = 2 * 60_000; // 2 minutes+export const AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES = 48 * 1024; // 48 KiB of ciphertext++// When someone reads logs for a date range, Infisical has to find the chunks holding requests from it. A chunk's+// file name carries the time of its last request, and the proxy never puts requests more than 10 minutes apart in one+// chunk. So the listing starts 11 minutes past the end of the range, and stops at the first chunk whose last request+// is before its start. Infisical refuses a chunk whose id time doesn't match its endedAt to within a second.+export const AGENT_VAULT_SESSION_LOG_RANGE_MARGIN_MS = 11 * 60_000; // 11 minutes+export const AGENT_VAULT_SESSION_LOG_CHUNK_ID_TIME_TOLERANCE_MS = 1_000;++// The live view (new requests appearing while the logs panel is open) doesn't list S3. Each time a proxy asks for+// an upload link, Infisical adds the chunk's file name to a small Redis list for that session, and the panel reads+// the names added since its last check. The list keeps the newest 10 names and is deleted 2 minutes after the last+// one was added. When the panel may have missed names that dropped off, it reads the newest page of history instead.+export const AGENT_VAULT_SESSION_LOG_FEED_MAX_ENTRIES = 10;+export const AGENT_VAULT_SESSION_LOG_FEED_TTL_SECONDS = 120; // 2 minutes++// What everyone but an Agent Vault admin sees when Infisical can't read the bucket: the first when AWS isn't answering,+// the second when an admin has to fix the settings or the AWS side. The admin message names the cause, which can+// 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.";+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.";diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-enums.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-enums.tsindex d470dc07b2..2dbc46ba9e 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-enums.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-enums.ts@@ -1,11 +1,8 @@-export enum AgentVaultSessionLogStorageUnavailableReason {- NoConnection = "no-connection",- ConnectionUnusable = "connection-unusable"-}+// The error name a session log read fails with when Infisical can't read the bucket. API callers switch on it.+export const AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE = "AgentVaultSessionLogStorageUnavailable";// Wire contract: the Go proxy (cli/packages/agentvault/session_log.go) switches on these APIError.Name values.export enum AgentVaultSessionLogErrorName {- CeilingReached = "AgentVaultSessionLogCeilingReached",Disabled = "AgentVaultSessionLogDisabled",ClockSkew = "AgentVaultSessionLogClockSkew"}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 868efce574..d98beaabf1 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,40 +1,72 @@+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 {+ buildSessionLogFolder,buildSessionLogObjectKey,+ chunkIdTimeMs,+ describeListFailure,getSessionLogEntitlement,+ parseSessionLogObjectKey,resolveStorageConfig,+ toRev,TSessionLogLicenseService} from "./agent-vault-session-log-fns";vi.mock("@app/lib/logger", () => ({ logger: { warn: () => {} } }));-describe("buildSessionLogObjectKey", () => {- const base = {- projectId: "proj-1",- sessionId: "sess-1",- proxyId: "proxy-1",- startedAt: new Date("2026-09-16T10:31:04.221Z"),- chunkId: "01a0a9c5-231d-7abc-8def-0123456789ab"- };+describe("session log object names", () => {+ const projectId = "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, proxy, date and chunk", () => {- expect(buildSessionLogObjectKey({ ...base, keyPrefix: "logs" })).toBe(- "logs/proj-1/sess-1/proxy-1/2026-09-16/01a0a9c5-231d-7abc-8def-0123456789ab.json.enc"+ 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`);});test("omits the prefix segment entirely when there is no prefix", () => {- expect(buildSessionLogObjectKey({ ...base, keyPrefix: null })).toBe(- "proj-1/sess-1/proxy-1/2026-09-16/01a0a9c5-231d-7abc-8def-0123456789ab.json.enc"- );+ expect(buildSessionLogFolder({ keyPrefix: null, projectId, sessionId })).toBe(`${projectId}/${sessionId}/`);+ });++ test("reads the time out of the chunk id", () => {+ expect(chunkIdTimeMs(chunkId)).toBe(1791305882000);+ });++ test("a newer chunk sorts first, which is the only order S3 lists in", () => {+ expect(toRev(2_000) < toRev(1_000)).toBe(true);+ expect(toRev(1_000)).toHaveLength(13);+ });++ test("clamps a time outside what 13 digits can hold", () => {+ expect(toRev(-5)).toBe("9999999999999");+ expect(toRev(1e14)).toBe("0000000000000");+ });++ test("parses a name it built", () => {+ expect(parseSessionLogObjectKey(folder, buildSessionLogObjectKey({ folder, proxyId, chunkId }))).toEqual({+ chunkId,+ proxyId,+ lastRecordAt: new Date(1791305882000)+ });});- test("dates by UTC, so a chunk near midnight does not land in the reader's day", () => {- const key = buildSessionLogObjectKey({ ...base, startedAt: new Date("2026-09-16T23:59:59.999Z") });- expect(key).toContain("/2026-09-16/");+ test.each([+ {+ why: "another session's folder",+ key: `agent-vault-1/${projectId}/other/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` },+ { why: "a proxy that is not a uuid", key: `${folder}8208694117999_${chunkId}.proxy-1.json.enc` },+ { why: "a file someone else put there", key: `${folder}notes.txt` }+ ])("skips $why", ({ key }) => {+ expect(parseSessionLogObjectKey(folder, key)).toBeNull();});});@@ -104,3 +136,64 @@ describe("getSessionLogEntitlement", () => {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 6da3edcce6..a37e38953e 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,3 +1,4 @@+import RE2 from "re2";import { z } from "zod";import { TAgentVaultSessionLogConfigs } from "@app/db/schemas";@@ -6,7 +7,7 @@ import { logger } from "@app/lib/logger";import { AWSRegion } from "@app/services/app-connection/app-connection-enums";import {- AGENT_VAULT_SESSION_LOG_CHUNK_ID_REGEX,+ 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";@@ -14,23 +15,47 @@ import { TResolvedSessionLogStorageConfig } from "./agent-vault-session-log-typeexport const withKeyPrefix = (keyPrefix: string | null | undefined, key: string) =>keyPrefix ? `${keyPrefix}/${key}` : key;-export const buildSessionLogObjectKey = ({+const MAX_REV = 9_999_999_999_999;++export const chunkIdTimeMs = (chunkId: string) => parseInt(chunkId.slice(0, 8) + chunkId.slice(9, 13), 16);++// 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,- proxyId,- startedAt,- chunkId+ sessionId}: {keyPrefix?: string | null;projectId: string;sessionId: string;+}) => withKeyPrefix(keyPrefix, `${projectId}/${sessionId}/`);++export const buildSessionLogObjectKey = ({+ folder,+ proxyId,+ chunkId+}: {+ folder: string;proxyId: string;- startedAt: Date;chunkId: string;-}) => {- const day = startedAt.toISOString().slice(0, 10);- return withKeyPrefix(keyPrefix, `${projectId}/${sessionId}/${proxyId}/${day}/${chunkId}.json.enc`);+}) => `${folder}${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(+ `^(\\d{13})_(${AGENT_VAULT_SESSION_LOG_CHUNK_ID_PATTERN})\\.(${UUID_PATTERN})\\.json\\.enc$`+);++// Anything else in the folder is skipped: only Infisical names objects there, through the links it signs.+export const parseSessionLogObjectKey = (folder: string, key: string) => {+ if (!key.startsWith(folder)) return null;+ const match = SESSION_LOG_OBJECT_NAME_REGEX.exec(key.slice(folder.length));+ if (!match) return null;+ const [, rev, chunkId, proxyId] = match;+ const lastRecordAtMs = chunkIdTimeMs(chunkId);+ if (rev !== toRev(lastRecordAtMs)) return null;+ return { chunkId, proxyId, lastRecordAt: new Date(lastRecordAtMs) };};export const resolveStorageConfig = (@@ -45,6 +70,64 @@ export const resolveStorageConfig = (};};+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));@@ -83,19 +166,22 @@ export const getSessionLogEntitlement = async (return entitlement;};-const CURSOR_VERSION = 1;-const MAX_CURSOR_LENGTH = 256;+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"),- id: z.string().regex(AGENT_VAULT_SESSION_LOG_CHUNK_ID_REGEX)+ after: z.string().min(1).max(1024)});const TailCursorPayloadSchema = z.object({v: z.literal(CURSOR_VERSION),m: z.literal("t"),- at: z.string().datetime()+ id: z.string().regex(new RE2(/^\d{1,16}-\d{1,16}$/))});const encode = (payload: object) => Buffer.from(JSON.stringify(payload)).toString("base64url");@@ -108,9 +194,10 @@ const decode = (cursor: string): unknown => {}};-export const encodeHistoryCursor = (chunkId: string) => encode({ v: CURSOR_VERSION, m: "h", id: chunkId });+// 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 = (at: Date) => encode({ v: CURSOR_VERSION, m: "t", at: at.toISOString() });+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;@@ -132,7 +219,7 @@ export const HistoryCursorSchema = z});return z.NEVER;}- return parsed.data.id;+ return parsed.data.after;});export const TailCursorSchema = z@@ -148,9 +235,9 @@ export const TailCursorSchema = zmessage:modeOf(payload) === "h"? "This cursor is for paging back through logs. Pass it to the session logs endpoint instead"- : "Invalid cursor. Pass the liveCursor or nextCursor of a previous response unchanged"+ : "Invalid cursor. Pass the nextCursor of a previous response unchanged"});return z.NEVER;}- return new Date(parsed.data.at);+ return parsed.data.id;});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 1f0a84360a..23ad045d3c 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@@ -2,7 +2,6 @@ import { describe, expect, test } from "vitest";import {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 { encodeHistoryCursor, encodeTailCursor } from "./agent-vault-session-log-fns";@@ -15,21 +14,15 @@ import {const validChunk = {chunkId: "01a0a9c5-231d-7abc-8def-0123456789ab",- startedAt: "2026-09-16T10:30:00.000Z",endedAt: "2026-09-16T10:31:00.000Z",- firstSeq: 0,- lastSeq: 41,- recordCount: 42,- droppedCount: 0,ciphertextBytes: 4096,- iv: "qrvM3e7/ABEiM0RV",ciphertextSha256: "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU"};describe("the chunk create body", () => {- test("accepts a well-formed chunk and coerces the timestamps to dates", () => {+ test("accepts a well-formed chunk and coerces the timestamp to a date", () => {const parsed = AgentVaultSessionLogChunkCreateSchema.parse(validChunk);- expect(parsed.startedAt).toBeInstanceOf(Date);+ expect(parsed.endedAt).toBeInstanceOf(Date);expect(parsed.endedAt.toISOString()).toBe("2026-09-16T10:31:00.000Z");});@@ -39,24 +32,14 @@ describe("the chunk create body", () => {{field: "chunkId",value: "01A0A9C5-231D-7ABC-8DEF-0123456789AB",- why: "Postgres returns lowercase, so an uppercase id would never decrypt"+ why: "the browser rebuilds the AAD from the lowercase id in the object name"},- { field: "recordCount", value: 0, why: "an empty chunk is never worth a row" },- { field: "recordCount", value: AGENT_VAULT_SESSION_LOG_MAX_CHUNK_RECORDS + 1, why: "over the slice size" },- { field: "recordCount", value: 1.5, why: "not an integer" },- { field: "droppedCount", value: -1, why: "negative" },- { field: "firstSeq", value: -1, why: "sequence numbers start at zero" },- { field: "lastSeq", value: Number.MAX_SAFE_INTEGER + 2, why: "past what reads back from bigint exactly" },- { field: "droppedCount", value: 1e19, why: "past what the bigint column holds" },{field: "ciphertextBytes",value: AGENT_VAULT_SESSION_LOG_MIN_CHUNK_BYTES - 1,- why: "smaller than '[]' plus a tag"+ why: "smaller than an IV, '[]' and a tag"},{ field: "ciphertextBytes", value: AGENT_VAULT_SESSION_LOG_MAX_CHUNK_BYTES + 1, why: "over the size ceiling" },- { field: "iv", value: "qrvM3e7/ABEiM0RV=", why: "padded base64 is the wrong width" },- { field: "iv", value: "qrvM3e7/ABEiM0R", why: "15 characters is not 12 bytes" },- { field: "iv", value: "qrvM3e7-ABEiM0RV", why: "url-safe base64 is a different alphabet" },{field: "ciphertextSha256",value: "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",@@ -77,67 +60,61 @@ describe("the chunk create body", () => {expect(AgentVaultSessionLogChunkCreateSchema.safeParse({ ...validChunk, [field]: value }).success).toBe(false);});- test("rejects a body carrying anything the contract does not name", () => {+ test("drops a field the contract does not name, so a caller can't choose the object key", () => {const parsed = AgentVaultSessionLogChunkCreateSchema.parse({ ...validChunk, objectKey: "attacker/controlled" });expect(parsed).not.toHaveProperty("objectKey");});});describe("the session logs history query", () => {- test("defaults to 1000 records and no cursor", () => {- expect(AgentVaultSessionLogHistoryQuerySchema.parse({})).toEqual({ limit: 1000, cursor: undefined });+ test("accepts a history query with no cursor", () => {+ expect(AgentVaultSessionLogHistoryQuerySchema.parse({})).toEqual({ cursor: undefined });});- test("coerces a querystring limit, which always arrives as a string", () => {- expect(AgentVaultSessionLogHistoryQuerySchema.parse({ limit: "25" }).limit).toBe(25);- });-- test.each([0, 5001, -1])("rejects a limit of %s", (limit) => {- expect(AgentVaultSessionLogHistoryQuerySchema.safeParse({ limit }).success).toBe(false);- });-- test("reads a cursor back as the chunk to page before", () => {- const cursor = encodeHistoryCursor("01a0a9c5-231d-7abc-8def-0123456789ab");- expect(AgentVaultSessionLogHistoryQuerySchema.parse({ cursor }).cursor).toBe(- "01a0a9c5-231d-7abc-8def-0123456789ab"- );+ test("reads a cursor back as the name to continue after", () => {+ const after = "8208694117999_01a11226-9990-7a3f-8c21-4e6f9b2d1a07.e91f3c20-7d4b-4a8e-9f1c-3b5d7e2a6c48.json.enc";+ expect(AgentVaultSessionLogHistoryQuerySchema.parse({ cursor: encodeHistoryCursor(after) }).cursor).toBe(after);});test.each(["yesterday",- Buffer.from('{"v":1,"m":"h","id":"not-a-uuid"}').toString("base64url"),- Buffer.from('{"v":1,"m":"h","id":"3f2b8c1e-9d4a-4e6b-a1c7-5f0e2d9b8a64"}').toString("base64url")+ Buffer.from('{"v":1,"m":"h","id":"01a0a9c5-231d-7abc-8def-0123456789ab"}').toString("base64url"),+ Buffer.from('{"v":2,"m":"h","after":""}').toString("base64url"),+ Buffer.from(JSON.stringify({ v: 2, m: "h", after: "x".repeat(1025) })).toString("base64url")])("rejects a cursor it did not issue: %s", (cursor) => {expect(AgentVaultSessionLogHistoryQuerySchema.safeParse({ cursor }).success).toBe(false);});test("says where a tail cursor belongs", () => {- const result = AgentVaultSessionLogHistoryQuerySchema.safeParse({ cursor: encodeTailCursor(new Date()) });+ const result = AgentVaultSessionLogHistoryQuerySchema.safeParse({ cursor: encodeTailCursor("1791278402731-0") });expect(result.success).toBe(false);expect(result.error?.issues[0].message).toMatch(/session logs tail endpoint/);});});describe("the session logs tail query", () => {- test("starts from now when no cursor is given", () => {- expect(AgentVaultSessionLogTailQuerySchema.parse({})).toEqual({ limit: 1000, cursor: undefined });+ test("accepts a tail query with no cursor", () => {+ expect(AgentVaultSessionLogTailQuerySchema.parse({})).toEqual({ cursor: undefined });});- test("reads a cursor back as the time to continue from", () => {- const at = new Date("2026-09-25T10:00:00.123Z");- expect(AgentVaultSessionLogTailQuerySchema.parse({ cursor: encodeTailCursor(at) }).cursor).toEqual(at);+ test("reads a cursor back as the feed entry to continue after", () => {+ expect(AgentVaultSessionLogTailQuerySchema.parse({ cursor: encodeTailCursor("1791278402731-3") }).cursor).toBe(+ "1791278402731-3"+ );});- test.each(["yesterday", Buffer.from('{"v":1,"m":"t","at":"soon"}').toString("base64url")])(- "rejects a cursor it did not issue: %s",- (cursor) => {- expect(AgentVaultSessionLogTailQuerySchema.safeParse({ cursor }).success).toBe(false);- }- );+ test.each([+ "yesterday",+ Buffer.from('{"v":1,"m":"t","at":"2026-09-25T10:00:00.123Z"}').toString("base64url"),+ Buffer.from('{"v":2,"m":"t","id":"1791278402731"}').toString("base64url"),+ Buffer.from('{"v":2,"m":"t","id":"99999999999999999-0"}').toString("base64url")+ ])("rejects a cursor it did not issue: %s", (cursor) => {+ expect(AgentVaultSessionLogTailQuerySchema.safeParse({ cursor }).success).toBe(false);+ });test("says where a history cursor belongs", () => {const result = AgentVaultSessionLogTailQuerySchema.safeParse({- cursor: encodeHistoryCursor("01a0a9c5-231d-7abc-8def-0123456789ab")+ cursor: encodeHistoryCursor("8208694117999_01a11226-9990-7a3f-8c21-4e6f9b2d1a07")});expect(result.success).toBe(false);expect(result.error?.issues[0].message).toMatch(/session logs endpoint instead/);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 40c75c59df..d1f1fb394f 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@@ -5,23 +5,14 @@ import { AWSRegion } from "@app/services/app-connection/app-connection-enums";import {AGENT_VAULT_SESSION_LOG_CHUNK_ID_REGEX,- AGENT_VAULT_SESSION_LOG_DEFAULT_PAGE_RECORDS,AGENT_VAULT_SESSION_LOG_MAX_CHUNK_BYTES,- AGENT_VAULT_SESSION_LOG_MAX_CHUNK_RECORDS,- AGENT_VAULT_SESSION_LOG_MAX_PAGE_RECORDS,AGENT_VAULT_SESSION_LOG_MIN_CHUNK_BYTES} from "./agent-vault-session-log-constants";-import { AgentVaultSessionLogStorageUnavailableReason } from "./agent-vault-session-log-enums";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";-const IvSchema = z- .string()- .regex(/^[A-Za-z0-9+/]{16}$/, "Must be 12 bytes of unpadded base64")- .describe(AGENT_VAULT.SESSION_LOGS.iv);-const CiphertextSha256Schema = z.string().regex(/^[A-Za-z0-9+/]{43}$/, "Must be a SHA-256 digest as unpadded base64")@@ -32,25 +23,15 @@ export const AgentVaultSessionLogChunkCreateSchema = z.object({.string().regex(AGENT_VAULT_SESSION_LOG_CHUNK_ID_REGEX, "Must be a lowercase UUIDv7").describe(AGENT_VAULT.SESSION_LOGS.chunkId),- startedAt: z.coerce.date().describe(AGENT_VAULT.SESSION_LOGS.startedAt),endedAt: z.coerce.date().describe(AGENT_VAULT.SESSION_LOGS.endedAt),- firstSeq: z.number().int().min(0).safe().describe(AGENT_VAULT.SESSION_LOGS.firstSeq),- lastSeq: z.number().int().min(0).safe().describe(AGENT_VAULT.SESSION_LOGS.lastSeq),- recordCount: z- .number()- .int()- .min(1)- .max(AGENT_VAULT_SESSION_LOG_MAX_CHUNK_RECORDS)- .describe(AGENT_VAULT.SESSION_LOGS.recordCount),- droppedCount: z.number().int().min(0).safe().describe(AGENT_VAULT.SESSION_LOGS.droppedCount),ciphertextBytes: z.number().int().min(AGENT_VAULT_SESSION_LOG_MIN_CHUNK_BYTES).max(AGENT_VAULT_SESSION_LOG_MAX_CHUNK_BYTES).describe(AGENT_VAULT.SESSION_LOGS.ciphertextBytes),- iv: IvSchema,- ciphertextSha256: CiphertextSha256Schema+ ciphertextSha256: CiphertextSha256Schema,+ iv: z.string().max(64).optional().describe(AGENT_VAULT.SESSION_LOGS.legacyIv)});export const AgentVaultSessionLogChunkCreateResponseSchema = z.object({@@ -59,72 +40,41 @@ export const AgentVaultSessionLogChunkCreateResponseSchema = z.object({expiresInSeconds: z.number().describe(AGENT_VAULT.SESSION_LOGS.expiresInSeconds)});-const SessionLogLimitSchema = z.coerce- .number()- .int()- .min(1)- .max(AGENT_VAULT_SESSION_LOG_MAX_PAGE_RECORDS)- .default(AGENT_VAULT_SESSION_LOG_DEFAULT_PAGE_RECORDS)- .describe(AGENT_VAULT.SESSION_LOGS.limit);-export const AgentVaultSessionLogHistoryQuerySchema = z.object({- limit: SessionLogLimitSchema,cursor: HistoryCursorSchema.optional().describe(AGENT_VAULT.SESSION_LOGS.historyCursor),from: z.coerce.date().optional().describe(AGENT_VAULT.SESSION_LOGS.from),to: z.coerce.date().optional().describe(AGENT_VAULT.SESSION_LOGS.to)});export const AgentVaultSessionLogTailQuerySchema = z.object({- limit: SessionLogLimitSchema,cursor: TailCursorSchema.optional().describe(AGENT_VAULT.SESSION_LOGS.tailCursor)});export const AgentVaultSessionLogChunkViewSchema = z.object({chunkId: z.string().describe(AGENT_VAULT.SESSION_LOGS.chunkId),proxyId: z.string().describe(AGENT_VAULT.SESSION_LOGS.proxyId),- proxyName: z.string().describe(AGENT_VAULT.SESSION_LOGS.proxyName),- startedAt: z.date().describe(AGENT_VAULT.SESSION_LOGS.startedAt),- endedAt: z.date().describe(AGENT_VAULT.SESSION_LOGS.endedAt),- firstSeq: z.number().describe(AGENT_VAULT.SESSION_LOGS.firstSeq),- lastSeq: z.number().describe(AGENT_VAULT.SESSION_LOGS.lastSeq),- recordCount: z.number().describe(AGENT_VAULT.SESSION_LOGS.recordCount),- droppedCount: z.number().describe(AGENT_VAULT.SESSION_LOGS.droppedCount),ciphertextBytes: z.number().describe(AGENT_VAULT.SESSION_LOGS.ciphertextBytes),- iv: z.string().describe(AGENT_VAULT.SESSION_LOGS.iv),- ciphertextSha256: z.string().describe(AGENT_VAULT.SESSION_LOGS.ciphertextSha256),- presignedGetUrl: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.presignedGetUrl),- createdAt: z.date().describe(AGENT_VAULT.SESSION_LOGS.chunkCreatedAt)+ presignedGetUrl: z.string().describe(AGENT_VAULT.SESSION_LOGS.presignedGetUrl)});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),- storageUnavailable: z- .object({- reason: z- .nativeEnum(AgentVaultSessionLogStorageUnavailableReason)- .describe(AGENT_VAULT.SESSION_LOGS.storageUnavailableReason),- message: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.storageUnavailableMessage)- })- .nullable()- .describe(AGENT_VAULT.SESSION_LOGS.storageUnavailable)+ sessionKey: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.sessionKey)}).describe(AGENT_VAULT.SESSION_LOGS.sessionLogs);export const AgentVaultSessionLogHistoryResponseSchema = z.object({sessionLogs: AgentVaultSessionLogSchema,chunks: AgentVaultSessionLogChunkViewSchema.array(),- nextCursor: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.historyNextCursor),- liveCursor: z.string().describe(AGENT_VAULT.SESSION_LOGS.liveCursor)+ nextCursor: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.historyNextCursor)});export const AgentVaultSessionLogTailResponseSchema = z.object({sessionLogs: AgentVaultSessionLogSchema,chunks: AgentVaultSessionLogChunkViewSchema.array(),- nextCursor: z.string().describe(AGENT_VAULT.SESSION_LOGS.tailNextCursor),- hasMore: z.boolean().describe(AGENT_VAULT.SESSION_LOGS.tailHasMore)+ nextCursor: z.string().describe(AGENT_VAULT.SESSION_LOGS.tailNextCursor)});export const AgentVaultSessionLogSettingsSchema = z.object({@@ -141,7 +91,6 @@ export const AgentVaultSessionLogSettingsResponseSchema = z.object({export const AgentVaultSessionLogHealthResponseSchema = z.object({health: z.object({- isStorageFull: z.boolean().describe(AGENT_VAULT.SESSION_LOGS.isStorageFull),connectionError: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.connectionError)})});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 cb74fbfef1..6d6e811074 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@@ -1,37 +1,65 @@+import { S3ServiceException } from "@aws-sdk/client-s3";import { createMongoAbility } from "@casl/ability";+import { v7 as uuidv7 } from "uuid";import { beforeEach, describe, expect, test, vi } from "vitest";-import { BadRequestError, DatabaseError } from "@app/lib/errors";+import { BadRequestError, DatabaseError, InternalServerError } from "@app/lib/errors";import {- AGENT_VAULT_SESSION_LOG_MAX_STORED_CHUNKS,+ 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} from "./agent-vault-session-log-constants";-import { AgentVaultSessionLogErrorName } from "./agent-vault-session-log-enums";-import { buildSessionLogObjectKey, encodeTailCursor } from "./agent-vault-session-log-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 { 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";-const CEILING = AGENT_VAULT_SESSION_LOG_MAX_STORED_CHUNKS;+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 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 assertReachable = vi.fn(async () => {});vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));+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 () => ({presignPut,- presignGet: vi.fn(async () => "https://bucket.s3.amazonaws.com/signed-get"),+ presignGet,+ listChunks,+ assertReachable,mintCorsProbeUrl: vi.fn(async () => "https://bucket.s3.amazonaws.com/probe"),validate: vi.fn(async () => {})}))};});-const PROXY = { id: "proxy-1", name: "proxy-one", projectId: "proj-1", orgId: "org-1" };+const PROXY = { id: PROXY_ID, name: "proxy-one", projectId: PROJECT_ID, orgId: "org-1" };const liveSession = () => ({- id: "sess-1",- projectId: "proj-1",+ id: SESSION_ID,+ projectId: PROJECT_ID,userId: "user-1",identityId: null,expiresAt: null,@@ -42,39 +70,37 @@ const liveSession = () => ({const enabledConfig = () => ({id: "cfg-1",- projectId: "proj-1",+ projectId: PROJECT_ID,enabled: true,appConnectionId: "conn-1",bucket: "my-bucket",region: "us-east-1",- keyPrefix: "logs",- storedChunkCount: 0+ keyPrefix: "logs"});-const validChunk = () => ({- chunkId: "01a0a9c5-231d-7abc-8def-0123456789ab",- startedAt: new Date(Date.now() - 60_000),- endedAt: new Date(Date.now() - 1_000),- firstSeq: 0,- lastSeq: 41,- recordCount: 42,- droppedCount: 0,+// 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() }),+ endedAt,ciphertextBytes: 4096,- iv: "qrvM3e7/ABEiM0RV",ciphertextSha256: "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU"});+const objectFor = (lastRecordAtMs: number, proxyId = PROXY_ID) => {+ const chunkId = uuidv7({ msecs: lastRecordAtMs });+ return { chunkId, key: buildSessionLogObjectKey({ folder: FOLDER, proxyId, chunkId }) };+};++type TFeedEntry = [string, string[]];+type TOverrides = {proxy?: unknown;session?: unknown;config?: unknown;- storedAfterIncrement?: number;- createThrows?: unknown;- isReplay?: boolean;- existingChunk?: unknown;- destinationChanged?: boolean;- pageRows?: unknown[];- proxies?: unknown[];+ feed?: TFeedEntry[];+ feedAddFails?: boolean;+ feedAddHangs?: boolean;+ isAdmin?: boolean;connection?: unknown;configCreateThrows?: unknown;licensed?: boolean;@@ -83,22 +109,6 @@ type TOverrides = {};const build = (overrides: TOverrides = {}) => {- const created = { ...validChunk(), objectKey: "logs/proj-1/sess-1/proxy-1/2026-09-16/chunk.json.enc" };-- const createIfAbsent = vi.fn(async (values: Record<string, unknown>) => {- if (overrides.createThrows) return Promise.reject(overrides.createThrows);- if (overrides.isReplay) return undefined;- return { ...created, ...values };- });- const recordStoredChunk = vi.fn(async () => overrides.storedAfterIncrement ?? 42);- const findChunk = vi.fn(async () =>- overrides.existingChunk ? { proxyId: PROXY.id, ...(overrides.existingChunk as object) } : null- );- const moveChunk = vi.fn(async (values: Record<string, unknown>) =>- overrides.destinationChanged- ? undefined- : { ...(overrides.existingChunk as object), bucket: values.bucket, objectKey: values.objectKey }- );const validateConnection = vi.fn(async () => ({}));const findConnection = vi.fn(async () => overrides.connection);const config = "config" in overrides ? overrides.config : enabledConfig();@@ -106,20 +116,17 @@ const build = (overrides: TOverrides = {}) => {...(config as object),...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";+ });+ const findSession = vi.fn(async () => ("session" in overrides ? overrides.session : liveSession()));+ const streamRange = vi.fn(async () => overrides.feed ?? []);const service = agentVaultSessionLogServiceFactory({- agentVaultSessionLogChunkDAL: {- createIfAbsent,- findOne: findChunk,- moveToDestinationIfCurrent: moveChunk,- transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) => cb({})),- findForSessionPage: vi.fn(async () => ({ chunks: overrides.pageRows ?? [], hasMore: false })),- findReceivedForSession: vi.fn(async () => ({ chunks: overrides.pageRows ?? [], hasMore: false }))- } as never,agentVaultSessionLogConfigDAL: {findOne: vi.fn(async () => config),findByProjectIdFromPrimary: vi.fn(async () => config),- recordStoredChunk,updateById: updateConfig,create: vi.fn(async (values: Record<string, unknown>) => {if (overrides.configCreateThrows) return Promise.reject(overrides.configCreateThrows);@@ -127,18 +134,17 @@ const build = (overrides: TOverrides = {}) => {})} as never,agentVaultSessionDAL: {- findOne: vi.fn(async () => ("session" in overrides ? overrides.session : liveSession()))+ findOne: findSession} as never,agentVaultProxyDAL: {- findByIdWithOrg: vi.fn(async () => ("proxy" in overrides ? overrides.proxy : PROXY)),- find: vi.fn(async () => overrides.proxies ?? [PROXY])+ findByIdWithOrg: vi.fn(async () => ("proxy" in overrides ? overrides.proxy : PROXY))} as never,appConnectionDAL: { findById: findConnection } as never,appConnectionService: { validateAppConnectionUsageById: validateConnection } as never,permissionService: {getProjectPermission: vi.fn(async () => ({permission: createMongoAbility([{ action: "read", subject: "agent-vault-sessions" }]),- hasRole: () => true+ hasRole: () => overrides.isAdmin ?? true}))} as never,kmsService: { createCipherPairWithDataKey: vi.fn() } as never,@@ -146,57 +152,52 @@ const build = (overrides: TOverrides = {}) => {getPlan: vi.fn(async () => ({ agentVaultByoS3: overrides.licensed ?? true })),isServingFallbackPlan: vi.fn(async () => overrides.planFallback ?? false),getLastKnownPlan: vi.fn(async () => overrides.lastKnownPlan ?? null)- } as never+ } as never,+ keyStore: { streamAdd, streamRange } as never});- return {- service,- createIfAbsent,- recordStoredChunk,- findChunk,- moveChunk,- validateConnection,- findConnection,- updateConfig- };+ return { service, validateConnection, findConnection, updateConfig, streamAdd, streamRange, findSession };};-const record = (service: ReturnType<typeof build>["service"], chunk = validChunk()) =>- service.recordChunk({ proxyId: PROXY.id, sessionId: "sess-1", chunk });+const record = (+ service: ReturnType<typeof build>["service"],+ chunk: TCreateChunkUploadUrlDTO["chunk"] = validChunk()+) => service.createChunkUploadUrl({ proxyId: PROXY_ID, sessionId: SESSION_ID, chunk });-const atCurrentDestination = (chunk: ReturnType<typeof validChunk>) => ({- ...chunk,- bucket: "my-bucket",- objectKey: buildSessionLogObjectKey({- keyPrefix: "logs",- projectId: "proj-1",- sessionId: "sess-1",- proxyId: PROXY.id,- startedAt: chunk.startedAt,- chunkId: chunk.chunkId- })-});+const scope = {+ projectId: PROJECT_ID,+ ctx: { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never,+ sessionId: SESSION_ID+};beforeEach(() => {vi.clearAllMocks();+ listChunks.mockResolvedValue({ objects: [], isTruncated: false });});-describe("recordChunk: who is allowed to write", () => {- test("a happy path writes the row, counts the chunk and returns an upload url", async () => {- const { service, createIfAbsent, recordStoredChunk } = build();- const result = await record(service);+describe("createChunkUploadUrl: who is allowed to write", () => {+ test("a happy path signs the chunk's name and adds it to the live feed", async () => {+ const { service, streamAdd } = build();+ const chunk = validChunk();+ const result = await record(service, chunk);expect(result.uploadUrl).toBe("https://bucket.s3.amazonaws.com/signed-put");- expect(result.chunkId).toBe("01a0a9c5-231d-7abc-8def-0123456789ab");- expect(recordStoredChunk).toHaveBeenCalledWith("cfg-1", expect.anything());+ expect(result.chunkId).toBe(chunk.chunkId);- const values = createIfAbsent.mock.calls[0][0];- expect(String(values.objectKey)).toMatch(- /^logs\/proj-1\/sess-1\/proxy-1\/\d{4}-\d{2}-\d{2}\/01a0a9c5-231d-7abc-8def-0123456789ab\.json\.enc$/+ const objectKey = buildSessionLogObjectKey({ folder: FOLDER, proxyId: PROXY_ID, chunkId: chunk.chunkId });+ expect(presignPut).toHaveBeenCalledWith({+ objectKey,+ ciphertextBytes: 4096,+ ciphertextSha256: chunk.ciphertextSha256+ });+ expect(streamAdd).toHaveBeenCalledWith(+ `agent-vault-session-log-feed:${SESSION_ID}`,+ "*",+ { key: objectKey, bucket: "my-bucket", bytes: "4096" },+ 10,+ 120,+ true);- expect(values.bucket).toBe("my-bucket");- expect(values.proxyName).toBe("proxy-one");- expect(values.projectId).toBe("proj-1");});test("an unknown proxy is a 404 that says nothing about the session", async () => {@@ -204,13 +205,14 @@ describe("recordChunk: who is allowed to write", () => {await expect(record(service)).rejects.toMatchObject({ message: "Session not found" });});- test("a session in another project reads exactly like a missing one", async () => {- const { service } = build({ session: undefined });+ test("looks the session up in the proxy's own project, so another project's session reads as missing", async () => {+ const { service, findSession } = build({ session: undefined });await expect(record(service)).rejects.toMatchObject({ message: "Session not found" });+ expect(findSession).toHaveBeenCalledWith({ id: SESSION_ID, projectId: PROJECT_ID });});});-describe("recordChunk: the retirement grace window", () => {+describe("createChunkUploadUrl: the retirement grace window", () => {const hoursAgo = (h: number) => new Date(Date.now() - h * 60 * 60 * 1000);test.each([@@ -219,7 +221,7 @@ describe("recordChunk: the retirement grace window", () => {{ why: "revoked 23 hours ago", session: { revokedAt: hoursAgo(23), expiresAt: null } }])("still accepts a chunk from a session $why", async ({ session }) => {const { service } = build({ session: { ...liveSession(), ...session } });- await expect(record(service)).resolves.toMatchObject({ chunkId: "01a0a9c5-231d-7abc-8def-0123456789ab" });+ await expect(record(service)).resolves.toHaveProperty("uploadUrl");});test.each([@@ -245,7 +247,7 @@ describe("recordChunk: the retirement grace window", () => {const { service } = build({session: { ...liveSession(), userId: null, identityId: null, updatedAt: hoursAgo(23) }});- await expect(record(service)).resolves.toMatchObject({ chunkId: "01a0a9c5-231d-7abc-8def-0123456789ab" });+ await expect(record(service)).resolves.toHaveProperty("uploadUrl");});test("a session whose owner was deleted more than a day ago is refused", async () => {@@ -256,291 +258,411 @@ describe("recordChunk: the retirement grace window", () => {message: "Session ended too long ago to accept session logs"});});-- test("an expiry in the future is not retirement", async () => {- const { service } = build({- session: { ...liveSession(), expiresAt: new Date(Date.now() + 60 * 60 * 1000) }- });- await expect(record(service)).resolves.toBeTruthy();- });});-describe("recordChunk: when session logs are off", () => {+describe("createChunkUploadUrl: when session logs are off", () => {test.each([{ why: "there is no config row", 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 } }])("refuses with the named error when $why", async ({ config }) => {- const { service, createIfAbsent } = build({ config });+ const { service } = build({ config });await expect(record(service)).rejects.toMatchObject({ name: AgentVaultSessionLogErrorName.Disabled });- expect(createIfAbsent).not.toHaveBeenCalled();+ expect(presignPut).not.toHaveBeenCalled();});});-describe("recordChunk: semantic validation", () => {- test.each([- {- why: "startedAt is after endedAt",- patch: { startedAt: new Date(Date.now()), endedAt: new Date(Date.now() - 60_000) },- message: "Chunk startedAt is after its endedAt"- },- {- why: "the chunk is older than the maximum age",- patch: {- startedAt: new Date(Date.now() - 31 * 24 * 60 * 60 * 1000),- endedAt: new Date(Date.now() - 31 * 24 * 60 * 60 * 1000)- },- message: "Chunk is older than the maximum accepted age"- },- {- why: "firstSeq exceeds lastSeq",- patch: { firstSeq: 50, lastSeq: 10 },- message: "Chunk firstSeq is greater than its lastSeq"- },- {- why: "more records than the sequence range can hold",- patch: { firstSeq: 0, lastSeq: 5, recordCount: 42 },- message: "Chunk holds more records than its sequence range allows"- }- ])("rejects when $why", async ({ patch, message }) => {- const { service, createIfAbsent } = build();- await expect(record(service, { ...validChunk(), ...patch })).rejects.toMatchObject({ message });- expect(createIfAbsent).not.toHaveBeenCalled();- });-- test("a chunk whose range is larger than its count is fine, since the ring drops records", async () => {- const { service } = build();- await expect(- record(service, { ...validChunk(), firstSeq: 0, lastSeq: 999, recordCount: 42 })- ).resolves.toBeTruthy();- });-+describe("createChunkUploadUrl: the proxy's clock", () => {test("a proxy clock too far ahead is refused with the named error, saying how far", async () => {- const { service, createIfAbsent } = build();- const refusal = record(service, { ...validChunk(), endedAt: new Date(Date.now() + 10 * 60_000) });+ const { service } = build();+ const refusal = record(service, validChunk(new Date(Date.now() + 10 * 60_000)));await expect(refusal).rejects.toMatchObject({ name: AgentVaultSessionLogErrorName.ClockSkew });await expect(refusal).rejects.toThrow(/about 10 minutes ahead/);- expect(createIfAbsent).not.toHaveBeenCalled();+ expect(presignPut).not.toHaveBeenCalled();});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(), startedAt: soon, endedAt: soon })).resolves.toBeTruthy();+ await expect(record(service, validChunk(soon))).resolves.toBeTruthy();});- test("refuses a chunk claiming more records than its bytes could hold", async () => {- const { service, createIfAbsent } = build();- await expect(- record(service, { ...validChunk(), firstSeq: 0, lastSeq: 999, recordCount: 1000, ciphertextBytes: 64 })- ).rejects.toMatchObject({ message: "Chunk is too small to hold the number of records it claims" });- expect(createIfAbsent).not.toHaveBeenCalled();+ test("a proxy clock more than 30 days behind is refused with the named error", async () => {+ const { service } = build();+ const refusal = record(service, validChunk(new Date(Date.now() - 31 * 24 * 60 * 60_000)));+ await expect(refusal).rejects.toMatchObject({ name: AgentVaultSessionLogErrorName.ClockSkew });+ await expect(refusal).rejects.toThrow(/more than 30 days behind/);+ expect(presignPut).not.toHaveBeenCalled();});- test("accepts a chunk whose size is plausible for its record count", async () => {+ test("a proxy clock a few days behind is tolerated", async () => {const { service } = build();- await expect(record(service, { ...validChunk(), recordCount: 10, ciphertextBytes: 4096 })).resolves.toBeTruthy();+ await expect(record(service, validChunk(new Date(Date.now() - 3 * 24 * 60 * 60_000)))).resolves.toBeTruthy();});});-describe("recordChunk: the organization ceiling", () => {- test("refuses with the named error once the increment carries the org past the limit", async () => {- const { service } = build({ storedAfterIncrement: CEILING + 1 });- await expect(record(service)).rejects.toMatchObject({ name: AgentVaultSessionLogErrorName.CeilingReached });- });-- test("the refusal is thrown from inside the transaction, so the row is rolled back with it", async () => {- const { service, createIfAbsent, recordStoredChunk } = build({ storedAfterIncrement: CEILING + 1 });- await expect(record(service)).rejects.toThrow();- expect(createIfAbsent).toHaveBeenCalledTimes(1);- expect(recordStoredChunk).toHaveBeenCalledTimes(1);+describe("createChunkUploadUrl: what the chunk says about itself", () => {+ test("a chunk whose id time is minutes off its endedAt is refused before it is signed", async () => {+ const { service, streamAdd } = build();+ const endedAt = new Date(Date.now() - 1_000);+ const chunk = { ...validChunk(endedAt), chunkId: uuidv7({ msecs: endedAt.getTime() - 5 * 60_000 }) };+ await expect(record(service, chunk)).rejects.toThrow("The chunk ID's time must match the chunk's endedAt");+ expect(presignPut).not.toHaveBeenCalled();+ expect(streamAdd).not.toHaveBeenCalled();});- test("landing exactly on the ceiling is allowed", async () => {- const { service } = build({ storedAfterIncrement: CEILING });- await expect(record(service)).resolves.toBeTruthy();+ test("an endedAt that rounds differently from the id is still accepted", async () => {+ const { service } = build();+ const endedAt = new Date(Date.now() - 1_000);+ const chunk = { ...validChunk(endedAt), chunkId: uuidv7({ msecs: endedAt.getTime() - 500 }) };+ await expect(record(service, chunk)).resolves.toBeTruthy();});- test("no upload url is minted for a refused chunk", async () => {- const { service } = build({ storedAfterIncrement: CEILING + 1 });- await expect(record(service)).rejects.toThrow();+ test("a chunk from a CLI that still sends the IV is refused with a message that says to update it", async () => {+ const { service, streamAdd } = build();+ await expect(record(service, { ...validChunk(), iv: "AAAAAAAAAAAAAAAA" })).rejects.toThrow(+ "This proxy's Infisical CLI is too old to record session logs. Update the Infisical CLI on this machine."+ );expect(presignPut).not.toHaveBeenCalled();+ expect(streamAdd).not.toHaveBeenCalled();});});-describe("recordChunk: re-sending a chunk", () => {- test("replays the stored row and does not count the records twice", async () => {+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, recordStoredChunk, findChunk } = build({- isReplay: true,- existingChunk: atCurrentDestination(chunk)- });+ 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 result = await record(service, chunk);+describe("createChunkUploadUrl: the live feed", () => {+ test("a feed that can't be written still hands out the upload url", async () => {+ const { service } = build({ feedAddFails: true });+ await expect(record(service)).resolves.toMatchObject({ uploadUrl: "https://bucket.s3.amazonaws.com/signed-put" });+ });- expect(result.chunkId).toBe("01a0a9c5-231d-7abc-8def-0123456789ab");- expect(result.uploadUrl).toBe("https://bucket.s3.amazonaws.com/signed-put");- expect(findChunk).toHaveBeenCalledWith(- { sessionId: "sess-1", chunkId: "01a0a9c5-231d-7abc-8def-0123456789ab" },- expect.anything()+ test("an upload never waits on Redis, even when it doesn't answer", async () => {+ const { service } = build({ feedAddHangs: true });+ await expect(record(service)).resolves.toMatchObject({ uploadUrl: "https://bucket.s3.amazonaws.com/signed-put" });+ });+});++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);+ 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(presignPut).not.toHaveBeenCalled();+ });++ 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);+ 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(recordStoredChunk).not.toHaveBeenCalled();});- test("presigns against the stored row's size and digest, not the resent body's claims", async () => {- const chunk = validChunk();- const storedSha256 = "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg";- const existing = { ...atCurrentDestination(chunk), ciphertextBytes: 999, ciphertextSha256: storedSha256 };- const { service } = build({ isReplay: true, existingChunk: existing });- await record(service, chunk);- expect(presignPut).toHaveBeenCalledWith({- objectKey: existing.objectKey,- ciphertextBytes: 999,- ciphertextSha256: storedSha256- });+ test("a live read fails too, so the caller keeps its cursor and nothing is skipped", async () => {+ vi.mocked(buildSessionLogStorage).mockRejectedValueOnce(unusable);+ 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)+ );});- test("a chunk re-sent after the destination moved is moved to the current bucket and key before it is presigned", async () => {- const { service, moveChunk } = build({- isReplay: true,- existingChunk: { ...validChunk(), id: "row-1", bucket: "old-bucket", objectKey: "old/key.json.enc" }- });- await record(service);+ test("a member who isn't an admin is told to ask an admin, without the AWS error", async () => {+ vi.mocked(buildSessionLogStorage).mockRejectedValueOnce(unusable);+ const { service } = build({ isAdmin: false });+ await expect(service.listSessionLogs(scope)).rejects.toEqual(+ storageUnavailable(AGENT_VAULT_SESSION_LOG_STORAGE_NEEDS_ADMIN_MESSAGE)+ );+ });- const [values, tx] = moveChunk.mock.calls[0] as unknown as [Record<string, unknown>, unknown];- expect(values).toMatchObject({ id: "row-1", projectId: "proj-1", bucket: "my-bucket", keyPrefix: "logs" });- expect(String(values.objectKey)).toMatch(- /^logs\/proj-1\/sess-1\/proxy-1\/\d{4}-\d{2}-\d{2}\/01a0a9c5-231d-7abc-8def-0123456789ab\.json\.enc$/+ 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" })+ );+ const { service } = build({ isAdmin: false });+ await expect(service.listSessionLogs(scope)).rejects.toEqual(+ storageUnavailable(AGENT_VAULT_SESSION_LOG_STORAGE_NEEDS_ADMIN_MESSAGE));- expect(tx).toBeDefined();- expect(presignPut).toHaveBeenCalledWith({- objectKey: values.objectKey,- ciphertextBytes: 4096,- ciphertextSha256: validChunk().ciphertextSha256- });});- test("a move that finds the destination changed again is a retryable 500 and presigns nothing", async () => {- const { service, moveChunk } = build({- isReplay: true,- destinationChanged: true,- existingChunk: { ...validChunk(), id: "row-1", bucket: "old-bucket", objectKey: "old/key.json.enc" }- });+ 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" })+ );+ 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));+ });- await expect(record(service)).rejects.toMatchObject({- name: "InternalServerError",- message:- "The session log bucket or key prefix changed while this chunk was being recorded. The proxy sends it again automatically."- });- expect(moveChunk).toHaveBeenCalledTimes(1);- expect(presignPut).not.toHaveBeenCalled();+ 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 chunk re-sent to the destination it is already at is left alone", async () => {- const chunk = validChunk();- const existing = atCurrentDestination(chunk);- const { service, moveChunk } = build({ isReplay: true, existingChunk: existing });- await record(service, chunk);+ 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)");+ });- expect(moveChunk).not.toHaveBeenCalled();- expect(presignPut).toHaveBeenCalledWith({- objectKey: existing.objectKey,- ciphertextBytes: 4096,- ciphertextSha256: validChunk().ciphertextSha256+ 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" })+ );+ const { service } = build();+ const error = await service.listSessionLogs(scope).catch((err: unknown) => err);+ expect(error).toBeInstanceOf(BadRequestError);+ expect((error as Error).message).toContain("s3:ListBucket");+ });++ 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" })+ );+ const { service } = build();+ const error = await service.listSessionLogs(scope).catch((err: unknown) => err);+ expect(error).toBeInstanceOf(InternalServerError);+ expect(error).toEqual(+ storageUnavailable(+ "Infisical couldn't list session logs in bucket 'my-bucket' (SlowDown). S3 isn't responding. Try again in a bit."+ )+ );+ });++ test("anything else that goes wrong while listing stays an error", async () => {+ listChunks.mockRejectedValueOnce(new TypeError("a bug"));+ const { service } = build();+ await expect(service.listSessionLogs(scope)).rejects.toThrow("a bug");+ });+});++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();+ });++ 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 { 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}`+ }+ ]);+ expect(page.sessionLogs.sessionKey).toBe(Buffer.alloc(32, 7).toString("base64"));+ expect(page.nextCursor).toBeNull();+ });++ test("a page ends at its byte budget and the cursor continues after the last chunk it took", async () => {+ 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({+ objects: [+ { key: newer.key, size: big },+ { key: older.key, size: big }+ ],+ isTruncated: false});+ const { service } = build();++ const page = await service.listSessionLogs(scope);+ expect(page.chunks.map((chunk) => chunk.chunkId)).toEqual([newer.chunkId]);+ expect(page.nextCursor).toBe(encodeHistoryCursor(newer.key.slice(FOLDER.length)));});- test("a chunk id another proxy recorded is refused before the row is touched", async () => {- const { service, moveChunk, recordStoredChunk } = build({- isReplay: true,- existingChunk: { ...validChunk(), proxyId: "proxy-2", bucket: "old-bucket", objectKey: "theirs/key.json.enc" }+ test("always takes at least one chunk, however large", async () => {+ const huge = objectFor(Date.now());+ listChunks.mockResolvedValueOnce({+ objects: [{ key: huge.key, size: AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES * 4 }],+ isTruncated: false});+ const { service } = build();+ const page = await service.listSessionLogs(scope);+ expect(page.chunks).toHaveLength(1);+ });- await expect(record(service)).rejects.toMatchObject({- name: "Conflict",- message: "This chunk ID was already recorded by another proxy"+ test("skips files it didn't write, and still moves past them", async () => {+ listChunks.mockResolvedValueOnce({ objects: [{ key: `${FOLDER}notes.txt`, size: 10 }], isTruncated: true });+ const { service } = build();+ const page = await service.listSessionLogs(scope);+ expect(page.chunks).toEqual([]);+ expect(page.nextCursor).toBe(encodeHistoryCursor("notes.txt"));+ });++ test("an empty page that says more remain ends the listing instead of failing", async () => {+ listChunks.mockResolvedValueOnce({ objects: [], isTruncated: true });+ const { service } = build();+ const page = await service.listSessionLogs(scope);+ expect(page.chunks).toEqual([]);+ expect(page.nextCursor).toBeNull();+ });++ 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` });+ });++ 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` });+ });++ 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(moveChunk).not.toHaveBeenCalled();- expect(recordStoredChunk).not.toHaveBeenCalled();- expect(presignPut).not.toHaveBeenCalled();});- test("a row that vanished between the insert and the read is a 500, not a silent success", async () => {- const { service } = build({ isReplay: true, existingChunk: null });- await expect(record(service)).rejects.toMatchObject({- message: "Session log chunk vanished between insert and read"+ test("stops at the first chunk whose last request is before the range starts, with nothing older to load", async () => {+ const from = new Date(Date.now() - 60_000);+ const inside = objectFor(from.getTime() + 1_000);+ const before = objectFor(from.getTime() - 1_000);+ listChunks.mockResolvedValueOnce({+ objects: [+ { key: inside.key, size: 100 },+ { key: before.key, size: 100 }+ ],+ isTruncated: true});+ const { service } = build();+ const page = await service.listSessionLogs({ ...scope, from });+ expect(page.chunks.map((chunk) => chunk.chunkId)).toEqual([inside.chunkId]);+ expect(page.nextCursor).toBeNull();});- test("a database error propagates rather than being read as a replay", async () => {- const other = new DatabaseError({ error: { code: "23503" }, name: "create" });- const { service, findChunk } = build({ createThrows: other });- await expect(record(service)).rejects.toThrow();- expect(findChunk).not.toHaveBeenCalled();+ test("refuses a range that ends before it starts", async () => {+ const { service } = build();+ await expect(+ service.listSessionLogs({+ ...scope,+ from: new Date("2026-10-07T10:00:00Z"),+ to: new Date("2026-10-07T09:00:00Z")+ })+ ).rejects.toThrow("The 'from' time must be before the 'to' time");});});-describe("when the AWS connection can't be used", () => {- const unusable = new BadRequestError({ message: "Couldn't use the AWS connection 'prod-logs': AccessDenied" });- const storedRow = () => ({- ...validChunk(),- proxyId: "proxy-1",- proxyName: "proxy-one",- bucket: "my-bucket",- objectKey: "logs/key.json.enc",- createdAt: new Date()- });- const scope = {- projectId: "proj-1",- ctx: { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never,- sessionId: "sess-1",- limit: 100- };- const readSessionLogs = (service: ReturnType<typeof build>["service"]) => service.listSessionLogs(scope);- const tailSessionLogs = (service: ReturnType<typeof build>["service"], receivedAfter: Date) =>- service.tailSessionLogs({ ...scope, receivedAfter });+describe("tailSessionLogs: reading the live feed", () => {+ const entry = (id: string, key: string, bucket = "my-bucket"): TFeedEntry => [+ id,+ ["key", key, "bucket", bucket, "bytes", "4096"]+ ];- test("a chunk is refused as a retryable 500 before any row is written, without the connection's details", async () => {- vi.mocked(buildSessionLogStorage).mockRejectedValueOnce(unusable);- const { service, createIfAbsent } = 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(createIfAbsent).not.toHaveBeenCalled();+ test("with no cursor, reads the feed from its start", async () => {+ const { service, streamRange } = build();+ await service.tailSessionLogs(scope);+ expect(streamRange).toHaveBeenCalledWith(`agent-vault-session-log-feed:${SESSION_ID}`, "(0-0", "+");});- test("a read lists the chunks without links and tells an admin why", async () => {- vi.mocked(buildSessionLogStorage).mockRejectedValueOnce(unusable);- const { service } = build({ pageRows: [storedRow()] });- const page = await readSessionLogs(service);- expect(page.sessionLogs.storageUnavailable).toEqual({ reason: "connection-unusable", message: unusable.message });- expect(page.sessionLogs.sessionKey).toBeNull();- expect(page.chunks.map((chunk) => chunk.presignedGetUrl)).toEqual([null]);+ test("returns each new entry as a chunk and moves the cursor to the last one", async () => {+ const first = objectFor(Date.now() - 2_000);+ const second = objectFor(Date.now() - 1_000);+ const { service } = build({ feed: [entry("100-0", first.key), entry("101-0", second.key)] });++ const page = await service.tailSessionLogs({ ...scope, cursor: "99-0" });+ expect(page.chunks.map((chunk) => chunk.chunkId)).toEqual([first.chunkId, second.chunkId]);+ expect(page.chunks[0]).toMatchObject({ proxyId: PROXY_ID, ciphertextBytes: 4096 });+ expect(page.nextCursor).toBe(encodeTailCursor("101-0"));});- test("a live read holds its cursor so nothing is skipped once the connection is back", async () => {- vi.mocked(buildSessionLogStorage).mockRejectedValueOnce(unusable);- const { service } = build({ pageRows: [storedRow()] });- const since = new Date(Date.now() - 60_000);- const page = await tailSessionLogs(service, since);+ test("an entry sent twice for the same chunk is returned each time, so a full feed still reads as full", async () => {+ const { key } = objectFor(Date.now());+ const { service } = build({ feed: [entry("100-0", key), entry("101-0", key)] });+ const page = await service.tailSessionLogs(scope);+ expect(page.chunks).toHaveLength(2);+ });++ test("skips entries from an earlier bucket or prefix, 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`)]+ });+ const page = await service.tailSessionLogs(scope);expect(page.chunks).toEqual([]);- expect(page.nextCursor).toBe(encodeTailCursor(since));- expect(page.hasMore).toBe(false);+ expect(page.nextCursor).toBe(encodeTailCursor("101-0"));});- test("a read names each chunk's proxy by its current name", async () => {- vi.mocked(buildSessionLogStorage).mockRejectedValueOnce(unusable);- const { service } = build({ pageRows: [storedRow()], proxies: [{ ...PROXY, name: "proxy-renamed" }] });- const page = await readSessionLogs(service);- expect(page.chunks.map((chunk) => chunk.proxyName)).toEqual(["proxy-renamed"]);+ test("skips an entry whose size isn't a whole number, and still moves past it", async () => {+ const { key } = objectFor(Date.now());+ const { service } = build({ feed: [["100-0", ["key", key, "bucket", "my-bucket", "bytes", "lots"]]] });+ const page = await service.tailSessionLogs(scope);+ expect(page.chunks).toEqual([]);+ expect(page.nextCursor).toBe(encodeTailCursor("100-0"));+ });++ 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 });+ 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 }),+ expect.anything()+ );});- test("a read falls back to the stored name once the proxy is deleted", async () => {- vi.mocked(buildSessionLogStorage).mockRejectedValueOnce(unusable);- const { service } = build({ pageRows: [storedRow()], proxies: [] });- const page = await readSessionLogs(service);- expect(page.chunks.map((chunk) => chunk.proxyName)).toEqual(["proxy-one"]);+ test("an empty feed keeps the cursor and never touches the AWS connection", 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();});});@@ -549,7 +671,7 @@ describe("updateSessionLogSettings: when the connection is checked again", () =>const actor = { type: "user", id: "user-1", orgId: "org-1", authMethod: null } as never;const save = (service: ReturnType<typeof build>["service"], patch: Record<string, unknown>) =>- service.updateSessionLogSettings({ projectId: "proj-1", ctx, actor, ...patch });+ service.updateSessionLogSettings({ projectId: PROJECT_ID, ctx, actor, ...patch });test.each([{ use: "a different connection", patch: { appConnectionId: "5c6fd1a9-3c89-4a64-9e5f-6b7cfe0f1a2b" } },@@ -587,6 +709,25 @@ describe("updateSessionLogSettings: when the connection is checked again", () =>});});+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();+ await expect(+ service.updateSessionLogSettings({ projectId: PROJECT_ID, ctx, actor, bucket: "logs--usw2-az1--x-s3" })+ ).rejects.toThrow("Directory buckets");+ expect(updateConfig).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);+ });+});+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({@@ -595,7 +736,7 @@ describe("updateSessionLogSettings: two first saves at once", () => {});await expect(service.updateSessionLogSettings({- projectId: "proj-1",+ 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@@ -609,7 +750,7 @@ describe("without session logs on the plan", () => {const actor = { type: "user", id: "user-1", orgId: "org-1", authMethod: null } as never;const save = (service: ReturnType<typeof build>["service"], patch: Record<string, unknown>) =>- service.updateSessionLogSettings({ projectId: "proj-1", ctx, actor, ...patch });+ service.updateSessionLogSettings({ projectId: PROJECT_ID, ctx, actor, ...patch });test("a save that turns recording on is refused before the connection is checked", async () => {const { service, validateConnection, updateConfig } = build({@@ -642,18 +783,20 @@ describe("without session logs on the plan", () => {});test("a chunk is refused with the error that tells the proxy logging is off", async () => {- const { service, createIfAbsent } = build({ licensed: false });+ const { service } = build({ licensed: false });await expect(record(service)).rejects.toMatchObject({name: AgentVaultSessionLogErrorName.Disabled,message: AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN});- expect(createIfAbsent).not.toHaveBeenCalled();+ expect(presignPut).not.toHaveBeenCalled();});test("logs recorded while it was on can still be read, and read as not recording", async () => {- const { service } = build({ licensed: false, pageRows: [] });- const page = await service.listSessionLogs({ projectId: "proj-1", ctx, sessionId: "sess-1", limit: 100 });- expect(page.chunks).toEqual([]);+ 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);});});@@ -664,34 +807,52 @@ describe("while the License Server can't be reached", () => {const unreachable = { licensed: false, planFallback: true } as const;test("a chunk from a paid org is still accepted on its last known plan", async () => {- const { service, createIfAbsent } = build({+ const { service } = build({...unreachable,lastKnownPlan: { plan: { agentVaultByoS3: true }, fetchedAt: Date.now() - 10 * 60_000 }});await record(service);- expect(createIfAbsent).toHaveBeenCalledTimes(1);+ expect(presignPut).toHaveBeenCalledTimes(1);});test("a chunk is held, not refused, when there is no recent real answer", async () => {- const { service, createIfAbsent } = build({+ const { service } = build({...unreachable,lastKnownPlan: { plan: { agentVaultByoS3: true }, fetchedAt: Date.now() - 2 * 60 * 60_000 }});await expect(record(service)).rejects.toMatchObject({ name: "InternalServerError" });- expect(createIfAbsent).not.toHaveBeenCalled();+ expect(presignPut).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: "proj-1", ctx, actor, enabled: true })).rejects.toThrow(- "Infisical couldn't confirm your plan right now. Try again in a few minutes."- );+ 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("a page still reads as recording", async () => {- const { service } = build({ ...unreachable, pageRows: [] });- const page = await service.listSessionLogs({ projectId: "proj-1", ctx, sessionId: "sess-1", limit: 100 });+ const { service } = build({ ...unreachable });+ const page = await service.listSessionLogs({ projectId: PROJECT_ID, ctx, sessionId: SESSION_ID });expect(page.sessionLogs.enabled).toBe(true);});});++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);+ });++ test("is clear once the connection works and the bucket answers", async () => {+ const { service } = build();+ const { health } = await service.getSessionLogHealth({ projectId: PROJECT_ID, ctx: scope.ctx });+ expect(health.connectionError).toBeNull();+ expect(assertReachable).toHaveBeenCalledTimes(1);+ });+});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 be08971de1..c9b14d06a3 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,14 +1,15 @@+import { S3ServiceException } from "@aws-sdk/client-s3";import { ForbiddenError } from "@casl/ability";-import { TAgentVaultSessionLogChunks, TAgentVaultSessionLogConfigs } from "@app/db/schemas";+import { TAgentVaultSessionLogConfigs } from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {ProjectPermissionAgentVaultSessionActions,ProjectPermissionSub} from "@app/ee/services/permission/project-permission";+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import {BadRequestError,- ConflictError,ForbiddenRequestError,InternalServerError,NotFoundError,@@ -25,61 +26,66 @@ 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";import { isOwnerlessSession, isSessionOwnedBy } from "../agent-vault-session/agent-vault-session-fns";-import { TAgentVaultSessionLogChunkDALFactory } from "./agent-vault-session-log-chunk-dal";import { TAgentVaultSessionLogConfigDALFactory } from "./agent-vault-session-log-config-dal";import {+ AGENT_VAULT_SESSION_LOG_CHUNK_ID_TIME_TOLERANCE_MS,AGENT_VAULT_SESSION_LOG_CLOCK_SKEW_MS,+ AGENT_VAULT_SESSION_LOG_FEED_MAX_ENTRIES,+ AGENT_VAULT_SESSION_LOG_FEED_TTL_SECONDS,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_MAX_STORED_CHUNKS,- AGENT_VAULT_SESSION_LOG_MIN_BYTES_PER_RECORD,AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS,- AGENT_VAULT_SESSION_LOG_RECEIVE_OVERLAP_MS,+ 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} from "./agent-vault-session-log-constants";import {- AgentVaultSessionLogErrorName,- AgentVaultSessionLogStorageUnavailableReason+ AGENT_VAULT_SESSION_LOG_STORAGE_UNAVAILABLE,+ AgentVaultSessionLogErrorName} from "./agent-vault-session-log-enums";import {+ buildSessionLogFolder,buildSessionLogObjectKey,+ chunkIdTimeMs,+ describeListFailure,encodeHistoryCursor,encodeTailCursor,getSessionLogEntitlement,isSessionLogIngestEnabled,+ parseSessionLogObjectKey,resolveStorageConfig,+ SESSION_LOG_FEED_START,+ toRev,TSessionLogLicenseService} from "./agent-vault-session-log-fns";import { unwrapSessionLogKey } from "./agent-vault-session-log-secrets";import { buildSessionLogStorage, TAgentVaultSessionLogStorage } from "./agent-vault-session-log-storage-fns";import {TAgentVaultSessionLogScoped,- TAgentVaultSessionLogStorageUnavailable,TAgentVaultSessionScoped,+ TCreateChunkUploadUrlDTO,TListSessionLogsDTO,- TRecordChunkDTO,TTailSessionLogsDTO,TUpdateSessionLogSettingsDTO} from "./agent-vault-session-log-types";type TAgentVaultSessionLogServiceFactoryDep = {- agentVaultSessionLogChunkDAL: TAgentVaultSessionLogChunkDALFactory;agentVaultSessionLogConfigDAL: TAgentVaultSessionLogConfigDALFactory;agentVaultSessionDAL: Pick<TAgentVaultSessionDALFactory, "findOne">;- agentVaultProxyDAL: Pick<TAgentVaultProxyDALFactory, "findByIdWithOrg" | "find">;+ agentVaultProxyDAL: Pick<TAgentVaultProxyDALFactory, "findByIdWithOrg">;appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey" | "decryptWithInputKey">;licenseService: TSessionLogLicenseService;+ keyStore: Pick<TKeyStoreFactory, "streamAdd" | "streamRange">;};export type TAgentVaultSessionLogServiceFactory = ReturnType<typeof agentVaultSessionLogServiceFactory>;export const agentVaultSessionLogServiceFactory = ({- agentVaultSessionLogChunkDAL,agentVaultSessionLogConfigDAL,agentVaultSessionDAL,agentVaultProxyDAL,@@ -87,29 +93,11 @@ export const agentVaultSessionLogServiceFactory = ({appConnectionService,permissionService,kmsService,- licenseService+ licenseService,+ keyStore}: TAgentVaultSessionLogServiceFactoryDep) => {const $storageDeps = { appConnectionDAL, kmsService };- const toCount = (value: number | string) => Number(value);-- const toChunkView = (row: TAgentVaultSessionLogChunks, proxyName: string, presignedGetUrl: string | null) => ({- chunkId: row.chunkId,- proxyId: row.proxyId,- proxyName,- startedAt: row.startedAt,- endedAt: row.endedAt,- firstSeq: toCount(row.firstSeq),- lastSeq: toCount(row.lastSeq),- recordCount: row.recordCount,- droppedCount: toCount(row.droppedCount),- ciphertextBytes: row.ciphertextBytes,- iv: row.iv,- ciphertextSha256: row.ciphertextSha256,- presignedGetUrl,- createdAt: row.createdAt- });-const NO_SETTINGS = { enabled: false, appConnectionId: null, bucket: null, region: null, keyPrefix: null };const toSettingsView = (config: TAgentVaultSessionLogConfigs) => ({@@ -129,7 +117,15 @@ export const agentVaultSessionLogServiceFactory = ({}};- const recordChunk = async ({ proxyId, sessionId, chunk }: TRecordChunkDTO) => {+ 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) {+ throw new BadRequestError({+ message:+ "This proxy's Infisical CLI is too old to record session logs. Update the Infisical CLI on this machine."+ });+ }+const sessionNotFound = () => new NotFoundError({ message: "Session not found" });const proxy = await agentVaultProxyDAL.findByIdWithOrg(proxyId);@@ -176,9 +172,6 @@ export const agentVaultSessionLogServiceFactory = ({});}- if (chunk.startedAt > chunk.endedAt) {- throw new BadRequestError({ message: "Chunk startedAt is after its endedAt" });- }const aheadMs = chunk.endedAt.getTime() - now.getTime();if (aheadMs > AGENT_VAULT_SESSION_LOG_CLOCK_SKEW_MS) {throw new BadRequestError({@@ -186,17 +179,17 @@ export const agentVaultSessionLogServiceFactory = ({message: `This proxy's clock is about ${Math.round(aheadMs / 60_000)} minutes ahead of Infisical's. Its clock must be within ${AGENT_VAULT_SESSION_LOG_CLOCK_SKEW_MS / 60_000} minutes for session logs to be recorded`});}- if (now.getTime() - chunk.startedAt.getTime() > AGENT_VAULT_SESSION_LOG_MAX_CHUNK_AGE_MS) {- throw new BadRequestError({ message: "Chunk is older than the maximum accepted age" });- }- if (chunk.firstSeq > chunk.lastSeq) {- throw new BadRequestError({ message: "Chunk firstSeq is greater than its lastSeq" });- }- if (chunk.lastSeq - chunk.firstSeq + 1 < chunk.recordCount) {- throw new BadRequestError({ message: "Chunk holds more records than its sequence range allows" });+ if (-aheadMs > AGENT_VAULT_SESSION_LOG_MAX_CHUNK_AGE_MS) {+ throw new BadRequestError({+ name: AgentVaultSessionLogErrorName.ClockSkew,+ message: `This proxy's clock is more than ${AGENT_VAULT_SESSION_LOG_MAX_CHUNK_AGE_MS / (24 * 60 * 60_000)} days behind Infisical's. Fix its clock for session logs to be recorded`+ });}- if (chunk.ciphertextBytes < chunk.recordCount * AGENT_VAULT_SESSION_LOG_MIN_BYTES_PER_RECORD) {- throw new BadRequestError({ message: "Chunk is too small to hold the number of records it claims" });+ if (+ Math.abs(chunkIdTimeMs(chunk.chunkId) - chunk.endedAt.getTime()) >+ AGENT_VAULT_SESSION_LOG_CHUNK_ID_TIME_TOLERANCE_MS+ ) {+ throw new BadRequestError({ message: "The chunk ID's time must match the chunk's endedAt" });}let sessionLogStorage: TAgentVaultSessionLogStorage;@@ -205,7 +198,7 @@ export const agentVaultSessionLogServiceFactory = ({} 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) {+ if (error instanceof BadRequestError || error instanceof InternalServerError) {logger.warn(error, `agentVaultSessionLog: could not use the session log connection [proxyId=${proxyId}]`);throw new InternalServerError({message:@@ -216,83 +209,37 @@ export const agentVaultSessionLogServiceFactory = ({}const objectKey = buildSessionLogObjectKey({- keyPrefix: storage.keyPrefix,- projectId: proxy.projectId,- sessionId: session.id,+ folder: buildSessionLogFolder({+ keyPrefix: storage.keyPrefix,+ projectId: proxy.projectId,+ sessionId: session.id+ }),proxyId,- startedAt: chunk.startedAt,chunkId: chunk.chunkId});-- const row = await agentVaultSessionLogChunkDAL.transaction(async (tx) => {- const created = await agentVaultSessionLogChunkDAL.createIfAbsent(- {- ...chunk,- sessionId: session.id,- projectId: proxy.projectId,- proxyId,- proxyName: proxy.name,- bucket: storage.bucket,- objectKey- },- tx- );-- if (!created) {- const existing = await agentVaultSessionLogChunkDAL.findOne(- { sessionId: session.id, chunkId: chunk.chunkId },- tx- );- if (!existing) {- throw new InternalServerError({ message: "Session log chunk vanished between insert and read" });- }- if (existing.proxyId !== proxyId) {- throw new ConflictError({ message: "This chunk ID was already recorded by another proxy" });- }- // A proxy only re-sends a chunk it never confirmed uploading, so after a move it belongs at the new destination.- if (existing.bucket !== storage.bucket || existing.objectKey !== objectKey) {- const moved = await agentVaultSessionLogChunkDAL.moveToDestinationIfCurrent(- {- id: existing.id,- projectId: proxy.projectId,- bucket: storage.bucket,- keyPrefix: storage.keyPrefix,- objectKey- },- tx- );- if (!moved) {- logger.warn(- `agentVaultSessionLog: session log destination changed while moving a re-sent chunk [sessionId=${session.id}] [chunkId=${chunk.chunkId}] [proxyId=${proxyId}]`- );- throw new InternalServerError({- message:- "The session log bucket or key prefix changed while this chunk was being recorded. The proxy sends it again automatically."- });- }- return moved;- }- return existing;- }-- const stored = await agentVaultSessionLogConfigDAL.recordStoredChunk(config.id, tx);- if (stored > AGENT_VAULT_SESSION_LOG_MAX_STORED_CHUNKS) {- throw new BadRequestError({- name: AgentVaultSessionLogErrorName.CeilingReached,- message: "Session logs have reached their limit for this organization. Contact Infisical support."- });- }- return created;- });-const uploadUrl = await sessionLogStorage.presignPut({- objectKey: row.objectKey,- ciphertextBytes: row.ciphertextBytes,- ciphertextSha256: row.ciphertextSha256+ 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) },+ AGENT_VAULT_SESSION_LOG_FEED_MAX_ENTRIES,+ AGENT_VAULT_SESSION_LOG_FEED_TTL_SECONDS,+ true+ )+ .catch((error) =>+ logger.warn(error, `agentVaultSessionLog: could not add a chunk to the live feed [sessionId=${session.id}]`)+ );+return {- chunkId: row.chunkId,+ chunkId: chunk.chunkId,uploadUrl,expiresInSeconds: AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS};@@ -311,143 +258,199 @@ export const agentVaultSessionLogServiceFactory = ({}const config = await agentVaultSessionLogConfigDAL.findOne({ projectId });- return { session, config, isAdmin };- };-- const $openSessionLogs = async ({- projectId,- ctx,- sessionId,- session,- config,- isAdmin,- rows- }: TAgentVaultSessionScoped &- Awaited<ReturnType<typeof $loadSessionLogs>> & { rows: TAgentVaultSessionLogChunks[] }) => {- const unreadSessionLogs = {+ const sessionLogs = {enabled:isSessionLogIngestEnabled(config) &&(await getSessionLogEntitlement(licenseService, ctx.actorOrgId)) !== "unlicensed",isRecordable: Boolean(session.encryptedSessionLogKey),- sessionKey: null,- storageUnavailable: null+ sessionKey: null as string | null};+ return { session, config, isAdmin, sessionLogs };+ };- if (!config || !rows.length) return { sessionLogs: unreadSessionLogs, chunks: [], isReadable: true };+ type TLoadedSessionLogs = Awaited<ReturnType<typeof $loadSessionLogs>>;- if (!session.encryptedSessionLogKey) {- logger.warn(`agentVaultSessionLog: session has chunks but no session log key [sessionId=${sessionId}]`);- return { sessionLogs: unreadSessionLogs, chunks: [], isReadable: true };+ // 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+ ? 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);+ };- // The current name, so a renamed proxy reads the same across its history; a deleted one keeps its stored name.- const proxyIds = [...new Set(rows.map((row) => row.proxyId))];- const currentProxyNames = new Map(- (await agentVaultProxyDAL.find({ projectId, $in: { id: proxyIds } })).map((proxy) => [proxy.id, proxy.name])- );- const proxyNameOf = (row: TAgentVaultSessionLogChunks) => currentProxyNames.get(row.proxyId) ?? row.proxyName;-- const unreadable = (storageUnavailable: TAgentVaultSessionLogStorageUnavailable) => ({- sessionLogs: { ...unreadSessionLogs, storageUnavailable },- chunks: rows.map((row) => toChunkView(row, proxyNameOf(row), null)),- isReadable: false- });-+ // 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) {- return unreadable({ reason: AgentVaultSessionLogStorageUnavailableReason.NoConnection, message: null });+ throw $storageUnavailable({+ isAdmin,+ adminMessage: "No AWS connection is set for session logs. Choose one in Settings."+ });}-- let sessionLogStorage: TAgentVaultSessionLogStorage;try {- sessionLogStorage = await buildSessionLogStorage(storage, ctx.actorOrgId, $storageDeps);+ 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;- return unreadable({- reason: AgentVaultSessionLogStorageUnavailableReason.ConnectionUnusable,- message: isAdmin ? error.message : null- });+ throw $storageUnavailable({ isAdmin, adminMessage: error.message });}+ };- const sessionKey = await unwrapSessionLogKey(- { projectId, sessionId, encryptedSessionLogKey: session.encryptedSessionLogKey },- kmsService- );-+ const $presignChunks = async (+ keyScope: { projectId: string; sessionId: string; encryptedSessionLogKey: Buffer },+ storage: TAgentVaultSessionLogStorage,+ found: { key: string; chunkId: string; proxyId: string; ciphertextBytes: number }[]+ ) => {const chunks = await Promise.all(- rows.map(async (row) =>- toChunkView(- row,- proxyNameOf(row),- row.bucket === config.bucket ? await sessionLogStorage.presignGet(row.objectKey) : null- )- )+ found.map(async ({ key, chunkId, proxyId, ciphertextBytes }) => ({+ chunkId,+ proxyId,+ ciphertextBytes,+ presignedGetUrl: await storage.presignGet(key)+ })));-- return {- sessionLogs: { ...unreadSessionLogs, sessionKey: sessionKey.toString("base64") },- chunks,- isReadable: true- };+ const sessionKey = await unwrapSessionLogKey(keyScope, kmsService);+ return { chunks, sessionKey: sessionKey.toString("base64") };};- const $caughtUpTo = (readAt: number) => new Date(readAt - AGENT_VAULT_SESSION_LOG_RECEIVE_OVERLAP_MS);+ // 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 ({ limit, before, from, to, ...scope }: TListSessionLogsDTO) => {- const readAt = Date.now();- const loaded = await $loadSessionLogs(scope);+ 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" });+ }- const { chunks: rows, hasMore } = loaded.config- ? await agentVaultSessionLogChunkDAL.findForSessionPage({- sessionId: scope.sessionId,- recordBudget: limit,- byteBudget: AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES,- maxChunks: AGENT_VAULT_SESSION_LOG_MAX_PAGE_CHUNKS,- before,- from,- to- })- : { chunks: [], hasMore: false };+ const { session, config, isAdmin, sessionLogs } = await $loadSessionLogs(scope);+ if (!config || !session.encryptedSessionLogKey) return { sessionLogs, chunks: [], nextCursor: null };- const { sessionLogs, chunks } = await $openSessionLogs({ ...scope, ...loaded, rows });+ const opened = await $openStorage({ ctx: scope.ctx, config, isAdmin });- return {- sessionLogs,- chunks,- nextCursor: hasMore && chunks.length ? encodeHistoryCursor(rows[rows.length - 1].chunkId) : null,- liveCursor: encodeTailCursor($caughtUpTo(readAt))- };- };+ // 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)}`;- const tailSessionLogs = async ({ limit, receivedAfter, ...scope }: TTailSessionLogsDTO) => {- const readAt = Date.now();- const since = receivedAfter ?? $caughtUpTo(readAt);- const loaded = await $loadSessionLogs(scope);-- const { chunks: rows, hasMore } = loaded.config- ? await agentVaultSessionLogChunkDAL.findReceivedForSession({- sessionId: scope.sessionId,- receivedAfter: since,- recordBudget: limit,- byteBudget: AGENT_VAULT_SESSION_LOG_MAX_PAGE_BYTES,- maxChunks: AGENT_VAULT_SESSION_LOG_MAX_PAGE_CHUNKS- })- : { chunks: [], hasMore: false };-- const { sessionLogs, chunks, isReadable } = await $openSessionLogs({ ...scope, ...loaded, rows });-- // Holding the cursor rather than skipping rows it could not hand links for, so they still arrive once- // the connection is back.- if (!isReadable) {- return { sessionLogs, chunks: [], nextCursor: encodeTailCursor(since), hasMore: false };+ 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 });}- return {- sessionLogs,- chunks,- nextCursor: encodeTailCursor(hasMore ? rows[rows.length - 1].createdAt : $caughtUpTo(readAt)),- hasMore- };+ 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;+ }+ }++ 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 tailSessionLogs = async ({ cursor = SESSION_LOG_FEED_START, ...scope }: TTailSessionLogsDTO) => {+ const { session, config, isAdmin, sessionLogs } = await $loadSessionLogs(scope);+ const unchanged = { sessionLogs, chunks: [], nextCursor: encodeTailCursor(cursor) };+ if (!config || !session.encryptedSessionLogKey) return unchanged;++ const entries = await keyStore.streamRange(+ KeyStorePrefixes.AgentVaultSessionLogFeed(session.id),+ `(${cursor}`,+ "+"+ );+ if (!entries.length) return unchanged;++ // 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 });++ 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 });+ });++ 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 getSessionLogSettings = async ({ projectId, ctx }: TAgentVaultSessionLogScoped) => {@@ -468,17 +471,19 @@ export const agentVaultSessionLogServiceFactory = ({let connectionError: string | null = null;if (storage) {try {- await buildSessionLogStorage(storage, ctx.actorOrgId, $storageDeps);+ const sessionLogStorage = await buildSessionLogStorage(storage, ctx.actorOrgId, $storageDeps);+ await sessionLogStorage.assertReachable();} catch (error) {logger.warn(error, `agentVaultSessionLog: could not use the session log connection [projectId=${projectId}]`);connectionError =- error instanceof BadRequestError ? error.message : "Couldn't check the AWS connection. Try again.";+ error instanceof BadRequestError || error instanceof InternalServerError+ ? error.message+ : "Couldn't check the AWS connection. Try again.";}}return {health: {- isStorageFull: config ? toCount(config.storedChunkCount) >= AGENT_VAULT_SESSION_LOG_MAX_STORED_CHUNKS : false,connectionError}};@@ -522,6 +527,14 @@ export const agentVaultSessionLogServiceFactory = ({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."+ });+ }+const entitlement = needsLicence ? await getSessionLogEntitlement(licenseService, ctx.actorOrgId) : "licensed";if (entitlement === "unknown") {throw new BadRequestError({@@ -600,7 +613,7 @@ export const agentVaultSessionLogServiceFactory = ({};return {- recordChunk,+ createChunkUploadUrl,listSessionLogs,tailSessionLogs,getSessionLogSettings,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 dfb10f856e..5dad4370fe 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@@ -16,7 +16,10 @@ vi.mock("@app/services/app-connection/app-connection-fns", () => ({vi.mock("@app/services/app-connection/aws/aws-connection-fns", () => ({getAwsConnectionConfig: vi.fn()}));-vi.mock("@app/lib/aws/s3", () => ({ createS3Bucket: 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 };@@ -43,7 +46,26 @@ describe("buildSessionLogStorage", () => {});});- test("assumes the role with Agent Vault's External ID, for its own connections too", async () => {+ test.each([+ {+ why: "AWS throttles the call",+ error: new STSServiceException({+ name: "Throttling",+ $fault: "client",+ $metadata: { httpStatusCode: 400 },+ message: "Rate exceeded"+ })+ },+ { 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."+ });+ });++ 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,@@ -59,7 +81,8 @@ describe("buildSessionLogStorage", () => {await buildSessionLogStorage(config, "org-1", deps);expect(getAwsConnectionConfig).toHaveBeenCalledWith(expect.objectContaining({ projectType: ProjectType.AgentVault }),- config.region+ config.region,+ { stsRequestHandler: { connectionTimeout: 5_000, requestTimeout: 15_000, throwOnRequestTimeout: true } });});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 acca30b155..4e2bcb99d9 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,8 +1,8 @@import { STSServiceException } from "@aws-sdk/client-sts";import { ProjectType } from "@app/db/schemas";-import { createS3Bucket } from "@app/lib/aws/s3";-import { BadRequestError } from "@app/lib/errors";+import { AWS_REQUEST_TIMEOUTS, createS3Bucket } from "@app/lib/aws/s3";+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";@@ -11,8 +11,11 @@ import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-conimport { TAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";-import { AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS } from "./agent-vault-session-log-constants";-import { withKeyPrefix } from "./agent-vault-session-log-fns";+import {+ AGENT_VAULT_SESSION_LOG_MAX_PAGE_CHUNKS,+ AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS+} 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 = {@@ -50,10 +53,16 @@ export const buildSessionLogStorage = async (// 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+ 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 =err instanceof STSServiceException || err instanceof BadRequestError? err.message@@ -78,7 +87,7 @@ export const buildSessionLogStorage = async (s3.presignCreateOnlyPut({key: objectKey,contentLength: ciphertextBytes,- // Stored unpadded; S3 wants the padded form+ // The proxy sends it unpadded; S3 wants the padded formsha256Base64: `${ciphertextSha256}=`,expiresInSeconds: AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS});@@ -86,8 +95,13 @@ export const buildSessionLogStorage = async (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);@@ -100,10 +114,19 @@ export const buildSessionLogStorage = async (throw new BadRequestError({message:access.failure === "unreachable"- ? `Unable to reach bucket '${bucket}'. Check the bucket name, the region, and that the connection's credentials can access it`+ ? unreachableMessage: `Bucket '${bucket}' is reachable but writing to it failed. Grant s3:PutObject on the configured key prefix`});};- return { presignPut, presignGet, mintCorsProbeUrl, validate };+ // 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;++ logger.warn({ err: reachable.error, bucket }, `Agent Vault session logs bucket is unreachable [bucket=${bucket}]`);+ throw new BadRequestError({ message: unreachableMessage });+ };++ return { presignPut, presignGet, listChunks, mintCorsProbeUrl, validate, assertReachable };};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 a1ec0a9955..34aae64834 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@@ -3,7 +3,6 @@ import { z } from "zod";import { OrgServiceActor, TGenericPermission } from "@app/lib/types";import { AWSRegion } from "@app/services/app-connection/app-connection-enums";-import { AgentVaultSessionLogStorageUnavailableReason } from "./agent-vault-session-log-enums";import type {AgentVaultSessionLogChunkCreateSchema,AgentVaultSessionLogSettingsUpdateSchema@@ -13,22 +12,20 @@ export type TAgentVaultSessionLogScoped = { projectId: string; ctx: TGenericPermexport type TAgentVaultSessionScoped = TAgentVaultSessionLogScoped & { sessionId: string };-export type TRecordChunkDTO = {+export type TCreateChunkUploadUrlDTO = {proxyId: string;sessionId: string;chunk: z.infer<typeof AgentVaultSessionLogChunkCreateSchema>;};export type TListSessionLogsDTO = TAgentVaultSessionScoped & {- limit: number;- before?: string;+ cursor?: string;from?: Date;to?: Date;};export type TTailSessionLogsDTO = TAgentVaultSessionScoped & {- limit: number;- receivedAfter?: Date;+ cursor?: string;};export type TUpdateSessionLogSettingsDTO = TAgentVaultSessionLogScoped & {@@ -41,8 +38,3 @@ export type TResolvedSessionLogStorageConfig = {region: AWSRegion;keyPrefix: string | null;};--export type TAgentVaultSessionLogStorageUnavailable = {- reason: AgentVaultSessionLogStorageUnavailableReason;- message: 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 518cc1d688..ba5276358a 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@@ -15,8 +15,6 @@ import { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { AgentVaultMemberType, AgentVaultSessionScope } from "../agent-vault/agent-vault-enums";import { getAgentVaultPermission, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/agent-vault-access-bundle-dal";-import { TAgentVaultSessionLogChunkDALFactory } from "../agent-vault-session-log/agent-vault-session-log-chunk-dal";-import { AGENT_VAULT_SESSION_LOG_RECENT_COUNTS_WINDOW_MS } from "../agent-vault-session-log/agent-vault-session-log-constants";import { generateSessionLogKey, wrapSessionLogKey } from "../agent-vault-session-log/agent-vault-session-log-secrets";import { TAgentVaultSessionAccessBundleDALFactory } from "./agent-vault-session-access-bundle-dal";import { TAgentVaultSessionDALFactory, TAgentVaultSessionListRow } from "./agent-vault-session-dal";@@ -38,7 +36,6 @@ type TAgentVaultSessionServiceFactoryDep = {membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;- agentVaultSessionLogChunkDAL: Pick<TAgentVaultSessionLogChunkDALFactory, "sumRecentCounts">;};export type TAgentVaultSessionServiceFactory = ReturnType<typeof agentVaultSessionServiceFactory>;@@ -49,8 +46,7 @@ export const agentVaultSessionServiceFactory = ({agentVaultAccessBundleDAL,membershipDAL,permissionService,- kmsService,- agentVaultSessionLogChunkDAL+ kmsService}: TAgentVaultSessionServiceFactoryDep) => {const requireSessionActor = (ctx: TMintSessionDTO["ctx"]) => {if (ctx.actor !== ActorType.USER && ctx.actor !== ActorType.IDENTITY) {@@ -64,19 +60,6 @@ export const agentVaultSessionServiceFactory = ({status: deriveSessionStatus({ ...session, userId, identityId })});- const toSessionViewsWithLogCounts = async (sessions: TAgentVaultSessionListRow[]) => {- const counts = sessions.length- ? await agentVaultSessionLogChunkDAL.sumRecentCounts({- sessionIds: sessions.map((session) => session.id),- windowMs: AGENT_VAULT_SESSION_LOG_RECENT_COUNTS_WINDOW_MS- })- : new Map<string, { recordedCount: number; droppedCount: number }>();- return sessions.map((session) => ({- ...toSessionView(session),- recentSessionLogCounts: counts.get(session.id) ?? { recordedCount: 0, droppedCount: 0 }- }));- };-const mintSession = async ({ projectId, ctx, accessBundles, actorName, actorEmail, ttl }: TMintSessionDTO) => {const actor = requireSessionActor(ctx);const { permission, accessBundleIds: reachable } = await getAgentVaultReachability(@@ -188,7 +171,7 @@ export const agentVaultSessionServiceFactory = ({offset});- return { sessions: await toSessionViewsWithLogCounts(sessions), totalCount };+ return { sessions: sessions.map(toSessionView), totalCount };};// A session you may not see reads exactly like one that does not exist.@@ -218,10 +201,7 @@ export const agentVaultSessionServiceFactory = ({ProjectPermissionSub.AgentVaultSessions);- const [session] = await toSessionViewsWithLogCounts([- await findVisibleSession({ projectId, ctx, sessionId, isAdmin })- ]);- return { session };+ return { session: toSessionView(await findVisibleSession({ projectId, ctx, sessionId, isAdmin })) };};const revokeSession = async ({ projectId, ctx, sessionId }: TRevokeSessionDTO) => {diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex c8478e797b..19fa7f3b80 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -245,11 +245,11 @@ path decides what a service can reach, so it stays literal.## Session logsMetadata only (method, host, path, status, decision), never bodies, headers or the query string. The agent is-hostile input: nothing it sends may erase or hide its own records, so a refused chunk counts as dropped, never-lost silently.+hostile 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.** Infisical keeps one index row per chunk and never- seals or opens one. There is no Postgres payload path; AWS only.+- **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.- **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@@ -258,23 +258,30 @@ lost silently.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 the- browser rebuilds the AAD from Postgres's string. A change here is a change in all three places.-- **Write order is insert, commit, presign.** Row first so a failed upload is a visible gap, presign after commit- so no network call holds the config row lock. The PUT is create-only (`If-None-Match: *`, the proxy reads 412- as uploaded) with the length and `x-amz-checksum-sha256` signed, so S3 refuses any other body.-- **A chunk row records its bucket and full key**, and reads presign only chunks in the current bucket, so- switching back makes old history readable. A re-send moves the row only through `moveToDestinationIfCurrent`,- whose one UPDATE checks the settings. No row locks.-- **`chunks.proxyId` has no FK**: the browser checks each record's `proxyId` against it, and `SET NULL` would make- a deleted proxy's chunks unreadable.+ browser rebuilds the AAD from the id in the object name. A change here is a change in all three places.+- **Infisical builds the name and signs it into a create-only PUT** (`If-None-Match: *`, the proxy reads 412 as+ uploaded) with the length and `x-amz-checksum-sha256` signed, so S3 refuses any other body. The `proxyId` in the+ name comes from the proxy's login, and the browser checks every record's `proxyId` against it.+- **A chunk id carries the time of the chunk's last request**, and the proxy never puts requests more than 10+ minutes apart in one chunk, so a date range lists from 11 minutes past its end and stops at the first chunk whose+ last 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.+- **A read that can't reach the bucket fails with `AgentVaultSessionLogStorageUnavailable`**: 400 when the+ settings or AWS side need fixing, 500 when S3 isn't responding. Never a 200 with no chunks, which callers read+ as "no logs". Only admins see the cause.- **Chunks are accepted for 24 hours after a session ends**, including when its owner is deleted (read from`updatedAt`, which the FK's `SET NULL` bumps). Deleting an identity must not erase its last minute.-- **History (`/logs`) pages on `chunkId`, the tail (`/logs/tail`) on our `createdAt`**, re-reading- `AGENT_VAULT_SESSION_LOG_RECEIVE_OVERLAP_MS` and deduping by chunk id. A late chunk has an old id and a new- `createdAt`, so the tail can't page on the id.-- **The org chunk limit is a lifetime counter** and internal: no env var, not documented, surfaced only as- `isStorageFull`. Kept as abuse prevention until usage and plans are decided. At the limit writes are refused,- never drop-oldest, which would let flooding evict evidence.+- **History (`/logs`) is one LIST paged by size; the tail (`/logs/tail`) never LISTs.** Registering a chunk adds+ its name to a Redis stream per session (last 10, 2-minute TTL), not awaited, since the Redis client queues+ rather than fails while Redis is down. A tail with no cursor reads the stream from its start, so a chunk still+ uploading when the page opened arrives; the browser dedupes on `(chunkId, proxyId)` and refetches tail 404s+ while they may still be uploading. When a poll comes late or returns a full feed, the panel also merges in the+ newest history page, at most once a minute, since the feed may have dropped names it never saw. If that+ page 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 logsstay readable. That breaks the License Checks rule in `CODE_QUALITY.md` on purpose. Turning session logs offdiff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 604ec9a36b..fea95718eb 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -166,6 +166,8 @@ export const KeyStorePrefixes = {PamAwsIamAccessKeyId: (sessionId: string) => `pam-aws-iam-access-key-id:${sessionId}` as const,PamDefaultProject: (orgId: string) => `pam-default-project:${orgId}` as const,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,CertDashboardStats: (projectId: string) => `cert-dashboard-stats:${projectId}` as const,OrgSecretScanningFindingsCount: (orgId: string) => `org-secret-scanning-findings-count:${orgId}` as const,@@ -369,7 +371,8 @@ export type TKeyStoreFactory = {id: string,fieldValue: Record<string, string>,maxLen?: number,- expiryInSeconds?: number+ expiryInSeconds?: number,+ isExactTrim?: boolean) => Promise<string | null>;streamRange: (key: string, start: string, end: string, count?: number) => Promise<[string, string[]][]>;streamTrim: (key: string, minId: string, inclusive?: boolean) => Promise<number>;@@ -777,7 +780,10 @@ export const keyStoreFactory = (id: string,fieldValue: Record<string, string>,maxLen = 1_000_000,- expiryInSeconds?: number+ expiryInSeconds?: number,+ // With "~", Redis only trims whole internal blocks of about 100 entries, so a cap of 10 could still hold around+ // 100. Small caps need exact trimming.+ isExactTrim = false) => {const args: string[] = [];for (const [field, value] of Object.entries(fieldValue)) {@@ -785,14 +791,15 @@ export const keyStoreFactory = (}if (!expiryInSeconds) {- return primaryRedis.xadd(key, "MAXLEN", "~", maxLen, id, ...args);+ return isExactTrim+ ? primaryRedis.xadd(key, "MAXLEN", maxLen, id, ...args)+ : primaryRedis.xadd(key, "MAXLEN", "~", maxLen, id, ...args);}- const results = await primaryRedis- .multi()- .xadd(key, "MAXLEN", "~", maxLen, id, ...args)- .expire(key, expiryInSeconds)- .exec();+ const pipeline = primaryRedis.multi();+ if (isExactTrim) pipeline.xadd(key, "MAXLEN", maxLen, id, ...args);+ else pipeline.xadd(key, "MAXLEN", "~", maxLen, id, ...args);+ const results = await pipeline.expire(key, expiryInSeconds).exec();const [addError, entryId] = results?.[0] ?? [null, null];if (addError) throw addError;diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex c68da31e6a..4b51107802 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4548,44 +4548,28 @@ export const AGENT_VAULT = {SESSION_LOGS: {chunkId: "The ID of the chunk.",proxyId: "The ID of the proxy that uploaded the chunk.",- proxyName: "The name of the proxy that uploaded the chunk. If the proxy was deleted, the name it had at the time.",- startedAt: "The time of the first record in the chunk.",endedAt: "The time of the last record in the chunk.",- firstSeq: "The sequence number of the first record in the chunk. Each proxy numbers its own records.",- lastSeq: "The sequence number of the last record in the chunk. Each proxy numbers its own records.",- recordCount: "The number of records in the chunk.",- droppedCount:- "The number of requests the proxy couldn't record, for example because too many requests came in at once or session logs were off. They're reported on the next chunk the proxy sends, so they happened before this chunk, but not necessarily right before its first record.",- ciphertextBytes: "The size of the encrypted chunk, in bytes.",- iv: "The AES-GCM initialization vector for the chunk, as base64.",+ ciphertextBytes: "The size of the encrypted chunk in bytes.",ciphertextSha256:- "The SHA-256 digest of the encrypted chunk, as base64 without padding. If the downloaded chunk has a different digest, the chunk was changed after it was uploaded.",+ "The SHA-256 digest of the encrypted chunk, including its IV, as base64 without padding. The bucket refuses an upload with a different digest.",+ legacyIv:+ "Sent only by Infisical CLI versions that can't record session logs. A request that includes it is refused.",uploadUrl:"The URL to upload the encrypted chunk to with a PUT request. The body must be exactly `ciphertextBytes` bytes.",- presignedGetUrl:- "The URL to download the chunk from. Null if the chunk is in a bucket session logs no longer use, or if `sessionLogs.storageUnavailable` is set.",+ presignedGetUrl: "The URL to download the chunk from.",expiresInSeconds: "The number of seconds before the URL expires.",- chunkCreatedAt:- "When the proxy registered the chunk with Infisical. Its upload to the bucket finishes shortly after, so a download in between returns 404.",isRecordable: "False if this session's requests can't be recorded.",- sessionKey: "The key that decrypts every chunk in this response, as base64. Null if no chunk can be read.",- storageUnavailable: "The reason the chunks can't be downloaded right now. Null if they can.",- storageUnavailableReason:- "`no-connection` if no AWS connection is set for session logs, or `connection-unusable` if Infisical can't use the AWS connection.",- storageUnavailableMessage: "The error Infisical got from the AWS connection. Returned only to Agent Vault admins.",+ sessionKey: "The key that decrypts every chunk in this response, as base64. Null if the response has no chunks.",sessionLogs:- "Whether session logs are on, the key that decrypts the chunks, and why they can't be downloaded, if they can't.",+ "Whether session logs are on, whether this session can be recorded, and the key that decrypts the chunks.",historyCursor: "The `nextCursor` from the previous response. Leave it out to start from the newest logs.",- historyNextCursor: "Pass this as `cursor` to get older logs. Null when there's nothing older.",- liveCursor:- "Pass this to [the endpoint that tails session logs](/api-reference/endpoints/agent-vault-session-logs/tail) to get new logs as they arrive.",+ historyNextCursor:+ "Pass this as `cursor` to get older logs. Null when there's nothing older. A page can have no chunks and still have a `nextCursor`.",tailCursor:- "The `liveCursor` from [the endpoint that lists session logs](/api-reference/endpoints/agent-vault-session-logs/list), or the `nextCursor` from your last call. Leave it out to start from now.",- tailNextCursor: "Pass this as `cursor` on your next call.",- tailHasMore: "Whether more logs are ready now. If false, wait a few seconds before calling again.",- limit: "How many records to return. Only whole chunks are returned, so a response can have slightly more.",- from: "Return only chunks with records at or after this time.",- to: "Return only chunks with records at or before this time.",+ "The `nextCursor` from your last call. Leave it out on the first call to start from the most recent chunks.",+ tailNextCursor: "Pass this as `cursor` on your next call, a few seconds later.",+ 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.",appConnectionId: "The ID of the AWS connection Infisical uses to write to and read from the bucket.",@@ -4597,7 +4581,6 @@ export const AGENT_VAULT = {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.",- isStorageFull: "Whether your organization has reached its session log storage limit.",hasSessionLogKey: "Whether the proxy already has this session's log key. If true, the key isn't returned again.",proxySessionKey:"The session's log key, as base64, sent once. Null when session logs are off or the proxy already has it."@@ -4609,10 +4592,6 @@ export const AGENT_VAULT = {ttl: "How long the session lasts: a duration such as 30m, 8h or 7d (at least 1m), or never. Defaults to 7d.",token: "The session token. Returned once, at mint, and never again.",expiresAt: "When the session expires, or null when it never does.",- recentSessionLogCounts:- "How many of the session's requests were recorded in its session log, and how many the proxy couldn't record, over the 24 hours before its most recent recorded request.",- recentRecordedCount: "The number of requests recorded in the session log.",- recentDroppedCount: "The number of requests the proxy couldn't record in the session log.",scope: "Whose sessions to list: your own (mine) or everyone's (all, administrators only).",status:"Filter by session status: `active`, `revoked` or `expired`. Separate several with commas to match any of them.",diff --git a/backend/src/lib/aws/s3.ts b/backend/src/lib/aws/s3.tsindex 28f2fc1bd1..f337d85875 100644--- a/backend/src/lib/aws/s3.ts+++ b/backend/src/lib/aws/s3.ts@@ -1,4 +1,10 @@-import { GetObjectCommand, HeadBucketCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";+import {+ GetObjectCommand,+ HeadBucketCommand,+ ListObjectsV2Command,+ PutObjectCommand,+ S3Client+} from "@aws-sdk/client-s3";import { getSignedUrl } from "@aws-sdk/s3-request-presigner";import { crypto } from "@app/lib/crypto/cryptography";@@ -7,6 +13,12 @@ import { CustomAWSHasher } from "./hashing";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 };++// 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 TS3Bucket = ReturnType<typeof createS3Bucket>;@@ -24,8 +36,11 @@ export const createS3Bucket = ({region,useFipsEndpoint: crypto.isFipsModeEnabled(),sha256: CustomAWSHasher,- credentials+ credentials,+ requestHandler: AWS_REQUEST_TIMEOUTS});+ // 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) });// These headers are signed so S3 enforces them: the body must be the declared size and hash to the declared// digest, and If-None-Match stops a re-minted link from overwriting an object already stored.@@ -59,12 +74,39 @@ export const createS3Bucket = ({const presignGet = (key: string, expiresInSeconds: number) =>getSignedUrl(client, new GetObjectCommand({ Bucket: bucket, Key: key }), { expiresIn: expiresInSeconds });- const checkAccess = async (testKey: string): Promise<TS3AccessCheck> => {+ // One page only: callers that page do so across requests, so one request can't walk an unbounded listing.+ const listPage = async ({+ prefix,+ startAfter,+ maxKeys+ }: {+ prefix: string;+ startAfter?: string;+ maxKeys: number;+ }) => {+ const res = await client.send(+ new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, StartAfter: startAfter, MaxKeys: maxKeys }),+ sendOptions()+ );+ const objects: { key: string; size: number }[] = [];+ (res.Contents ?? []).forEach(({ Key, Size }) => {+ if (Key !== undefined && Size !== undefined) objects.push({ key: Key, size: Size });+ });+ return { objects, isTruncated: Boolean(res.IsTruncated) };+ };++ const checkReachable = async (): Promise<{ ok: true } | { ok: false; error: unknown }> => {try {- await client.send(new HeadBucketCommand({ Bucket: bucket }));+ await client.send(new HeadBucketCommand({ Bucket: bucket }), sendOptions());+ return { ok: true };} catch (error) {- return { ok: false, failure: "unreachable", 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 };try {await client.send(new PutObjectCommand({@@ -72,7 +114,8 @@ export const createS3Bucket = ({Key: testKey,Body: Buffer.from("infisical-access-check"),ContentType: "application/octet-stream"- })+ }),+ sendOptions());} catch (error) {return { ok: false, failure: "unwritable", error };@@ -80,5 +123,5 @@ export const createS3Bucket = ({return { ok: true };};- return { presignCreateOnlyPut, presignGet, checkAccess };+ return { presignCreateOnlyPut, presignGet, listPage, checkReachable, checkAccess };};diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 229df1e045..6cd06bb06e 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -40,7 +40,6 @@ import { agentVaultResolveDALFactory } from "@app/ee/services/agent-vault-proxy/import { agentVaultSessionAccessBundleDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-access-bundle-dal";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 { agentVaultSessionLogChunkDALFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-chunk-dal";import { agentVaultSessionLogConfigDALFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-config-dal";import { agentVaultSessionLogServiceFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-service";import { assumePrivilegeServiceFactory } from "@app/ee/services/assume-privilege/assume-privilege-service";@@ -1988,7 +1987,6 @@ export const registerRoutes = async (const agentVaultSessionAccessBundleDAL = agentVaultSessionAccessBundleDALFactory(db);const agentVaultProxyDAL = agentVaultProxyDALFactory(db);const agentVaultResolveDAL = agentVaultResolveDALFactory(db);- const agentVaultSessionLogChunkDAL = agentVaultSessionLogChunkDALFactory(db);const agentVaultSessionLogConfigDAL = agentVaultSessionLogConfigDALFactory(db);const agentVaultAccessBundleService = agentVaultAccessBundleServiceFactory({@@ -2016,8 +2014,7 @@ export const registerRoutes = async (agentVaultAccessBundleDAL,membershipDAL,permissionService,- kmsService,- agentVaultSessionLogChunkDAL+ kmsService});const agentVaultProjectResolver = agentVaultProjectResolverFactory({@@ -3313,7 +3310,6 @@ export const registerRoutes = async (});const agentVaultSessionLogService = agentVaultSessionLogServiceFactory({- agentVaultSessionLogChunkDAL,agentVaultSessionLogConfigDAL,agentVaultSessionDAL,agentVaultProxyDAL,@@ -3321,7 +3317,8 @@ export const registerRoutes = async (appConnectionService,permissionService,kmsService,- licenseService+ licenseService,+ keyStore});const hsmConnectorService = hsmConnectorServiceFactory({diff --git a/backend/src/services/app-connection/aws/aws-connection-fns.ts b/backend/src/services/app-connection/aws/aws-connection-fns.tsindex c9ca6a3c3b..a3ad32e5cd 100644--- a/backend/src/services/app-connection/aws/aws-connection-fns.ts+++ b/backend/src/services/app-connection/aws/aws-connection-fns.ts@@ -1,4 +1,10 @@-import { AssumeRoleCommand, GetCallerIdentityCommand, STSClient, STSServiceException } from "@aws-sdk/client-sts";+import {+ AssumeRoleCommand,+ GetCallerIdentityCommand,+ STSClient,+ STSClientConfig,+ STSServiceException+} from "@aws-sdk/client-sts";import { AxiosError } from "axios";import { ProjectType } from "@app/db/schemas";@@ -65,7 +71,11 @@ export const getAwsConnectionListItem = () => {};};-export const getAwsConnectionConfig = async (appConnection: TAwsConnectionConfig, region = AWSRegion.US_EAST_1) => {+export const getAwsConnectionConfig = async (+ appConnection: TAwsConnectionConfig,+ region = AWSRegion.US_EAST_1,+ { stsRequestHandler }: { stsRequestHandler?: STSClientConfig["requestHandler"] } = {}+) => {const appCfg = getConfig();let accessKeyId: string;@@ -94,7 +104,8 @@ export const getAwsConnectionConfig = async (appConnection: TAwsConnectionConfigaccessKeyId: appCfg.INF_APP_CONNECTION_AWS_ACCESS_KEY_ID,secretAccessKey: appCfg.INF_APP_CONNECTION_AWS_SECRET_ACCESS_KEY}- : undefined // if hosting on AWS+ : undefined, // if hosting on AWS+ ...(stsRequestHandler ? { requestHandler: stsRequestHandler } : {})});// v1 (legacy) always used orgId; v2+ uses projectId when available, orgId otherwise.diff --git a/docs/documentation/platform/agent-vault/session-logs.mdx b/docs/documentation/platform/agent-vault/session-logs.mdxindex c4b8dc6962..568a47f2d5 100644--- a/docs/documentation/platform/agent-vault/session-logs.mdx+++ b/docs/documentation/platform/agent-vault/session-logs.mdx@@ -139,22 +139,16 @@ You can view a session's logs if you created the session or you're an Agent Vaul<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`.- </Step>- <Step>- Download each chunk from its `presignedGetUrl` within 5 minutes, before the URL expires.-+<Note>- If `presignedGetUrl` is null, it could be for either of the following two reasons:-- - The chunk is in a bucket that session logs no longer use- - Storage is unavailable. Read `sessionLogs.storageUnavailable` to find the reason why+ If Infisical can't read the bucket, the request fails with the error `AgentVaultSessionLogStorageUnavailable`, and the message says why.</Note></Step><Step>- Check that the SHA-256 digest of the downloaded bytes, as base64 without padding, matches `ciphertextSha256`. If the digests differ, the chunk was changed after the proxy uploaded it.+ Download each chunk from its `presignedGetUrl` within 5 minutes, before the URL expires.</Step><Step>- Decrypt the chunk with AES-256-GCM. The key is `sessionLogs.sessionKey` and the IV is the chunk's `iv`, both base64 decoded. The associated data is the SHA-256 digest of `<sessionId>|<chunkId>|v1`. The last 16 bytes of the chunk are the authentication tag.+ Decrypt the chunk with AES-256-GCM. The key is `sessionLogs.sessionKey`, base64 decoded. The first 12 bytes of the chunk are the IV, and the last 16 bytes are the authentication tag. The associated data is the SHA-256 digest of `<sessionId>|<chunkId>|v1`.</Step><Step>Parse the decrypted bytes as JSON. Each chunk holds an array of records, and `decision` holds the [outcome](#what-gets-recorded) in lowercase:@@ -191,21 +185,17 @@ You can view a session's logs if you created the session or you're an Agent Vaulconst { sessionLogs, chunks } = await res.json();for (const chunk of chunks) {- if (!chunk.presignedGetUrl) continue;const body = Buffer.from(await (await fetch(chunk.presignedGetUrl)).arrayBuffer());- const digest = createHash("sha256").update(body).digest("base64").replace(/=+$/, "");- if (digest !== chunk.ciphertextSha256) throw new Error(`Chunk ${chunk.chunkId} was changed`);-const aad = createHash("sha256").update(`${sessionId}|${chunk.chunkId}|v1`).digest();const decipher = createDecipheriv("aes-256-gcm",Buffer.from(sessionLogs.sessionKey, "base64"),- Buffer.from(chunk.iv, "base64")+ body.subarray(0, 12));decipher.setAAD(aad);decipher.setAuthTag(body.subarray(-16));- const plaintext = Buffer.concat([decipher.update(body.subarray(0, -16)), decipher.final()]);+ const plaintext = Buffer.concat([decipher.update(body.subarray(12, -16)), decipher.final()]);console.log(JSON.parse(plaintext.toString("utf8")));}@@ -215,7 +205,9 @@ You can view a session's logs if you created the session or you're an Agent VaulThe script runs outside a browser, so the bucket's CORS rule doesn't apply to it.</Note>- To receive new logs as they arrive, pass the response's `liveCursor` as `cursor` to [the endpoint that tails session logs](/api-reference/endpoints/agent-vault-session-logs/tail), then keep calling it with each response's `nextCursor`. If `hasMore` is true, call again right away. Otherwise, wait a few seconds before the next call. The same chunk can appear in more than one response, so skip any `chunkId` you've already read.+ 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.++ To export every chunk, page through [the endpoint that lists session logs](/api-reference/endpoints/agent-vault-session-logs/list). The tail is for following new logs as they arrive.</Tab></Tabs>@@ -226,7 +218,6 @@ Each request produces one record with:| Field | What it holds || --- | --- || **Time** | When the request was made |-| **Proxy** | The proxy that handled the request || **Method**, **Host**, **Path** | Where the request went, for example `POST api.github.com/repos/acme/web/issues` || **Upstream status** | The HTTP status code the API returned, such as `201`. For **Blocked** and **Error** requests, it's the status code the proxy returned, such as `403` or `502` || **Outcome** | What the proxy did with the request |@@ -261,54 +252,14 @@ You can't delete a connection while session logs use it. To delete the connectio### Changing the bucket or prefix-Infisical doesn't copy existing records when you change the bucket. You can't view the records in the old bucket in Infisical until you switch back to that bucket.--If you change only the key prefix, earlier records stay readable as long as the IAM role or user can still read the old prefix. The policy you [attached during setup](#attach-the-iam-policy) covers only the prefix you entered then, so add the new prefix to it instead of replacing it:--<Steps>- <Step>- In the **Session Logs** dialog, enter the new **Key Prefix** and select **View AWS Setup**.- </Step>- <Step>- In the policy it shows, copy the object ARN from the first statement's `Resource`, the one that ends in `/*`.- </Step>- <Step>- In the IAM console, open the inline policy you attached during setup. Turn the first statement's `Resource` into a list that holds both ARNs:-- ```json highlight={7-10}- {- "Version": "2012-10-17",- "Statement": [- {- "Effect": "Allow",- "Action": ["s3:PutObject", "s3:GetObject"],- "Resource": [- "arn:aws:s3:::<bucket>/<old-prefix>/*",- "arn:aws:s3:::<bucket>/<new-prefix>/*"- ]- },- {- "Effect": "Allow",- "Action": ["s3:ListBucket"],- "Resource": "arn:aws:s3:::<bucket>"- }- ]- }- ```-- Then, save the policy.- </Step>- <Step>- In the **Session Logs** dialog, select **Save**.- </Step>-</Steps>+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.### RetentionInfisical 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.-## Troubleshooting+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 a proxy couldn't upload some records, the session's logs show a row that says how many requests are missing. Those requests still reached their destination, but they aren't in the session log. To find out why the upload failed, check the output of each proxy the agent used.+## Troubleshooting-If the AWS connection returns an error or session logs reach their storage limit, a red dot appears next to **Settings** in the Agent Vault sidebar, and the **Settings** page shows the error.+If 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.diff --git a/docs/images/platform/agent-vault/session-logs-view.png b/docs/images/platform/agent-vault/session-logs-view.pngindex 0e09b39ae7..8ea4177274 100644Binary files a/docs/images/platform/agent-vault/session-logs-view.png and b/docs/images/platform/agent-vault/session-logs-view.png differdiff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsxindex cab6efb89c..8a02265057 100644--- a/frontend/src/hooks/api/agentVault/queries.tsx+++ b/frontend/src/hooks/api/agentVault/queries.tsx@@ -1,5 +1,6 @@-import { useRef } from "react";-import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";+import { useRef, useState } from "react";+import { InfiniteData, useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";+import axios from "axios";import { apiRequest } from "@app/config/request";import { useOrganization } from "@app/context";@@ -8,7 +9,12 @@ import { AgentVaultMemberType } from "./enums";import {createSessionLogChunkCache,decryptSessionLogPage,+ doesGapFillLeaveAHole,+ isLiveGapPossible,+ isRetryableResult,mergeSessionLogPages,+ SESSION_LOG_UPLOAD_GRACE_MS,+ sessionLogChunkKey,TAgentVaultSessionLogChunkCache} from "./sessionLogDecrypt";import {@@ -39,13 +45,16 @@ export const fetchAgentVaultProjectId = async () => {return data.projectId;};-const SESSION_LOG_PAGE_RECORDS = 200;--const SESSION_LOG_LIVE_RECORDS = 1000;+export const AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS = 15_000;-const SESSION_LOG_LIVE_MAX_READS = 10;+const SESSION_LOG_GAP_FILL_INTERVAL_MS = 60_000;-export const AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS = 15_000;+// The server's message when it can't read the bucket: the cause for an admin, a plain one for everyone else.+export const getSessionLogStorageError = (error: unknown) =>+ axios.isAxiosError<{ error?: string; message?: string }>(error) &&+ error.response?.data?.error === "AgentVaultSessionLogStorageUnavailable"+ ? (error.response.data.message ?? null)+ : null;// Every key carries the org, because Agent Vault is org-scoped through the JWT rather than through a// path parameter: without it a switch to another org would serve the previous org's data from cache.@@ -364,27 +373,40 @@ export const useGetAgentVaultSessionLogs = (// Reset during render so neither query fetches a new session into the old one's cache.const chunkCache = useRef<TAgentVaultSessionLogChunkCache | null>(null);+ const lastGapFillAt = useRef(0);+ const isGapPending = useRef(false);if (!chunkCache.current || chunkCache.current.sessionId !== sessionId) {chunkCache.current = createSessionLogChunkCache(sessionId ?? "");+ lastGapFillAt.current = 0;+ isGapPending.current = false;}+ // Set when a gap fill couldn't reach the rows already shown, so some requests may be missing. Only a history load+ // from the top that started after it can bring them back, since older pages lie below them.+ const [unfilledGap, setUnfilledGap] = useState<{ sessionId: string; foundAt: number } | null>(+ null+ );+ const historyKey = agentVaultKeys.sessionLogs(currentOrg.id, sessionId ?? "", range);const history = useInfiniteQuery({- queryKey: agentVaultKeys.sessionLogs(currentOrg.id, sessionId ?? "", range),+ queryKey: historyKey,enabled: enabled && Boolean(sessionId),initialPageParam: undefined as string | undefined,queryFn: async ({ pageParam, signal }) => {const cache = chunkCache.current as TAgentVaultSessionLogChunkCache;+ const startedAt = Date.now();const { data } = await apiRequest.get<TAgentVaultSessionLogHistoryPage>(url, {params: {- limit: SESSION_LOG_PAGE_RECORDS,...(pageParam ? { cursor: pageParam } : {}),...(range.from ? { from: range.from } : {}),...(range.to ? { to: range.to } : {})},signal});+ if (!pageParam) setUnfilledGap((gap) => (gap && gap.foundAt < startedAt ? null : gap));return decryptSessionLogPage(data, cache, signal);},+ // Trying again at once won't fix a bucket Infisical can't read; the panel offers Reload instead.+ retry: (failureCount, error) => !getSessionLogStorageError(error) && failureCount < 1,getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,placeholderData: (prev, prevQuery) =>sessionId && prevQuery?.queryKey.includes(sessionId) ? prev : undefined,@@ -393,40 +415,117 @@ export const useGetAgentVaultSessionLogs = (gcTime: 0});- const liveFrom = history.isPlaceholderData ? undefined : history.data?.pages[0]?.liveCursor;- const isRecordable = history.data?.pages[0]?.sessionLogs.isRecordable !== false;+ const isHistoryLoaded = Boolean(history.data) && !history.isPlaceholderData;+ // While session logs are off, or for a session that can't be recorded, Infisical refuses every upload.+ const canReceive =+ history.data?.pages[0]?.sessionLogs.enabled !== false &&+ history.data?.pages[0]?.sessionLogs.isRecordable !== false;const liveKey = agentVaultKeys.sessionLogsLive(currentOrg.id, sessionId ?? "", range);const live = useQuery({queryKey: liveKey,- enabled: enabled && isLive && isRecordable && Boolean(sessionId) && Boolean(liveFrom),+ enabled: enabled && isLive && canReceive && Boolean(sessionId) && isHistoryLoaded,queryFn: async ({ signal }) => {const cache = chunkCache.current as TAgentVaultSessionLogChunkCache;let arrived =queryClient.getQueryData<TAgentVaultDecryptedSessionLogPage<TAgentVaultSessionLogTailPage>>(liveKey);- let cursor = arrived?.nextCursor ?? liveFrom;- let hasMore = true;- for (let read = 0; hasMore && read < SESSION_LOG_LIVE_MAX_READS; read += 1) {- // eslint-disable-next-line no-await-in-loop- const { data } = await apiRequest.get<TAgentVaultSessionLogTailPage>(tailUrl, {- params: { limit: SESSION_LOG_LIVE_RECORDS, cursor },- signal- });- // eslint-disable-next-line no-await-in-loop- arrived = mergeSessionLogPages(arrived, await decryptSessionLogPage(data, cache, signal));- cursor = data.nextCursor;- ({ hasMore } = data);++ // The feed hands each chunk over once, so a chunk that hadn't landed yet is fetched again here, for as+ // long as it may still be uploading.+ const now = Date.now();+ const uploading = (arrived?.chunks ?? []).filter((chunk) => {+ const result = arrived?.decrypted[sessionLogChunkKey(chunk)];+ const firstSeenAt = result?.gap?.firstSeenAt;+ return (+ result &&+ isRetryableResult(result) &&+ firstSeenAt != null &&+ now < firstSeenAt + SESSION_LOG_UPLOAD_GRACE_MS+ );+ });+ if (arrived && uploading.length) {+ arrived = mergeSessionLogPages(+ arrived,+ await decryptSessionLogPage({ ...arrived, chunks: uploading }, cache, signal, {+ isTail: true+ })+ );+ }++ const lastPolledAt = arrived ? queryClient.getQueryState(liveKey)?.dataUpdatedAt : undefined;+ const { data } = await apiRequest.get<TAgentVaultSessionLogTailPage>(tailUrl, {+ params: arrived ? { cursor: arrived.nextCursor } : {},+ signal+ });++ // The feed may have dropped chunks this tab never saw, so merge in the newest page of history, which lists+ // them from the bucket. At most once a minute; a failed fill stays pending and is tried again on the next poll.+ const polledAt = Date.now();+ if (isLiveGapPossible({ lastPolledAt, now: polledAt, newChunkCount: data.chunks.length })) {+ isGapPending.current = true;}- return arrived as TAgentVaultDecryptedSessionLogPage<TAgentVaultSessionLogTailPage>;+ if (+ isGapPending.current &&+ polledAt - lastGapFillAt.current > SESSION_LOG_GAP_FILL_INTERVAL_MS+ ) {+ try {+ const { data: newest } = await apiRequest.get<TAgentVaultSessionLogHistoryPage>(url, {+ params: {+ ...(range.from ? { from: range.from } : {}),+ ...(range.to ? { to: range.to } : {})+ },+ signal+ });+ const shown = new Set(+ [+ ...(arrived?.chunks ?? []),+ ...(+ queryClient.getQueryData<+ InfiniteData<TAgentVaultDecryptedSessionLogPage<TAgentVaultSessionLogHistoryPage>>+ >(historyKey)?.pages ?? []+ ).flatMap((page) => page.chunks)+ ].map(sessionLogChunkKey)+ );+ const isGapUnfilled = doesGapFillLeaveAHole(newest, shown);+ arrived = mergeSessionLogPages(+ arrived,+ await decryptSessionLogPage({ ...newest, nextCursor: data.nextCursor }, cache, signal)+ );+ lastGapFillAt.current = polledAt;+ isGapPending.current = false;+ // Only ever set here: rows from an earlier partial fill can make a later page look complete.+ if (isGapUnfilled && sessionId) setUnfilledGap({ sessionId, foundAt: Date.now() });+ } catch (error) {+ if (signal.aborted) throw error;+ }+ }++ // The tail page goes last: the merge keeps its cursor. It can list a chunk more than once, which counts+ // toward a full feed above but is only opened once.+ const tail = {+ ...data,+ chunks: [+ ...new Map(data.chunks.map((chunk) => [sessionLogChunkKey(chunk), chunk])).values()+ ]+ };+ return mergeSessionLogPages(+ arrived,+ await decryptSessionLogPage(tail, cache, signal, { isTail: true })+ );},refetchInterval: AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS,staleTime: 0,gcTime: 0});- return { history, live, arrived: live.data };+ return {+ history,+ live,+ arrived: live.data,+ isLiveGapUnfilled: Boolean(sessionId) && unfilledGap?.sessionId === sessionId+ };};export const useListAgentVaultVariables = (accessBundleId: string, enabled = true) => {diff --git a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.tsindex 01c6520d15..7573114aaa 100644--- a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts+++ b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts@@ -4,10 +4,14 @@ import { afterEach, describe, it, vi } from "vitest";import {createSessionLogChunkCache,decryptSessionLogPage,+ doesGapFillLeaveAHole,+ isLiveGapPossible,+ mergeSessionLogPages,parseSessionLogRecords,- recordsMatchChunk+ recordsMatchChunk,+ sessionLogChunkKey} from "./sessionLogDecrypt";-import { TAgentVaultSessionLogPage } from "./types";+import { TAgentVaultSessionLogPage, TAgentVaultSessionLogRecord } from "./types";const record = {ts: "2026-09-23T10:00:00.000Z",@@ -42,32 +46,20 @@ describe("parseSessionLogRecords", () => {});describe("recordsMatchChunk", () => {- const chunk = { proxyId: "proxy-1", recordCount: 2, firstSeq: 10, lastSeq: 12 };- const records = parseSessionLogRecords([- { ...record, seq: 10 },- { ...record, seq: 12 }- ])!;+ const records = parseSessionLogRecords([record, { ...record, seq: 7 }])!;- it("accepts records that match the batch they came in, gaps in the sequence included", () => {- assert.equal(recordsMatchChunk(records, chunk), true);+ it("accepts records from the proxy the chunk is named for", () => {+ assert.equal(recordsMatchChunk(records, { proxyId: "proxy-1" }), true);});it("refuses a record that claims another proxy", () => {assert.equal(- recordsMatchChunk([records[0], { ...records[1], proxyId: "proxy-2" }], chunk),+ recordsMatchChunk([records[0], { ...records[1], proxyId: "proxy-2" }], {+ proxyId: "proxy-1"+ }),false);});-- it("refuses more or fewer records than the batch counts", () => {- assert.equal(recordsMatchChunk(records.slice(0, 1), chunk), false);- assert.equal(recordsMatchChunk([...records, { ...records[1], seq: 11 }], chunk), false);- });-- it("refuses a sequence number outside the batch's range", () => {- assert.equal(recordsMatchChunk([records[0], { ...records[1], seq: 13 }], chunk), false);- assert.equal(recordsMatchChunk([{ ...records[0], seq: 9 }, records[1]], chunk), false);- });});describe("decryptSessionLogPage", () => {@@ -76,28 +68,34 @@ describe("decryptSessionLogPage", () => {sessionLogs: {enabled: true,isRecordable: true,- sessionKey: btoa("\0".repeat(32)),- storageUnavailable: null+ sessionKey: btoa("\0".repeat(32))},chunks: [{chunkId,proxyId: "proxy-1",- proxyName: "proxy",- startedAt: record.ts,- endedAt: record.ts,- firstSeq: 0,- lastSeq: 0,- recordCount: 1,- droppedCount: 0,ciphertextBytes: 64,- iv: "qrvM3e7/ABEiM0RV",- ciphertextSha256: "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU",- presignedGetUrl: "https://bucket.example/chunk",- createdAt: "2026-09-23T10:00:05.000Z"+ presignedGetUrl: "https://bucket.example/chunk"}]};+ const key = sessionLogChunkKey(page.chunks[0]);++ // The same object Go's TestSealMatchesTheBrowserVector seals: the IV, then the ciphertext and tag.+ const sealed = Uint8Array.from(+ atob(+ "qrvM3e7/ABEiM0RVPLRwxBbgu+W68Br1N9gY1oUy8wjJxQClAtBh0NfJS1UcWOCPn3laS615sIqwFONhPIPNWRI3CA+a5tUJ7aoim0sQkE4d9gzou2mc/AWiCdToVBJPtdumA9jIzh3yAI81YPwcoDXEVnq2+7ooNNJShGdLX95itbrna/t4nFKRKSSgNzbH23eMtSMcSo72puk/2iwh4sVbTKzC2kwvbf1U6Mgd21zkIq2jDKKwhcT6mTfjPivW4FzmmkspQVMoWwANRX+QVyXzrMipZfoq5N/UcUI6rCvRUkqg+3ST5GVMelW0mjOO"+ ),+ (char) => char.charCodeAt(0)+ );+ const vectorPage: TAgentVaultSessionLogPage = {+ sessionLogs: {+ enabled: true,+ isRecordable: true,+ sessionKey: "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="+ },+ chunks: [{ ...page.chunks[0], ciphertextBytes: sealed.length }]+ };afterEach(() => {vi.unstubAllGlobals();@@ -109,7 +107,7 @@ describe("decryptSessionLogPage", () => {const cache = createSessionLogChunkCache("session-1");const first = await decryptSessionLogPage(page, cache);await decryptSessionLogPage(page, cache);- return { reason: first.decrypted[chunkId].gap?.reason, downloads: fetchMock.mock.calls.length };+ return { reason: first.decrypted[key].gap?.reason, downloads: fetchMock.mock.calls.length };};it("tells an object the bucket no longer has apart from a blocked request, and tries it again", async () => {@@ -135,48 +133,250 @@ describe("decryptSessionLogPage", () => {);});- it("tells an object changed after upload apart from one that fails to decrypt, and doesn't download it again", async () => {+ it("reports an object that won't decrypt, and doesn't download it again", async () => {assert.deepEqual(await openTwice(async () => new Response(new Uint8Array(64))), {- reason: "altered",+ reason: "gcm",downloads: 1});});- // The same vector Go's TestSealMatchesTheBrowserVector seals.+ it("stops reading an object bigger than the chunk it was listed as, without waiting for the rest", async () => {+ let isCancelled = false;+ const endless = () =>+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new Uint8Array(40));+ controller.enqueue(new Uint8Array(40));+ },+ cancel() {+ isCancelled = true;+ }+ });+ assert.deepEqual(await openTwice(async () => new Response(endless())), {+ reason: "size",+ downloads: 1+ });+ assert.equal(isCancelled, true);+ });++ it("stops reading an oversized object even where the browser reports a generic failure", async () => {+ // Chromium rejects the read with its own TypeError instead of the error the stream was aborted with.+ class ChromiumResponse extends Response {+ async arrayBuffer() {+ try {+ return await super.arrayBuffer();+ } catch {+ throw new TypeError("Failed to fetch");+ }+ }+ }+ vi.stubGlobal("Response", ChromiumResponse);+ const endless = () =>+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new Uint8Array(40));+ controller.enqueue(new Uint8Array(40));+ }+ });+ assert.deepEqual(await openTwice(async () => new ChromiumResponse(endless())), {+ reason: "size",+ downloads: 1+ });+ });++ it("never downloads an object too big to be a chunk", async () => {+ const huge: TAgentVaultSessionLogPage = {+ ...page,+ chunks: [{ ...page.chunks[0], ciphertextBytes: 9 * 1024 * 1024 }]+ };+ const fetchMock = vi.fn(async () => new Response(null));+ vi.stubGlobal("fetch", fetchMock);+ const result = await decryptSessionLogPage(huge, createSessionLogChunkCache("session-1"));+ assert.equal(result.decrypted[key].gap?.reason, "size");+ assert.equal(fetchMock.mock.calls.length, 0);+ });++ it("dates a missing chunk from when the live tail first handed it over, and only then", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(null, { status: 404 }))+ );+ const cache = createSessionLogChunkCache("session-1");+ const listed = await decryptSessionLogPage(page, cache);+ assert.equal(listed.decrypted[key].gap?.firstSeenAt, null);++ const tailed = await decryptSessionLogPage(page, cache, undefined, { isTail: true });+ const firstSeenAt = tailed.decrypted[key].gap?.firstSeenAt;+ assert.equal(typeof firstSeenAt, "number");++ const retried = await decryptSessionLogPage(page, cache, undefined, { isTail: true });+ assert.equal(retried.decrypted[key].gap?.firstSeenAt, firstSeenAt);+ });++ it("opens a chunk from a page that carries no key, with the key an earlier page did", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(null, { status: 404 }))+ );+ const cache = createSessionLogChunkCache("sess-1");+ await decryptSessionLogPage(vectorPage, cache);++ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(sealed))+ );+ const keyless = await decryptSessionLogPage(+ { ...vectorPage, sessionLogs: { ...vectorPage.sessionLogs, sessionKey: null } },+ cache+ );+ assert.equal(keyless.decrypted[key].gap, null);+ assert.equal(keyless.decrypted[key].records[0].path, "/zen");+ });+it("opens a chunk sealed with the pinned vector", async () => {- const sealed = Uint8Array.from(- atob(- "PLRwxBbgu+W68Br1N9gY1oUy8wjJxQClAtBh0NfJS1UcWOCPn3laS615sIqwFONhPIPNWRI3CA+a5tUJ7aoim0sQkE4d9gzou2mc/AWiCdToVBJPtdumA9jIzh3yAI81YPwcoDXEVnq2+7ooNNJShGdLX95itbrna/t4nFKRKSSgNzbH23eMtSMcSo72puk/2iwh4sVbTKzC2kwvbf1U6Mgd21zkIq2jDKKwhcT6mTfjPivW4FzmmkspQVMoWwANRX+QVyXzrMipZfoq5N/UcUI6rCvRUkqg+3ST5GVMelW0mjOO"- ),- (char) => char.charCodeAt(0)+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(sealed)));+ const result = await decryptSessionLogPage(vectorPage, createSessionLogChunkCache("sess-1"));++ assert.equal(result.decrypted[key].gap, null);+ assert.equal(result.decrypted[key].records[0].path, "/zen");+ });++ it("refuses a chunk whose records name a different proxy than its file", async () => {vi.stubGlobal("fetch",vi.fn(async () => new Response(sealed)));- const vectorPage: TAgentVaultSessionLogPage = {- sessionLogs: {- enabled: true,- isRecordable: true,- sessionKey: "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=",- storageUnavailable: null- },- chunks: [- {- ...page.chunks[0],- startedAt: "2026-09-16T10:31:04.221Z",- endedAt: "2026-09-16T10:31:04.221Z",- firstSeq: 1,- lastSeq: 1,- ciphertextBytes: sealed.length,- ciphertextSha256: "hCxLSvbYPNaExgeFuyNQJ/UtIKUlYGqj5YpXOeyJPSo"- }- ]+ const otherProxy = { ...vectorPage.chunks[0], proxyId: "proxy-2" };+ const result = await decryptSessionLogPage(+ { ...vectorPage, chunks: [otherProxy] },+ createSessionLogChunkCache("sess-1")+ );+ assert.equal(result.decrypted[sessionLogChunkKey(otherProxy)].gap?.reason, "mismatch");+ });++ it("keeps two proxies' chunks apart when they share a chunk id", async () => {+ const fetchMock = vi.fn(async () => new Response(null, { status: 404 }));+ vi.stubGlobal("fetch", fetchMock);+ const second = {+ ...page.chunks[0],+ proxyId: "proxy-2",+ presignedGetUrl: "https://bucket.example/other"};+ const result = await decryptSessionLogPage(+ { ...page, chunks: [page.chunks[0], second] },+ createSessionLogChunkCache("session-1")+ );+ assert.deepEqual(+ Object.keys(result.decrypted).sort(),+ [key, sessionLogChunkKey(second)].sort()+ );+ assert.equal(fetchMock.mock.calls.length, 2);+ });+});- const result = await decryptSessionLogPage(vectorPage, createSessionLogChunkCache("sess-1"));+describe("mergeSessionLogPages", () => {+ const chunk = (proxyId: string) => ({+ chunkId: "01a0a9c5-231d-7abc-8def-0123456789ab",+ proxyId,+ ciphertextBytes: 64,+ presignedGetUrl: `https://bucket.example/${proxyId}`+ });+ const decryptedPage = (proxyId: string, path: string) => ({+ sessionLogs: { enabled: true, isRecordable: true, sessionKey: null },+ chunks: [chunk(proxyId)],+ decrypted: {+ [sessionLogChunkKey(chunk(proxyId))]: {+ records: [{ ...record, proxyId, path } as TAgentVaultSessionLogRecord],+ gap: null,+ arrivedAt: null+ }+ }+ });++ it("returns the new page when there is nothing before it", () => {+ const page = decryptedPage("proxy-1", "/a");+ assert.equal(mergeSessionLogPages(undefined, page), page);+ });++ it("keeps another proxy's chunk with the same id, and lets a re-read chunk replace its earlier copy", () => {+ const merged = mergeSessionLogPages(+ mergeSessionLogPages(decryptedPage("proxy-1", "/old"), decryptedPage("proxy-2", "/b")),+ decryptedPage("proxy-1", "/new")+ );+ assert.deepEqual(+ merged.chunks.map((entry) => entry.proxyId),+ ["proxy-2", "proxy-1"]+ );+ assert.equal(merged.decrypted[sessionLogChunkKey(chunk("proxy-1"))].records[0].path, "/new");+ assert.equal(merged.decrypted[sessionLogChunkKey(chunk("proxy-2"))].records[0].path, "/b");+ });+});- assert.equal(result.decrypted[chunkId].gap, null);- assert.equal(result.decrypted[chunkId].records[0].path, "/zen");+describe("isLiveGapPossible", () => {+ const now = 1_000_000;+ it.each([+ { why: "the first poll", lastPolledAt: undefined, newChunkCount: 10, expected: false },+ {+ why: "a poll 99 seconds after the last",+ lastPolledAt: now - 99_000,+ newChunkCount: 0,+ expected: false+ },+ {+ why: "a poll 101 seconds after the last",+ lastPolledAt: now - 101_000,+ newChunkCount: 0,+ expected: true+ },+ {+ why: "a poll with 9 new chunks",+ lastPolledAt: now - 15_000,+ newChunkCount: 9,+ expected: false+ },+ {+ why: "a poll that returns a full feed",+ lastPolledAt: now - 15_000,+ newChunkCount: 10,+ expected: true+ }+ ])("reads $why as a possible gap: $expected", ({ lastPolledAt, newChunkCount, expected }) => {+ assert.equal(isLiveGapPossible({ lastPolledAt, now, newChunkCount }), expected);+ });+});++describe("doesGapFillLeaveAHole", () => {+ const chunk = (chunkId: string) => ({+ chunkId,+ proxyId: "proxy-1",+ ciphertextBytes: 100,+ presignedGetUrl: "https://bucket/x"+ });+ const shown = new Set(["proxy-1/c3"]);++ it.each([+ {+ why: "the page reaches a row already shown",+ chunks: ["c1", "c2", "c3"],+ nextCursor: "more",+ expected: false+ },+ {+ why: "the page ends before the rows shown",+ chunks: ["c1", "c2"],+ nextCursor: "more",+ expected: true+ },+ {+ why: "the page is the whole session",+ chunks: ["c1", "c2"],+ nextCursor: null,+ expected: false+ }+ ])("reads $why as a hole: $expected", ({ chunks, nextCursor, expected }) => {+ assert.equal(doesGapFillLeaveAHole({ chunks: chunks.map(chunk), nextCursor }, shown), expected);});});diff --git a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.ts b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.tsindex 1c1210e7bc..9670faa688 100644--- a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.ts+++ b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.ts@@ -11,6 +11,32 @@ import {const CHUNK_DOWNLOAD_TIMEOUT_MS = 60_000;+// The server refuses to sign an upload over this, so anything larger in the bucket is not a chunk.+const MAX_CHUNK_BYTES = 8 * 1024 * 1024;+const IV_BYTES = 12;+const TAG_BYTES = 16;++// The live tail hands a chunk over as soon as its proxy asks for an upload link, before the upload lands, so a+// tail chunk that isn't in the bucket yet is most likely still uploading rather than gone.+export const SESSION_LOG_UPLOAD_GRACE_MS = 2 * 60_000;++// Infisical's live feed keeps a session's newest 10 chunk names for 2 minutes. A poll that comes more than 100+// seconds after the last one, or returns a full feed, may have missed chunks that were trimmed or expired.+const SESSION_LOG_LIVE_GAP_MS = 100_000;+const SESSION_LOG_FEED_MAX_CHUNKS = 10;++export const isLiveGapPossible = ({+ lastPolledAt,+ now,+ newChunkCount+}: {+ lastPolledAt: number | undefined;+ now: number;+ newChunkCount: number;+}) =>+ lastPolledAt !== undefined &&+ (now - lastPolledAt > SESSION_LOG_LIVE_GAP_MS || newChunkCount >= SESSION_LOG_FEED_MAX_CHUNKS);+const AAD_VERSION = "v1";const base64ToBytes = (value: string) => {@@ -48,34 +74,58 @@ export const parseSessionLogRecords = (json: unknown): TAgentVaultSessionLogRecoreturn parsed.success ? (parsed.data as TAgentVaultSessionLogRecord[]) : null;};+// Two proxies can mint the same chunk id, so a chunk is only unique with its proxy.+export const sessionLogChunkKey = (+ chunk: Pick<TAgentVaultSessionLogChunk, "chunkId" | "proxyId">+) => `${chunk.proxyId}/${chunk.chunkId}`;++// One page of history can end before the rows already shown, which leaves older missed chunks out. If the page+// is the whole session there is nothing older to miss.+export const doesGapFillLeaveAHole = (+ newest: Pick<TAgentVaultSessionLogPage, "chunks"> & { nextCursor: string | null },+ shownChunkKeys: Set<string>+) =>+ newest.nextCursor !== null &&+ !newest.chunks.some((chunk) => shownChunkKeys.has(sessionLogChunkKey(chunk)));++// The object name carries the proxy Infisical signed the upload for, so every record inside must name it too.export const recordsMatchChunk = (records: TAgentVaultSessionLogRecord[],- chunk: Pick<TAgentVaultSessionLogChunk, "proxyId" | "recordCount" | "firstSeq" | "lastSeq">-) =>- records.length === chunk.recordCount &&- records.every(- (record) =>- record.proxyId === chunk.proxyId &&- record.seq >= chunk.firstSeq &&- record.seq <= chunk.lastSeq- );+ chunk: Pick<TAgentVaultSessionLogChunk, "proxyId">+) => records.every((record) => record.proxyId === chunk.proxyId);-const gapFor = (- chunk: TAgentVaultSessionLogChunk,- reason: TAgentVaultSessionLogGapReason-): TAgentVaultDecryptedChunk => ({+const gapFor = (reason: TAgentVaultSessionLogGapReason): TAgentVaultDecryptedChunk => ({records: [],- gap: {- chunkId: chunk.chunkId,- proxyId: chunk.proxyId,- proxyName: chunk.proxyName,- startedAt: chunk.startedAt,- reason,- recordCount: chunk.recordCount- },+ gap: { reason, firstSeenAt: null },arrivedAt: null});+class ChunkTooLargeError extends Error {}++// Stops reading past the expected size, so a huge object in the bucket can't freeze the tab.+const readCapped = async (res: Response, limit: number) => {+ if (!res.body) return res.arrayBuffer();+ let total = 0;+ // Chromium rejects the read with its own TypeError rather than the stream's error, so the cap keeps its own flag.+ let isTooLarge = false;+ const capped = res.body.pipeThrough(+ new TransformStream<Uint8Array, Uint8Array>({+ transform(part, controller) {+ total += part.byteLength;+ if (total > limit) {+ isTooLarge = true;+ controller.error(new ChunkTooLargeError());+ } else controller.enqueue(part);+ }+ })+ );+ try {+ return await new Response(capped).arrayBuffer();+ } catch (error) {+ throw isTooLarge ? new ChunkTooLargeError() : error;+ }+};+const isRetryableSessionLogGap = (reason?: TAgentVaultSessionLogGapReason) =>reason === "fetch" || reason === "missing" || reason === "refused";@@ -103,7 +153,9 @@ const openChunk = async (sessionId: string,signal?: AbortSignal): Promise<TAgentVaultDecryptedChunk> => {- if (!chunk.presignedGetUrl) return gapFor(chunk, "repointed");+ if (chunk.ciphertextBytes > MAX_CHUNK_BYTES || chunk.ciphertextBytes < IV_BYTES + TAG_BYTES) {+ return gapFor("size");+ }const download = withTimeout(signal, CHUNK_DOWNLOAD_TIMEOUT_MS);let body: ArrayBuffer;@@ -112,58 +164,61 @@ const openChunk = async (credentials: "omit",signal: download.signal});- if (!res.ok) return gapFor(chunk, res.status === 404 ? "missing" : "refused");- body = await res.arrayBuffer();+ if (!res.ok) return gapFor(res.status === 404 ? "missing" : "refused");+ body = await readCapped(res, chunk.ciphertextBytes);} catch (error) {+ if (error instanceof ChunkTooLargeError) return gapFor("size");if (signal?.aborted) throw error;- return gapFor(chunk, "fetch");+ return gapFor("fetch");} finally {download.clear();}- if (body.byteLength !== chunk.ciphertextBytes) return gapFor(chunk, "size");-- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", body));- const expected = base64ToBytes(chunk.ciphertextSha256);- if (digest.length !== expected.length || digest.some((byte, i) => byte !== expected[i])) {- return gapFor(chunk, "altered");- }+ if (body.byteLength !== chunk.ciphertextBytes) return gapFor("size");let plaintext: ArrayBuffer;try {plaintext = await crypto.subtle.decrypt({name: "AES-GCM",- iv: base64ToBytes(chunk.iv),+ iv: body.slice(0, IV_BYTES),additionalData: await buildAad(sessionId, chunk.chunkId)},key,- body+ body.slice(IV_BYTES));} catch {- return gapFor(chunk, "gcm");+ return gapFor("gcm");}try {const records = parseSessionLogRecords(JSON.parse(new TextDecoder().decode(plaintext)));- if (!records) return gapFor(chunk, "json");- if (!recordsMatchChunk(records, chunk)) return gapFor(chunk, "mismatch");+ if (!records) return gapFor("json");+ if (!recordsMatchChunk(records, chunk)) return gapFor("mismatch");return {records,gap: null,arrivedAt: null};} catch {- return gapFor(chunk, "json");+ return gapFor("json");}};export const createSessionLogChunkCache = (sessionId: string) => {let isSettled = false;+ // A tail page with nothing new carries no key, but a retry of an earlier chunk still needs it.+ let sessionKey: string | null = null;return {sessionId,keys: new Map<string, Promise<CryptoKey>>(),chunks: new Map<string, TAgentVaultDecryptedChunk>(),+ // When the live tail first handed over each chunk, so one still uploading is given time to land.+ firstSeen: new Map<string, number>(),+ sessionKey: () => sessionKey,+ rememberSessionKey: (key: string) => {+ sessionKey = key;+ },isSettled: () => isSettled,settle: () => {isSettled = true;@@ -176,13 +231,14 @@ export type TAgentVaultSessionLogChunkCache = ReturnType<typeof createSessionLogexport const decryptSessionLogPage = async <P extends TAgentVaultSessionLogPage>(page: P,cache: TAgentVaultSessionLogChunkCache,- signal?: AbortSignal+ signal?: AbortSignal,+ { isTail = false }: { isTail?: boolean } = {}): Promise<TAgentVaultDecryptedSessionLogPage<P>> => {const decrypted: Record<string, TAgentVaultDecryptedChunk> = {};- const { sessionKey } = page.sessionLogs;+ if (page.sessionLogs.sessionKey) cache.rememberSessionKey(page.sessionLogs.sessionKey);+ const sessionKey = cache.sessionKey();if (!sessionKey || !page.chunks.length) {- // Rows that could not be opened have not been shown, so the load that finally opens them is the first one.- if (!page.sessionLogs.storageUnavailable) cache.settle();+ cache.settle();return { ...page, decrypted };}@@ -197,27 +253,33 @@ export const decryptSessionLogPage = async <P extends TAgentVaultSessionLogPage>await Promise.all(page.chunks.map(async (chunk) => {- const known = cache.chunks.get(chunk.chunkId);+ const chunkKey = sessionLogChunkKey(chunk);+ const known = cache.chunks.get(chunkKey);if (known) {- decrypted[chunk.chunkId] = known;+ decrypted[chunkKey] = known;return;}- const result = key- ? await openChunk(chunk, key, cache.sessionId, signal)- : gapFor(chunk, "gcm");- // Failed downloads stay uncached so the next fetch retries with a freshly presigned URL.- if (!isRetryableResult(result)) cache.chunks.set(chunk.chunkId, result);- decrypted[chunk.chunkId] = result;- opened.push(chunk.chunkId);+ if (isTail && !cache.firstSeen.has(chunkKey)) cache.firstSeen.set(chunkKey, Date.now());+ let result = key ? await openChunk(chunk, key, cache.sessionId, signal) : gapFor("gcm");+ if (result.gap && isTail) {+ result = {+ ...result,+ gap: { ...result.gap, firstSeenAt: cache.firstSeen.get(chunkKey) ?? null }+ };+ }+ // Failed downloads stay uncached so a later read retries them.+ if (!isRetryableResult(result)) cache.chunks.set(chunkKey, result);+ decrypted[chunkKey] = result;+ opened.push(chunkKey);}));if (cache.isSettled()) {const arrivedAt = Date.now();- opened.forEach((chunkId) => {- const stamped = { ...decrypted[chunkId], arrivedAt };- decrypted[chunkId] = stamped;- if (cache.chunks.has(chunkId)) cache.chunks.set(chunkId, stamped);+ opened.forEach((chunkKey) => {+ const stamped = { ...decrypted[chunkKey], arrivedAt };+ decrypted[chunkKey] = stamped;+ if (cache.chunks.has(chunkKey)) cache.chunks.set(chunkKey, stamped);});}cache.settle();@@ -230,10 +292,13 @@ export const mergeSessionLogPages = <P extends TAgentVaultSessionLogPage>(page: TAgentVaultDecryptedSessionLogPage<P>): TAgentVaultDecryptedSessionLogPage<P> => {if (!previous) return page;- const reread = new Set(page.chunks.map((chunk) => chunk.chunkId));+ const reread = new Set(page.chunks.map(sessionLogChunkKey));return {...page,- chunks: [...previous.chunks.filter((chunk) => !reread.has(chunk.chunkId)), ...page.chunks],+ chunks: [+ ...previous.chunks.filter((chunk) => !reread.has(sessionLogChunkKey(chunk))),+ ...page.chunks+ ],decrypted: { ...previous.decrypted, ...page.decrypted }};};diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex 67319e009b..a68cd01fe8 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -205,7 +205,6 @@ export type TAgentVaultSession = {revokedAt: string | null;createdAt: string;accessBundles: TAgentVaultSessionAccessBundle[];- recentSessionLogCounts: { recordedCount: number; droppedCount: number };};export type TAgentVaultMintedSession = {@@ -301,7 +300,6 @@ export type TAgentVaultSessionLogSettings = {};export type TAgentVaultSessionLogHealth = {- isStorageFull: boolean;connectionError: string | null;};@@ -332,28 +330,14 @@ export type TUpdateAgentVaultSessionLogSettingsDTO = {export type TAgentVaultSessionLogChunk = {chunkId: string;proxyId: string;- proxyName: string;- startedAt: string;- endedAt: string;- firstSeq: number;- lastSeq: number;- recordCount: number;- droppedCount: number;ciphertextBytes: number;- iv: string;- ciphertextSha256: string;- presignedGetUrl: string | null;- createdAt: string;+ presignedGetUrl: string;};export type TAgentVaultSessionLog = {enabled: boolean;isRecordable: boolean;sessionKey: string | null;- storageUnavailable: {- reason: "no-connection" | "connection-unusable";- message: string | null;- } | null;};export type TAgentVaultSessionLogPage = {@@ -363,12 +347,10 @@ export type TAgentVaultSessionLogPage = {export type TAgentVaultSessionLogHistoryPage = TAgentVaultSessionLogPage & {nextCursor: string | null;- liveCursor: string;};export type TAgentVaultSessionLogTailPage = TAgentVaultSessionLogPage & {nextCursor: string;- hasMore: boolean;};export type TAgentVaultSessionLogRecord = {@@ -390,26 +372,14 @@ export type TAgentVaultSessionLogGapReason =| "missing"| "refused"| "size"- | "altered"| "gcm"| "json"- | "mismatch"- | "repointed";+ | "mismatch";export type TAgentVaultSessionLogGap = {- chunkId: string;- proxyId: string;- proxyName: string;- startedAt: string;reason: TAgentVaultSessionLogGapReason;- recordCount: number;-};--export type TAgentVaultSessionLogDrop = {- chunkId: string;- proxyId: string;- startedAt: string;- droppedCount: number;+ // When this browser first saw the chunk on the live tail; null for chunks listed from the bucket.+ firstSeenAt: number | null;};export type TAgentVaultDecryptedChunk = {diff --git a/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.test.ts b/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.test.tsindex a9e1c92a92..8d557655c3 100644--- a/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.test.ts+++ b/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.test.ts@@ -4,7 +4,7 @@ import { describe, it } from "vitest";import { TAgentVaultDecryptedChunk, TAgentVaultDecryptedSessionLogPage } from "./types";import { buildSessionLogTimeline } from "./useAgentVaultSessionLogTimeline";-const createdAt = Date.parse("2026-09-29T10:00:00.000Z");+const firstSeenAt = Date.parse("2026-09-29T10:00:00.000Z");const chunkId = "01a0a9c5-231d-7abc-8def-0123456789ab";const record = {@@ -22,50 +22,74 @@ const record = {} as TAgentVaultDecryptedChunk["records"][number];const pageWith = (result: TAgentVaultDecryptedChunk): TAgentVaultDecryptedSessionLogPage => ({- sessionLogs: { enabled: true, isRecordable: true, sessionKey: null, storageUnavailable: null },+ sessionLogs: { enabled: true, isRecordable: true, sessionKey: null },chunks: [{chunkId,proxyId: "proxy-1",- proxyName: "proxy",- startedAt: record.ts,- endedAt: record.ts,- firstSeq: 0,- lastSeq: 0,- recordCount: 1,- droppedCount: 0,ciphertextBytes: 64,- iv: "qrvM3e7/ABEiM0RV",- ciphertextSha256: "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU",- presignedGetUrl: "https://bucket.example/chunk",- createdAt: new Date(createdAt).toISOString()+ presignedGetUrl: "https://bucket.example/chunk"}],- decrypted: { [chunkId]: result }+ decrypted: { [`proxy-1/${chunkId}`]: result }});+// A tail chunk the bucket didn't have yet when this browser first saw it.const missing: TAgentVaultDecryptedChunk = {records: [],- gap: {- chunkId,- proxyId: "proxy-1",- proxyName: "proxy",- startedAt: record.ts,- reason: "missing",- recordCount: 1- },+ gap: { reason: "missing", firstSeenAt },arrivedAt: null};describe("buildSessionLogTimeline", () => {+ it("shows both proxies' requests when their chunks share an id", () => {+ const chunkFor = (proxyId: string) => ({+ chunkId,+ proxyId,+ ciphertextBytes: 64,+ presignedGetUrl: `https://bucket.example/${proxyId}`+ });+ const opened = (proxyId: string): TAgentVaultDecryptedChunk => ({+ records: [{ ...record, proxyId }],+ gap: null,+ arrivedAt: null+ });+ const timeline = buildSessionLogTimeline(+ [+ {+ ...pageWith(missing),+ chunks: [chunkFor("proxy-1"), chunkFor("proxy-2")],+ decrypted: {+ [`proxy-1/${chunkId}`]: opened("proxy-1"),+ [`proxy-2/${chunkId}`]: opened("proxy-2")+ }+ }+ ],+ firstSeenAt+ );+ assert.deepEqual(timeline.records.map((entry) => entry.proxyId).sort(), ["proxy-1", "proxy-2"]);+ });+it("holds a chunk that isn't in the bucket yet as still uploading while it is recent", () => {- const timeline = buildSessionLogTimeline([pageWith(missing)], createdAt + 30_000);+ const timeline = buildSessionLogTimeline([pageWith(missing)], firstSeenAt + 30_000);assert.deepEqual(timeline.gaps, []);assert.equal(timeline.hasUploadingChunks, true);});it("reports it as missing once two minutes have passed, so nothing waits on it forever", () => {- const timeline = buildSessionLogTimeline([pageWith(missing)], createdAt + 3 * 60_000);+ const timeline = buildSessionLogTimeline([pageWith(missing)], firstSeenAt + 3 * 60_000);+ assert.deepEqual(+ timeline.gaps.map((gap) => gap.reason),+ ["missing"]+ );+ assert.equal(timeline.hasUploadingChunks, false);+ });++ it("reports a chunk listed from the bucket as missing at once, since it was already uploaded", () => {+ const timeline = buildSessionLogTimeline(+ [pageWith({ ...missing, gap: { reason: "missing", firstSeenAt: null } })],+ firstSeenAt + 30_000+ );assert.deepEqual(timeline.gaps.map((gap) => gap.reason),["missing"]@@ -76,7 +100,7 @@ describe("buildSessionLogTimeline", () => {it("reports it once even when the live tail and a history reload both hold it", () => {const timeline = buildSessionLogTimeline([pageWith(missing), pageWith(missing)],- createdAt + 3 * 60_000+ firstSeenAt + 3 * 60_000);assert.equal(timeline.gaps.length, 1);assert.equal(timeline.hasUploadingChunks, false);@@ -85,7 +109,7 @@ describe("buildSessionLogTimeline", () => {it("never holds back a chunk that downloaded", () => {const timeline = buildSessionLogTimeline([pageWith({ records: [record], gap: null, arrivedAt: null })],- createdAt + 30_000+ firstSeenAt + 30_000);assert.equal(timeline.records.length, 1);assert.equal(timeline.hasUploadingChunks, false);@@ -94,10 +118,38 @@ describe("buildSessionLogTimeline", () => {it("lets a download that landed replace an earlier miss", () => {const timeline = buildSessionLogTimeline([pageWith(missing), pageWith({ records: [record], gap: null, arrivedAt: null })],- createdAt + 30_000+ firstSeenAt + 30_000);assert.equal(timeline.records.length, 1);assert.deepEqual(timeline.gaps, []);assert.equal(timeline.hasUploadingChunks, false);});++ it("leaves records after a date range out of the record limit", () => {+ const at = Date.parse(record.ts);+ const after = new Date(at + 5 * 60_000).toISOString();+ const records = [+ ...Array.from({ length: 100_001 }, (_, seq) => ({ ...record, seq, ts: after })),+ record+ ];+ const timeline = buildSessionLogTimeline(+ [pageWith({ records, gap: null, arrivedAt: null })],+ firstSeenAt,+ { from: at - 60_000, to: at + 60_000 }+ );+ assert.deepEqual(timeline.records, [record]);+ assert.equal(timeline.isTruncated, false);+ assert.equal(timeline.hasOpenedRecords, true);+ });++ it("still counts records outside the range as opened", () => {+ const at = Date.parse(record.ts);+ const timeline = buildSessionLogTimeline(+ [pageWith({ records: [record], gap: null, arrivedAt: null })],+ firstSeenAt,+ { from: at + 60_000, to: at + 120_000 }+ );+ assert.deepEqual(timeline.records, []);+ assert.equal(timeline.hasOpenedRecords, true);+ });});diff --git a/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.ts b/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.tsindex 1bd6b675bb..bc79f00083 100644--- a/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.ts+++ b/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.ts@@ -1,10 +1,13 @@import { useMemo } from "react";-import { isRetryableResult } from "./sessionLogDecrypt";+import {+ isRetryableResult,+ SESSION_LOG_UPLOAD_GRACE_MS,+ sessionLogChunkKey+} from "./sessionLogDecrypt";import {TAgentVaultDecryptedChunk,TAgentVaultDecryptedSessionLogPage,- TAgentVaultSessionLogDrop,TAgentVaultSessionLogGap,TAgentVaultSessionLogRecord} from "./types";@@ -13,44 +16,37 @@ const AGENT_VAULT_SESSION_LOG_MAX_RECORDS = 100_000;const AGENT_VAULT_SESSION_LOG_MAX_LOADED_BYTES = 64 * 1024 * 1024;-// A chunk is listed as soon as its proxy registers it, before its upload lands, so a chunk this recent that-// isn't in the bucket yet is most likely still uploading rather than gone.-const CHUNK_UPLOAD_GRACE_MS = 2 * 60_000;-export const sessionLogRecordKey = (record: TAgentVaultSessionLogRecord) =>`${record.proxyId}-${record.seq}-${record.ts}`;type TAgentVaultSessionLogTimeline = {records: TAgentVaultSessionLogRecord[];+ hasOpenedRecords: boolean;gaps: TAgentVaultSessionLogGap[];- drops: TAgentVaultSessionLogDrop[];arrivals: Map<string, number>;isTruncated: boolean;isOverByteBudget: boolean;hasUploadingChunks: boolean;};+type TSessionLogTimeRange = { from: number; to: number };+export const buildSessionLogTimeline = (pages: TAgentVaultDecryptedSessionLogPage[] | undefined,- now: number+ now: number,+ range?: TSessionLogTimeRange): TAgentVaultSessionLogTimeline => {const opened = new Map<string, TAgentVaultDecryptedChunk>();const openedBytes = new Map<string, number>();- const openedAt = new Map<string, number>();- const dropsByChunk = new Map<string, TAgentVaultSessionLogDrop>();(pages ?? []).forEach((page) =>page.chunks.forEach((chunk) => {- const result = page.decrypted[chunk.chunkId];+ const chunkKey = sessionLogChunkKey(chunk);+ const result = page.decrypted[chunkKey];if (!result) return;- if (chunk.droppedCount > 0) {- const { chunkId, proxyId, startedAt, droppedCount } = chunk;- dropsByChunk.set(chunkId, { chunkId, proxyId, startedAt, droppedCount });- }- const known = opened.get(chunk.chunkId);+ const known = opened.get(chunkKey);if (known && (!isRetryableResult(known) || isRetryableResult(result))) return;- opened.set(chunk.chunkId, result);- openedBytes.set(chunk.chunkId, chunk.ciphertextBytes);- openedAt.set(chunk.chunkId, Date.parse(chunk.createdAt));+ opened.set(chunkKey, result);+ openedBytes.set(chunkKey, chunk.ciphertextBytes);}));@@ -59,17 +55,28 @@ export const buildSessionLogTimeline = (const arrivals = new Map<string, number>();let loadedBytes = 0;let hasUploadingChunks = false;+ let hasOpenedRecords = false;- opened.forEach((result, chunkId) => {- records.push(...result.records);- if (!result.gap) loadedBytes += openedBytes.get(chunkId) ?? 0;+ // A date range also lists the chunks just after it, so records outside it are left out before the record limit.+ const isInRange = (record: TAgentVaultSessionLogRecord) => {+ if (!range) return true;+ const at = Date.parse(record.ts);+ return at >= range.from && at <= range.to;+ };++ opened.forEach((result, chunkKey) => {+ if (result.records.length) hasOpenedRecords = true;+ const inRange = range ? result.records.filter(isInRange) : result.records;+ records.push(...inRange);+ if (!result.gap) loadedBytes += openedBytes.get(chunkKey) ?? 0;if (result.arrivedAt !== null) {const { arrivedAt } = result;- result.records.forEach((record) => arrivals.set(sessionLogRecordKey(record), arrivedAt));+ inRange.forEach((record) => arrivals.set(sessionLogRecordKey(record), arrivedAt));}const isUploading =result.gap?.reason === "missing" &&- now < (openedAt.get(chunkId) ?? 0) + CHUNK_UPLOAD_GRACE_MS;+ result.gap.firstSeenAt !== null &&+ now < result.gap.firstSeenAt + SESSION_LOG_UPLOAD_GRACE_MS;if (isUploading) hasUploadingChunks = true;else if (result.gap) gaps.push(result.gap);});@@ -86,8 +93,8 @@ export const buildSessionLogTimeline = (const isOverByteBudget = loadedBytes >= AGENT_VAULT_SESSION_LOG_MAX_LOADED_BYTES;return {records: records.slice(0, AGENT_VAULT_SESSION_LOG_MAX_RECORDS),+ hasOpenedRecords,gaps,- drops: [...dropsByChunk.values()],arrivals,isTruncated: records.length > AGENT_VAULT_SESSION_LOG_MAX_RECORDS || isOverByteBudget,isOverByteBudget,@@ -97,6 +104,18 @@ export const buildSessionLogTimeline = (export const useAgentVaultSessionLogTimeline = (pages: TAgentVaultDecryptedSessionLogPage[] | undefined,- now: number+ now: number,+ rangeFrom?: number,+ rangeTo?: number): TAgentVaultSessionLogTimeline =>- useMemo(() => buildSessionLogTimeline(pages, now), [pages, now]);+ useMemo(+ () =>+ buildSessionLogTimeline(+ pages,+ now,+ rangeFrom !== undefined && rangeTo !== undefined+ ? { from: rangeFrom, to: rangeTo }+ : undefined+ ),+ [pages, now, rangeFrom, rangeTo]+ );diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsxindex 852cf033c6..1b23039e78 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx@@ -38,15 +38,14 @@ export const AgentVaultNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Subm{ label: "Proxies", icon: Server, pathSuffix: "proxies" }];- let settingsDot: NavItem["dotVariant"];- if (+ let settingsAlert: NavItem["alertVariant"];+ if (sessionLogHealth?.connectionError) settingsAlert = "danger";+ else if (sessionLogSettings?.bucket &&(!areAgentVaultSessionLogsOn(sessionLogSettings) ||isAgentVaultSessionLogPlanLapsed(sessionLogSettings, subscription)))- settingsDot = "warning";- else if (sessionLogHealth?.isStorageFull || sessionLogHealth?.connectionError)- settingsDot = "danger";+ settingsAlert = "warning";const administrationItems: NavItem[] = isAdmin? [@@ -57,7 +56,7 @@ export const AgentVaultNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: SubmactiveMatch: /\/access-management|\/groups\/|\/identities\/|\/members\/|\/roles\//},{ label: "Audit Logs", icon: FileText, pathSuffix: "audit-logs" },- { label: "Settings", icon: Settings, pathSuffix: "settings", dotVariant: settingsDot }+ { label: "Settings", icon: Settings, pathSuffix: "settings", alertVariant: settingsAlert }]: [];diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsxindex 706116efff..e3b83db620 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx@@ -1,5 +1,5 @@import { Link, useLocation } from "@tanstack/react-router";-import { ChevronRight } from "lucide-react";+import { ChevronRight, CircleAlertIcon, TriangleAlertIcon } from "lucide-react";import { twMerge } from "tailwind-merge";import {@@ -15,12 +15,14 @@ import { isOrgScopedProduct } from "@app/helpers/project";import type { NavItem, Submenu } from "./types";import { PROJECT_TYPE_PATH } from "./types";-const NavDot = ({ variant }: { variant: NonNullable<NavItem["dotVariant"]> }) => (+// Important, because the menu button sizes every icon inside it and recolors them while the item is active.+const NavAlertIcon = ({ variant }: { variant: NonNullable<NavItem["alertVariant"]> }) => (<span className="ml-auto flex shrink-0">- <span- aria-hidden- className={twMerge("size-2 rounded-full", variant === "danger" ? "bg-danger" : "bg-warning")}- />+ {variant === "danger" ? (+ <CircleAlertIcon aria-hidden className="size-3.5! text-danger!" />+ ) : (+ <TriangleAlertIcon aria-hidden className="size-3.5! text-warning!" />+ )}<span className="sr-only">Needs attention</span></span>);@@ -80,11 +82,11 @@ export const ProjectNavLink = ({{item.badgeCount}</Badge>)}- {item.dotVariant && <NavDot variant={item.dotVariant} />}+ {item.alertVariant && <NavAlertIcon variant={item.alertVariant} />}<ChevronRightclassName={twMerge("size-4 opacity-50",- !item.badgeCount && !item.dotVariant && "ml-auto"+ !item.badgeCount && !item.alertVariant && "ml-auto")}/></SidebarMenuButton>@@ -121,7 +123,7 @@ export const ProjectNavLink = ({{item.badgeCount}</Badge>)}- {item.dotVariant && <NavDot variant={item.dotVariant} />}+ {item.alertVariant && <NavAlertIcon variant={item.alertVariant} />}</Link></SidebarMenuButton></SidebarMenuItem>diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/types.ts b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/types.tsindex 3dbb2d9997..5c84ab4bdd 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/types.ts+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/types.ts@@ -34,7 +34,7 @@ export type NavItem = {activeMatch?: RegExp | ((pathname: string, search: Record<string, unknown>) => boolean);badgeCount?: number;badgeVariant?: "warning" | "danger" | "pam";- dotVariant?: "warning" | "danger";+ alertVariant?: "warning" | "danger";hidden?: boolean;submenu?: Submenu;/** Query params to append to the link and use for active state matching */diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsxindex 0e9a0f3a1e..8875b01c7d 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx@@ -96,7 +96,6 @@ import { RevokeSessionDialog } from "./components/RevokeSessionDialog";import { SessionCreatedDialog } from "./components/SessionCreatedDialog";import { SessionDetailSheet } from "./components/SessionDetailSheet";import { SessionExpiry } from "./components/SessionExpiry";-import { SessionLogLossIndicator } from "./components/SessionLogLossIndicator";import { SESSION_STATUS_PRESENTATION, SessionStatusBadge } from "./components/SessionStatusBadge";const STATUS_OPTIONS = [@@ -193,18 +192,6 @@ export const AgentVaultSessionsPage = () => {/><div className="flex flex-col gap-8">- {sessionLogHealth?.isStorageFull &&- sessionLogSettings &&- areAgentVaultSessionLogsOn(sessionLogSettings) && (- <Alert variant="danger">- <CircleAlertIcon />- <AlertDescription>- Session logs have reached their limit for this organization. Contact Infisical- support.- </AlertDescription>- </Alert>- )}-{sessionLogHealth?.connectionError &&sessionLogSettings &&areAgentVaultSessionLogsOn(sessionLogSettings) &&@@ -268,7 +255,7 @@ export const AgentVaultSessionsPage = () => {</Alert>)}- {isAdmin && <SessionLogReadAccessAlert />}+ {isAdmin && !sessionLogHealth?.connectionError && <SessionLogReadAccessAlert />}<Card><CardHeader>@@ -472,7 +459,6 @@ export const AgentVaultSessionsPage = () => {</TableCell><TableCell variant="action"><div className="flex items-center justify-end gap-1">- <SessionLogLossIndicator counts={session.recentSessionLogCounts} /><Tooltip><TooltipTrigger asChild><IconButtondiff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsxindex 08d91989ce..af0bad9751 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx@@ -26,7 +26,6 @@ import { TAgentVaultSession } from "@app/hooks/api/agentVault/types";import { useAgentVaultSheetState } from "@app/hooks/useAgentVaultSheetState";import { SessionExpiry } from "./SessionExpiry";-import { SessionLogLossIndicator } from "./SessionLogLossIndicator";import { SessionLogsPanel } from "./SessionLogsPanel";import { SessionStatusBadge } from "./SessionStatusBadge";@@ -157,7 +156,6 @@ export const SessionDetailSheet = ({ session, isPending = false, onRevoke }: Pro<SessionStatusBadge status={session.status} /></Detail></div>- <SessionLogLossIndicator counts={session.recentSessionLogCounts} side="left" />{session.status === AgentVaultSessionStatus.Active && (<Buttonvariant="danger"diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogLossIndicator.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogLossIndicator.tsxdeleted file mode 100644index a7253086cc..0000000000--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogLossIndicator.tsx+++ /dev/null@@ -1,33 +0,0 @@-import { ComponentProps } from "react";-import { TriangleAlertIcon } from "lucide-react";--import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";-import { TAgentVaultSession } from "@app/hooks/api/agentVault/types";--const LOSS_SHARE_THRESHOLD = 0.05;--export const SessionLogLossIndicator = ({- counts,- side-}: {- counts: TAgentVaultSession["recentSessionLogCounts"];- side?: ComponentProps<typeof TooltipContent>["side"];-}) => {- const total = counts.recordedCount + counts.droppedCount;- if (!total || counts.droppedCount / total < LOSS_SHARE_THRESHOLD) return null;-- const message = `Failed to record ${counts.droppedCount.toLocaleString()} ${counts.droppedCount === 1 ? "request" : "requests"} in the last 24 hours. Check the proxy's logs for details.`;-- return (- <Tooltip>- <TooltipTrigger asChild>- <span aria-label={message} className="flex text-warning">- <TriangleAlertIcon className="size-4" />- </span>- </TooltipTrigger>- <TooltipContent side={side} className="max-w-sm">- {message}- </TooltipContent>- </Tooltip>- );-};diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsxindex 2f9834769b..4a6e5ca075 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx@@ -4,7 +4,6 @@ import {ArrowRightIcon,CircleHelpIcon,CircleXIcon,- InfoIcon,KeyRoundIcon,type LucideIcon,PlusIcon,@@ -99,20 +98,11 @@ export const hostPatternFor = (record: TAgentVaultSessionLogRecord) => {type Props = {record: TAgentVaultSessionLogRecord;arrivedAt?: number;- proxyName?: string;- showProxy: boolean;accessBundleName?: string;onAddService?: () => void;};-export const SessionLogRow = ({- record,- arrivedAt,- proxyName,- showProxy,- accessBundleName,- onAddService-}: Props) => {+export const SessionLogRow = ({ record, arrivedAt, accessBundleName, onAddService }: Props) => {const [isArriving, setIsArriving] = useState(false);useEffect(() => {@@ -160,13 +150,6 @@ export const SessionLogRow = ({</TooltipContent></Tooltip></TableCell>- {showProxy && (- <TableCell className="text-xs text-muted">- <span className="block truncate" title={proxyName}>- {proxyName}- </span>- </TableCell>- )}<TableCell className="font-mono text-xs">{record.method}</TableCell><TableCell>{record.service ? (@@ -225,29 +208,3 @@ export const SessionLogRow = ({</TableRow>);};--export const SessionLogDropRow = ({- droppedCount,- columnCount-}: {- droppedCount: number;- columnCount: number;-}) => (- <TableRow className="bg-neutral/5 hover:bg-neutral/5">- <TableCell colSpan={columnCount} className="text-xs text-muted">- <span className="flex items-center justify-center gap-2">- Something went wrong while recording {droppedCount.toLocaleString()}{" "}- {droppedCount === 1 ? "request" : "requests"}- <Tooltip>- <TooltipTrigger asChild>- <InfoIcon aria-label="Why these requests are missing" className="size-3.5 shrink-0" />- </TooltipTrigger>- <TooltipContent className="max-w-sm">- These requests went through as normal, but the proxy couldn't save them to the- session log.- </TooltipContent>- </Tooltip>- </span>- </TableCell>- </TableRow>-);diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsxindex 4363a42c51..fb6772f5f5 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx@@ -3,7 +3,6 @@ import { Link } from "@tanstack/react-router";import { useVirtualizer } from "@tanstack/react-virtual";import { format } from "date-fns";import { SearchIcon, TriangleAlertIcon, XIcon } from "lucide-react";-import { twMerge } from "tailwind-merge";import { AgentVaultSessionLogUpgradeModal } from "@app/components/agent-vault/AgentVaultSessionLogUpgradeModal";import { ServiceSheet } from "@app/components/agent-vault/service-sheet";@@ -38,10 +37,12 @@ import { useOrganization, useProjectPermission, useSubscription } from "@app/conimport {AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS,AgentVaultSessionLogDecision,+ getSessionLogStorageError,sessionLogRecordKey,useAgentVaultSessionLogTimeline,useGetAgentVaultSessionLogs} from "@app/hooks/api/agentVault";+import { sessionLogChunkKey } from "@app/hooks/api/agentVault/sessionLogDecrypt";import {TAgentVaultSession,TAgentVaultSessionLogGapReason@@ -49,26 +50,22 @@ import {import { ProjectMembershipRole } from "@app/hooks/api/roles/types";import { LiveState, LiveStateBadge, LiveStatusRow } from "./LiveStatusRow";-import {- DECISION_PRESENTATION,- hostPatternFor,- SessionLogDropRow,- SessionLogRow-} from "./SessionLogRow";+import { DECISION_PRESENTATION, hostPatternFor, SessionLogRow } from "./SessionLogRow";import {chunkIdTime,groupSessionLogGaps,- interleaveSessionLogDrops,matchesSessionLogSearch,sessionLogSearchTerm} from "./SessionLogsPanel.utils";import { useNewRequestsCounter } from "./useNewRequestsCounter";import { useSessionLogsLiveTail } from "./useSessionLogsLiveTail";-const ALL_PROXIES = "all";-const FILTER_SEARCH_STEP = 5000;+// A walk back that finds nothing readable this many pages in a row pauses, so a bucket that refuses older+// chunks can't pull the whole session.+const EMPTY_PAGE_STEP = 5;+const UPLOAD_RECHECK_MS = 15_000;const SESSION_LOG_ROW_HEIGHT = 41;@@ -76,17 +73,12 @@ const SESSION_LOG_ROW_HEIGHT = 41;type DecisionFilter = "all" | AgentVaultSessionLogDecision;const GAP_EXPLANATION: Record<TAgentVaultSessionLogGapReason, { one: string; many: string }> = {- repointed: {- one: "is stored in a bucket this project no longer uses",- many: "are stored in a bucket this project no longer uses"- },fetch: { one: "could not be read from the bucket", many: "could not be read from the bucket" },- missing: { one: "is no longer in the bucket", many: "are no longer in the bucket" },+ missing: { one: "isn't in the bucket", many: "aren't in the bucket" },refused: { one: "was refused by the bucket", many: "were refused by the bucket" },- size: { one: "is stored at the wrong size", many: "are stored at the wrong size" },- altered: {- one: "was changed after it was uploaded",- many: "were changed after they were uploaded"+ size: {+ one: "doesn't match what the proxy uploaded",+ many: "don't match what the proxy uploaded"},gcm: { one: "could not be decrypted", many: "could not be decrypted" },json: {@@ -94,32 +86,12 @@ const GAP_EXPLANATION: Record<TAgentVaultSessionLogGapReason, { one: string; manmany: "were decrypted but could not be read"},mismatch: {- one: "doesn't match the proxy and batch that sent it",- many: "don't match the proxy and batch that sent them"+ one: "holds requests from a different proxy",+ many: "hold requests from a different proxy"}};-// Every proxy that has sent this session a chunk, kept once seen so the proxy filter doesn't lose-// options when a time range reloads the pages.-const useSeenProxyNames = (- sessionId: string,- pages: { chunks: { proxyId: string; proxyName: string }[] }[] | undefined-) => {- const [seen, setSeen] = useState({ sessionId, names: new Map<string, string>() });- const names = seen.sessionId === sessionId ? seen.names : new Map<string, string>();- const unseen = (pages ?? [])- .flatMap((page) => page.chunks)- .filter((chunk) => !names.has(chunk.proxyId));- if (seen.sessionId !== sessionId || unseen.length) {- const next = new Map(names);- unseen.forEach((chunk) => {- if (!next.has(chunk.proxyId)) next.set(chunk.proxyId, chunk.proxyName);- });- setSeen({ sessionId, names: next });- return next;- }- return names;-};+const COLUMN_COUNT = 7;type Props = {session: TAgentVaultSession;@@ -143,19 +115,13 @@ export const SessionLogsPanel = ({ session }: Props) => {const [search, setSearch] = useState("");const [decisionFilter, setDecisionFilter] = useState<DecisionFilter>("all");- const [proxyFilter, setProxyFilter] = useState(ALL_PROXIES);const { range, applyRange, isActive, canTail, isLive, isPausedForBudget, pauseForBudget } =useSessionLogsLiveTail(session);- const { history, live, arrived } = useGetAgentVaultSessionLogs(session.id, {+ const { history, live, arrived, isLiveGapUnfilled } = useGetAgentVaultSessionLogs(session.id, {isLive,from: range?.startDate,to: range?.endDate});- let liveState: LiveState | null = null;- if (canTail && isPausedForBudget) liveState = "paused";- else if (isLive && live.isError) liveState = "reconnecting";- else if (isLive && !isActive) liveState = "ended";- else if (isLive) liveState = "live";const retryLive = () => live.refetch().catch(() => {});const {data,@@ -176,15 +142,29 @@ export const SessionLogsPanel = ({ session }: Props) => {return arrived ? [arrived, ...data.pages] : data.pages;}, [data, arrived]);const [now, setNow] = useState(() => Date.now());- const { records, gaps, drops, arrivals, isTruncated, isOverByteBudget, hasUploadingChunks } =- useAgentVaultSessionLogTimeline(pages, now);- // While a chunk may still be uploading, the clock keeps moving so it turns into a missing gap once its- // grace runs out. The live tail already rereads recent chunks; otherwise nothing would, so history reloads.+ const {+ records,+ hasOpenedRecords,+ gaps,+ arrivals,+ isTruncated,+ isOverByteBudget,+ hasUploadingChunks+ } = useAgentVaultSessionLogTimeline(+ pages,+ now,+ range?.startDate.getTime(),+ range?.endDate.getTime()+ );+ // While a chunk from the live tail may still be uploading, the clock keeps moving so it turns into a missing+ // gap once its grace runs out. A live poll retries the chunk itself, but polling stops in a hidden tab and after+ // the session ends; then history reloads instead, since the bucket listing has the chunk once it lands.useEffect(() => {if (!hasUploadingChunks) return undefined;const timer = setTimeout(() => {setNow(Date.now());- if (!isLive) refetch({ cancelRefetch: false }).catch(() => {});+ if (!isLive || document.visibilityState === "hidden")+ refetch({ cancelRefetch: false }).catch(() => {});}, UPLOAD_RECHECK_MS);return () => clearTimeout(timer);}, [hasUploadingChunks, isLive, now, refetch]);@@ -193,99 +173,84 @@ export const SessionLogsPanel = ({ session }: Props) => {const isEnabled = pages?.[0]?.sessionLogs.enabled ?? false;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.+ const isWatching = isLive && isEnabled && isRecordable;+ let liveState: LiveState | null = null;+ if (canTail && isPausedForBudget) liveState = "paused";+ else if (isWatching && live.isError) liveState = "reconnecting";+ else if (isWatching && !isActive) liveState = "ended";+ else if (isWatching) liveState = "live";const hasChunks = (pages ?? []).some((page) => page.chunks.length > 0);- const storageUnavailable =- data?.pages.find((page) => page.sessionLogs.storageUnavailable)?.sessionLogs- .storageUnavailable ?? null;-- const proxyNames = useSeenProxyNames(session.id, pages);- const proxies = [...proxyNames.entries()].map(([id, name]) => ({ id, name }));+ // Only without data: a failed reload or older page keeps the rows already on screen.+ const storageError = data ? null : getSessionLogStorageError(history.error);const visible = useMemo(() =>records.filter((record) => {- if (range) {- const at = Date.parse(record.ts);- if (at < range.startDate.getTime() || at > range.endDate.getTime()) return false;- }if (decisionFilter !== "all" && record.decision !== decisionFilter) return false;- if (proxyFilter !== ALL_PROXIES && record.proxyId !== proxyFilter) return false;return matchesSessionLogSearch(record, search);}),- [records, search, decisionFilter, proxyFilter, range]+ [records, search, decisionFilter]);- const rows = useMemo(- () =>- interleaveSessionLogDrops(- visible,- drops.filter((drop) => {- if (range) {- const at = Date.parse(drop.startedAt);- if (at < range.startDate.getTime() || at > range.endDate.getTime()) return false;- }- return proxyFilter === ALL_PROXIES || drop.proxyId === proxyFilter;- })- ),- [visible, drops, proxyFilter, range]- );-- const hasBrowserFilter =- Boolean(sessionLogSearchTerm(search)) ||- decisionFilter !== "all" ||- proxyFilter !== ALL_PROXIES;+ const hasBrowserFilter = Boolean(sessionLogSearchTerm(search)) || decisionFilter !== "all";const isFiltered = hasBrowserFilter || Boolean(range);- const { searched, searchedUnreadable } = useMemo(+ // Counted once opened: a chunk's request count isn't known until it is decrypted.+ const { searched, emptyRun, oldestChunkAt } = useMemo(() =>(data?.pages ?? []).reduce((totals, page) => {- const pageRecords = page.chunks.reduce((sum, chunk) => sum + chunk.recordCount, 0);- const isReadable = page.chunks.some(- (chunk) => (page.decrypted[chunk.chunkId]?.records.length ?? 0) > 0+ const opened = page.chunks.reduce(+ (sum, chunk) => sum + (page.decrypted[sessionLogChunkKey(chunk)]?.records.length ?? 0),+ 0);+ const lastRequestTimes = page.chunks.map((chunk) => chunkIdTime(chunk.chunkId).getTime());return {- searched: totals.searched + pageRecords,- searchedUnreadable: totals.searchedUnreadable + (isReadable ? 0 : pageRecords)+ searched: totals.searched + opened,+ emptyRun: opened ? 0 : totals.emptyRun + 1,+ oldestChunkAt: lastRequestTimes.length+ ? Math.min(totals.oldestChunkAt ?? Infinity, ...lastRequestTimes)+ : totals.oldestChunkAt};},- { searched: 0, searchedUnreadable: 0 }+ { searched: 0, emptyRun: 0, oldestChunkAt: null as number | null }),[data]);+ const loadedPages = data?.pages.length ?? 0;const filterKey = [sessionLogSearchTerm(search),decisionFilter,- proxyFilter,range?.startDate.getTime(),range?.endDate.getTime()].join("|");const nextAllowance = () => ({filterKey,until: searched + FILTER_SEARCH_STEP,- unreadableUntil: searchedUnreadable + FILTER_SEARCH_STEP+ pagesAt: loadedPages});const [allowance, setAllowance] = useState(nextAllowance);- if (allowance.filterKey !== filterKey) setAllowance(nextAllowance());+ // Not while a new range's placeholder still shows the old range's pages, or the counts start from those.+ if (!isPlaceholderData && allowance.filterKey !== filterKey) setAllowance(nextAllowance());const searchOlder = () => setAllowance(nextAllowance());- // Pages that add no readable rows walk back in the same steps as a filtered search, so a bucket- // that refuses or has expired older chunks can't pull the whole session.+ // Empty pages only count since the last allowance, so Search Older Requests always walks further.const isSearchPaused =Boolean(hasNextPage) &&!isTruncated &&- (hasBrowserFilter- ? searched >= allowance.until- : searchedUnreadable >= allowance.unreadableUntil);+ ((hasBrowserFilter && searched >= allowance.until) ||+ Math.min(emptyRun, loadedPages - allowance.pagesAt) >= EMPTY_PAGE_STEP);const isFirstPageLoaded = Boolean(data?.pages.length) && !isPlaceholderData;const lastPage = data?.pages[data.pages.length - 1];- const oldestChunkId = lastPage?.nextCursor ? lastPage.chunks.at(-1)?.chunkId : undefined;- const searchedBackTo = oldestChunkId ? chunkIdTime(oldestChunkId) : null;+ const searchedBackTo =+ lastPage?.nextCursor && oldestChunkAt !== null ? new Date(oldestChunkAt) : null;const scrollRef = useRef<HTMLDivElement>(null);const rowVirtualizer = useVirtualizer({- count: rows.length,+ count: visible.length,getScrollElement: () => scrollRef.current,estimateSize: () => SESSION_LOG_ROW_HEIGHT,overscan: 16@@ -304,11 +269,11 @@ export const SessionLogsPanel = ({ session }: Props) => {)return;// Not cancelRefetch, so this walk can't cancel a Reload in flight.- if (isFirstPageLoaded && lastVisibleIndex >= rows.length - 30)+ if (isFirstPageLoaded && lastVisibleIndex >= visible.length - 30)fetchNextPage({ cancelRefetch: false }).catch(() => {});}, [lastVisibleIndex,- rows.length,+ visible.length,isFirstPageLoaded,hasNextPage,isFetchingNextPage,@@ -318,11 +283,10 @@ export const SessionLogsPanel = ({ session }: Props) => {isSearchPaused,fetchNextPage]);- const columnCount = proxies.length > 1 ? 8 : 7;const overflows = rowVirtualizer.getTotalSize() > (rowVirtualizer.scrollRect?.height ?? Infinity);const { newRequestCount, showNewRequests } = useNewRequestsCounter({scrollRef,- visible: rows,+ visible,arrivals,resetKey: `${session.id}|${filterKey}`,rowHeight: SESSION_LOG_ROW_HEIGHT@@ -365,7 +329,7 @@ export const SessionLogsPanel = ({ session }: Props) => {} else if (isStillLoading) {noRecordsTitle = "Loading requests";noRecordsDescription = "";- } else if (gaps.length > 0 && records.length === 0 && !hasNextPage) {+ } else if (gaps.length > 0 && !hasOpenedRecords && !hasNextPage) {noRecordsTitle = "Session logs unavailable";noRecordsDescription = "None of this session's logs could be loaded.";} else if (isSearchPaused && searchedBackTo) {@@ -374,6 +338,9 @@ export const SessionLogsPanel = ({ session }: Props) => {"MMM d, h:mm a")}`;noRecordsDescription = "Older requests have not been searched yet.";+ } else if (isSearchPaused) {+ noRecordsTitle = `No ${hasBrowserFilter ? "matching" : "readable"} requests found yet`;+ noRecordsDescription = "Older requests have not been searched yet.";} else if (range && (!hasChunks || !hasBrowserFilter)) {noRecordsTitle = "No requests in this range";noRecordsDescription = `This session recorded nothing between ${format(@@ -382,7 +349,7 @@ export const SessionLogsPanel = ({ session }: Props) => {)} and ${format(range.endDate, "MMM d, yyyy HH:mm")}.`;} else if (isFiltered) {noRecordsTitle = "No requests match these filters";- noRecordsDescription = "Try a different search term, outcome, proxy or time range.";+ noRecordsDescription = "Try a different search term, outcome or time range.";} else if (liveState === "live") {noRecordsLiveState = liveState;noRecordsTitle = "Waiting for requests";@@ -399,11 +366,11 @@ export const SessionLogsPanel = ({ session }: Props) => {noRecordsTitle = isActive ? "Nothing recorded yet" : "No requests recorded";noRecordsDescription = isActive? "Requests this session makes through a proxy will appear here shortly after."- : "This session ended without making any requests through a proxy.";+ : "";}const isUnreachable =- gaps.length > 0 && records.length === 0 && gaps.every((gap) => gap.reason === "fetch");+ gaps.length > 0 && !hasOpenedRecords && gaps.every((gap) => gap.reason === "fetch");const retryButton = (<Button@@ -416,25 +383,16 @@ export const SessionLogsPanel = ({ session }: Props) => {</Button>);- if (!isPending && !isPlaceholderData && !isLoadError && storageUnavailable) {- const isConnectionUnusable = storageUnavailable.reason === "connection-unusable";- let unreadableDescription = "This session's recorded requests aren't available. Ask an admin.";- if (isAdmin) {- unreadableDescription = isConnectionUnusable- ? (storageUnavailable.message ??- "The AWS connection for session logs can't be used right now.")- : "No AWS connection is set for session logs, so this session's recorded requests can't be loaded.";- }-+ if (storageError) {return (<Empty className="border"><EmptyHeader><EmptyTitle>Session logs can't be read</EmptyTitle>- <EmptyDescription>{unreadableDescription}</EmptyDescription>+ <EmptyDescription>{storageError}</EmptyDescription></EmptyHeader>- {isAdmin && (- <div className="flex gap-2">- {isConnectionUnusable && retryButton}+ <div className="flex gap-2">+ {retryButton}+ {isAdmin && (<Button variant="av" asChild><Linkto="/organizations/$orgId/agent-vault/settings"@@ -443,13 +401,22 @@ export const SessionLogsPanel = ({ session }: Props) => {Go to Settings</Link></Button>- </div>- )}+ )}+ </div></Empty>);}- if (!isPending && !isPlaceholderData && !isLoadError && !isEnabled && !hasChunks && !range) {+ // 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) {return (<Empty className="border">@@ -499,6 +466,7 @@ export const SessionLogsPanel = ({ session }: Props) => {!isPending &&!isPlaceholderData &&!isLoadError &&+ isActive &&isEnabled &&!isRecordable &&!hasChunks@@ -575,19 +543,6 @@ export const SessionLogsPanel = ({ session }: Props) => {onChange={(result) => applyRange(result)}onClear={() => applyRange(null)}/>- <Select value={proxyFilter} onValueChange={setProxyFilter}>- <SelectTrigger aria-label="Filter by proxy">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={ALL_PROXIES}>All Proxies</SelectItem>- {proxies.map((proxy) => (- <SelectItem key={proxy.id} value={proxy.id}>- {proxy.name}- </SelectItem>- ))}- </SelectContent>- </Select></div>{isUnreachable && (@@ -621,15 +576,25 @@ export const SessionLogsPanel = ({ session }: Props) => {</Alert>)}+ {isLiveGapUnfilled && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ <p>Some recent requests may be missing.</p>+ <AlertAction>{retryButton}</AlertAction>+ </AlertDescription>+ </Alert>+ )}+{!isUnreachable && gaps.length > 0 && (<Alert variant="warning"><TriangleAlertIcon /><AlertDescription><div className="flex flex-col gap-1">- {groupSessionLogGaps(gaps).map(({ reason, recordCount }) => (+ {groupSessionLogGaps(gaps).map(({ reason, chunkCount }) => (<span key={reason}>- {recordCount.toLocaleString()} {recordCount === 1 ? "request" : "requests"}{" "}- {GAP_EXPLANATION[reason][recordCount === 1 ? "one" : "many"]}.+ {chunkCount.toLocaleString()} {chunkCount === 1 ? "batch" : "batches"} of requests{" "}+ {GAP_EXPLANATION[reason][chunkCount === 1 ? "one" : "many"]}.</span>))}</div>@@ -685,13 +650,12 @@ export const SessionLogsPanel = ({ session }: Props) => {ref={scrollRef}// Auto layout sizes columns from only the rows the virtualizer has mounted, so they// would shift as rows scroll in and out- className={twMerge("w-full table-fixed", proxies.length > 1 ? "min-w-280" : "min-w-240")}+ className="w-full min-w-240 table-fixed"containerClassName="min-h-0 thin-scrollbar overflow-auto [overflow-anchor:none]"><TableHeader sticky><TableRow><TableHead className="w-48">Time</TableHead>- {proxies.length > 1 && <TableHead className="w-40">Proxy</TableHead>}<TableHead className="w-24">Method</TableHead><TableHead>Host</TableHead><TableHead>Path</TableHead>@@ -702,7 +666,7 @@ export const SessionLogsPanel = ({ session }: Props) => {{liveState && (<LiveStatusRowstate={liveState}- columnCount={columnCount}+ columnCount={COLUMN_COUNT}recordCount={records.length}isRetrying={live.isFetching}onRetry={retryLive}@@ -714,17 +678,7 @@ export const SessionLogsPanel = ({ session }: Props) => {<TableBody>{padTop > 0 && <tr style={{ height: padTop }} />}{virtualRows.map((virtualRow) => {- const row = rows[virtualRow.index];- if (row.kind === "drop") {- return (- <SessionLogDropRow- key={row.key}- droppedCount={row.droppedCount}- columnCount={columnCount}- />- );- }- const { record } = row;+ const record = visible[virtualRow.index];const isAddable =canAddService &&!record.service &&@@ -736,8 +690,6 @@ export const SessionLogsPanel = ({ session }: Props) => {key={sessionLogRecordKey(record)}record={record}arrivedAt={arrivals.get(sessionLogRecordKey(record))}- proxyName={proxyNames.get(record.proxyId)}- showProxy={proxies.length > 1}accessBundleName={accessBundle?.name}onAddService={isAddable@@ -756,7 +708,7 @@ export const SessionLogsPanel = ({ session }: Props) => {isSearchPaused ||(!hasNextPage && overflows)) && (<TableRow className="hover:bg-transparent">- <TableCell colSpan={columnCount} className="text-center text-xs text-muted">+ <TableCell colSpan={COLUMN_COUNT} className="text-center text-xs text-muted">{isFetchingNextPage && (<span className="flex items-center justify-center gap-2"><Spinner size="xs" />diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.ts b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.tsindex 14b5fcea9e..bda1ec1102 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.ts+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.ts@@ -8,7 +8,6 @@ import {chunkIdTime,findRowShift,groupSessionLogGaps,- interleaveSessionLogDrops,matchesSessionLogSearch} from "./SessionLogsPanel.utils";@@ -26,8 +25,7 @@ const record = (seq: number): TAgentVaultSessionLogRecord => ({accessBundle: null});-const rows = (...seqs: number[]) =>- seqs.map((seq) => ({ kind: "record" as const, record: record(seq) }));+const rows = (...seqs: number[]) => seqs.map(record);describe("findRowShift", () => {it("moves the row down by however many rows arrived at the top", () => {@@ -65,28 +63,13 @@ describe("chunkIdTime", () => {});describe("groupSessionLogGaps", () => {- const gap = (reason: "gcm" | "missing", recordCount: number, chunkId: string) => ({- chunkId,- proxyId: "proxy-1",- proxyName: "proxy",- startedAt: "2026-09-24T13:17:00.000Z",- reason,- recordCount- });+ const gap = (reason: "gcm" | "missing") => ({ reason, firstSeenAt: null });- it("adds up the requests for each reason, in the order the reasons first appear", () => {- assert.deepEqual(- groupSessionLogGaps([- gap("gcm", 10, "a"),- gap("gcm", 11, "b"),- gap("missing", 3, "c"),- gap("gcm", 21, "d")- ]),- [- { reason: "gcm", recordCount: 42 },- { reason: "missing", recordCount: 3 }- ]- );+ it("counts the batches for each reason, in the order the reasons first appear", () => {+ assert.deepEqual(groupSessionLogGaps([gap("gcm"), gap("gcm"), gap("missing"), gap("gcm")]), [+ { reason: "gcm", chunkCount: 3 },+ { reason: "missing", chunkCount: 1 }+ ]);});});@@ -123,44 +106,3 @@ describe("matchesSessionLogSearch", () => {assert.equal(matchesSessionLogSearch(repoRequest, "gitlab.com/repos"), false);});});--describe("interleaveSessionLogDrops", () => {- const drop = (chunkId: string, beforeSeq: number, droppedCount: number) => ({- chunkId,- proxyId: "proxy-1",- startedAt: record(beforeSeq).ts,- droppedCount- });- const shape = (seqs: number[], drops: ReturnType<typeof drop>[]) =>- interleaveSessionLogDrops(seqs.map(record), drops).map((row) =>- row.kind === "record" ? row.record.seq : `-${row.droppedCount}`- );-- it("puts a chunk's drops right under its oldest record", () => {- assert.deepEqual(shape([9, 8, 5, 4], [drop("b", 8, 12)]), [9, 8, "-12", 5, 4]);- });-- it("merges drops that end up side by side into one row", () => {- assert.deepEqual(shape([9, 2], [drop("b", 8, 12), drop("a", 5, 3)]), [9, "-15", 2]);- });-- it("never shows two drop rows next to each other, wherever the drops land", () => {- const drops = [- drop("f", 20, 1),- drop("e", 19, 2),- drop("d", 9, 4),- drop("c", 9, 8),- drop("b", 2, 16),- drop("a", 1, 32)- ];- const result = interleaveSessionLogDrops([9, 5, 3].map(record), drops);- result.forEach((row, index) => {- if (index > 0) assert.ok(!(row.kind === "drop" && result[index - 1].kind === "drop"));- });- assert.deepEqual(shape([9, 5, 3], drops), ["-3", 9, "-12", 5, 3, "-48"]);- });-- it("keeps drops older than every shown record at the bottom", () => {- assert.deepEqual(shape([9, 8], [drop("a", 3, 7)]), [9, 8, "-7"]);- });-});diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.ts b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.tsindex 63aedd6af4..51094a819c 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.ts+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.ts@@ -1,58 +1,20 @@import { sessionLogRecordKey } from "@app/hooks/api/agentVault";import {- TAgentVaultSessionLogDrop,TAgentVaultSessionLogGap,TAgentVaultSessionLogGapReason,TAgentVaultSessionLogRecord} from "@app/hooks/api/agentVault/types";-export type TSessionLogRow =- | { kind: "record"; record: TAgentVaultSessionLogRecord }- | { kind: "drop"; key: string; droppedCount: number };--export const sessionLogRowKey = (row: TSessionLogRow) =>- row.kind === "record" ? sessionLogRecordKey(row.record) : row.key;--// A chunk's drops happened just before its first record, so they sit under the newer rows. Drops left-// side by side (often by a filter) merge, so a session that lost thousands of requests shows one row per gap.-export const interleaveSessionLogDrops = (- records: TAgentVaultSessionLogRecord[],- drops: TAgentVaultSessionLogDrop[]-): TSessionLogRow[] => {- const pending = drops- .map((drop) => ({ drop, at: Date.parse(drop.startedAt) }))- .sort((a, b) => b.at - a.at);- const rows: TSessionLogRow[] = [];- let next = 0;- const pushDrop = (drop: TAgentVaultSessionLogDrop) => {- const last = rows[rows.length - 1];- if (last?.kind === "drop") {- rows[rows.length - 1] = { ...last, droppedCount: last.droppedCount + drop.droppedCount };- } else {- rows.push({ kind: "drop", key: `drop-${drop.chunkId}`, droppedCount: drop.droppedCount });- }- };- records.forEach((record) => {- const at = Date.parse(record.ts);- while (next < pending.length && pending[next].at > at) {- pushDrop(pending[next].drop);- next += 1;- }- rows.push({ kind: "record", record });- });- pending.slice(next).forEach(({ drop }) => pushDrop(drop));- return rows;-};-+// Where the row a reader was looking at moved to once new rows landed above it.export const findRowShift = (- before: TSessionLogRow[],- after: TSessionLogRow[],+ before: TAgentVaultSessionLogRecord[],+ after: TAgentVaultSessionLogRecord[],index: number): number | null => {const row = before[index];if (!row) return null;- const key = sessionLogRowKey(row);- const moved = after.findIndex((candidate) => sessionLogRowKey(candidate) === key);+ const key = sessionLogRecordKey(row);+ const moved = after.findIndex((candidate) => sessionLogRecordKey(candidate) === key);return moved < 0 ? null : moved - index;};@@ -123,15 +85,15 @@ const HTTP_STATUS_TEXT: Record<number, string> = {export const httpStatusLabel = (status: number) =>HTTP_STATUS_TEXT[status] ? `${status} ${HTTP_STATUS_TEXT[status]}` : String(status);+// A chunk ID is a UUIDv7, whose first 48 bits are the time of the chunk's last request.export const chunkIdTime = (chunkId: string) =>new Date(parseInt(chunkId.replace(/-/g, "").slice(0, 12), 16));+// Counts unreadable chunks by reason; how many requests each held is unknown until it is opened.export const groupSessionLogGaps = (gaps: TAgentVaultSessionLogGap[]) => {const byReason = new Map<TAgentVaultSessionLogGapReason, number>();- gaps.forEach((gap) =>- byReason.set(gap.reason, (byReason.get(gap.reason) ?? 0) + gap.recordCount)- );- return [...byReason].map(([reason, recordCount]) => ({ reason, recordCount }));+ gaps.forEach((gap) => byReason.set(gap.reason, (byReason.get(gap.reason) ?? 0) + 1));+ return [...byReason].map(([reason, chunkCount]) => ({ reason, chunkCount }));};// Records hold no query string, so a pasted URL is cut back to the host and path it was sent to.diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/useNewRequestsCounter.ts b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/useNewRequestsCounter.tsindex f04c317f5f..86fd60905e 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/useNewRequestsCounter.ts+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/useNewRequestsCounter.ts@@ -1,12 +1,13 @@import { RefObject, useEffect, useLayoutEffect, useRef, useState } from "react";import { sessionLogRecordKey } from "@app/hooks/api/agentVault";+import { TAgentVaultSessionLogRecord } from "@app/hooks/api/agentVault/types";-import { findRowShift, TSessionLogRow } from "./SessionLogsPanel.utils";+import { findRowShift } from "./SessionLogsPanel.utils";type Params = {scrollRef: RefObject<HTMLDivElement | null>;- visible: TSessionLogRow[];+ visible: TAgentVaultSessionLogRecord[];arrivals: Map<string, number>;resetKey: string;rowHeight: number;@@ -40,10 +41,9 @@ export const useNewRequestsCounter = ({if (!shift) return;scroller.scrollTop += shift * rowHeight;if (shift < 0) return;- const landedAbove = visible.slice(0, top + shift).filter((row) => {- if (row.kind !== "record") return false;- return (arrivals.get(sessionLogRecordKey(row.record)) ?? 0) > since;- }).length;+ const landedAbove = visible+ .slice(0, top + shift)+ .filter((record) => (arrivals.get(sessionLogRecordKey(record)) ?? 0) > since).length;if (landedAbove) setNewRequests((prev) => ({ ...prev, count: prev.count + landedAbove }));}, [visible, arrivals, scrollRef, rowHeight]);diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogAlerts.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogAlerts.tsxindex bbe15eefaa..1058c97c5c 100644--- a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogAlerts.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogAlerts.tsx@@ -33,8 +33,7 @@ export const SessionLogAlerts = () => {if (!config?.appConnectionId) {return "Session logs are off, and without an AWS connection the logs already in the bucket can't be read.";}- if (health?.connectionError || isReadBlocked)- return "Session logs are off, so nothing new is being stored.";+ 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.";@@ -49,15 +48,6 @@ export const SessionLogAlerts = () => {</Alert>)}- {health?.isStorageFull && (- <Alert variant="danger">- <CircleAlertIcon />- <AlertDescription>- Session logs have reached their limit for this organization. Contact Infisical support.- </AlertDescription>- </Alert>- )}-{isLapsed && (<Alert variant="warning"><TriangleAlertIcon />@@ -75,14 +65,23 @@ export const SessionLogAlerts = () => {</Alert>)}- {!isSettingsPending && !isHealthPending && hasDestination && !isLapsed && !isRecording && (- <Alert variant="warning">- <TriangleAlertIcon />- <AlertDescription>{notRecordingReason}</AlertDescription>- </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 />+ <SessionLogReadAccessAlert />+ </>+ )}<AgentVaultSessionLogUpgradeModal isOpen={isUpgradeOpen} onOpenChange={setIsUpgradeOpen} /></>diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.tsxindex 4e1d7b1a9d..9a935d9d8a 100644--- a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.tsx@@ -56,7 +56,7 @@ 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 = (hasSavedBucket: boolean) =>+const buildSchema = (savedBucket: string | null) =>z.object({enabled: z.boolean(),@@ -83,7 +83,7 @@ const buildSchema = (hasSavedBucket: boolean) =>}).superRefine((values, ctx) => {const { length } = values.bucket;- if (length === 0 && hasSavedBucket) {+ if (length === 0 && savedBucket) {ctx.addIssue({code: "custom",path: ["bucket"],@@ -102,6 +102,13 @@ const buildSchema = (hasSavedBucket: boolean) =>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."+ });}});@@ -143,7 +150,7 @@ export const SessionLogModal = ({setValue,watch,formState: { isSubmitting, isDirty }- } = useForm<FormData>({ resolver: zodResolver(buildSchema(Boolean(settings?.bucket))) });+ } = useForm<FormData>({ resolver: zodResolver(buildSchema(settings?.bucket ?? null)) });const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =useDiscardChangesGuard({ isDirty, onDiscard: () => onOpenChange(false) });@@ -417,9 +424,9 @@ export const SessionLogModal = ({<AlertDescription><p>Everything already recorded stays in{" "}- <span className="font-mono">{settings?.bucket}</span>, where Infisical can no- longer read it. To rotate credentials, update the AWS connection instead of- moving the bucket.+ <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>@@ -443,14 +450,14 @@ export const SessionLogModal = ({{settings?.keyPrefix ? (<p>Logs already recorded stay under{" "}- <span className="font-mono">{settings.keyPrefix}/</span>. Keep your AWS- policy allowing that prefix, or Infisical can't read them.+ <span className="font-mono">{settings.keyPrefix}/</span> and won't show+ in Infisical until you switch back to that prefix.</p>) : (<p>Logs already recorded stay at the top level of{" "}- <span className="font-mono">{settings?.bucket}</span>. Keep your AWS policy- allowing the whole bucket, or Infisical can't read them.+ <span className="font-mono">{settings?.bucket}</span> and won't show in+ Infisical until you remove the prefix again.</p>)}</AlertDescription>