Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(pam): cap session duration to grant remaining lifetime
bernie-gcfe5fdcb9997
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.tsindex 75ba3548ee..581f3e1e8f 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@@ -824,6 +824,7 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {actorEmail: z.string(),actorName: z.string(),reason: z.string().nullable().optional(),+ grantExpiresAt: z.string().nullable().optional(),auditLogInfo: z.object({ipAddress: z.string().optional(),userAgent: z.string().optional(),@@ -857,6 +858,7 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {actorIp: req.realIp ?? "",actorUserAgent: req.headers["user-agent"] ?? "",reason: payload.reason,+ grantExpiresAt: payload.grantExpiresAt ?? null,preAuthMessages,preAuthHandler});diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex a231bcd32b..f38fe98356 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -4,6 +4,7 @@ import picomatch from "picomatch";import { ActionProjectType, OrganizationActionScope, TableName, TPamAccounts, TPamResources } from "@app/db/schemas";import { decryptDomainConnectionDetails } from "@app/ee/services/pam-domain/pam-domain-fns";import {+ AWS_STS_MIN_DURATION_SECONDS,exchangeCredentialsForConsoleUrl,extractAwsAccountIdFromArn,generateAwsIamSessionCredentials,@@ -822,10 +823,10 @@ export const pamAccountServiceFactory = ({accountName: accountIdentity};- const canAccess = await fac.canAccess(approvalRequestGrantsDAL, resource.projectId, actor.id, inputs);+ const activeGrant = await fac.canAccess(approvalRequestGrantsDAL, resource.projectId, actor.id, inputs);// Grant does not exist, check policy and fallback to permission check- if (!canAccess) {+ if (!activeGrant) {const policy = await fac.matchPolicy(approvalPolicyDAL, resource.projectId, inputs);if (policy) {@@ -875,6 +876,16 @@ export const pamAccountServiceFactory = ({);}+ // Cap the requested duration to the grant's remaining lifetime+ let effectiveDuration = duration;+ if (activeGrant?.expiresAt) {+ const grantRemainingMs = activeGrant.expiresAt.getTime() - Date.now();+ if (grantRemainingMs <= 0) {+ throw new ForbiddenRequestError({ message: "Approval grant has expired" });+ }+ effectiveDuration = Math.min(duration, grantRemainingMs);+ }+// Reason check is intentionally placed after the approval/permission gates so// its distinct error code does not leak policy configuration to unauthorized actors.if (account.policyId) {@@ -987,12 +998,24 @@ export const pamAccountServiceFactory = ({projectId: account.projectId})) as TAwsIamAccountCredentials;+ let sessionDuration = awsCredentials.defaultSessionDuration;+ if (activeGrant?.expiresAt) {+ const grantRemainingSeconds = Math.floor((activeGrant.expiresAt.getTime() - Date.now()) / 1000);+ // STS rejects DurationSeconds below the floor, so a grant shorter than that can't be honored+ if (grantRemainingSeconds < AWS_STS_MIN_DURATION_SECONDS) {+ throw new ForbiddenRequestError({+ message: "Approval grant has insufficient remaining time for an AWS IAM session"+ });+ }+ sessionDuration = Math.min(sessionDuration, grantRemainingSeconds);+ }+const credentials = await generateAwsIamSessionCredentials({connectionDetails,targetRoleArn: awsCredentials.targetRoleArn,roleSessionName: actorEmail,projectId: account.projectId, // Use project ID as External ID for security- sessionDuration: awsCredentials.defaultSessionDuration+ sessionDuration});const session = await pamSessionDAL.create({@@ -1060,7 +1083,7 @@ export const pamAccountServiceFactory = ({selectedResourceId: isDomainAccount ? resource.id : null,userId: actor.id,gatewayId,- expiresAt: new Date(Date.now() + duration),+ expiresAt: new Date(Date.now() + effectiveDuration),reason: trimmedReason});@@ -1086,7 +1109,7 @@ export const pamAccountServiceFactory = ({const gatewayConnectionDetails = await gatewayV2Service.getPAMConnectionDetails({gatewayId,- duration,+ duration: effectiveDuration,sessionId: session.id,resourceType: resource.resourceType as PamResource,host,diff --git a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-federation.ts b/backend/src/ee/services/pam-resource/aws-iam/aws-iam-federation.tsindex 20b7e52fe4..af78a8f753 100644--- a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-federation.ts+++ b/backend/src/ee/services/pam-resource/aws-iam/aws-iam-federation.ts@@ -8,7 +8,7 @@ import { BadRequestError, InternalServerError } from "@app/lib/errors";import { TAwsIamResourceConnectionDetails } from "./aws-iam-resource-types";-const AWS_STS_MIN_DURATION_SECONDS = 900;+export const AWS_STS_MIN_DURATION_SECONDS = 900;// We hardcode us-east-1 because:// 1. IAM is global - roles can be assumed from any STS regional endpointdiff --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.tsindex 3e4fe6dcd0..ec5c95c00e 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@@ -120,6 +120,7 @@ type THandleWebSocketConnectionDTO = {actorIp: string;actorUserAgent: string;reason?: string | null;+ grantExpiresAt?: string | null;preAuthMessages: TEarlyBufferedMsg[];preAuthHandler: (raw: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => void;};@@ -262,14 +263,14 @@ export const pamWebAccessServiceFactory = ({accountName: accountIdentity};- const hasApprovalGrant = await approvalPolicy.canAccess(+ const approvalGrant = await approvalPolicy.canAccess(approvalRequestGrantsDAL,resource.projectId,actor.id,policyInputs);- if (!hasApprovalGrant) {+ if (!approvalGrant) {const matchedPolicy = await approvalPolicy.matchPolicy(approvalPolicyDAL, resource.projectId, policyInputs);if (matchedPolicy) {@@ -396,7 +397,8 @@ export const pamWebAccessServiceFactory = ({actorEmail,actorName,auditLogInfo,- reason: trimmedReason+ reason: trimmedReason,+ grantExpiresAt: approvalGrant?.expiresAt?.toISOString() ?? null})});@@ -432,6 +434,7 @@ export const pamWebAccessServiceFactory = ({actorIp,actorUserAgent,reason: accessReason,+ grantExpiresAt: grantExpiresAtIso,preAuthMessages,preAuthHandler}: THandleWebSocketConnectionDTO): Promise<void> => {@@ -594,7 +597,16 @@ export const pamWebAccessServiceFactory = ({// 3. CREATE SESSIONconst user = await requestMemoize(requestMemoKeys.userFindById(userId), () => userDAL.findById(userId));- const expiresAt = new Date(Date.now() + DEFAULT_WEB_SESSION_DURATION_MS);+ let sessionDurationMs = DEFAULT_WEB_SESSION_DURATION_MS;+ if (grantExpiresAtIso) {+ const grantRemainingMs = new Date(grantExpiresAtIso).getTime() - Date.now();+ if (grantRemainingMs <= 0) {+ sendSessionEndAndClose(socket, SessionEndReason.SessionGrantExpired);+ return;+ }+ sessionDurationMs = Math.min(sessionDurationMs, grantRemainingMs);+ }+ const expiresAt = new Date(Date.now() + sessionDurationMs);const isDomainAccount = !account.resourceId;@@ -627,7 +639,7 @@ export const pamWebAccessServiceFactory = ({resourceType: resource.resourceType as PamResource,host,port,- duration: DEFAULT_WEB_SESSION_DURATION_MS,+ duration: sessionDurationMs,actorMetadata: {id: userId,type: ActorType.USER,@@ -775,7 +787,7 @@ export const pamWebAccessServiceFactory = ({void cleanup();sendSessionEndAndClose(socket, SessionEndReason.SessionCompleted);}- }, DEFAULT_WEB_SESSION_DURATION_MS);+ }, sessionDurationMs);// WebSocket close/errorsocket.on("close", () => {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.tsindex b92b1332cd..aab3c97876 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@@ -10,7 +10,8 @@ export enum SessionEndReason {ConnectionLost = "Connection lost",SetupFailed = "Failed to establish connection",IdleTimeout = "Session closed due to inactivity",- SessionLimitReached = "Maximum concurrent sessions reached"+ SessionLimitReached = "Maximum concurrent sessions reached",+ SessionGrantExpired = "Approval grant has expired"}export enum TerminalServerMessageType {diff --git a/backend/src/services/approval-policy/approval-policy-service.ts b/backend/src/services/approval-policy/approval-policy-service.tsindex 70f1bab872..7275ffbbae 100644--- a/backend/src/services/approval-policy/approval-policy-service.ts+++ b/backend/src/services/approval-policy/approval-policy-service.ts@@ -1642,7 +1642,7 @@ export const approvalPolicyServiceFactory = ({return { requiresApproval: false, hasActiveGrant: false };}- const hasActiveGrant = await fac.canAccess(approvalRequestGrantsDAL, projectId, actor.id, inputs);+ const activeGrant = await fac.canAccess(approvalRequestGrantsDAL, projectId, actor.id, inputs);const innerConstraints = policy.constraints?.constraints;const constraints =@@ -1651,8 +1651,8 @@ export const approvalPolicyServiceFactory = ({: undefined;return {- requiresApproval: !hasActiveGrant,- hasActiveGrant,+ requiresApproval: !activeGrant,+ hasActiveGrant: !!activeGrant,constraints};};diff --git a/backend/src/services/approval-policy/approval-policy-types.ts b/backend/src/services/approval-policy/approval-policy-types.tsindex 130c28aaa8..733d211dc5 100644--- a/backend/src/services/approval-policy/approval-policy-types.ts+++ b/backend/src/services/approval-policy/approval-policy-types.ts@@ -1,6 +1,6 @@import { Knex } from "knex";-import { TApprovalPolicies } from "@app/db/schemas";+import { TApprovalPolicies, TApprovalRequestGrants } from "@app/db/schemas";import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";import { TApprovalRequestGrantsDALFactory } from "@app/services/approval-policy/approval-request-dal";import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";@@ -144,7 +144,7 @@ export type TApprovalRequestFactoryCanAccess<I extends TApprovalPolicyInputs> =projectId: string,userId: string,inputs: I-) => Promise<boolean>;+) => Promise<TApprovalRequestGrants | null>;export type TApprovalRequestFactoryValidateConstraints<P extends TApprovalPolicy, R extends TApprovalRequestData> = (policy: P,inputs: Rdiff --git a/backend/src/services/approval-policy/cert-request/cert-request-policy-factory.ts b/backend/src/services/approval-policy/cert-request/cert-request-policy-factory.tsindex 752e4ac3b1..fbfc0676ab 100644--- a/backend/src/services/approval-policy/cert-request/cert-request-policy-factory.ts+++ b/backend/src/services/approval-policy/cert-request/cert-request-policy-factory.ts@@ -45,7 +45,7 @@ export const certRequestPolicyFactory: TApprovalResourceFactory<};const canAccess: TApprovalRequestFactoryCanAccess<TCertRequestPolicyInputs> = async () => {- return false;+ return null;};const validateConstraints: TApprovalRequestFactoryValidateConstraints<diff --git a/backend/src/services/approval-policy/code-signing/code-signing-policy-factory.ts b/backend/src/services/approval-policy/code-signing/code-signing-policy-factory.tsindex c1cf19c2ba..1b530e8d05 100644--- a/backend/src/services/approval-policy/code-signing/code-signing-policy-factory.ts+++ b/backend/src/services/approval-policy/code-signing/code-signing-policy-factory.ts@@ -64,15 +64,15 @@ export const codeSigningPolicyFactory: TApprovalResourceFactory<const now = new Date();- const hasMatchingGrant = grants.some((grant) => {- const attributes = grant.attributes as TCodeSigningGrantAttributes | null;- if (!attributes || attributes.signerId !== inputs.signerId) return false;- if (attributes.windowStart && new Date(attributes.windowStart) > now) return false;- if (grant.expiresAt && new Date(grant.expiresAt) < now) return false;- return true;- });-- return hasMatchingGrant;+ return (+ grants.find((grant) => {+ const attributes = grant.attributes as TCodeSigningGrantAttributes | null;+ if (!attributes || attributes.signerId !== inputs.signerId) return false;+ if (attributes.windowStart && new Date(attributes.windowStart) > now) return false;+ if (grant.expiresAt && new Date(grant.expiresAt) < now) return false;+ return true;+ }) ?? null+ );};const validateConstraints: TApprovalRequestFactoryValidateConstraints<TCodeSigningPolicy, TCodeSigningRequestData> = (diff --git a/backend/src/services/approval-policy/pam-access/pam-access-policy-factory.ts b/backend/src/services/approval-policy/pam-access/pam-access-policy-factory.tsindex 4016c38f26..528e2c1753 100644--- a/backend/src/services/approval-policy/pam-access/pam-access-policy-factory.ts+++ b/backend/src/services/approval-policy/pam-access/pam-access-policy-factory.ts@@ -117,32 +117,34 @@ export const pamAccessPolicyFactory: TApprovalResourceFactory<});// TODO(andrey): Move some of this check to be part of SQL query- return grants.some((grant) => {- const grantAttributes = grant.attributes as TPamAccessPolicyInputs;+ return (+ grants.find((grant) => {+ const grantAttributes = grant.attributes as TPamAccessPolicyInputs;- if (inputs.resourceName || inputs.accountName) {- let resourceMatches = true;- let accountMatches = true;+ if (inputs.resourceName || inputs.accountName) {+ let resourceMatches = true;+ let accountMatches = true;- if (inputs.resourceName && grantAttributes.resourceName) {- resourceMatches = picomatch(grantAttributes.resourceName)(inputs.resourceName);- } else if (inputs.resourceName && !grantAttributes.resourceName) {- resourceMatches = false;- }+ if (inputs.resourceName && grantAttributes.resourceName) {+ resourceMatches = picomatch(grantAttributes.resourceName)(inputs.resourceName);+ } else if (inputs.resourceName && !grantAttributes.resourceName) {+ resourceMatches = false;+ }- if (inputs.accountName && grantAttributes.accountName) {- accountMatches = picomatch(grantAttributes.accountName)(inputs.accountName);- } else if (inputs.accountName && !grantAttributes.accountName) {- accountMatches = false;- }+ if (inputs.accountName && grantAttributes.accountName) {+ accountMatches = picomatch(grantAttributes.accountName)(inputs.accountName);+ } else if (inputs.accountName && !grantAttributes.accountName) {+ accountMatches = false;+ }- if (resourceMatches && accountMatches && (!grant.expiresAt || grant.expiresAt > new Date())) {- return true;+ if (resourceMatches && accountMatches && (!grant.expiresAt || grant.expiresAt > new Date())) {+ return true;+ }}- }- return false;- });+ return false;+ }) ?? null+ );};const validateConstraints: TApprovalRequestFactoryValidateConstraints<TPamAccessPolicy, TPamAccessRequestData> = (