Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(agent-vault): check a session's owner on the primary when writing it

Scott Wilson15cdad74af28
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.ts
index 7e5a32a80c..febf786762 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
@@ -302,12 +302,16 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {
};
// Conditional so two concurrent revokes cannot both believe they were the one that revoked it. The loser
- // gets no row back, which is what keeps the audit trail down to a single revocation.
+ // gets no row back, which is what keeps the audit trail down to a single revocation. A session whose owner
+ // was deleted is skipped too: updatedAt is the only record of when, and this write would move it.
const revokeIfActive = async (id: string, revokedAt: Date, tx?: Knex) => {
try {
const [row] = (await (tx || db)(TableName.AgentVaultSession)
.where({ id })
.whereNull("revokedAt")
+ .where((qb) => {
+ void qb.whereNotNull("userId").orWhereNotNull("identityId");
+ })
.update({ revokedAt }, "*")) as TAgentVaultSessions[];
return row as TAgentVaultSessions | undefined;
} catch (error) {
@@ -315,22 +319,40 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {
}
};
- // One statement on the primary: the row is locked, rewritten, and its label before the write comes back, so
- // two quick edits can't both read a stale label and the caller audits what actually changed.
+ // One statement on the primary: the row is locked, then rewritten only if it still has an owner, and its label
+ // before the write comes back. So two quick edits can't both read a stale label, the caller audits what
+ // actually changed, and a session whose owner was just deleted isn't written even if a replica hasn't seen
+ // that yet: updatedAt is the only record of when the owner went. No row back means no such session.
const updateLabel = async (id: string, projectId: string, label: string | null, tx?: Knex) => {
try {
const { rows } = (await (tx || db).raw(
- `WITH previous AS (SELECT id, label FROM ?? WHERE id = ? AND "projectId" = ? FOR UPDATE)
- UPDATE ?? AS session SET label = ? FROM previous WHERE session.id = previous.id
- RETURNING previous.label AS "previousLabel"`,
+ `WITH previous AS (
+ SELECT id, label, "userId", "identityId" FROM ?? WHERE id = ? AND "projectId" = ? FOR UPDATE
+ ), updated AS (
+ UPDATE ?? AS session SET label = ? FROM previous
+ WHERE session.id = previous.id AND (previous."userId" IS NOT NULL OR previous."identityId" IS NOT NULL)
+ RETURNING session.id
+ )
+ SELECT previous.label AS "previousLabel", EXISTS (SELECT 1 FROM updated) AS "isUpdated" FROM previous`,
[TableName.AgentVaultSession, id, projectId, TableName.AgentVaultSession, label]
- )) as { rows: { previousLabel: string | null }[] };
- return rows[0];
+ )) as { rows: { previousLabel: string | null; isUpdated: boolean }[] };
+ return rows[0] as { previousLabel: string | null; isUpdated: boolean } | undefined;
} catch (error) {
throw new DatabaseError({ error, name: "Update agent vault session label" });
}
};
+ // Read after a write that didn't happen, so the answer reflects the row as it is, not as a replica last saw it.
+ const findByIdOnPrimary = async (id: string, projectId: string, tx?: Knex) => {
+ try {
+ return (await (tx || db)(TableName.AgentVaultSession).where({ id, projectId }).first()) as
+ | TAgentVaultSessions
+ | undefined;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find agent vault session" });
+ }
+ };
+
// 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 {
@@ -343,5 +365,5 @@ export const agentVaultSessionDALFactory = (db: TDbClient) => {
}
};
- return { ...orm, findByTokenHash, findForList, revokeIfActive, updateLabel, createWithId };
+ return { ...orm, findByTokenHash, findForList, revokeIfActive, updateLabel, findByIdOnPrimary, createWithId };
};
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.ts
index 9c0245a8f6..acdf823ff8 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, isOwnerlessSession } from "./agent-vault-session-fns";
+import { deriveSessionStatus, generateSessionToken } from "./agent-vault-session-fns";
import {
TGetSessionByIdDTO,
TListSessionsDTO,
@@ -223,9 +223,7 @@ 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.
- // 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 };
+ 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());
@@ -233,10 +231,20 @@ export const agentVaultSessionServiceFactory = ({
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 });
+ // Nothing was written: a concurrent revoke won, or the owner was deleted, which already reads as revoked and is
+ // left untouched. Report the row as it is now, which the read above may not have seen.
+ const current = await agentVaultSessionDAL.findByIdOnPrimary(session.id, projectId);
return {
- session: toSessionView({ ...session, revokedAt: current?.revokedAt ?? session.revokedAt }),
+ session: toSessionView(
+ current
+ ? {
+ ...session,
+ revokedAt: current.revokedAt ?? null,
+ userId: current.userId ?? null,
+ identityId: current.identityId ?? null
+ }
+ : session
+ ),
revokedNow: false
};
};
@@ -249,16 +257,15 @@ 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)) {
+ // The visible session can come from a replica that lags, so the owner check and the previous label come from
+ // the write itself.
+ const updated = await agentVaultSessionDAL.updateLabel(session.id, projectId, label);
+ if (!updated) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });
+ if (!updated.isUpdated) {
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` });
return { session: toSessionView({ ...session, label }), previousLabel: updated.previousLabel };
};
diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.md
index b49caa3e41..930759257b 100644
--- a/backend/src/ee/services/agent-vault/AGENTS.md
+++ b/backend/src/ee/services/agent-vault/AGENTS.md
@@ -109,8 +109,10 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-
on the previous release writes none) and `toSessionActor` falls back to the backfill's guess.
- 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.
+ are refused and revoke is a no-op (the session already reads as revoked). The guard sits in each write's own
+ SQL on the primary (`updateLabel`, `revokeIfActive`), not in a check on the session read beforehand, which
+ can come from a replica that hasn't seen the deletion yet. 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 neither
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.