Skip to content

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

feat(agent-vault): edit session labels and tighten label validation

Scott Wilson839f5b6eba38
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.ts
index 2be546c2d6..b2aefbebc3 100644
--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts
+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts
@@ -3700,6 +3700,78 @@ describe("Agent Vault V1 Router", async () => {
expect(withNewline.statusCode).toBe(422);
});
+ test("a label that would read differently from what is stored is rejected", async () => {
+ const bundle = await createAccessBundle(`session-label-chars-${Date.now()}`);
+ const mint = (label: unknown) =>
+ inject("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundle.name], ttl: "1h", label });
+
+ const rejected = {
+ tab: "a\tb",
+ zeroWidthSpace: "​",
+ rightToLeftOverride: "revo ‮ltr",
+ lineSeparator: "a
b",
+ paragraphSeparator: "a
b",
+ c1Control: "a\u0085b",
+ privateUse: "ab",
+ loneSurrogate: "a\ud800b"
+ };
+ for await (const [name, label] of Object.entries(rejected)) {
+ const res = await mint(label);
+ expect(res.statusCode, name).toBe(422);
+ expect(JSON.stringify(res.json().message), name).toContain("invisible characters");
+ }
+
+ for await (const label of ["PR #123 (prod): café, 部署", "ship it 🚀"]) {
+ const res = await mint(label);
+ expect(res.statusCode).toBe(200);
+ expect(res.json().session.label).toBe(label);
+ }
+
+ const explicitNull = await mint(null);
+ expect(explicitNull.statusCode).toBe(200);
+ expect(explicitNull.json().session.label).toBeNull();
+
+ const blank = await mint(" ");
+ expect(blank.json().session.label).toBeNull();
+ });
+
+ test("a label can be changed or removed later, only by someone who can see the session", async () => {
+ const bundle = await createAccessBundle(`session-label-edit-${Date.now()}`);
+ const mint = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundle.name], ttl: "1h" });
+ const { id } = mint.json().session as { id: string };
+
+ const set = await inject("PATCH", `/api/v1/agent-vault/sessions/${id}`, { label: " first pass " });
+ expect(set.statusCode).toBe(200);
+ expect(set.json().session).toMatchObject({ id, label: "first pass", status: "active" });
+ expect((await inject("GET", `/api/v1/agent-vault/sessions/${id}`)).json().session.label).toBe("first pass");
+
+ // The label is the only field, so leaving it out must not read as clearing it.
+ expect((await inject("PATCH", `/api/v1/agent-vault/sessions/${id}`, {})).statusCode).toBe(422);
+ expect((await inject("PATCH", `/api/v1/agent-vault/sessions/${id}`, { label: "a​b" })).statusCode).toBe(
+ 422
+ );
+ expect((await inject("GET", `/api/v1/agent-vault/sessions/${id}`)).json().session.label).toBe("first pass");
+
+ const cleared = await inject("PATCH", `/api/v1/agent-vault/sessions/${id}`, { label: null });
+ expect(cleared.statusCode).toBe(200);
+ expect(cleared.json().session.label).toBeNull();
+
+ // A revoked session can still be labelled, for whoever reads it afterwards.
+ expect((await inject("POST", `/api/v1/agent-vault/sessions/${id}/revoke`)).statusCode).toBe(200);
+ const afterRevoke = await inject("PATCH", `/api/v1/agent-vault/sessions/${id}`, { label: "done" });
+ expect(afterRevoke.statusCode).toBe(200);
+ expect(afterRevoke.json().session).toMatchObject({ label: "done", status: "revoked" });
+
+ const member = await createMemberIdentity(`session-label-member-${Date.now()}`);
+ try {
+ const somebodyElses = await member.as("PATCH", `/api/v1/agent-vault/sessions/${id}`, { label: "mine now" });
+ expect(somebodyElses.statusCode).toBe(404);
+ expect((await inject("GET", `/api/v1/agent-vault/sessions/${id}`)).json().session.label).toBe("done");
+ } finally {
+ await member.cleanup();
+ }
+ });
+
test("search filters and counts on the server, not just the page", async () => {
const alpha = await createAccessBundle("search-alpha");
const beta = await createAccessBundle("search-beta");
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.ts
index 590caf40e4..e4f971f2ba 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
@@ -5,6 +5,10 @@ import {
AGENT_VAULT_NO_CONTROL_CHARS_RE
} from "@app/ee/services/agent-vault/agent-vault-credential-schemas";
import { AgentVaultSessionScope, AgentVaultSessionStatus } from "@app/ee/services/agent-vault/agent-vault-enums";
+import {
+ agentVaultSessionLabelSchema,
+ agentVaultSessionLabelUpdateSchema
+} from "@app/ee/services/agent-vault-session/agent-vault-session-fns";
import {
AGENT_VAULT_MAX_SESSION_BUNDLES,
AGENT_VAULT_SESSION_DEFAULT_TTL,
@@ -163,13 +167,7 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider
}
})
.describe(AGENT_VAULT.SESSION.ttl),
- label: z
- .string()
- .trim()
- .max(128, "Label must be at most 128 characters")
- .regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
- .optional()
- .describe(AGENT_VAULT.SESSION.label)
+ label: agentVaultSessionLabelSchema.describe(AGENT_VAULT.SESSION.label)
}),
response: {
200: z.object({
@@ -234,6 +232,46 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider
}
});
+ server.route({
+ method: "PATCH",
+ url: "/:sessionId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "updateAgentVaultSession",
+ description: "Update the label of an Agent Vault session",
+ tags: [ApiDocsTags.AgentVaultSessions],
+ params: z.object({ sessionId: z.string().uuid().describe(AGENT_VAULT.SESSION.sessionId) }),
+ body: z.object({
+ label: agentVaultSessionLabelUpdateSchema.describe(AGENT_VAULT.SESSION.updateLabel)
+ }),
+ response: { 200: z.object({ session: SessionWithAccessBundlesSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const { session, previousLabel } = await server.services.agentVaultSession.updateSessionLabel({
+ projectId: req.internalAgentVaultProjectId,
+ ctx: actorContext(req),
+ sessionId: req.params.sessionId,
+ label: req.body.label
+ });
+
+ if (previousLabel !== session.label) {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.internalAgentVaultProjectId,
+ event: {
+ type: EventType.AGENT_VAULT_SESSION_UPDATE,
+ metadata: { sessionId: session.id, label: session.label, previousLabel }
+ }
+ });
+ }
+
+ return { session };
+ }
+ });
+
server.route({
method: "POST",
url: "/:sessionId/revoke",
@@ -262,7 +300,7 @@ export const registerAgentVaultSessionRouter = async (server: FastifyZodProvider
projectId: req.internalAgentVaultProjectId,
event: {
type: EventType.AGENT_VAULT_SESSION_REVOKE,
- metadata: { sessionId: session.id }
+ metadata: { sessionId: session.id, label: session.label }
}
});
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.ts
index f8d9722db9..1d048fcf56 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,11 +1,47 @@
import crypto from "node:crypto";
+import RE2 from "re2";
+import { z } from "zod";
+
import { ActorType } from "@app/services/auth/auth-type";
import { AgentVaultSessionStatus } from "../agent-vault/agent-vault-enums";
export const AGENT_VAULT_SESSION_TOKEN_PREFIX = "agv_";
+export const AGENT_VAULT_SESSION_LABEL_MAX_LENGTH = 128;
+
+// Controls, format characters (zero-width spaces, text-direction overrides), private-use characters and
+// line or paragraph separators either render as nothing or reorder what is shown, so a stored label could
+// read differently from what search matches. RE2 sees a lone surrogate only after it becomes U+FFFD, so
+// isWellFormed catches that case.
+const AGENT_VAULT_SESSION_LABEL_DISALLOWED_RE = new RE2(/[\p{Cc}\p{Cf}\p{Co}\p{Zl}\p{Zp}]/u);
+
+export const AGENT_VAULT_SESSION_LABEL_MESSAGE =
+ "A label can't contain line breaks, tabs, or invisible characters such as zero-width spaces or text direction marks.";
+
+export const isValidAgentVaultSessionLabel = (label: string) =>
+ label.isWellFormed() && !AGENT_VAULT_SESSION_LABEL_DISALLOWED_RE.test(label);
+
+const agentVaultSessionLabelStringSchema = z
+ .string()
+ .trim()
+ .max(
+ AGENT_VAULT_SESSION_LABEL_MAX_LENGTH,
+ `A label can be at most ${AGENT_VAULT_SESSION_LABEL_MAX_LENGTH} characters`
+ )
+ .refine(isValidAgentVaultSessionLabel, AGENT_VAULT_SESSION_LABEL_MESSAGE);
+
+// Null and a blank string both mean no label, so a client can send back what a read returned.
+export const agentVaultSessionLabelSchema = agentVaultSessionLabelStringSchema
+ .nullish()
+ .transform((label) => label || null);
+
+// Required on update: the label is the only field, so leaving it out must not read as clearing it.
+export const agentVaultSessionLabelUpdateSchema = agentVaultSessionLabelStringSchema
+ .nullable()
+ .transform((label) => label || null);
+
export const hashSessionToken = (token: string) => crypto.createHash("sha256").update(token).digest("hex");
/** sha256, not bcrypt: the token is the lookup key. It is never stored and comes back exactly once. */
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 fba75f9fde..12352f2831 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
@@ -19,7 +19,13 @@ import { generateSessionLogKey, wrapSessionLogKey } from "../agent-vault-session
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 { TGetSessionByIdDTO, TListSessionsDTO, TMintSessionDTO, TRevokeSessionDTO } from "./agent-vault-session-types";
+import {
+ TGetSessionByIdDTO,
+ TListSessionsDTO,
+ TMintSessionDTO,
+ TRevokeSessionDTO,
+ TUpdateSessionLabelDTO
+} 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;
@@ -233,10 +239,26 @@ export const agentVaultSessionServiceFactory = ({
};
};
+ const updateSessionLabel = async ({ projectId, ctx, sessionId, label }: TUpdateSessionLabelDTO) => {
+ const { permission, isAdmin } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAgentVaultSessionActions.Edit,
+ ProjectPermissionSub.AgentVaultSessions
+ );
+
+ const session = await findVisibleSession({ projectId, ctx, sessionId, isAdmin });
+ if (session.label !== label) {
+ await agentVaultSessionDAL.updateById(session.id, { label });
+ }
+
+ return { session: toSessionView({ ...session, label }), previousLabel: session.label };
+ };
+
return {
mintSession,
listSessions,
getSessionById,
- revokeSession
+ revokeSession,
+ updateSessionLabel
};
};
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.ts
index 8c9b9cb359..979af15106 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
@@ -13,7 +13,7 @@ export type TMintSessionDTO = {
actorName: string;
actorEmail: string | null;
ttl: string;
- label?: string;
+ label: string | null;
};
export type TListSessionsDTO = {
@@ -34,6 +34,10 @@ export type TRevokeSessionDTO = {
export type TGetSessionByIdDTO = TRevokeSessionDTO;
+export type TUpdateSessionLabelDTO = TRevokeSessionDTO & {
+ label: string | null;
+};
+
export type TAgentVaultSessionActor =
| {
type: AgentVaultMemberType.User;
diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.md
index f3e9dde214..828950f606 100644
--- a/backend/src/ee/services/agent-vault/AGENTS.md
+++ b/backend/src/ee/services/agent-vault/AGENTS.md
@@ -21,7 +21,7 @@ agent-vault-access-bundle/ bundles, services, credential encryption, grants
agent-vault-variable/ global and personal variables and the reads behind Used By
agent-vault-member/ product membership (list, add, role, remove)
agent-vault-personal-value/ each actor's own values for the fields a service leaves to members
-agent-vault-session/ mint, revoke, list, get
+agent-vault-session/ mint, revoke, list, get, edit label
agent-vault-project/ the per-org project's lazy bootstrap and resolver
agent-vault-proxy/ create/rotate (proxy token + CA), bootstrap, heartbeat, resolve
agent-vault-session-log/ storage settings, chunk ingest, playback
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 839c33ce6d..1b99635a34 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -833,6 +833,7 @@ export enum EventType {
AGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD = "agent-vault-access-bundle-member-add",
AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE = "agent-vault-access-bundle-member-remove",
AGENT_VAULT_SESSION_MINT = "agent-vault-session-mint",
+ AGENT_VAULT_SESSION_UPDATE = "agent-vault-session-update",
AGENT_VAULT_SESSION_REVOKE = "agent-vault-session-revoke",
AGENT_VAULT_PROXY_REGISTER = "agent-vault-proxy-register",
AGENT_VAULT_PROXY_TOKEN_REISSUE = "agent-vault-proxy-token-reissue",
@@ -6781,10 +6782,20 @@ interface AgentVaultSessionMintEvent {
};
}
+interface AgentVaultSessionUpdateEvent {
+ type: EventType.AGENT_VAULT_SESSION_UPDATE;
+ metadata: {
+ sessionId: string;
+ label: string | null;
+ previousLabel: string | null;
+ };
+}
+
interface AgentVaultSessionRevokeEvent {
type: EventType.AGENT_VAULT_SESSION_REVOKE;
metadata: {
sessionId: string;
+ label: string | null;
};
}
@@ -8738,6 +8749,7 @@ export type Event =
| AgentVaultAccessBundleMemberAddEvent
| AgentVaultAccessBundleMemberRemoveEvent
| AgentVaultSessionMintEvent
+ | AgentVaultSessionUpdateEvent
| AgentVaultSessionRevokeEvent
| AgentVaultProxyRegisterEvent
| AgentVaultProxyTokenReissueEvent
diff --git a/backend/src/ee/services/permission/agent-vault-project-roles.test.ts b/backend/src/ee/services/permission/agent-vault-project-roles.test.ts
index 5e49e61033..0bfb6dffa6 100644
--- a/backend/src/ee/services/permission/agent-vault-project-roles.test.ts
+++ b/backend/src/ee/services/permission/agent-vault-project-roles.test.ts
@@ -56,12 +56,15 @@ describe("agent vault project roles", () => {
expect(admin.can(ProjectPermissionActions.Create, ProjectPermissionSub.ServiceTokens)).toBe(false);
});
- test("a member can mint and revoke sessions and read a proxy fingerprint, and nothing more", () => {
+ test("a member can mint, label and revoke sessions and read a proxy fingerprint, and nothing more", () => {
const member = abilityFor(ProjectMembershipRole.Member);
expect(member.can(ProjectPermissionAgentVaultSessionActions.Create, ProjectPermissionSub.AgentVaultSessions)).toBe(
true
);
+ expect(member.can(ProjectPermissionAgentVaultSessionActions.Edit, ProjectPermissionSub.AgentVaultSessions)).toBe(
+ true
+ );
expect(member.can(ProjectPermissionAgentVaultSessionActions.Revoke, ProjectPermissionSub.AgentVaultSessions)).toBe(
true
);
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index 23f2eaeb3b..3d96d75b1d 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -815,6 +815,7 @@ const buildAgentVaultProjectAdminPermissionRules = () => {
[
ProjectPermissionAgentVaultSessionActions.Read,
ProjectPermissionAgentVaultSessionActions.Create,
+ ProjectPermissionAgentVaultSessionActions.Edit,
ProjectPermissionAgentVaultSessionActions.Revoke
],
ProjectPermissionSub.AgentVaultSessions
@@ -917,6 +918,7 @@ const buildAgentVaultProjectMemberPermissionRules = () => {
[
ProjectPermissionAgentVaultSessionActions.Read,
ProjectPermissionAgentVaultSessionActions.Create,
+ ProjectPermissionAgentVaultSessionActions.Edit,
ProjectPermissionAgentVaultSessionActions.Revoke
],
ProjectPermissionSub.AgentVaultSessions
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index a882c5d605..c12503d28c 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -310,6 +310,7 @@ export enum ProjectPermissionAgentVaultAccessBundleActions {
export enum ProjectPermissionAgentVaultSessionActions {
Read = "read",
Create = "create",
+ Edit = "edit",
Revoke = "revoke"
}
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 389d686e26..b936efbdb2 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4757,7 +4757,9 @@ export const AGENT_VAULT = {
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.",
label:
- "A short description of what the session is for, such as `nightly deploy` or `support ticket triage`. Up to 128 characters. Shown wherever the session is listed.",
+ "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.",
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/api-reference/endpoints/agent-vault-sessions/update.mdx b/docs/api-reference/endpoints/agent-vault-sessions/update.mdx
new file mode 100644
index 0000000000..530c67ed87
--- /dev/null
+++ b/docs/api-reference/endpoints/agent-vault-sessions/update.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update session"
+openapi: "PATCH /api/v1/agent-vault/sessions/{sessionId}"
+---
diff --git a/docs/cli/reference.mdx b/docs/cli/reference.mdx
index 8afee1685c..c5a9a5ad15 100644
--- a/docs/cli/reference.mdx
+++ b/docs/cli/reference.mdx
@@ -221,6 +221,7 @@ You set the proxy's traffic policy, exceptions, and poll interval in Infisical,
{ name: "--client-id", value: "<string>", type: "string", description: "The client ID of the machine identity that creates the session, for `--access-bundle`. Can also be set with `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID`." },
{ name: "--client-secret", value: "<string>", type: "string", description: "The client secret of the machine identity that creates the session, for `--access-bundle`. Can also be set with `INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET`." },
{ name: "--keep-session", type: "bool", description: "Leave a session created with `--access-bundle` active when the agent exits, instead of revoking it. Can't be combined with `--session-token`." },
+ { name: "--label", value: "<string>", type: "string", description: "A short description of what a session created with `--access-bundle` is for, shown on the **Sessions** page, such as `nightly deploy`. Up to 128 characters, without line breaks, tabs, or invisible characters. Can't be combined with `--session-token`." },
{ name: "--no-ca-trust", type: "bool", description: "Skip writing the certificate authority, setting the trust variables, and adding it to the macOS keychain, for a machine that already trusts this proxy. `--ca-fingerprint` is still checked." },
{ name: "--no-proxy", value: "<string>", type: "string", description: "More hosts for the agent to reach directly instead of through the proxy, separated by commas. Always merged with `localhost,127.0.0.1` and any `NO_PROXY` in your environment." },
{ name: "--proxy", value: "<string>", type: "string", description: "The Agent Vault proxy's address as `host:port`, such as `10.0.1.5:17323`. A leading `http://` or `https://` is dropped. Required unless `INFISICAL_AGENT_VAULT_PROXY_ADDRESS` is set." },
@@ -236,7 +237,7 @@ You set the proxy's traffic policy, exceptions, and poll interval in Infisical,
]}
examples={[
{ title: "Run an agent with a session token", code: "infisical agent-vault run --session-token=<session-token> --proxy=10.0.1.5:17323 -- claude" },
- { title: "Create a session from an access bundle", code: "infisical agent-vault run --access-bundle=code-review --ttl=8h --proxy=10.0.1.5:17323 -- claude" },
+ { title: "Create a session from an access bundle", code: "infisical agent-vault run --access-bundle=code-review --ttl=8h --label=\"review PR 123\" --proxy=10.0.1.5:17323 -- claude" },
{ title: "Pin the proxy's certificate authority", code: "infisical agent-vault run --session-token=<session-token> --proxy=10.0.1.5:17323 --ca-fingerprint=SHA256:9F:2C:... -- claude" },
{ title: "Create the session as a machine identity", code: "infisical agent-vault run \\\n --access-bundle=code-review \\\n --client-id=<client-id> \\\n --client-secret=<client-secret> \\\n --proxy=10.0.1.5:17323 \\\n -- claude" },
{ title: "Read the settings from environment variables", code: "export INFISICAL_AGENT_VAULT_PROXY_ADDRESS=10.0.1.5:17323\nexport INFISICAL_AGENT_VAULT_SESSION_TOKEN=<session-token>\ninfisical agent-vault run -- claude" },
diff --git a/docs/docs.json b/docs/docs.json
index aba34c8346..718a2c8221 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -4570,6 +4570,7 @@
"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/update",
"api-reference/endpoints/agent-vault-sessions/revoke",
"api-reference/endpoints/agent-vault-session-logs/list",
"api-reference/endpoints/agent-vault-session-logs/tail"
diff --git a/docs/documentation/platform/agent-vault/sessions-api.mdx b/docs/documentation/platform/agent-vault/sessions-api.mdx
index f0c91c0791..84176d6b73 100644
--- a/docs/documentation/platform/agent-vault/sessions-api.mdx
+++ b/docs/documentation/platform/agent-vault/sessions-api.mdx
@@ -46,7 +46,7 @@ The response includes an `accessToken`, which you send with each request in the
## Step 3: Create a session
-Call [the endpoint that creates a session](/api-reference/endpoints/agent-vault-sessions/create) with the name of the access bundle and how long the session should last:
+Call [the endpoint that creates a session](/api-reference/endpoints/agent-vault-sessions/create) with the name of the access bundle, how long the session should last, and optionally a label that says what the session is for:
```bash
curl -X POST https://app.infisical.com/api/v1/agent-vault/sessions \
@@ -57,14 +57,15 @@ curl -X POST https://app.infisical.com/api/v1/agent-vault/sessions \
- `accessBundles` takes a list, but a session can have only one access bundle, so the list must have exactly one name
- `ttl` accepts a duration of at least one minute, such as `30m`, `8h`, or `7d`, or `never`, and defaults to `7d` (see [Choose how long a session lasts](#choose-how-long-a-session-lasts) to pick a value)
-- `label` is optional and describes what the session is for, in up to 128 characters
+- `label` is optional and describes what the session is for, in up to 128 characters (see [Label a session](/documentation/platform/agent-vault/sessions#label-a-session))
-The response includes the session's ID, the session token, and when the session expires:
+The response includes the session's ID, its label, the session token, and when the session expires:
```json
{
"session": {
"id": "6f1c2a9e-3b7d-4e8a-9c41-2d5f7b8e0a13",
+ "label": "nightly deploy",
"token": "<session-token>",
"expiresAt": "2026-10-07T19:00:00.000Z"
}
@@ -126,7 +127,7 @@ Revoke the session even if the agent fails, for example in a `finally` block or
## Step 6: Verify it works
-In Agent Vault, go to **Sessions** and select **All Sessions**. The **Identity** column shows the machine identity's name for the session you created. The session's **Status** is **Active** while the agent runs, and **Revoked** after [Step 5](#step-5-revoke-the-session).
+In Agent Vault, go to **Sessions** and select **All Sessions**. Find the session you created by its label in the **Label** column, or search for the label. The session's **Status** is **Active** while the agent runs, and **Revoked** after [Step 5](#step-5-revoke-the-session).
[View the session's logs](/documentation/platform/agent-vault/sessions#view-session-logs) to check which requests the agent made during the session.
diff --git a/docs/documentation/platform/agent-vault/sessions.mdx b/docs/documentation/platform/agent-vault/sessions.mdx
index 7dc84700e8..4fe785510c 100644
--- a/docs/documentation/platform/agent-vault/sessions.mdx
+++ b/docs/documentation/platform/agent-vault/sessions.mdx
@@ -22,10 +22,10 @@ Anyone granted at least one access bundle can create a session. Admins can creat
In Agent Vault, go to **Sessions** and select **Create Session**.
</Step>
<Step>
- Pick the **Access Bundle** the agent should use, set a duration under **Expires**, then select **Create Session**.
+ Pick the **Access Bundle** the agent should use, optionally enter a **Label** that says what the session is for, set a duration under **Expires**, then select **Create Session**.
<Frame>
- <img src="/images/platform/agent-vault/session-create.png" alt="The Create Session dialog with an access bundle picked and a seven day expiry" />
+ <img src="/images/platform/agent-vault/session-create.png" alt="The Create Session dialog with an access bundle picked, a label, and a seven day expiry" />
</Frame>
</Step>
<Step>
@@ -53,18 +53,18 @@ Anyone granted at least one access bundle can create a session. Admins can creat
infisical agent-vault run --access-bundle <bundle-name> --proxy <proxy-address> -- <agent-command>
```
- Set the duration with [`--ttl`](/cli/reference#agent-vault-run--flag-ttl), which takes a value like `30m`, `8h`, `7d`, or `never`.
+ Set the duration with [`--ttl`](/cli/reference#agent-vault-run--flag-ttl), which takes a value like `30m`, `8h`, `7d`, or `never`. To [label the session](#label-a-session), pass [`--label`](/cli/reference#agent-vault-run--flag-label).
The CLI creates the session as your user by default, or as a machine identity when you pass `--client-id` and `--client-secret` (or their environment variables). It revokes the session when the agent exits unless you pass `--keep-session`.
</Tab>
<Tab title="API">
- Call [the endpoint that creates a session](/api-reference/endpoints/agent-vault-sessions/create) with the access bundle's name and a `ttl`:
+ Call [the endpoint that creates a session](/api-reference/endpoints/agent-vault-sessions/create) with the access bundle's name, a `ttl`, and optionally a `label`:
```bash
curl -X POST https://app.infisical.com/api/v1/agent-vault/sessions \
-H "Authorization: Bearer <access-token>" \
-H "Content-Type: application/json" \
- -d '{"accessBundles": ["<access-bundle-name>"], "ttl": "1h"}'
+ -d '{"accessBundles": ["<access-bundle-name>"], "ttl": "1h", "label": "nightly deploy"}'
```
The response includes the session token.
@@ -75,6 +75,15 @@ Anyone granted at least one access bundle can create a session. Admins can creat
Picking **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>
+## Label a session
+
+A 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:
+
+- 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 on
+
## View session logs
[Session logs](/documentation/platform/agent-vault/session-logs) record every request an agent makes during a session. To view them, go to **Sessions** and select **View Session Logs** on the session's row. You can filter and search the requests, and while the session is active, new logs keep appearing.
@@ -90,7 +99,7 @@ To revoke a session before it expires, go to the **Sessions** page, open the ses
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" />
+ <img src="/images/platform/agent-vault/sessions-list.png" alt="The Sessions page listing active, revoked, and expired sessions with their label, access bundle, and expiry" />
</Frame>
## Access changes
@@ -108,6 +117,6 @@ If a session stops getting credentials because of a lost grant or a deleted bund
## Audit trail
-When 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.
+When you create a session, change its label, or revoke it, 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 which requests an agent made while its session was running, [view its session logs](#view-session-logs).
diff --git a/docs/images/platform/agent-vault/session-create.png b/docs/images/platform/agent-vault/session-create.png
index 4c79ae5983..07adb40cf5 100644
Binary files a/docs/images/platform/agent-vault/session-create.png and b/docs/images/platform/agent-vault/session-create.png differ
diff --git a/docs/images/platform/agent-vault/session-logs-view.png b/docs/images/platform/agent-vault/session-logs-view.png
index 8ea4177274..c83ea505ef 100644
Binary files a/docs/images/platform/agent-vault/session-logs-view.png and b/docs/images/platform/agent-vault/session-logs-view.png differ
diff --git a/docs/images/platform/agent-vault/sessions-list.png b/docs/images/platform/agent-vault/sessions-list.png
index 68b12d2b4c..86da2f0b6c 100644
Binary files a/docs/images/platform/agent-vault/sessions-list.png and b/docs/images/platform/agent-vault/sessions-list.png differ
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index e190929106..dbc51c1202 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -309,6 +309,7 @@ export enum ProjectPermissionAgentVaultAccessBundleActions {
export enum ProjectPermissionAgentVaultSessionActions {
Read = "read",
Create = "create",
+ Edit = "edit",
Revoke = "revoke"
}
diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsx
index 00ebdd0842..733b3f319a 100644
--- a/frontend/src/hooks/api/agentVault/mutations.tsx
+++ b/frontend/src/hooks/api/agentVault/mutations.tsx
@@ -20,6 +20,7 @@ import {
TAgentVaultProxySettingsDTO,
TAgentVaultProxyWithToken,
TAgentVaultService,
+ TAgentVaultSession,
TAgentVaultSessionLogSettingsState,
TAgentVaultVariable,
TAgentVaultWrittenMember,
@@ -32,6 +33,7 @@ import {
TUpdateAgentVaultAccessBundleDTO,
TUpdateAgentVaultMemberRolesDTO,
TUpdateAgentVaultServiceDTO,
+ TUpdateAgentVaultSessionLabelDTO,
TUpdateAgentVaultSessionLogSettingsDTO,
TUpdateAgentVaultVariableDTO
} from "./types";
@@ -223,6 +225,23 @@ export const useCreateAgentVaultSession = () => {
});
};
+export const useUpdateAgentVaultSessionLabel = () => {
+ const { currentOrg } = useOrganization();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ sessionId, label }: TUpdateAgentVaultSessionLabelDTO) => {
+ const { data } = await apiRequest.patch<{ session: TAgentVaultSession }>(
+ `/api/v1/agent-vault/sessions/${sessionId}`,
+ { label }
+ );
+ return data.session;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.sessions(currentOrg.id) });
+ }
+ });
+};
+
export const useRevokeAgentVaultSession = () => {
const { currentOrg } = useOrganization();
const queryClient = useQueryClient();
diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.ts
index c9a41f86bc..3f263f88f6 100644
--- a/frontend/src/hooks/api/agentVault/types.ts
+++ b/frontend/src/hooks/api/agentVault/types.ts
@@ -324,6 +324,11 @@ export type TCreateAgentVaultSessionDTO = {
label?: string;
};
+export type TUpdateAgentVaultSessionLabelDTO = {
+ sessionId: string;
+ label: string | null;
+};
+
export type TAgentVaultProxySettingsDTO = {
name: string;
trafficPolicy?: AgentVaultTrafficPolicy;
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index 9fbd666468..78ead5dbc6 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -494,6 +494,7 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD]: "Grant access bundle",
[EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE]: "Revoke access bundle",
[EventType.AGENT_VAULT_SESSION_MINT]: "Create session",
+ [EventType.AGENT_VAULT_SESSION_UPDATE]: "Update session label",
[EventType.AGENT_VAULT_SESSION_REVOKE]: "Revoke session",
[EventType.AGENT_VAULT_PROXY_REGISTER]: "Create proxy",
[EventType.AGENT_VAULT_PROXY_TOKEN_REISSUE]: "Generate proxy enrollment token",
@@ -579,6 +580,7 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {
EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD,
EventType.AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE,
EventType.AGENT_VAULT_SESSION_MINT,
+ EventType.AGENT_VAULT_SESSION_UPDATE,
EventType.AGENT_VAULT_SESSION_REVOKE,
EventType.AGENT_VAULT_PROXY_REGISTER,
EventType.AGENT_VAULT_PROXY_TOKEN_REISSUE,
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 287e31e0c1..ac14e2d56d 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -492,6 +492,7 @@ export enum EventType {
AGENT_VAULT_ACCESS_BUNDLE_MEMBER_ADD = "agent-vault-access-bundle-member-add",
AGENT_VAULT_ACCESS_BUNDLE_MEMBER_REMOVE = "agent-vault-access-bundle-member-remove",
AGENT_VAULT_SESSION_MINT = "agent-vault-session-mint",
+ AGENT_VAULT_SESSION_UPDATE = "agent-vault-session-update",
AGENT_VAULT_SESSION_REVOKE = "agent-vault-session-revoke",
AGENT_VAULT_PROXY_REGISTER = "agent-vault-proxy-register",
AGENT_VAULT_PROXY_TOKEN_REISSUE = "agent-vault-proxy-token-reissue",
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx
index 38471c1ab0..8d72671167 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx
@@ -11,6 +11,7 @@ import {
LogsIcon,
MoreHorizontalIcon,
PackageIcon,
+ PencilIcon,
PlusIcon,
SearchIcon,
TriangleAlertIcon,
@@ -89,6 +90,7 @@ import { SessionLogReadAccessAlert } from "@app/pages/agent-vault/AgentVaultSett
import { AgentVaultDocsUrls } from "../agent-vault-docs-urls";
import { CreateSessionDialog } from "./components/CreateSessionDialog";
+import { EditSessionLabelDialog } from "./components/EditSessionLabelDialog";
import { RevokeSessionDialog } from "./components/RevokeSessionDialog";
import { SessionCreatedDialog } from "./components/SessionCreatedDialog";
import { SessionDetailSheet } from "./components/SessionDetailSheet";
@@ -126,6 +128,7 @@ export const AgentVaultSessionsPage = () => {
getUserTablePreference("agentVaultSessionsTable", PreferenceKey.PerPage, 20)
);
const [sessionToRevoke, setSessionToRevoke] = useState<TAgentVaultSession | null>(null);
+ const [sessionToLabel, setSessionToLabel] = useState<TAgentVaultSession | null>(null);
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [mintedSession, setMintedSession] = useState<TAgentVaultMintedSession | null>(null);
const { sessionId: openSessionId, openSheet } = useAgentVaultSheetState();
@@ -286,6 +289,7 @@ export const AgentVaultSessionsPage = () => {
setSearch(e.target.value);
setPage(1);
}}
+ maxLength={255}
placeholder="Search by label, identity, email, or access bundle..."
/>
</InputGroup>
@@ -492,6 +496,10 @@ export const AgentVaultSessionsPage = () => {
<LogsIcon />
View Session Logs
</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setSessionToLabel(session)}>
+ <PencilIcon />
+ {session.label ? "Edit Label" : "Add Label"}
+ </DropdownMenuItem>
<DropdownMenuItem
variant="danger"
isDisabled={session.status !== AgentVaultSessionStatus.Active}
@@ -556,6 +564,14 @@ export const AgentVaultSessionsPage = () => {
session={openSession}
isPending={isOpenSessionPending}
onRevoke={setSessionToRevoke}
+ onEditLabel={setSessionToLabel}
+ />
+
+ <EditSessionLabelDialog
+ session={sessionToLabel}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setSessionToLabel(null);
+ }}
/>
<AgentVaultSessionLogUpgradeModal
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx
index 4f6aa00ee4..559cdcdb60 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/CreateSessionDialog.tsx
@@ -1,7 +1,10 @@
import { useEffect, useRef, useState } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
import { Link } from "@tanstack/react-router";
import { PackageIcon, TriangleAlertIcon } from "lucide-react";
import ms from "ms";
+import { z } from "zod";
import { PersonalValuesDialog } from "@app/components/agent-vault/PersonalValuesDialog";
import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";
@@ -43,6 +46,8 @@ import {
TAgentVaultService
} from "@app/hooks/api/agentVault/types";
+import { sessionLabelSchema } from "./sessionLabelSchema";
+
const NEVER_TTL = "never";
const CUSTOM_TTL = "custom";
@@ -56,8 +61,6 @@ const TTL_PRESETS = [
];
const DEFAULT_TTL_PRESET = "7d";
-const MAX_LABEL_LENGTH = 128;
-
const MIN_TTL_MS = 60 * 1000;
// Mirrors the API's ceiling: past it the expiry overflows and the request fails with a 500.
const MAX_TTL_MS = 100 * 365 * 24 * 60 * 60 * 1000;
@@ -76,6 +79,36 @@ const getCustomTtlError = (value: string) => {
return null;
};
+const schema = z
+ .object({
+ accessBundle: z.custom<TAgentVaultAccessBundleListItem | null>(),
+ label: sessionLabelSchema,
+ ttlPreset: z.string(),
+ customTtl: z.string()
+ })
+ .superRefine((data, ctx) => {
+ if (!data.accessBundle) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["accessBundle"],
+ message: "Pick an access bundle."
+ });
+ }
+ if (data.ttlPreset === CUSTOM_TTL) {
+ const error = getCustomTtlError(data.customTtl);
+ if (error) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["customTtl"], message: error });
+ }
+ });
+
+type FormData = z.infer<typeof schema>;
+
+const DEFAULT_VALUES: FormData = {
+ accessBundle: null,
+ label: "",
+ ttlPreset: DEFAULT_TTL_PRESET,
+ customTtl: ""
+};
+
type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
@@ -94,9 +127,16 @@ export const CreateSessionDialog = ({ isOpen, onOpenChange, onCreated }: Props)
});
const createSession = useCreateAgentVaultSession();
- const [selectedBundle, setSelectedBundle] = useState<TAgentVaultAccessBundleListItem | null>(
- null
- );
+ const {
+ control,
+ handleSubmit,
+ reset,
+ watch,
+ formState: { isSubmitting }
+ } = useForm<FormData>({ resolver: zodResolver(schema), defaultValues: DEFAULT_VALUES });
+ const selectedBundle = watch("accessBundle");
+ const ttlPreset = watch("ttlPreset");
+
const { data: selectedBundleDetails } = useGetAgentVaultAccessBundle(selectedBundle?.id ?? "");
const needsSetup =
selectedBundle && selectedBundleDetails?.id === selectedBundle.id
@@ -108,35 +148,21 @@ export const CreateSessionDialog = ({ isOpen, onOpenChange, onCreated }: Props)
const shownNeedsSetup = needsSetup.length > 4 ? needsSetup.slice(0, 3) : needsSetup;
const hiddenNeedsSetupCount = needsSetup.length - shownNeedsSetup.length;
const [serviceToSetUp, setServiceToSetUp] = useState<TAgentVaultService | null>(null);
- const [label, setLabel] = useState("");
- const [ttlPreset, setTtlPreset] = useState(DEFAULT_TTL_PRESET);
- const [customTtl, setCustomTtl] = useState("");
- const customTtlInputRef = useRef<HTMLInputElement>(null);
+ const customTtlInputRef = useRef<HTMLInputElement | null>(null);
const shouldFocusCustomTtlRef = useRef(false);
- const isCustomTtl = ttlPreset === CUSTOM_TTL;
- const ttl = isCustomTtl ? customTtl.trim() : ttlPreset;
- const customTtlError = isCustomTtl ? getCustomTtlError(customTtl) : null;
- const isTtlValid = customTtlError === null;
- const visibleTtlError = customTtl.length > 0 ? customTtlError : null;
-
useEffect(() => {
- if (isOpen) {
- setSelectedBundle(null);
- setLabel("");
- setTtlPreset(DEFAULT_TTL_PRESET);
- setCustomTtl("");
- }
- }, [isOpen]);
+ if (isOpen) reset(DEFAULT_VALUES);
+ }, [isOpen, reset]);
- const handleCreate = async () => {
- if (!selectedBundle) return;
+ const onSubmit = async ({ accessBundle, label, ttlPreset: preset, customTtl }: FormData) => {
+ if (!accessBundle) return;
try {
const session = await createSession.mutateAsync({
- accessBundles: [selectedBundle.name],
- ttl,
- label: label.trim() || undefined
+ accessBundles: [accessBundle.name],
+ ttl: preset === CUSTOM_TTL ? customTtl.trim() : preset,
+ label: label || undefined
});
createNotification({ text: "Session created", type: "success" });
onCreated(session);
@@ -157,98 +183,126 @@ export const CreateSessionDialog = ({ isOpen, onOpenChange, onCreated }: Props)
</DialogDescription>
</DialogHeader>
- <div className="flex flex-col gap-4">
- <Field>
- <FieldLabel htmlFor="agent-vault-session-bundle">Access Bundle</FieldLabel>
- <FieldContent>
- <Combobox
- id="agent-vault-session-bundle"
- options={accessBundles?.accessBundles ?? []}
- value={selectedBundle}
- shouldFilter={false}
- isLoading={isSearchingBundles}
- includeMissingSelectedOptions
- onInputValueChange={setBundleSearch}
- getOptionValue={(bundle) => bundle.id}
- getOptionLabel={(bundle) => bundle.name}
- placeholder="Pick an access bundle"
- searchPlaceholder="Search access bundles..."
- emptyMessage="No access bundle matches."
- modal
- renderOption={(bundle) => (
- <span className="flex min-w-0 items-center gap-2">
- <PackageIcon className="size-4 shrink-0 text-muted" />
- <span className="truncate">{bundle.name}</span>
- </span>
- )}
- renderValue={(bundle) => (
- <span className="flex min-w-0 items-center gap-2">
- <PackageIcon className="size-4 shrink-0 text-muted" />
- <span className="truncate">{bundle.name}</span>
- </span>
- )}
- onValueChange={setSelectedBundle}
- onClear={() => setSelectedBundle(null)}
- />
- </FieldContent>
- </Field>
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
+ <Controller
+ control={control}
+ name="accessBundle"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel htmlFor="agent-vault-session-bundle">Access Bundle</FieldLabel>
+ <FieldContent>
+ <Combobox
+ id="agent-vault-session-bundle"
+ options={accessBundles?.accessBundles ?? []}
+ value={field.value}
+ shouldFilter={false}
+ isLoading={isSearchingBundles}
+ includeMissingSelectedOptions
+ onInputValueChange={setBundleSearch}
+ getOptionValue={(bundle) => bundle.id}
+ getOptionLabel={(bundle) => bundle.name}
+ placeholder="Pick an access bundle"
+ searchPlaceholder="Search access bundles..."
+ emptyMessage="No access bundle matches."
+ modal
+ renderOption={(bundle) => (
+ <span className="flex min-w-0 items-center gap-2">
+ <PackageIcon className="size-4 shrink-0 text-muted" />
+ <span className="truncate">{bundle.name}</span>
+ </span>
+ )}
+ renderValue={(bundle) => (
+ <span className="flex min-w-0 items-center gap-2">
+ <PackageIcon className="size-4 shrink-0 text-muted" />
+ <span className="truncate">{bundle.name}</span>
+ </span>
+ )}
+ onValueChange={field.onChange}
+ onClear={() => field.onChange(null)}
+ />
+ </FieldContent>
+ </Field>
+ )}
+ />
- <Field>
- <FieldLabel htmlFor="agent-vault-session-label">Label</FieldLabel>
- <FieldContent>
- <Input
- id="agent-vault-session-label"
- value={label}
- onChange={(e) => setLabel(e.target.value)}
- maxLength={MAX_LABEL_LENGTH}
- placeholder="Nightly deploy"
- />
- <FieldDescription>Optional. Describes what this session is for.</FieldDescription>
- </FieldContent>
- </Field>
+ <Controller
+ control={control}
+ name="label"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel htmlFor="agent-vault-session-label">
+ Label <span className="text-muted">(optional)</span>
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ id="agent-vault-session-label"
+ placeholder="Nightly deploy"
+ isError={Boolean(fieldState.error)}
+ />
+ <FieldDescription>Describes what this session is for.</FieldDescription>
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
<Field>
<FieldLabel>Expires</FieldLabel>
<FieldContent>
- <Select
- value={ttlPreset}
- onValueChange={(value) => {
- shouldFocusCustomTtlRef.current = value === CUSTOM_TTL;
- setTtlPreset(value);
- }}
- >
- <SelectTrigger className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent
- position="popper"
- onCloseAutoFocus={(e) => {
- if (!shouldFocusCustomTtlRef.current) return;
- shouldFocusCustomTtlRef.current = false;
- e.preventDefault();
- customTtlInputRef.current?.focus();
- }}
- >
- {TTL_PRESETS.map((preset) => (
- <SelectItem key={preset.value} value={preset.value}>
- {preset.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {isCustomTtl && (
- <>
- <Input
- ref={customTtlInputRef}
- className="mt-2"
- value={customTtl}
- onChange={(e) => setCustomTtl(e.target.value)}
- placeholder="90m"
- isError={visibleTtlError !== null}
- />
- <FieldDescription>A duration such as 30m, 8h, or 7d.</FieldDescription>
- <FieldError>{visibleTtlError}</FieldError>
- </>
+ <Controller
+ control={control}
+ name="ttlPreset"
+ render={({ field }) => (
+ <Select
+ value={field.value}
+ onValueChange={(value) => {
+ shouldFocusCustomTtlRef.current = value === CUSTOM_TTL;
+ field.onChange(value);
+ }}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent
+ position="popper"
+ onCloseAutoFocus={(e) => {
+ if (!shouldFocusCustomTtlRef.current) return;
+ shouldFocusCustomTtlRef.current = false;
+ e.preventDefault();
+ customTtlInputRef.current?.focus();
+ }}
+ >
+ {TTL_PRESETS.map((preset) => (
+ <SelectItem key={preset.value} value={preset.value}>
+ {preset.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ {ttlPreset === CUSTOM_TTL && (
+ <Controller
+ control={control}
+ name="customTtl"
+ render={({ field, fieldState }) => (
+ <>
+ <Input
+ {...field}
+ ref={(el) => {
+ field.ref(el);
+ customTtlInputRef.current = el;
+ }}
+ className="mt-2"
+ placeholder="90m"
+ isError={Boolean(fieldState.error)}
+ />
+ <FieldDescription>A duration such as 30m, 8h, or 7d.</FieldDescription>
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </>
+ )}
+ />
)}
{ttlPreset === NEVER_TTL && (
<FieldDescription>This session runs until someone revokes it.</FieldDescription>
@@ -303,21 +357,20 @@ export const CreateSessionDialog = ({ isOpen, onOpenChange, onCreated }: Props)
</AlertDescription>
</Alert>
)}
- </div>
-
- <DialogFooter>
- <Button variant="ghost" onClick={() => onOpenChange(false)}>
- Cancel
- </Button>
- <Button
- variant="av"
- isDisabled={!selectedBundle || !isTtlValid}
- isPending={createSession.isPending}
- onClick={async () => handleCreate()}
- >
- Create Session
- </Button>
- </DialogFooter>
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ variant="av"
+ isDisabled={!selectedBundle}
+ isPending={isSubmitting}
+ >
+ Create Session
+ </Button>
+ </DialogFooter>
+ </form>
<PersonalValuesDialog
target={
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/EditSessionLabelDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/EditSessionLabelDialog.tsx
new file mode 100644
index 0000000000..75d96bcd63
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/EditSessionLabelDialog.tsx
@@ -0,0 +1,106 @@
+import { useEffect } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input
+} from "@app/components/v3";
+import { useUpdateAgentVaultSessionLabel } from "@app/hooks/api/agentVault";
+import { TAgentVaultSession } from "@app/hooks/api/agentVault/types";
+
+import { sessionLabelSchema } from "./sessionLabelSchema";
+
+const schema = z.object({ label: sessionLabelSchema });
+
+type FormData = z.infer<typeof schema>;
+
+type Props = {
+ session: TAgentVaultSession | null;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+export const EditSessionLabelDialog = ({ session, onOpenChange }: Props) => {
+ const updateLabel = useUpdateAgentVaultSessionLabel();
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ formState: { isSubmitting }
+ } = useForm<FormData>({ resolver: zodResolver(schema) });
+
+ useEffect(() => {
+ if (session) reset({ label: session.label ?? "" });
+ }, [session, reset]);
+
+ const onSubmit = async ({ label }: FormData) => {
+ if (!session) return;
+
+ try {
+ await updateLabel.mutateAsync({ sessionId: session.id, label: label || null });
+ createNotification({
+ text: label ? "Session label saved" : "Session label removed",
+ type: "success"
+ });
+ onOpenChange(false);
+ } catch {
+ // A failed request returns a 4xx that the global request handler surfaces as a toast
+ }
+ };
+
+ return (
+ <Dialog open={Boolean(session)} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{session?.label ? "Edit Label" : "Add Label"}</DialogTitle>
+ <DialogDescription>A label describes what this session is for.</DialogDescription>
+ </DialogHeader>
+
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
+ <Controller
+ control={control}
+ name="label"
+ render={({ field, fieldState }) => (
+ <Field>
+ <FieldLabel htmlFor="agent-vault-session-label-edit">Label</FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ id="agent-vault-session-label-edit"
+ placeholder="Nightly deploy"
+ isError={Boolean(fieldState.error)}
+ />
+ <FieldDescription>Leave it empty to remove the label.</FieldDescription>
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )}
+ />
+
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="av" isPending={isSubmitting}>
+ Save
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/RevokeSessionDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/RevokeSessionDialog.tsx
index 2b369956a8..7d33ca24ec 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/RevokeSessionDialog.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/RevokeSessionDialog.tsx
@@ -4,6 +4,12 @@ import { ConfirmationAlertDialog } from "@app/components/v3";
import { useRevokeAgentVaultSession } from "@app/hooks/api/agentVault";
import { TAgentVaultSession } from "@app/hooks/api/agentVault/types";
+// The label tells sessions apart when one identity holds several, so it leads when there is one.
+const describeSession = (session: TAgentVaultSession) =>
+ session.label
+ ? `"${session.label}" for "${memberDisplayName(session.actor)}"`
+ : `for "${memberDisplayName(session.actor)}"`;
+
type Props = {
session: TAgentVaultSession | null;
onOpenChange: (isOpen: boolean) => void;
@@ -18,7 +24,7 @@ export const RevokeSessionDialog = ({ session, onOpenChange }: Props) => {
try {
await revokeSession.mutateAsync(session.id);
createNotification({
- text: `Session for "${memberDisplayName(session.actor)}" revoked`,
+ text: `Session ${describeSession(session)} revoked`,
type: "success"
});
onOpenChange(false);
@@ -31,7 +37,7 @@ export const RevokeSessionDialog = ({ session, onOpenChange }: Props) => {
<ConfirmationAlertDialog
isOpen={Boolean(session)}
onOpenChange={onOpenChange}
- title={`Revoke Session for "${session ? memberDisplayName(session.actor) : ""}"`}
+ title={session ? `Revoke Session ${describeSession(session)}` : "Revoke Session"}
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/SessionDetailSheet.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx
index d49d31fde0..651e40922f 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionDetailSheet.tsx
@@ -1,6 +1,6 @@
import { Link } from "@tanstack/react-router";
import { format } from "date-fns";
-import { BanIcon, BotIcon, PackageIcon, UserIcon } from "lucide-react";
+import { BanIcon, BotIcon, PackageIcon, PencilIcon, UserIcon } from "lucide-react";
import { twMerge } from "tailwind-merge";
import { memberDisplayName, memberSubtitle } from "@app/components/agent-vault/MemberName";
@@ -13,6 +13,7 @@ import {
EmptyDescription,
EmptyHeader,
EmptyTitle,
+ IconButton,
Sheet,
SheetContent,
SheetDescription,
@@ -33,9 +34,15 @@ type Props = {
session: TAgentVaultSession | undefined;
isPending?: boolean;
onRevoke: (session: TAgentVaultSession) => void;
+ onEditLabel: (session: TAgentVaultSession) => void;
};
-export const SessionDetailSheet = ({ session, isPending = false, onRevoke }: Props) => {
+export const SessionDetailSheet = ({
+ session,
+ isPending = false,
+ onRevoke,
+ onEditLabel
+}: Props) => {
const { isOpen, closeSheet } = useAgentVaultSheetState();
const { currentOrg } = useOrganization();
@@ -174,12 +181,24 @@ export const SessionDetailSheet = ({ session, isPending = false, onRevoke }: Pro
</Button>
)}
</div>
- {session.label && (
- <Detail className="min-w-0 border-t border-border px-4 py-3">
+ <div className="flex items-start gap-2 border-t border-border px-4 py-3">
+ <Detail className="min-w-0 flex-1">
<DetailLabel>Label</DetailLabel>
- <DetailValue className="min-w-0 break-words">{session.label}</DetailValue>
+ <DetailValue
+ className={twMerge("min-w-0 break-words", !session.label && "text-muted")}
+ >
+ {session.label ?? "No label"}
+ </DetailValue>
</Detail>
- )}
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label={session.label ? "Edit label" : "Add label"}
+ onClick={() => onEditLabel(session)}
+ >
+ <PencilIcon />
+ </IconButton>
+ </div>
</div>
<div className="flex min-h-0 flex-1 flex-col">
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/sessionLabelSchema.ts b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/sessionLabelSchema.ts
new file mode 100644
index 0000000000..f035083809
--- /dev/null
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/sessionLabelSchema.ts
@@ -0,0 +1,15 @@
+import { z } from "zod";
+
+export const SESSION_LABEL_MAX_LENGTH = 128;
+
+// Mirrors the API's rule. With the u flag a lone surrogate is its own code point, so \p{Cs} sees it.
+const DISALLOWED_LABEL_CHARS_RE = /[\p{Cc}\p{Cf}\p{Co}\p{Cs}\p{Zl}\p{Zp}]/u;
+
+export const sessionLabelSchema = z
+ .string()
+ .trim()
+ .max(SESSION_LABEL_MAX_LENGTH, `A label can be at most ${SESSION_LABEL_MAX_LENGTH} characters`)
+ .refine(
+ (label) => !DISALLOWED_LABEL_CHARS_RE.test(label),
+ "A label can't contain line breaks, tabs, or invisible characters such as zero-width spaces or text direction marks."
+ );
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index de19b2ecf3..f755bf7792 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -301,6 +301,7 @@ const AgentVaultAccessBundlePolicyActionSchema = z.object({
const AgentVaultSessionPolicyActionSchema = z.object({
[ProjectPermissionAgentVaultSessionActions.Read]: z.boolean().optional(),
[ProjectPermissionAgentVaultSessionActions.Create]: z.boolean().optional(),
+ [ProjectPermissionAgentVaultSessionActions.Edit]: z.boolean().optional(),
[ProjectPermissionAgentVaultSessionActions.Revoke]: z.boolean().optional()
});
@@ -2545,6 +2546,11 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
value: ProjectPermissionAgentVaultSessionActions.Create,
description: "Mint a session over access bundles you can reach"
},
+ {
+ label: "Edit",
+ value: ProjectPermissionAgentVaultSessionActions.Edit,
+ description: "Change a session's label"
+ },
{
label: "Revoke",
value: ProjectPermissionAgentVaultSessionActions.Revoke,