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
fix(agent-vault): leave sessions whose owner was deleted untouched
Scott Wilson1ce282fa66bb
diff --git a/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts b/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.tsindex 31f1acbbdf..7345db60a0 100644--- a/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts@@ -759,7 +759,7 @@ describe("Agent Vault session logs", async () => {expect(res.statusCode).toBe(401);});- test("dates a session's retirement from its owner's deletion, not from a later edit", async () => {+ test("leaves a session whose owner was deleted untouched, so its late-log window stays closed", async () => {await configure();const bundle = await createAccessBundle(`session-logs-ownerless-${Date.now()}`);const member = await createMemberIdentity(`session-logs-ownerless-${Date.now()}`);@@ -773,22 +773,26 @@ describe("Agent Vault session logs", async () => {});expect(minted.statusCode, minted.payload).toBe(200);const { id: sessionId } = minted.json().session as { id: string };- const proxy = await createProxy(`session-logs-ownerless-${Date.now()}`);expect((await member.cleanup()).statusCode).toBe(200);- const ownerless = await testDb("agent_vault_sessions").where({ id: sessionId }).first();- expect(ownerless.identityId).toBeNull();- expect(ownerless.revokedAt).not.toBeNull();+ const before = await testDb("agent_vault_sessions").where({ id: sessionId }).first();+ expect(before.identityId).toBeNull();- // Owner deleted two days ago, then the session relabelled just now.- await testDb("agent_vault_sessions")- .where({ id: sessionId })- .update({ revokedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000) });const relabelled = await inject("PATCH", `/api/v1/agent-vault/sessions/${sessionId}`, { label: "afterwards" });- expect(relabelled.statusCode, relabelled.payload).toBe(200);+ expect(relabelled.statusCode).toBe(400);+ expect(relabelled.json().message).toBe(+ "The user or machine identity that owned this session was deleted, so its label can't be changed."+ );- const res = await proxy.postChunk(sessionId, chunkBody());- expect(res.statusCode).toBe(401);+ const revoked = await inject("POST", `/api/v1/agent-vault/sessions/${sessionId}/revoke`);+ expect(revoked.statusCode).toBe(200);+ expect(revoked.json().session.status).toBe("revoked");++ // updatedAt is the only record of when the owner went, so neither call may move it.+ const after = await testDb("agent_vault_sessions").where({ id: sessionId }).first();+ expect(after.updatedAt.getTime()).toBe(before.updatedAt.getTime());+ expect(after.revokedAt).toBeNull();+ expect(after.label).toBeNull();});test("still accepts a chunk from a session revoked minutes ago", async () => {diff --git a/backend/src/db/migrations/20261027190000_agent-vault-session-owner-removed-revoked-at.ts b/backend/src/db/migrations/20261027190000_agent-vault-session-owner-removed-revoked-at.tsdeleted file mode 100644index ec322e7377..0000000000--- a/backend/src/db/migrations/20261027190000_agent-vault-session-owner-removed-revoked-at.ts+++ /dev/null@@ -1,45 +0,0 @@-import { Knex } from "knex";--import { TableName } from "../schemas";--const FUNCTION_NAME = "agent_vault_session_revoke_on_owner_removed";-const TRIGGER_NAME = "agent_vault_sessions_revoke_on_owner_removed";--export async function up(knex: Knex): Promise<void> {- // Until now the removal time was only implied by updatedAt, which nothing else had touched on these rows.- await knex.raw(- `UPDATE ?? SET "revokedAt" = "updatedAt" WHERE "userId" IS NULL AND "identityId" IS NULL AND "revokedAt" IS NULL`,- [TableName.AgentVaultSession]- );-- // The owner columns are cleared by ON DELETE SET NULL from whichever path deletes the user or identity, so only- // the database sees the moment a session loses its owner.- await knex.raw(`- CREATE OR REPLACE FUNCTION ${FUNCTION_NAME}() RETURNS TRIGGER AS $$- BEGIN- NEW."revokedAt" = NOW();- RETURN NEW;- END;- $$ LANGUAGE plpgsql;- `);- await knex.raw(`DROP TRIGGER IF EXISTS "${TRIGGER_NAME}" ON ??`, [TableName.AgentVaultSession]);- await knex.raw(- `- CREATE TRIGGER "${TRIGGER_NAME}"- BEFORE UPDATE ON ??- FOR EACH ROW- WHEN (- NEW."userId" IS NULL AND NEW."identityId" IS NULL- AND (OLD."userId" IS NOT NULL OR OLD."identityId" IS NOT NULL)- AND NEW."revokedAt" IS NULL- )- EXECUTE PROCEDURE ${FUNCTION_NAME}();- `,- [TableName.AgentVaultSession]- );-}--export async function down(knex: Knex): Promise<void> {- await knex.raw(`DROP TRIGGER IF EXISTS "${TRIGGER_NAME}" ON ??`, [TableName.AgentVaultSession]);- await knex.raw(`DROP FUNCTION IF EXISTS ${FUNCTION_NAME}()`);-}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 1011e0b52f..8767065d20 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@@ -638,17 +638,16 @@ export const agentVaultProxyServiceFactory = ({throw new NotFoundError({ message: "Session not found" });}+ if (session.revokedAt) throw new UnauthorizedError({ message: "This session has been revoked" });+ if (session.expiresAt && session.expiresAt <= new Date()) {+ throw new UnauthorizedError({ message: "This session has expired" });+ }// The actor columns are SET NULL so the row outlives its owner for history. A null id must not reach the// lookups below: knex compiles `where col = null` to `IS NULL`, which matches every user row and made an- // ownerless session resolve as an admin. Checked before revokedAt, which a trigger also sets when the owner- // goes, so the message says why.+ // ownerless session resolve as an admin.if (!session.userId && !session.identityId) {throw new UnauthorizedError({ message: "The identity this session belonged to has been deleted" });}- if (session.revokedAt) throw new UnauthorizedError({ message: "This session has been revoked" });- if (session.expiresAt && session.expiresAt <= new Date()) {- throw new UnauthorizedError({ message: "This session has expired" });- }const actor = session.userId? { type: ActorType.USER as const, id: session.userId }diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.test.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.test.tsindex eb583c77a2..e4a0515628 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.test.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.test.ts@@ -312,17 +312,16 @@ describe("createChunkUploadUrl: the retirement grace window", () => {});});- // Deleting the owner clears both ids and a trigger stamps revokedAt, so these rows carry it like a revoke would.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, revokedAt: hoursAgo(23) }+ session: { ...liveSession(), userId: null, identityId: null, updatedAt: hoursAgo(23) }});await expect(record(service)).resolves.toHaveProperty("uploadUrl");});- test("a session whose owner was deleted more than a day ago stays refused after a later edit", async () => {+ test("a session whose owner was deleted more than a day ago is refused", async () => {const { service } = build({- session: { ...liveSession(), userId: null, identityId: null, revokedAt: hoursAgo(25), updatedAt: new Date() }+ 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"diff --git a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.tsindex 54c55619f6..30c48cd079 100644--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts@@ -27,7 +27,7 @@ import { ObjectStorageType } from "@app/services/object-storage/object-storage-timport { 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 { isSessionOwnedBy } from "../agent-vault-session/agent-vault-session-fns";+import { isOwnerlessSession, isSessionOwnedBy } from "../agent-vault-session/agent-vault-session-fns";import { TAgentVaultSessionLogConfigDALFactory } from "./agent-vault-session-log-config-dal";import {AGENT_VAULT_SESSION_LOG_CHUNK_ID_TIME_TOLERANCE_MS,@@ -185,8 +185,12 @@ export const agentVaultSessionLogServiceFactory = ({if (!session) throw sessionNotFound();const now = new Date();- // A session that loses its owner is stamped revoked by a database trigger, so revokedAt covers that case too.- const retirements = [session.revokedAt, session.expiresAt && session.expiresAt <= now ? session.expiresAt : null]+ // 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;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 1642051a61..9c0245a8f6 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@@ -18,7 +18,7 @@ import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/import { generateSessionLogKey, wrapSessionLogKey } from "../agent-vault-session-log/agent-vault-session-log-secrets";import { TAgentVaultSessionAccessBundleDALFactory } from "./agent-vault-session-access-bundle-dal";import { TAgentVaultSessionDALFactory, TAgentVaultSessionListRow } from "./agent-vault-session-dal";-import { deriveSessionStatus, generateSessionToken } from "./agent-vault-session-fns";+import { deriveSessionStatus, generateSessionToken, isOwnerlessSession } from "./agent-vault-session-fns";import {TGetSessionByIdDTO,TListSessionsDTO,@@ -223,7 +223,9 @@ export const agentVaultSessionServiceFactory = ({// 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: toSessionView(session), revokedNow: false };+ // A session whose owner was deleted already reads as revoked, and writing revokedAt would move updatedAt, the+ // only record of when the owner went, reopening the session's late-log window.+ if (session.revokedAt || isOwnerlessSession(session)) 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());@@ -247,6 +249,13 @@ export const agentVaultSessionServiceFactory = ({);const session = await findVisibleSession({ projectId, ctx, sessionId, isAdmin });+ // Once the owner is deleted, updatedAt is the only record of when, and the session log service retires the+ // session from it. Any write would move it and reopen the session's late-log window.+ if (isOwnerlessSession(session)) {+ throw new BadRequestError({+ message: "The user or machine identity that owned this session was deleted, so its label can't be changed."+ });+ }// The visible session can come from a replica that lags, so the previous label is the one the write replaced.const updated = await agentVaultSessionDAL.updateLabel(session.id, projectId, label);if (!updated) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.mdindex b9be587cad..b49caa3e41 100644--- a/backend/src/ee/services/agent-vault/AGENTS.md+++ b/backend/src/ee/services/agent-vault/AGENTS.md@@ -107,10 +107,10 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-id: 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 podon the previous release writes none) and `toSessionActor` falls back to the backfill's guess.-- When `SET NULL` leaves a session with neither actor id, the `agent_vault_sessions_revoke_on_owner_removed`- trigger stamps `revokedAt`, because no service sees the deletion of a user or machine identity happen. So- `revokedAt` is the one retirement time: never read `updatedAt` as when the owner went, since any edit to- the row (a label change) moves it.+- When `SET NULL` leaves a session with neither actor id, `updatedAt` is the only record of when the owner+ went, and the session log service retires the session from it. So nothing writes to such a row: label edits+ are refused and revoke is a no-op (the session already reads as revoked). A new write to sessions needs the+ same guard, or it reopens the session's late-log window.- Status is derived from `revokedAt`, `expiresAt` and the actor columns, never stored: a session with neitheractor id reads as revoked in the list and the status filter, so they agree with resolve refusing it. Expiryis enforced against the clock on every resolve; there is no expiry audit event, matching every other product.diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex b936efbdb2..b821705bab 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4759,7 +4759,7 @@ export const AGENT_VAULT = {label:"A short description of what the session is for, such as `nightly deploy` or `support ticket triage`. Up to 128 characters, without line breaks, tabs, or invisible characters. Shown wherever the session is listed.",updateLabel:- "The new label for the session, up to 128 characters, without line breaks, tabs, or invisible characters. Send null or an empty string to remove the label.",+ "The new label for the session, up to 128 characters, without line breaks, tabs, or invisible characters. Send null or an empty string to remove the label. You can't change the label once the session's owner is deleted.",token: "The session token. Returned once, at mint, and never again.",expiresAt: "When the session expires, or null when it never does.",scope: "Whose sessions to list: your own (mine) or everyone's (all, administrators only).",diff --git a/docs/documentation/platform/agent-vault/sessions.mdx b/docs/documentation/platform/agent-vault/sessions.mdxindex 4fe785510c..cf2d3070b7 100644--- a/docs/documentation/platform/agent-vault/sessions.mdx+++ b/docs/documentation/platform/agent-vault/sessions.mdx@@ -79,7 +79,7 @@ Anyone granted at least one access bundle can create a session. Admins can creatA label is a short description of what a session is for, such as `nightly deploy` or `support ticket triage`. If one identity creates many sessions, the label is how you tell the sessions apart on the **Sessions** page, and you can search sessions by their label. A label can be up to 128 characters, and can't contain line breaks, tabs, or invisible characters such as zero-width spaces.-You can add, change, or remove a session's label at any time, even after the session expires or is revoked:+You can add, change, or remove a session's label, even after the session expires or is revoked:- In Agent Vault, go to **Sessions**, open the session's menu, and select **Add Label** or **Edit Label**- From an agent or a script, call [the endpoint that updates a session](/api-reference/endpoints/agent-vault-sessions/update), for example to record what the agent is working ondiff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsxindex 8d72671167..a445231062 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx@@ -496,10 +496,13 @@ export const AgentVaultSessionsPage = () => {<LogsIcon />View Session Logs</DropdownMenuItem>- <DropdownMenuItem onClick={() => setSessionToLabel(session)}>- <PencilIcon />- {session.label ? "Edit Label" : "Add Label"}- </DropdownMenuItem>+ {/* The API refuses label edits once the session's owner is deleted */}+ {session.actor.id !== null && (+ <DropdownMenuItem onClick={() => setSessionToLabel(session)}>+ <PencilIcon />+ {session.label ? "Edit Label" : "Add Label"}+ </DropdownMenuItem>+ )}<DropdownMenuItemvariant="danger"isDisabled={session.status !== AgentVaultSessionStatus.Active}diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsxindex 651e40922f..c7a0a20303 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx@@ -190,14 +190,16 @@ export const SessionDetailSheet = ({{session.label ?? "No label"}</DetailValue></Detail>- <IconButton- variant="ghost"- size="xs"- aria-label={session.label ? "Edit label" : "Add label"}- onClick={() => onEditLabel(session)}- >- <PencilIcon />- </IconButton>+ {!isOwnerDeleted && (+ <IconButton+ variant="ghost"+ size="xs"+ aria-label={session.label ? "Edit label" : "Add label"}+ onClick={() => onEditLabel(session)}+ >+ <PencilIcon />+ </IconButton>+ )}</div></div>