Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(agent-vault): session logs (#8275)
Saif Ur Rahmanf0e9572c604e
diff --git a/backend/e2e-test/fakes/aws-connection-fns.ts b/backend/e2e-test/fakes/aws-connection-fns.tsindex 54c257565b..4de74182ca 100644--- a/backend/e2e-test/fakes/aws-connection-fns.ts+++ b/backend/e2e-test/fakes/aws-connection-fns.ts@@ -21,6 +21,7 @@ const DEFAULT_ACCOUNT_ID = "000000000000";type TFakeAwsConnectionState = {accountId: string | null;validationError: string | null;+ configError: string | null;};// Shared through globalThis for the same reason as the Parameter Store fake: the alias makes@@ -32,7 +33,8 @@ const globalScope = globalThis as typeof globalThis & {globalScope.infisicalFakeAwsConnection ??= {accountId: DEFAULT_ACCOUNT_ID,- validationError: null+ validationError: null,+ configError: null};const state = globalScope.infisicalFakeAwsConnection;@@ -43,6 +45,7 @@ export const fakeAwsConnection = {reset: () => {state.accountId = DEFAULT_ACCOUNT_ID;state.validationError = null;+ state.configError = null;},// What getAwsAccountId reports. null reproduces the real module's behavior when STS fails.@@ -54,12 +57,19 @@ export const fakeAwsConnection = {// Pass null to go back to accepting.failsValidationWith: (message: string | null) => {state.validationError = message;+ },++ // Make loading the connection's credentials reject, as the real provider does when AWS refuses to+ // let Infisical assume the role. Pass null to go back to accepting.+ failsConfigWith: (message: string | null) => {+ state.configError = message;}};// Mirrors the real access-key branch, which hands back whatever the connection carries and// makes no request. The assume-role branch is the one that calls STS, and no spec uses it.export const getAwsConnectionConfig = (appConnection: TAwsConnectionConfig, region = AWSRegion.US_EAST_1) => {+ if (state.configError) return Promise.reject(new BadRequestError({ message: state.configError }));const { credentials } = appConnection;return Promise.resolve({diff --git a/backend/e2e-test/fakes/s3.ts b/backend/e2e-test/fakes/s3.tsnew file mode 100644index 0000000000..64e386747b--- /dev/null+++ b/backend/e2e-test/fakes/s3.ts@@ -0,0 +1,109 @@+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+// links without reaching AWS. Wired up by test.alias in vitest.e2e.config.mts; nothing under src/+// references this file.+//+// 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.++type TAccessFailure = "unreachable" | "unwritable";++type TFakeState = {+ objects: Map<string, Buffer>;+ accessFailure: TAccessFailure | null;+ presignedPuts: Map<string, { bucket: string; key: string; contentLength: number }>;+ presignedGets: Map<string, { bucket: string; key: string }>;+ nextUrlId: number;+};++const freshState = (): TFakeState => ({+ objects: new Map(),+ accessFailure: null,+ presignedPuts: new Map(),+ presignedGets: new Map(),+ nextUrlId: 0+});++// On globalThis for the same reason as the Parameter Store fake: the server and a spec can reach this+// module by different specifiers, and module state would then split into two copies.+const globalScope = globalThis as typeof globalThis & { infisicalFakeS3Bucket?: TFakeState };+globalScope.infisicalFakeS3Bucket ??= freshState();+const state = globalScope.infisicalFakeS3Bucket;++const objectId = (bucket: string, key: string) => `${bucket}/${key}`;++export const fakeS3Bucket = {+ reset: () => {+ Object.assign(state, freshState());+ },++ // Make checkAccess fail the way a bucket that can't be reached, or can't be written to, would.+ // Pass null to go back to accepting.+ failsAccessCheckWith: (failure: TAccessFailure | null) => {+ state.accessFailure = failure;+ },++ put: (url: string, body: Buffer) => {+ const target = state.presignedPuts.get(url);+ if (!target) throw new Error(`No presigned PUT was minted for ${url}`);+ if (body.length !== target.contentLength) {+ throw new Error(`Presigned PUT expects ${target.contentLength} bytes, got ${body.length}`);+ }+ const id = objectId(target.bucket, target.key);+ if (state.objects.has(id)) {+ throw new Error(`Presigned PUT is create-only, and ${target.key} already exists`);+ }+ state.objects.set(id, body);+ },++ get: (url: string) => {+ const target = state.presignedGets.get(url);+ if (!target) throw new Error(`No presigned GET was minted for ${url}`);+ return state.objects.get(objectId(target.bucket, target.key)) ?? null;+ },++ objectKeys: (bucket: string) =>+ [...state.objects.keys()]+ .filter((id) => id.startsWith(`${bucket}/`))+ .map((id) => id.slice(bucket.length + 1))+ .sort()+};++export const createS3Bucket = ({ bucket }: Parameters<typeof RealS3.createS3Bucket>[0]) => {+ // The key is in the path, as on a real presigned link, so a spec can tell which object a link is for.+ const mintUrl = (kind: string, key: string) => {+ state.nextUrlId += 1;+ return `https://${bucket}.s3.fake.local/${key}?x-fake-link=${kind}-${state.nextUrlId}`;+ };++ return {+ presignCreateOnlyPut: ({ key, contentLength }: { key: string; contentLength: number }) => {+ const url = mintUrl("put", key);+ state.presignedPuts.set(url, { bucket, key, contentLength });+ return Promise.resolve(url);+ },++ presignGet: (key: string) => {+ const url = mintUrl("get", key);+ state.presignedGets.set(url, { bucket, key });+ return Promise.resolve(url);+ },++ checkAccess: (): Promise<RealS3.TS3AccessCheck> =>+ Promise.resolve(+ state.accessFailure+ ? { ok: false, failure: state.accessFailure, error: new Error(`fake bucket is ${state.accessFailure}`) }+ : { ok: true }+ )+ };+};++export const assertFakeMatchesRealS3: Pick<typeof RealS3, "createS3Bucket"> = { createS3Bucket };++export const assertFakeBucketShapeMatches: { [K in keyof RealS3.TS3Bucket]: unknown } = {+ presignCreateOnlyPut: null,+ presignGet: 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.tsnew file mode 100644index 0000000000..d62d42b523--- /dev/null+++ b/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts@@ -0,0 +1,1285 @@+import crypto from "node:crypto";++import * as x509 from "@peculiar/x509";+import { fakeAwsConnection } from "e2e-test/fakes/aws-connection-fns";+import { fakeS3Bucket } from "e2e-test/fakes/s3";+import { createAwsAppConnection, deleteAwsAppConnection } from "e2e-test/testUtils/app-connections";+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 { AgentVaultSessionLogErrorName } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-enums";+import {+ encodeHistoryCursor,+ encodeTailCursor+} 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";++initLogger();++const authHeader = { authorization: `Bearer ${jwtAuthToken}` };++const inject = (method: "GET" | "POST" | "PATCH" | "DELETE", url: string, body?: Record<string, unknown>) =>+ testServer.inject({ method, url, headers: authHeader, ...(body ? { body } : {}) });++const getProjectId = async () =>+ (JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as { projectId: string }).projectId;++const createAccessBundle = async (name: string) => {+ const res = await inject("POST", "/api/v1/agent-vault/access-bundles", { name });+ expect(res.statusCode).toBe(200);+ return (JSON.parse(res.payload) as { accessBundle: { id: string; name: string } }).accessBundle;+};++const mintSession = async (bundleName: string, ttl = "1h") => {+ const res = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundleName], ttl });+ expect(res.statusCode).toBe(200);+ return (JSON.parse(res.payload) as { session: { id: string; token: string } }).session;+};++const createMemberIdentity = async (name: string) => {+ const created = await inject("POST", "/api/v1/identities", {+ name,+ role: OrgMembershipRole.Member,+ organizationId: seedData1.organization.id+ });+ expect(created.statusCode).toBe(200);+ const identity = created.json().identity as { id: string };++ const attached = await inject("POST", `/api/v1/auth/universal-auth/identities/${identity.id}`, {+ accessTokenTTL: 3600,+ accessTokenMaxTTL: 3600,+ accessTokenNumUsesLimit: 0+ });+ expect(attached.statusCode).toBe(200);+ const { clientId } = attached.json().identityUniversalAuth;++ const secret = await inject("POST", `/api/v1/auth/universal-auth/identities/${identity.id}/client-secrets`, {});+ expect(secret.statusCode).toBe(200);++ const login = await testServer.inject({+ method: "POST",+ url: "/api/v1/auth/universal-auth/login",+ body: { clientId, clientSecret: secret.json().clientSecret }+ });+ expect(login.statusCode).toBe(200);+ const token = login.json().accessToken as string;++ expect(+ (+ await inject("POST", "/api/v1/agent-vault/members", {+ machineIdentityIds: [identity.id],+ role: ProjectMembershipRole.Member+ })+ ).statusCode+ ).toBe(200);++ return {+ id: identity.id,+ as: (method: "GET" | "POST" | "PATCH", url: string, body?: Record<string, unknown>) =>+ testServer.inject({ method, url, headers: { authorization: `Bearer ${token}` }, ...(body ? { body } : {}) }),+ cleanup: () => inject("DELETE", `/api/v1/identities/${identity.id}`)+ };+};++const generateRootCaPem = async () => {+ const alg = { name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" } as const;+ const keys = await x509.cryptoProvider.get().subtle.generateKey(alg, false, ["sign", "verify"]);+ const cert = await x509.X509CertificateGenerator.createSelfSigned({+ serialNumber: "01",+ name: "CN=agent-vault-test-ca",+ notBefore: new Date(Date.now() - 60_000),+ notAfter: new Date(Date.now() + 24 * 60 * 60 * 1000),+ signingAlgorithm: alg,+ keys,+ extensions: [new x509.BasicConstraintsExtension(true, 1, true)]+ });+ return cert.toString("pem");+};++const createProxy = async (name: string) => {+ const res = await inject("POST", "/api/v1/agent-vault/proxies", { name });+ expect(res.statusCode).toBe(200);+ const { proxy, token } = JSON.parse(res.payload) as { proxy: { id: string; name: string }; token: string };++ const enrolled = await testServer.inject({+ method: "POST",+ url: "/api/v1/agent-vault/proxy/login",+ body: { method: "token", token, rootCaCertificate: await generateRootCaPem() }+ });+ expect(enrolled.statusCode, enrolled.payload).toBe(200);+ const { accessToken } = JSON.parse(enrolled.payload) as { accessToken: string };++ return {+ ...proxy,+ postChunk: (sessionId: string, chunk: Record<string, unknown>) =>+ testServer.inject({+ method: "POST",+ url: `/api/v1/agent-vault/proxy/sessions/${sessionId}/logs/chunks`,+ headers: { authorization: `Bearer ${accessToken}` },+ body: chunk+ }),+ resolve: (sessionToken: string, hasSessionLogKey?: boolean) =>+ testServer.inject({+ method: "POST",+ url: "/api/v1/agent-vault/proxy/resolve",+ headers: { authorization: `Bearer ${accessToken}`, "x-infisical-agent-session": sessionToken },+ ...(hasSessionLogKey === undefined ? {} : { body: { hasSessionLogKey } })+ })+ };+};++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+});++const recordChunk = async (+ proxy: Awaited<ReturnType<typeof createProxy>>,+ sessionId: string,+ chunk: Record<string, unknown> = chunkBody()+) => {+ const res = await proxy.postChunk(sessionId, chunk);+ expect(res.statusCode, res.payload).toBe(200);+ return JSON.parse(res.payload) as { chunkId: string; uploadUrl: string; expiresInSeconds: number };+};++const BUCKET = "session-logs-bucket";++const SETTINGS_URL = "/api/v1/agent-vault/settings/session-logs";++const saveConfig = async (patch: Record<string, unknown>) => inject("PATCH", SETTINGS_URL, patch);++describe("Agent Vault session logs", async () => {+ let connectionId: string;+ let connectionName: string;+ let projectId: string;++ beforeAll(async () => {+ projectId = await getProjectId();+ expect(+ (await inject("POST", `/api/v1/organization-admin/projects/${projectId}/grant-admin-access`)).statusCode+ ).toBe(200);+ connectionName = `session-logs-aws-${Date.now()}`;+ connectionId = await createAwsAppConnection({ name: connectionName, authToken: jwtAuthToken });+ });++ // 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();+ await testDb("agent_vault_access_bundles").where({ projectId }).del();+ await testDb("memberships").where({ scopeProjectId: projectId }).del();+ await deleteAwsAppConnection({ connectionId, authToken: jwtAuthToken });+ });++ 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();+ });++ describe("settings", () => {+ test("reads as off, with no destination, before anything is configured", async () => {+ const res = await inject("GET", SETTINGS_URL);+ expect(res.statusCode).toBe(200);++ const body = JSON.parse(res.payload) as { settings: Record<string, unknown> };+ expect(body.settings).toMatchObject({ enabled: false, bucket: null, appConnectionId: null });+ expect(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 });++ const probe = await inject("GET", `${SETTINGS_URL}/cors-probe`);+ expect(probe.statusCode).toBe(200);+ expect(JSON.parse(probe.payload).probe).toBeNull();+ });++ test("saving a destination validates the bucket, and the CORS probe then points at it", async () => {+ const res = await saveConfig({+ enabled: true,+ appConnectionId: connectionId,+ bucket: BUCKET,+ region: "us-east-1",+ keyPrefix: "logs"+ });+ expect(res.statusCode, res.payload).toBe(200);++ const body = JSON.parse(res.payload) as { settings: Record<string, unknown> };+ expect(body.settings).toMatchObject({ enabled: true, bucket: BUCKET, region: "us-east-1", keyPrefix: "logs" });++ const probe = await inject("GET", `${SETTINGS_URL}/cors-probe`);+ expect(probe.statusCode).toBe(200);+ const probeBody = JSON.parse(probe.payload) as { probe: { url: string; expiresInSeconds: number } | null };+ expect(new URL(probeBody.probe?.url as string).pathname).toBe("/logs/.cors-probe");+ });++ test("a bucket it cannot write to is refused with the actionable message, and nothing is saved", async () => {+ fakeS3Bucket.failsAccessCheckWith("unwritable");++ const res = await saveConfig({+ enabled: true,+ appConnectionId: connectionId,+ bucket: "nope",+ region: "us-east-1"+ });+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res.payload).message).toBe(+ "Bucket 'nope' is reachable but writing to it failed. Grant s3:PutObject on the configured key prefix"+ );++ expect(await testDb("agent_vault_session_log_configs").where({ projectId }).first()).toBeUndefined();+ });++ test("turning session logs off is never blocked by a destination that has gone bad", async () => {+ await saveConfig({+ enabled: true,+ appConnectionId: connectionId,+ bucket: BUCKET,+ region: "us-east-1"+ });++ fakeS3Bucket.failsAccessCheckWith("unreachable");++ const res = await saveConfig({ enabled: false });+ expect(res.statusCode).toBe(200);+ expect(JSON.parse(res.payload).settings.enabled).toBe(false);++ expect((await saveConfig({ enabled: true })).statusCode).toBe(400);+ });++ test("a connection that can't be used says why, on the page and when saving", async () => {+ expect(+ (await saveConfig({ enabled: true, appConnectionId: connectionId, bucket: BUCKET, region: "us-east-1" }))+ .statusCode+ ).toBe(200);+ fakeAwsConnection.failsConfigWith("AWS refused to assume the role");++ const health = await inject("GET", `${SETTINGS_URL}/health`);+ const refused = `Couldn't use the AWS connection '${connectionName}' for session logs: AWS refused to assume the role`;+ expect(JSON.parse(health.payload).health.connectionError).toBe(refused);++ const save = await saveConfig({ keyPrefix: "elsewhere" });+ expect(save.statusCode).toBe(400);+ expect(JSON.parse(save.payload).message).toBe(refused);+ });++ test("turning session logs on without a complete destination names what is missing", async () => {+ const res = await saveConfig({ enabled: true });+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res.payload).message).toContain("an AWS connection");+ expect(JSON.parse(res.payload).message).toContain("a bucket");+ });++ test("a connection session logs use cannot be deleted", async () => {+ await saveConfig({ enabled: true, appConnectionId: connectionId, bucket: BUCKET, region: "us-east-1" });++ const res = await testServer.inject({+ method: "DELETE",+ url: `/api/v1/app-connections/aws/${connectionId}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` }+ });+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res.payload).message).toContain("Cannot delete App Connection with existing connections");++ const config = await testDb("agent_vault_session_log_configs").where({ projectId }).first();+ expect(config.appConnectionId).toBe(connectionId);+ });++ test("the connection can be detached only with recording off, and the destination is kept", async () => {+ await saveConfig({ enabled: true, appConnectionId: connectionId, bucket: BUCKET, region: "us-east-1" });++ const whileOn = await saveConfig({ appConnectionId: null });+ expect(whileOn.statusCode).toBe(400);+ expect(JSON.parse(whileOn.payload).message).toContain("Turn off session logs");++ const whileOff = await saveConfig({ enabled: false, appConnectionId: null });+ expect(whileOff.statusCode).toBe(200);+ expect(JSON.parse(whileOff.payload).settings).toMatchObject({+ enabled: false,+ appConnectionId: null,+ bucket: BUCKET+ });+ });++ test("a save that puts the connection to a new use checks it again; turning recording off does not", async () => {+ await saveConfig({+ enabled: true,+ appConnectionId: connectionId,+ bucket: BUCKET,+ region: "us-east-1",+ keyPrefix: "logs"+ });++ await testDb("app_connections").where({ id: connectionId }).update({ app: AppConnection.GCP });+ try {+ expect((await saveConfig({ enabled: false })).statusCode).toBe(200);+ expect((await saveConfig({ enabled: false })).statusCode).toBe(200);+ expect((await saveConfig({ enabled: true })).statusCode).toBe(400);+ expect((await saveConfig({ bucket: "a-different-bucket" })).statusCode).toBe(400);+ expect((await saveConfig({ region: "us-west-2" })).statusCode).toBe(400);+ expect((await saveConfig({ keyPrefix: "elsewhere" })).statusCode).toBe(400);+ } finally {+ await testDb("app_connections").where({ id: connectionId }).update({ app: AppConnection.AWS });+ }+ });++ test("a patch leaves out what it does not name", async () => {+ await saveConfig({+ enabled: true,+ appConnectionId: connectionId,+ bucket: BUCKET,+ region: "us-east-1",+ keyPrefix: "logs"+ });++ const off = await saveConfig({ enabled: false });+ expect(JSON.parse(off.payload).settings).toMatchObject({ enabled: false, bucket: BUCKET, keyPrefix: "logs" });+ });++ test("the key prefix is saved as typed, and one with a slash at either end is refused", async () => {+ const saved = await saveConfig({+ enabled: true,+ appConnectionId: connectionId,+ bucket: BUCKET,+ region: "us-east-1",+ keyPrefix: "logs/agent-vault"+ });+ expect(JSON.parse(saved.payload).settings.keyPrefix).toBe("logs/agent-vault");++ const refused = await Promise.all(+ ["/logs", "logs/", "logs//agent-vault"].map((keyPrefix) => saveConfig({ keyPrefix }))+ );+ expect(refused.map((res) => res.statusCode)).toEqual([422, 422, 422]);+ });++ test("a non-admin member cannot read or change the settings", async () => {+ const member = await createMemberIdentity(`session-logs-member-${Date.now()}`);+ try {+ expect((await member.as("GET", SETTINGS_URL)).statusCode).toBe(403);+ expect((await member.as("GET", `${SETTINGS_URL}/health`)).statusCode).toBe(403);+ expect((await member.as("PATCH", SETTINGS_URL, { enabled: false })).statusCode).toBe(403);+ } finally {+ await member.cleanup();+ }+ });+ });++ describe("recording a chunk", () => {+ const configure = async (patch: Record<string, unknown> = {}) =>+ saveConfig({+ enabled: true,+ appConnectionId: connectionId,+ bucket: BUCKET,+ region: "us-east-1",+ keyPrefix: "logs",+ ...patch+ });++ test("writes the row before the object exists, then presigns an upload for exactly that many bytes", 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$/);++ 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(+ 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 () => {+ 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 stored = Buffer.alloc(CHUNK_BYTES, 1);+ fakeS3Bucket.put(first.uploadUrl, stored);++ const second = await recordChunk(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`);+ const [only] = (JSON.parse(read.payload) as { chunks: { presignedGetUrl: string }[] }).chunks;+ 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()}`);+ 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 resent = await recordChunk(proxy, session.id, chunk);+ const stored = Buffer.alloc(CHUNK_BYTES, 3);+ fakeS3Bucket.put(resent.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 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]);+ });++ test("two proxies can write to one session, and a chunk id is only unique within it", 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 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 }));++ 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);+ });++ test("a connection that can't be used refuses the chunk as retryable and writes no row", async () => {+ await configure();+ fakeAwsConnection.failsConfigWith("AWS refused to assume the role");+ const bundle = await createAccessBundle(`session-logs-unusable-${Date.now()}`);+ const session = await mintSession(bundle.name);+ const proxy = await createProxy(`session-logs-unusable-${Date.now()}`);++ 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);+ });++ test("is refused with the named error while session logs are off", async () => {+ await configure({ enabled: false });+ const bundle = await createAccessBundle(`session-logs-off-${Date.now()}`);+ const session = await mintSession(bundle.name);+ const proxy = await createProxy(`session-logs-off-${Date.now()}`);++ const res = await proxy.postChunk(session.id, chunkBody());+ expect(res.statusCode).toBe(400);+ 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()}`);++ const [foreignOrg] = (await testDb("organizations")+ .insert({ name: "foreign org", slug: `foreign-org-${Date.now()}`, customerId: null })+ .returning("*")) as { id: string }[];+ try {+ const [foreignProject] = (await testDb("projects")+ .insert({+ name: "foreign agent vault",+ slug: `foreign-agent-vault-${Date.now()}`,+ type: ProjectType.AgentVault,+ orgId: foreignOrg.id,+ version: 3+ })+ .returning("*")) as { id: string }[];+ const [foreignSession] = (await testDb("agent_vault_sessions")+ .insert({+ projectId: foreignProject.id,+ actorType: "user",+ actorName: "foreign actor",+ tokenHash: `foreign-${Date.now()}`+ })+ .returning("*")) as { id: string }[];++ const foreign = await proxy.postChunk(foreignSession.id, chunkBody());+ const missing = await proxy.postChunk(crypto.randomUUID(), chunkBody());++ 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();+ }+ });+ });++ describe("what resolve tells the proxy", () => {+ const configure = async (patch: Record<string, unknown> = {}) =>+ saveConfig({+ enabled: true,+ appConnectionId: connectionId,+ bucket: BUCKET,+ region: "us-east-1",+ keyPrefix: "logs",+ ...patch+ });++ const setup = async (label: string) => {+ const bundle = await createAccessBundle(`session-logs-resolve-${label}-${Date.now()}`);+ const session = await mintSession(bundle.name);+ const proxy = await createProxy(`session-logs-resolve-${label}-${Date.now()}`);+ return { session, proxy };+ };++ test("hands the key over once, then trusts the proxy's cached copy", async () => {+ await configure();+ const { session, proxy } = await setup("key");++ const first = await proxy.resolve(session.token, false);+ expect(first.statusCode, first.payload).toBe(200);+ const firstBody = JSON.parse(first.payload) as {+ sessionLogs: { enabled: boolean; sessionKey: string | null };+ };+ expect(firstBody.sessionLogs.enabled).toBe(true);+ expect(Buffer.from(firstBody.sessionLogs.sessionKey!, "base64")).toHaveLength(32);++ const second = await proxy.resolve(session.token, true);+ const secondBody = JSON.parse(second.payload) as { sessionLogs: { enabled: boolean; sessionKey: string | null } };+ expect(secondBody.sessionLogs.enabled).toBe(true);+ expect(secondBody.sessionLogs.sessionKey).toBeNull();++ const third = await proxy.resolve(session.token, false);+ expect(JSON.parse(third.payload).sessionLogs.sessionKey).toBe(firstBody.sessionLogs.sessionKey);+ });++ test("reports session logs as off, with no key, when the project has no destination", async () => {+ const { session, proxy } = await setup("off");++ const res = await proxy.resolve(session.token, false);+ expect(res.statusCode, res.payload).toBe(200);+ expect(JSON.parse(res.payload).sessionLogs).toMatchObject({ enabled: false, sessionKey: null });+ });++ test("turning session logs off reaches a running proxy on its next poll", async () => {+ await configure();+ const { session, proxy } = await setup("flip");+ expect(JSON.parse((await proxy.resolve(session.token, false)).payload).sessionLogs.enabled).toBe(true);++ expect((await saveConfig({ enabled: false })).statusCode).toBe(200);++ expect(JSON.parse((await proxy.resolve(session.token, true)).payload).sessionLogs.enabled).toBe(false);+ });++ test("a proxy that predates session logs sends no body, still resolves, and isn't sent a key it can't use", async () => {+ await configure();+ const { session, proxy } = await setup("legacy");++ const res = await proxy.resolve(session.token);+ expect(res.statusCode, res.payload).toBe(200);+ expect(JSON.parse(res.payload).sessionLogs).toEqual({ enabled: true, sessionKey: null });+ });++ test("a session log key that can't be opened turns logs off for the session, and its services still resolve", async () => {+ await configure();+ const bundle = await createAccessBundle(`session-logs-resolve-badkey-${Date.now()}`);+ const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ name: "datadog",+ hostPattern: "api.datadoghq.com",+ credential: { type: "bearer", headerName: "DD-API-KEY", headerPrefix: "", value: "abc123" }+ });+ expect(created.statusCode, created.payload).toBe(200);+ const session = await mintSession(bundle.name);+ const other = await mintSession(bundle.name);+ const proxy = await createProxy(`session-logs-resolve-badkey-${Date.now()}`);++ const { encryptedSessionLogKey } = await testDb("agent_vault_sessions").where({ id: other.id }).first();+ await testDb("agent_vault_sessions").where({ id: session.id }).update({ encryptedSessionLogKey });++ const res = await proxy.resolve(session.token, false);+ expect(res.statusCode, res.payload).toBe(200);+ const body = JSON.parse(res.payload) as {+ services: { name: string }[];+ sessionLogs: { enabled: boolean; sessionKey: string | null };+ };+ expect(body.services.map((service) => service.name)).toEqual(["datadog"]);+ expect(body.sessionLogs).toEqual({ enabled: false, sessionKey: null });+ });+ });++ describe("what the write endpoint refuses", () => {+ const configure = async () =>+ saveConfig({+ enabled: true,+ appConnectionId: connectionId,+ bucket: BUCKET,+ region: "us-east-1",+ keyPrefix: "logs"+ });++ const setup = async (label: string) => {+ const bundle = await createAccessBundle(`session-logs-refuse-${label}-${Date.now()}`);+ const session = await mintSession(bundle.name);+ const proxy = await createProxy(`session-logs-refuse-${label}-${Date.now()}`);+ return { session, proxy };+ };++ 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 }) => {+ await configure();+ const { session, proxy } = await setup("schema");++ const res = await proxy.postChunk(session.id, chunkBody(patch));+ expect(res.statusCode).toBe(422);+ });++ 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 }) => {+ 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);+ });++ test("refuses a session that retired more than a day ago", async () => {+ await configure();+ const { session, proxy } = await setup("retired");++ await testDb("agent_vault_sessions")+ .where({ id: session.id })+ .update({ revokedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000) });++ const res = await proxy.postChunk(session.id, chunkBody());+ expect(res.statusCode).toBe(401);+ });++ test("still accepts a chunk from a session revoked minutes ago", async () => {+ await configure();+ const { session, proxy } = await setup("grace");++ expect((await inject("POST", `/api/v1/agent-vault/sessions/${session.id}/revoke`)).statusCode).toBe(200);++ const res = await proxy.postChunk(session.id, chunkBody());+ expect(res.statusCode, res.payload).toBe(200);+ });++ test("refuses an unauthenticated write", async () => {+ await configure();+ const { session } = await setup("anon");++ const res = await testServer.inject({+ method: "POST",+ url: `/api/v1/agent-vault/proxy/sessions/${session.id}/logs/chunks`,+ body: chunkBody()+ });+ expect(res.statusCode).toBe(401);+ });++ test("refuses a user token: this endpoint is for proxies only", async () => {+ await configure();+ const { session } = await setup("user");++ const res = await inject("POST", `/api/v1/agent-vault/proxy/sessions/${session.id}/logs/chunks`, chunkBody());+ expect(res.statusCode).toBe(403);+ });+ });++ describe("reading a session's logs", () => {+ const configure = async () =>+ saveConfig({+ enabled: true,+ appConnectionId: connectionId,+ bucket: BUCKET,+ region: "us-east-1",+ keyPrefix: "logs"+ });++ const seedChunks = async (count: number) => {+ const bundle = await createAccessBundle(+ `session-logs-read-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`+ );+ const session = await mintSession(bundle.name);+ const proxy = await createProxy(`session-logs-read-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);+ for (let i = 0; i < count; i += 1) {+ // 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));+ }+ return { session, proxy };+ };++ 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 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;+ };++ 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(body.chunks.every((chunk) => chunk.proxyId === proxy.id)).toBe(true);++ const ids = body.chunks.map((chunk) => chunk.chunkId);+ expect([...ids].sort().reverse()).toEqual(ids);++ body.chunks.forEach((chunk) => {+ expect(fakeS3Bucket.get(chunk.presignedGetUrl!)).toHaveLength(CHUNK_BYTES);+ });+ });++ 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 });+ });++ test("a time window narrows the chunks without disturbing the cursor", 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 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 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,+ 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()}`+ );+ expect((JSON.parse(overlapping.payload) as { chunks: unknown[] }).chunks).toHaveLength(2);++ const all = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);+ expect((JSON.parse(all.payload) as { chunks: unknown[] }).chunks).toHaveLength(4);+ });++ test("pages with a cursor, and the last page reports no more", 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(+ "GET",+ `/api/v1/agent-vault/sessions/${session.id}/logs?limit=${budget}&cursor=${firstBody.nextCursor}`+ );+ 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();+ });++ test("a page stops at its byte budget as well as its record budget", 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()}`);++ for (let i = 0; i < 3; i += 1) {+ // 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();+ });++ test("pages cover every chunk when seal order and record order disagree", 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 hoursAgo = (h: number) => new Date(Date.now() - h * 60 * 60 * 1000);++ 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);+ }++ 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(seen.sort()).toEqual([...written].sort());+ expect(new Set(seen).size).toBe(written.length);+ });++ type THistoryBody = {+ chunks: { chunkId: string }[];+ nextCursor: string | null;+ liveCursor: string;+ };++ type TTailBody = {+ chunks: { chunkId: string }[];+ nextCursor: string;+ hasMore: boolean;+ };++ 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 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 late = await recordChunk(+ 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);+ });++ test("a tail read cut short resumes after its last chunk, so a backlog is worked through", 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) {+ // 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;+ }++ 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");+ });++ test.each([+ { why: "a live cursor passed to history", path: "logs", cursor: () => encodeTailCursor(new Date()) },+ {+ why: "a history cursor passed to the tail",+ path: "logs/tail",+ cursor: () => encodeHistoryCursor(nextChunkId())+ },+ { 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 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 () => {+ await configure();+ const { session } = await seedChunks(1);++ expect((await saveConfig({ bucket: "a-different-bucket" })).statusCode).toBe(200);+ expect(await readLink(session.id)).toBeNull();++ expect((await saveConfig({ bucket: BUCKET })).statusCode).toBe(200);+ expect(fakeS3Bucket.get((await readLink(session.id)) as string)).toEqual(Buffer.alloc(CHUNK_BYTES));+ });++ test("a chunk keeps its link after only the prefix changes", async () => {+ await configure();+ const { session } = 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));+ });++ test("a key copied from another session is refused rather than handed out", async () => {+ await configure();+ const { session } = await seedChunks(1);+ const other = await mintSession((await createAccessBundle(`session-logs-other-${Date.now()}`)).name);++ const { encryptedSessionLogKey } = await testDb("agent_vault_sessions").where({ id: other.id }).first();+ await testDb("agent_vault_sessions").where({ id: session.id }).update({ encryptedSessionLogKey });++ const res = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}/logs`);+ expect(res.statusCode).toBe(500);+ expect(res.payload).not.toContain("sessionKey");+ });++ test("turning session logs off still serves what was already written", async () => {+ await configure();+ const { session } = await seedChunks(2);++ 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[] };+ 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 () => {+ 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");+ });++ test("when the connection can't be used, a session lists what it recorded 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",+ 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("a session with no logs comes back empty rather than erroring", async () => {+ await configure();+ 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({+ chunks: [],+ nextCursor: null,+ sessionLogs: { sessionKey: null }+ });+ });++ test("a member reads only their own session's logs; anyone else's is a 404 like a missing one", async () => {+ await configure();+ const { session: adminSession } = await seedChunks(1);++ const member = await createMemberIdentity(`session-logs-reader-${Date.now()}`);+ try {+ const missingId = crypto.randomUUID();+ for await (const suffix of ["logs", "logs/tail"]) {+ const somebodyElses = await member.as("GET", `/api/v1/agent-vault/sessions/${adminSession.id}/${suffix}`);+ const neverExisted = await member.as("GET", `/api/v1/agent-vault/sessions/${missingId}/${suffix}`);++ expect([suffix, somebodyElses.statusCode, neverExisted.statusCode]).toEqual([suffix, 404, 404]);+ expect(somebodyElses.json().message).toBe(`Session with ID '${adminSession.id}' not found`);+ expect(neverExisted.json().message).toBe(`Session with ID '${missingId}' not found`);+ }++ const bundle = await createAccessBundle(`session-logs-reader-${Date.now()}`);+ const granted = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/members`, {+ machineIdentityIds: [member.id]+ });+ expect(granted.statusCode).toBe(200);+ const minted = await member.as("POST", "/api/v1/agent-vault/sessions", {+ accessBundles: [bundle.name],+ ttl: "1h"+ });+ expect(minted.statusCode, minted.payload).toBe(200);+ const ownSession = minted.json().session as { id: string };++ const proxy = await createProxy(`session-logs-reader-${Date.now()}`);+ const { uploadUrl } = await recordChunk(proxy, ownSession.id);+ fakeS3Bucket.put(uploadUrl, Buffer.alloc(CHUNK_BYTES));++ const own = await member.as("GET", `/api/v1/agent-vault/sessions/${ownSession.id}/logs`);+ expect(own.statusCode, own.payload).toBe(200);+ expect(own.json().chunks).toHaveLength(1);+ expect(typeof own.json().sessionLogs.sessionKey).toBe("string");+ } finally {+ 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/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 65a30caa73..61ba9413c5 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -1,16 +1,19 @@import crypto from "node:crypto";+import { createAwsAppConnection, deleteAwsAppConnection } from "e2e-test/testUtils/app-connections";+import { AccessScope, ActionProjectType, OrgMembershipRole, ProjectMembershipRole, ProjectType } from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";-import { agentVaultAccessBundleDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-dal";import { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal";import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";import { agentVaultProxyDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-dal";-import { agentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";+import {+ AGENT_VAULT_MAX_PROXIES_PER_ORG,+ agentVaultProxyServiceFactory+} from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";import { agentVaultResolveDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-resolve-dal";-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 { agentVaultSessionLogConfigDALFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-config-dal";import { groupDALFactory } from "@app/ee/services/group/group-dal";import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";import { permissionServiceFactory } from "@app/ee/services/permission/permission-service";@@ -18,6 +21,7 @@ import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { UnauthorizedError } from "@app/lib/errors";import { initLogger } from "@app/lib/logger";import { additionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { ActorType } from "@app/services/auth/auth-type";import { identityDALFactory } from "@app/services/identity/identity-dal";import { usageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";@@ -157,6 +161,51 @@ const createProjectGroup = async (projectId: string, name: string, role: Projectconst getProjectId = async () =>(JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as { projectId: string }).projectId;+const createMemberIdentity = async (name: string) => {+ const created = await inject("POST", "/api/v1/identities", {+ name,+ role: OrgMembershipRole.Member,+ organizationId: seedData1.organization.id+ });+ expect(created.statusCode).toBe(200);+ const identity = created.json().identity as { id: string };++ const attached = await inject("POST", `/api/v1/auth/universal-auth/identities/${identity.id}`, {+ accessTokenTTL: 3600,+ accessTokenMaxTTL: 3600,+ accessTokenNumUsesLimit: 0+ });+ expect(attached.statusCode).toBe(200);+ const { clientId } = attached.json().identityUniversalAuth;++ const secret = await inject("POST", `/api/v1/auth/universal-auth/identities/${identity.id}/client-secrets`, {});+ expect(secret.statusCode).toBe(200);++ const login = await testServer.inject({+ method: "POST",+ url: "/api/v1/auth/universal-auth/login",+ body: { clientId, clientSecret: secret.json().clientSecret }+ });+ expect(login.statusCode).toBe(200);+ const token = login.json().accessToken as string;++ expect(+ (+ await inject("POST", "/api/v1/agent-vault/members", {+ machineIdentityIds: [identity.id],+ role: ProjectMembershipRole.Member+ })+ ).statusCode+ ).toBe(200);++ return {+ id: identity.id,+ as: (method: "GET" | "POST" | "PATCH", url: string, body?: Record<string, unknown>) =>+ testServer.inject({ method, url, headers: { authorization: `Bearer ${token}` }, ...(body ? { body } : {}) }),+ cleanup: () => inject("DELETE", `/api/v1/identities/${identity.id}`)+ };+};+const createAccessBundle = async (name: string) => {const res = await inject("POST", "/api/v1/agent-vault/access-bundles", { name });expect(res.statusCode).toBe(200);@@ -164,6 +213,14 @@ const createAccessBundle = async (name: string) => {};describe("Agent Vault V1 Router", async () => {+ // Tests create their own proxies, and an org can hold only AGENT_VAULT_MAX_PROXIES_PER_ORG.+ beforeEach(async () => {+ const project = await testDb("projects")+ .where({ orgId: seedData1.organization.id, type: ProjectType.AgentVault })+ .first();+ if (project) await testDb("agent_vault_proxies").where({ projectId: project.id }).del();+ });+test("resolving the project bootstraps it empty, and an org admin joins through grant-admin-access", async () => {const res = await inject("GET", "/api/v1/agent-vault/project");expect(res.statusCode).toBe(200);@@ -1224,7 +1281,196 @@ describe("Agent Vault V1 Router", async () => {});});+ describe("app connections", async () => {+ test("an organization connection is out of reach here, and an Agent Vault one is not", async () => {+ const projectId = await getProjectId();++ const orgConnectionId = await createAwsAppConnection({+ name: `av-scope-org-${Date.now()}`,+ authToken: jwtAuthToken+ });++ const created = await inject("POST", "/api/v1/agent-vault/app-connections/aws", {+ name: `av-scope-own-${Date.now()}`,+ method: "access-key",+ credentials: { accessKeyId: "AKIAFAKEACCESSKEYID", secretAccessKey: "fake-secret-access-key" },+ projectId: seedData1.project.id+ });+ expect(created.statusCode, created.payload).toBe(200);+ const ownConnection = created.json().appConnection as { id: string };+ expect(ownConnection).not.toHaveProperty("projectId");+ const ownRow = (await testDb("app_connections").where({ id: ownConnection.id }).first()) as+ | { projectId: string }+ | undefined;+ expect(ownRow?.projectId).toBe(projectId);++ const listed = await inject("GET", "/api/v1/agent-vault/app-connections/aws");+ expect(listed.statusCode).toBe(200);+ const listedIds = (listed.json().appConnections as { id: string }[]).map((row) => row.id);+ expect(listedIds).toContain(ownConnection.id);+ expect(listedIds).not.toContain(orgConnectionId);++ const byId = (connectionId: string) => `/api/v1/agent-vault/app-connections/aws/${connectionId}`;+ const reaching: ["GET" | "PATCH" | "DELETE", string, Record<string, unknown>?][] = [+ ["GET", byId(orgConnectionId)],+ ["PATCH", byId(orgConnectionId), { description: "reached from the wrong scope" }],+ ["DELETE", byId(orgConnectionId)]+ ];+ for await (const [method, url, body] of reaching) {+ const res = await inject(method, url, body);+ expect([method, res.statusCode]).toEqual([method, 404]);+ }++ const survived = await inject("GET", `/api/v1/app-connections/aws/${orgConnectionId}`);+ expect(survived.statusCode).toBe(200);++ const missingId = crypto.randomUUID();+ const outOfScope = await inject("GET", byId(orgConnectionId));+ const missing = await inject("GET", byId(missingId));+ expect(outOfScope.json().message.replace(orgConnectionId, "<id>")).toBe(+ missing.json().message.replace(missingId, "<id>")+ );++ const [otherApp] = (await testDb("app_connections")+ .insert({+ name: `av-scope-gh-${Date.now()}`,+ app: AppConnection.GitHub,+ method: "pat",+ encryptedCredentials: Buffer.from("never-decrypted"),+ orgId: seedData1.organization.id+ })+ .returning("id")) as { id: string }[];+ try {+ expect((await inject("GET", byId(otherApp.id))).statusCode).toBe(404);+ } finally {+ await testDb("app_connections").where({ id: otherApp.id }).delete();+ }++ const member = await createMemberIdentity(`av-scope-member-${Date.now()}`);+ try {+ expect((await member.as("GET", byId(orgConnectionId))).statusCode).toBe(404);+ expect((await member.as("GET", byId(ownConnection.id))).statusCode).toBe(403);+ } finally {+ await member.cleanup();+ }++ expect((await inject("GET", byId(ownConnection.id))).statusCode).toBe(200);+ expect(+ (await inject("PATCH", byId(ownConnection.id), { description: "reached from its own scope" })).statusCode+ ).toBe(200);+ expect((await inject("DELETE", byId(ownConnection.id))).statusCode).toBe(200);++ await deleteAwsAppConnection({ connectionId: orgConnectionId, authToken: jwtAuthToken });+ });++ test("an update through another app's route is refused before it writes, like a delete", async () => {+ const created = await inject("POST", "/api/v1/agent-vault/app-connections/aws", {+ name: `av-wrong-app-own-${Date.now()}`,+ method: "access-key",+ credentials: { accessKeyId: "AKIAFAKEACCESSKEYID", secretAccessKey: "fake-secret-access-key" }+ });+ expect(created.statusCode, created.payload).toBe(200);+ const ownAws = await testDb("app_connections").where({ id: created.json().appConnection.id }).first();+ const orgAwsId = await createAwsAppConnection({+ name: `av-wrong-app-org-${Date.now()}`,+ authToken: jwtAuthToken+ });+ const orgAws = await testDb("app_connections").where({ id: orgAwsId }).first();++ // Rows only, so a GitHub connection can sit where the create path would never put one.+ const githubRow = (name: string, projectId: string | null, encryptedCredentials: Buffer) => ({+ name,+ app: AppConnection.GitHub,+ method: "pat",+ encryptedCredentials,+ orgId: seedData1.organization.id,+ projectId+ });+ const [inAgentVault] = (await testDb("app_connections")+ .insert(githubRow(`av-wrong-app-gh-${Date.now()}`, ownAws.projectId, ownAws.encryptedCredentials))+ .returning("*")) as { id: string }[];+ const [inOrg] = (await testDb("app_connections")+ .insert(githubRow(`org-wrong-app-gh-${Date.now()}`, null, orgAws.encryptedCredentials))+ .returning("*")) as { id: string }[];++ try {+ const routes = [+ [inAgentVault.id, `/api/v1/agent-vault/app-connections/aws/${inAgentVault.id}`],+ [inOrg.id, `/api/v1/app-connections/aws/${inOrg.id}`]+ ] as const;+ for await (const [id, url] of routes) {+ const res = await inject("PATCH", url, { description: "through the wrong route" });+ expect([url, res.statusCode]).toEqual([url, 400]);+ expect(res.json().message).toBe(`App Connection with ID ${id} is not for App "aws"`);+ expect((await testDb("app_connections").where({ id }).first()).description).toBeNull();+ }+ } finally {+ await testDb("app_connections").whereIn("id", [inAgentVault.id, inOrg.id, ownAws.id, orgAwsId]).delete();+ }+ });++ test("only AWS is offered under Agent Vault", async () => {+ const res = await inject("GET", `/api/v1/app-connections/options?projectType=${ProjectType.AgentVault}`);+ expect(res.statusCode).toBe(200);+ const apps = (res.json().appConnectionOptions as { app: string }[]).map((option) => option.app);+ expect(apps).toEqual(["aws"]);+ });++ test("the shared route refuses a non-AWS connection in the Agent Vault project", async () => {+ const projectId = await getProjectId();++ const res = await inject("POST", "/api/v1/app-connections/humanitec", {+ name: `av-non-aws-${Date.now()}`,+ method: "api-token",+ credentials: { apiToken: "fake-api-token" },+ projectId+ });+ expect(res.statusCode, res.payload).toBe(400);+ expect(res.json().message).toBe("Humanitec Connections can't be used in this project. It supports: AWS.");+ });+ });+describe("sessions", async () => {+ test("a session reads by id, and one you may not see is indistinguishable from one that is not there", async () => {+ const bundle = await createAccessBundle(`session-by-id-${Date.now()}`);+ const mint = await inject("POST", "/api/v1/agent-vault/sessions", {+ accessBundles: [bundle.name],+ ttl: "1h"+ });+ expect(mint.statusCode).toBe(200);+ const { session } = JSON.parse(mint.payload) as { session: { id: string } };++ const mine = await inject("GET", `/api/v1/agent-vault/sessions/${session.id}`);+ expect(mine.statusCode).toBe(200);+ expect(mine.json().session).toMatchObject({+ id: session.id,+ status: "active",+ actor: expect.objectContaining({+ type: "user",+ id: seedData1.id,+ username: seedData1.username,+ email: seedData1.email+ }),+ accessBundles: [expect.objectContaining({ name: bundle.name })]+ });++ const member = await createMemberIdentity(`session-by-id-member-${Date.now()}`);+ try {+ expect((await member.as("GET", "/api/v1/agent-vault/sessions")).statusCode).toBe(200);++ const missingId = crypto.randomUUID();+ const somebodyElses = await member.as("GET", `/api/v1/agent-vault/sessions/${session.id}`);+ const neverExisted = await member.as("GET", `/api/v1/agent-vault/sessions/${missingId}`);++ expect([somebodyElses.statusCode, neverExisted.statusCode]).toEqual([404, 404]);+ expect(somebodyElses.json().message).toBe(`Session with ID '${session.id}' not found`);+ expect(neverExisted.json().message).toBe(`Session with ID '${missingId}' not found`);+ expect(somebodyElses.json().error).toBe(neverExisted.json().error);+ } finally {+ await member.cleanup();+ }+ });+test("the bundle comes only from the session row", async () => {const granted = await createAccessBundle("session-granted");const notNamed = await createAccessBundle("session-not-named");@@ -1324,7 +1570,7 @@ describe("Agent Vault V1 Router", async () => {const res = await inject("GET", `/api/v1/agent-vault/sessions?scope=all&${query}`);expect(res.statusCode).toBe(200);return JSON.parse(res.payload) as {- sessions: { id: string; actorName: string; accessBundles: { name: string }[] }[];+ sessions: { id: string; actor: Record<string, unknown>; accessBundles: { name: string }[] }[];totalCount: number;};};@@ -1390,6 +1636,14 @@ describe("Agent Vault V1 Router", async () => {expect: (r) => {expect(r.totalCount).toBe(1);expect(r.sessions[0].id).toBe(orphaned);+ expect(r.sessions[0].actor).toEqual({+ type: "user",+ id: null,+ username: "[email protected]",+ email: "[email protected]",+ firstName: "Gone Person",+ lastName: null+ });}},{@@ -1453,6 +1707,19 @@ describe("Agent Vault V1 Router", async () => {why: "a status with no members inside the match is empty",query: "search=matrix-&status=expired&limit=100",expect: (r) => expect(r.totalCount).toBe(0)+ },+ {+ why: "several statuses match any of them",+ query: "search=matrix-&status=active,revoked&limit=100",+ expect: (r) => expect(r.totalCount).toBe(7)+ },+ {+ why: "a status with no members adds nothing to one that has them",+ query: "search=matrix-&status=revoked,expired&limit=100",+ expect: (r) => {+ expect(r.totalCount).toBe(1);+ expect(r.sessions[0].id).toBe(orphaned);+ }}];@@ -1508,6 +1775,10 @@ describe("Agent Vault V1 Router", async () => {const first = await inject("POST", `/api/v1/agent-vault/sessions/${session.id}/revoke`);expect(first.statusCode).toBe(200);+ expect(JSON.parse(first.payload).session).toMatchObject({+ status: "revoked",+ actor: { type: "user", id: seedData1.id }+ });const firstRevokedAt = JSON.parse(first.payload).session.revokedAt as string;const second = await inject("POST", `/api/v1/agent-vault/sessions/${session.id}/revoke`);@@ -1521,22 +1792,115 @@ describe("Agent Vault V1 Router", async () => {});describe("session resolve", async () => {- const buildResolver = () =>+ const buildResolver = (+ overrides: Partial<+ Pick<Parameters<typeof agentVaultProxyServiceFactory>[0], "licenseService" | "agentVaultSessionLogConfigDAL">+ > = {}+ ) =>agentVaultProxyServiceFactory({agentVaultProxyDAL: agentVaultProxyDALFactory(testDb),agentVaultResolveDAL: agentVaultResolveDALFactory(testDb),agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),+ agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),permissionService: buildPermissionService(),kmsService: {createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })} as never,- resourceAuthMethodService: {} as never+ licenseService: { getPlan: () => Promise.resolve({ agentVaultByoS3: true }) } as never,+ resourceAuthMethodService: {} as never,+ ...overrides+ });++ const mintForResolve = async (name: string) => {+ const bundle = await createAccessBundle(name);+ const mint = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundle.name], ttl: "1h" });+ expect(mint.statusCode).toBe(200);+ const { session } = JSON.parse(mint.payload) as { session: { token: string } };+ const proxyRes = await inject("POST", "/api/v1/agent-vault/proxies", { name });+ expect(proxyRes.statusCode).toBe(200);+ const { proxy } = JSON.parse(proxyRes.payload) as { proxy: { id: string } };+ return { session, proxy };+ };++ const sessionLogConfig = (enabled: boolean) => ({+ findOne: () =>+ Promise.resolve({+ enabled,+ appConnectionId: crypto.randomUUID(),+ bucket: "session-logs",+ region: "us-east-1",+ keyPrefix: null+ })+ });++ test("resolve reports session logs off when the plan lacks them", async () => {+ const { session, proxy } = await mintForResolve("resolve-session-logs-unlicensed");+ const getPlan = vi.fn(() => Promise.resolve({ agentVaultByoS3: false }));+ const resolver = buildResolver({+ licenseService: {+ getPlan,+ isServingFallbackPlan: () => Promise.resolve(false),+ getLastKnownPlan: () => Promise.resolve(null)+ } as never,+ agentVaultSessionLogConfigDAL: sessionLogConfig(true) as never+ });++ const resolved = await resolver.resolveSession({+ proxyId: proxy.id,+ orgId: seedData1.organization.id,+ sessionToken: session.token,+ hasSessionLogKey: true});+ expect(getPlan).toHaveBeenCalledWith(seedData1.organization.id);+ expect(resolved.sessionLogs).toEqual({ enabled: false, sessionKey: null });+ });++ test("while the plan can't be confirmed, a proxy that holds the key keeps recording and no new key goes out", async () => {+ const { session, proxy } = await mintForResolve("resolve-session-logs-plan-unknown");+ const resolver = buildResolver({+ licenseService: {+ getPlan: () => Promise.resolve({ agentVaultByoS3: false }),+ isServingFallbackPlan: () => Promise.resolve(true),+ getLastKnownPlan: () => Promise.resolve(null)+ } as never,+ agentVaultSessionLogConfigDAL: sessionLogConfig(true) as never+ });+ const resolve = (hasSessionLogKey: boolean) =>+ resolver.resolveSession({+ proxyId: proxy.id,+ orgId: seedData1.organization.id,+ sessionToken: session.token,+ hasSessionLogKey+ });++ expect((await resolve(true)).sessionLogs).toEqual({ enabled: true, sessionKey: null });+ expect((await resolve(false)).sessionLogs).toEqual({ enabled: false, sessionKey: null });+ });++ test("resolve does not read the plan while session logs are off", async () => {+ const { session, proxy } = await mintForResolve("resolve-session-logs-off");+ const getPlan = vi.fn(() => Promise.resolve({ agentVaultByoS3: true }));+ const resolver = buildResolver({+ licenseService: { getPlan } as never,+ agentVaultSessionLogConfigDAL: sessionLogConfig(false) as never+ });++ const resolved = await resolver.resolveSession({+ proxyId: proxy.id,+ orgId: seedData1.organization.id,+ sessionToken: session.token,+ hasSessionLogKey: true+ });++ expect(getPlan).not.toHaveBeenCalled();+ expect(resolved.sessionLogs.enabled).toBe(false);+ });+test("resolve carries the policy and the decrypted transformations", async () => {const bundle = await createAccessBundle("resolve-transformations");const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {@@ -1569,6 +1933,7 @@ describe("Agent Vault V1 Router", async () => {agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),+ agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),permissionService: buildPermissionService(),@@ -1576,13 +1941,15 @@ describe("Agent Vault V1 Router", async () => {createCipherPairWithDataKey: () =>Promise.resolve({ decryptor: () => Buffer.from(JSON.stringify({ value: "unsealed" })) })} as never,+ licenseService: { getPlan: () => Promise.resolve({ agentVaultByoS3: true }) } as never,resourceAuthMethodService: {} as never});const resolved = await resolver.resolveSession({proxyId: proxy.id,orgId: seedData1.organization.id,- sessionToken: session.token+ sessionToken: session.token,+ hasSessionLogKey: false});expect(resolved.services).toHaveLength(1);@@ -1619,7 +1986,8 @@ describe("Agent Vault V1 Router", async () => {resolver.resolveSession({proxyId: proxy.id,orgId: seedData1.organization.id,- sessionToken: session.token+ sessionToken: session.token,+ hasSessionLogKey: false});const membership = await testDb("memberships")@@ -1656,7 +2024,8 @@ describe("Agent Vault V1 Router", async () => {buildResolver().resolveSession({proxyId: proxy.id,orgId: seedData1.organization.id,- sessionToken: session.token+ sessionToken: session.token,+ hasSessionLogKey: false});const [doomed] = (await testDb("users")@@ -1686,19 +2055,27 @@ describe("Agent Vault V1 Router", async () => {buildResolver().resolveSession({proxyId: proxy.id,orgId: seedData1.organization.id,- sessionToken: session.token+ sessionToken: session.token,+ hasSessionLogKey: false});- const identity = await createOrgIdentity(`doomed-${crypto.randomUUID()}`);- await testDb("agent_vault_sessions").where({ id: session.id }).update({ userId: null, identityId: identity.id });+ const identityName = `doomed-${crypto.randomUUID()}`;+ const identity = await createOrgIdentity(identityName);+ await testDb("agent_vault_sessions")+ .where({ id: session.id })+ .update({ userId: null, identityId: identity.id, actorType: "machineIdentity", actorName: identityName });await deleteOrgIdentity(identity.id);await expect(resolve()).rejects.toThrow("The identity this session belonged to has been deleted");// The list agrees with resolve: an ownerless session is shown as revoked, not active.const list = await inject("GET", "/api/v1/agent-vault/sessions?scope=all&limit=100");- const { sessions } = JSON.parse(list.payload) as { sessions: { id: string; status: string }[] };- expect(sessions.find((row) => row.id === session.id)?.status).toBe("revoked");+ const { sessions } = JSON.parse(list.payload) as {+ sessions: { id: string; status: string; actor: Record<string, unknown> }[];+ };+ const row = sessions.find((listed) => listed.id === session.id);+ expect(row?.status).toBe("revoked");+ expect(row?.actor).toEqual({ type: "machineIdentity", id: null, name: identityName });});test("an expired time-limited role stops resolving even though its membership row remains", async () => {@@ -1722,16 +2099,23 @@ describe("Agent Vault V1 Router", async () => {agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),+ agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),permissionService: buildPermissionService(),kmsService: {createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })} as never,+ licenseService: { getPlan: () => Promise.resolve({ agentVaultByoS3: true }) } as never,resourceAuthMethodService: {} as never});const resolve = () =>- resolver.resolveSession({ proxyId: proxy.id, orgId: seedData1.organization.id, sessionToken: session.token });+ resolver.resolveSession({+ proxyId: proxy.id,+ orgId: seedData1.organization.id,+ sessionToken: session.token,+ hasSessionLogKey: false+ });const membership = await testDb("memberships").where({ scope: AccessScope.Project, scopeProjectId: projectId, actorUserId: seedData1.id })@@ -1762,6 +2146,17 @@ describe("Agent Vault V1 Router", async () => {});describe("proxies", async () => {+ test("an org can hold AGENT_VAULT_MAX_PROXIES_PER_ORG proxies, and the next create is refused", async () => {+ for (let i = 0; i < AGENT_VAULT_MAX_PROXIES_PER_ORG; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ expect((await inject("POST", "/api/v1/agent-vault/proxies", { name: `cap-${i}` })).statusCode).toBe(200);+ }++ const refused = await inject("POST", "/api/v1/agent-vault/proxies", { name: "cap-over" });+ expect(refused.statusCode).toBe(400);+ expect(JSON.parse(refused.payload).message).toContain(`up to ${AGENT_VAULT_MAX_PROXIES_PER_ORG} proxies`);+ });+test("a create that omits the settings gets the documented defaults", async () => {const created = await inject("POST", "/api/v1/agent-vault/proxies", { name: "settings-defaults" });expect(created.statusCode).toBe(200);@@ -1849,60 +2244,6 @@ describe("Agent Vault V1 Router", async () => {});});- describe("retention sweep", async () => {- test("reaps sessions a month after they stopped working and leaves live ones alone", async () => {- const bundle = await createAccessBundle("sweep-bundle");- const mintOne = async (ttl: string) => {- const res = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundle.name], ttl });- expect(res.statusCode).toBe(200);- return (JSON.parse(res.payload) as { session: { id: string } }).session.id;- };- const longExpired = await mintOne("1h");- const longRevoked = await mintOne("never");- const recentlyExpired = await mintOne("1h");- const live = await mintOne("7d");- const neverEnding = await mintOne("never");- const oldOrphan = await mintOne("never");- const recentOrphan = await mintOne("never");-- const daysAgo = (days: number) => new Date(Date.now() - days * 24 * 60 * 60 * 1000);- // Ownerless sessions go by age, since nothing records when their actor was deleted.- await testDb("agent_vault_sessions")- .where({ id: oldOrphan })- .update({ userId: null, identityId: null, createdAt: daysAgo(31) });- await testDb("agent_vault_sessions").where({ id: recentOrphan }).update({ userId: null, identityId: null });- await testDb("agent_vault_sessions")- .where({ id: longExpired })- .update({ expiresAt: daysAgo(31) });- await testDb("agent_vault_sessions")- .where({ id: longRevoked })- .update({ revokedAt: daysAgo(31) });- await testDb("agent_vault_sessions")- .where({ id: recentlyExpired })- .update({ expiresAt: new Date(Date.now() - 60 * 60 * 1000) });- const sweeper = agentVaultSessionServiceFactory({- agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),- agentVaultSessionAccessBundleDAL: agentVaultSessionAccessBundleDALFactory(testDb),- agentVaultAccessBundleDAL: agentVaultAccessBundleDALFactory(testDb),- membershipDAL: membershipDALFactory(testDb),- permissionService: { getProjectPermission: () => Promise.reject(new Error("not used by the sweep")) }- });- await sweeper.sweepRetiredSessions();-- const remaining = (await testDb("agent_vault_sessions")- .whereIn("id", [longExpired, longRevoked, recentlyExpired, live, neverEnding, oldOrphan, recentOrphan])- .select("id")) as { id: string }[];- expect(remaining.map((row) => row.id).sort()).toEqual([recentlyExpired, live, neverEnding, recentOrphan].sort());-- const orphans = await testDb("agent_vault_session_access_bundles").whereIn("sessionId", [- longExpired,- longRevoked,- oldOrphan- ]);- expect(orphans).toHaveLength(0);- });- });-describe("roles", async () => {test("the predefined roles are admin and member only", async () => {const { projectId } = JSON.parse((await inject("GET", "/api/v1/agent-vault/project")).payload) as {@@ -2389,16 +2730,23 @@ describe("Agent Vault V1 Router", async () => {agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),+ agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),permissionService: buildPermissionService(),kmsService: {createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })} as never,+ licenseService: { getPlan: () => Promise.resolve({ agentVaultByoS3: true }) } as never,resourceAuthMethodService: {} as never});const resolve = () =>- resolver.resolveSession({ proxyId: proxy.id, orgId: seedData1.organization.id, sessionToken: session.token });+ resolver.resolveSession({+ proxyId: proxy.id,+ orgId: seedData1.organization.id,+ sessionToken: session.token,+ hasSessionLogKey: false+ });expect((await resolve()).services).toHaveLength(1);@@ -2480,16 +2828,23 @@ describe("Agent Vault V1 Router", async () => {agentVaultServiceCustomHeaderDAL: agentVaultServiceCustomHeaderDALFactory(testDb),agentVaultServiceSubstitutionDAL: agentVaultServiceSubstitutionDALFactory(testDb),agentVaultSessionDAL: agentVaultSessionDALFactory(testDb),+ agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),permissionService: buildPermissionService(),kmsService: {createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })} as never,+ licenseService: { getPlan: () => Promise.resolve({ agentVaultByoS3: true }) } as never,resourceAuthMethodService: {} as never});const resolve = () =>- resolver.resolveSession({ proxyId: proxy.id, orgId: seedData1.organization.id, sessionToken: session.token });+ resolver.resolveSession({+ proxyId: proxy.id,+ orgId: seedData1.organization.id,+ sessionToken: session.token,+ hasSessionLogKey: false+ });expect((await resolve()).services).toHaveLength(1);const groupMembership = await testDb("memberships")diff --git a/backend/e2e-test/setup/reset-fakes.ts b/backend/e2e-test/setup/reset-fakes.tsindex 8f20e20bba..d05c5951f2 100644--- a/backend/e2e-test/setup/reset-fakes.ts+++ b/backend/e2e-test/setup/reset-fakes.ts@@ -1,6 +1,7 @@import { fakeAwsConnection } from "e2e-test/fakes/aws-connection-fns";import { fakeIamUserSecret } from "e2e-test/fakes/aws-iam-user-secret-rotation-fns";import { fakeParameterStore } from "e2e-test/fakes/aws-parameter-store-sync-fns";+import { fakeS3Bucket } from "e2e-test/fakes/s3";// The fakes are module singletons shared with the server booted in this same process, and the// suite runs in a single fork with fileParallelism disabled. So a spec that seeds a@@ -15,5 +16,6 @@ import { fakeParameterStore } from "e2e-test/fakes/aws-parameter-store-sync-fns"beforeAll(() => {fakeParameterStore.reset();fakeAwsConnection.reset();+ fakeS3Bucket.reset();fakeIamUserSecret.reset();});diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 76d04e01ea..9c0efc4678 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -11,6 +11,7 @@ import { TAgentVaultMembershipServiceFactory } from "@app/ee/services/agent-vaulimport { TAgentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-project/agent-vault-project-resolver";import { TAgentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";import { TAgentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";+import { TAgentVaultSessionLogServiceFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-service";import { TAssumePrivilegeServiceFactory } from "@app/ee/services/assume-privilege/assume-privilege-types";import { TAuditLogServiceFactory, TCreateAuditLogDTO } from "@app/ee/services/audit-log/audit-log-types";import { TAuditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-service";@@ -371,6 +372,7 @@ declare module "fastify" {agentVaultAccessBundle: TAgentVaultAccessBundleServiceFactory;agentVaultProxy: TAgentVaultProxyServiceFactory;agentVaultSession: TAgentVaultSessionServiceFactory;+ agentVaultSessionLog: TAgentVaultSessionLogServiceFactory;agentVaultMembership: TAgentVaultMembershipServiceFactory;certManagerInstance: TCertManagerInstanceServiceFactory;certManagerExport: TCertManagerExportServiceFactory;diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 599f7d3e6c..62db78d2c4 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -38,6 +38,12 @@ import {TAgentVaultSessionAccessBundles,TAgentVaultSessionAccessBundlesInsert,TAgentVaultSessionAccessBundlesUpdate,+ TAgentVaultSessionLogChunks,+ TAgentVaultSessionLogChunksInsert,+ TAgentVaultSessionLogChunksUpdate,+ TAgentVaultSessionLogConfigs,+ TAgentVaultSessionLogConfigsInsert,+ TAgentVaultSessionLogConfigsUpdate,TAgentVaultSessions,TAgentVaultSessionsInsert,TAgentVaultSessionsUpdate,@@ -1824,6 +1830,16 @@ declare module "knex/types/tables" {TAgentVaultProxiesInsert,TAgentVaultProxiesUpdate>;+ [TableName.AgentVaultSessionLogConfig]: KnexOriginal.CompositeTableType<+ TAgentVaultSessionLogConfigs,+ TAgentVaultSessionLogConfigsInsert,+ TAgentVaultSessionLogConfigsUpdate+ >;+ [TableName.AgentVaultSessionLogChunk]: KnexOriginal.CompositeTableType<+ TAgentVaultSessionLogChunks,+ TAgentVaultSessionLogChunksInsert,+ TAgentVaultSessionLogChunksUpdate+ >;[TableName.PamAccountPolicy]: KnexOriginal.CompositeTableType<TPamAccountPolicies,TPamAccountPoliciesInsert,diff --git a/backend/src/db/migrations/20260923104435_agent-vault-session-logs.ts b/backend/src/db/migrations/20260923104435_agent-vault-session-logs.tsnew file mode 100644index 0000000000..2a733e4693--- /dev/null+++ b/backend/src/db/migrations/20260923104435_agent-vault-session-logs.ts@@ -0,0 +1,102 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.AgentVaultSessionLogConfig))) {+ await knex.schema.createTable(TableName.AgentVaultSessionLogConfig, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.string("projectId", 36).notNullable().unique();+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");++ t.boolean("enabled").notNullable().defaultTo(false);++ t.uuid("appConnectionId");+ t.foreign("appConnectionId").references("id").inTable(TableName.AppConnection).deferrable("deferred");+ t.index(["appConnectionId"]);++ t.string("bucket", 255);+ t.string("region", 32);+ t.string("keyPrefix", 512);++ t.bigint("storedChunkCount").notNullable().defaultTo(0);++ t.timestamps(true, true, true);+ });++ await createOnUpdateTrigger(knex, TableName.AgentVaultSessionLogConfig);+ }++ if (!(await knex.schema.hasTable(TableName.AgentVaultSessionLogChunk))) {+ 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");++ // Deliberately not a foreign key: every sealed record carries its proxyId and the browser checks it+ // against this column, so a SET NULL on proxy deletion would make every chunk that proxy wrote unreadable.+ 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);+ }++ if (await knex.schema.hasTable(TableName.AgentVaultSession)) {+ const hasSessionLogKey = await knex.schema.hasColumn(TableName.AgentVaultSession, "encryptedSessionLogKey");+ if (!hasSessionLogKey) {+ await knex.schema.alterTable(TableName.AgentVaultSession, (t) => {+ t.binary("encryptedSessionLogKey");+ });+ }+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasTable(TableName.AgentVaultSession)) {+ const hasSessionLogKey = await knex.schema.hasColumn(TableName.AgentVaultSession, "encryptedSessionLogKey");+ if (hasSessionLogKey) {+ await knex.schema.alterTable(TableName.AgentVaultSession, (t) => {+ t.dropColumn("encryptedSessionLogKey");+ });+ }+ }++ await dropOnUpdateTrigger(knex, TableName.AgentVaultSessionLogChunk);+ await knex.schema.dropTableIfExists(TableName.AgentVaultSessionLogChunk);++ await dropOnUpdateTrigger(knex, TableName.AgentVaultSessionLogConfig);+ await knex.schema.dropTableIfExists(TableName.AgentVaultSessionLogConfig);+}diff --git a/backend/src/db/migrations/20260928031017_agent-vault-session-actor-type.ts b/backend/src/db/migrations/20260928031017_agent-vault-session-actor-type.tsnew file mode 100644index 0000000000..cd88e3a1f9--- /dev/null+++ b/backend/src/db/migrations/20260928031017_agent-vault-session-actor-type.ts@@ -0,0 +1,34 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.AgentVaultSession, "actorType");+ if (!hasColumn) {+ await knex.schema.alterTable(TableName.AgentVaultSession, (t) => {+ t.string("actorType").nullable();+ });+ }++ // A session whose owner was deleted has lost both ids, so its snapshot tells them apart: mint records an+ // email only for a user.+ await knex.raw(+ `UPDATE ?? SET "actorType" = CASE+ WHEN "identityId" IS NOT NULL THEN 'machineIdentity'+ WHEN "userId" IS NOT NULL THEN 'user'+ WHEN "actorEmail" IS NOT NULL THEN 'user'+ ELSE 'machineIdentity'+ END+ WHERE "actorType" IS NULL`,+ [TableName.AgentVaultSession]+ );+}++export async function down(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.AgentVaultSession, "actorType");+ if (hasColumn) {+ await knex.schema.alterTable(TableName.AgentVaultSession, (t) => {+ t.dropColumn("actorType");+ });+ }+}diff --git a/backend/src/db/schemas/agent-vault-session-log-chunks.ts b/backend/src/db/schemas/agent-vault-session-log-chunks.tsnew file mode 100644index 0000000000..9e8c271b1c--- /dev/null+++ b/backend/src/db/schemas/agent-vault-session-log-chunks.ts@@ -0,0 +1,39 @@+// 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.tsnew file mode 100644index 0000000000..770754202f--- /dev/null+++ b/backend/src/db/schemas/agent-vault-session-log-configs.ts@@ -0,0 +1,30 @@+// 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 AgentVaultSessionLogConfigsSchema = z.object({+ id: z.string().uuid(),+ projectId: z.string(),+ enabled: z.boolean().default(false),+ appConnectionId: z.string().uuid().nullable().optional(),+ 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()+});++export type TAgentVaultSessionLogConfigs = z.infer<typeof AgentVaultSessionLogConfigsSchema>;+export type TAgentVaultSessionLogConfigsInsert = Omit<+ z.input<typeof AgentVaultSessionLogConfigsSchema>,+ TImmutableDBKeys+>;+export type TAgentVaultSessionLogConfigsUpdate = Partial<+ Omit<z.input<typeof AgentVaultSessionLogConfigsSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/agent-vault-sessions.ts b/backend/src/db/schemas/agent-vault-sessions.tsindex 9ebae2bb3f..740b8d2ba0 100644--- a/backend/src/db/schemas/agent-vault-sessions.ts+++ b/backend/src/db/schemas/agent-vault-sessions.ts@@ -5,6 +5,8 @@import { z } from "zod";+import { zodBuffer } from "@app/lib/zod";+import { TImmutableDBKeys } from "./models";export const AgentVaultSessionsSchema = z.object({@@ -18,7 +20,9 @@ export const AgentVaultSessionsSchema = z.object({expiresAt: z.date().nullable().optional(),revokedAt: z.date().nullable().optional(),createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ encryptedSessionLogKey: zodBuffer.nullable().optional(),+ actorType: z.string().nullable().optional()});export type TAgentVaultSessions = z.infer<typeof AgentVaultSessionsSchema>;diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 88f3152396..212f1056c9 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -10,6 +10,8 @@ export * from "./agent-vault-service-custom-headers";export * from "./agent-vault-service-substitutions";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 "./alert-channel-memberships";export * from "./alert-channel-recipients";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex fcd9585894..635ff9e65e 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -281,6 +281,8 @@ export enum TableName {AgentVaultSession = "agent_vault_sessions",AgentVaultSessionAccessBundle = "agent_vault_session_access_bundles",AgentVaultProxy = "agent_vault_proxies",+ AgentVaultSessionLogConfig = "agent_vault_session_log_configs",+ AgentVaultSessionLogChunk = "agent_vault_session_log_chunks",VaultExternalMigrationConfig = "vault_external_migration_configs",ExternalMigrationConfig = "external_migration_configs",diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.tsindex 02d5a75650..eba60b8f32 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts@@ -6,7 +6,7 @@ import {AGENT_VAULT_NO_CONTROL_CHARS_RE} from "@app/ee/services/agent-vault/agent-vault-credential-schemas";import { AgentVaultCredentialType } from "@app/ee/services/agent-vault/agent-vault-enums";-import { parseHostPatterns } from "@app/ee/services/agent-vault/agent-vault-host-pattern";+import { parseHostPatterns } from "@app/ee/services/agent-vault/agent-vault-host-pattern-fns";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { AGENT_VAULT } from "@app/lib/api-docs";import { ApiDocsTags } from "@app/lib/api-docs/constants";diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-app-connection-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-app-connection-router.tsnew file mode 100644index 0000000000..c90aeefc59--- /dev/null+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-app-connection-router.ts@@ -0,0 +1,79 @@+import { FastifyRequest } from "fastify";+import { z } from "zod";++import { ApiDocsTags, AppConnections } from "@app/lib/api-docs";+import { InternalServerError } from "@app/lib/errors";+import { slugSchema } from "@app/server/lib/schemas";+import {+ buildAppConnectionRouteContext,+ buildCreateAppConnectionRoute,+ buildDeleteAppConnectionRoute,+ buildGetAppConnectionRoute,+ buildListAppConnectionsRoute,+ buildUpdateAppConnectionRoute+} from "@app/server/routes/v1/app-connection-routers/app-connection-endpoints";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import {+ SanitizedAwsConnectionSchema,+ UpdateAwsConnectionSchema,+ ValidateAwsConnectionCredentialsSchema+} from "@app/services/app-connection/aws";++// Agent Vault picks the project itself, so creating a connection only asks for a name, description and AWS credentials.+const AgentVaultAwsConnectionCreateSchema = ValidateAwsConnectionCredentialsSchema.and(+ z.object({+ name: slugSchema({ field: "name" }).describe(AppConnections.CREATE(AppConnection.AWS).name),+ description: z+ .string()+ .trim()+ .max(256, "Description cannot exceed 256 characters")+ .nullish()+ .describe(AppConnections.CREATE(AppConnection.AWS).description)+ })+);++// Agent Vault never shows its project ID, so its connections don't carry one.+const [AssumeRoleConnectionSchema, AccessKeyConnectionSchema] = SanitizedAwsConnectionSchema.options;+const AgentVaultAwsConnectionSchema = z.discriminatedUnion("method", [+ AssumeRoleConnectionSchema.omit({ projectId: true }).describe(AssumeRoleConnectionSchema.description ?? ""),+ AccessKeyConnectionSchema.omit({ projectId: true }).describe(AccessKeyConnectionSchema.description ?? "")+]);++export const registerAgentVaultAppConnectionRouter = async (server: FastifyZodProvider) => {+ const ctx = buildAppConnectionRouteContext({+ server,+ app: AppConnection.AWS,+ sanitizedResponseSchema: AgentVaultAwsConnectionSchema,+ operationIdPrefix: "AgentVault",+ tags: [ApiDocsTags.AgentVaultAppConnections]+ });++ const resolveScope = (req: FastifyRequest) => {+ const projectId = req.internalAgentVaultProjectId;+ if (!projectId) {+ throw new InternalServerError({+ message:+ "Could not load Agent Vault for this organization. Try again, and contact support if it keeps happening."+ });+ }+ return { projectId };+ };++ buildListAppConnectionsRoute(ctx, { description: "Lists the AWS connections scoped to Agent Vault", resolveScope });+ buildGetAppConnectionRoute(ctx, { description: "Gets an AWS connection scoped to Agent Vault", resolveScope });+ buildCreateAppConnectionRoute(ctx, {+ createSchema: AgentVaultAwsConnectionCreateSchema,+ description: "Creates an AWS connection scoped to Agent Vault. Only Agent Vault can use the connection.",+ resolveScope+ });+ buildUpdateAppConnectionRoute(ctx, {+ updateSchema: UpdateAwsConnectionSchema,+ description: "Updates an AWS connection scoped to Agent Vault",+ resolveScope+ });+ buildDeleteAppConnectionRoute(ctx, {+ description:+ "Deletes an AWS connection scoped to Agent Vault. If session logs use the connection, switch them to another connection or to none first.",+ resolveScope+ });+};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 0b92195ce1..1a946c86c5 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@@ -2,12 +2,21 @@ import { z } from "zod";import { AgentVaultTrafficPolicy } from "@app/ee/services/agent-vault/agent-vault-enums";import { AGENT_VAULT_SESSION_TOKEN_PREFIX } from "@app/ee/services/agent-vault-session/agent-vault-session-fns";+import {+ AgentVaultSessionLogChunkCreateResponseSchema,+ AgentVaultSessionLogChunkCreateSchema+} from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-schemas";import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";import { ResourceAuthMethodType } from "@app/ee/services/resource-auth-method/resource-auth-method-fns";import { AGENT_VAULT } from "@app/lib/api-docs";import { ApiDocsTags } from "@app/lib/api-docs/constants";import { logger } from "@app/lib/logger";-import { agentVaultHeartbeatLimit, agentVaultResolveLimit, writeLimit } from "@app/server/config/rateLimiter";+import {+ agentVaultHeartbeatLimit,+ agentVaultResolveLimit,+ agentVaultSessionLogChunkLimit,+ writeLimit+} from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { ActorType, AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";@@ -26,6 +35,7 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProviurl: "/login",config: { rateLimit: writeLimit },schema: {+ hide: true,operationId: "loginAgentVaultProxy",description:"Proxy login. Body discriminates on `method`; token exchanges a one-time enrollment token for the proxy's access token.",@@ -106,6 +116,7 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProviurl: "/heartbeat",config: { rateLimit: agentVaultHeartbeatLimit },schema: {+ hide: true,operationId: "agentVaultProxyHeartbeat",description: "Report a proxy as alive and read back its settings",tags: [ApiDocsTags.AgentVaultProxies],@@ -120,6 +131,7 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProviurl: "/resolve",config: { rateLimit: agentVaultResolveLimit },schema: {+ hide: true,operationId: "resolveAgentVaultSession",description: "Resolve a session into the services and credentials the proxy should attach",tags: [ApiDocsTags.AgentVaultProxies],@@ -134,6 +146,13 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvi.describe(AGENT_VAULT.PROXY.sessionToken)}).passthrough(),+ // Nullish, not optional: proxies predating session logs send no body, which arrives as null. They can't+ // record, so the handler counts them as already holding the key and never sends it.+ body: z+ .object({+ hasSessionLogKey: z.boolean().default(false).describe(AGENT_VAULT.SESSION_LOGS.hasSessionLogKey)+ })+ .nullish(),response: {200: z.object({sessionId: z.string().uuid(),@@ -165,7 +184,11 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvi.object({ placeholder: z.string(), surfaces: z.string().array(), value: z.string() }).array()})- .array()+ .array(),+ sessionLogs: z.object({+ enabled: z.boolean().describe(AGENT_VAULT.SESSION_LOGS.enabled),+ sessionKey: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.proxySessionKey)+ })})}},@@ -175,7 +198,32 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvireturn server.services.agentVaultProxy.resolveSession({proxyId: req.permission.id,orgId: req.permission.orgId,- sessionToken: req.headers[SESSION_HEADER]+ sessionToken: req.headers[SESSION_HEADER],+ hasSessionLogKey: req.body ? req.body.hasSessionLogKey : true+ });+ }+ });++ server.route({+ method: "POST",+ url: "/sessions/:sessionId/logs/chunks",+ config: { rateLimit: agentVaultSessionLogChunkLimit },+ schema: {+ hide: true,+ operationId: "createAgentVaultSessionLogChunk",+ 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.",+ tags: [ApiDocsTags.AgentVaultSessionLogs],+ params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),+ body: AgentVaultSessionLogChunkCreateSchema,+ response: { 200: AgentVaultSessionLogChunkCreateResponseSchema }+ },+ onRequest: verifyAuth([AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN]),+ handler: async (req) => {+ return server.services.agentVaultSessionLog.recordChunk({+ proxyId: req.permission.id,+ sessionId: req.params.sessionId,+ chunk: req.body});}});diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-router.tsindex 1eccb4d97e..50784c88a8 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-router.ts@@ -1,7 +1,7 @@import { z } from "zod";import { AgentVaultTrafficPolicy } from "@app/ee/services/agent-vault/agent-vault-enums";-import { buildHostPatternSchema, parseHostPatterns } from "@app/ee/services/agent-vault/agent-vault-host-pattern";+import { buildHostPatternSchema, parseHostPatterns } from "@app/ee/services/agent-vault/agent-vault-host-pattern-fns";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { AGENT_VAULT } from "@app/lib/api-docs";import { ApiDocsTags } from "@app/lib/api-docs/constants";diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-router-fns.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-router-fns.tsindex 4f8e2e43ed..65c8c90deb 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-router-fns.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-router-fns.ts@@ -1,9 +1,9 @@import { FastifyRequest } from "fastify";-import { TAgentVaultActorContext } from "@app/ee/services/agent-vault/agent-vault-actor-types";import { AgentVaultMemberType } from "@app/ee/services/agent-vault/agent-vault-enums";+import { TGenericPermission } from "@app/lib/types";-export const actorContext = (req: FastifyRequest): TAgentVaultActorContext => ({+export const actorContext = (req: FastifyRequest): TGenericPermission => ({actorId: req.permission.id,actor: req.permission.type,actorOrgId: req.permission.orgId,diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.tsindex 698bc41079..8e74368f23 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts@@ -11,8 +11,8 @@ import {AgentVaultMemberType,AgentVaultSubstitutionSurface} from "@app/ee/services/agent-vault/agent-vault-enums";-import { hostPatternSchema } from "@app/ee/services/agent-vault/agent-vault-host-pattern";-import { agentVaultPathPrefixListSchema } from "@app/ee/services/agent-vault/agent-vault-path-prefix";+import { hostPatternSchema } from "@app/ee/services/agent-vault/agent-vault-host-pattern-fns";+import { agentVaultPathPrefixListSchema } from "@app/ee/services/agent-vault/agent-vault-path-prefix-schemas";import {addDuplicateCustomHeaderNameIssues,addDuplicatePlaceholderIssues,@@ -307,24 +307,34 @@ export const AgentVaultActorRefSchema = z.discriminatedUnion("type", [.describe(JSON.stringify({ title: "Group" }))]);-export const AgentVaultActorSchema = z.discriminatedUnion("type", [- z+const actorSchemas = <Id extends z.ZodTypeAny>(+ id: Id,+ docs: Record<"actorType" | "actorId" | "username" | "email" | "firstName" | "lastName" | "identityName", string>+) => ({+ user: z.object({- type: actorTypeSchema(AgentVaultMemberType.User),- id: actorIdSchema,- username: z.string().describe(AGENT_VAULT.MEMBER.username),- email: z.string().nullable().describe(AGENT_VAULT.MEMBER.email),- firstName: z.string().nullable().describe(AGENT_VAULT.MEMBER.firstName),- lastName: z.string().nullable().describe(AGENT_VAULT.MEMBER.lastName)+ type: z.literal(AgentVaultMemberType.User).describe(docs.actorType),+ id: id.describe(docs.actorId),+ username: z.string().describe(docs.username),+ email: z.string().nullable().describe(docs.email),+ firstName: z.string().nullable().describe(docs.firstName),+ lastName: z.string().nullable().describe(docs.lastName)}).describe(JSON.stringify({ title: "User" })),- z+ machineIdentity: z.object({- type: actorTypeSchema(AgentVaultMemberType.MachineIdentity),- id: actorIdSchema,- name: z.string().describe(AGENT_VAULT.MEMBER.identityName)+ type: z.literal(AgentVaultMemberType.MachineIdentity).describe(docs.actorType),+ id: id.describe(docs.actorId),+ name: z.string().describe(docs.identityName)})- .describe(JSON.stringify({ title: "Machine identity" })),+ .describe(JSON.stringify({ title: "Machine identity" }))+});++const memberActorSchemas = actorSchemas(z.string().uuid(), AGENT_VAULT.MEMBER);++export const AgentVaultActorSchema = z.discriminatedUnion("type", [+ memberActorSchemas.user,+ memberActorSchemas.machineIdentity,z.object({type: actorTypeSchema(AgentVaultMemberType.Group),@@ -334,6 +344,13 @@ export const AgentVaultActorSchema = z.discriminatedUnion("type", [.describe(JSON.stringify({ title: "Group" }))]);+const sessionActorSchemas = actorSchemas(z.string().uuid().nullable(), AGENT_VAULT.SESSION);++export const AgentVaultSessionActorSchema = z.discriminatedUnion("type", [+ sessionActorSchemas.user,+ sessionActorSchemas.machineIdentity+]);+// No .default().optional(): the optional wraps the default and the default never applies.export const agentVaultListQuery = (docs: { search: string; limit: string; offset: string }) => ({search: zdiff --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.tsnew file mode 100644index 0000000000..d1618f0566--- /dev/null+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-log-router.ts@@ -0,0 +1,74 @@+import { z } from "zod";++import {+ AgentVaultSessionLogHistoryQuerySchema,+ AgentVaultSessionLogHistoryResponseSchema,+ AgentVaultSessionLogTailQuerySchema,+ AgentVaultSessionLogTailResponseSchema+} from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-schemas";+import { AGENT_VAULT } from "@app/lib/api-docs";+import { ApiDocsTags } from "@app/lib/api-docs/constants";+import { readLimit } from "@app/server/config/rateLimiter";+import { addNoCacheHeaders } from "@app/server/lib/caching";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";++import { actorContext } from "./agent-vault-router-fns";++export const registerAgentVaultSessionLogRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/:sessionId/logs",+ config: { rateLimit: readLimit },+ schema: {+ hide: 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).",+ tags: [ApiDocsTags.AgentVaultSessionLogs],+ params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),+ querystring: AgentVaultSessionLogHistoryQuerySchema,+ response: { 200: AgentVaultSessionLogHistoryResponseSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req, reply) => {+ addNoCacheHeaders(reply);+ return server.services.agentVaultSessionLog.listSessionLogs({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ sessionId: req.params.sessionId,+ limit: req.query.limit,+ before: req.query.cursor,+ from: req.query.from,+ to: req.query.to+ });+ }+ });++ server.route({+ method: "GET",+ url: "/:sessionId/logs/tail",+ config: { rateLimit: readLimit },+ schema: {+ hide: 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).",+ tags: [ApiDocsTags.AgentVaultSessionLogs],+ params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),+ querystring: AgentVaultSessionLogTailQuerySchema,+ response: { 200: AgentVaultSessionLogTailResponseSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req, reply) => {+ addNoCacheHeaders(reply);+ return server.services.agentVaultSessionLog.tailSessionLogs({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ sessionId: req.params.sessionId,+ limit: req.query.limit,+ receivedAfter: 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 25978e87e8..341bde9d3f 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@@ -23,6 +23,9 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";+import { actorContext } from "./agent-vault-router-fns";+import { AgentVaultSessionActorSchema } from "./agent-vault-schemas";+const SessionAccessBundleSchema = z.object({id: z.string().uuid().nullable(),name: z.string(),@@ -31,16 +34,23 @@ const SessionAccessBundleSchema = z.object({const SessionSchema = z.object({id: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId),- userId: z.string().uuid().nullable(),- identityId: z.string().uuid().nullable(),- actorName: z.string(),- actorEmail: z.string().nullable(),+ actor: AgentVaultSessionActorSchema,status: z.nativeEnum(AgentVaultSessionStatus),expiresAt: z.date().nullable().describe(AGENT_VAULT.SESSION.expiresAt),revokedAt: z.date().nullable(),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)+});+export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",@@ -56,7 +66,14 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider.nativeEnum(AgentVaultSessionScope).default(AgentVaultSessionScope.Mine).describe(AGENT_VAULT.SESSION.scope),- status: z.nativeEnum(AgentVaultSessionStatus).optional().describe(AGENT_VAULT.SESSION.status),+ status: z+ .string()+ .trim()+ .max(64)+ .optional()+ .transform((val) => (val ? [...new Set(val.split(",").map((status) => status.trim()))] : undefined))+ .pipe(z.nativeEnum(AgentVaultSessionStatus).array().optional())+ .describe(AGENT_VAULT.SESSION.status),search: z.string().trim()@@ -65,26 +82,47 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider.optional().describe(AGENT_VAULT.SESSION.search),limit: z.coerce.number().int().min(1).max(100).default(20).describe(AGENT_VAULT.SESSION.limit),- offset: z.coerce.number().int().min(0).max(10000).default(0).describe(AGENT_VAULT.SESSION.offset)+ offset: z.coerce.number().int().min(0).default(0).describe(AGENT_VAULT.SESSION.offset)}),response: {200: z.object({- sessions: SessionSchema.extend({ accessBundles: SessionAccessBundleSchema.array() }).array(),+ sessions: SessionWithLogCountsSchema.array(),totalCount: z.number()})}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { status, ...query } = req.query;+ return server.services.agentVaultSession.listSessions({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ statuses: status,+ ...query+ });+ }+ });++ server.route({+ method: "GET",+ url: "/:sessionId",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "getAgentVaultSession",+ description: "Gets an Agent Vault session.",+ tags: [ApiDocsTags.AgentVaultSessions],+ params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),+ response: {+ 200: z.object({ session: SessionWithLogCountsSchema })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),handler: async (req) =>- server.services.agentVaultSession.listSessions({+ server.services.agentVaultSession.getSessionById({projectId: req.internalAgentVaultProjectId,- ctx: {- actorId: req.permission.id,- actor: req.permission.type,- actorOrgId: req.permission.orgId,- actorAuthMethod: req.permission.authMethod- },- ...req.query+ sessionId: req.params.sessionId,+ ctx: actorContext(req)})});@@ -160,12 +198,7 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvideractorName,actorEmail,projectId: req.internalAgentVaultProjectId,- ctx: {- actorId: req.permission.id,- actor: req.permission.type,- actorOrgId: req.permission.orgId,- actorAuthMethod: req.permission.authMethod- },+ ctx: actorContext(req),...req.body});@@ -213,12 +246,7 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProviderhandler: async (req) => {const { session, revokedNow } = await server.services.agentVaultSession.revokeSession({projectId: req.internalAgentVaultProjectId,- ctx: {- actorId: req.permission.id,- actor: req.permission.type,- actorOrgId: req.permission.orgId,- actorAuthMethod: req.permission.authMethod- },+ ctx: actorContext(req),sessionId: req.params.sessionId});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.tsnew file mode 100644index 0000000000..a0784e1d92--- /dev/null+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-settings-router.ts@@ -0,0 +1,130 @@+import {+ AgentVaultSessionLogCorsProbeResponseSchema,+ AgentVaultSessionLogHealthResponseSchema,+ AgentVaultSessionLogSettingsResponseSchema,+ AgentVaultSessionLogSettingsUpdateSchema+} from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-schemas";+import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { ApiDocsTags } from "@app/lib/api-docs/constants";+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { addNoCacheHeaders } from "@app/server/lib/caching";+import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";++import { actorContext } from "./agent-vault-router-fns";++export const registerAgentVaultSettingsRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/session-logs",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "getAgentVaultSessionLogSettings",+ description: "Gets the session log settings",+ tags: [ApiDocsTags.AgentVaultSettings],+ response: { 200: AgentVaultSessionLogSettingsResponseSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) =>+ server.services.agentVaultSessionLog.getSessionLogSettings({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req)+ })+ });++ server.route({+ method: "PATCH",+ url: "/session-logs",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "updateAgentVaultSessionLogSettings",+ description: "Updates the session log settings",+ tags: [ApiDocsTags.AgentVaultSettings],+ body: AgentVaultSessionLogSettingsUpdateSchema,+ response: { 200: AgentVaultSessionLogSettingsResponseSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const { settings, appConnectionName } = await server.services.agentVaultSessionLog.updateSessionLogSettings({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ actor: {+ type: req.permission.type,+ id: req.permission.id,+ authMethod: req.permission.authMethod,+ orgId: req.permission.orgId,+ rootOrgId: req.permission.rootOrgId,+ parentOrgId: req.permission.parentOrgId+ },+ ...req.body+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE,+ metadata: { ...settings, appConnectionName }+ }+ });++ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultSessionLogSettingsUpdated,+ properties: {+ enabled: settings.enabled,+ hasDestination: Boolean(settings.bucket)+ }+ });++ return { settings };+ }+ });++ server.route({+ method: "GET",+ url: "/session-logs/health",+ config: { rateLimit: readLimit },+ schema: {+ hide: true,+ operationId: "getAgentVaultSessionLogHealth",+ description:+ "Gets whether session logs have reached their storage limit, and whether Infisical can use the AWS connection",+ tags: [ApiDocsTags.AgentVaultSettings],+ response: { 200: AgentVaultSessionLogHealthResponseSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req, reply) => {+ addNoCacheHeaders(reply);+ return server.services.agentVaultSessionLog.getSessionLogHealth({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req)+ });+ }+ });++ server.route({+ method: "GET",+ url: "/session-logs/cors-probe",+ config: { rateLimit: readLimit },+ schema: {+ hide: true,+ operationId: "getAgentVaultSessionLogCorsProbe",+ description: "Gets a presigned URL for checking the bucket's CORS rule",+ tags: [ApiDocsTags.AgentVaultSettings],+ response: { 200: AgentVaultSessionLogCorsProbeResponseSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req, reply) => {+ addNoCacheHeaders(reply);+ return server.services.agentVaultSessionLog.getSessionLogCorsProbe({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req)+ });+ }+ });+};diff --git a/backend/src/ee/routes/v1/agent-vault-routers/index.ts b/backend/src/ee/routes/v1/agent-vault-routers/index.tsindex fb892bd07d..047d94d09b 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/index.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/index.ts@@ -1,14 +1,25 @@import { registerAgentVaultAccessBundleRouter } from "./agent-vault-access-bundle-router";+import { registerAgentVaultAppConnectionRouter } from "./agent-vault-app-connection-router";import { registerAgentVaultMembershipRouter } from "./agent-vault-membership-router";import { registerAgentVaultProjectRouter } from "./agent-vault-project-router";import { registerAgentVaultProxyAgentRouter } from "./agent-vault-proxy-agent-router";import { registerAgentVaultProxyRouter } from "./agent-vault-proxy-router";+import { registerAgentVaultSessionLogRouter } from "./agent-vault-session-log-router";import { registerAgentVaultSessionRouter } from "./agent-vault-session-router";+import { registerAgentVaultSettingsRouter } from "./agent-vault-settings-router";export const registerAgentVaultRouters = async (server: FastifyZodProvider) => {await server.register(registerAgentVaultProjectRouter, { prefix: "/project" });await server.register(registerAgentVaultAccessBundleRouter, { prefix: "/access-bundles" });- await server.register(registerAgentVaultSessionRouter, { prefix: "/sessions" });+ await server.register(+ async (sessionServer) => {+ await sessionServer.register(registerAgentVaultSessionRouter);+ await sessionServer.register(registerAgentVaultSessionLogRouter);+ },+ { prefix: "/sessions" }+ );+ await server.register(registerAgentVaultSettingsRouter, { prefix: "/settings" });+ await server.register(registerAgentVaultAppConnectionRouter, { prefix: "/app-connections/aws" });await server.register(registerAgentVaultProxyRouter, { prefix: "/proxies" });await server.register(registerAgentVaultMembershipRouter, { prefix: "/members" });// Separate prefix so the preValidation project hook still matches while these routes authenticate as the proxy.diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.tsindex eb2a61470e..6c7a1ccfbb 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts@@ -1,4 +1,5 @@-import { TAgentVaultActorContext } from "../agent-vault/agent-vault-actor-types";+import { TGenericPermission } from "@app/lib/types";+import {AgentVaultCredentialType,AgentVaultHttpMethod,@@ -21,7 +22,7 @@ export type TAgentVaultCredentialSummary =| { type: AgentVaultCredentialType.Basic }| { type: AgentVaultCredentialType.Passthrough };-export type TAgentVaultProjectScoped = { projectId: string; ctx: TAgentVaultActorContext };+export type TAgentVaultProjectScoped = { projectId: string; ctx: TGenericPermission };export type TListAccessBundlesDTO = TAgentVaultProjectScoped & {search?: string;diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.tsindex 4e5de153c3..d3856bc482 100644--- a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts@@ -18,6 +18,7 @@ import {ProjectPermissionSub} from "@app/ee/services/permission/project-permission";import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { TGenericPermission } from "@app/lib/types";import { ActorType } from "@app/services/auth/auth-type";import { TIdentityDALFactory } from "@app/services/identity/identity-dal";import { AgentVaultIdentities } from "@app/services/license-client";@@ -31,7 +32,6 @@ import { TUserDALFactory } from "@app/services/user/user-dal";import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";import { resolveUsersBySsoExternalId } from "@app/services/user-alias/user-alias-fns";-import { TAgentVaultActorContext } from "../agent-vault/agent-vault-actor-types";import { AgentVaultMemberType } from "../agent-vault/agent-vault-enums";import { TAgentVaultMemberDALFactory } from "./agent-vault-member-dal";@@ -53,7 +53,7 @@ export type TAgentVaultMembershipServiceFactory = ReturnType<typeof agentVaultMeexport type TListAgentVaultProductMembersDTO = {projectId: string;- ctx: TAgentVaultActorContext;+ ctx: TGenericPermission;};export type TListAgentVaultMembersDTO = {@@ -62,7 +62,7 @@ export type TListAgentVaultMembersDTO = {search?: string;limit: number;offset: number;- ctx: TAgentVaultActorContext;+ ctx: TGenericPermission;};export type TAgentVaultActorRef = { type: AgentVaultMemberType; id: string };@@ -79,19 +79,19 @@ export type TAddAgentVaultProductMembersDTO = TAgentVaultMemberIds & {projectId: string;emails: string[];role: ProjectMembershipRole.Admin | ProjectMembershipRole.Member;- ctx: TAgentVaultActorContext;+ ctx: TGenericPermission;};export type TUpdateAgentVaultProductMemberDTO = {projectId: string;actor: TAgentVaultActorRef;role: string;- ctx: TAgentVaultActorContext;+ ctx: TGenericPermission;};export type TRevokeAgentVaultProductMembersDTO = TAgentVaultMemberIds & {projectId: string;- ctx: TAgentVaultActorContext;+ ctx: TGenericPermission;};// actorName is for the audit body; the response schemas do not select it.@@ -132,7 +132,7 @@ const actorToIds = (actor: TAgentVaultActorRef): TAgentVaultMemberIds => ({machineIdentityIds: actor.type === AgentVaultMemberType.MachineIdentity ? [actor.id] : []});-const isSelf = (actor: TAgentVaultActorRef, ctx: TAgentVaultActorContext) =>+const isSelf = (actor: TAgentVaultActorRef, ctx: TGenericPermission) =>(actor.type === AgentVaultMemberType.User && ctx.actor === ActorType.USER && actor.id === ctx.actorId) ||(actor.type === AgentVaultMemberType.MachineIdentity && ctx.actor === ActorType.IDENTITY && actor.id === ctx.actorId);@@ -149,7 +149,7 @@ export const agentVaultMembershipServiceFactory = ({permissionService,usageMeteringService}: TAgentVaultMembershipServiceFactoryDep) => {- const getActorPermission = (projectId: string, ctx: TAgentVaultActorContext) =>+ const getActorPermission = (projectId: string, ctx: TGenericPermission) =>permissionService.getProjectPermission({actor: ctx.actor,actorId: ctx.actorId,@@ -159,7 +159,7 @@ export const agentVaultMembershipServiceFactory = ({actionProjectType: ActionProjectType.AgentVault});- const checkProductAdmin = async (projectId: string, ctx: TAgentVaultActorContext) => {+ const checkProductAdmin = async (projectId: string, ctx: TGenericPermission) => {const { hasRole } = await getActorPermission(projectId, ctx);if (!hasRole(ProjectMembershipRole.Admin)) {throw new ForbiddenRequestError({ message: "Only Agent Vault admins can perform this action" });diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-dal.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-dal.tsindex b8af7df385..df67c4518f 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-dal.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-dal.ts@@ -98,5 +98,14 @@ export const agentVaultProxyDALFactory = (db: TDbClient) => {}};- return { ...orm, findByIdWithOrg, findByIdInProject, findForList, recordHeartbeat };+ const countByProjectId = async (projectId: string, tx?: Knex) => {+ try {+ const result = await (tx || db.replicaNode())(TableName.AgentVaultProxy).where({ projectId }).count("id").first();+ return parseInt(String(result?.count || "0"), 10);+ } catch (error) {+ throw new DatabaseError({ error, name: "Count agent vault proxies" });+ }+ };++ return { ...orm, findByIdWithOrg, findByIdInProject, findForList, recordHeartbeat, countByProjectId };};diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.tsindex d7e0c33369..372d440f03 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts@@ -7,6 +7,7 @@ import {ProjectPermissionAgentVaultSessionActions,ProjectPermissionSub} from "@app/ee/services/permission/project-permission";+import { PgSqlLock } from "@app/keystore/keystore";import {BadRequestError,ForbiddenRequestError,@@ -28,6 +29,13 @@ import { TAgentVaultServiceCustomHeaderDALFactory } from "../agent-vault-access-import { TAgentVaultServiceSubstitutionDALFactory } from "../agent-vault-access-bundle/agent-vault-service-substitution-dal";import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fns";+import { TAgentVaultSessionLogConfigDALFactory } from "../agent-vault-session-log/agent-vault-session-log-config-dal";+import {+ getSessionLogEntitlement,+ isSessionLogIngestEnabled,+ TSessionLogLicenseService+} from "../agent-vault-session-log/agent-vault-session-log-fns";+import { openSessionLogKey } from "../agent-vault-session-log/agent-vault-session-log-secrets";import { RESOURCE_TYPE_AGENT_VAULT_PROXY } from "../resource-auth-method/resource-auth-method-fns";import { TResourceAuthMethodServiceFactory } from "../resource-auth-method/resource-auth-method-service";import { parseRootCaCertificate } from "./agent-vault-ca-fns";@@ -46,6 +54,8 @@ import {} from "./agent-vault-proxy-types";import { TAgentVaultResolveDALFactory } from "./agent-vault-resolve-dal";+export const AGENT_VAULT_MAX_PROXIES_PER_ORG = 10;+// Health is derived from the last heartbeat and the poll interval, never stored.const HEARTBEAT_MISSES_BEFORE_UNHEALTHY = 3;@@ -55,10 +65,12 @@ type TAgentVaultProxyServiceFactoryDep = {agentVaultServiceCustomHeaderDAL: Pick<TAgentVaultServiceCustomHeaderDALFactory, "findByServiceIds">;agentVaultServiceSubstitutionDAL: Pick<TAgentVaultServiceSubstitutionDALFactory, "findByServiceIds">;agentVaultSessionDAL: Pick<TAgentVaultSessionDALFactory, "findByTokenHash">;+ agentVaultSessionLogConfigDAL: Pick<TAgentVaultSessionLogConfigDALFactory, "findOne">;membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ licenseService: TSessionLogLicenseService;resourceAuthMethodService: Pick<TResourceAuthMethodServiceFactory,"initAtCreate" | "mintToken" | "loginWithToken" | "revokeAccess"@@ -73,10 +85,12 @@ export const agentVaultProxyServiceFactory = ({agentVaultServiceCustomHeaderDAL,agentVaultServiceSubstitutionDAL,agentVaultSessionDAL,+ agentVaultSessionLogConfigDAL,membershipDAL,orgDAL,permissionService,kmsService,+ licenseService,resourceAuthMethodService}: TAgentVaultProxyServiceFactoryDep) => {const isHealthy = (proxy: Pick<TAgentVaultProxies, "heartbeat" | "pollInterval" | "heartbeatTTL">) => {@@ -174,6 +188,15 @@ export const agentVaultProxyServiceFactory = ({const create = () =>agentVaultProxyDAL.transaction(async (tx) => {+ // Serialised per project so two creates at once can't both slip under the cap.+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.CreateAgentVaultProxy(projectId)]);+ if ((await agentVaultProxyDAL.countByProjectId(projectId, tx)) >= AGENT_VAULT_MAX_PROXIES_PER_ORG) {+ throw new BadRequestError({+ message: `Agent Vault allows up to ${AGENT_VAULT_MAX_PROXIES_PER_ORG} proxies per organization. Delete one you no longer use to add another.`+ });+ }+const created = await agentVaultProxyDAL.create({projectId,@@ -314,7 +337,7 @@ export const agentVaultProxyServiceFactory = ({};/** The only endpoint that decrypts a credential. The proxy's JWT authorizes; the session token is a selector. */- const resolveSession = async ({ proxyId, orgId, sessionToken }: TResolveSessionDTO) => {+ const resolveSession = async ({ proxyId, orgId, sessionToken, hasSessionLogKey }: TResolveSessionDTO) => {const session = await agentVaultSessionDAL.findByTokenHash(hashSessionToken(sessionToken));if (!session) throw new NotFoundError({ message: "Session not found" });@@ -400,9 +423,22 @@ export const agentVaultProxyServiceFactory = ({agentVaultServiceSubstitutionDAL.findByServiceIds(serviceIds)]);+ const sessionLogConfig = await agentVaultSessionLogConfigDAL.findOne({ projectId: session.projectId });+ const entitlement =+ isSessionLogIngestEnabled(sessionLogConfig) && Boolean(session.encryptedSessionLogKey)+ ? await getSessionLogEntitlement(licenseService, proxy.orgId)+ : "unlicensed";+ // While the plan can't be confirmed, a proxy that already holds the key keeps recording, and no key goes out.+ const sessionLogsEnabled = entitlement === "licensed" || (entitlement === "unknown" && hasSessionLogKey);+ const sessionLogKeyNeeded = entitlement === "licensed" && !hasSessionLogKey;+// A bundle of pass-through services has nothing sealed, so deriving the project data key would be+ // a kms_keys read (or an external KMS round trip) per resolve for nothing.const hasSealedValue =- rows.some((row) => row.encryptedCredential) || customHeaderRows.length > 0 || substitutionRows.length > 0;+ rows.some((row) => row.encryptedCredential) ||+ customHeaderRows.length > 0 ||+ substitutionRows.length > 0 ||+ sessionLogKeyNeeded;const decryptor = hasSealedValue? (await kmsService.createCipherPairWithDataKey({@@ -437,6 +473,27 @@ export const agentVaultProxyServiceFactory = ({}))}));+ // A key that can't be opened turns logs off for this session instead of cutting the agent off from its services.+ const $sessionLogs = (): { enabled: boolean; sessionKey: string | null } => {+ if (!sessionLogKeyNeeded || !session.encryptedSessionLogKey) {+ return { enabled: sessionLogsEnabled, sessionKey: null };+ }+ try {+ const sessionKey = openSessionLogKey({+ sessionId: session.id,+ payload: decryptor!({ cipherTextBlob: session.encryptedSessionLogKey })+ }).toString("base64");+ return { enabled: sessionLogsEnabled, sessionKey };+ } catch (error) {+ logger.error(+ error,+ `agentVaultResolve: could not open the session log key, session logs are off for this session [sessionId=${session.id}] [proxyId=${proxyId}]`+ );+ return { enabled: false, sessionKey: null };+ }+ };+ const sessionLogs = $sessionLogs();+logger.info(`agentVaultResolve: resolved [sessionId=${session.id}] [proxyId=${proxyId}] [services=${services.length}]`);@@ -444,7 +501,8 @@ export const agentVaultProxyServiceFactory = ({return {sessionId: session.id,expiresAt: session.expiresAt ?? null,- services+ services,+ sessionLogs};};diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.tsindex c2579600b4..ed74325f31 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts@@ -1,7 +1,8 @@-import { TAgentVaultActorContext } from "../agent-vault/agent-vault-actor-types";+import { TGenericPermission } from "@app/lib/types";+import { AgentVaultTrafficPolicy } from "../agent-vault/agent-vault-enums";-export type TAgentVaultProxyScoped = { projectId: string; ctx: TAgentVaultActorContext };+export type TAgentVaultProxyScoped = { projectId: string; ctx: TGenericPermission };export type TAgentVaultProxyConfig = {trafficPolicy: AgentVaultTrafficPolicy;@@ -47,6 +48,7 @@ export type TResolveSessionDTO = {proxyId: string;orgId: string;sessionToken: string;+ hasSessionLogKey: boolean;};export type TResolvedService = {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.tsnew file mode 100644index 0000000000..37d638d4d9--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-chunk-dal.ts@@ -0,0 +1,200 @@+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.tsnew file mode 100644index 0000000000..fdac272d8b--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-config-dal.ts@@ -0,0 +1,40 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName, TAgentVaultSessionLogConfigs } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify } from "@app/lib/knex";++export type TAgentVaultSessionLogConfigDALFactory = ReturnType<typeof agentVaultSessionLogConfigDALFactory>;++export const agentVaultSessionLogConfigDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.AgentVaultSessionLogConfig);++ // Reads the primary: a replica still saying "off" just after session logs are turned back on would make every proxy+ // drop what it holds.+ const findByProjectIdFromPrimary = async (+ projectId: string,+ tx?: Knex+ ): Promise<TAgentVaultSessionLogConfigs | undefined> => {+ try {+ return await (tx || db)(TableName.AgentVaultSessionLogConfig).where({ projectId }).first();+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault session log config from primary" });+ }+ };++ // 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 };+};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.tsnew file mode 100644index 0000000000..6077c4a913--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-constants.ts@@ -0,0 +1,51 @@+// 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+export 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.+export const AGENT_VAULT_SESSION_LOG_CLOCK_SKEW_MS = 5 * 60_000; // 5 minutes+export 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++// 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.+export const AGENT_VAULT_SESSION_LOG_LAST_KNOWN_PLAN_MAX_AGE_MS = 60 * 60_000; // 1 hour++// 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;+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_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.tsnew file mode 100644index 0000000000..d470dc07b2--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-enums.ts@@ -0,0 +1,11 @@+export enum AgentVaultSessionLogStorageUnavailableReason {+ NoConnection = "no-connection",+ ConnectionUnusable = "connection-unusable"+}++// 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.tsnew file mode 100644index 0000000000..868efce574--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-fns.test.ts@@ -0,0 +1,106 @@+import { describe, expect, test, vi } from "vitest";++import { AWSRegion } from "@app/services/app-connection/app-connection-enums";++import {+ buildSessionLogObjectKey,+ getSessionLogEntitlement,+ resolveStorageConfig,+ 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"+ };++ 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("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"+ );+ });++ 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/");+ });+});++describe("resolveStorageConfig", () => {+ const complete = {+ appConnectionId: "conn-1",+ bucket: "my-bucket",+ region: AWSRegion.US_EAST_1 as string,+ keyPrefix: "logs"+ };++ test("returns the coordinates when every required field is set", () => {+ expect(resolveStorageConfig(complete)).toEqual({+ appConnectionId: "conn-1",+ bucket: "my-bucket",+ region: AWSRegion.US_EAST_1,+ keyPrefix: "logs"+ });+ });++ test("treats a missing keyPrefix as null rather than incomplete", () => {+ expect(resolveStorageConfig({ ...complete, keyPrefix: null })?.keyPrefix).toBeNull();+ });++ test.each(["appConnectionId", "bucket", "region"] as const)("is null when %s is missing", (field) => {+ expect(resolveStorageConfig({ ...complete, [field]: null })).toBeNull();+ });+});++describe("getSessionLogEntitlement", () => {+ const licenseService = ({+ paid,+ fallback = false,+ lastKnown = null+ }: {+ paid: boolean;+ fallback?: boolean;+ lastKnown?: { paid: boolean; ageMs: number } | null;+ }) =>+ ({+ getPlan: async () => ({ agentVaultByoS3: paid }),+ isServingFallbackPlan: async () => fallback,+ getLastKnownPlan: async () =>+ lastKnown ? { plan: { agentVaultByoS3: lastKnown.paid }, fetchedAt: Date.now() - lastKnown.ageMs } : null+ }) as unknown as TSessionLogLicenseService;++ test.each([+ { why: "a paid plan", service: { paid: true }, expected: "licensed" },+ { why: "a real free plan", service: { paid: false }, expected: "unlicensed" },+ {+ why: "a fallback with a recent paid answer",+ service: { paid: false, fallback: true, lastKnown: { paid: true, ageMs: 10 * 60_000 } },+ expected: "licensed"+ },+ {+ why: "a fallback with a recent free answer",+ service: { paid: false, fallback: true, lastKnown: { paid: false, ageMs: 10 * 60_000 } },+ expected: "unlicensed"+ },+ {+ why: "a fallback whose last answer is over an hour old",+ service: { paid: false, fallback: true, lastKnown: { paid: true, ageMs: 61 * 60_000 } },+ expected: "unknown"+ },+ { why: "a fallback with no real answer on record", service: { paid: false, fallback: true }, expected: "unknown" }+ ])("reads $why as $expected", async ({ service, expected }) => {+ expect(await getSessionLogEntitlement(licenseService(service), "org-1")).toBe(expected);+ });+});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.tsnew file mode 100644index 0000000000..6da3edcce6--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-fns.ts@@ -0,0 +1,156 @@+import { z } from "zod";++import { TAgentVaultSessionLogConfigs } from "@app/db/schemas";+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";+import { logger } from "@app/lib/logger";+import { AWSRegion } from "@app/services/app-connection/app-connection-enums";++import {+ AGENT_VAULT_SESSION_LOG_CHUNK_ID_REGEX,+ AGENT_VAULT_SESSION_LOG_LAST_KNOWN_PLAN_MAX_AGE_MS+} from "./agent-vault-session-log-constants";+import { TResolvedSessionLogStorageConfig } from "./agent-vault-session-log-types";++export const withKeyPrefix = (keyPrefix: string | null | undefined, key: string) =>+ keyPrefix ? `${keyPrefix}/${key}` : key;++export const buildSessionLogObjectKey = ({+ keyPrefix,+ projectId,+ sessionId,+ proxyId,+ startedAt,+ chunkId+}: {+ keyPrefix?: string | null;+ projectId: string;+ sessionId: string;+ proxyId: string;+ startedAt: Date;+ chunkId: string;+}) => {+ const day = startedAt.toISOString().slice(0, 10);+ return withKeyPrefix(keyPrefix, `${projectId}/${sessionId}/${proxyId}/${day}/${chunkId}.json.enc`);+};++export const resolveStorageConfig = (+ config: Pick<TAgentVaultSessionLogConfigs, "appConnectionId" | "bucket" | "region" | "keyPrefix"> | undefined+): TResolvedSessionLogStorageConfig | null => {+ if (!config?.appConnectionId || !config.bucket || !config.region) return null;+ return {+ appConnectionId: config.appConnectionId,+ bucket: config.bucket,+ region: config.region as AWSRegion,+ keyPrefix: config.keyPrefix ?? null+ };+};++export const isSessionLogIngestEnabled = (config?: TAgentVaultSessionLogConfigs) =>+ Boolean(config?.enabled && resolveStorageConfig(config));++export type TSessionLogEntitlement = "licensed" | "unlicensed" | "unknown";++export type TSessionLogLicenseService = Pick<+ TLicenseServiceFactory,+ "getPlan" | "isServingFallbackPlan" | "getLastKnownPlan"+>;++const FALLBACK_LOG_INTERVAL_MS = 5 * 60_000;+const fallbackLoggedAt = new Map<string, number>();++// getPlan answers with the free plan while the License Server is down, which would otherwise read as a downgrade+// and stop recording. "unknown" is a fallback with no recent real answer to go on.+export const getSessionLogEntitlement = async (+ licenseService: TSessionLogLicenseService,+ orgId: string+): Promise<TSessionLogEntitlement> => {+ if ((await licenseService.getPlan(orgId)).agentVaultByoS3) return "licensed";+ if (!(await licenseService.isServingFallbackPlan(orgId))) return "unlicensed";++ const lastKnown = await licenseService.getLastKnownPlan(orgId);+ let entitlement: TSessionLogEntitlement = "unknown";+ if (lastKnown && Date.now() - lastKnown.fetchedAt <= AGENT_VAULT_SESSION_LOG_LAST_KNOWN_PLAN_MAX_AGE_MS) {+ entitlement = lastKnown.plan.agentVaultByoS3 ? "licensed" : "unlicensed";+ }++ const now = Date.now();+ if (now - (fallbackLoggedAt.get(orgId) ?? 0) >= FALLBACK_LOG_INTERVAL_MS) {+ fallbackLoggedAt.set(orgId, now);+ logger.warn(+ `agentVaultSessionLog: the plan is a License Server fallback, deciding session logs from the last known plan [orgId=${orgId}] [entitlement=${entitlement}] [lastKnownAgeMs=${lastKnown ? now - lastKnown.fetchedAt : "none"}]`+ );+ }+ return entitlement;+};++const CURSOR_VERSION = 1;+const MAX_CURSOR_LENGTH = 256;++const HistoryCursorPayloadSchema = z.object({+ v: z.literal(CURSOR_VERSION),+ m: z.literal("h"),+ id: z.string().regex(AGENT_VAULT_SESSION_LOG_CHUNK_ID_REGEX)+});++const TailCursorPayloadSchema = z.object({+ v: z.literal(CURSOR_VERSION),+ m: z.literal("t"),+ at: z.string().datetime()+});++const encode = (payload: object) => Buffer.from(JSON.stringify(payload)).toString("base64url");++const decode = (cursor: string): unknown => {+ try {+ return JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));+ } catch {+ return undefined;+ }+};++export const encodeHistoryCursor = (chunkId: string) => encode({ v: CURSOR_VERSION, m: "h", id: chunkId });++export const encodeTailCursor = (at: Date) => encode({ v: CURSOR_VERSION, m: "t", at: at.toISOString() });++const modeOf = (payload: unknown) =>+ payload && typeof payload === "object" && "m" in payload ? (payload as { m: unknown }).m : undefined;++export const HistoryCursorSchema = z+ .string()+ .trim()+ .max(MAX_CURSOR_LENGTH)+ .transform((cursor, ctx) => {+ const payload = decode(cursor);+ const parsed = HistoryCursorPayloadSchema.safeParse(payload);+ if (!parsed.success) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ modeOf(payload) === "t"+ ? "This cursor is for reading new logs as they arrive. Pass it to the session logs tail endpoint instead"+ : "Invalid cursor. Pass the nextCursor of a previous response unchanged"+ });+ return z.NEVER;+ }+ return parsed.data.id;+ });++export const TailCursorSchema = z+ .string()+ .trim()+ .max(MAX_CURSOR_LENGTH)+ .transform((cursor, ctx) => {+ const payload = decode(cursor);+ const parsed = TailCursorPayloadSchema.safeParse(payload);+ if (!parsed.success) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ modeOf(payload) === "h"+ ? "This cursor is for paging back through logs. Pass it to the session logs endpoint instead"+ : "Invalid cursor. Pass the liveCursor or nextCursor of a previous response unchanged"+ });+ return z.NEVER;+ }+ return new Date(parsed.data.at);+ });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.tsnew file mode 100644index 0000000000..1f0a84360a--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-schemas.test.ts@@ -0,0 +1,204 @@+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";+import {+ AgentVaultSessionLogChunkCreateSchema,+ AgentVaultSessionLogHistoryQuerySchema,+ AgentVaultSessionLogSettingsUpdateSchema,+ AgentVaultSessionLogTailQuerySchema+} from "./agent-vault-session-log-schemas";++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", () => {+ const parsed = AgentVaultSessionLogChunkCreateSchema.parse(validChunk);+ expect(parsed.startedAt).toBeInstanceOf(Date);+ expect(parsed.endedAt.toISOString()).toBe("2026-09-16T10:31:00.000Z");+ });++ test.each([+ { field: "chunkId", value: "not-a-uuid", why: "a chunk id has to be a UUIDv7 so it sorts by time" },+ { field: "chunkId", value: "3f2b8c1e-9d4a-4e6b-a1c7-5f0e2d9b8a64", why: "a v4 UUID does not sort by time" },+ {+ field: "chunkId",+ value: "01A0A9C5-231D-7ABC-8DEF-0123456789AB",+ why: "Postgres returns lowercase, so an uppercase id would never decrypt"+ },+ { 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"+ },+ { 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=",+ why: "padded base64 is the wrong width"+ },+ {+ field: "ciphertextSha256",+ value: "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuF",+ why: "42 characters is not 32 bytes"+ },+ {+ field: "ciphertextSha256",+ value: "47DEQpj8HBSa-/TImW-5JCeuQeRkm5NMpJWZG3hSuFU",+ why: "url-safe base64 is a different alphabet"+ },+ { field: "ciphertextSha256", value: undefined, why: "every chunk carries its digest" }+ ])("rejects $field: $why", ({ field, value }) => {+ expect(AgentVaultSessionLogChunkCreateSchema.safeParse({ ...validChunk, [field]: value }).success).toBe(false);+ });++ test("rejects a body carrying anything the contract does not name", () => {+ 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("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.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")+ ])("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()) });+ 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("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.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("says where a history cursor belongs", () => {+ const result = AgentVaultSessionLogTailQuerySchema.safeParse({+ cursor: encodeHistoryCursor("01a0a9c5-231d-7abc-8def-0123456789ab")+ });+ expect(result.success).toBe(false);+ expect(result.error?.issues[0].message).toMatch(/session logs endpoint instead/);+ });+});++describe("the settings patch", () => {+ test("every field is optional, so an empty patch is valid", () => {+ expect(AgentVaultSessionLogSettingsUpdateSchema.parse({})).toEqual({});+ });++ test("accepts null for the connection, which detaches it", () => {+ expect(AgentVaultSessionLogSettingsUpdateSchema.parse({ appConnectionId: null }).appConnectionId).toBeNull();+ });++ test.each([+ { value: "..", why: "the whole prefix is a traversal" },+ { value: "logs/../../etc", why: "a traversal segment in the middle" },+ { value: "logs/../secrets", why: "climbing out of the prefix" },+ { value: ".", why: "the whole prefix is a current-folder reference" },+ { value: "./logs", why: "a leading '.' folder, which browsers drop from the download link" },+ { value: "logs/./agent-vault", why: "a '.' folder in the middle" },+ { value: "logs/.", why: "a trailing '.' folder" },+ { value: "/logs", why: "a slash at the start" },+ { value: "logs/", why: "a slash at the end" },+ { value: "logs//agent-vault", why: "an empty folder between two slashes" },+ { value: "/", why: "only a slash" },+ { value: "logs/\u0000", why: "a control character" },+ { value: "team*", why: "an asterisk, which is a wildcard in the suggested IAM policy" },+ { value: "a".repeat(513), why: "longer than 512 characters" }+ ])("rejects a key prefix: $why", ({ value }) => {+ expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ keyPrefix: value }).success).toBe(false);+ });++ test.each(["logs", "logs/agent-vault", "a.b-c_d", "", ".hidden/logs", "logs/...", "logs.v2"])(+ "accepts the key prefix %s",+ (keyPrefix) => {+ expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ keyPrefix }).success).toBe(true);+ }+ );++ test("accepts a key prefix of exactly 512 characters", () => {+ expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ keyPrefix: "a".repeat(512) }).success).toBe(true);+ });++ test("rejects a region that is not an AWS region", () => {+ expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ region: "moon-base-1" }).success).toBe(false);+ });++ test.each([+ { value: "ab", why: "shorter than 3 characters" },+ { value: "a".repeat(64), why: "longer than 63 characters" },+ { value: "My-Bucket", why: "uppercase letters" },+ { value: "my_bucket", why: "an underscore" },+ { value: "-bucket", why: "a leading hyphen" },+ { value: "bucket.", why: "a trailing dot" }+ ])("rejects a bucket name with $why", ({ value }) => {+ expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ bucket: value }).success).toBe(false);+ });++ test.each(["session-logs-bucket", "a.b-c", "a".repeat(63)])("accepts the bucket name %s", (bucket) => {+ expect(AgentVaultSessionLogSettingsUpdateSchema.safeParse({ bucket }).success).toBe(true);+ });+});diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-schemas.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-schemas.tsnew file mode 100644index 0000000000..40c75c59df--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-schemas.ts@@ -0,0 +1,184 @@+import { z } from "zod";++import { AGENT_VAULT } from "@app/lib/api-docs";+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")+ .describe(AGENT_VAULT.SESSION_LOGS.ciphertextSha256);++export const AgentVaultSessionLogChunkCreateSchema = z.object({+ chunkId: z+ .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+});++export const AgentVaultSessionLogChunkCreateResponseSchema = z.object({+ chunkId: z.string().describe(AGENT_VAULT.SESSION_LOGS.chunkId),+ uploadUrl: z.string().describe(AGENT_VAULT.SESSION_LOGS.uploadUrl),+ 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)+});++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)+ })+ .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)+});++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)+});++export const AgentVaultSessionLogSettingsSchema = z.object({+ enabled: z.boolean().describe(AGENT_VAULT.SESSION_LOGS.configEnabled),+ appConnectionId: z.string().uuid().nullable().describe(AGENT_VAULT.SESSION_LOGS.appConnectionId),+ bucket: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.bucket),+ region: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.region),+ keyPrefix: z.string().nullable().describe(AGENT_VAULT.SESSION_LOGS.keyPrefix)+});++export const AgentVaultSessionLogSettingsResponseSchema = z.object({+ settings: AgentVaultSessionLogSettingsSchema+});++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)+ })+});++export const AgentVaultSessionLogCorsProbeResponseSchema = z.object({+ probe: z+ .object({+ url: z.string().describe(AGENT_VAULT.SESSION_LOGS.corsProbeUrl),+ expiresInSeconds: z.number().describe(AGENT_VAULT.SESSION_LOGS.expiresInSeconds)+ })+ .nullable()+});++export const AgentVaultSessionLogSettingsUpdateSchema = z+ .object({+ enabled: z.boolean().describe(AGENT_VAULT.SESSION_LOGS.configEnabled),+ appConnectionId: z.string().uuid().nullable().describe(AGENT_VAULT.SESSION_LOGS.appConnectionId),+ bucket: z+ .string()+ .trim()+ .max(63, BUCKET_NAME_RULE)+ .regex(/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/, BUCKET_NAME_RULE)+ .describe(AGENT_VAULT.SESSION_LOGS.bucket),+ region: z.nativeEnum(AWSRegion).describe(AGENT_VAULT.SESSION_LOGS.region),+ keyPrefix: z+ .string()+ .trim()+ .max(512, "May be at most 512 characters")+ .regex(/^[A-Za-z0-9!\-_.'()/]*$/, "May only contain letters, numbers and ! - _ . ' ( ) /")+ .refine(+ (v) => v === "" || v.split("/").every(Boolean),+ "Must be folder names separated by single slashes, with no slash at the start or end, like 'logs/agent-vault'"+ )+ .refine(+ (v) => !v.split("/").some((folder) => folder === "." || folder === ".."),+ "May not use '.' or '..' as a folder name"+ )+ .describe(AGENT_VAULT.SESSION_LOGS.keyPrefix)+ })+ .partial();diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.test.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.test.tsnew file mode 100644index 0000000000..5ec1b87dcd--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.test.ts@@ -0,0 +1,49 @@+import { describe, expect, test, vi } from "vitest";++import {+ generateSessionLogKey,+ openSessionLogKey,+ unwrapSessionLogKey,+ wrapSessionLogKey+} from "./agent-vault-session-log-secrets";++vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn() } }));++// The real KMS wrap is authenticated encryption; passing bytes through leaves only the label check under test.+const passThroughKms = {+ createCipherPairWithDataKey: async () => ({+ encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: Buffer.from(plainText) }),+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => Buffer.from(cipherTextBlob)+ })+} as never;++describe("session log keys", () => {+ test("a key opens for the session it was wrapped for", async () => {+ const sessionLogKey = generateSessionLogKey();+ const encryptedSessionLogKey = await wrapSessionLogKey(+ { projectId: "proj-1", sessionId: "sess-a", sessionLogKey },+ passThroughKms+ );++ const opened = await unwrapSessionLogKey(+ { projectId: "proj-1", sessionId: "sess-a", encryptedSessionLogKey },+ passThroughKms+ );+ expect(opened.equals(sessionLogKey)).toBe(true);+ });++ test("a key copied onto another session's row is refused rather than handed out", async () => {+ const encryptedSessionLogKey = await wrapSessionLogKey(+ { projectId: "proj-1", sessionId: "sess-a", sessionLogKey: generateSessionLogKey() },+ passThroughKms+ );++ await expect(+ unwrapSessionLogKey({ projectId: "proj-1", sessionId: "sess-b", encryptedSessionLogKey }, passThroughKms)+ ).rejects.toMatchObject({ name: "InternalServerError" });+ });++ test("a stored key without its session label is refused", () => {+ expect(() => openSessionLogKey({ sessionId: "sess-a", payload: generateSessionLogKey() })).toThrow();+ });+});diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.tsnew file mode 100644index 0000000000..6cf1dc1861--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-secrets.ts@@ -0,0 +1,56 @@+import { crypto } from "@app/lib/crypto/cryptography";+import { InternalServerError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";++const AGENT_VAULT_SESSION_LOG_KEY_BYTES = 32;++const LABEL_BYTES = 32;++type TKmsDep = Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;++// The KMS wrap takes no context, so the session id travels inside the payload: a key copied onto another+// session's row fails to open there instead of being handed out.+const sessionLabel = (sessionId: string) => crypto.nativeCrypto.createHash("sha256").update(`${sessionId}|v1`).digest();++export const generateSessionLogKey = () => crypto.randomBytes(AGENT_VAULT_SESSION_LOG_KEY_BYTES);++export const wrapSessionLogKey = async (+ { projectId, sessionId, sessionLogKey }: { projectId: string; sessionId: string; sessionLogKey: Buffer },+ kmsService: TKmsDep+) => {+ const { encryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });+ return encryptor({ plainText: Buffer.concat([sessionLabel(sessionId), sessionLogKey]) }).cipherTextBlob;+};++export const openSessionLogKey = ({ sessionId, payload }: { sessionId: string; payload: Buffer }) => {+ const belongs =+ payload.length === LABEL_BYTES + AGENT_VAULT_SESSION_LOG_KEY_BYTES &&+ crypto.nativeCrypto.timingSafeEqual(payload.subarray(0, LABEL_BYTES), sessionLabel(sessionId));+ if (!belongs) {+ logger.error(+ `agentVaultSessionLog: stored session log key does not belong to its session [sessionId=${sessionId}]`+ );+ throw new InternalServerError({ message: "This session's log key could not be used" });+ }+ return payload.subarray(LABEL_BYTES);+};++export const unwrapSessionLogKey = async (+ {+ projectId,+ sessionId,+ encryptedSessionLogKey+ }: { projectId: string; sessionId: string; encryptedSessionLogKey: Buffer },+ kmsService: TKmsDep+) => {+ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });+ return openSessionLogKey({ sessionId, payload: decryptor({ cipherTextBlob: encryptedSessionLogKey }) });+};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.tsnew file mode 100644index 0000000000..cb74fbfef1--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.test.ts@@ -0,0 +1,697 @@+import { createMongoAbility } from "@casl/ability";+import { beforeEach, describe, expect, test, vi } from "vitest";++import { BadRequestError, DatabaseError } from "@app/lib/errors";++import {+ AGENT_VAULT_SESSION_LOG_MAX_STORED_CHUNKS,+ 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 { agentVaultSessionLogServiceFactory } from "./agent-vault-session-log-service";+import { buildSessionLogStorage } from "./agent-vault-session-log-storage-fns";++const CEILING = AGENT_VAULT_SESSION_LOG_MAX_STORED_CHUNKS;++const presignPut = vi.fn(async () => "https://bucket.s3.amazonaws.com/signed-put");+vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));+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"),+ 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 liveSession = () => ({+ id: "sess-1",+ projectId: "proj-1",+ userId: "user-1",+ identityId: null,+ expiresAt: null,+ revokedAt: null,+ updatedAt: new Date(Date.now() - 60_000),+ encryptedSessionLogKey: Buffer.alloc(32)+});++const enabledConfig = () => ({+ id: "cfg-1",+ projectId: "proj-1",+ enabled: true,+ appConnectionId: "conn-1",+ bucket: "my-bucket",+ region: "us-east-1",+ keyPrefix: "logs",+ storedChunkCount: 0+});++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,+ ciphertextBytes: 4096,+ iv: "qrvM3e7/ABEiM0RV",+ ciphertextSha256: "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU"+});++type TOverrides = {+ proxy?: unknown;+ session?: unknown;+ config?: unknown;+ storedAfterIncrement?: number;+ createThrows?: unknown;+ isReplay?: boolean;+ existingChunk?: unknown;+ destinationChanged?: boolean;+ pageRows?: unknown[];+ proxies?: unknown[];+ connection?: unknown;+ configCreateThrows?: unknown;+ licensed?: boolean;+ planFallback?: boolean;+ lastKnownPlan?: { plan: { agentVaultByoS3: boolean }; fetchedAt: number } | null;+};++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();+ const updateConfig = vi.fn(async (_id: string, values: Record<string, unknown>) => ({+ ...(config as object),+ ...values+ }));++ 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);+ return { ...enabledConfig(), ...values };+ })+ } as never,+ agentVaultSessionDAL: {+ findOne: vi.fn(async () => ("session" in overrides ? overrides.session : liveSession()))+ } as never,+ agentVaultProxyDAL: {+ findByIdWithOrg: vi.fn(async () => ("proxy" in overrides ? overrides.proxy : PROXY)),+ find: vi.fn(async () => overrides.proxies ?? [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+ }))+ } as never,+ kmsService: { createCipherPairWithDataKey: vi.fn() } as never,+ licenseService: {+ getPlan: vi.fn(async () => ({ agentVaultByoS3: overrides.licensed ?? true })),+ isServingFallbackPlan: vi.fn(async () => overrides.planFallback ?? false),+ getLastKnownPlan: vi.fn(async () => overrides.lastKnownPlan ?? null)+ } as never+ });++ return {+ service,+ createIfAbsent,+ recordStoredChunk,+ findChunk,+ moveChunk,+ validateConnection,+ findConnection,+ updateConfig+ };+};++const record = (service: ReturnType<typeof build>["service"], chunk = validChunk()) =>+ service.recordChunk({ proxyId: PROXY.id, sessionId: "sess-1", 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+ })+});++beforeEach(() => {+ vi.clearAllMocks();+});++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);++ 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());++ 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$/+ );+ 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 () => {+ const { service } = build({ proxy: undefined });+ 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 });+ await expect(record(service)).rejects.toMatchObject({ message: "Session not found" });+ });+});++describe("recordChunk: the retirement grace window", () => {+ const hoursAgo = (h: number) => new Date(Date.now() - h * 60 * 60 * 1000);++ test.each([+ { why: "revoked an hour ago", session: { revokedAt: hoursAgo(1), expiresAt: null } },+ { why: "expired an hour ago", session: { revokedAt: null, expiresAt: hoursAgo(1) } },+ { 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" });+ });++ test.each([+ { why: "revoked", session: { revokedAt: hoursAgo(25), expiresAt: null } },+ { why: "expired", session: { revokedAt: null, expiresAt: hoursAgo(25) } }+ ])("refuses a chunk from a session $why more than a day ago", async ({ session }) => {+ const { service } = build({ session: { ...liveSession(), ...session } });+ await expect(record(service)).rejects.toMatchObject({+ message: "Session ended too long ago to accept session logs"+ });+ });++ test("retirement is the earlier of revoked and expired, so a long-expired session stays closed", async () => {+ const { service } = build({+ session: { ...liveSession(), revokedAt: new Date(Date.now() - 60_000), expiresAt: hoursAgo(24 * 7) }+ });+ await expect(record(service)).rejects.toMatchObject({+ message: "Session ended too long ago to accept session logs"+ });+ });++ test("a session whose owner was deleted still accepts what the proxy held, for a day", async () => {+ const { service } = build({+ session: { ...liveSession(), userId: null, identityId: null, updatedAt: hoursAgo(23) }+ });+ await expect(record(service)).resolves.toMatchObject({ chunkId: "01a0a9c5-231d-7abc-8def-0123456789ab" });+ });++ test("a session whose owner was deleted more than a day ago is refused", async () => {+ const { service } = build({+ session: { ...liveSession(), userId: null, identityId: null, updatedAt: hoursAgo(25) }+ });+ await expect(record(service)).rejects.toMatchObject({+ 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", () => {+ 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 });+ await expect(record(service)).rejects.toMatchObject({ name: AgentVaultSessionLogErrorName.Disabled });+ expect(createIfAbsent).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();+ });++ 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) });+ await expect(refusal).rejects.toMatchObject({ name: AgentVaultSessionLogErrorName.ClockSkew });+ await expect(refusal).rejects.toThrow(/about 10 minutes ahead/);+ expect(createIfAbsent).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();+ });++ 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("accepts a chunk whose size is plausible for its record count", async () => {+ const { service } = build();+ await expect(record(service, { ...validChunk(), recordCount: 10, ciphertextBytes: 4096 })).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);+ });++ test("landing exactly on the ceiling is allowed", async () => {+ const { service } = build({ storedAfterIncrement: CEILING });+ await expect(record(service)).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();+ expect(presignPut).not.toHaveBeenCalled();+ });+});++describe("recordChunk: re-sending a chunk", () => {+ test("replays the stored row and does not count the records twice", async () => {+ const chunk = validChunk();+ const { service, recordStoredChunk, findChunk } = build({+ isReplay: true,+ existingChunk: atCurrentDestination(chunk)+ });++ const result = await record(service, chunk);++ 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()+ );+ 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 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);++ 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$/+ );+ 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" }+ });++ 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 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);++ expect(moveChunk).not.toHaveBeenCalled();+ expect(presignPut).toHaveBeenCalledWith({+ objectKey: existing.objectKey,+ ciphertextBytes: 4096,+ ciphertextSha256: validChunk().ciphertextSha256+ });+ });++ 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" }+ });++ await expect(record(service)).rejects.toMatchObject({+ name: "Conflict",+ message: "This chunk ID was already recorded by another proxy"+ });+ 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("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();+ });+});++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 });++ 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("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("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);+ expect(page.chunks).toEqual([]);+ expect(page.nextCursor).toBe(encodeTailCursor(since));+ expect(page.hasMore).toBe(false);+ });++ 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("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"]);+ });+});++describe("updateSessionLogSettings: when the connection is checked again", () => {+ const ctx = { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never;+ const actor = { type: "user", id: "user-1", orgId: "org-1", authMethod: null } as never;++ const save = (service: ReturnType<typeof build>["service"], patch: Record<string, unknown>) =>+ service.updateSessionLogSettings({ projectId: "proj-1", ctx, actor, ...patch });++ test.each([+ { use: "a different connection", patch: { appConnectionId: "5c6fd1a9-3c89-4a64-9e5f-6b7cfe0f1a2b" } },+ { use: "a different bucket", patch: { bucket: "another-bucket" } },+ { use: "a different region", patch: { region: "us-west-2" } },+ { use: "a different prefix", patch: { keyPrefix: "elsewhere" } }+ ])("checks it when the save points it at $use", async ({ patch }) => {+ const { service, validateConnection } = build();+ await save(service, patch);+ expect(validateConnection).toHaveBeenCalledTimes(1);+ });++ test("checks it when the save turns recording on", async () => {+ const { service, validateConnection } = build({ config: { ...enabledConfig(), enabled: false } });+ await save(service, { enabled: true });+ expect(validateConnection).toHaveBeenCalledTimes(1);+ });++ test("never checks it when the save turns recording off, so an unusable connection cannot block that", async () => {+ const { service, validateConnection } = build();+ await save(service, { enabled: false });+ expect(validateConnection).not.toHaveBeenCalled();+ });++ test("skips it when the save leaves the destination as it was", async () => {+ const { service, validateConnection } = build();+ await save(service, {+ enabled: true,+ appConnectionId: "conn-1",+ bucket: "my-bucket",+ region: "us-east-1",+ keyPrefix: "logs"+ });+ expect(validateConnection).not.toHaveBeenCalled();+ });+});++describe("updateSessionLogSettings: two first saves at once", () => {+ test("the one that loses reads as a clash to retry, not a server error", async () => {+ const { service } = build({+ config: undefined,+ configCreateThrows: new DatabaseError({ error: { code: "23505" }, name: "create" })+ });+ await expect(+ service.updateSessionLogSettings({+ projectId: "proj-1",+ ctx: { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never,+ actor: { type: "user", id: "user-1", orgId: "org-1", authMethod: null } as never,+ enabled: false+ })+ ).rejects.toThrow("Session log settings were just changed. Reload and try again.");+ });+});++describe("without session logs on the plan", () => {+ const ctx = { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never;+ const actor = { type: "user", id: "user-1", orgId: "org-1", authMethod: null } as never;++ const save = (service: ReturnType<typeof build>["service"], patch: Record<string, unknown>) =>+ service.updateSessionLogSettings({ projectId: "proj-1", ctx, actor, ...patch });++ test("a save that turns recording on is refused before the connection is checked", async () => {+ const { service, validateConnection, updateConfig } = build({+ licensed: false,+ config: { ...enabledConfig(), enabled: false }+ });+ await expect(save(service, { enabled: true })).rejects.toThrow(AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN);+ expect(validateConnection).not.toHaveBeenCalled();+ expect(updateConfig).not.toHaveBeenCalled();+ });++ test("a save that changes the bucket is refused", async () => {+ const { service, updateConfig } = build({ licensed: false });+ await expect(save(service, { bucket: "another-bucket" })).rejects.toThrow(AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN);+ expect(updateConfig).not.toHaveBeenCalled();+ });++ test("a save that turns recording off still works", async () => {+ const { service, updateConfig } = build({ licensed: false });+ const { settings } = await save(service, { enabled: false });+ expect(settings.enabled).toBe(false);+ expect(updateConfig).toHaveBeenCalledTimes(1);+ });++ test("a save that turns recording off and removes the connection still works", async () => {+ const { service, validateConnection } = build({ licensed: false });+ const { settings } = await save(service, { enabled: false, appConnectionId: null });+ expect(settings).toMatchObject({ enabled: false, appConnectionId: null });+ expect(validateConnection).not.toHaveBeenCalled();+ });++ test("a chunk is refused with the error that tells the proxy logging is off", async () => {+ const { service, createIfAbsent } = build({ licensed: false });+ await expect(record(service)).rejects.toMatchObject({+ name: AgentVaultSessionLogErrorName.Disabled,+ message: AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN+ });+ expect(createIfAbsent).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([]);+ expect(page.sessionLogs.enabled).toBe(false);+ });+});++describe("while the License Server can't be reached", () => {+ const ctx = { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null } as never;+ const actor = { type: "user", id: "user-1", orgId: "org-1", authMethod: null } as never;+ const unreachable = { licensed: false, planFallback: true } as const;++ test("a chunk from a paid org is still accepted on its last known plan", async () => {+ const { service, createIfAbsent } = build({+ ...unreachable,+ lastKnownPlan: { plan: { agentVaultByoS3: true }, fetchedAt: Date.now() - 10 * 60_000 }+ });+ await record(service);+ expect(createIfAbsent).toHaveBeenCalledTimes(1);+ });++ test("a chunk is held, not refused, when there is no recent real answer", async () => {+ const { service, createIfAbsent } = 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();+ });++ 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."+ );+ 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 });+ expect(page.sessionLogs.enabled).toBe(true);+ });+});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.tsnew file mode 100644index 0000000000..be08971de1--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts@@ -0,0 +1,611 @@+import { ForbiddenError } from "@casl/ability";++import { TAgentVaultSessionLogChunks, 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 {+ BadRequestError,+ ConflictError,+ ForbiddenRequestError,+ InternalServerError,+ NotFoundError,+ UnauthorizedError+} from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";++import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";+import { getAgentVaultPermission } from "../agent-vault/agent-vault-permission";+import { TAgentVaultProxyDALFactory } from "../agent-vault-proxy/agent-vault-proxy-dal";+import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";+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_CLOCK_SKEW_MS,+ 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_LOGS_NOT_ON_PLAN+} from "./agent-vault-session-log-constants";+import {+ AgentVaultSessionLogErrorName,+ AgentVaultSessionLogStorageUnavailableReason+} from "./agent-vault-session-log-enums";+import {+ buildSessionLogObjectKey,+ encodeHistoryCursor,+ encodeTailCursor,+ getSessionLogEntitlement,+ isSessionLogIngestEnabled,+ resolveStorageConfig,+ 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,+ 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">;+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;+ appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey" | "decryptWithInputKey">;+ licenseService: TSessionLogLicenseService;+};++export type TAgentVaultSessionLogServiceFactory = ReturnType<typeof agentVaultSessionLogServiceFactory>;++export const agentVaultSessionLogServiceFactory = ({+ agentVaultSessionLogChunkDAL,+ agentVaultSessionLogConfigDAL,+ agentVaultSessionDAL,+ agentVaultProxyDAL,+ appConnectionDAL,+ appConnectionService,+ permissionService,+ kmsService,+ licenseService+}: 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) => ({+ enabled: config.enabled,+ appConnectionId: config.appConnectionId ?? null,+ bucket: config.bucket ?? null,+ region: config.region ?? null,+ keyPrefix: config.keyPrefix ?? null+ });++ const $requireAdmin = async ({ projectId, ctx }: TAgentVaultSessionLogScoped) => {+ const { isAdmin } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });+ if (!isAdmin) {+ throw new ForbiddenRequestError({+ message: "Only an Agent Vault administrator can view or change session log settings"+ });+ }+ };++ const recordChunk = async ({ proxyId, sessionId, chunk }: TRecordChunkDTO) => {+ const sessionNotFound = () => new NotFoundError({ message: "Session not found" });++ const proxy = await agentVaultProxyDAL.findByIdWithOrg(proxyId);+ if (!proxy) throw sessionNotFound();++ const session = await agentVaultSessionDAL.findOne({ id: sessionId, projectId: proxy.projectId });+ if (!session) throw sessionNotFound();++ const now = new Date();+ // Deleting the owner nulls it through the FK, which fires the update trigger, so updatedAt is when it happened.+ const retirements = [+ session.revokedAt,+ session.expiresAt && session.expiresAt <= now ? session.expiresAt : null,+ isOwnerlessSession(session) ? session.updatedAt : null+ ]+ .filter((at): at is Date => Boolean(at))+ .map((at) => at.getTime());+ const retiredAt = retirements.length ? Math.min(...retirements) : null;++ if (retiredAt !== null && now.getTime() - retiredAt > AGENT_VAULT_SESSION_LOG_LATE_CHUNK_GRACE_MS) {+ throw new UnauthorizedError({ message: "Session ended too long ago to accept session logs" });+ }++ const config = await agentVaultSessionLogConfigDAL.findByProjectIdFromPrimary(proxy.projectId);+ const storage = resolveStorageConfig(config);+ if (!config?.enabled || !storage) {+ throw new BadRequestError({+ name: AgentVaultSessionLogErrorName.Disabled,+ message: "Session logs are disabled"+ });+ }++ const entitlement = await getSessionLogEntitlement(licenseService, proxy.orgId);+ if (entitlement === "unlicensed") {+ throw new BadRequestError({+ name: AgentVaultSessionLogErrorName.Disabled,+ message: AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN+ });+ }+ // A 5xx, so the proxy holds the chunk and retries instead of switching session logs off.+ if (entitlement === "unknown") {+ throw new InternalServerError({+ message: "Infisical couldn't confirm this organization's plan right now. The proxy keeps the chunk and retries."+ });+ }++ 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({+ name: AgentVaultSessionLogErrorName.ClockSkew,+ 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 (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" });+ }++ let sessionLogStorage: TAgentVaultSessionLogStorage;+ try {+ sessionLogStorage = await buildSessionLogStorage(storage, proxy.orgId, $storageDeps);+ } 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) {+ logger.warn(error, `agentVaultSessionLog: could not use the session log connection [proxyId=${proxyId}]`);+ throw new InternalServerError({+ message:+ "Session logs can't use their AWS connection right now. An Agent Vault admin can check it in Settings."+ });+ }+ throw error;+ }++ const objectKey = buildSessionLogObjectKey({+ 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+ });++ return {+ chunkId: row.chunkId,+ uploadUrl,+ expiresInSeconds: AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS+ };+ };++ const $loadSessionLogs = async ({ projectId, ctx, sessionId }: TAgentVaultSessionScoped) => {+ const { permission, isAdmin } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAgentVaultSessionActions.Read,+ ProjectPermissionSub.AgentVaultSessions+ );++ const session = await agentVaultSessionDAL.findOne({ id: sessionId, projectId });+ if (!session || (!isSessionOwnedBy(ctx, session) && !isAdmin)) {+ throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });+ }++ 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 = {+ enabled:+ isSessionLogIngestEnabled(config) &&+ (await getSessionLogEntitlement(licenseService, ctx.actorOrgId)) !== "unlicensed",+ isRecordable: Boolean(session.encryptedSessionLogKey),+ sessionKey: null,+ storageUnavailable: null+ };++ if (!config || !rows.length) return { sessionLogs: unreadSessionLogs, chunks: [], isReadable: true };++ if (!session.encryptedSessionLogKey) {+ logger.warn(`agentVaultSessionLog: session has chunks but no session log key [sessionId=${sessionId}]`);+ return { sessionLogs: unreadSessionLogs, chunks: [], isReadable: true };+ }++ // 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+ });++ const storage = resolveStorageConfig(config);+ if (!storage) {+ return unreadable({ reason: AgentVaultSessionLogStorageUnavailableReason.NoConnection, message: null });+ }++ let sessionLogStorage: TAgentVaultSessionLogStorage;+ try {+ sessionLogStorage = await buildSessionLogStorage(storage, ctx.actorOrgId, $storageDeps);+ } catch (error) {+ if (!(error instanceof BadRequestError)) throw error;+ return unreadable({+ reason: AgentVaultSessionLogStorageUnavailableReason.ConnectionUnusable,+ message: isAdmin ? error.message : null+ });+ }++ const sessionKey = await unwrapSessionLogKey(+ { projectId, sessionId, encryptedSessionLogKey: session.encryptedSessionLogKey },+ kmsService+ );++ const chunks = await Promise.all(+ rows.map(async (row) =>+ toChunkView(+ row,+ proxyNameOf(row),+ row.bucket === config.bucket ? await sessionLogStorage.presignGet(row.objectKey) : null+ )+ )+ );++ return {+ sessionLogs: { ...unreadSessionLogs, sessionKey: sessionKey.toString("base64") },+ chunks,+ isReadable: true+ };+ };++ const $caughtUpTo = (readAt: number) => new Date(readAt - AGENT_VAULT_SESSION_LOG_RECEIVE_OVERLAP_MS);++ const listSessionLogs = async ({ limit, before, from, to, ...scope }: TListSessionLogsDTO) => {+ const readAt = Date.now();+ const loaded = await $loadSessionLogs(scope);++ 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 { sessionLogs, chunks } = await $openSessionLogs({ ...scope, ...loaded, rows });++ return {+ sessionLogs,+ chunks,+ nextCursor: hasMore && chunks.length ? encodeHistoryCursor(rows[rows.length - 1].chunkId) : null,+ liveCursor: encodeTailCursor($caughtUpTo(readAt))+ };+ };++ 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 };+ }++ return {+ sessionLogs,+ chunks,+ nextCursor: encodeTailCursor(hasMore ? rows[rows.length - 1].createdAt : $caughtUpTo(readAt)),+ hasMore+ };+ };++ const getSessionLogSettings = async ({ projectId, ctx }: TAgentVaultSessionLogScoped) => {+ await $requireAdmin({ projectId, ctx });++ const config = await agentVaultSessionLogConfigDAL.findOne({ projectId });+ return {+ settings: config ? toSettingsView(config) : NO_SETTINGS+ };+ };++ const getSessionLogHealth = async ({ projectId, ctx }: TAgentVaultSessionLogScoped) => {+ await $requireAdmin({ projectId, ctx });++ const config = await agentVaultSessionLogConfigDAL.findOne({ projectId });+ const storage = resolveStorageConfig(config);++ let connectionError: string | null = null;+ if (storage) {+ try {+ await buildSessionLogStorage(storage, ctx.actorOrgId, $storageDeps);+ } 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.";+ }+ }++ return {+ health: {+ isStorageFull: config ? toCount(config.storedChunkCount) >= AGENT_VAULT_SESSION_LOG_MAX_STORED_CHUNKS : false,+ connectionError+ }+ };+ };++ const getSessionLogCorsProbe = async ({ projectId, ctx }: TAgentVaultSessionLogScoped) => {+ await $requireAdmin({ projectId, ctx });++ const config = await agentVaultSessionLogConfigDAL.findOne({ projectId });+ const storage = resolveStorageConfig(config);+ if (!storage) return { probe: null };++ const sessionLogStorage = await buildSessionLogStorage(storage, ctx.actorOrgId, $storageDeps);+ return {+ probe: {+ url: await sessionLogStorage.mintCorsProbeUrl(),+ expiresInSeconds: AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS+ }+ };+ };++ const updateSessionLogSettings = async ({ projectId, ctx, actor, ...patch }: TUpdateSessionLogSettingsDTO) => {+ await $requireAdmin({ projectId, ctx });++ const existing = await agentVaultSessionLogConfigDAL.findByProjectIdFromPrimary(projectId);+ const current = existing ?? NO_SETTINGS;++ const next = {+ enabled: patch.enabled ?? current.enabled,+ appConnectionId: patch.appConnectionId === undefined ? (current.appConnectionId ?? null) : patch.appConnectionId,+ bucket: patch.bucket ?? current.bucket ?? null,+ region: patch.region ?? current.region ?? null,+ keyPrefix: patch.keyPrefix === undefined ? (current.keyPrefix ?? null) : patch.keyPrefix || null+ };++ // Turning off and removing the connection stay open without the plan: the config's foreign key would+ // otherwise block deleting a connection the customer can no longer use.+ const needsLicence =+ (next.enabled && !current.enabled) ||+ next.bucket !== (current.bucket ?? null) ||+ next.region !== (current.region ?? null) ||+ next.keyPrefix !== (current.keyPrefix ?? null) ||+ (next.appConnectionId !== null && next.appConnectionId !== (current.appConnectionId ?? null));+ const entitlement = needsLicence ? await getSessionLogEntitlement(licenseService, ctx.actorOrgId) : "licensed";+ if (entitlement === "unknown") {+ throw new BadRequestError({+ message: "Infisical couldn't confirm your plan right now. Try again in a few minutes."+ });+ }+ if (entitlement === "unlicensed") {+ throw new BadRequestError({ message: AGENT_VAULT_SESSION_LOGS_NOT_ON_PLAN });+ }++ // Any new use of the connection is revalidated, destination changes included, or an admin who may not use+ // it could point it at their own bucket. Never on turn-off: that must work even with a broken connection.+ const usesConnectionAnew =+ next.appConnectionId !== current.appConnectionId ||+ next.bucket !== (current.bucket ?? null) ||+ next.region !== (current.region ?? null) ||+ next.keyPrefix !== (current.keyPrefix ?? null) ||+ (next.enabled && !current.enabled);+ const validatedConnection =+ next.appConnectionId && usesConnectionAnew+ ? await appConnectionService.validateAppConnectionUsageById(+ AppConnection.AWS,+ { connectionId: next.appConnectionId, projectId },+ actor+ )+ : null;++ if (next.enabled) {+ if (!next.appConnectionId && current.enabled && current.appConnectionId) {+ throw new BadRequestError({ message: "Turn off session logs before removing their AWS connection." });+ }+ const missing = (+ [+ ["appConnectionId", "an AWS connection"],+ ["bucket", "a bucket"],+ ["region", "a region"]+ ] as const+ )+ .filter(([field]) => !next[field])+ .map(([, label]) => label);+ if (missing.length) {+ throw new BadRequestError({+ message: `Session logs need ${missing.join(", ").replace(/, ([^,]*)$/, " and $1")}.`+ });+ }+ }++ const storage = next.enabled ? resolveStorageConfig(next) : null;+ const sessionLogStorage = storage ? await buildSessionLogStorage(storage, ctx.actorOrgId, $storageDeps) : null;+ if (sessionLogStorage) await sessionLogStorage.validate();++ const values = { ...next, projectId };++ let saved: TAgentVaultSessionLogConfigs;+ if (existing) {+ saved = await agentVaultSessionLogConfigDAL.updateById(existing.id, values);+ } else {+ try {+ saved = await agentVaultSessionLogConfigDAL.create(values);+ } catch (err) {+ if (isUniqueViolation(err)) {+ throw new BadRequestError({ message: "Session log settings were just changed. Reload and try again." });+ }+ throw err;+ }+ }++ let appConnectionName: string | null = null;+ if (validatedConnection) {+ appConnectionName = validatedConnection.name;+ } else if (saved.appConnectionId) {+ appConnectionName = (await appConnectionDAL.findById(saved.appConnectionId))?.name ?? null;+ }++ return { settings: toSettingsView(saved), appConnectionName };+ };++ return {+ recordChunk,+ listSessionLogs,+ tailSessionLogs,+ getSessionLogSettings,+ getSessionLogHealth,+ getSessionLogCorsProbe,+ updateSessionLogSettings+ };+};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.tsnew file mode 100644index 0000000000..6de126dc8f--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns.test.ts@@ -0,0 +1,81 @@+import { STSServiceException } from "@aws-sdk/client-sts";+import { describe, expect, test, vi } from "vitest";++import { AppConnection, AWSRegion } from "@app/services/app-connection/app-connection-enums";+import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-fns";++import { buildSessionLogStorage } from "./agent-vault-session-log-storage-fns";++vi.mock("@app/lib/logger", () => ({+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }+}));+vi.mock("@app/services/app-connection/app-connection-fns", () => ({+ decryptAppConnection: vi.fn(async (raw: unknown) => raw)+}));+vi.mock("@app/services/app-connection/aws/aws-connection-fns", () => ({+ getAwsConnectionConfig: vi.fn()+}));++describe("buildSessionLogStorage", () => {+ const config = { appConnectionId: "conn-1", bucket: "logs", region: AWSRegion.US_EAST_1, keyPrefix: null };+ const deps = {+ appConnectionDAL: {+ findById: vi.fn(async () => ({ id: "conn-1", name: "prod-logs", orgId: "org-1", app: AppConnection.AWS }))+ },+ kmsService: {}+ } as unknown as Parameters<typeof buildSessionLogStorage>[2];++ test("says which connection could not be used and what AWS said", async () => {+ vi.mocked(getAwsConnectionConfig).mockRejectedValueOnce(+ new STSServiceException({+ name: "AccessDenied",+ $fault: "client",+ $metadata: { httpStatusCode: 403 },+ message: "User is not authorized to perform: sts:AssumeRole"+ })+ );+ await expect(buildSessionLogStorage(config, "org-1", deps)).rejects.toMatchObject({+ name: "BadRequest",+ message:+ "Couldn't use the AWS connection 'prod-logs' for session logs: User is not authorized to perform: sts:AssumeRole"+ });+ });++ test("keeps anything that is not from AWS out of the message", async () => {+ vi.mocked(getAwsConnectionConfig).mockRejectedValueOnce(new Error("kms_keys row missing"));+ await expect(buildSessionLogStorage(config, "org-1", deps)).rejects.toMatchObject({+ message: "Couldn't use the AWS connection 'prod-logs' for session logs: Infisical could not load its credentials"+ });+ });++ test.each([+ { why: "no longer exists", row: undefined },+ {+ why: "belongs to another organization",+ row: { id: "conn-1", name: "theirs", orgId: "org-2", app: AppConnection.AWS }+ }+ ])("treats a connection that $why as missing", async ({ row }) => {+ vi.mocked(getAwsConnectionConfig).mockClear();+ vi.mocked(deps.appConnectionDAL.findById).mockResolvedValueOnce(row as never);+ await expect(buildSessionLogStorage(config, "org-1", deps)).rejects.toMatchObject({+ name: "BadRequest",+ message: "The AWS connection used for session logs no longer exists. Choose another on the Settings page."+ });+ expect(getAwsConnectionConfig).not.toHaveBeenCalled();+ });++ test("refuses a connection that is not AWS", async () => {+ vi.mocked(getAwsConnectionConfig).mockClear();+ vi.mocked(deps.appConnectionDAL.findById).mockResolvedValueOnce({+ id: "conn-1",+ name: "github",+ orgId: "org-1",+ app: AppConnection.GitHub+ } as never);+ await expect(buildSessionLogStorage(config, "org-1", deps)).rejects.toMatchObject({+ name: "BadRequest",+ message: `The connection used for session logs is a ${AppConnection.GitHub} connection. Session logs require an AWS connection`+ });+ expect(getAwsConnectionConfig).not.toHaveBeenCalled();+ });+});diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns.tsnew file mode 100644index 0000000000..b47fa4a970--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-storage-fns.ts@@ -0,0 +1,104 @@+import { STSServiceException } from "@aws-sdk/client-sts";++import { createS3Bucket } from "@app/lib/aws/s3";+import { BadRequestError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";+import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-fns";+import { TAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-types";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";++import { AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS } from "./agent-vault-session-log-constants";+import { withKeyPrefix } from "./agent-vault-session-log-fns";+import { TResolvedSessionLogStorageConfig } from "./agent-vault-session-log-types";++type TStorageDeps = {+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey" | "decryptWithInputKey">;+};++export type TAgentVaultSessionLogStorage = Awaited<ReturnType<typeof buildSessionLogStorage>>;++export const buildSessionLogStorage = async (+ config: TResolvedSessionLogStorageConfig,+ orgId: string,+ { appConnectionDAL, kmsService }: TStorageDeps+) => {+ const raw = await appConnectionDAL.findById(config.appConnectionId);+ if (raw && raw.orgId !== orgId) {+ logger.error(+ `Agent Vault session log connection is in another organization [appConnectionId=${raw.id}] [orgId=${orgId}]`+ );+ }+ if (!raw || raw.orgId !== orgId) {+ throw new BadRequestError({+ message: "The AWS connection used for session logs no longer exists. Choose another on the Settings page."+ });+ }+ if (raw.app !== AppConnection.AWS) {+ throw new BadRequestError({+ message: `The connection used for session logs is a ${raw.app} connection. Session logs require an AWS connection`+ });+ }++ let credentials: Awaited<ReturnType<typeof getAwsConnectionConfig>>["credentials"];+ try {+ const connection = await decryptAppConnection(raw, kmsService as Parameters<typeof decryptAppConnection>[1]);+ ({ credentials } = await getAwsConnectionConfig(connection as unknown as TAwsConnectionConfig, config.region));+ } catch (err) {+ logger.warn({ err }, `Agent Vault session logs could not use their AWS connection [appConnectionId=${raw.id}]`);+ const reason =+ err instanceof STSServiceException || err instanceof BadRequestError+ ? err.message+ : "Infisical could not load its credentials";+ throw new BadRequestError({+ message: `Couldn't use the AWS connection '${raw.name}' for session logs: ${reason}`+ });+ }++ const { bucket, keyPrefix } = config;+ const s3 = createS3Bucket({ region: config.region, bucket, credentials });++ const presignPut = async ({+ objectKey,+ ciphertextBytes,+ ciphertextSha256+ }: {+ objectKey: string;+ ciphertextBytes: number;+ ciphertextSha256: string;+ }) =>+ s3.presignCreateOnlyPut({+ key: objectKey,+ contentLength: ciphertextBytes,+ // Stored unpadded; S3 wants the padded form+ sha256Base64: `${ciphertextSha256}=`,+ expiresInSeconds: AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS+ });++ const presignGet = async (objectKey: string) =>+ s3.presignGet(objectKey, AGENT_VAULT_SESSION_LOG_PRESIGN_EXPIRY_SECONDS);++ const mintCorsProbeUrl = async () => presignGet(withKeyPrefix(keyPrefix, ".cors-probe"));++ const validate = async () => {+ const testKey = withKeyPrefix(keyPrefix, ".test/write-check");+ const access = await s3.checkAccess(testKey);+ if (access.ok) return;++ logger.warn(+ { err: access.error, bucket, testKey },+ `Agent Vault session logs bucket check failed [bucket=${bucket}] [failure=${access.failure}]`+ );+ throw new BadRequestError({+ message:+ access.failure === "unreachable"+ ? `Unable to reach bucket '${bucket}'. Check the bucket name, the region, and that the connection's credentials can access it`+ : `Bucket '${bucket}' is reachable but writing to it failed. Grant s3:PutObject on the configured key prefix`+ });+ };++ return { presignPut, presignGet, mintCorsProbeUrl, validate };+};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.tsnew file mode 100644index 0000000000..a1ec0a9955--- /dev/null+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-types.ts@@ -0,0 +1,48 @@+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+} from "./agent-vault-session-log-schemas";++export type TAgentVaultSessionLogScoped = { projectId: string; ctx: TGenericPermission };++export type TAgentVaultSessionScoped = TAgentVaultSessionLogScoped & { sessionId: string };++export type TRecordChunkDTO = {+ proxyId: string;+ sessionId: string;+ chunk: z.infer<typeof AgentVaultSessionLogChunkCreateSchema>;+};++export type TListSessionLogsDTO = TAgentVaultSessionScoped & {+ limit: number;+ before?: string;+ from?: Date;+ to?: Date;+};++export type TTailSessionLogsDTO = TAgentVaultSessionScoped & {+ limit: number;+ receivedAfter?: Date;+};++export type TUpdateSessionLogSettingsDTO = TAgentVaultSessionLogScoped & {+ actor: OrgServiceActor;+} & z.infer<typeof AgentVaultSessionLogSettingsUpdateSchema>;++export type TResolvedSessionLogStorageConfig = {+ appConnectionId: string;+ bucket: string;+ 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-dal.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-dal.tsindex ed6a1dece3..48946623d7 100644--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-dal.ts+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-dal.ts@@ -1,13 +1,14 @@import { Knex } from "knex";import { TDbClient } from "@app/db";-import { TableName, TAgentVaultSessions } from "@app/db/schemas";+import { TableName, TAgentVaultSessions, TAgentVaultSessionsInsert } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";import { sanitizeSqlLikeString } from "@app/lib/fn/string";import { ormify } from "@app/lib/knex";import { ActorType } from "@app/services/auth/auth-type";-import { AgentVaultSessionStatus } from "../agent-vault/agent-vault-enums";+import { AgentVaultMemberType, AgentVaultSessionStatus } from "../agent-vault/agent-vault-enums";+import { TAgentVaultSessionActor } from "./agent-vault-session-types";export type TAgentVaultSessionDALFactory = ReturnType<typeof agentVaultSessionDALFactory>;@@ -15,8 +16,7 @@ export type TAgentVaultSessionListRow = {id: string;userId: string | null;identityId: string | null;- actorName: string;- actorEmail: string | null;+ actor: TAgentVaultSessionActor;expiresAt: Date | null;revokedAt: Date | null;createdAt: Date;@@ -56,13 +56,47 @@ const statusFilter = (query: Knex.QueryBuilder, status: AgentVaultSessionStatus,});};-const userDisplayName = ({- userFirstName,- userLastName-}: {+// A deleted owner leaves only the snapshot mint took, which holds a user's full name in one field.+const toSessionActor = (row: {+ actorType?: string | null;+ userId: string | null;+ identityId: string | null;+ userUsername: string | null;+ userEmail: string | null;userFirstName: string | null;userLastName: string | null;-}) => [userFirstName, userLastName].filter(Boolean).join(" ") || null;+ identityName: string | null;+ actorName: string;+ actorEmail: string | null;+}): TAgentVaultSessionActor => {+ // Null only on rows written by a pod still on the previous release during a rolling deploy.+ const actorType =+ row.actorType ??+ (row.identityId || (!row.userId && !row.actorEmail)+ ? AgentVaultMemberType.MachineIdentity+ : AgentVaultMemberType.User);+ if (actorType === AgentVaultMemberType.MachineIdentity) {+ return { type: AgentVaultMemberType.MachineIdentity, id: row.identityId, name: row.identityName ?? row.actorName };+ }+ if (row.userId && row.userUsername) {+ return {+ type: AgentVaultMemberType.User,+ id: row.userId,+ username: row.userUsername,+ email: row.userEmail,+ firstName: row.userFirstName,+ lastName: row.userLastName+ };+ }+ return {+ type: AgentVaultMemberType.User,+ id: null,+ username: row.actorEmail ?? row.actorName,+ email: row.actorEmail,+ firstName: row.actorName || null,+ lastName: null+ };+};export const agentVaultSessionDALFactory = (db: TDbClient) => {const orm = ormify(db, TableName.AgentVaultSession);@@ -78,15 +112,17 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {const findForList = async ({projectId,+ sessionId,actor,- status,+ statuses,search,limit,offset}: {projectId: string;+ sessionId?: string;actor?: { type: ActorType.USER | ActorType.IDENTITY; id: string };- status?: AgentVaultSessionStatus;+ statuses?: AgentVaultSessionStatus[];search?: string;limit: number;offset: number;@@ -99,9 +135,16 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {const applyFilters = (query: Knex.QueryBuilder) => {void query.where(`${TableName.AgentVaultSession}.projectId`, projectId);+ if (sessionId) void query.where(`${TableName.AgentVaultSession}.id`, sessionId);if (actor?.type === ActorType.USER) void query.where(`${TableName.AgentVaultSession}.userId`, actor.id);if (actor?.type === ActorType.IDENTITY) void query.where(`${TableName.AgentVaultSession}.identityId`, actor.id);- if (status) statusFilter(query, status, now);+ if (statuses?.length) {+ void query.where((qb) => {+ statuses.forEach((status) => {+ void qb.orWhere((sub) => statusFilter(sub, status, now));+ });+ });+ }// Shared with the count query, so the pager describes the filtered set rather than the whole one.if (search) {const term = `%${sanitizeSqlLikeString(search)}%`;@@ -188,7 +231,9 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {db.ref("expiresAt").withSchema(TableName.AgentVaultSession),db.ref("revokedAt").withSchema(TableName.AgentVaultSession),db.ref("createdAt").withSchema(TableName.AgentVaultSession),+ db.ref("actorType").withSchema(TableName.AgentVaultSession),db.ref("username").withSchema(TableName.Users).as("userUsername"),+ db.ref("email").withSchema(TableName.Users).as("userEmail"),db.ref("firstName").withSchema(TableName.Users).as("userFirstName"),db.ref("lastName").withSchema(TableName.Users).as("userLastName"),db.ref("name").withSchema(TableName.Identity).as("identityName"),@@ -207,7 +252,9 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {expiresAt: Date | null;revokedAt: Date | null;createdAt: Date;+ actorType: string | null;userUsername: string | null;+ userEmail: string | null;userFirstName: string | null;userLastName: string | null;identityName: string | null;@@ -227,8 +274,7 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {id: row.id,userId: row.userId,identityId: row.identityId,- actorName: row.identityName ?? userDisplayName(row) ?? row.userUsername ?? row.actorName,- actorEmail: row.identityId ? null : (row.userUsername ?? row.actorEmail),+ actor: toSessionActor(row),expiresAt: row.expiresAt,revokedAt: row.revokedAt,createdAt: row.createdAt,@@ -264,26 +310,17 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {}};- const pruneRetiredBefore = async (cutoff: Date, tx?: Knex) => {+ // The id is chosen by the caller because the session log key is wrapped with it before the row exists.+ const createWithId = async (data: TAgentVaultSessionsInsert & { id: string }, tx?: Knex) => {try {- return await (tx || db)(TableName.AgentVaultSession)- .where((qb) => {- void qb- .where("revokedAt", "<", cutoff)- .orWhere((inner) => {- void inner.whereNull("revokedAt").where("expiresAt", "<", cutoff);- })- // An ownerless session stopped working the moment its actor was deleted, and nothing stamps- // that moment, so it goes by age: a never session would otherwise outlive the 30 days for good.- .orWhere((inner) => {- void inner.whereNull("userId").whereNull("identityId").where("createdAt", "<", cutoff);- });- })- .del();+ const [session] = await (tx || db)(TableName.AgentVaultSession)+ .insert(data as never)+ .returning("*");+ return session;} catch (error) {- throw new DatabaseError({ error, name: "Prune retired Agent Vault sessions" });+ throw new DatabaseError({ error, name: "Create Agent Vault session" });}};- return { ...orm, findByTokenHash, findForList, revokeIfActive, pruneRetiredBefore };+ return { ...orm, findByTokenHash, findForList, revokeIfActive, createWithId };};diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.tsindex 522c0597dc..f8d9722db9 100644--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.ts+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-fns.ts@@ -1,5 +1,7 @@import crypto from "node:crypto";+import { ActorType } from "@app/services/auth/auth-type";+import { AgentVaultSessionStatus } from "../agent-vault/agent-vault-enums";export const AGENT_VAULT_SESSION_TOKEN_PREFIX = "agv_";@@ -17,6 +19,13 @@ export const generateSessionToken = () => {export const isOwnerlessSession = (session: { userId?: string | null; identityId?: string | null }) =>!session.userId && !session.identityId;+export const isSessionOwnedBy = (+ ctx: { actor: ActorType; actorId: string },+ session: { userId?: string | null; identityId?: string | null }+) =>+ (ctx.actor === ActorType.USER && session.userId === ctx.actorId) ||+ (ctx.actor === ActorType.IDENTITY && session.identityId === ctx.actorId);+export const deriveSessionStatus = (session: { expiresAt: Date | null; revokedAt: Date | null; userId?: string | null; identityId?: string | null },now = new Date()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 b2fa900183..518cc1d688 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@@ -1,24 +1,27 @@import { ForbiddenError } from "@casl/ability";-import { ActionProjectType, ProjectMembershipRole } 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 { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";-import { logger } from "@app/lib/logger";import { ms } from "@app/lib/ms";import { ActorType } from "@app/services/auth/auth-type";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TMembershipDALFactory } from "@app/services/membership/membership-dal";-import { AgentVaultSessionScope } from "../agent-vault/agent-vault-enums";-import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";+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 } from "./agent-vault-session-dal";+import { TAgentVaultSessionDALFactory, TAgentVaultSessionListRow } from "./agent-vault-session-dal";import { deriveSessionStatus, generateSessionToken } from "./agent-vault-session-fns";-import { TListSessionsDTO, TMintSessionDTO, TRevokeSessionDTO } from "./agent-vault-session-types";+import { TGetSessionByIdDTO, TListSessionsDTO, TMintSessionDTO, TRevokeSessionDTO } from "./agent-vault-session-types";// V1 ships one bundle per session; the junction table, `position` and the proxy matcher all handle more.export const AGENT_VAULT_MAX_SESSION_BUNDLES = 1;@@ -34,10 +37,10 @@ type TAgentVaultSessionServiceFactoryDep = {agentVaultAccessBundleDAL: Pick<TAgentVaultAccessBundleDALFactory, "find">;membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ agentVaultSessionLogChunkDAL: Pick<TAgentVaultSessionLogChunkDALFactory, "sumRecentCounts">;};-const SESSION_RETENTION_DAYS = 30;-export type TAgentVaultSessionServiceFactory = ReturnType<typeof agentVaultSessionServiceFactory>;export const agentVaultSessionServiceFactory = ({@@ -45,7 +48,9 @@ export const agentVaultSessionServiceFactory = ({agentVaultSessionAccessBundleDAL,agentVaultAccessBundleDAL,membershipDAL,- permissionService+ permissionService,+ kmsService,+ agentVaultSessionLogChunkDAL}: TAgentVaultSessionServiceFactoryDep) => {const requireSessionActor = (ctx: TMintSessionDTO["ctx"]) => {if (ctx.actor !== ActorType.USER && ctx.actor !== ActorType.IDENTITY) {@@ -54,6 +59,24 @@ export const agentVaultSessionServiceFactory = ({return { type: ctx.actor, id: ctx.actorId };};+ const toSessionView = ({ userId, identityId, ...session }: TAgentVaultSessionListRow) => ({+ ...session,+ 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(@@ -91,16 +114,26 @@ export const agentVaultSessionServiceFactory = ({const expiresAt = ttl === AGENT_VAULT_SESSION_TTL_NEVER ? null : new Date(Date.now() + ms(ttl));const { token, tokenHash } = generateSessionToken();+ const sessionId = crypto.nativeCrypto.randomUUID();+ const encryptedSessionLogKey = await wrapSessionLogKey(+ { projectId, sessionId, sessionLogKey: generateSessionLogKey() },+ kmsService+ );+const session = await agentVaultSessionDAL.transaction(async (tx) => {- const created = await agentVaultSessionDAL.create(+ const created = await agentVaultSessionDAL.createWithId({+ id: sessionId,projectId,userId: actor.type === ActorType.USER ? actor.id : null,identityId: actor.type === ActorType.IDENTITY ? actor.id : null,+ actorType:+ actor.type === ActorType.IDENTITY ? AgentVaultMemberType.MachineIdentity : AgentVaultMemberType.User,actorName,actorEmail,tokenHash,- expiresAt+ expiresAt,+ encryptedSessionLogKey},tx);@@ -133,20 +166,8 @@ export const agentVaultSessionServiceFactory = ({};};- const getSessionAuthority = async ({ projectId, ctx }: { projectId: string; ctx: TListSessionsDTO["ctx"] }) => {- const { permission, hasRole } = await permissionService.getProjectPermission({- actor: ctx.actor,- actorId: ctx.actorId,- projectId,- actorAuthMethod: ctx.actorAuthMethod,- actorOrgId: ctx.actorOrgId,- actionProjectType: ActionProjectType.AgentVault- });- return { permission, isAdmin: hasRole(ProjectMembershipRole.Admin) };- };-- const listSessions = async ({ projectId, ctx, scope, status, search, limit, offset }: TListSessionsDTO) => {- const { permission, isAdmin } = await getSessionAuthority({ projectId, ctx });+ const listSessions = async ({ projectId, ctx, scope, statuses, search, limit, offset }: TListSessionsDTO) => {+ const { permission, isAdmin } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionAgentVaultSessionActions.Read,ProjectPermissionSub.AgentVaultSessions@@ -161,72 +182,79 @@ export const agentVaultSessionServiceFactory = ({const { sessions, totalCount } = await agentVaultSessionDAL.findForList({projectId,actor,- status,+ statuses,search,limit,offset});- return {- sessions: sessions.map((session) => ({ ...session, status: deriveSessionStatus(session) })),- totalCount- };+ return { sessions: await toSessionViewsWithLogCounts(sessions), totalCount };};- const revokeSession = async ({ projectId, ctx, sessionId }: TRevokeSessionDTO) => {- const { permission, isAdmin } = await getSessionAuthority({ projectId, ctx });+ // A session you may not see reads exactly like one that does not exist.+ const findVisibleSession = async ({+ projectId,+ ctx,+ sessionId,+ isAdmin+ }: TGetSessionByIdDTO & { isAdmin: boolean }) => {+ const {+ sessions: [session]+ } = await agentVaultSessionDAL.findForList({+ projectId,+ sessionId,+ actor: isAdmin ? undefined : requireSessionActor(ctx),+ limit: 1,+ offset: 0+ });+ if (!session) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });+ return session;+ };++ const getSessionById = async ({ projectId, ctx, sessionId }: TGetSessionByIdDTO) => {+ const { permission, isAdmin } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionAgentVaultSessionActions.Revoke,+ ProjectPermissionAgentVaultSessionActions.Read,ProjectPermissionSub.AgentVaultSessions);- const session = await agentVaultSessionDAL.findOne({ id: sessionId, projectId });- if (!session) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });+ const [session] = await toSessionViewsWithLogCounts([+ await findVisibleSession({ projectId, ctx, sessionId, isAdmin })+ ]);+ return { session };+ };- // The CASL action alone would let any member revoke another member's session.- const isOwner =- (ctx.actor === ActorType.USER && session.userId === ctx.actorId) ||- (ctx.actor === ActorType.IDENTITY && session.identityId === ctx.actorId);- if (!isOwner && !isAdmin) {- throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });- }+ const revokeSession = async ({ projectId, ctx, sessionId }: TRevokeSessionDTO) => {+ const { permission, isAdmin } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAgentVaultSessionActions.Revoke,+ ProjectPermissionSub.AgentVaultSessions+ );- // The row type leaves nullable columns optional; the response contract does not.- const withStatus = (row: typeof session) => {- const normalized = {- ...row,- userId: row.userId ?? null,- identityId: row.identityId ?? null,- actorEmail: row.actorEmail ?? null,- expiresAt: row.expiresAt ?? null,- revokedAt: row.revokedAt ?? null- };- return { ...normalized, status: deriveSessionStatus(normalized) };- };+ const session = await findVisibleSession({ projectId, ctx, sessionId, isAdmin });// revokedNow lets the caller audit a real revocation without auditing a repeat. Revoking twice stays a// 200 with the original revokedAt, so the second caller is not the one who revoked it.- if (session.revokedAt) return { session: withStatus(session), revokedNow: false };+ if (session.revokedAt) return { session: toSessionView(session), revokedNow: false };+ // The timestamp comes from the written row: a read-back could land on a replica that has not seen it.const revoked = await agentVaultSessionDAL.revokeIfActive(session.id, new Date());- if (revoked) return { session: withStatus(revoked), revokedNow: true };+ if (revoked) {+ return { session: toSessionView({ ...session, revokedAt: revoked.revokedAt ?? null }), revokedNow: true };+ }// A concurrent revoke won. Report its timestamp rather than the one this request read.const current = await agentVaultSessionDAL.findOne({ id: session.id, projectId });- return { session: withStatus(current ?? session), revokedNow: false };- };-- // Expiry needs no sweep: it is enforced against the clock on every resolve and derived per row on read.- const sweepRetiredSessions = async () => {- const cutoff = new Date(Date.now() - SESSION_RETENTION_DAYS * 24 * 60 * 60 * 1000);- const pruned = await agentVaultSessionDAL.pruneRetiredBefore(cutoff);- logger.info(`agent-vault: session sweep pruned ${pruned} retired session(s)`);+ return {+ session: toSessionView({ ...session, revokedAt: current?.revokedAt ?? session.revokedAt }),+ revokedNow: false+ };};return {mintSession,listSessions,- revokeSession,- sweepRetiredSessions+ getSessionById,+ revokeSession};};diff --git a/backend/src/ee/services/agent-vault-session/agent-vault-session-types.ts b/backend/src/ee/services/agent-vault-session/agent-vault-session-types.tsindex fc5a068a10..99c1b88d64 100644--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-types.ts+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-types.ts@@ -1,9 +1,14 @@-import { TAgentVaultActorContext } from "../agent-vault/agent-vault-actor-types";-import { AgentVaultSessionScope, AgentVaultSessionStatus } from "../agent-vault/agent-vault-enums";+import { TGenericPermission } from "@app/lib/types";++import {+ AgentVaultMemberType,+ AgentVaultSessionScope,+ AgentVaultSessionStatus+} from "../agent-vault/agent-vault-enums";export type TMintSessionDTO = {projectId: string;- ctx: TAgentVaultActorContext;+ ctx: TGenericPermission;accessBundles: string[];actorName: string;actorEmail: string | null;@@ -12,9 +17,9 @@ export type TMintSessionDTO = {export type TListSessionsDTO = {projectId: string;- ctx: TAgentVaultActorContext;+ ctx: TGenericPermission;scope: AgentVaultSessionScope;- status?: AgentVaultSessionStatus;+ statuses?: AgentVaultSessionStatus[];limit: number;offset: number;search?: string;@@ -22,6 +27,19 @@ export type TListSessionsDTO = {export type TRevokeSessionDTO = {projectId: string;- ctx: TAgentVaultActorContext;+ ctx: TGenericPermission;sessionId: string;};++export type TGetSessionByIdDTO = TRevokeSessionDTO;++export type TAgentVaultSessionActor =+ | {+ type: AgentVaultMemberType.User;+ id: string | null;+ username: string;+ email: string | null;+ firstName: string | null;+ lastName: string | null;+ }+ | { type: AgentVaultMemberType.MachineIdentity; id: string | null; name: string };diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex 64edb74115..2c02e4d7e9 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -19,9 +19,10 @@ never in anything the agent holds.agent-vault/ shared: enums, host grammar, conflict detection, reachabilityagent-vault-access-bundle/ bundles, services, credential encryption, grantsagent-vault-member/ product membership (list, add, role, remove)-agent-vault-session/ mint, revoke, list, retention sweep+agent-vault-session/ mint, revoke, list, getagent-vault-project/ the per-org project's lazy bootstrap and resolveragent-vault-proxy/ login (enrollment), heartbeat, resolve+agent-vault-session-log/ storage settings, chunk ingest, playback```Routes: `ee/routes/v1/agent-vault-routers/`, prefix `/api/v1/agent-vault`. CLI: `packages/cmd/agent_vault*.go`@@ -92,10 +93,13 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-the actor is out and work again if the actor is added back. Settled with the product owner.- Session actor columns are `SET NULL` so history survives the actor. Resolve refuses a session with neitherid: a null actor id reaches the membership lookups as `IS NULL`, matches user rows, and resolved as admin.+ `actorType` is stored at mint because `SET NULL` erases which kind of owner it was. It stays nullable (a pod+ on the previous release writes none) and `toSessionActor` falls back to the backfill's guess.- Status is derived from `revokedAt`, `expiresAt` and the actor columns, never stored: a session with neither- actor id reads as revoked in the list, the status filter and the sweep, so they agree with resolve refusing- it. Expiry is enforced against the clock on every resolve. `sweepRetiredSessions` exists only for the 30 day hard delete; there is no expiry audit- event, matching every other product.+ actor id reads as revoked in the list and the status filter, so they agree with resolve refusing it. Expiry+ is enforced against the clock on every resolve; there is no expiry audit event, matching every other product.+- **Sessions are never deleted**, so the Sessions page is a full history and a session's row keeps the key its+ logs need. Settled with the product owner.## Proxies@@ -114,13 +118,13 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-## Host and path grammar-`agent-vault-host-pattern.ts` is the grammar of record. The CLI matcher (`packages/agentvault/match.go`) does+`agent-vault-host-pattern-fns.ts` is the grammar of record. The CLI matcher (`packages/agentvault/match.go`) doesthe matching at runtime and reimplements the same rules, so a change here needs the same change there.- Paths are rejected *in a host pattern*; `allowedPathPrefixes` is a separate filter that never decodes.A filter is judged by what it *allows*, so the refusals are the load-bearing half. The grammar is anallowlist because a prefix is compared against the escaped path: one carrying anything Go's encoder- rewrites could never match. `agent-vault-path-prefix.ts` is the grammar of record, `policy.go` the match.+ rewrites could never match. `agent-vault-path-prefix-schemas.ts` is the grammar of record, `policy.go` the match.- Methods and path prefixes are filters on a service that already matched, **not** part of the match key,so the same-bundle host conflict rule stays host-only. Two services on one host differing only by methodis still a hard reject.@@ -169,6 +173,50 @@ header" is the name in every layer; unqualified "header" means the credential'sleaves it alone. `$decryptCredential` reads NULL as passthrough, so a bearer row that lost its secret wouldsilently stop attaching a credential.+## Session logs++Metadata 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.++- **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.+- **PAM session recording is a separate product.** The overlap with `pam-session-recording` is deliberate; don't+ share code with it.+- **Keys.** Mint wraps a per-session log key with the project data key, even while session logs are off, and+ puts `sha256(sessionId|v1)` in front because the KMS wrap takes no context. Unwrap only through+ `openSessionLogKey`, so a key copied onto another row is refused. A key that won't open turns logs off for+ that session on resolve: session logs must never break brokering.+- **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.+- **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.+- **Nothing deletes from the bucket**, so the IAM policy asks for no `s3:DeleteObject`.+- **Session logs are a paid feature (`agentVaultByoS3`).** Without it, nothing new is recorded, but saved logs+ stay readable. That breaks the License Checks rule in `CODE_QUALITY.md` on purpose. Turning session logs off+ and removing their connection stay allowed, or the connection could never be deleted.+- **`/agent-vault/app-connections/aws/*` are the shared builders in `app-connection-endpoints.ts` called with+ a `resolveScope`.** The project comes from the server, a connection outside Agent Vault is a 404 before any+ permission check, and responses leave out `projectId`. `createAppConnection` refuses any app but AWS in this+ project, the general routes included. The UI uses the general `/app-connections/aws` routes.+- **The admin role carries the CASL `AppConnections` subject**, the one exception to `hasRole(Admin)`, because+ the shared connection modals read CASL.+## The CLI- Trust is stateless: `agent-vault run` fetches the CA from the proxy on every run; `--ca-fingerprint` is an optional@@ -192,3 +240,6 @@ header" is the name in every layer; unqualified "header" means the credential's- The service template catalog (`helpers/agentVaultTemplates.ts`) is frontend-only and never persisted; iconsre-derive from the stored host pattern. The backend must never learn a service name.- Docs links live in `pages/agent-vault/agent-vault-docs-urls.ts`; keep them pointing at existing pages.+- The browser fetches session logs straight from S3, so `frontend/index.html`'s CSP `connect-src` must list+ every host the SDK presigns: `*.s3.<region>`, the path-style `s3.<region>` used for dotted bucket names, and+ both `s3-fips` forms. A region added to `AWSRegion` needs its hosts there too.diff --git a/backend/src/ee/services/agent-vault/agent-vault-actor-types.ts b/backend/src/ee/services/agent-vault/agent-vault-actor-types.tsdeleted file mode 100644index 1944be7d06..0000000000--- a/backend/src/ee/services/agent-vault/agent-vault-actor-types.ts+++ /dev/null@@ -1,8 +0,0 @@-import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";--export type TAgentVaultActorContext = {- actor: ActorType;- actorId: string;- actorOrgId: string;- actorAuthMethod: ActorAuthMethod;-};diff --git a/backend/src/ee/services/agent-vault/agent-vault-conflict-fns.ts b/backend/src/ee/services/agent-vault/agent-vault-conflict-fns.tsindex 8fad993e67..5977cd3472 100644--- a/backend/src/ee/services/agent-vault/agent-vault-conflict-fns.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-conflict-fns.ts@@ -1,4 +1,4 @@-import { intersectHostPatterns } from "./agent-vault-host-pattern";+import { intersectHostPatterns } from "./agent-vault-host-pattern-fns";export type TConflictCandidate = {id: string;diff --git a/backend/src/ee/services/agent-vault/agent-vault-host-pattern.test.ts b/backend/src/ee/services/agent-vault/agent-vault-host-pattern-fns.test.tssimilarity index 99%rename from backend/src/ee/services/agent-vault/agent-vault-host-pattern.test.tsrename to backend/src/ee/services/agent-vault/agent-vault-host-pattern-fns.test.tsindex bb7a9b9d28..ae64663d15 100644--- a/backend/src/ee/services/agent-vault/agent-vault-host-pattern.test.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-host-pattern-fns.test.ts@@ -7,7 +7,7 @@ import {matchesHost,parseHostPatterns,relateHostPatterns-} from "./agent-vault-host-pattern";+} from "./agent-vault-host-pattern-fns";const parseOne = (raw: string) => {const { patterns, errors } = parseHostPatterns(raw);diff --git a/backend/src/ee/services/agent-vault/agent-vault-host-pattern.ts b/backend/src/ee/services/agent-vault/agent-vault-host-pattern-fns.tssimilarity index 100%rename from backend/src/ee/services/agent-vault/agent-vault-host-pattern.tsrename to backend/src/ee/services/agent-vault/agent-vault-host-pattern-fns.tsdiff --git a/backend/src/ee/services/agent-vault/agent-vault-path-prefix.test.ts b/backend/src/ee/services/agent-vault/agent-vault-path-prefix-schemas.test.tssimilarity index 98%rename from backend/src/ee/services/agent-vault/agent-vault-path-prefix.test.tsrename to backend/src/ee/services/agent-vault/agent-vault-path-prefix-schemas.test.tsindex 42365e2837..ccae0d203b 100644--- a/backend/src/ee/services/agent-vault/agent-vault-path-prefix.test.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-path-prefix-schemas.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { agentVaultPathPrefixListSchema, normalizePathPrefix } from "./agent-vault-path-prefix";+import { agentVaultPathPrefixListSchema, normalizePathPrefix } from "./agent-vault-path-prefix-schemas";describe("agent vault path prefixes", () => {describe("grammar", () => {diff --git a/backend/src/ee/services/agent-vault/agent-vault-path-prefix.ts b/backend/src/ee/services/agent-vault/agent-vault-path-prefix-schemas.tssimilarity index 100%rename from backend/src/ee/services/agent-vault/agent-vault-path-prefix.tsrename to backend/src/ee/services/agent-vault/agent-vault-path-prefix-schemas.tsdiff --git a/backend/src/ee/services/agent-vault/agent-vault-permission.ts b/backend/src/ee/services/agent-vault/agent-vault-permission.tsindex 7b7718afc8..5299b21510 100644--- a/backend/src/ee/services/agent-vault/agent-vault-permission.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-permission.ts@@ -3,16 +3,18 @@ import { Knex } from "knex";import { ActionProjectType, ProjectMembershipRole, ResourceType } from "@app/db/schemas";import { isActiveRole } from "@app/ee/services/permission/permission-fns";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { TGenericPermission } from "@app/lib/types";import { ActorType } from "@app/services/auth/auth-type";import { TMembershipDALFactory } from "@app/services/membership/membership-dal";-import { TAgentVaultActorContext } from "./agent-vault-actor-types";-type TProjectPermissionResult = Awaited<ReturnType<TPermissionServiceFactory["getProjectPermission"]>>;-export type TAgentVaultReachability = {+export type TAgentVaultPermission = {permission: TProjectPermissionResult["permission"];isAdmin: boolean;+};++export type TAgentVaultReachability = TAgentVaultPermission & {accessBundleIds: string[] | null;};@@ -54,13 +56,10 @@ export const findReachableAccessBundleIds = async (return [...new Set(reachable.map((row) => row.scopeResourceId!))];};-// A service-layer filter rather than a CASL condition: conditions interpolate only identity.id,-// username and metadata.-export const getAgentVaultReachability = async (- { permissionService, membershipDAL }: { permissionService: TPermissionDep; membershipDAL: TMembershipDep },- { projectId, ctx }: { projectId: string; ctx: TAgentVaultActorContext },- tx?: Knex-): Promise<TAgentVaultReachability> => {+const $loadAgentVaultPermission = async (+ { permissionService }: { permissionService: TPermissionDep },+ { projectId, ctx }: { projectId: string; ctx: TGenericPermission }+) => {const { permission, hasRole, memberships } = await permissionService.getProjectPermission({actor: ctx.actor,actorId: ctx.actorId,@@ -69,8 +68,28 @@ export const getAgentVaultReachability = async (actorOrgId: ctx.actorOrgId,actionProjectType: ActionProjectType.AgentVault});+ return { permission, isAdmin: hasRole(ProjectMembershipRole.Admin), memberships };+};- const isAdmin = hasRole(ProjectMembershipRole.Admin);+export const getAgentVaultPermission = async (+ deps: { permissionService: TPermissionDep },+ args: { projectId: string; ctx: TGenericPermission }+): Promise<TAgentVaultPermission> => {+ const { permission, isAdmin } = await $loadAgentVaultPermission(deps, args);+ return { permission, isAdmin };+};++// A service-layer filter rather than a CASL condition: conditions interpolate only identity.id,+// username and metadata.+export const getAgentVaultReachability = async (+ { permissionService, membershipDAL }: { permissionService: TPermissionDep; membershipDAL: TMembershipDep },+ { projectId, ctx }: { projectId: string; ctx: TGenericPermission },+ tx?: Knex+): Promise<TAgentVaultReachability> => {+ const { permission, isAdmin, memberships } = await $loadAgentVaultPermission(+ { permissionService },+ { projectId, ctx }+ );if (isAdmin) return { isAdmin, accessBundleIds: null, permission };if (ctx.actor !== ActorType.USER && ctx.actor !== ActorType.IDENTITY) {diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 7d0c0e6bc0..6040b916d8 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -790,6 +790,7 @@ export enum EventType {AGENT_VAULT_PROXY_UPDATE = "agent-vault-proxy-update",AGENT_VAULT_PROXY_REVOKE = "agent-vault-proxy-revoke",AGENT_VAULT_PROXY_DELETE = "agent-vault-proxy-delete",+ AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE = "agent-vault-session-log-settings-update",APPROVAL_POLICY_CREATE = "approval-policy-create",APPROVAL_POLICY_UPDATE = "approval-policy-update",APPROVAL_POLICY_DELETE = "approval-policy-delete",@@ -6304,6 +6305,18 @@ interface AgentVaultProxyDeleteEvent {};}+interface AgentVaultSessionLogSettingsUpdateEvent {+ type: EventType.AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE;+ metadata: {+ enabled: boolean;+ appConnectionId: string | null;+ appConnectionName: string | null;+ bucket: string | null;+ region: string | null;+ keyPrefix: string | null;+ };+}+interface AgentVaultAccessBundleCreateEvent {type: EventType.AGENT_VAULT_ACCESS_BUNDLE_CREATE;metadata: {@@ -8345,6 +8358,7 @@ export type Event =| AgentVaultProxyUpdateEvent| AgentVaultProxyRevokeEvent| AgentVaultProxyDeleteEvent+ | AgentVaultSessionLogSettingsUpdateEvent| PamAccountCreateEvent| PamAccountUpdateEvent| PamAccountDeleteEventdiff --git a/backend/src/ee/services/license/__mocks__/license-fns.ts b/backend/src/ee/services/license/__mocks__/license-fns.tsindex 42f6114834..e36eadd2ff 100644--- a/backend/src/ee/services/license/__mocks__/license-fns.ts+++ b/backend/src/ee/services/license/__mocks__/license-fns.ts@@ -59,6 +59,7 @@ export const getDefaultOnPremFeatures = () => {honeyTokens: false,honeyTokenLimit: 0,secretsBrokering: true,+ agentVaultByoS3: true,secretSyncLimit: null,maxPamAccounts: null,// PKI / Cert Managerdiff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.tsindex 5ddff88d5a..ae1f3624f0 100644--- a/backend/src/ee/services/license/license-fns.ts+++ b/backend/src/ee/services/license/license-fns.ts@@ -110,6 +110,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({honeyTokens: false,honeyTokenLimit: 0,secretsBrokering: true,+ agentVaultByoS3: false,secretSyncLimit: null,maxPamAccounts: null,// PKI / Cert Managerdiff --git a/backend/src/ee/services/license/license-service.ts b/backend/src/ee/services/license/license-service.tsindex 2d151e50d6..d33d3f7024 100644--- a/backend/src/ee/services/license/license-service.ts+++ b/backend/src/ee/services/license/license-service.ts@@ -207,6 +207,12 @@ export const licenseServiceFactory = ({jitteredLicenseCloudPlanTtl(),JSON.stringify(currentPlan));+ await keyStore.setItemWithExpiry(+ KeyStorePrefixes.LicenseCloudPlanLastKnown(orgId),+ KeyStoreTtls.LicenseCloudPlanLastKnownInSeconds,+ JSON.stringify({ plan: currentPlan, fetchedAt: Date.now() })+ );+ await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlanFallback(orgId));return currentPlan;};@@ -275,11 +281,13 @@ export const licenseServiceFactory = ({error,`getPlan: encountered an error when fetching pan [orgId=${orgId}] [projectId=${projectId}] [error]`);+ const fallbackTtl = jitteredLicenseCloudPlanTtl();await keyStore.setItemWithExpiry(KeyStorePrefixes.LicenseCloudPlan(orgId),- jitteredLicenseCloudPlanTtl(),+ fallbackTtl,JSON.stringify(onPremFeatures));+ await keyStore.setItemWithExpiry(KeyStorePrefixes.LicenseCloudPlanFallback(orgId), fallbackTtl, "1");return onPremFeatures;} finally {logger.info(`getPlan: Process done for [orgId=${orgId}] [projectId=${projectId}]`);@@ -287,6 +295,18 @@ export const licenseServiceFactory = ({return onPremFeatures;};+ // Whether the plan getPlan serves for this org is the fallback above rather than a real answer.+ const isServingFallbackPlan = async (orgId: string) => {+ const [marker] = await keyStore.getItems([KeyStorePrefixes.LicenseCloudPlanFallback(orgId)]);+ return Boolean(marker);+ };++ // The last plan the License Server actually returned for this org, and when.+ const getLastKnownPlan = async (orgId: string) => {+ const [raw] = await keyStore.getItems([KeyStorePrefixes.LicenseCloudPlanLastKnown(orgId)]);+ return raw ? (JSON.parse(raw) as { plan: TFeatureSet; fetchedAt: number }) : null;+ };+const refreshPlan = async (orgId: string) => {await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(orgId));if (instanceType === InstanceType.Cloud) {@@ -382,6 +402,8 @@ export const licenseServiceFactory = ({return onPremFeatures;},getPlan,+ isServingFallbackPlan,+ getLastKnownPlan,getOrgSeatUsage,getCustomerId,getLicenseId,diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.tsindex 8041395e49..50372fab05 100644--- a/backend/src/ee/services/license/license-types.ts+++ b/backend/src/ee/services/license/license-types.ts@@ -97,6 +97,7 @@ export type TFeatureSet = {honeyTokens: false;honeyTokenLimit: 0;secretsBrokering: true;+ agentVaultByoS3: false;secretSyncLimit: null;maxPamAccounts: null;diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.tsindex 5a6ef153dd..56625d7191 100644--- a/backend/src/ee/services/permission/default-roles.ts+++ b/backend/src/ee/services/permission/default-roles.ts@@ -832,6 +832,17 @@ const buildAgentVaultProjectAdminPermissionRules = () => {ProjectPermissionSub.AgentVaultProxies);+ can(+ [+ ProjectPermissionAppConnectionActions.Read,+ ProjectPermissionAppConnectionActions.Create,+ ProjectPermissionAppConnectionActions.Edit,+ ProjectPermissionAppConnectionActions.Delete,+ ProjectPermissionAppConnectionActions.Connect+ ],+ ProjectPermissionSub.AppConnections+ );+can([ProjectPermissionMemberActions.Create,diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 278d9d4141..4ef90d53b3 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -30,6 +30,7 @@ export const PgSqlLock = {PamResourceSshCaInit: (resourceId: string) => pgAdvisoryLockHashText(`pam-resource-ssh-ca-init:${resourceId}`),CreateIdentity: (orgId: string) => pgAdvisoryLockHashText(`create-identity:${orgId}`),CreateGateway: (orgId: string) => pgAdvisoryLockHashText(`create-gateway:${orgId}`),+ CreateAgentVaultProxy: (projectId: string) => pgAdvisoryLockHashText(`create-agent-vault-proxy:${projectId}`),AccessSharedSecret: (sharedSecretId: string) => pgAdvisoryLockHashText(`access-shared-secret:${sharedSecretId}`),KmsOrgKeyCreation: (orgId: string) => pgAdvisoryLockHashText(`kms-org-key:${orgId}`),KmsOrgDataKeyCreation: (orgId: string) => pgAdvisoryLockHashText(`kms-org-data-key:${orgId}`),@@ -195,6 +196,9 @@ export const KeyStorePrefixes = {SecretManagerCachePattern: "secret-manager:*",AuditLogMigrationAlert: "audit-log-migration-alert-last-row-count",LicenseCloudPlan: (orgId: string) => `infisical-cloud-plan-${orgId}` as const,+ // Set alongside the free plan getPlan caches when the License Server fails, so callers can tell it from a real answer.+ LicenseCloudPlanFallback: (orgId: string) => `infisical-cloud-plan-fallback-${orgId}` as const,+ LicenseCloudPlanLastKnown: (orgId: string) => `infisical-cloud-plan-last-known-${orgId}` as const,// Set after a billing mutation to flag the org's plan cache for stale-while-revalidate reads.LicenseCachePassThrough: (orgId: string) => `license-cache-passthrough-${orgId}` as const,// Single-flight guard so only one background revalidation runs per org per lock window.@@ -264,6 +268,7 @@ export const KeyStoreTtls = {InvalidatingCacheInSeconds: 1800, // 30 minutes max lock for cache invalidation jobAuditLogMigrationAlertInSeconds: 604800, // 7 daysLicenseCloudPlanInSeconds: 900, // 15 minutes+ LicenseCloudPlanLastKnownInSeconds: 86400, // 24 hoursPamDefaultProjectInSeconds: 300, // 5 minutesAgentVaultDefaultProjectInSeconds: 300, // 5 minutes// How long reads stay in stale-while-revalidate mode after a billing mutation (covers Stripe reconciliation).diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex a698fe1802..35d75f03ec 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -106,6 +106,9 @@ export enum ApiDocsTags {AgentVaultSessions = "Agent Vault Sessions",AgentVaultProxies = "Agent Vault Proxies",AgentVaultMembers = "Agent Vault Members",+ AgentVaultSessionLogs = "Agent Vault Session Logs",+ AgentVaultSettings = "Agent Vault Settings",+ AgentVaultAppConnections = "Agent Vault App Connections",KmipServers = "KMIP Servers",Instance = "Instance"}@@ -4387,17 +4390,89 @@ export const AGENT_VAULT = {sessionToken: "The session an agent is running with. A selector, not a second credential.",createdAt: "When the proxy was registered."},+ 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.",+ 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.",+ 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.",+ 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.",+ sessionLogs:+ "Whether session logs are on, the key that decrypts the chunks, and why they can't be downloaded, if they can't.",+ 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.",+ 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.",+ 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.",+ bucket:+ "The name of the S3 bucket. 3 to 63 characters: lowercase letters, numbers, dots and hyphens, starting and ending with a letter or number.",+ region: "The AWS region of the bucket.",+ keyPrefix:+ "The folder in the bucket to store session logs in, such as `logs/agent-vault`. Up to 512 characters: letters, numbers and `! - _ . ' ( ) /`, with no slash at the start or end, no empty folder name, and no folder named `.` or `..`.",+ 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."+ },+SESSION: {sessionId: "The ID of the session.",accessBundles: "The access bundle this session carries, by name. A list that accepts exactly one name.",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.",+ status:+ "Filter by session status: `active`, `revoked` or `expired`. Separate several with commas to match any of them.",search: "Match sessions by actor name, actor email or access bundle name.",limit: "The maximum number of sessions to return.",- offset: "How many sessions to skip."+ offset: "How many sessions to skip.",+ actorType: "Whether the session belongs to a user or a machine identity.",+ actorId: "The ID of the user or machine identity the session belongs to, or null if it was deleted.",+ username: "The username of the user. Once the user is deleted, the email recorded when the session was created.",+ email: "The email address of the user. Once the user is deleted, the email recorded when the session was created.",+ firstName:+ "The first name of the user. Once the user is deleted, the full name recorded when the session was created.",+ lastName: "The last name of the user, or null once the user is deleted.",+ identityName:+ "The name of the machine identity. Once the machine identity is deleted, the name recorded when the session was created."}};diff --git a/backend/src/lib/aws/s3.test.ts b/backend/src/lib/aws/s3.test.tsnew file mode 100644index 0000000000..4c7106b299--- /dev/null+++ b/backend/src/lib/aws/s3.test.ts@@ -0,0 +1,31 @@+import { describe, expect, test, vi } from "vitest";++import { createS3Bucket } from "./s3";++vi.mock("@app/lib/crypto/cryptography", async () => ({+ crypto: { isFipsModeEnabled: () => false, nativeCrypto: await import("node:crypto") }+}));++describe("presignCreateOnlyPut", () => {+ const bucket = createS3Bucket({+ region: "us-east-1",+ bucket: "my-bucket",+ credentials: { accessKeyId: "AKIAEXAMPLE", secretAccessKey: "example-secret" }+ });++ test("signs the length, the digest and a create-only condition, so none can be dropped or changed", async () => {+ const url = new URL(+ await bucket.presignCreateOnlyPut({+ key: "logs/a.json.enc",+ contentLength: 42,+ sha256Base64: "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",+ expiresInSeconds: 300+ })+ );+ const signed = (url.searchParams.get("X-Amz-SignedHeaders") ?? "").split(";");+ expect(signed).toContain("content-length");+ expect(signed).toContain("if-none-match");+ expect(signed).toContain("x-amz-checksum-sha256");+ expect(url.searchParams.has("x-amz-checksum-sha256")).toBe(false);+ });+});diff --git a/backend/src/lib/aws/s3.ts b/backend/src/lib/aws/s3.tsnew file mode 100644index 0000000000..28f2fc1bd1--- /dev/null+++ b/backend/src/lib/aws/s3.ts@@ -0,0 +1,84 @@+import { GetObjectCommand, HeadBucketCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";++import { crypto } from "@app/lib/crypto/cryptography";++import { CustomAWSHasher } from "./hashing";++type TS3Credentials = { accessKeyId: string; secretAccessKey: string; sessionToken?: string };++export type TS3AccessCheck = { ok: true } | { ok: false; failure: "unreachable" | "unwritable"; error: unknown };++export type TS3Bucket = ReturnType<typeof createS3Bucket>;++export const createS3Bucket = ({+ region,+ bucket,+ credentials+}: {+ region: string;+ bucket: string;+ credentials: TS3Credentials;+}) => {+ const client = new S3Client({+ region,+ useFipsEndpoint: crypto.isFipsModeEnabled(),+ sha256: CustomAWSHasher,+ credentials+ });++ // 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.+ const presignCreateOnlyPut = ({+ key,+ contentLength,+ sha256Base64,+ expiresInSeconds+ }: {+ key: string;+ contentLength: number;+ sha256Base64: string;+ expiresInSeconds: number;+ }) =>+ getSignedUrl(+ client,+ new PutObjectCommand({+ Bucket: bucket,+ Key: key,+ ContentLength: contentLength,+ ContentType: "application/octet-stream",+ IfNoneMatch: "*",+ ChecksumSHA256: sha256Base64+ }),+ {+ expiresIn: expiresInSeconds,+ unhoistableHeaders: new Set(["content-length", "if-none-match", "x-amz-checksum-sha256"])+ }+ );++ const presignGet = (key: string, expiresInSeconds: number) =>+ getSignedUrl(client, new GetObjectCommand({ Bucket: bucket, Key: key }), { expiresIn: expiresInSeconds });++ const checkAccess = async (testKey: string): Promise<TS3AccessCheck> => {+ try {+ await client.send(new HeadBucketCommand({ Bucket: bucket }));+ } catch (error) {+ return { ok: false, failure: "unreachable", error };+ }+ try {+ await client.send(+ new PutObjectCommand({+ Bucket: bucket,+ Key: testKey,+ Body: Buffer.from("infisical-access-check"),+ ContentType: "application/octet-stream"+ })+ );+ } catch (error) {+ return { ok: false, failure: "unwritable", error };+ }+ return { ok: true };+ };++ return { presignCreateOnlyPut, presignGet, checkAccess };+};diff --git a/backend/src/server/config/rateLimiter.ts b/backend/src/server/config/rateLimiter.tsindex 8b27ccfbfd..db45230f5a 100644--- a/backend/src/server/config/rateLimiter.ts+++ b/backend/src/server/config/rateLimiter.ts@@ -80,6 +80,16 @@ export const agentVaultResolveLimit: RateLimitOptions = {}};+export const agentVaultSessionLogChunkLimit: RateLimitOptions = {+ timeWindow: 60 * 1000,+ hook: "preValidation",+ max: 600,+ keyGenerator: (req) => {+ const actorId = (req as { permission?: { id?: string } }).permission?.id;+ return actorId ? `agent-vault-session-log:${actorId}` : req.realIp;+ }+};+export const agentVaultHeartbeatLimit: RateLimitOptions = {timeWindow: 60 * 1000,hook: "preValidation",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 44d9cea517..8720b9fb93 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -38,6 +38,9 @@ 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";import { clickhouseAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-clickhouse-dal";import { auditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";@@ -1873,6 +1876,8 @@ 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({agentVaultAccessBundleDAL,@@ -1893,7 +1898,9 @@ export const registerRoutes = async (agentVaultSessionAccessBundleDAL,agentVaultAccessBundleDAL,membershipDAL,- permissionService+ permissionService,+ kmsService,+ agentVaultSessionLogChunkDAL});const agentVaultProjectResolver = agentVaultProjectResolverFactory({@@ -2002,10 +2009,12 @@ export const registerRoutes = async (agentVaultServiceCustomHeaderDAL,agentVaultServiceSubstitutionDAL,agentVaultSessionDAL,+ agentVaultSessionLogConfigDAL,membershipDAL,orgDAL,permissionService,kmsService,+ licenseService,resourceAuthMethodService});@@ -3057,8 +3066,7 @@ export const registerRoutes = async (approvalRequestDAL,approvalRequestGrantsDAL,certificateRequestDAL,- scepTransactionDAL,- agentVaultSessionService+ scepTransactionDAL});const healthAlert = healthAlertServiceFactory({@@ -3210,6 +3218,18 @@ export const registerRoutes = async (keyStore});+ const agentVaultSessionLogService = agentVaultSessionLogServiceFactory({+ agentVaultSessionLogChunkDAL,+ agentVaultSessionLogConfigDAL,+ agentVaultSessionDAL,+ agentVaultProxyDAL,+ appConnectionDAL,+ appConnectionService,+ permissionService,+ kmsService,+ licenseService+ });+const hsmConnectorService = hsmConnectorServiceFactory({hsmConnectorDAL,permissionService,@@ -4346,6 +4366,7 @@ export const registerRoutes = async (agentVaultAccessBundle: agentVaultAccessBundleService,agentVaultProxy: agentVaultProxyService,agentVaultSession: agentVaultSessionService,+ agentVaultSessionLog: agentVaultSessionLogService,agentVaultMembership: agentVaultMembershipService,pamAccountTemplate: pamAccountTemplateService,pamFolder: pamFolderService,diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.tsindex a9d8f57cfb..53970520f8 100644--- a/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts+++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts@@ -1,3 +1,4 @@+import { FastifyRequest } from "fastify";import { z } from "zod";import { EventType } from "@app/ee/services/audit-log/audit-log-types";@@ -9,45 +10,54 @@ import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { APP_CONNECTION_NAME_MAP } from "@app/services/app-connection/app-connection-maps";-import { TAppConnection, TAppConnectionInput } from "@app/services/app-connection/app-connection-types";+import { TAppConnectionInput, TAppConnectionScope } from "@app/services/app-connection/app-connection-types";import { TCreateAppConnectionCredentialRotationSchema } from "@app/services/app-connection/credential-rotation/app-connection-credential-rotation-types";import { AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";-export const registerAppConnectionEndpoints = <T extends TAppConnection, I extends TAppConnectionInput>({+type TAppConnectionCreateSchema<I extends TAppConnectionInput> = z.ZodType<{+ name: string;+ method: I["method"];+ credentials: I["credentials"];+ description?: string | null;+ isPlatformManagedCredentials?: boolean;+ isAutoRotationEnabled?: boolean | null;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;+ projectId?: string;+ rotation?: TCreateAppConnectionCredentialRotationSchema | null;+ configuration?: Record<string, unknown>;+}>;++type TAppConnectionUpdateSchema<I extends TAppConnectionInput> = z.ZodType<{+ name?: string;+ credentials?: I["credentials"];+ description?: string | null;+ isPlatformManagedCredentials?: boolean;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;+ isAutoRotationEnabled?: boolean | null;+ rotation?: Partial<TCreateAppConnectionCredentialRotationSchema> | null;+ configuration?: Record<string, unknown>;+}>;++// For routes that belong to one project the caller never names, such as Agent Vault's: the server supplies it.+type TResolveScope = (req: FastifyRequest) => TAppConnectionScope;++type TAppConnectionRouteContext = ReturnType<typeof buildAppConnectionRouteContext>;++export const buildAppConnectionRouteContext = ({server,app,- createSchema,- updateSchema,- sanitizedResponseSchema+ sanitizedResponseSchema,+ operationIdPrefix = "",+ tags = [ApiDocsTags.AppConnections]}: {- app: AppConnection;server: FastifyZodProvider;- createSchema: z.ZodType<{- name: string;- method: I["method"];- credentials: I["credentials"];- description?: string | null;- isPlatformManagedCredentials?: boolean;- isAutoRotationEnabled?: boolean | null;- gatewayId?: string | null;- gatewayPoolId?: string | null;- projectId?: string;- rotation?: TCreateAppConnectionCredentialRotationSchema | null;- configuration?: Record<string, unknown>;- }>;- updateSchema: z.ZodType<{- name?: string;- credentials?: I["credentials"];- description?: string | null;- isPlatformManagedCredentials?: boolean;- gatewayId?: string | null;- gatewayPoolId?: string | null;- isAutoRotationEnabled?: boolean | null;- rotation?: Partial<TCreateAppConnectionCredentialRotationSchema> | null;- configuration?: Record<string, unknown>;- }>;+ app: AppConnection;sanitizedResponseSchema: z.ZodTypeAny;+ operationIdPrefix?: string;+ tags?: ApiDocsTags[];}) => {const appName = APP_CONNECTION_NAME_MAP[app];const specialCases: Record<string, string> = {@@ -62,12 +72,23 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten[AppConnection.TravisCI]: "TravisCI"};const appNameForOpId =- specialCases[app] ??- app- .split("-")- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))- .join("");+ operationIdPrefix ++ (specialCases[app] ??+ app+ .split("-")+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))+ .join(""));++ return { server, app, appName, appNameForOpId, sanitizedResponseSchema, tags };+};+export const buildListAppConnectionsRoute = (+ { server, app, appName, appNameForOpId, sanitizedResponseSchema, tags }: TAppConnectionRouteContext,+ {+ description = `List the ${appName} Connections for the current organization or project.`,+ resolveScope+ }: { description?: string; resolveScope?: TResolveScope } = {}+) => {server.route({method: "GET",url: `/`,@@ -77,10 +98,12 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenschema: {hide: false,operationId: `list${appNameForOpId}AppConnections`,- tags: [ApiDocsTags.AppConnections],- description: `List the ${appName} Connections for the current organization or project.`,- querystring: z.object({- projectId: z.string().optional().describe(AppConnections.LIST(app).projectId)+ tags,+ description,+ ...(!resolveScope && {+ querystring: z.object({+ projectId: z.string().optional().describe(AppConnections.LIST(app).projectId)+ })}),response: {200: z.object({ appConnections: sanitizedResponseSchema.array() })@@ -88,12 +111,8 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),handler: async (req) => {- const { projectId } = req.query;- const appConnections = (await server.services.appConnection.listAppConnections(- req.permission,- app,- projectId- )) as T[];+ const projectId = resolveScope ? resolveScope(req).projectId : (req.query as { projectId?: string }).projectId;+ const appConnections = await server.services.appConnection.listAppConnections(req.permission, app, projectId);await server.services.auditLog.createAuditLog({...req.auditLogInfo,@@ -112,7 +131,14 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenreturn { appConnections };}});+};+export const buildListAvailableAppConnectionsRoute = (+ { server, app, appName, appNameForOpId, tags }: TAppConnectionRouteContext,+ {+ description = `List the ${appName} Connections the current user has permission to establish connections within this project.`+ }: { description?: string } = {}+) => {server.route({method: "GET",url: "/available",@@ -122,8 +148,8 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenschema: {hide: false,operationId: `list${appNameForOpId}AvailableAppConnections`,- tags: [ApiDocsTags.AppConnections],- description: `List the ${appName} Connections the current user has permission to establish connections within this project.`,+ tags,+ description,querystring: z.object({projectId: z.string().optional().describe(AppConnections.LIST(app).projectId)}),@@ -167,7 +193,15 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenreturn { appConnections };}});+};+export const buildGetAppConnectionRoute = (+ { server, app, appName, appNameForOpId, sanitizedResponseSchema, tags }: TAppConnectionRouteContext,+ {+ description = `Get the specified ${appName} Connection by ID.`,+ resolveScope+ }: { description?: string; resolveScope?: TResolveScope } = {}+) => {server.route({method: "GET",url: "/:connectionId",@@ -177,8 +211,8 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenschema: {hide: false,operationId: `get${appNameForOpId}AppConnection`,- tags: [ApiDocsTags.AppConnections],- description: `Get the specified ${appName} Connection by ID.`,+ tags,+ description,params: z.object({connectionId: z.string().uuid().describe(AppConnections.GET_BY_ID(app).connectionId)}),@@ -190,11 +224,12 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenhandler: async (req) => {const { connectionId } = req.params;- const appConnection = (await server.services.appConnection.findAppConnectionById(+ const appConnection = await server.services.appConnection.findAppConnectionById(app,connectionId,- req.permission- )) as T;+ req.permission,+ resolveScope?.(req)+ );await server.services.auditLog.createAuditLog({...req.auditLogInfo,@@ -211,7 +246,15 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenreturn { appConnection };}});+};+export const buildGetAppConnectionByNameRoute = (+ { server, app, appName, appNameForOpId, sanitizedResponseSchema, tags }: TAppConnectionRouteContext,+ {+ description = `Get the specified ${appName} Connection by name.`,+ resolveScope+ }: { description?: string; resolveScope?: TResolveScope } = {}+) => {server.route({method: "GET",url: `/connection-name/:connectionName`,@@ -221,8 +264,8 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenschema: {hide: false,operationId: `get${appNameForOpId}AppConnectionByName`,- tags: [ApiDocsTags.AppConnections],- description: `Get the specified ${appName} Connection by name.`,+ tags,+ description,params: z.object({connectionName: z.string()@@ -230,8 +273,10 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten.min(1, "Connection name required").describe(AppConnections.GET_BY_NAME(app).connectionName)}),- querystring: z.object({- projectId: z.string().trim().optional().describe(AppConnections.GET_BY_NAME(app).projectId)+ ...(!resolveScope && {+ querystring: z.object({+ projectId: z.string().trim().optional().describe(AppConnections.GET_BY_NAME(app).projectId)+ })}),response: {200: z.object({ appConnection: sanitizedResponseSchema })@@ -240,16 +285,16 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenonRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),handler: async (req) => {const { connectionName } = req.params;- const { projectId } = req.query;+ const projectId = resolveScope ? resolveScope(req).projectId : (req.query as { projectId?: string }).projectId;- const appConnection = (await server.services.appConnection.findAppConnectionByName(+ const appConnection = await server.services.appConnection.findAppConnectionByName(app,{connectionName,projectId},req.permission- )) as T;+ );await server.services.auditLog.createAuditLog({...req.auditLogInfo,@@ -266,7 +311,16 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenreturn { appConnection };}});+};+export const buildCreateAppConnectionRoute = <I extends TAppConnectionInput>(+ { server, app, appName, appNameForOpId, sanitizedResponseSchema, tags }: TAppConnectionRouteContext,+ {+ createSchema,+ description = `Create ${startsWithVowel(appName) ? "an" : "a"} ${appName} Connection.`,+ resolveScope+ }: { createSchema: TAppConnectionCreateSchema<I>; description?: string; resolveScope?: TResolveScope }+) => {server.route({method: "POST",url: "/",@@ -276,8 +330,8 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenschema: {hide: false,operationId: `create${appNameForOpId}AppConnection`,- tags: [ApiDocsTags.AppConnections],- description: `Create ${startsWithVowel(appName) ? "an" : "a"} ${appName} Connection.`,+ tags,+ description,body: createSchema,response: {200: z.object({ appConnection: sanitizedResponseSchema })@@ -289,23 +343,23 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenname,method,credentials,- description,+ description: connectionDescription,isPlatformManagedCredentials,gatewayId,gatewayPoolId,- projectId,isAutoRotationEnabled,rotation,configuration} = req.body;+ const projectId = resolveScope ? resolveScope(req).projectId : req.body.projectId;- const appConnection = (await server.services.appConnection.createAppConnection(+ const appConnection = await server.services.appConnection.createAppConnection({name,method,app,credentials,- description,+ description: connectionDescription,isPlatformManagedCredentials,gatewayId,gatewayPoolId,@@ -315,7 +369,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenconfiguration},req.permission- )) as T;+ );await server.services.auditLog.createAuditLog({...req.auditLogInfo,@@ -349,7 +403,17 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenreturn { appConnection };}});+};+export const buildUpdateAppConnectionRoute = <I extends TAppConnectionInput>(+ ctx: TAppConnectionRouteContext,+ {+ updateSchema,+ description = `Update the specified ${ctx.appName} Connection.`,+ resolveScope+ }: { updateSchema: TAppConnectionUpdateSchema<I>; description?: string; resolveScope?: TResolveScope }+) => {+ const { server, app, appNameForOpId, sanitizedResponseSchema, tags } = ctx;server.route({method: "PATCH",url: "/:connectionId",@@ -359,8 +423,8 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenschema: {hide: false,operationId: `update${appNameForOpId}AppConnection`,- tags: [ApiDocsTags.AppConnections],- description: `Update the specified ${appName} Connection.`,+ tags,+ description,params: z.object({connectionId: z.string().uuid().describe(AppConnections.UPDATE(app).connectionId)}),@@ -374,7 +438,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenconst {name,credentials,- description,+ description: connectionDescription,isPlatformManagedCredentials,gatewayId,gatewayPoolId,@@ -384,12 +448,13 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten} = req.body;const { connectionId } = req.params;- const appConnection = (await server.services.appConnection.updateAppConnection(+ const appConnection = await server.services.appConnection.updateAppConnection(+ app,{name,credentials,connectionId,- description,+ description: connectionDescription,isPlatformManagedCredentials,gatewayId,gatewayPoolId,@@ -397,8 +462,9 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenrotation: rotation ?? undefined,configuration},- req.permission- )) as T;+ req.permission,+ resolveScope?.(req)+ );await server.services.auditLog.createAuditLog({...req.auditLogInfo,@@ -408,7 +474,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extentype: EventType.UPDATE_APP_CONNECTION,metadata: {name,- description,+ description: connectionDescription,credentialsUpdated: Boolean(credentials),connectionId,isPlatformManagedCredentials@@ -428,7 +494,16 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenreturn { appConnection };}});+};+export const buildDeleteAppConnectionRoute = (+ ctx: TAppConnectionRouteContext,+ {+ description = `Delete the specified ${ctx.appName} Connection.`,+ resolveScope+ }: { description?: string; resolveScope?: TResolveScope } = {}+) => {+ const { server, app, appNameForOpId, sanitizedResponseSchema, tags } = ctx;server.route({method: "DELETE",url: `/:connectionId`,@@ -438,8 +513,8 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenschema: {hide: false,operationId: `delete${appNameForOpId}AppConnection`,- tags: [ApiDocsTags.AppConnections],- description: `Delete the specified ${appName} Connection.`,+ tags,+ description,params: z.object({connectionId: z.string().uuid().describe(AppConnections.DELETE(app).connectionId)}),@@ -451,11 +526,12 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenhandler: async (req) => {const { connectionId } = req.params;- const appConnection = (await server.services.appConnection.deleteAppConnection(+ const appConnection = await server.services.appConnection.deleteAppConnection(app,connectionId,- req.permission- )) as T;+ req.permission,+ resolveScope?.(req)+ );await server.services.auditLog.createAuditLog({...req.auditLogInfo,@@ -484,7 +560,16 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenreturn { appConnection };}});+};+export const buildRotateAppConnectionCredentialsRoute = (+ ctx: TAppConnectionRouteContext,+ {+ description = `Rotate the credentials for the specified ${ctx.appName} Connection.`,+ resolveScope+ }: { description?: string; resolveScope?: TResolveScope } = {}+) => {+ const { server, app, appNameForOpId, sanitizedResponseSchema, tags } = ctx;server.route({method: "POST",url: "/:connectionId/rotate-credentials",@@ -494,8 +579,8 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenschema: {hide: false,operationId: `rotate${appNameForOpId}AppConnectionCredentials`,- tags: [ApiDocsTags.AppConnections],- description: `Rotate the credentials for the specified ${appName} Connection.`,+ tags,+ description,params: z.object({connectionId: z.string().uuid().describe(AppConnections.ROTATE_CREDENTIALS(app).connectionId)}),@@ -507,13 +592,18 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenhandler: async (req) => {const { connectionId } = req.params;- await server.services.appConnection.triggerCredentialRotation({ app, connectionId }, req.permission);+ await server.services.appConnection.triggerCredentialRotation(+ { app, connectionId },+ req.permission,+ resolveScope?.(req)+ );- const appConnection = (await server.services.appConnection.findAppConnectionById(+ const appConnection = await server.services.appConnection.findAppConnectionById(app,connectionId,- req.permission- )) as T;+ req.permission,+ resolveScope?.(req)+ );await server.services.auditLog.createAuditLog({...req.auditLogInfo,@@ -530,6 +620,31 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenreturn { appConnection };}});+};++export const registerAppConnectionEndpoints = <I extends TAppConnectionInput>({+ server,+ app,+ createSchema,+ updateSchema,+ sanitizedResponseSchema+}: {+ app: AppConnection;+ server: FastifyZodProvider;+ createSchema: TAppConnectionCreateSchema<I>;+ updateSchema: TAppConnectionUpdateSchema<I>;+ sanitizedResponseSchema: z.ZodTypeAny;+}) => {+ const ctx = buildAppConnectionRouteContext({ server, app, sanitizedResponseSchema });++ buildListAppConnectionsRoute(ctx);+ buildListAvailableAppConnectionsRoute(ctx);+ buildGetAppConnectionRoute(ctx);+ buildGetAppConnectionByNameRoute(ctx);+ buildCreateAppConnectionRoute(ctx, { createSchema });+ buildUpdateAppConnectionRoute(ctx, { updateSchema });+ buildDeleteAppConnectionRoute(ctx);+ buildRotateAppConnectionCredentialsRoute(ctx);// scott: we will need this once we have individual app connection page and may want to expose to API// server.route({diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.tsindex 5779e9e884..3a8e21fcbe 100644--- a/backend/src/services/app-connection/app-connection-fns.ts+++ b/backend/src/services/app-connection/app-connection-fns.ts@@ -350,6 +350,35 @@ const PKI_APP_CONNECTIONS = [AppConnection.MicrosoftIntune];+const AGENT_VAULT_APP_CONNECTIONS = [AppConnection.AWS];++export const isAppConnectionAllowedInProject = (app: AppConnection, projectType?: ProjectType) => {+ switch (projectType) {+ case ProjectType.SecretManager:+ return (+ Boolean(SECRET_SYNC_APP_CONNECTION_MAP[app]) ||+ Boolean(SECRET_ROTATION_APP_CONNECTION_MAP[app]) ||+ EXTERNAL_MIGRATION_APP_CONNECTIONS.includes(app)+ );+ case ProjectType.SecretScanning:+ return Boolean(SECRET_SCANNING_APP_CONNECTION_MAP[app]);+ case ProjectType.CertificateManager:+ return PKI_APP_CONNECTIONS.includes(app);+ case ProjectType.KMS:+ return false;+ case ProjectType.PAM:+ return false;+ case ProjectType.AgentVault:+ return AGENT_VAULT_APP_CONNECTIONS.includes(app);+ default:+ return true;+ }+};++// Products whose allowed connection types are also enforced on create. Other products only use them to filter the picker.+// Add a product only once nothing creates other connection types in it through the API.+export const PROJECT_TYPES_ENFORCING_APP_CONNECTION_TYPES = [ProjectType.AgentVault];+export const listAppConnectionOptions = (orgId: string, projectType?: ProjectType) => {return [getAwsConnectionListItem(),@@ -446,26 +475,7 @@ export const listAppConnectionOptions = (orgId: string, projectType?: ProjectTyp}}- switch (projectType) {- case ProjectType.SecretManager:- return (- Boolean(SECRET_SYNC_APP_CONNECTION_MAP[option.app]) ||- Boolean(SECRET_ROTATION_APP_CONNECTION_MAP[option.app]) ||- EXTERNAL_MIGRATION_APP_CONNECTIONS.includes(option.app)- );- case ProjectType.SecretScanning:- return Boolean(SECRET_SCANNING_APP_CONNECTION_MAP[option.app]);- case ProjectType.CertificateManager:- return PKI_APP_CONNECTIONS.includes(option.app);- case ProjectType.KMS:- return false;- case ProjectType.PAM:- return false;- case ProjectType.AgentVault:- return false;- default:- return true;- }+ return isAppConnectionAllowedInProject(option.app, projectType);}).sort((a, b) => a.name.localeCompare(b.name));};diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex f348daa402..e163b8636b 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -1,7 +1,7 @@import { ForbiddenError, subject } from "@casl/ability";import { Knex } from "knex";-import { ActionProjectType, OrganizationActionScope, TAppConnections } from "@app/db/schemas";+import { ActionProjectType, OrganizationActionScope, ProjectType, TAppConnections } from "@app/db/schemas";import { ValidateChefConnectionCredentialsSchema } from "@app/ee/services/app-connections/chef";import { chefConnectionService } from "@app/ee/services/app-connections/chef/chef-connection-service";import { ValidateOCIConnectionCredentialsSchema } from "@app/ee/services/app-connections/oci";@@ -34,7 +34,9 @@ import {encryptAppConnectionCredentials,enterpriseAppCheck,getAppConnectionMethodName,+ isAppConnectionAllowedInProject,listAppConnectionOptions,+ PROJECT_TYPES_ENFORCING_APP_CONNECTION_TYPES,TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM,validateAppConnectionCredentials} from "@app/services/app-connection/app-connection-fns";@@ -55,6 +57,7 @@ import {TAppConnection,TAppConnectionConfig,TAppConnectionRaw,+ TAppConnectionScope,TCreateAppConnectionDTO,TGetAppConnectionByNameDTO,TUpdateAppConnectionDTO,@@ -393,10 +396,17 @@ export const appConnectionServiceFactory = ({);};- const findAppConnectionById = async (app: AppConnection, connectionId: string, actor: OrgServiceActor) => {+ const findAppConnectionById = async (+ app: AppConnection,+ connectionId: string,+ actor: OrgServiceActor,+ scope?: TAppConnectionScope+ ) => {const appConnection = await appConnectionDAL.findById(connectionId);- if (!appConnection) throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });+ // Checked before any permission or app check, so a connection outside the scope reads exactly like a missing one.+ if (!appConnection || (scope && appConnection.projectId !== scope.projectId))+ throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });if (appConnection.projectId) {const { permission } = await permissionService.getProjectPermission({@@ -548,6 +558,18 @@ export const appConnectionServiceFactory = ({ProjectPermissionAppConnectionActions.Create,ProjectPermissionSub.AppConnections);++ if (+ PROJECT_TYPES_ENFORCING_APP_CONNECTION_TYPES.includes(project.type as ProjectType) &&+ !isAppConnectionAllowedInProject(app, project.type as ProjectType)+ ) {+ const supported = listAppConnectionOptions(actor.orgId, project.type as ProjectType).map(+ (option) => option.name+ );+ throw new BadRequestError({+ message: `${APP_CONNECTION_NAME_MAP[app]} Connections can't be used in this project. It supports: ${supported.join(", ")}.`+ });+ }} else {ForbiddenError.from(orgPermission).throwUnlessCan(OrgPermissionAppConnectionActions.Create,@@ -727,6 +749,7 @@ export const appConnectionServiceFactory = ({};const updateAppConnection = async (+ app: AppConnection,{connectionId,credentials,@@ -737,7 +760,8 @@ export const appConnectionServiceFactory = ({rotation,...params}: TUpdateAppConnectionDTO,- actor: OrgServiceActor+ actor: OrgServiceActor,+ scope?: TAppConnectionScope) => {if (gatewayId && gatewayPoolId) {throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });@@ -745,7 +769,8 @@ export const appConnectionServiceFactory = ({const appConnection = await appConnectionDAL.findById(connectionId);- if (!appConnection) throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });+ if (!appConnection || (scope && appConnection.projectId !== scope.projectId))+ throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });await enterpriseAppCheck(licenseService,@@ -784,6 +809,9 @@ export const appConnectionServiceFactory = ({);}+ if (appConnection.app !== app)+ throw new BadRequestError({ message: `App Connection with ID ${connectionId} is not for App "${app}"` });+if (gatewayId !== undefined && gatewayId !== appConnection.gatewayId) {ForbiddenError.from(orgPermission).throwUnlessCan(OrgPermissionGatewayActions.AttachGateways,@@ -837,7 +865,7 @@ export const appConnectionServiceFactory = ({let updatedCredentials: undefined | TAppConnection["credentials"];- const { app, method } = appConnection as DiscriminativePick<TAppConnectionConfig, "app" | "method">;+ const { method } = appConnection as DiscriminativePick<TAppConnectionConfig, "app" | "method">;let validationGatewayIdForUpdate: string | null | undefined = effectiveGatewayIdForUpdate;if (credentials) {@@ -1097,10 +1125,16 @@ export const appConnectionServiceFactory = ({}};- const deleteAppConnection = async (app: AppConnection, connectionId: string, actor: OrgServiceActor) => {+ const deleteAppConnection = async (+ app: AppConnection,+ connectionId: string,+ actor: OrgServiceActor,+ scope?: TAppConnectionScope+ ) => {const appConnection = await appConnectionDAL.findById(connectionId);- if (!appConnection) throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });+ if (!appConnection || (scope && appConnection.projectId !== scope.projectId))+ throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });if (appConnection.projectId) {const { permission } = await permissionService.getProjectPermission({@@ -1327,11 +1361,13 @@ export const appConnectionServiceFactory = ({const triggerCredentialRotation = async ({ app, connectionId }: { app: AppConnection; connectionId: string },- actor: OrgServiceActor+ actor: OrgServiceActor,+ scope?: TAppConnectionScope) => {const appConnection = await appConnectionDAL.findById(connectionId);- if (!appConnection) throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });+ if (!appConnection || (scope && appConnection.projectId !== scope.projectId))+ throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });if (appConnection.app !== app)throw new BadRequestError({ message: `App Connection with ID ${connectionId} is not for App "${app}"` });diff --git a/backend/src/services/app-connection/app-connection-types.ts b/backend/src/services/app-connection/app-connection-types.tsindex 51857cfdbc..9fdee4dceb 100644--- a/backend/src/services/app-connection/app-connection-types.ts+++ b/backend/src/services/app-connection/app-connection-types.ts@@ -740,6 +740,8 @@ export type TValidateAppConnectionUsageByIdDTO = {projectId: string;};+export type TAppConnectionScope = { projectId: string };+export type TAppConnectionConfig =| TAwsConnectionConfig| TGitHubConnectionConfigdiff --git a/backend/src/services/license-client/feature-mapping.ts b/backend/src/services/license-client/feature-mapping.tsindex c80529ca0f..5a7ec25d36 100644--- a/backend/src/services/license-client/feature-mapping.ts+++ b/backend/src/services/license-client/feature-mapping.ts@@ -363,11 +363,20 @@ const pamMappings: TFeatureMapping[] = [}];+// Agent Vault: session logs written to the customer's own bucket.+const agentVaultMappings: TFeatureMapping[] = [+ {+ v2Key: "agent_vault_byo_s3",+ v1Field: "agentVaultByoS3"+ }+];+export const FEATURE_MAPPINGS: TFeatureMapping[] = [...platformMappings,...secretManagerMappings,...certManagerMappings,- ...pamMappings+ ...pamMappings,+ ...agentVaultMappings];// v1 TFeatureSet keys intentionally not compared: live usage counters, plan metadata, and v1 fieldsdiff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.tsindex 0edd21bccd..c6a04318a2 100644--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts@@ -1,4 +1,3 @@-import { TAgentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";import { TAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";import { TScepTransactionDALFactory } from "@app/ee/services/pki-scep/pki-scep-transaction-dal";@@ -41,7 +40,6 @@ type TDailyResourceCleanUpQueueServiceFactoryDep = {approvalRequestGrantsDAL: Pick<TApprovalRequestGrantsDALFactory, "markExpiredGrants">;certificateRequestDAL: Pick<TCertificateRequestDALFactory, "markExpiredApprovalRequests">;scepTransactionDAL: Pick<TScepTransactionDALFactory, "pruneExpiredTransactions">;- agentVaultSessionService: Pick<TAgentVaultSessionServiceFactory, "sweepRetiredSessions">;};export type TDailyResourceCleanUpQueueServiceFactory = ReturnType<typeof dailyResourceCleanUpQueueServiceFactory>;@@ -65,8 +63,7 @@ export const dailyResourceCleanUpQueueServiceFactory = ({approvalRequestDAL,approvalRequestGrantsDAL,certificateRequestDAL,- scepTransactionDAL,- agentVaultSessionService+ scepTransactionDAL}: TDailyResourceCleanUpQueueServiceFactoryDep) => {const appCfg = getConfig();@@ -99,7 +96,6 @@ export const dailyResourceCleanUpQueueServiceFactory = ({await keyValueStoreDAL.pruneExpiredKeys();await scepTransactionDAL.pruneExpiredTransactions();await identityAccessTokenRevocationDAL.removeExpiredRevocations();- await agentVaultSessionService.sweepRetiredSessions();}});diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex 10eb367e81..c270c23ff1 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -323,6 +323,7 @@ export enum PostHogEventTypes {AgentVaultAccessBundleMemberRemoved = "Agent Vault Access Bundle Member Removed",AgentVaultSessionCreated = "Agent Vault Session Created",AgentVaultSessionRevoked = "Agent Vault Session Revoked",+ AgentVaultSessionLogSettingsUpdated = "Agent Vault Session Log Settings Updated",AgentVaultProxyRegistered = "Agent Vault Proxy Registered",AgentVaultProxyUpdated = "Agent Vault Proxy Updated",AgentVaultProxyDeleted = "Agent Vault Proxy Deleted",@@ -2488,6 +2489,14 @@ export type TAgentVaultSessionRevokedEvent = {properties: TAgentVaultEventBase & { sessionId: string };};+export type TAgentVaultSessionLogSettingsUpdatedEvent = {+ event: PostHogEventTypes.AgentVaultSessionLogSettingsUpdated;+ properties: TAgentVaultEventBase & {+ enabled: boolean;+ hasDestination: boolean;+ };+};+export type TAgentVaultProxyRegisteredEvent = {event: PostHogEventTypes.AgentVaultProxyRegistered;properties: TAgentVaultEventBase & {@@ -2557,6 +2566,7 @@ export type TAgentVaultPostHogEvent =| TAgentVaultAccessBundleMemberRemovedEvent| TAgentVaultSessionCreatedEvent| TAgentVaultSessionRevokedEvent+ | TAgentVaultSessionLogSettingsUpdatedEvent| TAgentVaultProxyRegisteredEvent| TAgentVaultProxyUpdatedEvent| TAgentVaultProxyDeletedEventdiff --git a/backend/vitest.e2e.config.mts b/backend/vitest.e2e.config.mtsindex 3ff5a10ca5..aaa3ad1a9b 100644--- a/backend/vitest.e2e.config.mts+++ b/backend/vitest.e2e.config.mts@@ -84,6 +84,10 @@ export default defineConfig({{find: "./aws-connection-fns",replacement: path.resolve(__dirname, "./e2e-test/fakes/aws-connection-fns")+ },+ {+ find: /^@app\/lib\/aws\/s3$/,+ replacement: path.resolve(__dirname, "./e2e-test/fakes/s3")}]},diff --git a/docs/api-reference/endpoints/agent-vault-app-connections/create.mdx b/docs/api-reference/endpoints/agent-vault-app-connections/create.mdxnew file mode 100644index 0000000000..292a7d2d43--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-app-connections/create.mdx@@ -0,0 +1,4 @@+---+title: "Create AWS connection"+openapi: "POST /api/v1/agent-vault/app-connections/aws"+---diff --git a/docs/api-reference/endpoints/agent-vault-app-connections/delete.mdx b/docs/api-reference/endpoints/agent-vault-app-connections/delete.mdxnew file mode 100644index 0000000000..d2c8b450f6--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-app-connections/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete AWS connection"+openapi: "DELETE /api/v1/agent-vault/app-connections/aws/{connectionId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-app-connections/get.mdx b/docs/api-reference/endpoints/agent-vault-app-connections/get.mdxnew file mode 100644index 0000000000..f6748b5823--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-app-connections/get.mdx@@ -0,0 +1,4 @@+---+title: "Get AWS connection"+openapi: "GET /api/v1/agent-vault/app-connections/aws/{connectionId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-app-connections/list.mdx b/docs/api-reference/endpoints/agent-vault-app-connections/list.mdxnew file mode 100644index 0000000000..ebf5cc758e--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-app-connections/list.mdx@@ -0,0 +1,4 @@+---+title: "List AWS connections"+openapi: "GET /api/v1/agent-vault/app-connections/aws"+---diff --git a/docs/api-reference/endpoints/agent-vault-app-connections/update.mdx b/docs/api-reference/endpoints/agent-vault-app-connections/update.mdxnew file mode 100644index 0000000000..78c1754c41--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-app-connections/update.mdx@@ -0,0 +1,4 @@+---+title: "Update AWS connection"+openapi: "PATCH /api/v1/agent-vault/app-connections/aws/{connectionId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-session-logs/list.mdx b/docs/api-reference/endpoints/agent-vault-session-logs/list.mdxnew file mode 100644index 0000000000..b5b52c6f75--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-session-logs/list.mdx@@ -0,0 +1,4 @@+---+title: "List session logs"+openapi: "GET /api/v1/agent-vault/sessions/{sessionId}/logs"+---diff --git a/docs/api-reference/endpoints/agent-vault-session-logs/tail.mdx b/docs/api-reference/endpoints/agent-vault-session-logs/tail.mdxnew file mode 100644index 0000000000..2ed8db642c--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-session-logs/tail.mdx@@ -0,0 +1,4 @@+---+title: "Tail session logs"+openapi: "GET /api/v1/agent-vault/sessions/{sessionId}/logs/tail"+---diff --git a/docs/api-reference/endpoints/agent-vault-sessions/get.mdx b/docs/api-reference/endpoints/agent-vault-sessions/get.mdxnew file mode 100644index 0000000000..2caba8d000--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-sessions/get.mdx@@ -0,0 +1,4 @@+---+title: "Get session"+openapi: "GET /api/v1/agent-vault/sessions/{sessionId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-settings/get-session-log-settings.mdx b/docs/api-reference/endpoints/agent-vault-settings/get-session-log-settings.mdxnew file mode 100644index 0000000000..9ee7d56d47--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-settings/get-session-log-settings.mdx@@ -0,0 +1,4 @@+---+title: "Get session log settings"+openapi: "GET /api/v1/agent-vault/settings/session-logs"+---diff --git a/docs/api-reference/endpoints/agent-vault-settings/update-session-log-settings.mdx b/docs/api-reference/endpoints/agent-vault-settings/update-session-log-settings.mdxnew file mode 100644index 0000000000..ca1de51531--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-settings/update-session-log-settings.mdx@@ -0,0 +1,4 @@+---+title: "Update session log settings"+openapi: "PATCH /api/v1/agent-vault/settings/session-logs"+---diff --git a/docs/docs.json b/docs/docs.jsonindex 1c7e61e4ad..16be8632fc 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -801,6 +801,7 @@"documentation/platform/agent-vault/access-bundles","documentation/platform/agent-vault/services","documentation/platform/agent-vault/sessions",+ "documentation/platform/agent-vault/session-logs","documentation/platform/agent-vault/proxies","documentation/platform/agent-vault/access-control"]@@ -4438,8 +4439,28 @@"group": "Sessions","pages": ["api-reference/endpoints/agent-vault-sessions/list",+ "api-reference/endpoints/agent-vault-sessions/get","api-reference/endpoints/agent-vault-sessions/create",- "api-reference/endpoints/agent-vault-sessions/revoke"+ "api-reference/endpoints/agent-vault-sessions/revoke",+ "api-reference/endpoints/agent-vault-session-logs/list",+ "api-reference/endpoints/agent-vault-session-logs/tail"+ ]+ },+ {+ "group": "Settings",+ "pages": [+ "api-reference/endpoints/agent-vault-settings/get-session-log-settings",+ "api-reference/endpoints/agent-vault-settings/update-session-log-settings"+ ]+ },+ {+ "group": "App connections",+ "pages": [+ "api-reference/endpoints/agent-vault-app-connections/list",+ "api-reference/endpoints/agent-vault-app-connections/get",+ "api-reference/endpoints/agent-vault-app-connections/create",+ "api-reference/endpoints/agent-vault-app-connections/update",+ "api-reference/endpoints/agent-vault-app-connections/delete"]}]diff --git a/docs/documentation/platform/agent-vault/how-it-works.mdx b/docs/documentation/platform/agent-vault/how-it-works.mdxindex 1bd9c361a7..03cd63e9c7 100644--- a/docs/documentation/platform/agent-vault/how-it-works.mdx+++ b/docs/documentation/platform/agent-vault/how-it-works.mdx@@ -154,7 +154,7 @@ Even if an attacker stole the session token, they could only reach the hosts, meA proxy runs where your agent's traffic leaves your network. It intercepts every outbound request, authorizes the request against the session's access bundle, attaches the matching service's credential as a header, and forwards the request to the upstream host. If the request breaks the matching service's [method or path rules](/documentation/platform/agent-vault/services#methods-and-paths), the proxy refuses it instead.-<Card title="Proxies" icon="route" href="/documentation/platform/agent-vault/proxies">+<Card title="Proxies" icon="server" href="/documentation/platform/agent-vault/proxies">Forward proxies that intercept an AI agent's requests and attach real credentials on the way out.</Card>diff --git a/docs/documentation/platform/agent-vault/overview.mdx b/docs/documentation/platform/agent-vault/overview.mdxindex 511aea78e4..16e804de41 100644--- a/docs/documentation/platform/agent-vault/overview.mdx+++ b/docs/documentation/platform/agent-vault/overview.mdx@@ -34,9 +34,12 @@ Infisical Agent Vault is an access layer for AI agents. It securely equips agent<Card title="Sessions" icon="monitor" href="/documentation/platform/agent-vault/sessions">Time-bound grants that let AI agents access services without holding real credentials.</Card>- <Card title="Proxies" icon="route" href="/documentation/platform/agent-vault/proxies">+ <Card title="Proxies" icon="server" href="/documentation/platform/agent-vault/proxies">Forward proxies that intercept an AI agent's requests and attach real credentials on the way out.</Card>+ <Card title="Session logs" icon="list" href="/documentation/platform/agent-vault/session-logs">+ A record of every request an AI agent makes, stored encrypted in your own Amazon S3 bucket.+ </Card><Card title="Access control" icon="shield-half" href="/documentation/platform/agent-vault/access-control">Understand how permissions work in Agent Vault.</Card>diff --git a/docs/documentation/platform/agent-vault/session-logs.mdx b/docs/documentation/platform/agent-vault/session-logs.mdxnew file mode 100644index 0000000000..6894b39214--- /dev/null+++ b/docs/documentation/platform/agent-vault/session-logs.mdx@@ -0,0 +1,210 @@+---+title: "Session logs"+description: "Keep an encrypted record of every request an AI agent makes, stored in your own Amazon S3 bucket."+---++<Info>+ Session logs are a paid feature.++ If you're using Infisical Cloud, they're available under the **Enterprise Tier**. If you're self-hosting Infisical, contact [email protected] to purchase an enterprise license to use them.+</Info>++A session log is the per-request record of what an agent actually did: the method, host, path, status, and whether a credential went out with it. Every request that reaches a proxy is recorded, including requests to hosts that no access bundle covers.++Records are encrypted before they leave the proxy and stored in an Amazon S3 bucket you own.++## Setting up session logs++Go to **Settings** under Agent Vault and select **Set Up Session Logs** on the **Session Logs** card:++1. Turn on **Enable**.+2. Pick the **AWS Connection** whose credentials write the records. It can be one from your organization or one created in Agent Vault, or select **Create New Connection** to add one.+3. Enter the **Bucket** and **Region** of an S3 bucket you've already created.+4. Optionally set a **Key Prefix**, so session logs sit under one path in a bucket you use for other things.+5. Select **Save**.++<Frame>+ <img src="/images/platform/agent-vault/session-logs-setup.png" alt="The Session Logs dialog with Enable turned on and an AWS connection, region, bucket, and key prefix filled in" />+</Frame>++When you save, Infisical checks that the bucket exists and that it can write to it.++The connection needs an IAM policy and the bucket needs a CORS rule. Select **View AWS Setup** in the **Session Logs** dialog to see both.++<Tabs>+ <Tab title="IAM policy">+ Attach this identity policy (not a bucket policy) to the user or role the connection authenticates as:++ ```json+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": ["s3:PutObject", "s3:GetObject"],+ "Resource": "arn:aws:s3:::<bucket>/<prefix>/*"+ },+ {+ "Effect": "Allow",+ "Action": ["s3:ListBucket"],+ "Resource": "arn:aws:s3:::<bucket>"+ }+ ]+ }+ ```+ </Tab>+ <Tab title="CORS rule">+ Add this CORS rule to the bucket, because your browser is what fetches the records:++ ```json+ [+ {+ "AllowedHeaders": ["*"],+ "AllowedMethods": ["GET"],+ "AllowedOrigins": ["https://app.infisical.com"],+ "MaxAgeSeconds": 3000+ }+ ]+ ```++ If you're on EU Cloud or a self-hosted instance, replace `https://app.infisical.com` with `https://eu.infisical.com` or your instance's URL.+ </Tab>+</Tabs>++## Viewing session logs++Go to **Sessions** and select **View Session Logs** on the session's row. You can filter and search the requests, and while the session is active, new logs keep appearing.++<Frame>+ <img src="/images/platform/agent-vault/session-logs-view.png" alt="The Session Logs sheet for an active session, listing each request's time, method, host, path, upstream status, and outcome" />+</Frame>++<Accordion title="Reading session logs through the API" id="reading-session-logs-through-the-api">+ The API returns a session's logs as chunks. A chunk is one encrypted batch of [records](#what-gets-recorded) that a proxy uploaded to your bucket. You can read a session's logs if you created the session or you're an Agent Vault admin.++ <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. If `presignedGetUrl` is null, either the chunk is in a bucket other than the current one, or `sessionLogs.storageUnavailable` says why the chunk can't be downloaded right now.+ </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.+ </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.+ </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:++ ```json+ {+ "ts": "2026-09-16T10:31:04.221Z",+ "seq": 8412,+ "proxyId": "7c1e…",+ "method": "POST",+ "host": "api.github.com",+ "port": "443",+ "path": "/repos/acme/web/issues",+ "status": 201,+ "decision": "brokered",+ "service": "github",+ "accessBundle": "code-review"+ }+ ```+ </Step>+ </Steps>++ This Node.js script reads the newest page of a session's logs:++ ```javascript+ import { createDecipheriv, createHash } from "node:crypto";++ const token = "<your-access-token>";+ const sessionId = "<session-id>".toLowerCase();++ const res = await fetch(`https://app.infisical.com/api/v1/agent-vault/sessions/${sessionId}/logs`, {+ headers: { Authorization: `Bearer ${token}` }+ });+ const { 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")+ );+ decipher.setAAD(aad);+ decipher.setAuthTag(body.subarray(-16));+ const plaintext = Buffer.concat([decipher.update(body.subarray(0, -16)), decipher.final()]);++ console.log(JSON.parse(plaintext.toString("utf8")));+ }+ ```++ The script runs outside a browser, so the bucket's CORS rule doesn't apply to it.++ 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.+</Accordion>++## What gets recorded++Each request produces one record with:++| Field | What it holds |+| --- | --- |+| **Time** | When the request was made |+| **Proxy** | The proxy that handled it |+| **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 Agent Vault returned itself, such as `403` or `502` |+| **Outcome** | What the proxy did with the request |+| **Service** | The service that matched the request, if any |++The outcome is one of four:++| Outcome | What happened |+| --- | --- |+| **Brokered** | A service matched and its credential went out with the request |+| **Passthrough** | No service matched, or the one that did carries no credential. The request went out untouched |+| **Blocked** | The traffic policy refused the request |+| **Error** | The proxy couldn't reach the upstream |++Request and response bodies, headers, and query strings aren't recorded.++## Managing session logs++### Connections++Session logs use one AWS connection at a time, which you pick in the **Session Logs** dialog. It can be one created in Agent Vault or one your organization already has under **Integrations**. See [AWS connection](/integrations/app-connections/aws) for how to create one.++To update its AWS credentials, open the menu next to **Configure** on the **Session Logs** card and select **Edit AWS Credentials**. For an organization connection, update the credentials under **Integrations** instead.++To add or delete Agent Vault's AWS connections, select **Manage Connections** from the same menu:++<Frame>+ <img src="/images/platform/agent-vault/session-logs-connections.png" alt="The Manage Connections sheet listing Agent Vault's AWS connections, with the one session logs use marked In Use" />+</Frame>++You can't delete the connection session logs are using. Pick a different one in the **Session Logs** dialog first.++### Changing the bucket or prefix++Changing the bucket copies nothing, so everything recorded before the change can't be read in Infisical until you switch back to that bucket.++Changing only the key prefix keeps earlier records readable, as long as the AWS connection can still read the old prefix. The [IAM policy](#setting-up-session-logs) on this page covers only the current prefix.++### Retention++Infisical never deletes sessions or their session logs. To delete older logs automatically, add a lifecycle rule to the bucket in AWS.++## Troubleshooting++If a session shows no session logs when you expect some, check the logs of each proxy the agent used.diff --git a/docs/documentation/platform/agent-vault/sessions.mdx b/docs/documentation/platform/agent-vault/sessions.mdxindex 7766b5142d..bfb39aef82 100644--- a/docs/documentation/platform/agent-vault/sessions.mdx+++ b/docs/documentation/platform/agent-vault/sessions.mdx@@ -54,11 +54,19 @@ Anyone granted at least one access bundle can create a session. Admins can creatPicking **Never** as the duration keeps the session working until someone revokes it. Only use this for long-running agents, and revoke the session once the agent has finished.</Tip>+## View session logs++Session logs record every request an agent makes during a session. If you haven't already, [set up session logs](/documentation/platform/agent-vault/session-logs#setting-up-session-logs). Then go to **Sessions** and select **View Session Logs** on the session's row. You can filter and search the requests, and while the session is active, new logs keep appearing.++<Frame>+ <img src="/images/platform/agent-vault/session-logs-view.png" alt="The Session Logs sheet for an active session, listing each request's time, method, host, path, upstream status, and outcome" />+</Frame>+## Revoke a sessionTo revoke a session before it expires, go to the **Sessions** page, open the session's menu, and select **Revoke Session**. The proxy stops attaching credentials for the session within one [poll interval](/documentation/platform/agent-vault/proxies#poll-interval).-The **Sessions** page shows each session as **Active**, **Revoked**, or **Expired**, and keeps expired and revoked sessions for 30 days so you can audit what an agent had access to during the session:+The **Sessions** page shows each session as **Active**, **Revoked**, or **Expired**, and keeps expired and revoked sessions so you can audit what an agent had access to during the session:<Frame><img src="/images/platform/agent-vault/sessions-list.png" alt="The Sessions page listing active, revoked, and expired sessions with their access bundle and expiry" />@@ -80,3 +88,5 @@ If a session stops getting credentials because of a lost grant or a deleted bund## Audit trailWhen you create or revoke a session, Infisical writes an audit event. To review these events, open **Audit Logs** in Agent Vault, or scope an [audit log stream](/documentation/platform/audit-log-streams/audit-log-streams) to the Agent Vault product.++Audit events cover what you changed in Infisical. To see what an agent reached while its session was running, [view its session logs](#view-session-logs).diff --git a/docs/images/platform/agent-vault/session-logs-connections.png b/docs/images/platform/agent-vault/session-logs-connections.pngnew file mode 100644index 0000000000..f8c2fd01bfBinary files /dev/null and b/docs/images/platform/agent-vault/session-logs-connections.png differdiff --git a/docs/images/platform/agent-vault/session-logs-setup.png b/docs/images/platform/agent-vault/session-logs-setup.pngnew file mode 100644index 0000000000..ff1354a158Binary files /dev/null and b/docs/images/platform/agent-vault/session-logs-setup.png differdiff --git a/docs/images/platform/agent-vault/session-logs-view.png b/docs/images/platform/agent-vault/session-logs-view.pngnew file mode 100644index 0000000000..0e09b39ae7Binary files /dev/null and b/docs/images/platform/agent-vault/session-logs-view.png differdiff --git a/frontend/index.html b/frontend/index.htmlindex 4a75f674b4..f909f8b6a7 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -12,7 +12,7 @@style-src 'self' 'unsafe-inline' https://hcaptcha.com https://*.hcaptcha.com https://tags.srv.stackadapt.com;child-src https://api.stripe.com;frame-src https://js.stripe.com/ https://api.stripe.com https://www.youtube.com/ https://hcaptcha.com https://*.hcaptcha.com https://www.googletagmanager.com;- connect-src 'self' blob: wss://nexus-websocket-a.intercom.io https://api-iam.intercom.io https://api.heroku.com/ https://id.heroku.com/oauth/authorize https://id.heroku.com/oauth/token https://checkout.stripe.com https://app.posthog.com https://*.posthog.com https://api.stripe.com https://api.pwnedpasswords.com http://127.0.0.1:* https://hcaptcha.com https://*.hcaptcha.com https://www.googletagmanager.com https://www.google-analytics.com https://region1.google-analytics.com https://analytics.google.com https://stats.g.doubleclick.net https://googleads.g.doubleclick.net https://forms.hscollectedforms.net https://forms.hubspot.com https://api.hubapi.com https://*.ads.linkedin.com https://tags.srv.stackadapt.com https://api.unifyintent.com https://pixel-config.reddit.com https://static.ads-twitter.com https://analytics.twitter.com https://cdn.jsdelivr.net/npm/@lottiefiles/[email protected]/dist/dotlottie-player.wasm https://*.s3.amazonaws.com https://*.s3.us-east-1.amazonaws.com https://*.s3.us-east-2.amazonaws.com https://*.s3.us-west-1.amazonaws.com https://*.s3.us-west-2.amazonaws.com https://*.s3.af-south-1.amazonaws.com https://*.s3.ap-east-1.amazonaws.com https://*.s3.ap-south-1.amazonaws.com https://*.s3.ap-south-2.amazonaws.com https://*.s3.ap-southeast-1.amazonaws.com https://*.s3.ap-southeast-2.amazonaws.com https://*.s3.ap-southeast-3.amazonaws.com https://*.s3.ap-southeast-4.amazonaws.com https://*.s3.ap-northeast-1.amazonaws.com https://*.s3.ap-northeast-2.amazonaws.com https://*.s3.ap-northeast-3.amazonaws.com https://*.s3.ca-central-1.amazonaws.com https://*.s3.eu-central-1.amazonaws.com https://*.s3.eu-central-2.amazonaws.com https://*.s3.eu-west-1.amazonaws.com https://*.s3.eu-west-2.amazonaws.com https://*.s3.eu-west-3.amazonaws.com https://*.s3.eu-south-1.amazonaws.com https://*.s3.eu-south-2.amazonaws.com https://*.s3.eu-north-1.amazonaws.com https://*.s3.me-south-1.amazonaws.com https://*.s3.me-central-1.amazonaws.com https://*.s3.sa-east-1.amazonaws.com https://*.s3.us-gov-east-1.amazonaws.com https://*.s3.us-gov-west-1.amazonaws.com;+ connect-src 'self' blob: wss://nexus-websocket-a.intercom.io https://api-iam.intercom.io https://api.heroku.com/ https://id.heroku.com/oauth/authorize https://id.heroku.com/oauth/token https://checkout.stripe.com https://app.posthog.com https://*.posthog.com https://api.stripe.com https://api.pwnedpasswords.com http://127.0.0.1:* https://hcaptcha.com https://*.hcaptcha.com https://www.googletagmanager.com https://www.google-analytics.com https://region1.google-analytics.com https://analytics.google.com https://stats.g.doubleclick.net https://googleads.g.doubleclick.net https://forms.hscollectedforms.net https://forms.hubspot.com https://api.hubapi.com https://*.ads.linkedin.com https://tags.srv.stackadapt.com https://api.unifyintent.com https://pixel-config.reddit.com https://static.ads-twitter.com https://analytics.twitter.com https://cdn.jsdelivr.net/npm/@lottiefiles/[email protected]/dist/dotlottie-player.wasm https://*.s3.amazonaws.com https://*.s3.us-east-1.amazonaws.com https://*.s3.us-east-2.amazonaws.com https://*.s3.us-west-1.amazonaws.com https://*.s3.us-west-2.amazonaws.com https://*.s3.af-south-1.amazonaws.com https://*.s3.ap-east-1.amazonaws.com https://*.s3.ap-south-1.amazonaws.com https://*.s3.ap-south-2.amazonaws.com https://*.s3.ap-southeast-1.amazonaws.com https://*.s3.ap-southeast-2.amazonaws.com https://*.s3.ap-southeast-3.amazonaws.com https://*.s3.ap-southeast-4.amazonaws.com https://*.s3.ap-northeast-1.amazonaws.com https://*.s3.ap-northeast-2.amazonaws.com https://*.s3.ap-northeast-3.amazonaws.com https://*.s3.ca-central-1.amazonaws.com https://*.s3.eu-central-1.amazonaws.com https://*.s3.eu-central-2.amazonaws.com https://*.s3.eu-west-1.amazonaws.com https://*.s3.eu-west-2.amazonaws.com https://*.s3.eu-west-3.amazonaws.com https://*.s3.eu-south-1.amazonaws.com https://*.s3.eu-south-2.amazonaws.com https://*.s3.eu-north-1.amazonaws.com https://*.s3.me-south-1.amazonaws.com https://*.s3.me-central-1.amazonaws.com https://*.s3.sa-east-1.amazonaws.com https://*.s3.us-gov-east-1.amazonaws.com https://*.s3.us-gov-west-1.amazonaws.com https://s3.amazonaws.com https://s3.us-east-1.amazonaws.com https://s3.us-east-2.amazonaws.com https://s3.us-west-1.amazonaws.com https://s3.us-west-2.amazonaws.com https://s3.af-south-1.amazonaws.com https://s3.ap-east-1.amazonaws.com https://s3.ap-south-1.amazonaws.com https://s3.ap-south-2.amazonaws.com https://s3.ap-southeast-1.amazonaws.com https://s3.ap-southeast-2.amazonaws.com https://s3.ap-southeast-3.amazonaws.com https://s3.ap-southeast-4.amazonaws.com https://s3.ap-northeast-1.amazonaws.com https://s3.ap-northeast-2.amazonaws.com https://s3.ap-northeast-3.amazonaws.com https://s3.ca-central-1.amazonaws.com https://s3.eu-central-1.amazonaws.com https://s3.eu-central-2.amazonaws.com https://s3.eu-west-1.amazonaws.com https://s3.eu-west-2.amazonaws.com https://s3.eu-west-3.amazonaws.com https://s3.eu-south-1.amazonaws.com https://s3.eu-south-2.amazonaws.com https://s3.eu-north-1.amazonaws.com https://s3.me-south-1.amazonaws.com https://s3.me-central-1.amazonaws.com https://s3.sa-east-1.amazonaws.com https://s3.us-gov-east-1.amazonaws.com https://s3.us-gov-west-1.amazonaws.com https://*.s3-fips.us-east-1.amazonaws.com https://s3-fips.us-east-1.amazonaws.com https://*.s3-fips.us-east-2.amazonaws.com https://s3-fips.us-east-2.amazonaws.com https://*.s3-fips.us-west-1.amazonaws.com https://s3-fips.us-west-1.amazonaws.com https://*.s3-fips.us-west-2.amazonaws.com https://s3-fips.us-west-2.amazonaws.com https://*.s3-fips.ca-central-1.amazonaws.com https://s3-fips.ca-central-1.amazonaws.com https://*.s3-fips.us-gov-east-1.amazonaws.com https://s3-fips.us-gov-east-1.amazonaws.com https://*.s3-fips.us-gov-west-1.amazonaws.com https://s3-fips.us-gov-west-1.amazonaws.com;img-src 'self' https://static.intercomassets.com https://js.intercomcdn.com https://downloads.intercomcdn.com https://*.stripe.com https://i.ytimg.com/ data: https://images.ctfassets.net https://www.googletagmanager.com https://www.google-analytics.com https://www.google.com https://googleads.g.doubleclick.net https://www.googleadservices.com https://track.hubspot.com https://forms.hubspot.com https://forms.hsforms.com https://alb.reddit.com https://*.ads.linkedin.com https://analytics.twitter.com;media-src 'self' https://js.intercomcdn.com;font-src 'self' data: https://fonts.intercomcdn.com/ https://fonts.gstatic.com;diff --git a/frontend/src/components/agent-vault/AgentVaultSessionLogUpgradeModal.tsx b/frontend/src/components/agent-vault/AgentVaultSessionLogUpgradeModal.tsxnew file mode 100644index 0000000000..4a102e9657--- /dev/null+++ b/frontend/src/components/agent-vault/AgentVaultSessionLogUpgradeModal.tsx@@ -0,0 +1,16 @@+import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+};++export const AgentVaultSessionLogUpgradeModal = ({ isOpen, onOpenChange }: Props) => (+ <UpgradePlanModal+ paywallKey="agent-vault.session-logs"+ isOpen={isOpen}+ onOpenChange={onOpenChange}+ isEnterpriseFeature+ text="Your current plan does not include session logs, which record every request your agents make. To unlock them, upgrade to the Infisical Enterprise plan."+ />+);diff --git a/frontend/src/components/agent-vault/MemberName.tsx b/frontend/src/components/agent-vault/MemberName.tsxindex 9b09624e16..b67a16e114 100644--- a/frontend/src/components/agent-vault/MemberName.tsx+++ b/frontend/src/components/agent-vault/MemberName.tsx@@ -1,7 +1,11 @@import { BotIcon, UserIcon, UsersIcon } from "lucide-react";import { AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";-import { TAgentVaultActor, TAgentVaultMember } from "@app/hooks/api/agentVault/types";+import {+ TAgentVaultActor,+ TAgentVaultMember,+ TAgentVaultSessionActor+} from "@app/hooks/api/agentVault/types";export const MEMBER_KIND: Record<AgentVaultMemberType, { label: string; icon: typeof UserIcon }> = {[AgentVaultMemberType.User]: { label: "User", icon: UserIcon },@@ -9,14 +13,14 @@ export const MEMBER_KIND: Record<AgentVaultMemberType, { label: string; icon: ty[AgentVaultMemberType.Group]: { label: "Group", icon: UsersIcon }};-export const memberDisplayName = (actor: TAgentVaultActor) => {+export const memberDisplayName = (actor: TAgentVaultActor | TAgentVaultSessionActor) => {if (actor.type !== AgentVaultMemberType.User) return actor.name;const fullName = [actor.firstName, actor.lastName].filter(Boolean).join(" ");return fullName || actor.username || actor.email || "Unknown";};-export const memberSubtitle = (actor: TAgentVaultActor) => {+export const memberSubtitle = (actor: TAgentVaultActor | TAgentVaultSessionActor) => {if (actor.type !== AgentVaultMemberType.User) return MEMBER_KIND[actor.type].label;return actor.email || actor.username;};diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsxindex b35dde7082..e18d4a479d 100644--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx@@ -1,6 +1,7 @@import { useEffect, useMemo, useRef, useState } from "react";import { FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";+import slugify from "@sindresorhus/slugify";import axios from "axios";import { createNotification } from "@app/components/notifications";@@ -20,7 +21,7 @@ import {} from "@app/components/v3";import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";import { hostError } from "@app/helpers/agentVaultHostPattern";-import { AgentVaultTemplate } from "@app/helpers/agentVaultTemplates";+import { AgentVaultTemplate, findTemplateForHostPattern } from "@app/helpers/agentVaultTemplates";import { useDiscardChangesGuard, useWizardSteps } from "@app/hooks";import {AgentVaultCredentialType,@@ -64,11 +65,36 @@ const BLANK_SERVICE_FORM: TServiceForm = {substitutions: []};+// A template placeholder like <your-tenant>.atlassian.net is not a host, so it goes into the draft.+const formFromTemplate = (picked: AgentVaultTemplate | null, hosts: string[]): TServiceForm => {+ const hostFields = {+ hosts: hosts.filter((host) => !hostError(host, [])),+ hostDraft: hosts.find((host) => Boolean(hostError(host, []))) ?? ""+ };+ if (!picked) {+ return { ...BLANK_SERVICE_FORM, ...hostFields };+ }++ const cred = picked.credential;+ return {+ ...BLANK_SERVICE_FORM,+ name: picked.key,+ ...hostFields,+ credentialType: cred.type,+ ...(cred.type === AgentVaultCredentialType.Bearer && {+ headerName: cred.headerName ?? "Authorization",+ headerPrefix: cred.headerPrefix ?? "Bearer"+ })+ };+};+type Props = {isOpen: boolean;onOpenChange: (isOpen: boolean) => void;accessBundleId: string;service?: TAgentVaultService | null;+ prefillHost?: string;+ onSaved?: () => void;};// Long enough for the advanced section to open and settle. There is no event to wait on: the section@@ -76,7 +102,14 @@ type Props = {// until after it mounts and takes its height.const SECTION_OPEN_MS = 250;-export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }: Props) => {+export const ServiceSheet = ({+ isOpen,+ onOpenChange,+ accessBundleId,+ service,+ prefillHost,+ onSaved+}: Props) => {const isUpdate = Boolean(service);const createService = useCreateAgentVaultService();const updateService = useUpdateAgentVaultService();@@ -100,10 +133,15 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =useDiscardChangesGuard({ isDirty, onDiscard: () => onOpenChange(false) });+ // A prefilled host has already been matched against the templates, and anything picked on the+ // template step would replace that host.+ const hasTemplateStep = !isUpdate && !prefillHost;const steps = useMemo(() =>- isUpdate ? SERVICE_STEPS.filter((meta) => meta.step !== ServiceStep.Template) : SERVICE_STEPS,- [isUpdate]+ hasTemplateStep+ ? SERVICE_STEPS+ : SERVICE_STEPS.filter((meta) => meta.step !== ServiceStep.Template),+ [hasTemplateStep]);const stepKeys = useMemo(() => steps.map((meta) => meta.step), [steps]);@@ -183,33 +221,35 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:value: UNCHANGED_SECRET}))});+ } else if (prefillHost) {+ const picked = findTemplateForHostPattern(prefillHost) ?? null;+ const form = formFromTemplate(picked, [prefillHost]);+ setTemplate(picked);+ reset(+ picked+ ? form+ : {+ ...form,+ name: slugify(prefillHost.replace(/:\d+$/, ""), { lowercase: true })+ .slice(0, 64)+ .replace(/-+$/, "")+ }+ );} else {reset(BLANK_SERVICE_FORM);}- }, [isOpen, service, isUpdate, reset, setStep]);+ }, [isOpen, service, isUpdate, prefillHost, reset, setStep]);const handleTemplatePicked = (picked: AgentVaultTemplate | null) => {setTemplate(picked);-- if (picked) {- const cred = picked.credential;- // A template placeholder like <your-tenant>.atlassian.net is not a host, so it goes into the draft.- const parts = picked.hostPattern.split(",").map((host) => host.trim());-- reset({- ...BLANK_SERVICE_FORM,- name: picked.key,- hosts: parts.filter((host) => !hostError(host, [])),- hostDraft: parts.find((host) => Boolean(hostError(host, []))) ?? "",- credentialType: cred.type,- ...(cred.type === AgentVaultCredentialType.Bearer && {- headerName: cred.headerName ?? "Authorization",- headerPrefix: cred.headerPrefix ?? "Bearer"- })- });- } else {- reset(BLANK_SERVICE_FORM);- }+ reset(+ picked+ ? formFromTemplate(+ picked,+ picked.hostPattern.split(",").map((host) => host.trim())+ )+ : BLANK_SERVICE_FORM+ );setStep(1);};@@ -301,6 +341,7 @@ export const ServiceSheet = ({ isOpen, onOpenChange, accessBundleId, service }:type: "success"});+ onSaved?.();onOpenChange(false);} catch (error) {const serverResponse = axios.isAxiosError(error)diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect.tsxindex 47ca3c8f2e..3659de6c8e 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect.tsx@@ -15,6 +15,7 @@ type Props = {value: string;onChange: (value: string | undefined) => void;isError?: boolean;+ isDisabled?: boolean;"aria-describedby"?: string;"aria-labelledby"?: string;};diff --git a/frontend/src/components/v3/generic/Table/Table.tsx b/frontend/src/components/v3/generic/Table/Table.tsxindex f2b43e970d..4c70c3db96 100644--- a/frontend/src/components/v3/generic/Table/Table.tsx+++ b/frontend/src/components/v3/generic/Table/Table.tsx@@ -50,7 +50,10 @@ function TableHeader({data-slot="table-header"className={cn("text-sm [&_tr]:border-b [&_tr]:hover:bg-transparent",- sticky && "sticky top-0 z-10 bg-container",+ // collapsed borders are painted by the table and scroll away under a sticky header,+ // so the header draws its bottom border as an inset shadow that moves with it+ sticky &&+ "sticky top-0 z-10 bg-container [&_th]:border-b-0 [&_th]:shadow-[inset_0_-1px_0_var(--color-border)] [&_tr]:border-b-0",className)}{...props}diff --git a/frontend/src/components/v3/platform/DateRangeFilter/DateRangeFilter.stories.tsx b/frontend/src/components/v3/platform/DateRangeFilter/DateRangeFilter.stories.tsxnew file mode 100644index 0000000000..9f1b8a8121--- /dev/null+++ b/frontend/src/components/v3/platform/DateRangeFilter/DateRangeFilter.stories.tsx@@ -0,0 +1,341 @@+import { useState } from "react";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { subDays, subMonths } from "date-fns";+import { expect, fireEvent, fn, userEvent, within } from "storybook/test";++import { ButtonGroup } from "../../generic/ButtonGroup";+import {+ DateRangeFilter,+ type DateRangeFilterAccent,+ type DateRangeFilterResult,+ DateRangeFilterType+} from "./DateRangeFilter";+import { DateRangeQuickPresets } from "./DateRangeQuickPresets";++const atTime = (date: Date, hours: number, minutes = 0) => {+ const result = new Date(date);+ result.setHours(hours, minutes, 0, 0);+ return result;+};++const meta = {+ title: "Platform/Date Range Filter",+ component: DateRangeFilter,+ parameters: {+ layout: "centered"+ },+ args: {+ onChange: fn(),+ onClear: undefined+ },+ tags: ["autodocs"]+} satisfies Meta<typeof DateRangeFilter>;++export default meta;+type Story = StoryObj<typeof meta>;++export const Default: Story = {+ parameters: {+ docs: {+ description: {+ story:+ "With no default value the filter starts on Last 1 hour. Last counts back from now; Fixed picks a start and end on the calendar, down to the minute."+ }+ }+ }+};++export const Accents: Story = {+ name: "Example: Accents",+ render: (args) => (+ <div className="flex items-center gap-3">+ {(["primary", "secondary", "av"] as DateRangeFilterAccent[]).map((accent) => (+ <DateRangeFilter key={accent} {...args} accent={accent} />+ ))}+ </div>+ ),+ parameters: {+ docs: {+ description: {+ story:+ "Match the accent to the scope: primary inside a project, secondary at the organization, av in Agent Vault. It colours the selected tab, presets, calendar range and Apply button."+ }+ }+ }+};++export const FixedRange: Story = {+ name: "Example: Fixed Range",+ args: {+ defaultValue: {+ type: DateRangeFilterType.Fixed,+ startDate: atTime(subDays(new Date(), 7), 9),+ endDate: atTime(subDays(new Date(), 5), 17, 30)+ }+ },+ parameters: {+ docs: {+ description: {+ story:+ "A fixed range shows its start and end dates on the trigger. Opening it restores the calendar selection and both times."+ }+ }+ }+};++export const Inactive: Story = {+ name: "Example: Inactive",+ render: (args) => (+ <div className="flex items-center gap-3">+ <DateRangeFilter {...args} isActive={false} />+ <DateRangeFilter {...args} isActive={false} inactiveLabel="Entire Session" accent="av" />+ </div>+ ),+ parameters: {+ docs: {+ description: {+ story:+ "Set isActive to false when no range applies, for example while a quick preset is chosen instead. The trigger then shows inactiveLabel, which defaults to Custom."+ }+ }+ }+};++const ClearableFilter = (args: Story["args"]) => {+ const [range, setRange] = useState<DateRangeFilterResult | null>(null);++ return (+ <div className="flex flex-col items-center gap-3">+ <DateRangeFilter+ {...args}+ onChange={(result) => {+ setRange(result);+ args?.onChange?.(result);+ }}+ onClear={() => {+ setRange(null);+ args?.onClear?.();+ }}+ isActive={Boolean(range)}+ inactiveLabel="Any Time"+ />+ <span className="text-xs text-muted">+ {range+ ? `${range.startDate.toLocaleString()} to ${range.endDate.toLocaleString()}`+ : "No range applied"}+ </span>+ </div>+ );+};++export const Clearable: Story = {+ name: "Example: Clearable",+ args: {+ onClear: fn()+ },+ render: (args) => <ClearableFilter {...args} />,+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.click(canvas.getByRole("button", { name: /Any Time/ }));+ await expect(body.queryByRole("button", { name: "Clear" })).not.toBeInTheDocument();+ await userEvent.click(body.getByRole("button", { name: "Apply" }));+ await expect(args.onChange).toHaveBeenCalledTimes(1);++ await userEvent.click(canvas.getByRole("button", { name: /Last 1h/ }));+ await userEvent.click(body.getByRole("button", { name: "Clear" }));+ await expect(args.onClear).toHaveBeenCalledTimes(1);+ await expect(canvas.getByRole("button", { name: /Any Time/ })).toBeInTheDocument();+ },+ parameters: {+ docs: {+ description: {+ story:+ "Pass onClear to offer a Clear button in the footer. It appears only while a range is applied, and the parent decides what cleared means by flipping isActive."+ }+ }+ }+};++export const WithoutTimezoneToggle: Story = {+ name: "Example: Without Timezone Toggle",+ args: {+ showTimezoneToggle: false,+ defaultValue: {+ type: DateRangeFilterType.Fixed,+ startDate: atTime(subDays(new Date(), 3), 0),+ endDate: atTime(subDays(new Date(), 1), 23, 59)+ }+ },+ parameters: {+ docs: {+ description: {+ story:+ "Hide the Local/UTC toggle when the results are always shown in one timezone. It only ever appears on the Fixed tab."+ }+ }+ }+};++export const Utc: Story = {+ name: "Example: UTC by Default",+ args: {+ defaultIsUtc: true,+ defaultValue: {+ type: DateRangeFilterType.Fixed,+ startDate: atTime(subDays(new Date(), 2), 8),+ endDate: atTime(subDays(new Date(), 2), 18)+ }+ },+ parameters: {+ docs: {+ description: {+ story:+ "defaultIsUtc starts the toggle on UTC. The result passed to onChange carries isUtc so the caller can format timestamps to match."+ }+ }+ }+};++export const EarliestDate: Story = {+ name: "Example: Earliest Date",+ args: {+ earliestDate: subMonths(new Date(), 8)+ },+ parameters: {+ docs: {+ description: {+ story:+ "The calendar reaches back three months by default. Pass earliestDate to move that bound, further back for data kept longer, or forward so days before the data existed can't be picked."+ }+ }+ }+};++export const FixedOnly: Story = {+ name: "Example: Fixed Only",+ args: {+ showRelativeRanges: false,+ earliestDate: subDays(new Date(), 20)+ },+ parameters: {+ docs: {+ description: {+ story:+ "Set showRelativeRanges to false when counting back from now means nothing, such as for data that ended long ago. Only the Fixed tab is shown, and with no default value it starts on the whole span from earliestDate to now."+ }+ }+ }+};++const WithQuickPresetsFilter = (args: Story["args"]) => {+ const [preset, setPreset] = useState("1h");++ return (+ <ButtonGroup>+ <DateRangeQuickPresets+ value={preset}+ onChange={(value, result) => {+ setPreset(value);+ args?.onChange?.(result);+ }}+ />+ <DateRangeFilter+ {...args}+ isActive={!preset}+ onChange={(result) => {+ setPreset("");+ args?.onChange?.(result);+ }}+ />+ </ButtonGroup>+ );+};++export const WithQuickPresets: Story = {+ name: "Example: With Quick Presets",+ render: (args) => <WithQuickPresetsFilter {...args} />,+ parameters: {+ docs: {+ description: {+ story:+ "The Audit Logs layout: quick presets for common windows, with the filter as the Custom option beside them. Choosing a preset makes the filter inactive, and applying a custom range clears the preset."+ }+ }+ }+};++const SessionLogsFilter = ({+ isSessionActive,+ ...args+}: Story["args"] & { isSessionActive: boolean }) => {+ const [range, setRange] = useState<DateRangeFilterResult | null>(null);++ return (+ <DateRangeFilter+ {...args}+ accent="av"+ inactiveLabel="Entire Session"+ showTimezoneToggle={false}+ earliestDate={subDays(new Date(), isSessionActive ? 2 : 120)}+ showRelativeRanges={isSessionActive}+ isActive={Boolean(range)}+ onChange={(result) => {+ setRange(result);+ args?.onChange?.(result);+ }}+ onClear={() => setRange(null)}+ />+ );+};++export const SessionLogs: Story = {+ name: "Example: Session Logs",+ render: (args) => (+ <div className="flex items-center gap-3">+ <SessionLogsFilter {...args} isSessionActive />+ <SessionLogsFilter {...args} isSessionActive={false} />+ </div>+ ),+ parameters: {+ docs: {+ description: {+ story:+ "Agent Vault's session logs: the calendar starts on the day the session was created, Clear goes back to the entire session, and an ended session offers only fixed ranges. The second filter is for a session that ended four months ago, past the default three-month bound."+ }+ }+ }+};++export const InvalidFixedRange: Story = {+ name: "Example: Invalid Fixed Range",+ args: {+ defaultValue: {+ type: DateRangeFilterType.Fixed,+ startDate: atTime(subDays(new Date(), 1), 9),+ endDate: atTime(subDays(new Date(), 1), 17)+ }+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.click(canvas.getByRole("button"));+ const [startTime] =+ canvasElement.ownerDocument.body.querySelectorAll<HTMLInputElement>('input[type="time"]');+ fireEvent.change(startTime, { target: { value: "18:00" } });++ await expect(body.getByText("Start date must be before end date.")).toBeInTheDocument();+ await expect(body.getByRole("button", { name: "Apply" })).toBeDisabled();+ await expect(args.onChange).not.toHaveBeenCalled();+ },+ parameters: {+ docs: {+ description: {+ story:+ "A start at or after the end shows an error under the times and disables Apply, so onChange never receives a backwards range."+ }+ }+ }+};diff --git a/frontend/src/components/v3/platform/DateRangeFilter/DateRangeFilter.tsx b/frontend/src/components/v3/platform/DateRangeFilter/DateRangeFilter.tsxindex a8f9f0c961..056b04703e 100644--- a/frontend/src/components/v3/platform/DateRangeFilter/DateRangeFilter.tsx+++ b/frontend/src/components/v3/platform/DateRangeFilter/DateRangeFilter.tsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useMemo, useState } from "react";import { type DateRange } from "react-day-picker";-import { addDays, addMonths, format, subMonths } from "date-fns";+import { addDays, addMonths, format, max, startOfDay, subMonths } from "date-fns";import { ArrowRight, CalendarIcon } from "lucide-react";import ms from "ms";@@ -59,8 +59,14 @@ type Props = {defaultValue?: DateRangeFilterValue;defaultIsUtc?: boolean;onChange: (value: DateRangeFilterResult) => void;+ onClear?: () => void;accent?: DateRangeFilterAccent;isActive?: boolean;+ inactiveLabel?: string;+ showTimezoneToggle?: boolean;+ earliestDate?: Date;+ showRelativeRanges?: boolean;+ size?: Extract<ButtonProps["size"], "sm" | "md">;className?: string;};@@ -176,20 +182,38 @@ export function DateRangeFilter({defaultValue,defaultIsUtc = false,onChange,+ onClear,accent = "primary",isActive = true,+ inactiveLabel = "Custom",+ showTimezoneToggle = true,+ earliestDate,+ showRelativeRanges = true,+ size = "sm",className}: Props) {- const initialValue = defaultValue ?? { type: DateRangeFilterType.Last, value: "1h" };+ const today = new Date();+ const earliestDay = earliestDate ?? addDays(subMonths(today, MAX_RANGE_MONTHS), 1);+ const modes = showRelativeRanges+ ? [DateRangeFilterType.Last, DateRangeFilterType.Fixed]+ : [DateRangeFilterType.Fixed];+ const initialValue: DateRangeFilterValue =+ defaultValue ??+ (showRelativeRanges+ ? { type: DateRangeFilterType.Last, value: "1h" }+ : { type: DateRangeFilterType.Fixed, startDate: earliestDay, endDate: today });const [appliedValue, setAppliedValue] = useState<DateRangeFilterValue>(initialValue);const [appliedIsUtc, setAppliedIsUtc] = useState(defaultIsUtc);const [isOpen, setIsOpen] = useState(false);- const [mode, setMode] = useState<DateRangeFilterType>(+ const [selectedMode, setMode] = useState<DateRangeFilterType>(initialValue.type === DateRangeFilterType.Fixed? DateRangeFilterType.Fixed: DateRangeFilterType.Last);+ // The tabs can change while mounted, so a hidden Last tab never stays selected.+ const mode = showRelativeRanges ? selectedMode : DateRangeFilterType.Fixed;+// Last mode state — seed from the initial value if it's a Last typeconst initialLastParsed =initialValue.type === DateRangeFilterType.Last@@ -254,9 +278,16 @@ export function DateRangeFilter({setIsOpen(false);};- const today = new Date();+ const handleClear = () => {+ setAppliedValue(initialValue);+ setAppliedIsUtc(defaultIsUtc);+ onClear?.();+ setIsOpen(false);+ };- const calendarDefaultMonth = pendingRange?.from ? pendingRange.from : addMonths(today, -1);+ const calendarDefaultMonth = pendingRange?.from+ ? pendingRange.from+ : max([addMonths(today, -1), earliestDay]);const isInvalidFixedRange = useMemo(() => {if (mode !== DateRangeFilterType.Fixed || !pendingRange?.from || !pendingRange?.to)@@ -292,9 +323,9 @@ export function DateRangeFilter({const renderTrigger = () => {if (!isActive) {return (- <Button variant="outline" size="sm" className={cn("gap-1.5 font-normal", className)}>+ <Button variant="outline" size={size} className={cn("gap-1.5 font-normal", className)}><CalendarIcon className="text-muted-foreground size-3.5 shrink-0" />- Custom+ {inactiveLabel}</Button>);}@@ -303,7 +334,7 @@ export function DateRangeFilter({return (<Buttonvariant="outline"- size="sm"+ size={size}className={cn("gap-1.5 font-normal", accentStyles.selectedChip, className)}><span className="text-xs">{format(appliedValue.startDate, "MMM d, yyyy")}</span>@@ -317,7 +348,7 @@ export function DateRangeFilter({return (<Buttonvariant="outline"- size="sm"+ size={size}className={cn("gap-1.5 font-normal", accentStyles.selectedChip, className)}><CalendarIcon className="text-muted-foreground size-3.5 shrink-0" />@@ -340,7 +371,7 @@ export function DateRangeFilter({<div className="flex">{/* Left sidebar */}<div className="flex w-24 shrink-0 flex-col border-r border-border py-2">- {[DateRangeFilterType.Last, DateRangeFilterType.Fixed].map((m) => (+ {modes.map((m) => (<buttonkey={m}type="button"@@ -459,12 +490,9 @@ export function DateRangeFilter({numberOfMonths={2}showOutsideDays={false}captionLayout="dropdown"- disabled={[- { after: today },- { before: addDays(subMonths(today, MAX_RANGE_MONTHS), 1) }- ]}+ disabled={[{ after: today }, { before: startOfDay(earliestDay) }]}defaultMonth={calendarDefaultMonth}- startMonth={addDays(subMonths(today, MAX_RANGE_MONTHS), 1)}+ startMonth={earliestDay}endMonth={today}className="p-0"classNames={{@@ -513,37 +541,42 @@ export function DateRangeFilter({{/* Footer */}<div className="flex items-center justify-between gap-2 border-t border-border px-4 py-3">- {mode === DateRangeFilterType.Fixed ? (- <div className="flex shrink-0 cursor-pointer items-center gap-2 select-none">- <span- className={cn(- "text-sm transition-colors",- !pendingIsUtc ? "text-foreground" : "text-muted-foreground"- )}- >- Local- </span>- <Toggle- id="date-range-utc-toggle"- checked={pendingIsUtc}- onCheckedChange={setPendingIsUtc}- size="sm"- className={accentStyles.switchChecked}- />- {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}- <label- htmlFor="date-range-utc-toggle"- className={cn(- "cursor-pointer text-sm transition-colors",- pendingIsUtc ? "text-foreground" : "text-muted-foreground"- )}- >- UTC- </label>- </div>- ) : (- <div />- )}+ <div className="flex items-center gap-4">+ {onClear && isActive && (+ <Button variant="ghost" size="sm" onClick={handleClear}>+ Clear+ </Button>+ )}+ {mode === DateRangeFilterType.Fixed && showTimezoneToggle && (+ <div className="flex shrink-0 cursor-pointer items-center gap-2 select-none">+ <span+ className={cn(+ "text-sm transition-colors",+ !pendingIsUtc ? "text-foreground" : "text-muted-foreground"+ )}+ >+ Local+ </span>+ <Toggle+ id="date-range-utc-toggle"+ checked={pendingIsUtc}+ onCheckedChange={setPendingIsUtc}+ size="sm"+ className={accentStyles.switchChecked}+ />+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}+ <label+ htmlFor="date-range-utc-toggle"+ className={cn(+ "cursor-pointer text-sm transition-colors",+ pendingIsUtc ? "text-foreground" : "text-muted-foreground"+ )}+ >+ UTC+ </label>+ </div>+ )}+ </div><div className="flex items-center gap-2"><Button variant="ghost" size="sm" onClick={() => setIsOpen(false)}>Canceldiff --git a/frontend/src/components/v3/platform/OverflowBadgeList/OverflowBadgeList.tsx b/frontend/src/components/v3/platform/OverflowBadgeList/OverflowBadgeList.tsxindex 5a9049920a..96e3aef56b 100644--- a/frontend/src/components/v3/platform/OverflowBadgeList/OverflowBadgeList.tsx+++ b/frontend/src/components/v3/platform/OverflowBadgeList/OverflowBadgeList.tsx@@ -156,7 +156,13 @@ export const OverflowBadgeList = <T,>({}}>{linkProps ? (- <Link {...linkProps}>+ <Link+ {...linkProps}+ onClick={(event) => {+ event.stopPropagation();+ linkProps.onClick?.(event);+ }}+ >{icon}<span>{label}</span></Link>diff --git a/frontend/src/helpers/agentVaultHostPattern.ts b/frontend/src/helpers/agentVaultHostPattern.tsindex d426963a1e..d4fc086603 100644--- a/frontend/src/helpers/agentVaultHostPattern.ts+++ b/frontend/src/helpers/agentVaultHostPattern.ts@@ -21,7 +21,7 @@ const hostKey = (raw: string): string | null => {/*** A partial pre-check, so a malformed host is caught on the field that holds it rather than bounced- * back from a submit. agent-vault-host-pattern.ts stays the grammar of record.+ * back from a submit. agent-vault-host-pattern-fns.ts stays the grammar of record.** `existing` must never contain the value being checked: the duplicate is reported on the second* occurrence, matching the server.diff --git a/frontend/src/helpers/agentVaultPathPrefix.ts b/frontend/src/helpers/agentVaultPathPrefix.tsindex 1c46b51756..c34914d7d5 100644--- a/frontend/src/helpers/agentVaultPathPrefix.ts+++ b/frontend/src/helpers/agentVaultPathPrefix.ts@@ -1,6 +1,6 @@import { z } from "zod";-// Mirrors backend/src/ee/services/agent-vault/agent-vault-path-prefix.ts, which stays the grammar of record.+// Mirrors backend/src/ee/services/agent-vault/agent-vault-path-prefix-schemas.ts, which stays the grammar of record.// Kept here so a bad prefix is caught before the request rather than coming back as a server error.const PATH_PREFIX_RE = /^\/[A-Za-z0-9\-._~$&+/:=@]*$/;diff --git a/frontend/src/helpers/agentVaultSessionLogs.ts b/frontend/src/helpers/agentVaultSessionLogs.tsnew file mode 100644index 0000000000..4ba76846a0--- /dev/null+++ b/frontend/src/helpers/agentVaultSessionLogs.ts@@ -0,0 +1,10 @@+import { TAgentVaultSessionLogSettings } from "@app/hooks/api/agentVault/types";+import { SubscriptionPlan } from "@app/hooks/api/subscriptions/types";++export const areAgentVaultSessionLogsOn = (settings: TAgentVaultSessionLogSettings) =>+ Boolean(settings.enabled && settings.appConnectionId && settings.bucket && settings.region);++export const isAgentVaultSessionLogPlanLapsed = (+ settings: TAgentVaultSessionLogSettings,+ subscription: Pick<SubscriptionPlan, "agentVaultByoS3">+) => Boolean(settings.bucket) && !subscription.agentVaultByoS3;diff --git a/frontend/src/helpers/userTablePreferences.ts b/frontend/src/helpers/userTablePreferences.tsindex a23438746c..2cf654370a 100644--- a/frontend/src/helpers/userTablePreferences.ts+++ b/frontend/src/helpers/userTablePreferences.ts@@ -1,7 +1,8 @@const TABLE_PREFERENCES_KEY = "userTablePreferences";export enum PreferenceKey {- PerPage = "perPage"+ PerPage = "perPage",+ SessionScope = "sessionScope"}interface TableSpecificPreferences {diff --git a/frontend/src/hooks/api/agentVault/enums.ts b/frontend/src/hooks/api/agentVault/enums.tsindex c4e620051d..4f35bcc08f 100644--- a/frontend/src/hooks/api/agentVault/enums.ts+++ b/frontend/src/hooks/api/agentVault/enums.ts@@ -42,3 +42,10 @@ export enum AgentVaultSessionScope {Mine = "mine",All = "all"}++export enum AgentVaultSessionLogDecision {+ Brokered = "brokered",+ Passthrough = "passthrough",+ Blocked = "blocked",+ Error = "error"+}diff --git a/frontend/src/hooks/api/agentVault/index.ts b/frontend/src/hooks/api/agentVault/index.tsindex f49a872a5a..6b91c358d2 100644--- a/frontend/src/hooks/api/agentVault/index.ts+++ b/frontend/src/hooks/api/agentVault/index.ts@@ -2,3 +2,4 @@ export * from "./enums";export * from "./mutations";export * from "./queries";export * from "./types";+export * from "./useAgentVaultSessionLogTimeline";diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsxindex 16e96f524b..6c7153019a 100644--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@ -18,12 +18,14 @@ import {TAgentVaultProxy,TAgentVaultProxySettingsDTO,TAgentVaultService,+ TAgentVaultSessionLogSettings,TAgentVaultWrittenMember,TCreateAgentVaultAccessBundleDTO,TCreateAgentVaultServiceDTO,TCreateAgentVaultSessionDTO,TUpdateAgentVaultAccessBundleDTO,- TUpdateAgentVaultServiceDTO+ TUpdateAgentVaultServiceDTO,+ TUpdateAgentVaultSessionLogSettingsDTO} from "./types";export const useCreateAgentVaultAccessBundle = () => {@@ -359,3 +361,29 @@ export const useRevokeAgentVaultMembers = () => {onSuccess: () => invalidateMembers(queryClient, currentOrg.id)});};++export const useUpdateAgentVaultSessionLogSettings = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async (params: TUpdateAgentVaultSessionLogSettingsDTO) => {+ const { data } = await apiRequest.patch<{ settings: TAgentVaultSessionLogSettings }>(+ "/api/v1/agent-vault/settings/session-logs",+ params+ );+ return data.settings;+ },+ onSuccess: (settings) => {+ queryClient.setQueryData(agentVaultKeys.sessionLogSettings(currentOrg.id), settings);+ // Reset, not invalidate: the cached result may be for the previous bucket.+ queryClient.resetQueries({+ queryKey: agentVaultKeys.sessionLogCorsProbe(currentOrg.id)+ });+ queryClient.invalidateQueries({+ queryKey: agentVaultKeys.sessionLogHealth(currentOrg.id)+ });+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.sessions(currentOrg.id) });+ }+ });+};diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsxindex 7fdfb949d3..0d33f9163e 100644--- a/frontend/src/hooks/api/agentVault/queries.tsx+++ b/frontend/src/hooks/api/agentVault/queries.tsx@@ -1,18 +1,32 @@-import { useQuery } from "@tanstack/react-query";+import { useRef } from "react";+import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";import { useOrganization } from "@app/context";import { AgentVaultMemberType } from "./enums";+import {+ createSessionLogChunkCache,+ decryptSessionLogPage,+ mergeSessionLogPages,+ TAgentVaultSessionLogChunkCache+} from "./sessionLogDecrypt";import {TAgentVaultAccessBundleDetails,TAgentVaultAccessBundleListItem,+ TAgentVaultDecryptedSessionLogPage,TAgentVaultMember,TAgentVaultProductActor,TAgentVaultProductMember,TAgentVaultProductMemberOf,TAgentVaultProxy,TAgentVaultSession,+ TAgentVaultSessionLogCorsProbe,+ TAgentVaultSessionLogHealth,+ TAgentVaultSessionLogHistoryPage,+ TAgentVaultSessionLogReadCheck,+ TAgentVaultSessionLogSettings,+ TAgentVaultSessionLogTailPage,TListAgentVaultAccessBundlesDTO,TListAgentVaultMembersDTO,TListAgentVaultProxiesDTO,@@ -24,6 +38,14 @@ export const fetchAgentVaultProjectId = async () => {return data.projectId;};+const SESSION_LOG_PAGE_RECORDS = 200;++const SESSION_LOG_LIVE_RECORDS = 1000;++const SESSION_LOG_LIVE_MAX_READS = 10;++export const AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS = 15_000;+// 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.export const agentVaultKeys = {@@ -34,6 +56,8 @@ export const agentVaultKeys = {// sessions() is the invalidation prefix; folding the parameters in would put an `undefined` in it,// which prefix-matches nothing.sessions: (orgId: string) => [...agentVaultKeys.all(orgId), "sessions"] as const,+ session: (orgId: string, sessionId: string) =>+ [...agentVaultKeys.sessions(orgId), "detail", sessionId] as const,sessionList: (orgId: string, params?: TListAgentVaultSessionsDTO) =>[...agentVaultKeys.sessions(orgId), params] as const,accessBundleList: (orgId: string, params?: TListAgentVaultAccessBundlesDTO) =>@@ -60,7 +84,17 @@ export const agentVaultKeys = {// Nested under members() so adding a member invalidates the candidate list too.availableMembers: (orgId: string) => [...agentVaultKeys.members(orgId), "available"] as const,availableMemberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>- [...agentVaultKeys.availableMembers(orgId), params] as const+ [...agentVaultKeys.availableMembers(orgId), params] as const,+ sessionLogSettings: (orgId: string) =>+ [...agentVaultKeys.all(orgId), "settings", "session-logs"] as const,+ sessionLogHealth: (orgId: string) =>+ [...agentVaultKeys.sessionLogSettings(orgId), "health"] as const,+ sessionLogCorsProbe: (orgId: string) =>+ [...agentVaultKeys.sessionLogSettings(orgId), "cors-probe"] as const,+ sessionLogs: (orgId: string, sessionId: string, range?: { from?: string; to?: string }) =>+ [...agentVaultKeys.sessions(orgId), sessionId, "logs", range ?? {}] as const,+ sessionLogsLive: (orgId: string, sessionId: string, range?: { from?: string; to?: string }) =>+ [...agentVaultKeys.sessions(orgId), sessionId, "logs-live", range ?? {}] as const};export const useListAgentVaultMembers = <T extends AgentVaultMemberType = AgentVaultMemberType>(@@ -189,10 +223,13 @@ export const useListAgentVaultSessions = (params?: TListAgentVaultSessionsDTO) =return useQuery({queryKey: agentVaultKeys.sessionList(currentOrg.id, params),queryFn: async () => {+ const { statuses, ...rest } = params ?? {};const { data } = await apiRequest.get<{sessions: TAgentVaultSession[];totalCount: number;- }>("/api/v1/agent-vault/sessions", { params });+ }>("/api/v1/agent-vault/sessions", {+ params: { ...rest, status: statuses?.length ? statuses.join(",") : undefined }+ });return data;},refetchInterval: 30_000,@@ -216,3 +253,175 @@ export const useListAgentVaultProxies = (params: TListAgentVaultProxiesDTO = {})placeholderData: (prev) => prev});};++export const useGetAgentVaultSessionLogSettings = (enabled = true) => {+ const { currentOrg } = useOrganization();++ return useQuery({+ queryKey: agentVaultKeys.sessionLogSettings(currentOrg.id),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ settings: TAgentVaultSessionLogSettings }>(+ "/api/v1/agent-vault/settings/session-logs"+ );+ return data.settings;+ },+ enabled+ });+};++export const useGetAgentVaultSessionLogHealth = (enabled = true) => {+ const { currentOrg } = useOrganization();++ return useQuery({+ queryKey: agentVaultKeys.sessionLogHealth(currentOrg.id),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ health: TAgentVaultSessionLogHealth }>(+ "/api/v1/agent-vault/settings/session-logs/health"+ );+ return data.health;+ },+ enabled+ });+};++export const fetchAgentVaultSessionLogReadAccess =+ async (): Promise<TAgentVaultSessionLogReadCheck | null> => {+ const { data } = await apiRequest.get<{ probe: TAgentVaultSessionLogCorsProbe }>(+ "/api/v1/agent-vault/settings/session-logs/cors-probe"+ );+ if (!data.probe) return null;+ const { host, origin } = new URL(data.probe.url);+ let isHostBlocked = false;+ const onViolation = (event: SecurityPolicyViolationEvent) => {+ if (event.effectiveDirective === "connect-src" && event.blockedURI.startsWith(origin)) {+ isHostBlocked = true;+ }+ };+ document.addEventListener("securitypolicyviolation", onViolation);+ // The probed object never exists. S3 adds CORS headers to its 404 and to a 403 alike, so fetch+ // rejects only when the rule is missing or this page's CSP blocks the host, and a 403 means the+ // connection may not read the bucket.+ try {+ const res = await fetch(data.probe.url, { mode: "cors", credentials: "omit" });+ return { status: res.status === 403 ? "access-denied" : "readable", host };+ } catch {+ // The violation event is queued as a task, so it can land after fetch has already rejected.+ await new Promise((resolve) => {+ setTimeout(resolve, 0);+ });+ return { status: isHostBlocked ? "host-blocked" : "cors-missing", host };+ } finally {+ document.removeEventListener("securitypolicyviolation", onViolation);+ }+ };++export const useGetAgentVaultSessionLogCorsProbe = (enabled = true) => {+ const { currentOrg } = useOrganization();++ return useQuery({+ queryKey: agentVaultKeys.sessionLogCorsProbe(currentOrg.id),+ queryFn: fetchAgentVaultSessionLogReadAccess,+ enabled,+ retry: false+ });+};++export const useGetAgentVaultSession = (sessionId: string | undefined, enabled = true) => {+ const { currentOrg } = useOrganization();++ return useQuery({+ queryKey: agentVaultKeys.session(currentOrg.id, sessionId ?? ""),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ session: TAgentVaultSession }>(+ `/api/v1/agent-vault/sessions/${sessionId}`+ );+ return data.session;+ },+ enabled: enabled && Boolean(sessionId),+ refetchInterval: 30_000,+ retry: false+ });+};++export const useGetAgentVaultSessionLogs = (+ sessionId: string | undefined,+ {+ enabled = true,+ isLive = false,+ from,+ to+ }: { enabled?: boolean; isLive?: boolean; from?: Date; to?: Date } = {}+) => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();++ const range = { from: from?.toISOString(), to: to?.toISOString() };+ const url = `/api/v1/agent-vault/sessions/${sessionId}/logs`;+ const tailUrl = `${url}/tail`;++ // Reset during render so neither query fetches a new session into the old one's cache.+ const chunkCache = useRef<TAgentVaultSessionLogChunkCache | null>(null);+ if (!chunkCache.current || chunkCache.current.sessionId !== sessionId) {+ chunkCache.current = createSessionLogChunkCache(sessionId ?? "");+ }++ const history = useInfiniteQuery({+ queryKey: agentVaultKeys.sessionLogs(currentOrg.id, sessionId ?? "", range),+ enabled: enabled && Boolean(sessionId),+ initialPageParam: undefined as string | undefined,+ queryFn: async ({ pageParam, signal }) => {+ const cache = chunkCache.current as TAgentVaultSessionLogChunkCache;+ 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+ });+ return decryptSessionLogPage(data, cache, signal);+ },+ getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,+ placeholderData: (prev, prevQuery) =>+ sessionId && prevQuery?.queryKey.includes(sessionId) ? prev : undefined,+ staleTime: 0,+ // Pages hold decrypted plaintext, so drop them as soon as nothing observes them.+ gcTime: 0+ });++ const liveFrom = history.isPlaceholderData ? undefined : history.data?.pages[0]?.liveCursor;+ const isRecordable = 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),+ 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);+ }+ return arrived as TAgentVaultDecryptedSessionLogPage<TAgentVaultSessionLogTailPage>;+ },+ refetchInterval: AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS,+ staleTime: 0,+ gcTime: 0+ });++ return { history, live, arrived: live.data };+};diff --git a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.tsnew file mode 100644index 0000000000..01c6520d15--- /dev/null+++ b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts@@ -0,0 +1,182 @@+import assert from "node:assert/strict";+import { afterEach, describe, it, vi } from "vitest";++import {+ createSessionLogChunkCache,+ decryptSessionLogPage,+ parseSessionLogRecords,+ recordsMatchChunk+} from "./sessionLogDecrypt";+import { TAgentVaultSessionLogPage } from "./types";++const record = {+ ts: "2026-09-23T10:00:00.000Z",+ seq: 0,+ proxyId: "proxy-1",+ method: "GET",+ host: "api.github.com",+ port: "443",+ path: "/",+ status: 200,+ decision: "passthrough",+ service: null,+ accessBundle: null+};++describe("parseSessionLogRecords", () => {+ it("accepts records in the shape the proxy writes", () => {+ assert.deepEqual(parseSessionLogRecords([record]), [record]);+ });++ it("refuses a record whose host is not a string, which search would throw on", () => {+ assert.equal(parseSessionLogRecords([record, { ...record, host: 42 }]), null);+ });++ it("refuses a record whose timestamp is not a date, which the table would throw on", () => {+ assert.equal(parseSessionLogRecords([{ ...record, ts: "nope" }]), null);+ });++ it("refuses anything that is not an array of records", () => {+ assert.equal(parseSessionLogRecords({ records: [record] }), null);+ });+});++describe("recordsMatchChunk", () => {+ const chunk = { proxyId: "proxy-1", recordCount: 2, firstSeq: 10, lastSeq: 12 };+ const records = parseSessionLogRecords([+ { ...record, seq: 10 },+ { ...record, seq: 12 }+ ])!;++ it("accepts records that match the batch they came in, gaps in the sequence included", () => {+ assert.equal(recordsMatchChunk(records, chunk), true);+ });++ it("refuses a record that claims another proxy", () => {+ assert.equal(+ recordsMatchChunk([records[0], { ...records[1], proxyId: "proxy-2" }], chunk),+ 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", () => {+ const chunkId = "01a0a9c5-231d-7abc-8def-0123456789ab";+ const page: TAgentVaultSessionLogPage = {+ sessionLogs: {+ enabled: true,+ isRecordable: true,+ sessionKey: btoa("\0".repeat(32)),+ storageUnavailable: 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: "2026-09-23T10:00:05.000Z"+ }+ ]+ };++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ const openTwice = async (download: () => Promise<Response>) => {+ const fetchMock = vi.fn(download);+ vi.stubGlobal("fetch", fetchMock);+ 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 };+ };++ it("tells an object the bucket no longer has apart from a blocked request, and tries it again", async () => {+ assert.deepEqual(await openTwice(async () => new Response(null, { status: 404 })), {+ reason: "missing",+ downloads: 2+ });+ });++ it("reports a download the bucket refused, and tries it again", async () => {+ assert.deepEqual(await openTwice(async () => new Response(null, { status: 403 })), {+ reason: "refused",+ downloads: 2+ });+ });++ it("keeps a request the browser could not make as a failed download, and tries it again", async () => {+ assert.deepEqual(+ await openTwice(async () => {+ throw new TypeError("Failed to fetch");+ }),+ { reason: "fetch", downloads: 2 }+ );+ });++ it("tells an object changed after upload apart from one that fails to decrypt, and doesn't download it again", async () => {+ assert.deepEqual(await openTwice(async () => new Response(new Uint8Array(64))), {+ reason: "altered",+ downloads: 1+ });+ });++ // The same vector Go's TestSealMatchesTheBrowserVector seals.+ 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 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 result = await decryptSessionLogPage(vectorPage, createSessionLogChunkCache("sess-1"));++ assert.equal(result.decrypted[chunkId].gap, null);+ assert.equal(result.decrypted[chunkId].records[0].path, "/zen");+ });+});diff --git a/frontend/src/hooks/api/agentVault/sessionLogDecrypt.ts b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.tsnew file mode 100644index 0000000000..1c1210e7bc--- /dev/null+++ b/frontend/src/hooks/api/agentVault/sessionLogDecrypt.ts@@ -0,0 +1,239 @@+import { z } from "zod";++import {+ TAgentVaultDecryptedChunk,+ TAgentVaultDecryptedSessionLogPage,+ TAgentVaultSessionLogChunk,+ TAgentVaultSessionLogGapReason,+ TAgentVaultSessionLogPage,+ TAgentVaultSessionLogRecord+} from "./types";++const CHUNK_DOWNLOAD_TIMEOUT_MS = 60_000;++const AAD_VERSION = "v1";++const base64ToBytes = (value: string) => {+ const binary = atob(value);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);+ return bytes;+};++// Must byte-match the AAD the Go proxy seals each chunk with.+const buildAad = async (sessionId: string, chunkId: string) =>+ crypto.subtle.digest(+ "SHA-256",+ new TextEncoder().encode(`${sessionId}|${chunkId}|${AAD_VERSION}`)+ );++const SessionLogRecordsSchema = z.array(+ z.object({+ ts: z.string().refine((value) => !Number.isNaN(Date.parse(value))),+ seq: z.number().int().nonnegative(),+ proxyId: z.string(),+ method: z.string(),+ host: z.string(),+ port: z.string(),+ path: z.string(),+ status: z.number().int(),+ decision: z.string(),+ service: z.string().nullable(),+ accessBundle: z.string().nullable()+ })+);++export const parseSessionLogRecords = (json: unknown): TAgentVaultSessionLogRecord[] | null => {+ const parsed = SessionLogRecordsSchema.safeParse(json);+ return parsed.success ? (parsed.data as TAgentVaultSessionLogRecord[]) : null;+};++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+ );++const gapFor = (+ chunk: TAgentVaultSessionLogChunk,+ reason: TAgentVaultSessionLogGapReason+): TAgentVaultDecryptedChunk => ({+ records: [],+ gap: {+ chunkId: chunk.chunkId,+ proxyId: chunk.proxyId,+ proxyName: chunk.proxyName,+ startedAt: chunk.startedAt,+ reason,+ recordCount: chunk.recordCount+ },+ arrivedAt: null+});++const isRetryableSessionLogGap = (reason?: TAgentVaultSessionLogGapReason) =>+ reason === "fetch" || reason === "missing" || reason === "refused";++export const isRetryableResult = (result: TAgentVaultDecryptedChunk) =>+ isRetryableSessionLogGap(result.gap?.reason);++const withTimeout = (signal: AbortSignal | undefined, ms: number) => {+ const controller = new AbortController();+ const abort = () => controller.abort();+ const timer = setTimeout(abort, ms);+ if (signal?.aborted) abort();+ signal?.addEventListener("abort", abort, { once: true });+ return {+ signal: controller.signal,+ clear: () => {+ clearTimeout(timer);+ signal?.removeEventListener("abort", abort);+ }+ };+};++const openChunk = async (+ chunk: TAgentVaultSessionLogChunk,+ key: CryptoKey,+ sessionId: string,+ signal?: AbortSignal+): Promise<TAgentVaultDecryptedChunk> => {+ if (!chunk.presignedGetUrl) return gapFor(chunk, "repointed");++ const download = withTimeout(signal, CHUNK_DOWNLOAD_TIMEOUT_MS);+ let body: ArrayBuffer;+ try {+ const res = await fetch(chunk.presignedGetUrl, {+ credentials: "omit",+ signal: download.signal+ });+ if (!res.ok) return gapFor(chunk, res.status === 404 ? "missing" : "refused");+ body = await res.arrayBuffer();+ } catch (error) {+ if (signal?.aborted) throw error;+ return gapFor(chunk, "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");+ }++ let plaintext: ArrayBuffer;+ try {+ plaintext = await crypto.subtle.decrypt(+ {+ name: "AES-GCM",+ iv: base64ToBytes(chunk.iv),+ additionalData: await buildAad(sessionId, chunk.chunkId)+ },+ key,+ body+ );+ } catch {+ return gapFor(chunk, "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");+ return {+ records,+ gap: null,+ arrivedAt: null+ };+ } catch {+ return gapFor(chunk, "json");+ }+};++export const createSessionLogChunkCache = (sessionId: string) => {+ let isSettled = false;+ return {+ sessionId,+ keys: new Map<string, Promise<CryptoKey>>(),+ chunks: new Map<string, TAgentVaultDecryptedChunk>(),+ isSettled: () => isSettled,+ settle: () => {+ isSettled = true;+ }+ };+};++export type TAgentVaultSessionLogChunkCache = ReturnType<typeof createSessionLogChunkCache>;++export const decryptSessionLogPage = async <P extends TAgentVaultSessionLogPage>(+ page: P,+ cache: TAgentVaultSessionLogChunkCache,+ signal?: AbortSignal+): Promise<TAgentVaultDecryptedSessionLogPage<P>> => {+ const decrypted: Record<string, TAgentVaultDecryptedChunk> = {};+ const { sessionKey } = page.sessionLogs;+ 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();+ return { ...page, decrypted };+ }++ let keyPromise = cache.keys.get(sessionKey);+ if (!keyPromise) {+ keyPromise = (async () =>+ crypto.subtle.importKey("raw", base64ToBytes(sessionKey), "AES-GCM", false, ["decrypt"]))();+ cache.keys.set(sessionKey, keyPromise);+ }+ const key = await keyPromise.catch(() => null);+ const opened: string[] = [];++ await Promise.all(+ page.chunks.map(async (chunk) => {+ const known = cache.chunks.get(chunk.chunkId);+ if (known) {+ decrypted[chunk.chunkId] = 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 (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);+ });+ }+ cache.settle();++ return { ...page, decrypted };+};++export const mergeSessionLogPages = <P extends TAgentVaultSessionLogPage>(+ previous: TAgentVaultDecryptedSessionLogPage<P> | undefined,+ page: TAgentVaultDecryptedSessionLogPage<P>+): TAgentVaultDecryptedSessionLogPage<P> => {+ if (!previous) return page;+ const reread = new Set(page.chunks.map((chunk) => chunk.chunkId));+ return {+ ...page,+ chunks: [...previous.chunks.filter((chunk) => !reread.has(chunk.chunkId)), ...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 b9815e5a44..202e76e091 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -2,6 +2,7 @@ import {AgentVaultCredentialType,AgentVaultHttpMethod,AgentVaultMemberType,+ AgentVaultSessionLogDecision,AgentVaultSessionScope,AgentVaultSessionStatus,AgentVaultSubstitutionSurface,@@ -183,17 +184,23 @@ export type TAgentVaultSessionAccessBundle = {position: number;};+export type TAgentVaultSessionActor =+ | (Omit<Extract<TAgentVaultActor, { type: AgentVaultMemberType.User }>, "id"> & {+ id: string | null;+ })+ | (Omit<Extract<TAgentVaultActor, { type: AgentVaultMemberType.MachineIdentity }>, "id"> & {+ id: string | null;+ });+export type TAgentVaultSession = {id: string;- userId: string | null;- identityId: string | null;- actorName: string;- actorEmail: string | null;+ actor: TAgentVaultSessionActor;status: AgentVaultSessionStatus;expiresAt: string | null;revokedAt: string | null;createdAt: string;accessBundles: TAgentVaultSessionAccessBundle[];+ recentSessionLogCounts: { recordedCount: number; droppedCount: number };};export type TAgentVaultMintedSession = {@@ -224,7 +231,7 @@ export type TAgentVaultEnrollment = {export type TListAgentVaultSessionsDTO = {scope?: AgentVaultSessionScope;- status?: AgentVaultSessionStatus;+ statuses?: AgentVaultSessionStatus[];limit?: number;offset?: number;search?: string;@@ -279,3 +286,135 @@ export type TAgentVaultProxySettingsDTO = {allowedHosts?: string | null;pollInterval?: number;};++export type TAgentVaultSessionLogSettings = {+ enabled: boolean;+ appConnectionId: string | null;+ bucket: string | null;+ region: string | null;+ keyPrefix: string | null;+};++export type TAgentVaultSessionLogHealth = {+ isStorageFull: boolean;+ connectionError: string | null;+};++export type TAgentVaultSessionLogCorsProbe = {+ url: string;+ expiresInSeconds: number;+} | null;++export type TAgentVaultSessionLogReadAccess =+ | "readable"+ | "cors-missing"+ | "access-denied"+ | "host-blocked";++export type TAgentVaultSessionLogReadCheck = {+ status: TAgentVaultSessionLogReadAccess;+ host: string;+};++export type TUpdateAgentVaultSessionLogSettingsDTO = {+ enabled?: boolean;+ appConnectionId?: string | null;+ bucket?: string;+ region?: string;+ keyPrefix?: string;+};++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;+};++export type TAgentVaultSessionLog = {+ enabled: boolean;+ isRecordable: boolean;+ sessionKey: string | null;+ storageUnavailable: {+ reason: "no-connection" | "connection-unusable";+ message: string | null;+ } | null;+};++export type TAgentVaultSessionLogPage = {+ sessionLogs: TAgentVaultSessionLog;+ chunks: TAgentVaultSessionLogChunk[];+};++export type TAgentVaultSessionLogHistoryPage = TAgentVaultSessionLogPage & {+ nextCursor: string | null;+ liveCursor: string;+};++export type TAgentVaultSessionLogTailPage = TAgentVaultSessionLogPage & {+ nextCursor: string;+ hasMore: boolean;+};++export type TAgentVaultSessionLogRecord = {+ ts: string;+ seq: number;+ proxyId: string;+ method: string;+ host: string;+ port: string;+ path: string;+ status: number;+ decision: AgentVaultSessionLogDecision;+ service: string | null;+ accessBundle: string | null;+};++export type TAgentVaultSessionLogGapReason =+ | "fetch"+ | "missing"+ | "refused"+ | "size"+ | "altered"+ | "gcm"+ | "json"+ | "mismatch"+ | "repointed";++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;+};++export type TAgentVaultDecryptedChunk = {+ records: TAgentVaultSessionLogRecord[];+ gap: TAgentVaultSessionLogGap | null;+ arrivedAt: number | null;+};++export type TAgentVaultDecryptedSessionLogPage<+ P extends TAgentVaultSessionLogPage = TAgentVaultSessionLogPage+> = P & {+ decrypted: Record<string, TAgentVaultDecryptedChunk>;+};diff --git a/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.test.ts b/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.test.tsnew file mode 100644index 0000000000..a9e1c92a92--- /dev/null+++ b/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.test.ts@@ -0,0 +1,103 @@+import assert from "node:assert/strict";+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 chunkId = "01a0a9c5-231d-7abc-8def-0123456789ab";++const record = {+ ts: "2026-09-29T09:59:59.000Z",+ seq: 0,+ proxyId: "proxy-1",+ method: "GET",+ host: "api.github.com",+ port: "443",+ path: "/",+ status: 200,+ decision: "passthrough",+ service: null,+ accessBundle: null+} as TAgentVaultDecryptedChunk["records"][number];++const pageWith = (result: TAgentVaultDecryptedChunk): TAgentVaultDecryptedSessionLogPage => ({+ sessionLogs: { enabled: true, isRecordable: true, sessionKey: null, storageUnavailable: 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()+ }+ ],+ decrypted: { [chunkId]: result }+});++const missing: TAgentVaultDecryptedChunk = {+ records: [],+ gap: {+ chunkId,+ proxyId: "proxy-1",+ proxyName: "proxy",+ startedAt: record.ts,+ reason: "missing",+ recordCount: 1+ },+ arrivedAt: null+};++describe("buildSessionLogTimeline", () => {+ 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);+ 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);+ assert.deepEqual(+ timeline.gaps.map((gap) => gap.reason),+ ["missing"]+ );+ assert.equal(timeline.hasUploadingChunks, false);+ });++ 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+ );+ assert.equal(timeline.gaps.length, 1);+ assert.equal(timeline.hasUploadingChunks, false);+ });++ it("never holds back a chunk that downloaded", () => {+ const timeline = buildSessionLogTimeline(+ [pageWith({ records: [record], gap: null, arrivedAt: null })],+ createdAt + 30_000+ );+ assert.equal(timeline.records.length, 1);+ assert.equal(timeline.hasUploadingChunks, false);+ });++ 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+ );+ assert.equal(timeline.records.length, 1);+ assert.deepEqual(timeline.gaps, []);+ assert.equal(timeline.hasUploadingChunks, false);+ });+});diff --git a/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.ts b/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.tsnew file mode 100644index 0000000000..1bd6b675bb--- /dev/null+++ b/frontend/src/hooks/api/agentVault/useAgentVaultSessionLogTimeline.ts@@ -0,0 +1,102 @@+import { useMemo } from "react";++import { isRetryableResult } from "./sessionLogDecrypt";+import {+ TAgentVaultDecryptedChunk,+ TAgentVaultDecryptedSessionLogPage,+ TAgentVaultSessionLogDrop,+ TAgentVaultSessionLogGap,+ TAgentVaultSessionLogRecord+} from "./types";++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[];+ gaps: TAgentVaultSessionLogGap[];+ drops: TAgentVaultSessionLogDrop[];+ arrivals: Map<string, number>;+ isTruncated: boolean;+ isOverByteBudget: boolean;+ hasUploadingChunks: boolean;+};++export const buildSessionLogTimeline = (+ pages: TAgentVaultDecryptedSessionLogPage[] | undefined,+ now: number+): 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];+ 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);+ 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));+ })+ );++ const records: TAgentVaultSessionLogRecord[] = [];+ const gaps: TAgentVaultSessionLogGap[] = [];+ const arrivals = new Map<string, number>();+ let loadedBytes = 0;+ let hasUploadingChunks = false;++ opened.forEach((result, chunkId) => {+ records.push(...result.records);+ if (!result.gap) loadedBytes += openedBytes.get(chunkId) ?? 0;+ if (result.arrivedAt !== null) {+ const { arrivedAt } = result;+ result.records.forEach((record) => arrivals.set(sessionLogRecordKey(record), arrivedAt));+ }+ const isUploading =+ result.gap?.reason === "missing" &&+ now < (openedAt.get(chunkId) ?? 0) + CHUNK_UPLOAD_GRACE_MS;+ if (isUploading) hasUploadingChunks = true;+ else if (result.gap) gaps.push(result.gap);+ });++ const times = new Map<TAgentVaultSessionLogRecord, number>();+ records.forEach((record) => times.set(record, Date.parse(record.ts)));+ records.sort((a, b) => {+ const byTime = (times.get(b) as number) - (times.get(a) as number);+ if (byTime !== 0) return byTime;+ if (a.proxyId !== b.proxyId) return a.proxyId < b.proxyId ? -1 : 1;+ return b.seq - a.seq;+ });++ const isOverByteBudget = loadedBytes >= AGENT_VAULT_SESSION_LOG_MAX_LOADED_BYTES;+ return {+ records: records.slice(0, AGENT_VAULT_SESSION_LOG_MAX_RECORDS),+ gaps,+ drops: [...dropsByChunk.values()],+ arrivals,+ isTruncated: records.length > AGENT_VAULT_SESSION_LOG_MAX_RECORDS || isOverByteBudget,+ isOverByteBudget,+ hasUploadingChunks+ };+};++export const useAgentVaultSessionLogTimeline = (+ pages: TAgentVaultDecryptedSessionLogPage[] | undefined,+ now: number+): TAgentVaultSessionLogTimeline =>+ useMemo(() => buildSessionLogTimeline(pages, now), [pages, now]);diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex fa7793a6c0..a4039f320d 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -481,7 +481,8 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.AGENT_VAULT_PROXY_ENROLL]: "Enroll proxy",[EventType.AGENT_VAULT_PROXY_UPDATE]: "Update proxy",[EventType.AGENT_VAULT_PROXY_REVOKE]: "Revoke proxy access",- [EventType.AGENT_VAULT_PROXY_DELETE]: "Delete proxy"+ [EventType.AGENT_VAULT_PROXY_DELETE]: "Delete proxy",+ [EventType.AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE]: "Update session log settings"};export const userAgentTypeToNameMap: { [K in UserAgentType]: string } = {@@ -554,6 +555,7 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {EventType.AGENT_VAULT_PROXY_ENROLL,EventType.AGENT_VAULT_PROXY_UPDATE,EventType.AGENT_VAULT_PROXY_REVOKE,- EventType.AGENT_VAULT_PROXY_DELETE+ EventType.AGENT_VAULT_PROXY_DELETE,+ EventType.AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE]};diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex e7aee8583a..d707a20d19 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -479,5 +479,6 @@ export enum EventType {AGENT_VAULT_PROXY_ENROLL = "agent-vault-proxy-enroll",AGENT_VAULT_PROXY_UPDATE = "agent-vault-proxy-update",AGENT_VAULT_PROXY_REVOKE = "agent-vault-proxy-revoke",- AGENT_VAULT_PROXY_DELETE = "agent-vault-proxy-delete"+ AGENT_VAULT_PROXY_DELETE = "agent-vault-proxy-delete",+ AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE = "agent-vault-session-log-settings-update"}diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.tsindex 908ea223ea..00bc0a6276 100644--- a/frontend/src/hooks/api/subscriptions/types.ts+++ b/frontend/src/hooks/api/subscriptions/types.ts@@ -99,6 +99,7 @@ export type SubscriptionPlan = {honeyTokens: boolean;honeyTokenLimit: number;secretsBrokering: boolean;+ agentVaultByoS3: boolean;pam?: boolean | null;certManager?: boolean | null;secretsFolderRbac: boolean;diff --git a/frontend/src/hooks/useAgentVaultSheetState.ts b/frontend/src/hooks/useAgentVaultSheetState.tsnew file mode 100644index 0000000000..1c2fd39919--- /dev/null+++ b/frontend/src/hooks/useAgentVaultSheetState.ts@@ -0,0 +1,28 @@+import { useNavigate, useSearch } from "@tanstack/react-router";+import { z } from "zod";++export const agentVaultSheetSearchParams = z.object({+ sessionId: z.string().uuid().optional().catch(undefined)+});++export const useAgentVaultSheetState = () => {+ const navigate = useNavigate();+ const search = useSearch({ strict: false }) as Record<string, unknown>;+ const sessionId = search.sessionId as string | undefined;++ return {+ sessionId,+ isOpen: Boolean(sessionId),+ openSheet: (id: string) => {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ navigate({ search: { ...search, sessionId: id } as any });+ },+ closeSheet: () => {+ const rest = Object.fromEntries(+ Object.entries(search).filter(([key]) => key !== "sessionId")+ );+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ navigate({ search: rest as any });+ }+ };+};diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsxindex 7ebc849cf4..852cf033c6 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx@@ -1,4 +1,4 @@-import { FileText, IdCard, Info, Package, Route, Shield } from "lucide-react";+import { FileText, IdCard, Info, Package, Server, Settings, Shield } from "lucide-react";import { useAgentVaultIntro } from "@app/components/agent-vault/AgentVaultIntro";import {@@ -7,7 +7,15 @@ import {SidebarMenuButton,SidebarMenuItem} from "@app/components/v3";-import { useProjectPermission } from "@app/context";+import { useProjectPermission, useSubscription } from "@app/context";+import {+ areAgentVaultSessionLogsOn,+ isAgentVaultSessionLogPlanLapsed+} from "@app/helpers/agentVaultSessionLogs";+import {+ useGetAgentVaultSessionLogHealth,+ useGetAgentVaultSessionLogSettings+} from "@app/hooks/api/agentVault";import { ProjectMembershipRole } from "@app/hooks/api/roles/types";import { ProjectNavList } from "./ProjectNavLink";@@ -17,37 +25,53 @@ export const AgentVaultNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submconst { hasProjectRole } = useProjectPermission();const { setOpen: setIsIntroOpen } = useAgentVaultIntro();const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);+ const { data: sessionLogSettings } = useGetAgentVaultSessionLogSettings(isAdmin);+ const { data: sessionLogHealth } = useGetAgentVaultSessionLogHealth(isAdmin);+ const { subscription } = useSubscription();const accessItems: NavItem[] = [{ label: "Sessions", icon: IdCard, pathSuffix: "sessions" },{ label: "Access Bundles", icon: Package, pathSuffix: "access-bundles" }];- const governanceItems: NavItem[] = isAdmin+ const infrastructureItems: NavItem[] = [+ { label: "Proxies", icon: Server, pathSuffix: "proxies" }+ ];++ let settingsDot: NavItem["dotVariant"];+ if (+ sessionLogSettings?.bucket &&+ (!areAgentVaultSessionLogsOn(sessionLogSettings) ||+ isAgentVaultSessionLogPlanLapsed(sessionLogSettings, subscription))+ )+ settingsDot = "warning";+ else if (sessionLogHealth?.isStorageFull || sessionLogHealth?.connectionError)+ settingsDot = "danger";++ const administrationItems: NavItem[] = isAdmin? [- { label: "Audit Logs", icon: FileText, pathSuffix: "audit-logs" },{label: "Access Control",icon: Shield,pathSuffix: "access-management",activeMatch: /\/access-management|\/groups\/|\/identities\/|\/members\/|\/roles\//- }+ },+ { label: "Audit Logs", icon: FileText, pathSuffix: "audit-logs" },+ { label: "Settings", icon: Settings, pathSuffix: "settings", dotVariant: settingsDot }]: [];- const infrastructureItems: NavItem[] = [{ label: "Proxies", icon: Route, pathSuffix: "proxies" }];-return (<><ProjectNavList items={accessItems} onSubmenuOpen={onSubmenuOpen} />- {governanceItems.length > 0 && (- <SidebarCollapsibleGroup label="Governance">- <ProjectNavList items={governanceItems} onSubmenuOpen={onSubmenuOpen} />- </SidebarCollapsibleGroup>- )}<SidebarCollapsibleGroup label="Infrastructure"><ProjectNavList items={infrastructureItems} onSubmenuOpen={onSubmenuOpen} /></SidebarCollapsibleGroup>+ {administrationItems.length > 0 && (+ <SidebarCollapsibleGroup label="Administration">+ <ProjectNavList items={administrationItems} onSubmenuOpen={onSubmenuOpen} />+ </SidebarCollapsibleGroup>+ )}<SidebarMenu className="mt-auto"><SidebarMenuItem><SidebarMenuButtondiff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsxindex 0f1984f434..706116efff 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx@@ -15,6 +15,16 @@ 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"]> }) => (+ <span className="ml-auto flex shrink-0">+ <span+ aria-hidden+ className={twMerge("size-2 rounded-full", variant === "danger" ? "bg-danger" : "bg-warning")}+ />+ <span className="sr-only">Needs attention</span>+ </span>+);+// --- Project nav link (handles submenu chevron or normal link) ---export const ProjectNavLink = ({@@ -70,7 +80,13 @@ export const ProjectNavLink = ({{item.badgeCount}</Badge>)}- <ChevronRight className={twMerge("size-4 opacity-50", !item.badgeCount && "ml-auto")} />+ {item.dotVariant && <NavDot variant={item.dotVariant} />}+ <ChevronRight+ className={twMerge(+ "size-4 opacity-50",+ !item.badgeCount && !item.dotVariant && "ml-auto"+ )}+ /></SidebarMenuButton></SidebarMenuItem>);@@ -105,6 +121,7 @@ export const ProjectNavLink = ({{item.badgeCount}</Badge>)}+ {item.dotVariant && <NavDot variant={item.dotVariant} />}</Link></SidebarMenuButton></SidebarMenuItem>diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/types.ts b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/types.tsindex 50d4c0fe12..3dbb2d9997 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/types.ts+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/types.ts@@ -34,6 +34,7 @@ export type NavItem = {activeMatch?: RegExp | ((pathname: string, search: Record<string, unknown>) => boolean);badgeCount?: number;badgeVariant?: "warning" | "danger" | "pam";+ dotVariant?: "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/AgentVaultAccessControlPage/AgentVaultAccessControlPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/AgentVaultAccessControlPage.tsxindex 3b40a9f8eb..22cdbbde27 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/AgentVaultAccessControlPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/AgentVaultAccessControlPage.tsx@@ -24,8 +24,7 @@ export enum AgentVaultAccessControlTab {Groups = "groups"}-const AgentVaultAccessControlPageContent = () => {- const { t } = useTranslation();+const AgentVaultAccessControlTabs = () => {const navigate = useNavigate();const { currentOrg } = useOrganization();@@ -43,6 +42,42 @@ const AgentVaultAccessControlPageContent = () => {});};+ return (+ <Tabs value={selectedTab} onValueChange={updateTab}>+ <TabsList variant="av" aria-label="Agent Vault access control sections">+ <TabsTrigger value={AgentVaultAccessControlTab.Users}>Users</TabsTrigger>+ <TabsTrigger value={AgentVaultAccessControlTab.MachineIdentities}>+ Machine Identities+ </TabsTrigger>+ <TabsTrigger value={AgentVaultAccessControlTab.Groups}>Groups</TabsTrigger>+ </TabsList>+ <TabsContent value={AgentVaultAccessControlTab.Users}>+ <MembersTab />+ </TabsContent>+ <TabsContent value={AgentVaultAccessControlTab.MachineIdentities}>+ <IdentitiesTab />+ </TabsContent>+ <TabsContent value={AgentVaultAccessControlTab.Groups}>+ <GroupsTab />+ </TabsContent>+ </Tabs>+ );+};++// Built at module scope: wrapping inside the render makes a new component type each pass, which+// remounts the tabs and replays the gate.+const AgentVaultAccessControlTabsWithPermission = withProjectPermission(+ AgentVaultAccessControlTabs,+ {+ action: ProjectPermissionMemberActions.Read,+ subject: ProjectPermissionSub.Member,+ accessRestrictedMode: "dialog"+ }+);++export const AgentVaultAccessControlPage = () => {+ const { t } = useTranslation();+return (<div className="mx-auto mb-6 flex w-full max-w-8xl flex-col gap-8"><Helmet>@@ -54,35 +89,7 @@ const AgentVaultAccessControlPageContent = () => {title="Access Control"description="Manage access for users, machine identities, and groups."/>- <Tabs value={selectedTab} onValueChange={updateTab}>- <TabsList variant="av" aria-label="Agent Vault access control sections">- <TabsTrigger value={AgentVaultAccessControlTab.Users}>Users</TabsTrigger>- <TabsTrigger value={AgentVaultAccessControlTab.MachineIdentities}>- Machine Identities- </TabsTrigger>- <TabsTrigger value={AgentVaultAccessControlTab.Groups}>Groups</TabsTrigger>- </TabsList>- <TabsContent value={AgentVaultAccessControlTab.Users}>- <MembersTab />- </TabsContent>- <TabsContent value={AgentVaultAccessControlTab.MachineIdentities}>- <IdentitiesTab />- </TabsContent>- <TabsContent value={AgentVaultAccessControlTab.Groups}>- <GroupsTab />- </TabsContent>- </Tabs>+ <AgentVaultAccessControlTabsWithPermission /></div>);};--// Built at module scope: wrapping inside the render makes a new component type each pass, which-// remounts the tabs and replays the gate.-export const AgentVaultAccessControlPage = withProjectPermission(- AgentVaultAccessControlPageContent,- {- action: ProjectPermissionMemberActions.Read,- subject: ProjectPermissionSub.Member,- accessRestrictedMode: "dialog"- }-);diff --git a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsxindex fd2bcca0b7..97573b057e 100644--- a/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultProxiesPage/AgentVaultProxiesPage.tsx@@ -9,7 +9,7 @@ import {PencilIcon,PlusIcon,RefreshCwIcon,- RouteIcon,+ ServerIcon,TrashIcon,TriangleAlertIcon} from "lucide-react";@@ -229,7 +229,7 @@ export const AgentVaultProxiesPage = () => {</Helmet><PageHeaderscope={ProjectType.AgentVault}- icon={RouteIcon}+ icon={ServerIcon}title="Proxies"description="Manage the proxies your agents route their requests through."/>diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsxindex 8d0fd0ed13..f696f4dc35 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx@@ -6,15 +6,24 @@ import { format } from "date-fns";import {BanIcon,BotIcon,+ CircleAlertIcon,+ FilterIcon,IdCardIcon,+ LogsIcon,MoreHorizontalIcon,PackageIcon,PlusIcon,SearchIcon,+ TriangleAlertIcon,UserIcon} from "lucide-react";+import { AgentVaultSessionLogUpgradeModal } from "@app/components/agent-vault/AgentVaultSessionLogUpgradeModal";+import { memberDisplayName, memberSubtitle } from "@app/components/agent-vault/MemberName";import {+ Alert,+ AlertAction,+ AlertDescription,Button,Card,CardAction,@@ -24,8 +33,10 @@ import {CardTitle,DocumentationLinkBadge,DropdownMenu,+ DropdownMenuCheckboxItem,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuLabel,DropdownMenuTrigger,Empty,EmptyDescription,@@ -38,11 +49,6 @@ import {OverflowBadgeList,PageHeader,Pagination,- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,Skeleton,Table,TableBody,@@ -50,11 +56,18 @@ import {TableHead,TableHeader,TableRow,+ Tabs,+ TabsList,+ TabsTrigger,Tooltip,TooltipContent,TooltipTrigger} from "@app/components/v3";-import { useOrganization, useProjectPermission } from "@app/context";+import { useOrganization, useProjectPermission, useSubscription } from "@app/context";+import {+ areAgentVaultSessionLogsOn,+ isAgentVaultSessionLogPlanLapsed+} from "@app/helpers/agentVaultSessionLogs";import {getUserTablePreference,PreferenceKey,@@ -62,23 +75,35 @@ import {} from "@app/helpers/userTablePreferences";import { useDebounce, useResetPageHelper } from "@app/hooks";import {+ AgentVaultMemberType,AgentVaultSessionScope,AgentVaultSessionStatus,+ useGetAgentVaultSession,+ useGetAgentVaultSessionLogHealth,+ useGetAgentVaultSessionLogSettings,useListAgentVaultAccessBundles,useListAgentVaultSessions} from "@app/hooks/api/agentVault";import { TAgentVaultMintedSession, TAgentVaultSession } from "@app/hooks/api/agentVault/types";import { ProjectType } from "@app/hooks/api/projects/types";import { ProjectMembershipRole } from "@app/hooks/api/roles/types";+import { useAgentVaultSheetState } from "@app/hooks/useAgentVaultSheetState";+import { SessionLogReadAccessAlert } from "@app/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogReadAccessAlert";import { AgentVaultDocsUrls } from "../agent-vault-docs-urls";import { CreateSessionDialog } from "./components/CreateSessionDialog";import { RevokeSessionDialog } from "./components/RevokeSessionDialog";import { SessionCreatedDialog } from "./components/SessionCreatedDialog";+import { SessionDetailSheet } from "./components/SessionDetailSheet";import { SessionExpiry } from "./components/SessionExpiry";-import { SessionStatusBadge } from "./components/SessionStatusBadge";+import { SessionLogLossIndicator } from "./components/SessionLogLossIndicator";+import { SESSION_STATUS_PRESENTATION, SessionStatusBadge } from "./components/SessionStatusBadge";-const ALL_STATUSES = "all";+const STATUS_OPTIONS = [+ AgentVaultSessionStatus.Active,+ AgentVaultSessionStatus.Revoked,+ AgentVaultSessionStatus.Expired+];export const AgentVaultSessionsPage = () => {const { t } = useTranslation();@@ -88,10 +113,17 @@ export const AgentVaultSessionsPage = () => {const [search, setSearch] = useState("");const [debouncedSearch] = useDebounce(search);- const [statusFilter, setStatusFilter] = useState<AgentVaultSessionStatus | typeof ALL_STATUSES>(- ALL_STATUSES- );- const [scope, setScope] = useState(AgentVaultSessionScope.Mine);+ const [statuses, setStatuses] = useState<AgentVaultSessionStatus[]>([]);+ const [scope, setScope] = useState(() => {+ const stored = getUserTablePreference(+ "agentVaultSessionsTable",+ PreferenceKey.SessionScope,+ AgentVaultSessionScope.All+ );+ return Object.values(AgentVaultSessionScope).includes(stored)+ ? stored+ : AgentVaultSessionScope.All;+ });const [page, setPage] = useState(1);const [perPage, setPerPage] = useState(() =>getUserTablePreference("agentVaultSessionsTable", PreferenceKey.PerPage, 20)@@ -99,24 +131,38 @@ export const AgentVaultSessionsPage = () => {const [sessionToRevoke, setSessionToRevoke] = useState<TAgentVaultSession | null>(null);const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);const [mintedSession, setMintedSession] = useState<TAgentVaultMintedSession | null>(null);+ const { sessionId: openSessionId, openSheet } = useAgentVaultSheetState();const { data, isPending } = useListAgentVaultSessions({scope: isAdmin ? scope : AgentVaultSessionScope.Mine,- status: statusFilter === ALL_STATUSES ? undefined : statusFilter,+ statuses,search: debouncedSearch.trim() || undefined,limit: perPage,offset: (page - 1) * perPage});const { data: accessBundles } = useListAgentVaultAccessBundles({ limit: 1 });+ const { data: sessionLogSettings } = useGetAgentVaultSessionLogSettings(isAdmin);+ const { data: sessionLogHealth } = useGetAgentVaultSessionLogHealth(isAdmin);+ const { subscription } = useSubscription();+ const [isUpgradeOpen, setIsUpgradeOpen] = useState(false);+ const isSessionLogPlanLapsed = Boolean(+ sessionLogSettings && isAgentVaultSessionLogPlanLapsed(sessionLogSettings, subscription)+ );const sessions = data?.sessions ?? [];const totalCount = data?.totalCount ?? 0;+ const loadedOpenSession = sessions.find((session) => session.id === openSessionId);+ const { data: fetchedOpenSession, isPending: isFetchingOpenSession } =+ useGetAgentVaultSession(openSessionId);+ const openSession = fetchedOpenSession ?? loadedOpenSession;+ const isOpenSessionPending = Boolean(openSessionId) && !openSession && isFetchingOpenSession;+useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });// The debounced term, not the typed one: the rows on screen were fetched with this, so keying the copy// off the live input would caption a stale result set.- const isFiltered = Boolean(debouncedSearch.trim()) || statusFilter !== ALL_STATUSES;+ const isFiltered = Boolean(debouncedSearch.trim()) || statuses.length > 0;const hasReachableBundles = (accessBundles?.totalCount ?? 0) > 0;let emptyTitle: string;@@ -146,6 +192,81 @@ export const AgentVaultSessionsPage = () => {description="Create sessions that let your agents reach the services in an access bundle."/>+ {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) &&+ !isSessionLogPlanLapsed && (+ <Alert variant="danger">+ <CircleAlertIcon />+ <AlertDescription>+ <p>{sessionLogHealth.connectionError}</p>+ <AlertAction>+ <Button variant="outline" size="sm" asChild>+ <Link+ to="/organizations/$orgId/agent-vault/settings"+ params={{ orgId: currentOrg.id }}+ >+ Go to Settings+ </Link>+ </Button>+ </AlertAction>+ </AlertDescription>+ </Alert>+ )}++ {isSessionLogPlanLapsed && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ <p>Your plan no longer includes session logs, so new requests aren't recorded.</p>+ <AlertAction>+ <Button variant="outline" size="sm" onClick={() => setIsUpgradeOpen(true)}>+ Upgrade+ </Button>+ </AlertAction>+ </AlertDescription>+ </Alert>+ )}++ {sessionLogSettings &&+ Boolean(sessionLogSettings.bucket) &&+ !isSessionLogPlanLapsed &&+ !areAgentVaultSessionLogsOn(sessionLogSettings) && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ <p>+ Sessions aren't being logged, so there is no record of what your agents+ reached.+ </p>+ <AlertAction>+ <Button variant="outline" size="sm" asChild>+ <Link+ to="/organizations/$orgId/agent-vault/settings"+ params={{ orgId: currentOrg.id }}+ >+ Go to Settings+ </Link>+ </Button>+ </AlertAction>+ </AlertDescription>+ </Alert>+ )}++ {isAdmin && <SessionLogReadAccessAlert />}+<Card><CardHeader><CardTitle>@@ -167,55 +288,67 @@ export const AgentVaultSessionsPage = () => {</Button></CardAction></CardHeader>- <CardContent className="flex items-center gap-4">- <div className="flex-1">- <InputGroup>- <InputGroupAddon>- <SearchIcon />- </InputGroupAddon>- <InputGroupInput- value={search}- onChange={(e) => {- setSearch(e.target.value);- setPage(1);- }}- placeholder="Search by identity, email, or access bundle..."- />- </InputGroup>- </div>- <Select- value={statusFilter}- onValueChange={(value) => {- setStatusFilter(value as AgentVaultSessionStatus | typeof ALL_STATUSES);- setPage(1);- }}- >- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={ALL_STATUSES}>All Statuses</SelectItem>- <SelectItem value={AgentVaultSessionStatus.Active}>Active</SelectItem>- <SelectItem value={AgentVaultSessionStatus.Revoked}>Revoked</SelectItem>- <SelectItem value={AgentVaultSessionStatus.Expired}>Expired</SelectItem>- </SelectContent>- </Select>+ <CardContent className="flex items-center gap-2">+ <InputGroup className="flex-1">+ <InputGroupAddon>+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ value={search}+ onChange={(e) => {+ setSearch(e.target.value);+ setPage(1);+ }}+ placeholder="Search by identity, email, or access bundle..."+ />+ </InputGroup>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton aria-label="Filter sessions" variant={statuses.length ? "av" : "outline"}>+ <FilterIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuLabel>Status</DropdownMenuLabel>+ {STATUS_OPTIONS.map((status) => {+ const { label, icon: Icon, iconClassName } = SESSION_STATUS_PRESENTATION[status];+ return (+ <DropdownMenuCheckboxItem+ key={status}+ checked={statuses.includes(status)}+ onClick={(e) => {+ e.preventDefault();+ setStatuses((prev) =>+ prev.includes(status) ? prev.filter((s) => s !== status) : [...prev, status]+ );+ setPage(1);+ }}+ >+ <Icon className={iconClassName} />+ {label}+ </DropdownMenuCheckboxItem>+ );+ })}+ </DropdownMenuContent>+ </DropdownMenu>{isAdmin && (- <Select+ <Tabsvalue={scope}onValueChange={(value) => {setScope(value as AgentVaultSessionScope);setPage(1);+ setUserTablePreference(+ "agentVaultSessionsTable",+ PreferenceKey.SessionScope,+ value+ );}}>- <SelectTrigger aria-label="Session scope">- <SelectValue />- </SelectTrigger>- <SelectContent position="popper">- <SelectItem value={AgentVaultSessionScope.All}>All Sessions</SelectItem>- <SelectItem value={AgentVaultSessionScope.Mine}>My Sessions</SelectItem>- </SelectContent>- </Select>+ <TabsList variant="filled">+ <TabsTrigger value={AgentVaultSessionScope.All}>All Sessions</TabsTrigger>+ <TabsTrigger value={AgentVaultSessionScope.Mine}>My Sessions</TabsTrigger>+ </TabsList>+ </Tabs>)}</CardContent>@@ -265,23 +398,27 @@ export const AgentVaultSessionsPage = () => {))}{!isPending &&sessions.map((session) => (- <TableRow key={session.id}>+ <TableRow+ key={session.id}+ onClick={() => openSheet(session.id)}+ className="cursor-pointer"+ ><TableCell><Tooltip><TooltipTrigger asChild><div className="flex w-fit items-center gap-2">- {session.identityId ? (+ {session.actor.type === AgentVaultMemberType.MachineIdentity ? (<BotIcon className="size-4 text-muted" />) : (<UserIcon className="size-4 text-muted" />)}- {session.actorName}+ {memberDisplayName(session.actor)}</div></TooltipTrigger><TooltipContent>- {session.identityId- ? `${session.identityId} (machine identity)`- : session.actorEmail}+ {session.actor.type === AgentVaultMemberType.MachineIdentity+ ? `${session.actor.id ?? "Deleted"} (machine identity)`+ : memberSubtitle(session.actor)}</TooltipContent></Tooltip></TableCell>@@ -326,16 +463,47 @@ export const AgentVaultSessionsPage = () => {<SessionStatusBadge status={session.status} /></TableCell><TableCell variant="action">- {session.status === AgentVaultSessionStatus.Active && (+ <div className="flex items-center justify-end gap-1">+ <SessionLogLossIndicator counts={session.recentSessionLogCounts} />+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ variant="ghost"+ size="xs"+ aria-label="View session logs"+ onClick={(event) => {+ event.stopPropagation();+ openSheet(session.id);+ }}+ >+ <LogsIcon />+ </IconButton>+ </TooltipTrigger>+ <TooltipContent>View Session Logs</TooltipContent>+ </Tooltip><DropdownMenu><DropdownMenuTrigger asChild>- <IconButton variant="ghost" size="xs" aria-label="Open session actions">+ <IconButton+ variant="ghost"+ size="xs"+ aria-label="Open session actions"+ onClick={(event) => event.stopPropagation()}+ ><MoreHorizontalIcon /></IconButton></DropdownMenuTrigger>- <DropdownMenuContent sideOffset={2} align="end">+ <DropdownMenuContent+ sideOffset={2}+ align="end"+ onClick={(event) => event.stopPropagation()}+ >+ <DropdownMenuItem onClick={() => openSheet(session.id)}>+ <LogsIcon />+ View Session Logs+ </DropdownMenuItem><DropdownMenuItemvariant="danger"+ isDisabled={session.status !== AgentVaultSessionStatus.Active}onClick={() => setSessionToRevoke(session)}><BanIcon />@@ -343,7 +511,7 @@ export const AgentVaultSessionsPage = () => {</DropdownMenuItem></DropdownMenuContent></DropdownMenu>- )}+ </div></TableCell></TableRow>))}@@ -391,6 +559,14 @@ export const AgentVaultSessionsPage = () => {if (!isOpen) setSessionToRevoke(null);}}/>++ <SessionDetailSheet+ session={openSession}+ isPending={isOpenSessionPending}+ onRevoke={setSessionToRevoke}+ />++ <AgentVaultSessionLogUpgradeModal isOpen={isUpgradeOpen} onOpenChange={setIsUpgradeOpen} /></div>);};diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/LiveStatusRow.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/LiveStatusRow.tsxnew file mode 100644index 0000000000..148923a1c2--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/LiveStatusRow.tsx@@ -0,0 +1,131 @@+import {+ ArrowUpIcon,+ HourglassIcon,+ type LucideIcon,+ PauseIcon,+ TriangleAlertIcon+} from "lucide-react";+import { twMerge } from "tailwind-merge";++import { Badge, Button, TableCell, TableRow } from "@app/components/v3";+import { AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS } from "@app/hooks/api/agentVault";++export type LiveState = "live" | "reconnecting" | "paused" | "ended";++const LIVE_STATE_PRESENTATION: Record<+ LiveState,+ {+ label: string;+ variant: "success" | "warning" | "neutral";+ icon?: LucideIcon;+ rowClassName: string;+ }+> = {+ live: { label: "Live", variant: "success", rowClassName: "bg-success/5 text-success/80" },+ reconnecting: {+ label: "Reconnecting",+ variant: "warning",+ icon: TriangleAlertIcon,+ rowClassName: "bg-warning/5 text-warning/80"+ },+ paused: {+ label: "Paused",+ variant: "neutral",+ icon: PauseIcon,+ rowClassName: "bg-neutral/5 text-neutral/80"+ },+ ended: {+ label: "Session Ended",+ variant: "neutral",+ icon: HourglassIcon,+ rowClassName: "bg-neutral/5 text-neutral/80"+ }+};++const LiveDot = ({ className }: { className?: string }) => (+ <span aria-hidden className={twMerge("relative flex size-1.5 shrink-0", className)}>+ <span className="absolute inline-flex size-full rounded-full bg-current opacity-75 motion-safe:animate-ping" />+ <span className="relative inline-flex size-full rounded-full bg-current" />+ </span>+);++export const LiveStateBadge = ({ state }: { state: LiveState }) => {+ const { label, variant, icon: Icon } = LIVE_STATE_PRESENTATION[state];++ return (+ <Badge variant={variant}>+ {Icon ? <Icon /> : <LiveDot />}+ {label}+ </Badge>+ );+};++const liveStateDescription = (state: LiveState, recordCount: number) => {+ if (state === "live") return "New requests show up here within about a minute.";+ if (state === "reconnecting")+ return `Couldn't check for new requests. Trying again every ${AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS / 1000} seconds.`;+ if (state === "paused")+ return `Showing the most recent ${recordCount.toLocaleString()} requests. Pick a time range to see further back.`;+ return "Its last requests can take up to a minute to show up.";+};++type Props = {+ state: LiveState;+ columnCount: number;+ recordCount: number;+ isRetrying?: boolean;+ onRetry?: () => void;+ newRequestCount?: number;+ onShowNewRequests?: () => void;+};++export const LiveStatusRow = ({+ state,+ columnCount,+ recordCount,+ isRetrying,+ onRetry,+ newRequestCount = 0,+ onShowNewRequests+}: Props) => (+ <TableRow>+ {/* A collapsed border scrolls away under a sticky header, so this draws its divider the way the column headers do */}+ <TableCell+ colSpan={columnCount}+ className={twMerge(+ "relative h-8 border-b-0 py-1 shadow-[inset_0_-1px_0_var(--color-border)]",+ LIVE_STATE_PRESENTATION[state].rowClassName+ )}+ >+ <div role="status" className="flex min-w-0 items-center gap-2">+ <LiveStateBadge state={state} />+ <span className="min-w-0 truncate text-xs">{liveStateDescription(state, recordCount)}</span>+ {state === "reconnecting" && onRetry && (+ <Button+ variant="link"+ size="xs"+ className="ml-auto text-xs"+ isPending={isRetrying}+ onClick={onRetry}+ >+ Check Now+ </Button>+ )}+ </div>+ {newRequestCount > 0 && onShowNewRequests && (+ // Hangs off the sticky header, so it stays in view while the rows scroll under it+ <div className="absolute top-full left-1/2 mt-2 -translate-x-1/2 animate-in duration-200 fade-in-0 slide-in-from-top-1 motion-reduce:animate-none">+ <Button+ variant="outline"+ size="xs"+ className="rounded-full bg-popover shadow-floating hover:bg-container-hover in-data-[theme=light]:shadow-floating-light"+ onClick={onShowNewRequests}+ >+ <ArrowUpIcon />+ {newRequestCount.toLocaleString()} New {newRequestCount === 1 ? "Request" : "Requests"}+ </Button>+ </div>+ )}+ </TableCell>+ </TableRow>+);diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/RevokeSessionDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/RevokeSessionDialog.tsxindex 9c5de2062f..93fe5fe688 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/RevokeSessionDialog.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/RevokeSessionDialog.tsx@@ -1,3 +1,4 @@+import { memberDisplayName } from "@app/components/agent-vault/MemberName";import { createNotification } from "@app/components/notifications";import { DeleteConfirmDialog } from "@app/components/v3";import { useRevokeAgentVaultSession } from "@app/hooks/api/agentVault";@@ -16,7 +17,10 @@ export const RevokeSessionDialog = ({ session, onOpenChange }: Props) => {try {await revokeSession.mutateAsync(session.id);- createNotification({ text: `Session for "${session.actorName}" revoked`, type: "success" });+ createNotification({+ text: `Session for "${memberDisplayName(session.actor)}" revoked`,+ type: "success"+ });onOpenChange(false);} catch {// A failed request returns a 4xx that the global request handler surfaces as a toast@@ -27,7 +31,7 @@ export const RevokeSessionDialog = ({ session, onOpenChange }: Props) => {<DeleteConfirmDialogisOpen={Boolean(session)}onOpenChange={onOpenChange}- title={`Revoke Session for "${session?.actorName}"`}+ title={`Revoke Session for "${session ? memberDisplayName(session.actor) : ""}"`}description="Proxies stop attaching credentials for this session at their next poll. This cannot be undone."confirmKey="revoke"confirmLabel="Revoke Session"diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionCreatedDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionCreatedDialog.tsxindex b3226a64dd..03e4f8cc8a 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionCreatedDialog.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionCreatedDialog.tsx@@ -15,7 +15,7 @@ import {import { TAgentVaultMintedSession } from "@app/hooks/api/agentVault/types";import { AgentVaultDocsUrls } from "../../agent-vault-docs-urls";-import { SessionExpiry } from "./SessionExpiry";+import { formatSessionExpiry } from "./SessionExpiry";type Props = {session: TAgentVaultMintedSession | null;@@ -59,7 +59,7 @@ export const SessionCreatedDialog = ({ session, onOpenChange }: Props) => (<div className="flex flex-col gap-1.5"><span className="text-xs text-accent">Expires</span>- <SessionExpiry expiresAt={session?.expiresAt ?? null} />+ <span className="text-sm">{formatSessionExpiry(session?.expiresAt ?? null)}</span></div><p className="mt-2 text-xs text-accent">diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsxnew file mode 100644index 0000000000..08d91989ce--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx@@ -0,0 +1,183 @@+import { Link } from "@tanstack/react-router";+import { format } from "date-fns";+import { BanIcon, BotIcon, PackageIcon, UserIcon } from "lucide-react";+import { twMerge } from "tailwind-merge";++import { memberDisplayName, memberSubtitle } from "@app/components/agent-vault/MemberName";+import {+ Button,+ Detail,+ DetailLabel,+ DetailValue,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetHeader,+ SheetTitle,+ Spinner+} from "@app/components/v3";+import { useOrganization } from "@app/context";+import { AgentVaultMemberType, AgentVaultSessionStatus } from "@app/hooks/api/agentVault";+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";++type Props = {+ session: TAgentVaultSession | undefined;+ isPending?: boolean;+ onRevoke: (session: TAgentVaultSession) => void;+};++export const SessionDetailSheet = ({ session, isPending = false, onRevoke }: Props) => {+ const { isOpen, closeSheet } = useAgentVaultSheetState();+ const { currentOrg } = useOrganization();++ const isOwnerDeleted = session?.actor.id === null;+ const isMachineIdentity = session?.actor.type === AgentVaultMemberType.MachineIdentity;+ const hasExpired = Boolean(+ session?.expiresAt && new Date(session.expiresAt).getTime() <= Date.now()+ );++ return (+ <Sheet open={isOpen} onOpenChange={(open) => !open && closeSheet()}>+ <SheetContent+ size="workspace"+ className="flex h-full max-h-full flex-col gap-y-0"+ onOpenAutoFocus={(event) => event.preventDefault()}+ >+ {!session && isPending && (+ <Empty className="m-4 border">+ <EmptyHeader>+ <Spinner size="sm" />+ </EmptyHeader>+ </Empty>+ )}+ {!session && !isPending && (+ <Empty className="m-4 border">+ <EmptyHeader>+ <EmptyTitle>Session not found</EmptyTitle>+ <EmptyDescription>+ This session doesn't exist, or you don't have access to it.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ )}+ {session && (+ <>+ <SheetHeader>+ <SheetTitle>Session Logs</SheetTitle>+ <SheetDescription>Every request the agent made during this session.</SheetDescription>+ </SheetHeader>++ <div className="flex min-h-0 flex-1 flex-col gap-4 p-4">+ <div className="flex shrink-0 items-center gap-4 overflow-hidden rounded-md border border-border bg-container py-3 pr-4">+ {/* -ml-px pushes each row's leading divider past the clipped edge, so a wrapped row doesn't start with one */}+ <div className="-ml-px flex min-w-0 flex-1 flex-wrap gap-y-3 *:border-l *:border-border *:px-4">+ <Detail className="min-w-0">+ <DetailLabel>{isMachineIdentity ? "Machine Identity" : "User"}</DetailLabel>+ <DetailValue+ className={twMerge("flex items-center gap-2", isOwnerDeleted && "text-muted")}+ >+ {isMachineIdentity ? (+ <BotIcon className="size-4 shrink-0 text-muted" />+ ) : (+ <UserIcon className="size-4 shrink-0 text-muted" />+ )}+ <span className="truncate">+ {memberDisplayName(session.actor)}+ {isOwnerDeleted && " (deleted)"}+ </span>+ {!isMachineIdentity && (+ <span className="truncate text-muted">{memberSubtitle(session.actor)}</span>+ )}+ </DetailValue>+ </Detail>+ <Detail className="min-w-0">+ <DetailLabel>+ {session.accessBundles.length === 1 ? "Access Bundle" : "Access Bundles"}+ </DetailLabel>+ <DetailValue className="flex flex-wrap gap-x-4 gap-y-1">+ {session.accessBundles.map((bundle) =>+ bundle.id ? (+ <Link+ key={bundle.id}+ to="/organizations/$orgId/agent-vault/access-bundles/$accessBundleId"+ params={{ orgId: currentOrg.id, accessBundleId: bundle.id }}+ className="group flex min-w-0 items-center gap-2"+ >+ <PackageIcon className="size-4 shrink-0 text-muted" />+ <span className="truncate group-hover:underline group-hover:underline-offset-2">+ {bundle.name}+ </span>+ </Link>+ ) : (+ <span+ key={bundle.name}+ className="flex min-w-0 items-center gap-2 text-muted"+ >+ <PackageIcon className="size-4 shrink-0" />+ <span className="truncate">{bundle.name} (deleted)</span>+ </span>+ )+ )}+ </DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Created</DetailLabel>+ <DetailValue>+ {format(new Date(session.createdAt), "MMM d, yyyy h:mm a")}+ </DetailValue>+ </Detail>+ {session.revokedAt && (+ <Detail>+ <DetailLabel>Revoked</DetailLabel>+ <DetailValue>+ {format(new Date(session.revokedAt), "MMM d, yyyy h:mm a")}+ </DetailValue>+ </Detail>+ )}+ {session.status !== AgentVaultSessionStatus.Revoked && (+ <Detail>+ <DetailLabel>{hasExpired ? "Expired" : "Expires"}</DetailLabel>+ <DetailValue>+ <SessionExpiry expiresAt={session.expiresAt} />+ </DetailValue>+ </Detail>+ )}+ <Detail className="items-start">+ <DetailLabel>Status</DetailLabel>+ <SessionStatusBadge status={session.status} />+ </Detail>+ </div>+ <SessionLogLossIndicator counts={session.recentSessionLogCounts} side="left" />+ {session.status === AgentVaultSessionStatus.Active && (+ <Button+ variant="danger"+ size="sm"+ className="shrink-0"+ onClick={() => onRevoke(session)}+ >+ <BanIcon />+ Revoke Session+ </Button>+ )}+ </div>++ <div className="flex min-h-0 flex-1 flex-col">+ <SessionLogsPanel session={session} />+ </div>+ </div>+ </>+ )}+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionExpiry.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionExpiry.tsxindex eaecf47554..ecf5d19be0 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionExpiry.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionExpiry.tsx@@ -6,6 +6,13 @@ type Props = {expiresAt: string | null;};+export const formatSessionExpiry = (expiresAt: string | null) => {+ if (!expiresAt) return "Never";+ const expiry = new Date(expiresAt);+ const hasPassed = expiry.getTime() <= Date.now();+ return `${hasPassed ? "" : "in "}${formatDistanceToNowStrict(expiry, { addSuffix: hasPassed })}`;+};+export const SessionExpiry = ({ expiresAt }: Props) => {if (!expiresAt) {return (@@ -18,18 +25,12 @@ export const SessionExpiry = ({ expiresAt }: Props) => {);}- const expiry = new Date(expiresAt);- const hasPassed = expiry.getTime() <= Date.now();-return (<Tooltip><TooltipTrigger asChild>- <span className="text-sm">- {hasPassed ? "" : "in "}- {formatDistanceToNowStrict(expiry, { addSuffix: hasPassed })}- </span>+ <span className="text-sm">{formatSessionExpiry(expiresAt)}</span></TooltipTrigger>- <TooltipContent>{format(expiry, "MMM d, yyyy h:mm a")}</TooltipContent>+ <TooltipContent>{format(new Date(expiresAt), "MMM d, yyyy h:mm a")}</TooltipContent></Tooltip>);};diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogLossIndicator.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogLossIndicator.tsxnew file mode 100644index 0000000000..a7253086cc--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogLossIndicator.tsx@@ -0,0 +1,33 @@+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.tsxnew file mode 100644index 0000000000..2f9834769b--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx@@ -0,0 +1,253 @@+import { useEffect, useState } from "react";+import { format } from "date-fns";+import {+ ArrowRightIcon,+ CircleHelpIcon,+ CircleXIcon,+ InfoIcon,+ KeyRoundIcon,+ type LucideIcon,+ PlusIcon,+ ShieldBanIcon+} from "lucide-react";+import { twMerge } from "tailwind-merge";++import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";+import {+ Badge,+ Button,+ TableCell,+ TableRow,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { AgentVaultSessionLogDecision } from "@app/hooks/api/agentVault";+import { TAgentVaultSessionLogRecord } from "@app/hooks/api/agentVault/types";++import { httpStatusLabel } from "./SessionLogsPanel.utils";++const ARRIVAL_HOLD_MS = 1200;++export const DECISION_PRESENTATION: Record<+ AgentVaultSessionLogDecision,+ {+ label: string;+ variant: "success" | "neutral" | "warning" | "danger";+ icon: LucideIcon;+ iconClassName: string;+ }+> = {+ [AgentVaultSessionLogDecision.Brokered]: {+ label: "Brokered",+ variant: "success",+ icon: KeyRoundIcon,+ iconClassName: "text-success"+ },+ [AgentVaultSessionLogDecision.Passthrough]: {+ label: "Passthrough",+ variant: "neutral",+ icon: ArrowRightIcon,+ iconClassName: "text-neutral"+ },+ [AgentVaultSessionLogDecision.Blocked]: {+ label: "Blocked",+ variant: "warning",+ icon: ShieldBanIcon,+ iconClassName: "text-warning"+ },+ [AgentVaultSessionLogDecision.Error]: {+ label: "Error",+ variant: "danger",+ icon: CircleXIcon,+ iconClassName: "text-danger"+ }+};++const decisionPresentation = (decision: AgentVaultSessionLogDecision) =>+ DECISION_PRESENTATION[decision] ?? {+ label: decision || "Unknown",+ variant: "neutral" as const,+ icon: CircleHelpIcon+ };++const statusTone = (status: number) => {+ if (status >= 500) return "text-danger";+ if (status >= 400) return "text-warning";+ return "text-foreground";+};++// Agent Vault answers Blocked and Error requests itself, so their status is its own reply, not the+// upstream's.+const isProxyAnswered = (decision: AgentVaultSessionLogDecision) =>+ decision === AgentVaultSessionLogDecision.Blocked ||+ decision === AgentVaultSessionLogDecision.Error;++const proxyAnswerDescription = (record: TAgentVaultSessionLogRecord) => {+ const answer = `Agent Vault returned ${httpStatusLabel(record.status)}`;+ return record.decision === AgentVaultSessionLogDecision.Blocked+ ? `${answer} without sending this request to ${record.host}`+ : `${answer} with no response from ${record.host}`;+};++// A host pattern without a port means 443, and an IPv6 literal needs its brackets back.+export const hostPatternFor = (record: TAgentVaultSessionLogRecord) => {+ const host = record.host.includes(":") ? `[${record.host}]` : record.host;+ return record.port === "443" ? host : `${host}:${record.port}`;+};++type Props = {+ record: TAgentVaultSessionLogRecord;+ arrivedAt?: number;+ proxyName?: string;+ showProxy: boolean;+ accessBundleName?: string;+ onAddService?: () => void;+};++export const SessionLogRow = ({+ record,+ arrivedAt,+ proxyName,+ showProxy,+ accessBundleName,+ onAddService+}: Props) => {+ const [isArriving, setIsArriving] = useState(false);++ useEffect(() => {+ if (arrivedAt === undefined) return undefined;+ const remaining = arrivedAt + ARRIVAL_HOLD_MS - Date.now();+ if (remaining <= 0) return undefined;+ setIsArriving(true);+ const timer = setTimeout(() => setIsArriving(false), remaining);+ return () => clearTimeout(timer);+ }, [arrivedAt]);++ const presentation = decisionPresentation(record.decision);+ const proxyAnswered = isProxyAnswered(record.decision);+ const outcome = (+ <Badge variant={presentation.variant}>+ <presentation.icon />+ {presentation.label}+ </Badge>+ );+ const host = (+ <span className="flex w-fit max-w-full items-center gap-2 text-sm">+ <ServiceIcon hostPattern={record.host} />+ <span className="truncate" title={record.service ? undefined : record.host}>+ {record.host}+ </span>+ </span>+ );++ return (+ <TableRow+ className={twMerge(+ "transition-colors duration-700 motion-reduce:transition-none",+ isArriving && "bg-surface-active"+ )}+ >+ <TableCell>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="font-mono text-xs whitespace-nowrap">+ {format(new Date(record.ts), "MMM d, yyyy HH:mm:ss")}+ </span>+ </TooltipTrigger>+ <TooltipContent>+ {format(new Date(record.ts), "MMM d, yyyy HH:mm:ss.SSS (zzz)")}+ </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 ? (+ <Tooltip>+ <TooltipTrigger asChild>{host}</TooltipTrigger>+ <TooltipContent>{record.service}</TooltipContent>+ </Tooltip>+ ) : (+ host+ )}+ </TableCell>+ <TableCell>+ <span className="block truncate" title={record.path}>+ {record.path}+ </span>+ </TableCell>+ <TableCell className="font-mono text-xs">+ {!proxyAnswered && record.status ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <span className={statusTone(record.status)}>{record.status}</span>+ </TooltipTrigger>+ <TooltipContent>+ {record.host} returned {httpStatusLabel(record.status)}+ </TooltipContent>+ </Tooltip>+ ) : (+ <span className="text-muted">—</span>+ )}+ </TableCell>+ <TableCell>+ {proxyAnswered && record.status ? (+ <Tooltip>+ <TooltipTrigger asChild>{outcome}</TooltipTrigger>+ <TooltipContent className="max-w-sm">{proxyAnswerDescription(record)}</TooltipContent>+ </Tooltip>+ ) : (+ outcome+ )}+ </TableCell>+ <TableCell variant="action">+ {onAddService && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="ghost" size="xs" onClick={onAddService}>+ <PlusIcon />+ Add Service+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ Add {record.host} to {accessBundleName}+ </TooltipContent>+ </Tooltip>+ )}+ </TableCell>+ </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.tsxnew file mode 100644index 0000000000..4363a42c51--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx@@ -0,0 +1,821 @@+import { useEffect, useMemo, useRef, useState } from "react";+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";+import {+ Alert,+ AlertAction,+ AlertDescription,+ Button,+ DateRangeFilter,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ IconButton,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Spinner,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import { useOrganization, useProjectPermission, useSubscription } from "@app/context";+import {+ AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS,+ AgentVaultSessionLogDecision,+ sessionLogRecordKey,+ useAgentVaultSessionLogTimeline,+ useGetAgentVaultSessionLogs+} from "@app/hooks/api/agentVault";+import {+ TAgentVaultSession,+ TAgentVaultSessionLogGapReason+} from "@app/hooks/api/agentVault/types";+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";++import { LiveState, LiveStateBadge, LiveStatusRow } from "./LiveStatusRow";+import {+ DECISION_PRESENTATION,+ hostPatternFor,+ SessionLogDropRow,+ 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;++const UPLOAD_RECHECK_MS = 15_000;++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" },+ 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"+ },+ gcm: { one: "could not be decrypted", many: "could not be decrypted" },+ json: {+ one: "was decrypted but could not be read",+ many: "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"+ }+};++// 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;+};++type Props = {+ session: TAgentVaultSession;+};++export const SessionLogsPanel = ({ session }: Props) => {+ const { currentOrg } = useOrganization();+ const { hasProjectRole } = useProjectPermission();+ const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);+ const { subscription } = useSubscription();+ const [isUpgradeOpen, setIsUpgradeOpen] = useState(false);+ // A session holds one bundle (AGENT_VAULT_MAX_SESSION_BUNDLES). Raising that cap needs a bundle+ // picker here: the rows offering Add Service matched no service, so they name no bundle.+ const accessBundle = session.accessBundles[0];+ const canAddService = isAdmin && Boolean(accessBundle?.id);+ // Not cleared on close: a prefilled host drops the sheet's template step, so clearing the host+ // while the sheet animates out would change the step on screen.+ const [serviceHost, setServiceHost] = useState<string | null>(null);+ const [isServiceSheetOpen, setIsServiceSheetOpen] = useState(false);+ const [addedHosts, setAddedHosts] = useState<Set<string>>(() => new Set());++ 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, {+ 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,+ isPending,+ isPlaceholderData,+ isError,+ isFetching,+ isRefetching,+ refetch,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ isFetchNextPageError+ } = history;++ const pages = useMemo(() => {+ if (!data) return undefined;+ 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.+ useEffect(() => {+ if (!hasUploadingChunks) return undefined;+ const timer = setTimeout(() => {+ setNow(Date.now());+ if (!isLive) refetch({ cancelRefetch: false }).catch(() => {});+ }, UPLOAD_RECHECK_MS);+ return () => clearTimeout(timer);+ }, [hasUploadingChunks, isLive, now, refetch]);+ if (isOverByteBudget && !isPlaceholderData && !isPausedForBudget) pauseForBudget();+ const isLoadError = isError && !data;++ const isEnabled = pages?.[0]?.sessionLogs.enabled ?? false;+ const isRecordable = pages?.[0]?.sessionLogs.isRecordable ?? true;+ 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 }));++ 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]+ );++ 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 isFiltered = hasBrowserFilter || Boolean(range);++ const { searched, searchedUnreadable } = 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+ );+ return {+ searched: totals.searched + pageRecords,+ searchedUnreadable: totals.searchedUnreadable + (isReadable ? 0 : pageRecords)+ };+ },+ { searched: 0, searchedUnreadable: 0 }+ ),+ [data]+ );++ 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+ });+ const [allowance, setAllowance] = useState(nextAllowance);+ if (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.+ const isSearchPaused =+ Boolean(hasNextPage) &&+ !isTruncated &&+ (hasBrowserFilter+ ? searched >= allowance.until+ : searchedUnreadable >= allowance.unreadableUntil);+ 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 scrollRef = useRef<HTMLDivElement>(null);+ const rowVirtualizer = useVirtualizer({+ count: rows.length,+ getScrollElement: () => scrollRef.current,+ estimateSize: () => SESSION_LOG_ROW_HEIGHT,+ overscan: 16+ });+ const virtualRows = rowVirtualizer.getVirtualItems();++ const lastVisibleIndex = virtualRows.length ? virtualRows[virtualRows.length - 1].index : 0;+ useEffect(() => {+ if (+ !hasNextPage ||+ isFetchingNextPage ||+ isFetchNextPageError ||+ isPlaceholderData ||+ isTruncated ||+ isSearchPaused+ )+ return;+ // Not cancelRefetch, so this walk can't cancel a Reload in flight.+ if (isFirstPageLoaded && lastVisibleIndex >= rows.length - 30)+ fetchNextPage({ cancelRefetch: false }).catch(() => {});+ }, [+ lastVisibleIndex,+ rows.length,+ isFirstPageLoaded,+ hasNextPage,+ isFetchingNextPage,+ isFetchNextPageError,+ isPlaceholderData,+ isTruncated,+ isSearchPaused,+ fetchNextPage+ ]);+ const columnCount = proxies.length > 1 ? 8 : 7;+ const overflows = rowVirtualizer.getTotalSize() > (rowVirtualizer.scrollRect?.height ?? Infinity);+ const { newRequestCount, showNewRequests } = useNewRequestsCounter({+ scrollRef,+ visible: rows,+ arrivals,+ resetKey: `${session.id}|${filterKey}`,+ rowHeight: SESSION_LOG_ROW_HEIGHT+ });++ const padTop = virtualRows.length ? virtualRows[0].start : 0;+ const padBottom = virtualRows.length+ ? rowVirtualizer.getTotalSize() - virtualRows[virtualRows.length - 1].end+ : 0;++ const isOpening = (isPending || isPlaceholderData) && visible.length === 0;+ const isSearchFailed = isFiltered && isFetchNextPageError;+ const isWalkingBack =+ isFirstPageLoaded &&+ Boolean(hasNextPage) &&+ !isSearchPaused &&+ !isTruncated &&+ !isFetchNextPageError;+ const isStillSearching = isFiltered && isWalkingBack;+ const isStillLoading = !isFiltered && records.length === 0 && isWalkingBack;++ let noRecordsTitle: string;+ let noRecordsDescription: string;+ let noRecordsLiveState: LiveState | null = null;+ if (isOpening) {+ noRecordsTitle = "Loading requests";+ noRecordsDescription = "";+ } else if (isLoadError) {+ noRecordsTitle = "Failed to load session logs";+ noRecordsDescription = "Something went wrong while loading this session's requests.";+ } else if (isSearchFailed) {+ noRecordsTitle = "Failed to search older requests";+ noRecordsDescription = "Something went wrong while loading older requests.";+ } else if (isFetchNextPageError) {+ noRecordsTitle = "Couldn't load older requests";+ noRecordsDescription = "";+ } else if (isStillSearching) {+ noRecordsTitle = "Searching older requests";+ noRecordsDescription = "";+ } else if (isStillLoading) {+ noRecordsTitle = "Loading requests";+ noRecordsDescription = "";+ } else if (gaps.length > 0 && records.length === 0 && !hasNextPage) {+ noRecordsTitle = "Session logs unavailable";+ noRecordsDescription = "None of this session's logs could be loaded.";+ } else if (isSearchPaused && searchedBackTo) {+ noRecordsTitle = `No ${hasBrowserFilter ? "matching" : "readable"} requests since ${format(+ searchedBackTo,+ "MMM d, h:mm a"+ )}`;+ 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(+ range.startDate,+ "MMM d, yyyy HH:mm"+ )} 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.";+ } else if (liveState === "live") {+ noRecordsLiveState = liveState;+ noRecordsTitle = "Waiting for requests";+ noRecordsDescription = "Requests made through a proxy show up here within about a minute.";+ } else if (liveState === "reconnecting") {+ noRecordsLiveState = liveState;+ noRecordsTitle = "Couldn't check for new requests";+ noRecordsDescription = `Trying again every ${AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS / 1000} seconds.`;+ } else if (liveState === "ended") {+ noRecordsLiveState = liveState;+ noRecordsTitle = "Nothing recorded yet";+ noRecordsDescription = "Its last requests can take up to a minute to show up.";+ } else {+ 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");++ const retryButton = (+ <Button+ variant="outline"+ size="sm"+ isPending={isRefetching}+ onClick={() => refetch().catch(() => {})}+ >+ Reload+ </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.";+ }++ return (+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>Session logs can't be read</EmptyTitle>+ <EmptyDescription>{unreadableDescription}</EmptyDescription>+ </EmptyHeader>+ {isAdmin && (+ <div className="flex gap-2">+ {isConnectionUnusable && retryButton}+ <Button variant="av" asChild>+ <Link+ to="/organizations/$orgId/agent-vault/settings"+ params={{ orgId: currentOrg.id }}+ >+ Go to Settings+ </Link>+ </Button>+ </div>+ )}+ </Empty>+ );+ }++ if (!isPending && !isPlaceholderData && !isLoadError && !isEnabled && !hasChunks && !range) {+ if (!subscription.agentVaultByoS3) {+ return (+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>Session logs aren't on your plan</EmptyTitle>+ <EmptyDescription>+ {isAdmin+ ? "Upgrade to record what your agents reach."+ : "Ask an Agent Vault administrator about upgrading."}+ </EmptyDescription>+ </EmptyHeader>+ {isAdmin && (+ <Button variant="av" onClick={() => setIsUpgradeOpen(true)}>+ Upgrade+ </Button>+ )}+ <AgentVaultSessionLogUpgradeModal+ isOpen={isUpgradeOpen}+ onOpenChange={setIsUpgradeOpen}+ />+ </Empty>+ );+ }++ const offDescription = isAdmin+ ? "Point Agent Vault at a bucket under Settings to start recording what your agents reach."+ : "Ask an Agent Vault administrator to turn it on.";++ return (+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>Session logs are off</EmptyTitle>+ <EmptyDescription>{offDescription}</EmptyDescription>+ </EmptyHeader>+ {isAdmin && (+ <Button variant="av" asChild>+ <Link to="/organizations/$orgId/agent-vault/settings" params={{ orgId: currentOrg.id }}>+ Go to Settings+ </Link>+ </Button>+ )}+ </Empty>+ );+ }++ if (+ !isPending &&+ !isPlaceholderData &&+ !isLoadError &&+ isEnabled &&+ !isRecordable &&+ !hasChunks+ ) {+ return (+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>Session logs aren't available for this session</EmptyTitle>+ <EmptyDescription>+ To record requests, create a new session and run it through a proxy on the latest+ Infisical CLI.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ );+ }++ return (+ <div className="flex h-full min-h-0 flex-col gap-4">+ <div className="flex flex-wrap items-center gap-2">+ <div className="min-w-56 flex-1">+ <InputGroup>+ <InputGroupAddon>+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ value={search}+ onChange={(event) => setSearch(event.target.value)}+ placeholder="Search host, path, method or service..."+ />+ {search && (+ <InputGroupAddon align="inline-end">+ <IconButton+ variant="ghost"+ size="xs"+ aria-label="Clear search"+ onClick={() => setSearch("")}+ >+ <XIcon />+ </IconButton>+ </InputGroupAddon>+ )}+ </InputGroup>+ </div>+ <Select+ value={decisionFilter}+ onValueChange={(value) => setDecisionFilter(value as DecisionFilter)}+ >+ <SelectTrigger aria-label="Filter by outcome">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper">+ <SelectItem value="all">All Outcomes</SelectItem>+ {Object.entries(DECISION_PRESENTATION).map(+ ([value, { label, icon: Icon, iconClassName }]) => (+ <SelectItem key={value} value={value}>+ <span className="flex items-center gap-2">+ <Icon className={iconClassName} />+ {label}+ </span>+ </SelectItem>+ )+ )}+ </SelectContent>+ </Select>+ <DateRangeFilter+ accent="av"+ size="md"+ isActive={Boolean(range)}+ inactiveLabel="Entire Session"+ showTimezoneToggle={false}+ earliestDate={new Date(session.createdAt)}+ showRelativeRanges={isActive}+ 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 && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ <div className="flex flex-col gap-1">+ <p>+ None of this session's logs could be downloaded from the bucket. The+ bucket's CORS rule may not allow this origin, or this network may block the+ bucket.+ </p>+ {!isAdmin && (+ <p>Ask an Agent Vault administrator to check the bucket's CORS rule.</p>+ )}+ </div>+ <AlertAction className="flex gap-2">+ {retryButton}+ {isAdmin && (+ <Button variant="outline" size="sm" asChild>+ <Link+ to="/organizations/$orgId/agent-vault/settings"+ params={{ orgId: currentOrg.id }}+ >+ Go to Settings+ </Link>+ </Button>+ )}+ </AlertAction>+ </AlertDescription>+ </Alert>+ )}++ {!isUnreachable && gaps.length > 0 && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ <div className="flex flex-col gap-1">+ {groupSessionLogGaps(gaps).map(({ reason, recordCount }) => (+ <span key={reason}>+ {recordCount.toLocaleString()} {recordCount === 1 ? "request" : "requests"}{" "}+ {GAP_EXPLANATION[reason][recordCount === 1 ? "one" : "many"]}.+ </span>+ ))}+ </div>+ {!isFetchNextPageError &&+ gaps.some((gap) => gap.reason === "fetch" || gap.reason === "refused") && (+ <AlertAction>{retryButton}</AlertAction>+ )}+ </AlertDescription>+ </Alert>+ )}++ {visible.length === 0 ? (+ <Empty className="border">+ <EmptyHeader>+ {(isOpening || isStillSearching || isStillLoading) && <Spinner size="sm" />}+ {noRecordsLiveState && <LiveStateBadge state={noRecordsLiveState} />}+ <EmptyTitle>{noRecordsTitle}</EmptyTitle>+ {noRecordsDescription && <EmptyDescription>{noRecordsDescription}</EmptyDescription>}+ </EmptyHeader>+ {noRecordsLiveState === "reconnecting" && (+ <Button variant="outline" size="sm" isPending={live.isFetching} onClick={retryLive}>+ Check Now+ </Button>+ )}+ {isSearchPaused && !isFetchNextPageError && (+ <Button variant="outline" size="sm" onClick={searchOlder}>+ Search Older Requests+ </Button>+ )}+ {isFetchNextPageError && (+ <Button+ variant="outline"+ size="sm"+ isPending={isFetchingNextPage}+ onClick={() => fetchNextPage().catch(() => {})}+ >+ {isSearchFailed ? "Search Again" : "Retry"}+ </Button>+ )}+ {isLoadError && (+ <Button+ variant="outline"+ size="sm"+ isPending={isFetching}+ onClick={() => refetch().catch(() => {})}+ >+ Reload+ </Button>+ )}+ </Empty>+ ) : (+ <Table+ 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")}+ 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>+ <TableHead className="w-24">Upstream</TableHead>+ <TableHead className="w-36">Outcome</TableHead>+ <TableHead variant="action" className={canAddService ? "w-36" : "w-12"} />+ </TableRow>+ {liveState && (+ <LiveStatusRow+ state={liveState}+ columnCount={columnCount}+ recordCount={records.length}+ isRetrying={live.isFetching}+ onRetry={retryLive}+ newRequestCount={newRequestCount}+ onShowNewRequests={showNewRequests}+ />+ )}+ </TableHeader>+ <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 isAddable =+ canAddService &&+ !record.service &&+ (record.decision === AgentVaultSessionLogDecision.Blocked ||+ record.decision === AgentVaultSessionLogDecision.Passthrough) &&+ !addedHosts.has(hostPatternFor(record));+ return (+ <SessionLogRow+ key={sessionLogRecordKey(record)}+ record={record}+ arrivedAt={arrivals.get(sessionLogRecordKey(record))}+ proxyName={proxyNames.get(record.proxyId)}+ showProxy={proxies.length > 1}+ accessBundleName={accessBundle?.name}+ onAddService={+ isAddable+ ? () => {+ setServiceHost(hostPatternFor(record));+ setIsServiceSheetOpen(true);+ }+ : undefined+ }+ />+ );+ })}+ {padBottom > 0 && <tr style={{ height: padBottom }} />}+ {(isFetchingNextPage ||+ isFetchNextPageError ||+ isSearchPaused ||+ (!hasNextPage && overflows)) && (+ <TableRow className="hover:bg-transparent">+ <TableCell colSpan={columnCount} className="text-center text-xs text-muted">+ {isFetchingNextPage && (+ <span className="flex items-center justify-center gap-2">+ <Spinner size="xs" />+ Loading more+ </span>+ )}+ {!isFetchingNextPage && isFetchNextPageError && (+ <span className="flex items-center justify-center gap-1">+ Couldn't load older requests ·+ <Button+ variant="link"+ size="xs"+ onClick={() => fetchNextPage().catch(() => {})}+ >+ Retry+ </Button>+ </span>+ )}+ {!isFetchingNextPage &&+ !isFetchNextPageError &&+ isSearchPaused &&+ searchedBackTo && (+ <span className="flex items-center justify-center gap-1">+ Searched back to {format(searchedBackTo, "MMM d, h:mm a")} ·+ <Button variant="link" size="xs" onClick={searchOlder}>+ Search Older Requests+ </Button>+ </span>+ )}+ {!isFetchingNextPage &&+ !isFetchNextPageError &&+ !isSearchPaused &&+ "No more requests"}+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </Table>+ )}++ {isTruncated && !(liveState === "paused" && visible.length > 0) && (+ <p className="text-xs text-muted">+ Showing the most recent {records.length.toLocaleString()} requests. Pick a time range to+ see further back.+ {liveState === "paused" && " Live updates are paused."}+ </p>+ )}++ {canAddService && accessBundle.id && (+ <ServiceSheet+ isOpen={isServiceSheetOpen}+ onOpenChange={setIsServiceSheetOpen}+ accessBundleId={accessBundle.id}+ prefillHost={serviceHost ?? undefined}+ onSaved={() => {+ if (serviceHost) setAddedHosts((prev) => new Set(prev).add(serviceHost));+ }}+ />+ )}+ </div>+ );+};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.tsnew file mode 100644index 0000000000..14b5fcea9e--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.ts@@ -0,0 +1,166 @@+import assert from "node:assert/strict";+import { describe, it } from "vitest";++import { AgentVaultSessionLogDecision } from "@app/hooks/api/agentVault/enums";+import { TAgentVaultSessionLogRecord } from "@app/hooks/api/agentVault/types";++import {+ chunkIdTime,+ findRowShift,+ groupSessionLogGaps,+ interleaveSessionLogDrops,+ matchesSessionLogSearch+} from "./SessionLogsPanel.utils";++const record = (seq: number): TAgentVaultSessionLogRecord => ({+ ts: new Date(Date.UTC(2026, 8, 23, 10, 0, 0, seq)).toISOString(),+ seq,+ proxyId: "proxy-1",+ method: "GET",+ host: "api.github.com",+ port: "443",+ path: "/",+ status: 200,+ decision: AgentVaultSessionLogDecision.Passthrough,+ service: null,+ accessBundle: null+});++const rows = (...seqs: number[]) =>+ seqs.map((seq) => ({ kind: "record" as const, record: record(seq) }));++describe("findRowShift", () => {+ it("moves the row down by however many rows arrived at the top", () => {+ assert.equal(findRowShift(rows(5, 4, 3, 2, 1), rows(8, 7, 6, 5, 4, 3, 2, 1), 2), 3);+ });++ it("moves the row down when a late chunk slots rows in above it, not only at the top", () => {+ assert.equal(findRowShift(rows(9, 5, 4, 1), rows(9, 7, 6, 5, 4, 1), 2), 2);+ });++ it("leaves the row where it is when rows land below it", () => {+ assert.equal(findRowShift(rows(9, 8, 5), rows(9, 8, 5, 3, 2), 1), 0);+ });++ it("moves the row up when rows above it are no longer shown", () => {+ assert.equal(findRowShift(rows(9, 8, 7, 6), rows(9, 6), 3), -2);+ });++ it("has nothing to hold when the row itself is no longer shown", () => {+ assert.equal(findRowShift(rows(9, 8, 7), rows(9, 7), 1), null);+ });++ it("has nothing to hold past the end of what was shown", () => {+ assert.equal(findRowShift(rows(9, 8), rows(10, 9, 8), 5), null);+ });+});++describe("chunkIdTime", () => {+ it("reads the time from the example UUIDv7 in RFC 9562", () => {+ assert.equal(+ chunkIdTime("017f22e2-79b0-7cc3-98c4-dc0c0c07398f").toISOString(),+ "2022-02-22T19:22:22.000Z"+ );+ });+});++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+ });++ 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 }+ ]+ );+ });+});++describe("matchesSessionLogSearch", () => {+ const repoRequest = { ...record(1), path: "/repos/infisical/cli" };++ it("matches a host and path pasted together", () => {+ assert.equal(matchesSessionLogSearch(repoRequest, "api.github.com/repos/infisical"), true);+ });++ it("ignores the scheme of a pasted URL", () => {+ assert.equal(matchesSessionLogSearch(repoRequest, "https://api.github.com/repos"), true);+ assert.equal(matchesSessionLogSearch(repoRequest, "HTTP://api.github.com"), true);+ });++ it("matches a host with its port", () => {+ assert.equal(matchesSessionLogSearch(repoRequest, "api.github.com:443/repos"), true);+ assert.equal(matchesSessionLogSearch(repoRequest, "api.github.com:8443/repos"), false);+ });++ it("ignores the query string and fragment of a pasted URL", () => {+ assert.equal(+ matchesSessionLogSearch(repoRequest, "https://api.github.com/repos/infisical/cli?page=2"),+ true+ );+ assert.equal(matchesSessionLogSearch(repoRequest, "api.github.com/repos#readme"), true);+ });++ it("matches everything when only a scheme is typed", () => {+ assert.equal(matchesSessionLogSearch(repoRequest, "https://"), true);+ });++ it("does not match a path on a different host", () => {+ 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.tsnew file mode 100644index 0000000000..63aedd6af4--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.ts@@ -0,0 +1,158 @@+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;+};++export const findRowShift = (+ before: TSessionLogRow[],+ after: TSessionLogRow[],+ index: number+): number | null => {+ const row = before[index];+ if (!row) return null;+ const key = sessionLogRowKey(row);+ const moved = after.findIndex((candidate) => sessionLogRowKey(candidate) === key);+ return moved < 0 ? null : moved - index;+};++const HTTP_STATUS_TEXT: Record<number, string> = {+ 100: "Continue",+ 101: "Switching Protocols",+ 102: "Processing",+ 103: "Early Hints",+ 200: "OK",+ 201: "Created",+ 202: "Accepted",+ 203: "Non-Authoritative Information",+ 204: "No Content",+ 205: "Reset Content",+ 206: "Partial Content",+ 207: "Multi-Status",+ 208: "Already Reported",+ 226: "IM Used",+ 300: "Multiple Choices",+ 301: "Moved Permanently",+ 302: "Found",+ 303: "See Other",+ 304: "Not Modified",+ 305: "Use Proxy",+ 307: "Temporary Redirect",+ 308: "Permanent Redirect",+ 400: "Bad Request",+ 401: "Unauthorized",+ 402: "Payment Required",+ 403: "Forbidden",+ 404: "Not Found",+ 405: "Method Not Allowed",+ 406: "Not Acceptable",+ 407: "Proxy Authentication Required",+ 408: "Request Timeout",+ 409: "Conflict",+ 410: "Gone",+ 411: "Length Required",+ 412: "Precondition Failed",+ 413: "Content Too Large",+ 414: "URI Too Long",+ 415: "Unsupported Media Type",+ 416: "Range Not Satisfiable",+ 417: "Expectation Failed",+ 421: "Misdirected Request",+ 422: "Unprocessable Content",+ 423: "Locked",+ 424: "Failed Dependency",+ 425: "Too Early",+ 426: "Upgrade Required",+ 428: "Precondition Required",+ 429: "Too Many Requests",+ 431: "Request Header Fields Too Large",+ 451: "Unavailable For Legal Reasons",+ 500: "Internal Server Error",+ 501: "Not Implemented",+ 502: "Bad Gateway",+ 503: "Service Unavailable",+ 504: "Gateway Timeout",+ 505: "HTTP Version Not Supported",+ 506: "Variant Also Negotiates",+ 507: "Insufficient Storage",+ 508: "Loop Detected",+ 510: "Not Extended",+ 511: "Network Authentication Required"+};++export const httpStatusLabel = (status: number) =>+ HTTP_STATUS_TEXT[status] ? `${status} ${HTTP_STATUS_TEXT[status]}` : String(status);++export const chunkIdTime = (chunkId: string) =>+ new Date(parseInt(chunkId.replace(/-/g, "").slice(0, 12), 16));++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 }));+};++// Records hold no query string, so a pasted URL is cut back to the host and path it was sent to.+export const sessionLogSearchTerm = (search: string) =>+ search+ .trim()+ .toLowerCase()+ .replace(/^https?:\/\//, "")+ .replace(/[?#].*$/, "");++export const matchesSessionLogSearch = (record: TAgentVaultSessionLogRecord, search: string) => {+ const term = sessionLogSearchTerm(search);+ if (!term) return true;+ const host = record.host.toLowerCase();+ const path = record.path.toLowerCase();+ return [+ host,+ path,+ record.method.toLowerCase(),+ (record.service ?? "").toLowerCase(),+ `${host}${path}`,+ `${host}:${record.port}${path}`+ ].some((field) => field.includes(term));+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionStatusBadge.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionStatusBadge.tsxindex cedff31319..e578f1895b 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionStatusBadge.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionStatusBadge.tsx@@ -1,16 +1,31 @@-import { BanIcon, CircleCheckIcon, CircleSlashIcon } from "lucide-react";+import { ActivityIcon, BanIcon, TimerIcon } from "lucide-react";import { Badge } from "@app/components/v3";import { AgentVaultSessionStatus } from "@app/hooks/api/agentVault";-const STATUS_PRESENTATION = {- [AgentVaultSessionStatus.Active]: { label: "Active", variant: "success", icon: CircleCheckIcon },- [AgentVaultSessionStatus.Revoked]: { label: "Revoked", variant: "danger", icon: BanIcon },- [AgentVaultSessionStatus.Expired]: { label: "Expired", variant: "neutral", icon: CircleSlashIcon }+export const SESSION_STATUS_PRESENTATION = {+ [AgentVaultSessionStatus.Active]: {+ label: "Active",+ variant: "success",+ icon: ActivityIcon,+ iconClassName: "text-success"+ },+ [AgentVaultSessionStatus.Revoked]: {+ label: "Revoked",+ variant: "danger",+ icon: BanIcon,+ iconClassName: "text-danger"+ },+ [AgentVaultSessionStatus.Expired]: {+ label: "Expired",+ variant: "neutral",+ icon: TimerIcon,+ iconClassName: "text-neutral"+ }} as const;export const SessionStatusBadge = ({ status }: { status: AgentVaultSessionStatus }) => {- const { label, variant, icon: Icon } = STATUS_PRESENTATION[status];+ const { label, variant, icon: Icon } = SESSION_STATUS_PRESENTATION[status];return (<Badge variant={variant}>diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/useNewRequestsCounter.ts b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/useNewRequestsCounter.tsnew file mode 100644index 0000000000..f04c317f5f--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/useNewRequestsCounter.ts@@ -0,0 +1,67 @@+import { RefObject, useEffect, useLayoutEffect, useRef, useState } from "react";++import { sessionLogRecordKey } from "@app/hooks/api/agentVault";++import { findRowShift, TSessionLogRow } from "./SessionLogsPanel.utils";++type Params = {+ scrollRef: RefObject<HTMLDivElement | null>;+ visible: TSessionLogRow[];+ arrivals: Map<string, number>;+ resetKey: string;+ rowHeight: number;+};++// Keeps the rows a reader has scrolled to in place as new ones land above them, and counts the new ones.+export const useNewRequestsCounter = ({+ scrollRef,+ visible,+ arrivals,+ resetKey,+ rowHeight+}: Params) => {+ const [newRequests, setNewRequests] = useState({ key: resetKey, count: 0 });+ if (newRequests.key !== resetKey) {+ setNewRequests({ key: resetKey, count: 0 });+ }++ const shownBefore = useRef(visible);+ // Only arrivals stamped since the last change count, so rows a filter change reveals aren't new.+ const countedAt = useRef(Date.now());+ useLayoutEffect(() => {+ const before = shownBefore.current;+ shownBefore.current = visible;+ const since = countedAt.current;+ countedAt.current = Date.now();+ const scroller = scrollRef.current;+ if (!scroller || scroller.scrollTop === 0) return;+ const top = Math.floor(scroller.scrollTop / rowHeight);+ const shift = findRowShift(before, visible, top);+ 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;+ if (landedAbove) setNewRequests((prev) => ({ ...prev, count: prev.count + landedAbove }));+ }, [visible, arrivals, scrollRef, rowHeight]);++ const hasNewRequests = newRequests.count > 0;+ useEffect(() => {+ const scroller = scrollRef.current;+ if (!scroller || !hasNewRequests) return undefined;+ const clearAtTop = () => {+ if (scroller.scrollTop < 1) setNewRequests((prev) => ({ ...prev, count: 0 }));+ };+ scroller.addEventListener("scroll", clearAtTop, { passive: true });+ return () => scroller.removeEventListener("scroll", clearAtTop);+ }, [hasNewRequests, scrollRef]);++ const showNewRequests = () => {+ scrollRef.current?.scrollTo({ top: 0, behavior: "smooth" });+ setNewRequests((prev) => ({ ...prev, count: 0 }));+ };++ return { newRequestCount: newRequests.count, showNewRequests };+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/useSessionLogsLiveTail.ts b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/useSessionLogsLiveTail.tsnew file mode 100644index 0000000000..9584398ff1--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/useSessionLogsLiveTail.ts@@ -0,0 +1,76 @@+import { useEffect, useState } from "react";++import { type DateRangeFilterResult } from "@app/components/v3";+import { AgentVaultSessionStatus } from "@app/hooks/api/agentVault";+import { TAgentVaultSession } from "@app/hooks/api/agentVault/types";++// A proxy uploads what it still holds on its next flush, up to a minute after the session ends, so+// the view keeps checking for new requests a while longer.+const SESSION_END_TAIL_MS = 2 * 60_000;++const MAX_TIMEOUT_MS = 2 ** 31 - 1;++const endTailDeadline = (session: TAgentVaultSession) => {+ const endedAt =+ session.revokedAt ??+ (session.status === AgentVaultSessionStatus.Expired ? session.expiresAt : null);+ return endedAt ? new Date(endedAt).getTime() + SESSION_END_TAIL_MS : null;+};++// Decides whether the panel polls for new requests: while the session runs, for a short while after it+// ends, and only while the picked range still reaches the present.+export const useSessionLogsLiveTail = (session: TAgentVaultSession) => {+ const [range, setRange] = useState<DateRangeFilterResult | null>(null);+ const [isRangeOpen, setIsRangeOpen] = useState(true);+ const applyRange = (next: DateRangeFilterResult | null) => {+ setRange(next);+ setIsRangeOpen(!next || next.endDate.getTime() > Date.now());+ };+ useEffect(() => {+ if (!range || !isRangeOpen) return undefined;+ const remaining = range.endDate.getTime() - Date.now();+ if (remaining > MAX_TIMEOUT_MS) return undefined;+ const timer = setTimeout(() => setIsRangeOpen(false), Math.max(remaining, 0));+ return () => clearTimeout(timer);+ }, [range, isRangeOpen]);++ const isActive = session.status === AgentVaultSessionStatus.Active;+ const tailEndsAt = endTailDeadline(session);+ const [endTail, setEndTail] = useState(() => ({+ endsAt: tailEndsAt,+ isOpen: tailEndsAt !== null && tailEndsAt > Date.now()+ }));+ if (endTail.endsAt !== tailEndsAt) {+ setEndTail({ endsAt: tailEndsAt, isOpen: tailEndsAt !== null && tailEndsAt > Date.now() });+ }+ useEffect(() => {+ const { endsAt, isOpen } = endTail;+ if (endsAt === null || !isOpen) return undefined;+ const timer = setTimeout(+ () => setEndTail({ endsAt, isOpen: false }),+ Math.max(endsAt - Date.now(), 0)+ );+ return () => clearTimeout(timer);+ }, [endTail]);+ const isTailingEnd = endTail.endsAt === tailEndsAt && endTail.isOpen;++ const liveScope = [session.id, range?.startDate.getTime(), range?.endDate.getTime()].join("|");+ const [budgetLatch, setBudgetLatch] = useState({ scope: liveScope, isOver: false });+ if (budgetLatch.scope !== liveScope) {+ setBudgetLatch({ scope: liveScope, isOver: false });+ }+ const isPausedForBudget = budgetLatch.scope === liveScope && budgetLatch.isOver;+ const pauseForBudget = () => setBudgetLatch({ scope: liveScope, isOver: true });++ const canTail = (isActive || isTailingEnd) && isRangeOpen;++ return {+ range,+ applyRange,+ isActive,+ canTail,+ isLive: canTail && !isPausedForBudget,+ isPausedForBudget,+ pauseForBudget+ };+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/route.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/route.tsxindex d9b9c64ac0..060c59bde7 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/route.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/route.tsx@@ -1,4 +1,7 @@-import { createFileRoute } from "@tanstack/react-router";+import { createFileRoute, stripSearchParams } from "@tanstack/react-router";+import { zodValidator } from "@tanstack/zod-adapter";++import { agentVaultSheetSearchParams } from "@app/hooks/useAgentVaultSheetState";import { AgentVaultSessionsPage } from "./AgentVaultSessionsPage";@@ -6,6 +9,8 @@ export const Route = createFileRoute("/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions")({component: AgentVaultSessionsPage,+ validateSearch: zodValidator(agentVaultSheetSearchParams),+ search: { middlewares: [stripSearchParams({ sessionId: undefined })] },beforeLoad: ({ context }) => {return { breadcrumbs: [...context.breadcrumbs, { label: "Sessions" }] };}diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/AgentVaultSettingsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/AgentVaultSettingsPage.tsxnew file mode 100644index 0000000000..c236b4877c--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/AgentVaultSettingsPage.tsx@@ -0,0 +1,40 @@+import { Helmet } from "react-helmet";+import { useTranslation } from "react-i18next";+import { SettingsIcon } from "lucide-react";++import { AccessRestrictedDialog, PageHeader } from "@app/components/v3";+import { useProjectPermission } from "@app/context";+import { ProjectType } from "@app/hooks/api/projects/types";+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";++import { SessionLogAlerts } from "./components/SessionLogAlerts";+import { SessionLogSection } from "./components/SessionLogSection";++export const AgentVaultSettingsPage = () => {+ const { t } = useTranslation();+ const { hasProjectRole } = useProjectPermission();+ const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);++ return (+ <div className="mx-auto mb-6 flex w-full max-w-8xl flex-col gap-8">+ <Helmet>+ <title>{t("common.head-title", { title: "Settings" })}</title>+ </Helmet>++ <PageHeader+ scope={ProjectType.AgentVault}+ icon={SettingsIcon}+ title="Settings"+ description="Configure session logs and the connections Agent Vault uses."+ />+ {isAdmin ? (+ <>+ <SessionLogAlerts />+ <SessionLogSection />+ </>+ ) : (+ <AccessRestrictedDialog />+ )}+ </div>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/AwsSetupDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/AwsSetupDialog.tsxnew file mode 100644index 0000000000..169b44895a--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/AwsSetupDialog.tsx@@ -0,0 +1,228 @@+import { useEffect, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { TriangleAlertIcon } from "lucide-react";++import {+ Alert,+ AlertDescription,+ AlertTitle,+ Button,+ CodeBlock,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger+} from "@app/components/v3";+import { useOrganization } from "@app/context";+import { agentVaultKeys, useGetAgentVaultSessionLogCorsProbe } from "@app/hooks/api/agentVault";++const iamPolicyFor = (bucket: string, keyPrefix: string) => {+ const objects = `arn:aws:s3:::${bucket || "<bucket>"}/${keyPrefix ? `${keyPrefix}/` : ""}*`;+ return JSON.stringify(+ {+ Version: "2012-10-17",+ Statement: [+ {+ Effect: "Allow",+ Action: ["s3:PutObject", "s3:GetObject"],+ Resource: objects+ },+ {+ Effect: "Allow",+ Action: ["s3:ListBucket"],+ Resource: `arn:aws:s3:::${bucket || "<bucket>"}`+ }+ ]+ },+ null,+ 2+ );+};++const corsPolicyFor = (origin: string) =>+ JSON.stringify(+ [+ {+ AllowedHeaders: ["*"],+ AllowedMethods: ["GET"],+ AllowedOrigins: [origin],+ MaxAgeSeconds: 3000+ }+ ],+ null,+ 2+ );++const Steps = ({ items }: { items: string[] }) => (+ <ol className="flex flex-col gap-1.5 text-xs text-muted">+ {items.map((item, index) => (+ <li key={item} className="flex gap-2">+ <span className="flex size-4 shrink-0 items-center justify-center rounded-full bg-container text-[10px] font-medium text-foreground">+ {index + 1}+ </span>+ {item}+ </li>+ ))}+ </ol>+);++export const HostBlockedMessage = ({ host }: { host: string }) => (+ <>+ Your browser can't reach <span className="font-mono">{host}</span>, because this Infisical+ instance doesn't allow it. Ask whoever runs Infisical to allow that host.+ </>+);++type TabValue = "policy" | "cors";++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ bucket: string | null;+ keyPrefix: string | null;+ isUnsaved?: boolean;+};++export const AwsSetupDialog = ({+ isOpen,+ onOpenChange,+ bucket,+ keyPrefix,+ isUnsaved = false+}: Props) => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ const { data: savedReadCheck } = useGetAgentVaultSessionLogCorsProbe(isOpen && !isUnsaved);+ // The check reads the saved bucket, so it says nothing about a bucket that is only typed in.+ const readCheck = isUnsaved ? null : savedReadCheck;+ const readAccess = readCheck?.status;+ const isCorsMissing = readAccess === "cors-missing";+ // Any answer S3 let the browser read proves the CORS rule is already attached.+ const hasCorsRule = readAccess === "access-denied" || readAccess === "readable";+ const [tab, setTab] = useState<TabValue>("policy");+ const [hasPickedTab, setHasPickedTab] = useState(false);++ const pickTab = (next: TabValue) => {+ setHasPickedTab(true);+ setTab(next);+ };++ const handleOpenChange = (next: boolean) => {+ // Re-checked on close, so the page's warning clears once the rule or policy is attached.+ if (!next) {+ queryClient.invalidateQueries({+ queryKey: agentVaultKeys.sessionLogCorsProbe(currentOrg.id)+ });+ }+ onOpenChange(next);+ };++ useEffect(() => {+ if (!isOpen) return;+ setTab(isCorsMissing ? "cors" : "policy");+ setHasPickedTab(false);+ }, [isOpen]);++ useEffect(() => {+ if (isCorsMissing && !hasPickedTab) setTab("cors");+ }, [isCorsMissing, hasPickedTab]);++ return (+ <Dialog open={isOpen} onOpenChange={handleOpenChange}>+ <DialogContent className="max-w-3xl">+ <DialogHeader>+ <DialogTitle>AWS Setup</DialogTitle>+ <DialogDescription>+ {isUnsaved+ ? "Saving with session logs on checks that Infisical can write to the bucket, so attach the IAM policy first. The CORS rule lets your browser read records back."+ : "Two things to set up in AWS so Infisical can write records, and so your browser can read them back."}+ </DialogDescription>+ </DialogHeader>++ <DialogBody className="space-y-4">+ {readCheck?.status === "host-blocked" && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ <HostBlockedMessage host={readCheck.host} />+ </AlertDescription>+ </Alert>+ )}+ <Tabs value={tab} onValueChange={(next) => pickTab(next as TabValue)}>+ <TabsList variant="av">+ <TabsTrigger value="policy">1. IAM Policy</TabsTrigger>+ <TabsTrigger value="cors">2. CORS Rule</TabsTrigger>+ </TabsList>++ <TabsContent value="policy" className="space-y-4">+ {readAccess === "access-denied" && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertTitle>This connection is not allowed to read from this bucket.</AlertTitle>+ <AlertDescription>+ Nobody can read session logs back until this policy is attached, and new logs+ may not be stored.+ </AlertDescription>+ </Alert>+ )}+ <Steps+ items={[+ "In AWS, open IAM, then Policies, then Create policy.",+ "Select the JSON tab and paste the policy below.",+ "Attach it to the IAM user or role this connection authenticates as."+ ]}+ />+ <CodeBlock+ label="Lets the connection's credentials write and read objects"+ value={iamPolicyFor(bucket ?? "", keyPrefix ?? "")}+ />+ </TabsContent>++ <TabsContent value="cors" className="space-y-4">+ {isCorsMissing && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertTitle>This bucket is not allowing requests from this origin.</AlertTitle>+ <AlertDescription>+ Session logs are still stored, but nobody can read them back until this rule is+ attached.+ </AlertDescription>+ </Alert>+ )}+ <Steps+ items={[+ `In AWS, open S3 and select the ${bucket ? `${bucket} bucket` : "bucket"}.`,+ "Open the Permissions tab and find Cross-origin resource sharing (CORS).",+ "Select Edit, paste the rule below, and save."+ ]}+ />+ <CodeBlock+ label="Lets your browser read the records back"+ value={corsPolicyFor(window.location.origin)}+ />+ </TabsContent>+ </Tabs>+ </DialogBody>++ <DialogFooter>+ {tab === "policy" && !hasCorsRule ? (+ <Button variant="av" type="button" onClick={() => pickTab("cors")}>+ Next+ </Button>+ ) : (+ <Button variant="av" type="button" onClick={() => handleOpenChange(false)}>+ Done+ </Button>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogAlerts.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogAlerts.tsxnew file mode 100644index 0000000000..bbe15eefaa--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogAlerts.tsx@@ -0,0 +1,90 @@+import { useState } from "react";+import { CircleAlertIcon, TriangleAlertIcon } from "lucide-react";++import { AgentVaultSessionLogUpgradeModal } from "@app/components/agent-vault/AgentVaultSessionLogUpgradeModal";+import { Alert, AlertAction, AlertDescription, Button } from "@app/components/v3";+import { useSubscription } from "@app/context";+import {+ areAgentVaultSessionLogsOn,+ isAgentVaultSessionLogPlanLapsed+} from "@app/helpers/agentVaultSessionLogs";+import {+ useGetAgentVaultSessionLogCorsProbe,+ useGetAgentVaultSessionLogHealth,+ useGetAgentVaultSessionLogSettings+} from "@app/hooks/api/agentVault";++import { SessionLogReadAccessAlert } from "./SessionLogReadAccessAlert";++export const SessionLogAlerts = () => {+ const { data: config, isPending: isSettingsPending } = useGetAgentVaultSessionLogSettings();+ const { data: health, isPending: isHealthPending } = useGetAgentVaultSessionLogHealth();+ const { data: readCheck } = useGetAgentVaultSessionLogCorsProbe();+ const { subscription } = useSubscription();+ const [isUpgradeOpen, setIsUpgradeOpen] = useState(false);++ const hasDestination = Boolean(config?.bucket);+ const isLapsed = Boolean(config && isAgentVaultSessionLogPlanLapsed(config, subscription));+ const isRecording = config ? areAgentVaultSessionLogsOn(config) : false;+ const isReadBlocked = Boolean(readCheck && readCheck.status !== "readable");++ const notRecordingReason = (() => {+ if (!config?.enabled) {+ if (!config?.appConnectionId) {+ return "Session logs are off, and without an AWS connection the logs already in the bucket can't be read.";+ }+ if (health?.connectionError || 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.";+ })();++ return (+ <>+ {health?.connectionError && (+ <Alert variant="danger">+ <CircleAlertIcon />+ <AlertDescription>{health.connectionError}</AlertDescription>+ </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 />+ <AlertDescription>+ <p>+ Your plan no longer includes session logs, so new requests aren't recorded.+ {config?.appConnectionId && " Saved logs stay viewable."}+ </p>+ <AlertAction>+ <Button variant="outline" size="sm" onClick={() => setIsUpgradeOpen(true)}>+ Upgrade+ </Button>+ </AlertAction>+ </AlertDescription>+ </Alert>+ )}++ {!isSettingsPending && !isHealthPending && hasDestination && !isLapsed && !isRecording && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>{notRecordingReason}</AlertDescription>+ </Alert>+ )}++ <SessionLogReadAccessAlert />++ <AgentVaultSessionLogUpgradeModal isOpen={isUpgradeOpen} onOpenChange={setIsUpgradeOpen} />+ </>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogConnectionsSheet.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogConnectionsSheet.tsxnew file mode 100644index 0000000000..3e05a8e9ac--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogConnectionsSheet.tsx@@ -0,0 +1,265 @@+import { subject } from "@casl/ability";+import {+ AsteriskIcon,+ CopyIcon,+ InfoIcon,+ MoreHorizontalIcon,+ PencilIcon,+ PlusIcon,+ Trash2Icon+} from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Badge,+ Button,+ DocumentationLinkBadge,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ IconButton,+ ProviderIcon,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetHeader,+ SheetTitle,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";+import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";+import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";+import { usePopUp } from "@app/hooks";+import { useGetAgentVaultSessionLogSettings } from "@app/hooks/api/agentVault";+import { useListAppConnections } from "@app/hooks/api/appConnections";+import { AppConnection } from "@app/hooks/api/appConnections/enums";+import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";+import { DeleteAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components/DeleteAppConnectionModal";+import { EditAppConnectionCredentialsModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components/EditAppConnectionCredentialsModal";+import { EditAppConnectionDetailsModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components/EditAppConnectionDetailsModal";++import { AgentVaultDocsUrls } from "../../agent-vault-docs-urls";++const AWS_CONNECTION = APP_CONNECTION_MAP[AppConnection.AWS];++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+};++export const SessionLogConnectionsSheet = ({ isOpen, onOpenChange }: Props) => {+ const { currentProject } = useProject();+ const { permission } = useProjectPermission();+ const { data: settings } = useGetAgentVaultSessionLogSettings();+ const { data: connections = [], isPending } = useListAppConnections(currentProject.id);+ const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([+ "addConnection",+ "editDetails",+ "editCredentials",+ "deleteConnection"+ ] as const);++ const canCreate = permission.can(+ ProjectPermissionAppConnectionActions.Create,+ ProjectPermissionSub.AppConnections+ );++ const copyConnectionId = (connectionId: string) => {+ navigator.clipboard.writeText(connectionId);+ createNotification({ text: "Connection ID copied to clipboard", type: "info" });+ };++ return (+ <Sheet open={isOpen} onOpenChange={onOpenChange}>+ <SheetContent size="form">+ <SheetHeader>+ <SheetTitle className="flex items-center gap-2">+ Manage Connections+ <DocumentationLinkBadge href={`${AgentVaultDocsUrls.sessionLogs}#connections`} />+ </SheetTitle>+ <SheetDescription>+ AWS connections only Agent Vault can use. Organization connections are edited under+ Integrations.+ </SheetDescription>+ </SheetHeader>++ <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">+ <div className="flex justify-end">+ <Button+ size="sm"+ variant="av"+ isDisabled={!canCreate}+ onClick={() => handlePopUpOpen("addConnection")}+ >+ <PlusIcon />+ Add Connection+ </Button>+ </div>++ {isPending && <Skeleton className="h-16 w-full" />}++ {!isPending && connections.length === 0 && (+ <Empty className="flex-none border">+ <EmptyHeader>+ <EmptyTitle>No connections yet</EmptyTitle>+ <EmptyDescription>+ Add an AWS connection, then choose it when you set up session logs.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ )}++ {!isPending && connections.length > 0 && (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-full">Name</TableHead>+ <TableHead>Method</TableHead>+ <TableHead variant="action" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {connections.map((connection) => {+ const method = getAppConnectionMethodDetails(connection.method);+ const MethodIcon = method.icon;+ const isInUse = connection.id === settings?.appConnectionId;+ const connectionSubject = subject(ProjectPermissionSub.AppConnections, {+ connectionId: connection.id+ });+ const canEdit = permission.can(+ ProjectPermissionAppConnectionActions.Edit,+ connectionSubject+ );+ const canDelete = permission.can(+ ProjectPermissionAppConnectionActions.Delete,+ connectionSubject+ );++ return (+ <TableRow key={connection.id}>+ <TableCell className="max-w-0">+ <div className="flex min-w-0 items-center gap-2">+ <ProviderIcon+ alt={`${AWS_CONNECTION.name} connection`}+ icon={AWS_CONNECTION.image}+ className="w-4 shrink-0"+ />+ <span className="min-w-0 truncate">{connection.name}</span>+ {connection.description && (+ <Tooltip>+ <TooltipTrigger asChild>+ <InfoIcon className="size-3.5 shrink-0 text-muted" />+ </TooltipTrigger>+ <TooltipContent>{connection.description}</TooltipContent>+ </Tooltip>+ )}+ {isInUse && <Badge variant="info">In Use</Badge>}+ </div>+ </TableCell>+ <TableCell>+ <span className="flex items-center gap-1.5">+ <MethodIcon className="size-3.5 text-label/75" />+ {method.name}+ </span>+ </TableCell>+ <TableCell variant="action">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ variant="ghost"+ size="xs"+ aria-label={`Actions for ${connection.name}`}+ >+ <MoreHorizontalIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent sideOffset={2} align="end">+ <DropdownMenuItem onClick={() => copyConnectionId(connection.id)}>+ <CopyIcon />+ Copy Connection ID+ </DropdownMenuItem>+ <DropdownMenuItem+ isDisabled={!canEdit}+ onClick={() => handlePopUpOpen("editDetails", connection)}+ >+ <PencilIcon />+ Edit Details+ </DropdownMenuItem>+ <DropdownMenuItem+ isDisabled={!canEdit}+ onClick={() => handlePopUpOpen("editCredentials", connection)}+ >+ <AsteriskIcon />+ Edit Credentials+ </DropdownMenuItem>+ <Tooltip>+ <TooltipTrigger asChild>+ <div>+ <DropdownMenuItem+ variant="danger"+ isDisabled={!canDelete || isInUse}+ onClick={() => handlePopUpOpen("deleteConnection", connection)}+ >+ <Trash2Icon />+ Delete Connection+ </DropdownMenuItem>+ </div>+ </TooltipTrigger>+ {isInUse && (+ <TooltipContent side="left">+ Session logs use this connection. Choose another one in Configure+ before deleting it.+ </TooltipContent>+ )}+ </Tooltip>+ </DropdownMenuContent>+ </DropdownMenu>+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ )}+ </div>++ <AddAppConnectionModal+ isOpen={popUp.addConnection.isOpen}+ onOpenChange={(isAddOpen) => handlePopUpToggle("addConnection", isAddOpen)}+ projectId={currentProject.id}+ projectType={currentProject.type}+ app={AppConnection.AWS}+ />+ <EditAppConnectionDetailsModal+ isOpen={popUp.editDetails.isOpen}+ onOpenChange={(isEditOpen) => handlePopUpToggle("editDetails", isEditOpen)}+ appConnection={popUp.editDetails.data}+ />+ <EditAppConnectionCredentialsModal+ isOpen={popUp.editCredentials.isOpen}+ onOpenChange={(isEditOpen) => handlePopUpToggle("editCredentials", isEditOpen)}+ appConnection={popUp.editCredentials.data}+ />+ <DeleteAppConnectionModal+ isOpen={popUp.deleteConnection.isOpen}+ onOpenChange={(isDeleteOpen) => handlePopUpToggle("deleteConnection", isDeleteOpen)}+ appConnection={popUp.deleteConnection.data}+ />+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.tsxnew file mode 100644index 0000000000..4e1d7b1a9d--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogModal.tsx@@ -0,0 +1,503 @@+import { useEffect } from "react";+import { Controller, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { z } from "zod";++import { AppConnectionOptionContent } from "@app/components/app-connections";+import { createNotification } from "@app/components/notifications";+import { AwsRegionSelect } from "@app/components/secret-syncs/forms/SecretSyncDestinationFields/shared";+import {+ Alert,+ AlertAction,+ AlertDescription,+ Button,+ Combobox,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DiscardChangesAlertDialog,+ DocumentationLinkBadge,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ FieldLegend,+ FieldSet,+ Input,+ Label,+ ProviderIcon,+ Toggle+} from "@app/components/v3";+import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";+import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";+import { APP_CONNECTION_MAP, AWS_REGIONS } from "@app/helpers/appConnections";+import { useDiscardChangesGuard, usePopUp } from "@app/hooks";+import {+ useGetAgentVaultSessionLogSettings,+ useUpdateAgentVaultSessionLogSettings+} from "@app/hooks/api/agentVault";+import { TAgentVaultSessionLogSettings } from "@app/hooks/api/agentVault/types";+import { AppConnection } from "@app/hooks/api/appConnections/enums";+import { useListAvailableAppConnections } from "@app/hooks/api/appConnections/queries";+import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";++import { AgentVaultDocsUrls } from "../../agent-vault-docs-urls";+import { AwsSetupDialog } from "./AwsSetupDialog";++const NO_CONNECTION = "none";+const CREATE_CONNECTION = "_create";++const AWS_CONNECTION = APP_CONNECTION_MAP[AppConnection.AWS];++const S3_BUCKET_NAME = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;++const buildSchema = (hasSavedBucket: boolean) =>+ z+ .object({+ enabled: z.boolean(),+ appConnectionId: z.string(),+ bucket: z.string().trim().max(255),+ region: z.string(),+ keyPrefix: z+ .string()+ .trim()+ .max(512, "At most 512 characters")+ .regex(/^[A-Za-z0-9!\-_.'()/]*$/, "Use only letters, numbers and ! - _ . ' ( ) /")+ .refine(+ (value) => value === "" || value.split("/").every(Boolean),+ "Use folder names separated by single slashes, with no slash at the start or end"+ )+ .refine(+ (value) => !value.split("/").some((segment) => segment === "." || segment === ".."),+ "Cannot use '.' or '..' as a folder name"+ )+ })+ .refine((values) => !values.enabled || values.appConnectionId !== NO_CONNECTION, {+ message: "Session logs need an AWS connection",+ path: ["appConnectionId"]+ })+ .superRefine((values, ctx) => {+ const { length } = values.bucket;+ if (length === 0 && hasSavedBucket) {+ ctx.addIssue({+ code: "custom",+ path: ["bucket"],+ message: "A bucket can be replaced, not removed"+ });+ } else if (length === 0 && values.enabled) {+ ctx.addIssue({+ code: "custom",+ path: ["bucket"],+ message: "Session logs need a bucket"+ });+ } else if (length > 0 && !S3_BUCKET_NAME.test(values.bucket)) {+ ctx.addIssue({+ code: "custom",+ path: ["bucket"],+ message:+ "Use 3 to 63 lowercase letters, numbers, dots or hyphens, starting and ending with a letter or number"+ });+ }+ });++type FormData = z.infer<ReturnType<typeof buildSchema>>;++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ onSaved: (settings: TAgentVaultSessionLogSettings) => void;+ onEditCredentials?: () => void;+ // Without the plan, recording can only be switched off and the connection removed.+ isCleanupOnly?: boolean;+};++export const SessionLogModal = ({+ isOpen,+ onOpenChange,+ onSaved,+ onEditCredentials,+ isCleanupOnly = false+}: Props) => {+ const { currentProject } = useProject();+ const { permission } = useProjectPermission();+ const { data: settings } = useGetAgentVaultSessionLogSettings();+ const { data: connections, isPending: isLoadingConnections } = useListAvailableAppConnections(+ AppConnection.AWS,+ currentProject.id+ );+ const updateConfig = useUpdateAgentVaultSessionLogSettings();+ const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([+ "addConnection",+ "awsSetup"+ ] as const);++ const {+ control,+ handleSubmit,+ reset,+ setValue,+ watch,+ formState: { isSubmitting, isDirty }+ } = useForm<FormData>({ resolver: zodResolver(buildSchema(Boolean(settings?.bucket))) });++ const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =+ useDiscardChangesGuard({ isDirty, onDiscard: () => onOpenChange(false) });++ useEffect(() => {+ if (!isOpen || !settings) return;++ reset({+ enabled: settings.bucket ? settings.enabled : true,+ appConnectionId: settings.appConnectionId ?? NO_CONNECTION,+ bucket: settings.bucket ?? "",+ region: settings.region ?? AWS_REGIONS[0].slug,+ keyPrefix: settings.keyPrefix ?? ""+ });+ }, [isOpen, settings, reset]);++ const bucket = watch("bucket") ?? "";+ const keyPrefix = watch("keyPrefix") ?? "";+ const isEnabled = watch("enabled");+ const isDetaching =+ watch("appConnectionId") === NO_CONNECTION && Boolean(settings?.appConnectionId);++ const canCreateConnection = permission.can(+ ProjectPermissionAppConnectionActions.Create,+ ProjectPermissionSub.AppConnections+ );++ const connectionOptions = [+ ...(canCreateConnection && !isCleanupOnly+ ? [{ id: CREATE_CONNECTION, name: "Create New Connection" }]+ : []),+ ...(isEnabled ? [] : [{ id: NO_CONNECTION, name: "None" }]),+ ...(connections ?? []).filter(+ (connection) => !isCleanupOnly || connection.id === settings?.appConnectionId+ )+ ];++ const typedBucket = bucket.trim();+ const isBucketChange =+ Boolean(settings?.bucket) &&+ S3_BUCKET_NAME.test(typedBucket) &&+ typedBucket !== settings?.bucket;+ const isPrefixOnlyChange =+ Boolean(settings?.bucket) &&+ !isBucketChange &&+ keyPrefix.trim() !== (settings?.keyPrefix ?? "");++ const onSubmit = async (values: FormData) => {+ try {+ const result = await updateConfig.mutateAsync({+ enabled: values.enabled,+ appConnectionId: values.appConnectionId === NO_CONNECTION ? null : values.appConnectionId,+ bucket: values.bucket || undefined,+ region: values.region,+ keyPrefix: values.keyPrefix+ });+ createNotification({ text: "Session log settings saved", type: "success" });+ onOpenChange(false);+ onSaved(result);+ } catch {+ // MutationCache.onError already reports the failure.+ }+ };++ return (+ <Dialog open={isOpen} onOpenChange={(open) => (open ? onOpenChange(true) : requestDiscard())}>+ <DialogContent className="max-w-xl">+ <form onSubmit={handleSubmit(onSubmit)} className="flex min-h-0 flex-col gap-6">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ Session Logs+ <DocumentationLinkBadge href={AgentVaultDocsUrls.sessionLogs} />+ </DialogTitle>+ <DialogDescription>+ The bucket records are written to, and the credentials that reach it.+ </DialogDescription>+ </DialogHeader>++ {isCleanupOnly && (+ <Alert variant="warning">+ <AlertDescription>+ Your plan no longer includes session logs. You can turn them off and remove the AWS+ connection.+ </AlertDescription>+ </Alert>+ )}++ <FieldGroup>+ <FieldSet>+ <Controller+ control={control}+ name="enabled"+ render={({ field }) => (+ <Field orientation="horizontal">+ <FieldContent>+ <Label htmlFor="agent-vault-session-log-enabled">Enable</Label>+ <FieldDescription>+ When enabled, requests made by the agents are saved to the bucket below.+ </FieldDescription>+ </FieldContent>+ <Toggle+ id="agent-vault-session-log-enabled"+ variant="av"+ checked={field.value ?? false}+ onCheckedChange={field.onChange}+ disabled={isCleanupOnly && !settings?.enabled}+ />+ </Field>+ )}+ />+ </FieldSet>++ <FieldSet>+ <FieldLegend variant="label">Storage</FieldLegend>++ <Controller+ control={control}+ name="appConnectionId"+ render={({ field, fieldState }) => (+ <Field>+ <div className="flex items-center justify-between gap-2">+ <FieldLabel>AWS Connection</FieldLabel>+ <Button+ variant="link"+ size="xs"+ type="button"+ onClick={() => handlePopUpOpen("awsSetup")}+ >+ View AWS Setup+ </Button>+ </div>+ <FieldContent>+ <Combobox+ value={connectionOptions.find((option) => option.id === field.value)}+ isClearable={false}+ onValueChange={(option) => {+ if (option.id === CREATE_CONNECTION) {+ handlePopUpOpen("addConnection");+ return;+ }+ field.onChange(option.id);+ }}+ isLoading={isLoadingConnections}+ isError={Boolean(fieldState.error)}+ isDisabled={isCleanupOnly && isEnabled}+ options={connectionOptions}+ placeholder="Select a connection..."+ getOptionLabel={(option) => option.name}+ getOptionValue={(option) => option.id}+ renderOption={(option) => (+ <span className="flex min-w-0 items-center gap-2">+ {option.id !== CREATE_CONNECTION && option.id !== NO_CONNECTION && (+ <ProviderIcon+ alt={`${AWS_CONNECTION.name} connection`}+ icon={AWS_CONNECTION.image}+ className="w-4 shrink-0"+ />+ )}+ <span className="min-w-0 flex-1">+ {option.id === NO_CONNECTION ? (+ option.name+ ) : (+ <AppConnectionOptionContent+ data={option}+ isOnlyOption={+ option.id === CREATE_CONNECTION &&+ connectionOptions.length === 1+ }+ />+ )}+ </span>+ </span>+ )}+ renderValue={(option) => (+ <span className="flex min-w-0 items-center gap-2">+ {option.id !== NO_CONNECTION && (+ <ProviderIcon+ alt={`${AWS_CONNECTION.name} connection`}+ icon={AWS_CONNECTION.image}+ className="w-4 shrink-0"+ />+ )}+ <span className="truncate">{option.name}</span>+ </span>+ )}+ modal+ />+ <FieldDescription>+ {isDetaching+ ? "Without a connection, session logs can't be read. The bucket is kept, so attaching a connection later brings the history back."+ : "Its credentials write the records, and read them back when you open a session's logs."}+ </FieldDescription>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />++ <Controller+ control={control}+ name="region"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel+ id="agent-vault-session-log-region-label"+ htmlFor="agent-vault-session-log-region"+ >+ Region+ </FieldLabel>+ <FieldContent>+ <AwsRegionSelect+ id="agent-vault-session-log-region"+ value={field.value}+ onChange={field.onChange}+ isError={Boolean(fieldState.error)}+ isDisabled={isCleanupOnly}+ aria-labelledby="agent-vault-session-log-region-label"+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />++ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <Controller+ control={control}+ name="bucket"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Bucket</FieldLabel>+ <FieldContent>+ <Input+ {...field}+ placeholder="acme-agent-vault-session-logs"+ isError={Boolean(fieldState.error)}+ disabled={isCleanupOnly}+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="keyPrefix"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>+ Key Prefix <span className="text-muted">(optional)</span>+ </FieldLabel>+ <FieldContent>+ <Input+ {...field}+ placeholder="agent-vault"+ isError={Boolean(fieldState.error)}+ disabled={isCleanupOnly}+ />+ <FieldDescription>+ Session logs are written under this prefix.+ </FieldDescription>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ </div>++ {isBucketChange && (+ <Alert variant="warning">+ <AlertDescription>+ <p>+ Everything already recorded stays in{" "}+ <span className="font-mono">{settings?.bucket}</span>, where Infisical can no+ longer read it. To rotate credentials, update the AWS connection instead of+ moving the bucket.+ </p>+ {onEditCredentials && (+ <AlertAction>+ <Button+ variant="outline"+ size="sm"+ type="button"+ onClick={onEditCredentials}+ >+ Edit AWS Credentials+ </Button>+ </AlertAction>+ )}+ </AlertDescription>+ </Alert>+ )}++ {isPrefixOnlyChange && (+ <Alert variant="info">+ <AlertDescription>+ {settings?.keyPrefix ? (+ <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.+ </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.+ </p>+ )}+ </AlertDescription>+ </Alert>+ )}+ </FieldSet>+ </FieldGroup>++ <DialogFooter>+ <Button variant="ghost" type="button" onClick={() => requestDiscard()}>+ Cancel+ </Button>+ <Button type="submit" variant="av" isPending={isSubmitting} isDisabled={isSubmitting}>+ Save+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>++ <AddAppConnectionModal+ isOpen={popUp.addConnection.isOpen}+ onOpenChange={(isModalOpen) => handlePopUpToggle("addConnection", isModalOpen)}+ projectType={currentProject.type}+ projectId={currentProject.id}+ app={AppConnection.AWS}+ onComplete={(connection) => {+ if (connection) {+ setValue("appConnectionId", connection.id, { shouldValidate: true, shouldDirty: true });+ }+ }}+ />++ <AwsSetupDialog+ isOpen={popUp.awsSetup.isOpen}+ onOpenChange={(isSetupOpen) => handlePopUpToggle("awsSetup", isSetupOpen)}+ bucket={bucket.trim()}+ keyPrefix={keyPrefix.trim()}+ isUnsaved+ />++ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Changes?"+ description="Your changes to the session log settings will be lost."+ />+ </Dialog>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogReadAccessAlert.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogReadAccessAlert.tsxnew file mode 100644index 0000000000..0e8a39a1a1--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogReadAccessAlert.tsx@@ -0,0 +1,65 @@+import { ReactNode, useState } from "react";+import { TriangleAlertIcon } from "lucide-react";++import { Alert, AlertAction, AlertDescription, Button } from "@app/components/v3";+import {+ useGetAgentVaultSessionLogCorsProbe,+ useGetAgentVaultSessionLogSettings+} from "@app/hooks/api/agentVault";+import { TAgentVaultSessionLogReadAccess } from "@app/hooks/api/agentVault/types";++import { AwsSetupDialog, HostBlockedMessage } from "./AwsSetupDialog";++const READ_ACCESS_ALERTS: Record<+ Exclude<TAgentVaultSessionLogReadAccess, "readable">,+ { message: (host: string) => ReactNode; action?: string }+> = {+ "cors-missing": {+ message: () =>+ "Session logs can't be read back, because the bucket they're stored in isn't allowing requests from this origin.",+ action: "View CORS Rule"+ },+ "access-denied": {+ message: () =>+ "Session logs can't be read back, because the AWS connection isn't allowed to read from the bucket they're stored in.",+ action: "View IAM Policy"+ },+ "host-blocked": {+ message: (host) => <HostBlockedMessage host={host} />+ }+};++export const SessionLogReadAccessAlert = () => {+ const [isAwsSetupOpen, setIsAwsSetupOpen] = useState(false);+ const { data: config } = useGetAgentVaultSessionLogSettings();+ const { data: readCheck } = useGetAgentVaultSessionLogCorsProbe();+ const readAlert =+ readCheck && readCheck.status !== "readable" ? READ_ACCESS_ALERTS[readCheck.status] : null;++ return (+ <>+ {readAlert && (+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ <p>{readAlert.message(readCheck?.host ?? "")}</p>+ {readAlert.action && (+ <AlertAction>+ <Button variant="outline" size="sm" onClick={() => setIsAwsSetupOpen(true)}>+ {readAlert.action}+ </Button>+ </AlertAction>+ )}+ </AlertDescription>+ </Alert>+ )}++ <AwsSetupDialog+ isOpen={isAwsSetupOpen}+ onOpenChange={setIsAwsSetupOpen}+ bucket={config?.bucket ?? null}+ keyPrefix={config?.keyPrefix ?? null}+ />+ </>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogSection.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogSection.tsxnew file mode 100644index 0000000000..b2586b0d2b--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/components/SessionLogSection.tsx@@ -0,0 +1,262 @@+import { useState } from "react";+import { subject } from "@casl/ability";+import { useQueryClient } from "@tanstack/react-query";+import { AsteriskIcon, ChevronDownIcon, PlugIcon } from "lucide-react";++import { AgentVaultSessionLogUpgradeModal } from "@app/components/agent-vault/AgentVaultSessionLogUpgradeModal";+import {+ Badge,+ Button,+ ButtonGroup,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Detail,+ DetailGroup,+ DetailLabel,+ DetailValue,+ DocumentationLinkBadge,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ IconButton,+ ProviderIcon,+ Skeleton,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import {+ ProjectPermissionSub,+ useOrganization,+ useProject,+ useProjectPermission,+ useSubscription+} from "@app/context";+import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";+import { areAgentVaultSessionLogsOn } from "@app/helpers/agentVaultSessionLogs";+import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";+import {+ agentVaultKeys,+ fetchAgentVaultSessionLogReadAccess,+ useGetAgentVaultSessionLogSettings+} from "@app/hooks/api/agentVault";+import { TAgentVaultSessionLogSettings } from "@app/hooks/api/agentVault/types";+import { AppConnection } from "@app/hooks/api/appConnections/enums";+import {+ useListAppConnections,+ useListAvailableAppConnections+} from "@app/hooks/api/appConnections/queries";+import { EditAppConnectionCredentialsModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components/EditAppConnectionCredentialsModal";++import { AgentVaultDocsUrls } from "../../agent-vault-docs-urls";+import { AwsSetupDialog } from "./AwsSetupDialog";+import { SessionLogConnectionsSheet } from "./SessionLogConnectionsSheet";+import { SessionLogModal } from "./SessionLogModal";++const AWS_CONNECTION = APP_CONNECTION_MAP[AppConnection.AWS];++export const SessionLogSection = () => {+ const { currentOrg } = useOrganization();+ const { currentProject } = useProject();+ const { permission } = useProjectPermission();+ const { subscription } = useSubscription();+ const queryClient = useQueryClient();+ const [isModalOpen, setIsModalOpen] = useState(false);+ const [isUpgradeOpen, setIsUpgradeOpen] = useState(false);+ const [isConnectionsSheetOpen, setIsConnectionsSheetOpen] = useState(false);+ const [isEditCredentialsOpen, setIsEditCredentialsOpen] = useState(false);+ const [awsSetup, setAwsSetup] = useState<{+ bucket: string | null;+ keyPrefix: string | null;+ } | null>(null);+ const { data: config, isPending } = useGetAgentVaultSessionLogSettings();+ const { data: connections } = useListAvailableAppConnections(+ AppConnection.AWS,+ currentProject.id+ );+ const { data: agentVaultConnections = [] } = useListAppConnections(currentProject.id);++ const hasDestination = Boolean(config?.bucket);+ const isEnabled = Boolean(config?.enabled) && subscription.agentVaultByoS3;+ // Without the plan, Configure still opens for an existing setup so an admin can switch it off and+ // detach the connection; there is nothing to clean up otherwise, so it offers the upgrade.+ const isCleanupOnly =+ !subscription.agentVaultByoS3 && Boolean(config?.enabled || config?.appConnectionId);++ // Saving with session logs on already proved Infisical can write, so the dialog only opens for a+ // step the read check finds missing.+ const offerAwsSetup = async (settings: TAgentVaultSessionLogSettings) => {+ if (!areAgentVaultSessionLogsOn(settings)) return;+ const readCheck = await queryClient+ .fetchQuery({+ queryKey: agentVaultKeys.sessionLogCorsProbe(currentOrg.id),+ queryFn: fetchAgentVaultSessionLogReadAccess+ })+ .catch(() => null);+ if (readCheck?.status === "cors-missing" || readCheck?.status === "access-denied") {+ setAwsSetup({ bucket: settings.bucket, keyPrefix: settings.keyPrefix });+ }+ };++ const connection = connections?.find(({ id }) => id === config?.appConnectionId);+ const connectionName = connection?.name ?? null;+ const isOrgConnection = Boolean(connection && !connection.projectId);+ // The available list holds only names and IDs, and the credentials editor needs the full+ // connection, which only Agent Vault's own list returns.+ const editableConnection = agentVaultConnections.find(({ id }) => id === config?.appConnectionId);+ const canEditConnection = editableConnection+ ? permission.can(+ ProjectPermissionAppConnectionActions.Edit,+ subject(ProjectPermissionSub.AppConnections, { connectionId: editableConnection.id })+ )+ : false;+ const hasConnectionMenu = Boolean(config?.appConnectionId) || agentVaultConnections.length > 0;++ return (+ <>+ <Card>+ <CardHeader>+ <CardTitle>+ Session Logs+ <DocumentationLinkBadge href={AgentVaultDocsUrls.sessionLogs} />+ </CardTitle>+ <CardDescription>+ Requests your agents make through a proxy, encrypted and written to a bucket you own.+ </CardDescription>+ <CardAction>+ <ButtonGroup>+ <Button+ variant="av"+ isDisabled={isPending}+ onClick={() =>+ subscription.agentVaultByoS3 || isCleanupOnly+ ? setIsModalOpen(true)+ : setIsUpgradeOpen(true)+ }+ >+ {!config || hasDestination ? "Configure" : "Set Up Session Logs"}+ </Button>+ {hasConnectionMenu && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ variant="av"+ aria-label="Connection options"+ className="border-l-transparent"+ >+ <ChevronDownIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={4} className="min-w-48">+ {config?.appConnectionId && (+ <Tooltip>+ <TooltipTrigger asChild>+ <div>+ <DropdownMenuItem+ isDisabled={!canEditConnection}+ onClick={() => setIsEditCredentialsOpen(true)}+ >+ <AsteriskIcon />+ Edit AWS Credentials+ </DropdownMenuItem>+ </div>+ </TooltipTrigger>+ {isOrgConnection && (+ <TooltipContent side="left">+ Session logs use an organization connection. Edit its credentials under+ Integrations.+ </TooltipContent>+ )}+ </Tooltip>+ )}+ <DropdownMenuItem onClick={() => setIsConnectionsSheetOpen(true)}>+ <PlugIcon />+ Manage Connections+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </ButtonGroup>+ </CardAction>+ </CardHeader>++ {(isPending || (hasDestination && config)) && (+ <CardContent>+ {isPending && <Skeleton className="h-10 w-full" />}++ {!isPending && hasDestination && config && (+ <DetailGroup className="flex-row flex-wrap gap-x-8">+ <Detail>+ <DetailLabel>Status</DetailLabel>+ <DetailValue>+ <Badge variant={isEnabled ? "success" : "neutral"}>+ {isEnabled ? "Enabled" : "Disabled"}+ </Badge>+ </DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Connection</DetailLabel>+ <DetailValue className="flex items-center gap-2">+ {connectionName && (+ <ProviderIcon+ alt={`${AWS_CONNECTION.name} connection`}+ icon={AWS_CONNECTION.image}+ className="w-4 shrink-0"+ />+ )}+ {connectionName ?? "None"}+ </DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Region</DetailLabel>+ <DetailValue>{config.region}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Bucket</DetailLabel>+ <DetailValue>{config.bucket}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Key Prefix</DetailLabel>+ <DetailValue>{config.keyPrefix || "None"}</DetailValue>+ </Detail>+ </DetailGroup>+ )}+ </CardContent>+ )}+ </Card>++ <SessionLogModal+ isOpen={isModalOpen}+ onOpenChange={setIsModalOpen}+ onSaved={offerAwsSetup}+ onEditCredentials={canEditConnection ? () => setIsEditCredentialsOpen(true) : undefined}+ isCleanupOnly={isCleanupOnly}+ />++ <AgentVaultSessionLogUpgradeModal isOpen={isUpgradeOpen} onOpenChange={setIsUpgradeOpen} />++ <AwsSetupDialog+ isOpen={Boolean(awsSetup)}+ onOpenChange={(isOpen) => !isOpen && setAwsSetup(null)}+ bucket={awsSetup?.bucket ?? null}+ keyPrefix={awsSetup?.keyPrefix ?? null}+ />++ <EditAppConnectionCredentialsModal+ isOpen={isEditCredentialsOpen}+ onOpenChange={setIsEditCredentialsOpen}+ appConnection={editableConnection}+ />++ <SessionLogConnectionsSheet+ isOpen={isConnectionsSheetOpen}+ onOpenChange={setIsConnectionsSheetOpen}+ />+ </>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSettingsPage/route.tsx b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/route.tsxnew file mode 100644index 0000000000..f4be6b5f98--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSettingsPage/route.tsx@@ -0,0 +1,12 @@+import { createFileRoute } from "@tanstack/react-router";++import { AgentVaultSettingsPage } from "./AgentVaultSettingsPage";++export const Route = createFileRoute(+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings"+)({+ component: AgentVaultSettingsPage,+ beforeLoad: ({ context }) => {+ return { breadcrumbs: [...context.breadcrumbs, { label: "Settings" }] };+ }+});diff --git a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts b/frontend/src/pages/agent-vault/agent-vault-docs-urls.tsindex 5fecdac389..3393f20c6b 100644--- a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts+++ b/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts@@ -6,5 +6,6 @@ export const AgentVaultDocsUrls = {accessBundles: `${AGENT_VAULT_DOCS_BASE_URL}/access-bundles`,services: `${AGENT_VAULT_DOCS_BASE_URL}/services`,sessions: `${AGENT_VAULT_DOCS_BASE_URL}/sessions`,- proxies: `${AGENT_VAULT_DOCS_BASE_URL}/proxies`+ proxies: `${AGENT_VAULT_DOCS_BASE_URL}/proxies`,+ sessionLogs: `${AGENT_VAULT_DOCS_BASE_URL}/session-logs`} as const;diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsxindex ff19c258fc..45aa6451a3 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx@@ -46,6 +46,7 @@ import { useToggle } from "@app/hooks";import { GitHubConnectionMethod, TAppConnection } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";import { useListGitHubApps } from "@app/hooks/api/gitHubApps";+import { ProjectType } from "@app/hooks/api/projects/types";import { CredentialRotationStatusBadge } from "./AppConnectionForm/shared/CredentialRotationBadge";@@ -196,7 +197,11 @@ export const AppConnectionRow = ({{project ? (<Link// @ts-expect-error app-connections aren't in kms/ssh- to={`${getProjectBaseURL(project.type)}/app-connections`}+ to={+ project.type === ProjectType.AgentVault+ ? "/organizations/$orgId/agent-vault/settings"+ : `${getProjectBaseURL(project.type)}/app-connections`+ }params={{orgId: currentOrg?.id || "",projectId: project.iddiff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.tsindex eab5ac3900..05b47ef72d 100644--- a/frontend/src/routeTree.gen.ts+++ b/frontend/src/routeTree.gen.ts@@ -101,6 +101,7 @@ import { Route as pamPamDiscoveryPageRouteImport } from './pages/pam/PamDiscoverimport { Route as pamPamApprovalRequestsPageRouteImport } from './pages/pam/PamApprovalRequestsPage/route'import { Route as organizationNetworkingPageRelayDetailsByIDPageRouteImport } from './pages/organization/NetworkingPage/RelayDetailsByIDPage/route'import { Route as organizationNetworkingPageGatewayDetailsByIDPageRouteImport } from './pages/organization/NetworkingPage/GatewayDetailsByIDPage/route'+import { Route as agentVaultAgentVaultSettingsPageRouteImport } from './pages/agent-vault/AgentVaultSettingsPage/route'import { Route as agentVaultAgentVaultSessionsPageRouteImport } from './pages/agent-vault/AgentVaultSessionsPage/route'import { Route as agentVaultAgentVaultProxiesPageRouteImport } from './pages/agent-vault/AgentVaultProxiesPage/route'import { Route as secretScanningLayoutImport } from './pages/secret-scanning/layout'@@ -1216,6 +1217,13 @@ const organizationNetworkingPageGatewayDetailsByIDPageRouteRoute =AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdNetworkingRoute,} as any)+const agentVaultAgentVaultSettingsPageRouteRoute =+ agentVaultAgentVaultSettingsPageRouteImport.update({+ id: '/settings',+ path: '/settings',+ getParentRoute: () => agentVaultLayoutRoute,+ } as any)+const agentVaultAgentVaultSessionsPageRouteRoute =agentVaultAgentVaultSessionsPageRouteImport.update({id: '/sessions',@@ -3283,6 +3291,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof agentVaultAgentVaultSessionsPageRouteImportparentRoute: typeof agentVaultLayoutImport}+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings': {+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings'+ path: '/settings'+ fullPath: '/organizations/$orgId/agent-vault/settings'+ preLoaderRoute: typeof agentVaultAgentVaultSettingsPageRouteImport+ parentRoute: typeof agentVaultLayoutImport+ }'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId': {id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId'path: '/gateways/$gatewayId'@@ -5600,6 +5615,7 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaulinterface agentVaultLayoutRouteChildren {agentVaultAgentVaultProxiesPageRouteRoute: typeof agentVaultAgentVaultProxiesPageRouteRouteagentVaultAgentVaultSessionsPageRouteRoute: typeof agentVaultAgentVaultSessionsPageRouteRoute+ agentVaultAgentVaultSettingsPageRouteRoute: typeof agentVaultAgentVaultSettingsPageRouteRouteredirectsAgentVaultIndexRedirectRoute: typeof redirectsAgentVaultIndexRedirectRouteAuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteWithChildrenprojectAccessControlPageRouteAgentVaultRoute: typeof projectAccessControlPageRouteAgentVaultRoute@@ -5615,6 +5631,8 @@ const agentVaultLayoutRouteChildren: agentVaultLayoutRouteChildren = {agentVaultAgentVaultProxiesPageRouteRoute,agentVaultAgentVaultSessionsPageRouteRoute:agentVaultAgentVaultSessionsPageRouteRoute,+ agentVaultAgentVaultSettingsPageRouteRoute:+ agentVaultAgentVaultSettingsPageRouteRoute,redirectsAgentVaultIndexRedirectRoute: redirectsAgentVaultIndexRedirectRoute,AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRoute:AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteWithChildren,@@ -6167,6 +6185,7 @@ export interface FileRoutesByFullPath {'/organization/app-connections/github/manifest/callback': typeof redirectsGithubManifestCallbackRedirectRoute'/organizations/$orgId/agent-vault/proxies': typeof agentVaultAgentVaultProxiesPageRouteRoute'/organizations/$orgId/agent-vault/sessions': typeof agentVaultAgentVaultSessionsPageRouteRoute+ '/organizations/$orgId/agent-vault/settings': typeof agentVaultAgentVaultSettingsPageRouteRoute'/organizations/$orgId/networking/gateways/$gatewayId': typeof organizationNetworkingPageGatewayDetailsByIDPageRouteRoute'/organizations/$orgId/networking/relays/$relayId': typeof organizationNetworkingPageRelayDetailsByIDPageRouteRoute'/organizations/$orgId/pam/approval-requests': typeof pamPamApprovalRequestsPageRouteRoute@@ -6449,6 +6468,7 @@ export interface FileRoutesByTo {'/organization/app-connections/github/manifest/callback': typeof redirectsGithubManifestCallbackRedirectRoute'/organizations/$orgId/agent-vault/proxies': typeof agentVaultAgentVaultProxiesPageRouteRoute'/organizations/$orgId/agent-vault/sessions': typeof agentVaultAgentVaultSessionsPageRouteRoute+ '/organizations/$orgId/agent-vault/settings': typeof agentVaultAgentVaultSettingsPageRouteRoute'/organizations/$orgId/networking/gateways/$gatewayId': typeof organizationNetworkingPageGatewayDetailsByIDPageRouteRoute'/organizations/$orgId/networking/relays/$relayId': typeof organizationNetworkingPageRelayDetailsByIDPageRouteRoute'/organizations/$orgId/pam/approval-requests': typeof pamPamApprovalRequestsPageRouteRoute@@ -6726,6 +6746,7 @@ export interface FileRoutesById {'/_authenticate/_inject-org-details/organization/app-connections/github/manifest/callback': typeof redirectsGithubManifestCallbackRedirectRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies': typeof agentVaultAgentVaultProxiesPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions': typeof agentVaultAgentVaultSessionsPageRouteRoute+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings': typeof agentVaultAgentVaultSettingsPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId': typeof organizationNetworkingPageGatewayDetailsByIDPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/relays/$relayId': typeof organizationNetworkingPageRelayDetailsByIDPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/approval-requests': typeof pamPamApprovalRequestsPageRouteRoute@@ -7021,6 +7042,7 @@ export interface FileRouteTypes {| '/organization/app-connections/github/manifest/callback'| '/organizations/$orgId/agent-vault/proxies'| '/organizations/$orgId/agent-vault/sessions'+ | '/organizations/$orgId/agent-vault/settings'| '/organizations/$orgId/networking/gateways/$gatewayId'| '/organizations/$orgId/networking/relays/$relayId'| '/organizations/$orgId/pam/approval-requests'@@ -7302,6 +7324,7 @@ export interface FileRouteTypes {| '/organization/app-connections/github/manifest/callback'| '/organizations/$orgId/agent-vault/proxies'| '/organizations/$orgId/agent-vault/sessions'+ | '/organizations/$orgId/agent-vault/settings'| '/organizations/$orgId/networking/gateways/$gatewayId'| '/organizations/$orgId/networking/relays/$relayId'| '/organizations/$orgId/pam/approval-requests'@@ -7577,6 +7600,7 @@ export interface FileRouteTypes {| '/_authenticate/_inject-org-details/organization/app-connections/github/manifest/callback'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions'+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/relays/$relayId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/approval-requests'@@ -8284,6 +8308,7 @@ export const routeTree = rootRoute"children": ["/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions",+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-management",@@ -8335,6 +8360,10 @@ export const routeTree = rootRoute"filePath": "agent-vault/AgentVaultSessionsPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"},+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings": {+ "filePath": "agent-vault/AgentVaultSettingsPage/route.tsx",+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"+ },"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking/gateways/$gatewayId": {"filePath": "organization/NetworkingPage/GatewayDetailsByIDPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/networking"diff --git a/frontend/src/routes.ts b/frontend/src/routes.tsindex e4fedd0532..94305355f8 100644--- a/frontend/src/routes.ts+++ b/frontend/src/routes.ts@@ -386,6 +386,7 @@ const agentVaultRoutes = route("/organizations/$orgId/agent-vault", [route("/$accessBundleId", "agent-vault/AgentVaultAccessBundleDetailPage/route.tsx")]),route("/proxies", "agent-vault/AgentVaultProxiesPage/route.tsx"),+ route("/settings", "agent-vault/AgentVaultSettingsPage/route.tsx"),route("/audit-logs", "project/AuditLogsPage/route-agent-vault.tsx"),route("/access-management", "project/AccessControlPage/route-agent-vault.tsx"),