Skip to content

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

Add a reason field before PAM account access

Carlos Monastyrski264d397100c8
diff --git a/backend/src/db/migrations/20260417245211_pam-session-reason.ts b/backend/src/db/migrations/20260417245211_pam-session-reason.ts
new file mode 100644
index 0000000000..57cad699b7
--- /dev/null
+++ b/backend/src/db/migrations/20260417245211_pam-session-reason.ts
@@ -0,0 +1,25 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PamSession)) {
+ const hasCol = await knex.schema.hasColumn(TableName.PamSession, "reason");
+ if (!hasCol) {
+ await knex.schema.alterTable(TableName.PamSession, (t) => {
+ t.text("reason").nullable();
+ });
+ }
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PamSession)) {
+ const hasCol = await knex.schema.hasColumn(TableName.PamSession, "reason");
+ if (hasCol) {
+ await knex.schema.alterTable(TableName.PamSession, (t) => {
+ t.dropColumn("reason");
+ });
+ }
+ }
+}
diff --git a/backend/src/db/schemas/pam-sessions.ts b/backend/src/db/schemas/pam-sessions.ts
index f499da367d..a3fc0d4ad4 100644
--- a/backend/src/db/schemas/pam-sessions.ts
+++ b/backend/src/db/schemas/pam-sessions.ts
@@ -32,7 +32,8 @@ export const PamSessionsSchema = z.object({
resourceId: z.string().uuid().nullable().optional(),
encryptedAiInsights: zodBuffer.nullable().optional(),
aiInsightsStatus: z.string().nullable().optional(),
- aiInsightsError: z.string().nullable().optional()
+ aiInsightsError: z.string().nullable().optional(),
+ reason: z.string().nullable().optional()
});
export type TPamSessions = z.infer<typeof PamSessionsSchema>;
diff --git a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts
index 2e4275c550..88f93b4fd5 100644
--- a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts
+++ b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts
@@ -514,6 +514,7 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
accountName: z.string().trim(),
projectId: z.string().uuid(),
mfaSessionId: z.string().optional(),
+ reason: z.string().trim().max(1000).optional(),
duration: z
.string()
.min(1)
@@ -567,7 +568,8 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
accountName: req.body.accountName,
projectId: req.body.projectId,
duration: req.body.duration,
- mfaSessionId: req.body.mfaSessionId
+ mfaSessionId: req.body.mfaSessionId,
+ reason: req.body.reason
},
req.permission
);
@@ -582,7 +584,8 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
accountId: response.account.id,
resourceName: req.body.resourceName,
accountName: response.account.name,
- duration: req.body.duration ? new Date(req.body.duration).toISOString() : undefined
+ duration: req.body.duration ? new Date(req.body.duration).toISOString() : undefined,
+ reason: req.body.reason
}
}
});
@@ -618,7 +621,8 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
}),
body: z.object({
projectId: z.string().uuid(),
- mfaSessionId: z.string().optional()
+ mfaSessionId: z.string().optional(),
+ reason: z.string().trim().max(1000).optional()
}),
response: {
200: z.object({ ticket: z.string() })
@@ -639,7 +643,8 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
actorEmail: req.auth.user.email ?? "",
actorName: `${req.auth.user.firstName ?? ""} ${req.auth.user.lastName ?? ""}`.trim(),
auditLogInfo: req.auditLogInfo,
- mfaSessionId: req.body.mfaSessionId
+ mfaSessionId: req.body.mfaSessionId,
+ reason: req.body.reason
});
await server.services.telemetry
@@ -708,6 +713,7 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
accountName: z.string(),
actorEmail: z.string(),
actorName: z.string(),
+ reason: z.string().nullable().optional(),
auditLogInfo: z.object({
ipAddress: z.string().optional(),
userAgent: z.string().optional(),
@@ -737,7 +743,8 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
auditLogInfo: payload.auditLogInfo as AuditLogInfo,
userId,
actorIp: req.realIp ?? "",
- actorUserAgent: req.headers["user-agent"] ?? ""
+ actorUserAgent: req.headers["user-agent"] ?? "",
+ reason: payload.reason
});
} catch (err) {
logger.error(err, "WebSocket ticket validation failed");
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 41d5206eb2..9be8dd24a9 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -4923,6 +4923,7 @@ interface PamAccountAccessEvent {
resourceName: string;
accountName: string;
duration?: string;
+ reason?: string;
};
}
diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-constants.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-constants.ts
index 1206b2c7c2..c6f9069a83 100644
--- a/backend/src/ee/services/pam-account-policy/pam-account-policy-constants.ts
+++ b/backend/src/ee/services/pam-account-policy/pam-account-policy-constants.ts
@@ -4,7 +4,8 @@ import { PamAccountPolicyRuleType } from "./pam-account-policy-enums";
export const PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES: Record<PamAccountPolicyRuleType, PamResource[] | "all"> = {
[PamAccountPolicyRuleType.CommandBlocking]: [PamResource.SSH],
- [PamAccountPolicyRuleType.SessionLogMasking]: "all"
+ [PamAccountPolicyRuleType.SessionLogMasking]: "all",
+ [PamAccountPolicyRuleType.RequireReason]: "all"
};
export const PAM_ACCOUNT_POLICY_RULE_METADATA: Record<PamAccountPolicyRuleType, { name: string; description: string }> =
@@ -16,5 +17,9 @@ export const PAM_ACCOUNT_POLICY_RULE_METADATA: Record<PamAccountPolicyRuleType,
[PamAccountPolicyRuleType.SessionLogMasking]: {
name: "Session Log Masking",
description: "Mask sensitive data in session logs matching specified patterns"
+ },
+ [PamAccountPolicyRuleType.RequireReason]: {
+ name: "Require Access Reason",
+ description: "Require users to provide a reason before they can start a session"
}
};
diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-enums.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-enums.ts
index 0461215089..e62f5a97be 100644
--- a/backend/src/ee/services/pam-account-policy/pam-account-policy-enums.ts
+++ b/backend/src/ee/services/pam-account-policy/pam-account-policy-enums.ts
@@ -1,4 +1,5 @@
export enum PamAccountPolicyRuleType {
CommandBlocking = "command-blocking",
- SessionLogMasking = "session-log-masking"
+ SessionLogMasking = "session-log-masking",
+ RequireReason = "require-reason"
}
diff --git a/backend/src/ee/services/pam-account-policy/pam-account-policy-schemas.ts b/backend/src/ee/services/pam-account-policy/pam-account-policy-schemas.ts
index 1901f82e67..2814a37cea 100644
--- a/backend/src/ee/services/pam-account-policy/pam-account-policy-schemas.ts
+++ b/backend/src/ee/services/pam-account-policy/pam-account-policy-schemas.ts
@@ -26,9 +26,12 @@ const RuleConfigSchema = z.object({
patterns: z.array(re2PatternSchema).min(1).max(20, "A rule can have at most 20 patterns")
});
+const RequireReasonConfigSchema = z.object({});
+
export const PolicyRulesBaseSchema = z.object({
[PamAccountPolicyRuleType.CommandBlocking]: RuleConfigSchema.optional(),
- [PamAccountPolicyRuleType.SessionLogMasking]: RuleConfigSchema.optional()
+ [PamAccountPolicyRuleType.SessionLogMasking]: RuleConfigSchema.optional(),
+ [PamAccountPolicyRuleType.RequireReason]: RequireReasonConfigSchema.optional()
});
export const PolicyRulesInputSchema = PolicyRulesBaseSchema.refine(
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts
index cb658ef7a5..40155001e7 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -632,7 +632,8 @@ export const pamAccountServiceFactory = ({
actorName,
actorUserAgent,
duration,
- mfaSessionId
+ mfaSessionId,
+ reason
}: TAccessAccountDTO,
actor: OrgServiceActor
) => {
@@ -655,6 +656,19 @@ export const pamAccountServiceFactory = ({
});
}
+ const trimmedReason = reason?.trim() || null;
+
+ if (account.policyId) {
+ const policy = await pamAccountPolicyDAL.findById(account.policyId);
+ const policyRules = (policy?.rules ?? {}) as TPolicyRules;
+ if (policy?.isActive && policyRules[PamAccountPolicyRuleType.RequireReason] && !trimmedReason) {
+ throw new BadRequestError({
+ message: "A reason is required to access this account",
+ name: "PAM_REASON_REQUIRED"
+ });
+ }
+ }
+
const fac = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.PamAccess](ApprovalPolicyType.PamAccess);
const inputs = {
@@ -819,7 +833,8 @@ export const pamAccountServiceFactory = ({
resourceId: resource.id,
userId: actor.id,
expiresAt,
- startedAt: new Date()
+ startedAt: new Date(),
+ reason: trimmedReason
});
// Schedule session expiration job to run at expiresAt
@@ -853,7 +868,8 @@ export const pamAccountServiceFactory = ({
accountId: account.id,
resourceId: resource.id,
userId: actor.id,
- expiresAt: new Date(Date.now() + duration)
+ expiresAt: new Date(Date.now() + duration),
+ reason: trimmedReason
});
if (!gatewayId) {
@@ -1045,13 +1061,17 @@ export const pamAccountServiceFactory = ({
const policy = await pamAccountPolicyDAL.findById(account.policyId);
if (policy && policy.isActive) {
const rules = (policy.rules ?? {}) as TPolicyRules;
- for (const ruleType of Object.values(PamAccountPolicyRuleType)) {
+
+ const gatewayRuleTypes = [
+ PamAccountPolicyRuleType.CommandBlocking,
+ PamAccountPolicyRuleType.SessionLogMasking
+ ] as const;
+ for (const ruleType of gatewayRuleTypes) {
const ruleConfig = rules[ruleType];
- if (ruleConfig) {
- const supported = PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES[ruleType];
- if (supported === "all" || supported.includes(resource.resourceType as PamResource)) {
- policyRules[ruleType] = ruleConfig;
- }
+ const supported = PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES[ruleType];
+ const isSupported = supported === "all" || supported.includes(resource.resourceType as PamResource);
+ if (ruleConfig && isSupported) {
+ policyRules[ruleType] = ruleConfig;
}
}
}
diff --git a/backend/src/ee/services/pam-account/pam-account-types.ts b/backend/src/ee/services/pam-account/pam-account-types.ts
index 7ef9273614..d4a2a1091c 100644
--- a/backend/src/ee/services/pam-account/pam-account-types.ts
+++ b/backend/src/ee/services/pam-account/pam-account-types.ts
@@ -30,6 +30,7 @@ export type TAccessAccountDTO = {
actorUserAgent: string;
duration: number;
mfaSessionId?: string;
+ reason?: string;
};
export type TListAccountsDTO = {
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
index 2b8d747674..7849cc2996 100644
--- a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
@@ -33,6 +33,9 @@ import { TUserDALFactory } from "@app/services/user/user-dal";
import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
import { decryptAccountCredentials } from "../pam-account/pam-account-fns";
+import { TPamAccountPolicyDALFactory } from "../pam-account-policy/pam-account-policy-dal";
+import { PamAccountPolicyRuleType } from "../pam-account-policy/pam-account-policy-enums";
+import { TPolicyRules } from "../pam-account-policy/pam-account-policy-types";
import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";
import { decryptResourceConnectionDetails } from "../pam-resource/pam-resource-fns";
import {
@@ -64,6 +67,7 @@ const SUPPORTED_WEB_ACCESS_RESOURCES = [PamResource.Postgres, PamResource.SSH, P
type TPamWebAccessServiceFactoryDep = {
pamAccountDAL: Pick<TPamAccountDALFactory, "findById" | "findMetadataByAccountIds">;
+ pamAccountPolicyDAL: Pick<TPamAccountPolicyDALFactory, "findById">;
pamResourceDAL: Pick<TPamResourceDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
@@ -98,9 +102,11 @@ type THandleWebSocketConnectionDTO = {
actorName: string;
actorIp: string;
actorUserAgent: string;
+ reason?: string | null;
};
export const pamWebAccessServiceFactory = ({
pamAccountDAL,
+ pamAccountPolicyDAL,
pamResourceDAL,
permissionService,
auditLogService,
@@ -160,7 +166,8 @@ export const pamWebAccessServiceFactory = ({
actorEmail,
actorName,
auditLogInfo,
- mfaSessionId
+ mfaSessionId,
+ reason
}: TIssueWebSocketTicketDTO) => {
const account = await pamAccountDAL.findById(accountId);
@@ -172,6 +179,19 @@ export const pamWebAccessServiceFactory = ({
throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
}
+ const trimmedReason = reason?.trim() || null;
+
+ if (account.policyId) {
+ const policy = await pamAccountPolicyDAL.findById(account.policyId);
+ const policyRules = (policy?.rules ?? {}) as TPolicyRules;
+ if (policy?.isActive && policyRules[PamAccountPolicyRuleType.RequireReason] && !trimmedReason) {
+ throw new BadRequestError({
+ message: "A reason is required to access this account",
+ name: "PAM_REASON_REQUIRED"
+ });
+ }
+ }
+
const resource = await pamResourceDAL.findById(account.resourceId);
if (!resource) {
@@ -295,7 +315,8 @@ export const pamWebAccessServiceFactory = ({
accountName: account.name,
actorEmail,
actorName,
- auditLogInfo
+ auditLogInfo,
+ reason: trimmedReason
})
});
@@ -328,7 +349,8 @@ export const pamWebAccessServiceFactory = ({
actorEmail,
actorName,
actorIp,
- actorUserAgent
+ actorUserAgent,
+ reason: accessReason
}: THandleWebSocketConnectionDTO): Promise<void> => {
let session: { id: string } | null = null;
let cleanedUp = false;
@@ -476,7 +498,8 @@ export const pamWebAccessServiceFactory = ({
resourceType: resource.resourceType,
accountId: account.id,
resourceId: resource.id,
- userId
+ userId,
+ reason: accessReason?.trim() || null
});
await pamSessionExpirationService.scheduleSessionExpiration(session.id, expiresAt);
@@ -578,7 +601,8 @@ export const pamWebAccessServiceFactory = ({
accountId,
resourceName,
accountName,
- duration: expiresAt.toISOString()
+ duration: expiresAt.toISOString(),
+ reason: accessReason ?? undefined
}
}
});
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts b/backend/src/ee/services/pam-web-access/pam-web-access-types.ts
index 1263290f0a..2a09937edf 100644
--- a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-types.ts
@@ -70,4 +70,5 @@ export type TIssueWebSocketTicketDTO = {
actorName: string;
auditLogInfo: AuditLogInfo;
mfaSessionId?: string;
+ reason?: string;
};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index de8a5cf558..1dc566f61b 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2954,6 +2954,7 @@ export const registerRoutes = async (
const pamWebAccessService = pamWebAccessServiceFactory({
pamAccountDAL,
+ pamAccountPolicyDAL,
pamResourceDAL,
permissionService,
auditLogService,
diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsx
index af356dfd56..2fcb857b0f 100644
--- a/frontend/src/hooks/api/pam/mutations.tsx
+++ b/frontend/src/hooks/api/pam/mutations.tsx
@@ -191,6 +191,7 @@ export type TAccessPamAccountDTO = {
accountName: string;
projectId: string;
duration: string;
+ reason?: string;
};
export type TAccessPamAccountResponse = {
@@ -214,7 +215,8 @@ export const useAccessPamAccount = () => {
resourceName,
accountName,
projectId,
- duration
+ duration,
+ reason
}: TAccessPamAccountDTO) => {
const { data } = await apiRequest.post<TAccessPamAccountResponse>(
"/api/v1/pam/accounts/access",
@@ -223,7 +225,8 @@ export const useAccessPamAccount = () => {
resourceName,
accountName,
projectId,
- duration
+ duration,
+ reason
}
);
diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx
index 7d8e8ba54d..d9fca70c1c 100644
--- a/frontend/src/hooks/api/pam/queries.tsx
+++ b/frontend/src/hooks/api/pam/queries.tsx
@@ -487,3 +487,29 @@ export const useListPamAccountPolicies = (
...options
});
};
+
+export const useGetPamAccountPolicy = (
+ policyId: string | null | undefined,
+ options?: Omit<
+ UseQueryOptions<
+ TPamAccountPolicy,
+ unknown,
+ TPamAccountPolicy,
+ ReturnType<typeof pamKeys.getAccountPolicy>
+ >,
+ "queryKey" | "queryFn" | "enabled"
+ >
+) => {
+ return useQuery({
+ queryKey: pamKeys.getAccountPolicy(policyId ?? ""),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ policy: TPamAccountPolicy }>(
+ `/api/v1/pam/account-policies/${policyId}`
+ );
+
+ return data.policy;
+ },
+ enabled: Boolean(policyId),
+ ...options
+ });
+};
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index d226e06e3a..1d1fadeeff 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -132,6 +132,7 @@ export type TPamSession = {
aiInsightsStatus?: string | null;
aiInsightsError?: string | null;
aiInsights?: TPamSessionAiInsights | null;
+ reason?: string | null;
};
// Resource DTOs
@@ -295,11 +296,12 @@ export type TPamSessionLogsPage = {
// Account Policy types
export enum PamAccountPolicyRuleType {
CommandBlocking = "command-blocking",
- SessionLogMasking = "session-log-masking"
+ SessionLogMasking = "session-log-masking",
+ RequireReason = "require-reason"
}
export type TPamAccountPolicyRuleConfig = {
- patterns: string[];
+ patterns?: string[];
};
export type TPamAccountPolicyRules = Partial<
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
index 6e6d9e635c..6219ebe61e 100644
--- a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
+++ b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
@@ -2,30 +2,33 @@ import { useState } from "react";
import { Helmet } from "react-helmet";
import { useParams } from "@tanstack/react-router";
-import { PamResourceType, useGetPamAccountById } from "@app/hooks/api/pam";
+import { PamResourceType, TPamAccount, useGetPamAccountById } from "@app/hooks/api/pam";
import { PamDataExplorerPage } from "@app/pages/pam/PamDataExplorerPage/PamDataExplorerPage";
+import { ReasonGate } from "./ReasonGate";
import { useWebAccessSession } from "./useWebAccessSession";
const TerminalContent = ({
- accountId,
+ account,
projectId,
- orgId
+ orgId,
+ reason
}: {
- accountId: string;
+ account: TPamAccount;
projectId: string;
orgId: string;
+ reason: string;
}) => {
- const { data: account, isPending } = useGetPamAccountById(accountId);
const [sessionEnded, setSessionEnded] = useState(false);
const { containerRef, isConnected, disconnect, reconnect } = useWebAccessSession({
- accountId,
+ accountId: account.id,
projectId,
orgId,
- resourceName: account?.resource.name ?? "",
- accountName: account?.name ?? "",
- resourceType: account?.resource.resourceType ?? "",
+ resourceName: account.resource.name,
+ accountName: account.name,
+ resourceType: account.resource.resourceType,
+ reason,
onSessionEnd: () => setSessionEnded(true)
});
@@ -34,22 +37,6 @@ const TerminalContent = ({
reconnect();
};
- if (isPending) {
- return (
- <div className="flex h-screen w-screen items-center justify-center bg-[#0d1117] text-mineshaft-300">
- Loading...
- </div>
- );
- }
-
- if (!account) {
- return (
- <div className="flex h-screen w-screen items-center justify-center bg-[#0d1117]">
- <p className="text-mineshaft-300">Could not find PAM Account with ID {accountId}</p>
- </div>
- );
- }
-
let statusLabel = "Connecting";
let statusDotClass = "bg-yellow-500";
if (isConnected) {
@@ -129,11 +116,31 @@ const PageContent = () => {
);
}
- if (account?.resource.resourceType === PamResourceType.Postgres) {
- return <PamDataExplorerPage />;
+ if (!account) {
+ return (
+ <div className="flex h-screen w-screen items-center justify-center bg-[#0d1117]">
+ <p className="text-mineshaft-300">Could not find PAM Account with ID {accountId}</p>
+ </div>
+ );
}
- return <TerminalContent accountId={accountId!} projectId={projectId!} orgId={orgId!} />;
+ return (
+ <ReasonGate account={account}>
+ {(reason) => {
+ if (account.resource.resourceType === PamResourceType.Postgres) {
+ return <PamDataExplorerPage reason={reason} />;
+ }
+ return (
+ <TerminalContent
+ account={account}
+ projectId={projectId!}
+ orgId={orgId!}
+ reason={reason}
+ />
+ );
+ }}
+ </ReasonGate>
+ );
};
export const PamAccountAccessPage = () => {
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/ReasonGate.tsx b/frontend/src/pages/pam/PamAccountAccessPage/ReasonGate.tsx
new file mode 100644
index 0000000000..5dbf39eeff
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountAccessPage/ReasonGate.tsx
@@ -0,0 +1,91 @@
+import { ReactNode, useState } from "react";
+import { AlertTriangleIcon } from "lucide-react";
+
+import { Button } from "@app/components/v3/generic/Button";
+import { PamAccountPolicyRuleType, TPamAccount, useGetPamAccountPolicy } from "@app/hooks/api/pam";
+
+type Props = {
+ account: TPamAccount;
+ children: (reason: string) => ReactNode;
+};
+
+export const ReasonGate = ({ account, children }: Props) => {
+ const [submittedReason, setSubmittedReason] = useState<string | null>(null);
+ const [draft, setDraft] = useState("");
+ const [touched, setTouched] = useState(false);
+
+ const { data: policy, isPending: isPolicyQueryPending } = useGetPamAccountPolicy(
+ account.policyId
+ );
+ const isPolicyLoading = Boolean(account.policyId) && isPolicyQueryPending;
+
+ if (submittedReason !== null) {
+ return <>{children(submittedReason)}</>;
+ }
+
+ const isReasonRequired = Boolean(
+ policy?.isActive && policy.rules?.[PamAccountPolicyRuleType.RequireReason]
+ );
+
+ const trimmed = draft.trim();
+ const canContinue = !isReasonRequired || trimmed.length > 0;
+ const showError = touched && isReasonRequired && trimmed.length === 0;
+
+ const handleSubmit = () => {
+ if (!canContinue) {
+ setTouched(true);
+ return;
+ }
+ setSubmittedReason(trimmed);
+ };
+
+ return (
+ <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">
+ {isPolicyLoading ? (
+ <p className="text-xs text-mineshaft-400">Loading account policy...</p>
+ ) : (
+ <>
+ {isReasonRequired ? <AlertTriangleIcon className="size-8 text-mineshaft-400" /> : null}
+ <h2 className="text-sm font-medium text-mineshaft-100">
+ {isReasonRequired ? "Reason Required" : "Before You Continue"}
+ </h2>
+ <p className="max-w-sm text-center text-xs text-mineshaft-400">
+ {isReasonRequired
+ ? "This account's policy requires a reason for access. The reason will be stored with the session for audit purposes."
+ : "Optionally provide a reason for this session. The reason will be stored with the session for audit purposes."}
+ </p>
+ <div className="flex w-full max-w-sm flex-col gap-2">
+ <textarea
+ className="w-full rounded border border-mineshaft-600 bg-bunker-700 px-3 py-2 text-xs text-mineshaft-200 placeholder:text-mineshaft-500 focus:border-mineshaft-400 focus:outline-none"
+ placeholder={
+ isReasonRequired
+ ? "e.g. Investigating incident INC-1234"
+ : "Optional — e.g. Running migration for release 2.4"
+ }
+ rows={3}
+ maxLength={1000}
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
+ handleSubmit();
+ }
+ }}
+ />
+ {showError && <p className="text-xs text-red-400">A reason is required to continue.</p>}
+ <div className="flex justify-center gap-2">
+ <Button
+ variant="outline"
+ size="xs"
+ isDisabled={isReasonRequired && trimmed.length === 0}
+ onClick={handleSubmit}
+ >
+ {!isReasonRequired && trimmed.length === 0 ? "Skip & Continue" : "Continue"}
+ </Button>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts b/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts
index 1116c96f61..eb5679adfa 100644
--- a/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts
+++ b/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts
@@ -18,6 +18,7 @@ type UseWebAccessSessionOptions = {
resourceName: string;
accountName: string;
resourceType: string;
+ reason?: string;
onSessionEnd?: () => void;
};
@@ -28,6 +29,7 @@ export const useWebAccessSession = ({
resourceName,
accountName,
resourceType,
+ reason,
onSessionEnd
}: UseWebAccessSessionOptions) => {
const [containerEl, setContainerEl] = useState<HTMLDivElement | null>(null);
@@ -237,7 +239,7 @@ export const useWebAccessSession = ({
try {
const { data } = await apiRequest.post<{ ticket: string }>(
`/api/v1/pam/accounts/${accountId}/web-access-ticket`,
- { projectId }
+ { projectId, reason }
);
if (containerEl) {
containerEl.style.width = "";
@@ -329,7 +331,7 @@ export const useWebAccessSession = ({
terminal.reset();
const { data: retryData } = await apiRequest.post<{ ticket: string }>(
`/api/v1/pam/accounts/${accountId}/web-access-ticket`,
- { projectId, mfaSessionId }
+ { projectId, mfaSessionId, reason }
);
openWebSocket(terminal, retryData.ticket);
} catch {
@@ -400,7 +402,7 @@ export const useWebAccessSession = ({
terminal.write("\r\nFailed to connect. Please close and try again.\r\n");
}
- }, [accountId, projectId, orgId, resourceName, accountName, containerEl, openWebSocket]);
+ }, [accountId, projectId, orgId, resourceName, accountName, reason, containerEl, openWebSocket]);
const disconnect = useCallback(() => {
const ws = wsRef.current;
diff --git a/frontend/src/pages/pam/PamAccountPoliciesPage/components/PolicySheet.tsx b/frontend/src/pages/pam/PamAccountPoliciesPage/components/PolicySheet.tsx
index 95d2c5a6e0..2f9cc1c941 100644
--- a/frontend/src/pages/pam/PamAccountPoliciesPage/components/PolicySheet.tsx
+++ b/frontend/src/pages/pam/PamAccountPoliciesPage/components/PolicySheet.tsx
@@ -44,6 +44,7 @@ import {
import { PAM_RESOURCE_TYPE_MAP } from "@app/hooks/api/pam/maps";
import {
+ PAM_ACCOUNT_POLICY_RULE_IS_PATTERNLESS,
PAM_ACCOUNT_POLICY_RULE_METADATA,
PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES
} from "./constants";
@@ -66,13 +67,21 @@ const RulePatternSchema = z.object({
.refine(isValidRegex, { message: "Invalid regular expression" })
});
-const RuleSchema = z.object({
- ruleType: z.nativeEnum(PamAccountPolicyRuleType),
- patterns: z
- .array(RulePatternSchema)
- .min(1, "At least one pattern is required")
- .max(20, "A rule can have at most 20 patterns")
-});
+const RuleSchema = z
+ .object({
+ ruleType: z.nativeEnum(PamAccountPolicyRuleType),
+ patterns: z.array(RulePatternSchema).max(20, "A rule can have at most 20 patterns").optional()
+ })
+ .superRefine((rule, ctx) => {
+ if (PAM_ACCOUNT_POLICY_RULE_IS_PATTERNLESS[rule.ruleType]) return;
+ if (!rule.patterns || rule.patterns.length < 1) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["patterns"],
+ message: "At least one pattern is required"
+ });
+ }
+ });
const FormSchema = z.object({
name: z.string().trim().min(1, "Name is required").max(255),
@@ -90,19 +99,33 @@ type Props = {
};
const rulesToFormData = (rules: TPamAccountPolicyRules): TFormData["rules"] => {
- return (Object.entries(rules) as [PamAccountPolicyRuleType, { patterns: string[] }][])
- .filter(([, config]) => config?.patterns)
- .map(([ruleType, config]) => ({
- ruleType,
- patterns: config.patterns.map((p) => ({ value: p }))
- }));
+ return (
+ Object.entries(rules) as [PamAccountPolicyRuleType, { patterns?: string[] } | undefined][]
+ )
+ .filter(([ruleType, config]) => {
+ if (PAM_ACCOUNT_POLICY_RULE_IS_PATTERNLESS[ruleType]) return Boolean(config);
+ return Boolean(config?.patterns);
+ })
+ .map(([ruleType, config]) => {
+ if (PAM_ACCOUNT_POLICY_RULE_IS_PATTERNLESS[ruleType]) {
+ return { ruleType };
+ }
+ return {
+ ruleType,
+ patterns: (config?.patterns ?? []).map((p) => ({ value: p }))
+ };
+ });
};
const formDataToRules = (rules: TFormData["rules"]): TPamAccountPolicyRules => {
return rules.reduce<TPamAccountPolicyRules>((acc, rule) => {
- acc[rule.ruleType] = {
- patterns: rule.patterns.map((p) => p.value)
- };
+ if (PAM_ACCOUNT_POLICY_RULE_IS_PATTERNLESS[rule.ruleType]) {
+ acc[rule.ruleType] = {};
+ } else {
+ acc[rule.ruleType] = {
+ patterns: (rule.patterns ?? []).map((p) => p.value)
+ };
+ }
return acc;
}, {});
};
@@ -376,7 +399,13 @@ export const PolicySheet = ({ isOpen, onOpenChange, projectId, policy }: Props)
disabled={isAdded}
onSelect={() => {
if (!isAdded) {
- appendRule({ ruleType, patterns: [{ value: "" }] });
+ const isPatternless =
+ PAM_ACCOUNT_POLICY_RULE_IS_PATTERNLESS[ruleType];
+ appendRule(
+ isPatternless
+ ? { ruleType }
+ : { ruleType, patterns: [{ value: "" }] }
+ );
setAddRuleOpen(false);
}
}}
@@ -403,6 +432,7 @@ export const PolicySheet = ({ isOpen, onOpenChange, projectId, policy }: Props)
const ruleType = currentRules[ruleIndex]?.ruleType;
if (!ruleType) return null;
const meta = PAM_ACCOUNT_POLICY_RULE_METADATA[ruleType];
+ const isPatternless = PAM_ACCOUNT_POLICY_RULE_IS_PATTERNLESS[ruleType];
return (
<div key={ruleField.id} className="rounded-md border border-border bg-card p-4">
@@ -424,9 +454,11 @@ export const PolicySheet = ({ isOpen, onOpenChange, projectId, policy }: Props)
<p className="mt-2 text-xs text-muted">{meta.description}</p>
)}
- <div className="mt-3">
- <RulePatterns control={control} ruleIndex={ruleIndex} errors={errors} />
- </div>
+ {!isPatternless && (
+ <div className="mt-3">
+ <RulePatterns control={control} ruleIndex={ruleIndex} errors={errors} />
+ </div>
+ )}
</div>
);
})}
diff --git a/frontend/src/pages/pam/PamAccountPoliciesPage/components/constants.ts b/frontend/src/pages/pam/PamAccountPoliciesPage/components/constants.ts
index a2aec6560d..b15cb9e715 100644
--- a/frontend/src/pages/pam/PamAccountPoliciesPage/components/constants.ts
+++ b/frontend/src/pages/pam/PamAccountPoliciesPage/components/constants.ts
@@ -6,7 +6,8 @@ export const PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES: Record<
PamResourceType[] | "all"
> = {
[PamAccountPolicyRuleType.CommandBlocking]: [PamResourceType.SSH],
- [PamAccountPolicyRuleType.SessionLogMasking]: "all"
+ [PamAccountPolicyRuleType.SessionLogMasking]: "all",
+ [PamAccountPolicyRuleType.RequireReason]: "all"
};
export const PAM_ACCOUNT_POLICY_RULE_METADATA: Record<
@@ -20,5 +21,15 @@ export const PAM_ACCOUNT_POLICY_RULE_METADATA: Record<
[PamAccountPolicyRuleType.SessionLogMasking]: {
name: "Session Log Masking",
description: "Mask sensitive data in session logs matching specified patterns"
+ },
+ [PamAccountPolicyRuleType.RequireReason]: {
+ name: "Require Access Reason",
+ description: "Require users to provide a reason before they can start a session"
}
};
+
+export const PAM_ACCOUNT_POLICY_RULE_IS_PATTERNLESS: Record<PamAccountPolicyRuleType, boolean> = {
+ [PamAccountPolicyRuleType.CommandBlocking]: false,
+ [PamAccountPolicyRuleType.SessionLogMasking]: false,
+ [PamAccountPolicyRuleType.RequireReason]: true
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx
index e0822d8c7a..436c3d42b2 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx
@@ -70,18 +70,21 @@ export const PamAccessAccountModal = ({ isOpen, onOpenChange, account, projectId
const command = useMemo(() => {
if (!account) return "";
+ const base = (verb: string) =>
+ `infisical pam ${verb} access --resource ${account.resource.name} --account ${account.name} --project-id ${projectId} --duration ${cliDuration} --domain ${siteURL}`;
+
switch (account.resource.resourceType) {
case PamResourceType.Postgres:
case PamResourceType.MySQL:
case PamResourceType.MsSQL:
case PamResourceType.MongoDB:
- return `infisical pam db access --resource ${account.resource.name} --account ${account.name} --project-id ${projectId} --duration ${cliDuration} --domain ${siteURL}`;
+ return base("db");
case PamResourceType.Redis:
- return `infisical pam redis access --resource ${account.resource.name} --account ${account.name} --project-id ${projectId} --duration ${cliDuration} --domain ${siteURL}`;
+ return base("redis");
case PamResourceType.SSH:
- return `infisical pam ssh access --resource ${account.resource.name} --account ${account.name} --project-id ${projectId} --duration ${cliDuration} --domain ${siteURL}`;
+ return base("ssh");
case PamResourceType.Kubernetes:
- return `infisical pam kubernetes access --resource ${account.resource.name} --account ${account.name} --project-id ${projectId} --duration ${cliDuration} --domain ${siteURL}`;
+ return base("kubernetes");
default:
return "";
}
@@ -121,6 +124,7 @@ export const PamAccessAccountModal = ({ isOpen, onOpenChange, account, projectId
ariaLabel="copy"
variant="outline_bg"
colorSchema="secondary"
+ isDisabled={!isDurationValid}
onClick={() => {
navigator.clipboard.writeText(command);
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx
index 789ef9cb00..20fcc43785 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx
+++ b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx
@@ -33,7 +33,11 @@ import type { SchemaInfo, TableDetail, TableInfo } from "./data-explorer-types";
import { useDataExplorerSession } from "./use-data-explorer-session";
import { BROWSE_TAB_ID, useQueryTabs } from "./use-query-tabs";
-export const PamDataExplorerPage = () => {
+type Props = {
+ reason?: string;
+};
+
+export const PamDataExplorerPage = ({ reason }: Props = {}) => {
const { accountId, projectId, orgId } = useParams({
strict: false
}) as {
@@ -88,10 +92,11 @@ export const PamDataExplorerPage = () => {
orgId,
resourceName: account?.resource?.name ?? "",
accountName: account?.name ?? "",
- onSessionEnd: (reason?: string) => {
+ reason,
+ onSessionEnd: (endReason?: string) => {
unsavedChangeCountRef.current = 0;
setHasDisconnected(true);
- setDisconnectReason(reason ?? null);
+ setDisconnectReason(endReason ?? null);
}
});
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts
index 3c1894b3a4..d90b13bef4 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts
+++ b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts
@@ -41,6 +41,7 @@ type UseDataExplorerSessionOptions = {
orgId: string;
resourceName: string;
accountName: string;
+ reason?: string;
onSessionEnd?: (reason?: string) => void;
};
@@ -52,6 +53,7 @@ export const useDataExplorerSession = ({
orgId,
resourceName,
accountName,
+ reason: accessReason,
onSessionEnd
}: UseDataExplorerSessionOptions) => {
const [isConnected, setIsConnected] = useState(false);
@@ -171,7 +173,7 @@ export const useDataExplorerSession = ({
try {
const { data } = await apiRequest.post<{ ticket: string }>(
`/api/v1/pam/accounts/${accountId}/web-access-ticket`,
- { projectId, mfaSessionId }
+ { projectId, mfaSessionId, reason: accessReason }
);
openWebSocket(data.ticket);
} catch (err: unknown) {
@@ -220,7 +222,7 @@ export const useDataExplorerSession = ({
readyRejectRef.current?.(new Error("Failed to connect"));
}
},
- [accountId, projectId, openWebSocket]
+ [accountId, projectId, accessReason, openWebSocket]
);
const disconnect = useCallback(() => {
diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionDetailsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionDetailsSection.tsx
index f53803ce86..24074046ef 100644
--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionDetailsSection.tsx
+++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionDetailsSection.tsx
@@ -34,7 +34,8 @@ export const PamSessionDetailsSection = ({
actorIp,
actorUserAgent,
startedAt,
- expiresAt
+ expiresAt,
+ reason
}
}: Props) => {
const [copyTextId, isCopyingId, setCopyTextId] = useTimedReset<string>({
@@ -106,6 +107,10 @@ export const PamSessionDetailsSection = ({
<p className="truncate">{actorUserAgent}</p>
</DetailItem>
+ <DetailItem label="Reason">
+ <p className="break-words whitespace-pre-wrap">{reason || "—"}</p>
+ </DetailItem>
+
<DetailItem label="Created At">
<p>{new Date(createdAt).toLocaleString()}</p>
</DetailItem>