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
feat(pam): auto approvals
Andrey52ef064c277e
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 75742a3e81..8ccc1350d6 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -77,6 +77,15 @@ import {TApprovalPolicies,TApprovalPoliciesInsert,TApprovalPoliciesUpdate,+ TApprovalPolicyAutoApprovalConditions,+ TApprovalPolicyAutoApprovalConditionsInsert,+ TApprovalPolicyAutoApprovalConditionsUpdate,+ TApprovalPolicyAutoApprovalInputs,+ TApprovalPolicyAutoApprovalInputsInsert,+ TApprovalPolicyAutoApprovalInputsUpdate,+ TApprovalPolicyAutoApprovalRules,+ TApprovalPolicyAutoApprovalRulesInsert,+ TApprovalPolicyAutoApprovalRulesUpdate,TApprovalPolicyBypassers,TApprovalPolicyBypassersInsert,TApprovalPolicyBypassersUpdate,@@ -1939,6 +1948,21 @@ declare module "knex/types/tables" {TApprovalPolicyBypassersInsert,TApprovalPolicyBypassersUpdate>;+ [TableName.ApprovalPolicyAutoApprovalInputs]: KnexOriginal.CompositeTableType<+ TApprovalPolicyAutoApprovalInputs,+ TApprovalPolicyAutoApprovalInputsInsert,+ TApprovalPolicyAutoApprovalInputsUpdate+ >;+ [TableName.ApprovalPolicyAutoApprovalRules]: KnexOriginal.CompositeTableType<+ TApprovalPolicyAutoApprovalRules,+ TApprovalPolicyAutoApprovalRulesInsert,+ TApprovalPolicyAutoApprovalRulesUpdate+ >;+ [TableName.ApprovalPolicyAutoApprovalConditions]: KnexOriginal.CompositeTableType<+ TApprovalPolicyAutoApprovalConditions,+ TApprovalPolicyAutoApprovalConditionsInsert,+ TApprovalPolicyAutoApprovalConditionsUpdate+ >;[TableName.ApprovalPolicySecretEnvironment]: KnexOriginal.CompositeTableType<TApprovalPolicySecretEnvironments,TApprovalPolicySecretEnvironmentsInsert,diff --git a/backend/src/db/migrations/20261013120000_approval-policy-auto-approval.ts b/backend/src/db/migrations/20261013120000_approval-policy-auto-approval.tsnew file mode 100644index 0000000000..2f9403aefc--- /dev/null+++ b/backend/src/db/migrations/20261013120000_approval-policy-auto-approval.ts@@ -0,0 +1,102 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.ApprovalPolicyAutoApprovalInputs))) {+ await knex.schema.createTable(TableName.ApprovalPolicyAutoApprovalInputs, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("policyId").notNullable();+ t.foreign("policyId").references("id").inTable(TableName.ApprovalPolicies).onDelete("CASCADE");++ t.integer("position").notNullable();++ t.uuid("connectionId").notNullable().index();+ t.foreign("connectionId").references("id").inTable(TableName.AppConnection).deferrable("deferred");++ t.string("subject", 64).notNullable();++ t.unique(["policyId", "connectionId", "subject"]);++ t.timestamps(true, true, true);+ });+ await createOnUpdateTrigger(knex, TableName.ApprovalPolicyAutoApprovalInputs);+ }++ if (!(await knex.schema.hasTable(TableName.ApprovalPolicyAutoApprovalRules))) {+ await knex.schema.createTable(TableName.ApprovalPolicyAutoApprovalRules, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("policyId").notNullable().index();+ t.foreign("policyId").references("id").inTable(TableName.ApprovalPolicies).onDelete("CASCADE");++ t.integer("position").notNullable();+ t.string("name", 128).notNullable();++ t.timestamps(true, true, true);+ });+ await createOnUpdateTrigger(knex, TableName.ApprovalPolicyAutoApprovalRules);+ }++ if (!(await knex.schema.hasTable(TableName.ApprovalPolicyAutoApprovalConditions))) {+ await knex.schema.createTable(TableName.ApprovalPolicyAutoApprovalConditions, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("ruleId").notNullable().index();+ t.foreign("ruleId").references("id").inTable(TableName.ApprovalPolicyAutoApprovalRules).onDelete("CASCADE");++ t.integer("position").notNullable();++ t.uuid("inputId").nullable().index();+ t.foreign("inputId").references("id").inTable(TableName.ApprovalPolicyAutoApprovalInputs).deferrable("deferred");++ t.uuid("connectionId").nullable().index();+ t.foreign("connectionId").references("id").inTable(TableName.AppConnection).deferrable("deferred");++ t.string("constraint", 64).notNullable();+ t.jsonb("values").notNullable();++ t.check(+ '("inputId" IS NOT NULL AND "connectionId" IS NULL) OR ("inputId" IS NULL AND "connectionId" IS NOT NULL)'+ );++ t.timestamps(true, true, true);+ });+ await createOnUpdateTrigger(knex, TableName.ApprovalPolicyAutoApprovalConditions);+ }++ if (await knex.schema.hasTable(TableName.ApprovalRequests)) {+ const hasAutoApprovedAt = await knex.schema.hasColumn(TableName.ApprovalRequests, "autoApprovedAt");+ const hasEvidence = await knex.schema.hasColumn(TableName.ApprovalRequests, "autoApprovalEvidence");+ if (!hasAutoApprovedAt || !hasEvidence) {+ await knex.schema.alterTable(TableName.ApprovalRequests, (t) => {+ if (!hasAutoApprovedAt) t.datetime("autoApprovedAt").nullable();+ if (!hasEvidence) t.jsonb("autoApprovalEvidence").nullable();+ });+ }+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasTable(TableName.ApprovalRequests)) {+ const hasAutoApprovedAt = await knex.schema.hasColumn(TableName.ApprovalRequests, "autoApprovedAt");+ const hasEvidence = await knex.schema.hasColumn(TableName.ApprovalRequests, "autoApprovalEvidence");+ if (hasAutoApprovedAt || hasEvidence) {+ await knex.schema.alterTable(TableName.ApprovalRequests, (t) => {+ if (hasAutoApprovedAt) t.dropColumn("autoApprovedAt");+ if (hasEvidence) t.dropColumn("autoApprovalEvidence");+ });+ }+ }++ await dropOnUpdateTrigger(knex, TableName.ApprovalPolicyAutoApprovalConditions);+ await knex.schema.dropTableIfExists(TableName.ApprovalPolicyAutoApprovalConditions);++ await dropOnUpdateTrigger(knex, TableName.ApprovalPolicyAutoApprovalRules);+ await knex.schema.dropTableIfExists(TableName.ApprovalPolicyAutoApprovalRules);++ await dropOnUpdateTrigger(knex, TableName.ApprovalPolicyAutoApprovalInputs);+ await knex.schema.dropTableIfExists(TableName.ApprovalPolicyAutoApprovalInputs);+}diff --git a/backend/src/db/schemas/approval-policy-auto-approval-conditions.ts b/backend/src/db/schemas/approval-policy-auto-approval-conditions.tsnew file mode 100644index 0000000000..1e1f2f670d--- /dev/null+++ b/backend/src/db/schemas/approval-policy-auto-approval-conditions.ts@@ -0,0 +1,29 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const ApprovalPolicyAutoApprovalConditionsSchema = z.object({+ id: z.string().uuid(),+ ruleId: z.string().uuid(),+ position: z.number(),+ inputId: z.string().uuid().nullable().optional(),+ connectionId: z.string().uuid().nullable().optional(),+ constraint: z.string(),+ values: z.unknown(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TApprovalPolicyAutoApprovalConditions = z.infer<typeof ApprovalPolicyAutoApprovalConditionsSchema>;+export type TApprovalPolicyAutoApprovalConditionsInsert = Omit<+ z.input<typeof ApprovalPolicyAutoApprovalConditionsSchema>,+ TImmutableDBKeys+>;+export type TApprovalPolicyAutoApprovalConditionsUpdate = Partial<+ Omit<z.input<typeof ApprovalPolicyAutoApprovalConditionsSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/approval-policy-auto-approval-inputs.ts b/backend/src/db/schemas/approval-policy-auto-approval-inputs.tsnew file mode 100644index 0000000000..f90bdfe5b8--- /dev/null+++ b/backend/src/db/schemas/approval-policy-auto-approval-inputs.ts@@ -0,0 +1,27 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const ApprovalPolicyAutoApprovalInputsSchema = z.object({+ id: z.string().uuid(),+ policyId: z.string().uuid(),+ position: z.number(),+ connectionId: z.string().uuid(),+ subject: z.string(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TApprovalPolicyAutoApprovalInputs = z.infer<typeof ApprovalPolicyAutoApprovalInputsSchema>;+export type TApprovalPolicyAutoApprovalInputsInsert = Omit<+ z.input<typeof ApprovalPolicyAutoApprovalInputsSchema>,+ TImmutableDBKeys+>;+export type TApprovalPolicyAutoApprovalInputsUpdate = Partial<+ Omit<z.input<typeof ApprovalPolicyAutoApprovalInputsSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/approval-policy-auto-approval-rules.ts b/backend/src/db/schemas/approval-policy-auto-approval-rules.tsnew file mode 100644index 0000000000..92e2408971--- /dev/null+++ b/backend/src/db/schemas/approval-policy-auto-approval-rules.ts@@ -0,0 +1,26 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const ApprovalPolicyAutoApprovalRulesSchema = z.object({+ id: z.string().uuid(),+ policyId: z.string().uuid(),+ position: z.number(),+ name: z.string(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TApprovalPolicyAutoApprovalRules = z.infer<typeof ApprovalPolicyAutoApprovalRulesSchema>;+export type TApprovalPolicyAutoApprovalRulesInsert = Omit<+ z.input<typeof ApprovalPolicyAutoApprovalRulesSchema>,+ TImmutableDBKeys+>;+export type TApprovalPolicyAutoApprovalRulesUpdate = Partial<+ Omit<z.input<typeof ApprovalPolicyAutoApprovalRulesSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/approval-requests.ts b/backend/src/db/schemas/approval-requests.tsindex 3dccd7687e..aac4ddfb06 100644--- a/backend/src/db/schemas/approval-requests.ts+++ b/backend/src/db/schemas/approval-requests.ts@@ -25,7 +25,9 @@ export const ApprovalRequestsSchema = z.object({updatedAt: z.date(),machineIdentityId: z.string().uuid().nullable().optional(),scopeType: z.string().nullable().optional(),- scopeId: z.string().uuid().nullable().optional()+ scopeId: z.string().uuid().nullable().optional(),+ autoApprovedAt: z.date().nullable().optional(),+ autoApprovalEvidence: z.unknown().nullable().optional()});export type TApprovalRequests = z.infer<typeof ApprovalRequestsSchema>;diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 6539387a61..5889de5e3c 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -23,6 +23,9 @@ export * from "./alerts";export * from "./app-connection-credential-rotations";export * from "./app-connections";export * from "./approval-policies";+export * from "./approval-policy-auto-approval-conditions";+export * from "./approval-policy-auto-approval-inputs";+export * from "./approval-policy-auto-approval-rules";export * from "./approval-policy-bypassers";export * from "./approval-policy-secret-environments";export * from "./approval-policy-step-approvers";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 2afbf3e508..54b9cfe39a 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -323,6 +323,9 @@ export enum TableName {ApprovalPolicySteps = "approval_policy_steps",ApprovalPolicyStepApprovers = "approval_policy_step_approvers",ApprovalPolicyBypassers = "approval_policy_bypassers",+ ApprovalPolicyAutoApprovalInputs = "approval_policy_auto_approval_inputs",+ ApprovalPolicyAutoApprovalRules = "approval_policy_auto_approval_rules",+ ApprovalPolicyAutoApprovalConditions = "approval_policy_auto_approval_conditions",ApprovalPolicySecretEnvironment = "approval_policy_secret_environments",ApprovalRequests = "approval_requests",ApprovalRequestSteps = "approval_request_steps",diff --git a/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.tsindex 0af07ff8ff..1a37352374 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts@@ -6,12 +6,26 @@ import { PamAccessType } from "@app/ee/services/pam/pam-enums";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";-import { ApprovalPolicyType, ApproverType } from "@app/services/approval-policy/approval-policy-enums";+import {+ ApprovalAuditAction,+ ApprovalPolicyType,+ ApproverType+} from "@app/services/approval-policy/approval-policy-enums";+import {+ AutoApprovalInputValuesSchema,+ AutoApprovalOutcomeSchema,+ AutoApprovalInputDetailsSchema+} from "@app/services/approval-policy/auto-approval/auto-approval-schemas";import { parsePamAccessDuration } from "@app/services/approval-policy/pam-access/pam-access-policy-fns";import { AuthMode } from "@app/services/auth/auth-type";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";-const EnrichedRequestSchema = ApprovalRequestsSchema.extend({+// The evidence holds data fetched from other services, so only its outcome is returned+const RequestSchema = ApprovalRequestsSchema.omit({ autoApprovalEvidence: true }).extend({+ autoApproval: AutoApprovalOutcomeSchema.optional()+});++const EnrichedRequestSchema = RequestSchema.extend({accountName: z.string().nullable(),accountType: z.string().nullable(),folderName: z.string().nullable(),@@ -51,14 +65,15 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider).optional().describe("Self-approve the request immediately instead of waiting for an approver. Requires break-glass eligibility and a reason of at least 10 characters, which is reused as the bypass reason."- )+ ),+ autoApprovalInputs: AutoApprovalInputValuesSchema.optional()}).refine((b) => Boolean(b.accountId) || Boolean(b.path), {message: "Either 'accountId' or 'path' is required"}),response: {200: z.object({- request: ApprovalRequestsSchema+ request: RequestSchema})}},@@ -72,6 +87,7 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider)duration: req.body.duration,accessType: req.body.accessType,breakGlass: req.body.breakGlass,+ autoApprovalInputs: req.body.autoApprovalInputs,actorId: req.permission.id,actor: req.permission.type,actorOrgId: req.permission.orgId,@@ -129,6 +145,22 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider)});}+ if (result.request.autoApprovedAt) {+ const autoApprovedEvent = await server.services.approvalPolicy.buildAuditEvent({+ action: ApprovalAuditAction.RequestAutoApproved,+ request: result.request,+ actorId: req.permission.id+ });+ if (autoApprovedEvent) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalPamProjectId,+ event: autoApprovedEvent+ });+ }+ }+void server.services.telemetry.sendPostHogEvents({event: PostHogEventTypes.PamAccessRequestCreated,@@ -246,6 +278,7 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider)}),response: {200: z.object({+ autoApprovalInputs: AutoApprovalInputDetailsSchema.array(),steps: z.array(z.object({requiredApprovals: z.number(),diff --git a/backend/src/ee/routes/v1/pam-routers/pam-approval-configuration-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-approval-configuration-router.tsindex 1f8ae3df9c..53675bdcc8 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-approval-configuration-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-approval-configuration-router.ts@@ -5,6 +5,10 @@ import { PamNotificationEvent } from "@app/ee/services/pam/pam-enums";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { ApproverType } from "@app/services/approval-policy/approval-policy-enums";+import {+ AutoApprovalConfigResponseSchema,+ AutoApprovalConfigSchema+} from "@app/services/approval-policy/auto-approval/auto-approval-schemas";import { AuthMode } from "@app/services/auth/auth-type";const ApproverSchema = z.object({@@ -55,7 +59,8 @@ export const registerPamApprovalConfigurationRouter = async (server: FastifyZodP})),notificationConfigs: z.array(NotificationConfigResponseSchema),- breakGlassUsers: z.array(ApproverSchema)+ breakGlassUsers: z.array(ApproverSchema),+ autoApproval: AutoApprovalConfigResponseSchema})}},@@ -90,7 +95,8 @@ export const registerPamApprovalConfigurationRouter = async (server: FastifyZodP.optional().describe("Users and groups allowed to grant themselves access without an approver. Omitted leaves the stored list unchanged; an empty array clears it."- )+ ),+ autoApproval: AutoApprovalConfigSchema.optional()}),response: {200: z.object({@@ -106,6 +112,7 @@ export const registerPamApprovalConfigurationRouter = async (server: FastifyZodPsteps: req.body.steps,notificationConfigs: req.body.notificationConfigs,breakGlassUsers: req.body.breakGlassUsers,+ autoApproval: req.body.autoApproval,actorId: req.permission.id,actor: req.permission.type,actorOrgId: req.permission.orgId,@@ -123,7 +130,8 @@ export const registerPamApprovalConfigurationRouter = async (server: FastifyZodPpolicyId: result.policyId,stepCount: result.stepCount,notificationConfigCount: result.notificationConfigCount,- breakGlassUserCount: result.breakGlassUserCount+ breakGlassUserCount: result.breakGlassUserCount,+ autoApprovalRuleCount: result.autoApprovalRuleCount}}});diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 30faead9fb..983fc9baa5 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -842,12 +842,14 @@ export enum EventType {APPROVAL_REQUEST_LIST = "approval-request-list",APPROVAL_REQUEST_CREATE = "approval-request-create",APPROVAL_REQUEST_APPROVE = "approval-request-approve",+ APPROVAL_REQUEST_AUTO_APPROVE = "approval-request-auto-approve",APPROVAL_REQUEST_REJECT = "approval-request-reject",APPROVAL_REQUEST_CANCEL = "approval-request-cancel",APPROVAL_REQUEST_GRANT_LIST = "approval-request-grant-list",APPROVAL_REQUEST_GRANT_GET = "approval-request-grant-get",APPROVAL_REQUEST_GRANT_REVOKE = "approval-request-grant-revoke",PAM_ACCESS_POLICY_BYPASSED = "pam-access-policy-bypassed",+ PAM_ACCESS_REQUEST_AUTO_APPROVED = "pam-access-request-auto-approved",ACCESS_APPROVAL_REQUEST_CREATE = "access-approval-request-create",ACCESS_APPROVAL_REQUEST_REVIEW = "access-approval-request-review",ACCESS_APPROVAL_REQUEST_REVOKE = "access-approval-request-revoke",@@ -6832,6 +6834,7 @@ interface PamApprovalConfigUpdateEvent {stepCount: number;notificationConfigCount?: number;breakGlassUserCount?: number;+ autoApprovalRuleCount?: number;};}@@ -7035,6 +7038,25 @@ interface ApprovalRequestApproveEvent {} & TApprovalRequestSubjectMetadata;}+// The rule that approved the request and what it checked, so an admin can see why access was granted+type TAutoApprovalAuditMetadata = {+ ruleId: string | null;+ ruleName?: string;+ linkedRecords: { label: string; value: string }[];+ conditions: string[];+};++interface ApprovalRequestAutoApproveEvent {+ type: EventType.APPROVAL_REQUEST_AUTO_APPROVE;+ metadata: {+ policyType: string;+ approvalRequestId: string;+ requesterName: string;+ requesterEmail: string;+ } & TAutoApprovalAuditMetadata &+ TApprovalRequestSubjectMetadata;+}+interface ApprovalRequestRejectEvent {type: EventType.APPROVAL_REQUEST_REJECT;metadata: {@@ -7104,6 +7126,22 @@ interface PamAccessPolicyBypassedEvent {};}+interface PamAccessRequestAutoApprovedEvent {+ type: EventType.PAM_ACCESS_REQUEST_AUTO_APPROVED;+ metadata: {+ requestId: string;+ grantId?: string;+ accountId?: string;+ accountName?: string;+ folderId?: string;+ folderName?: string;+ requesterName?: string;+ requesterEmail?: string;+ duration?: string;+ accessType: string;+ } & TAutoApprovalAuditMetadata;+}+interface AccessApprovalRequestCreateEvent {type: EventType.ACCESS_APPROVAL_REQUEST_CREATE;metadata: {@@ -8608,12 +8646,14 @@ export type Event =| ApprovalRequestListEvent| ApprovalRequestCreateEvent| ApprovalRequestApproveEvent+ | ApprovalRequestAutoApproveEvent| ApprovalRequestRejectEvent| ApprovalRequestCancelEvent| ApprovalRequestGrantListEvent| ApprovalRequestGrantGetEvent| ApprovalRequestGrantRevokeEvent| PamAccessPolicyBypassedEvent+ | PamAccessRequestAutoApprovedEvent| AccessApprovalRequestCreateEvent| AccessApprovalRequestReviewEvent| AccessApprovalRequestRevokeEventdiff --git a/backend/src/ee/services/pam-access-request/pam-access-approval-resource.ts b/backend/src/ee/services/pam-access-request/pam-access-approval-resource.tsindex b4af3b434b..de3adda42a 100644--- a/backend/src/ee/services/pam-access-request/pam-access-approval-resource.ts+++ b/backend/src/ee/services/pam-access-request/pam-access-approval-resource.ts@@ -30,6 +30,7 @@ import {TApprovalRequestDALFactory,TApprovalRequestGrantsDALFactory} from "@app/services/approval-policy/approval-request-dal";+import { getAutoApprovalSummary } from "@app/services/approval-policy/auto-approval/auto-approval-fns";import {matchesPamAccessSubject,matchPamAccessGrants,@@ -489,6 +490,20 @@ export const pamAccessApprovalResourceFactory = ({}};+ // The account's template opts it in with Allow Auto-Approval+ const allowsAutoApproval: NonNullable<TPamAccessApprovalResource["allowsAutoApproval"]> = async ({+ projectId,+ requestData+ }) => {+ const { accountId } = requestData as { accountId?: string };+ if (!accountId) return false;++ const account = await pamAccountDAL.findByIdWithDetails(accountId);+ if (!account || account.projectId !== projectId) return false;++ return resolveAccessControls(account.templatePolicies).allowAutoApproval;+ };+const assertCanReview: NonNullable<TPamAccessApprovalResource["assertCanReview"]> = async ({request,decision,@@ -812,6 +827,37 @@ export const pamAccessApprovalResourceFactory = ({};}+ if (event === ApprovalNotificationEvent.AutoApproved) {+ const summary = getAutoApprovalSummary(request.autoApprovalEvidence);+ const ruleName = summary?.ruleName ?? "an auto-approval rule";+ const linkedRecords = summary?.linkedRecords.map(({ label, value }) => `${label} ${value}`).join(", ");+ const requestUrl = `${cfg.SITE_URL}/organizations/${orgId}/pam/approval-requests?requestId=${request.id}`;++ return {+ inApp: {+ type: NotificationType.ACCESS_APPROVAL_REQUEST_UPDATED,+ title: "Access auto-approved",+ body: `**${escapeMarkdown(requesterName)}** was granted ${accessTypeLabel} to **${escapeMarkdown(accountName)}** by the auto-approval rule "${escapeMarkdown(ruleName)}".`,+ link: requestUrl+ },+ email: {+ subjectLine: "PAM Access Auto-Approved",+ template: SmtpTemplates.AccessPamRequestAutoApproved,+ substitutions: {+ requesterFullName: requesterName,+ requesterEmail,+ folderName: folder?.name ?? undefined,+ accountName,+ accessDuration: formatDuration(inputs.duration),+ accessTypeLabel,+ ruleName,+ linkedRecords: linkedRecords || undefined,+ requestUrl+ }+ }+ };+ }+// A decided request leaves the approver inbox, so its messages link to the accounts page insteadconst approved = event === ApprovalNotificationEvent.Approved;return {@@ -995,6 +1041,26 @@ export const pamAccessApprovalResourceFactory = ({};}+ if (action === ApprovalAuditAction.RequestAutoApproved) {+ const summary = getAutoApprovalSummary(request.autoApprovalEvidence);+ if (!summary) return null;++ const [grant] = grantId ? [] : await approvalRequestGrantsDAL.find({ requestId: request.id });+ return {+ type: EventType.PAM_ACCESS_REQUEST_AUTO_APPROVED,+ metadata: {+ ...scope,+ requestId: request.id,+ grantId: grantId ?? grant?.id,+ requesterName: request.requesterName,+ requesterEmail: request.requesterEmail,+ duration: inputs?.duration,+ accessType: inputs?.accessType ?? PamAccessType.Session,+ ...summary+ }+ };+ }+if (action !== ApprovalAuditAction.RequestBypassed || !grantId) return null;const policy = request.policyId ? await approvalPolicyDAL.findById(request.policyId) : null;@@ -1073,6 +1139,7 @@ export const pamAccessApprovalResourceFactory = ({verifyPolicyActors,assertCanCreateRequest,assertCanReview,+ allowsAutoApproval,isBreakGlassEligible,assertBreakGlassEligible,assertCanRevokeGrant,diff --git a/backend/src/ee/services/pam-access-request/pam-access-request-events.ts b/backend/src/ee/services/pam-access-request/pam-access-request-events.tsindex 4908f3ee48..c130660e18 100644--- a/backend/src/ee/services/pam-access-request/pam-access-request-events.ts+++ b/backend/src/ee/services/pam-access-request/pam-access-request-events.ts@@ -14,7 +14,8 @@ const EVENT_BY_APPROVAL_EVENT: Record<ApprovalNotificationEvent, PamAccessReques[ApprovalNotificationEvent.Requested]: PamAccessRequestEvent.Requested,[ApprovalNotificationEvent.Approved]: PamAccessRequestEvent.Approved,[ApprovalNotificationEvent.Rejected]: PamAccessRequestEvent.Denied,- [ApprovalNotificationEvent.Bypassed]: PamAccessRequestEvent.Bypassed+ [ApprovalNotificationEvent.Bypassed]: PamAccessRequestEvent.Bypassed,+ [ApprovalNotificationEvent.AutoApproved]: PamAccessRequestEvent.Approved};export const buildPamAccessRequestEvent = ({diff --git a/backend/src/ee/services/pam-access-request/pam-access-request-service.ts b/backend/src/ee/services/pam-access-request/pam-access-request-service.tsindex 3588ee17df..a5a961cdc2 100644--- a/backend/src/ee/services/pam-access-request/pam-access-request-service.ts+++ b/backend/src/ee/services/pam-access-request/pam-access-request-service.ts@@ -179,7 +179,7 @@ export const pamAccessRequestServiceFactory = ({throw new NotFoundError({ message: "Folder not found" });}- const { steps, bypassers } = await approvalPolicyService.getScopeConfiguration(+ const { steps, bypassers, autoApproval } = await approvalPolicyService.getScopeConfiguration(ApprovalPolicyType.PamAccess,ApprovalPolicyScope.PamFolder,folderId,@@ -189,7 +189,8 @@ export const pamAccessRequestServiceFactory = ({return {steps: steps.map((step) => ({ approvers: step.approvers })),notificationConfigs: await getNotificationConfigs(folderId),- breakGlassUsers: bypassers+ breakGlassUsers: bypassers,+ autoApproval};};@@ -199,6 +200,7 @@ export const pamAccessRequestServiceFactory = ({steps,notificationConfigs,breakGlassUsers,+ autoApproval,...ctx}: TSetApprovalConfigurationDTO) => {await verifyProductMembership(permissionService, projectId, ctx);@@ -279,6 +281,7 @@ export const pamAccessRequestServiceFactory = ({{steps: steps.map((step) => ({ requiredApprovals: 1, approvers: step.approvers })),...(managesBreakGlass ? { bypassers: dedupedBreakGlassUsers } : {}),+ ...(autoApproval ? { autoApproval } : {}),name: `PAM Folder Approval - ${folder.name}`,conditions: [],constraints: { accessDuration: { min: "30s", max: "7d" } }@@ -296,7 +299,8 @@ export const pamAccessRequestServiceFactory = ({folderId,stepCount: steps.length,notificationConfigCount: notificationConfigs?.length,- breakGlassUserCount: managesBreakGlass ? dedupedBreakGlassUsers.length : undefined+ breakGlassUserCount: managesBreakGlass ? dedupedBreakGlassUsers.length : undefined,+ autoApprovalRuleCount: autoApproval?.rules.length};};@@ -387,6 +391,7 @@ export const pamAccessRequestServiceFactory = ({duration,accessType = PamAccessType.Session,breakGlass = false,+ autoApprovalInputs,...ctx}: TCreateAccessRequestDTO) => {const trimmedReason = reason?.trim() || undefined;@@ -439,6 +444,8 @@ export const pamAccessRequestServiceFactory = ({},justification: trimmedReason,skipApproverNotification: breakGlass,+ autoApprovalInputs,+ skipAutoApproval: breakGlass,machineIdentityId: ctx.actor === ActorType.IDENTITY ? ctx.actorId : undefined,requesterName: requester.name,requesterEmail: requester.email@@ -618,7 +625,7 @@ export const pamAccessRequestServiceFactory = ({ctx);- if (!account.folderId) return { steps: [] };+ if (!account.folderId) return { steps: [], autoApprovalInputs: [] };return approvalPolicyService.getApproverRoster(ApprovalPolicyType.PamAccess,diff --git a/backend/src/ee/services/pam-access-request/pam-access-request-types.ts b/backend/src/ee/services/pam-access-request/pam-access-request-types.tsindex 0c80497abd..12bfe4768c 100644--- a/backend/src/ee/services/pam-access-request/pam-access-request-types.ts+++ b/backend/src/ee/services/pam-access-request/pam-access-request-types.ts@@ -1,4 +1,8 @@import { ApprovalRequestApprovalDecision, ApproverType } from "@app/services/approval-policy/approval-policy-enums";+import {+ TAutoApprovalConfig,+ TAutoApprovalInputValue+} from "@app/services/approval-policy/auto-approval/auto-approval-types";import { ActorType } from "@app/services/auth/auth-type";import { PamAccessType, PamNotificationEvent } from "../pam/pam-enums";@@ -24,6 +28,8 @@ export type TSetApprovalConfigurationDTO = {// undefined leaves existing configs unchanged so older clients that only manage steps can't wipe themnotificationConfigs?: TPamNotificationConfigInput[];breakGlassUsers?: { type: ApproverType; id: string }[];+ // undefined leaves the stored rules unchanged+ autoApproval?: TAutoApprovalConfig;} & TActorContext;export type TBreakGlassAccessRequestDTO = {@@ -40,6 +46,7 @@ export type TCreateAccessRequestDTO = {reason?: string;duration: string;accessType?: PamAccessType;+ autoApprovalInputs?: TAutoApprovalInputValue[];} & TActorContext;export type TListAccessRequestsDTO = {diff --git a/backend/src/ee/services/pam/pam-policies.test.ts b/backend/src/ee/services/pam/pam-policies.test.tsindex bf28a14793..0dd41f756d 100644--- a/backend/src/ee/services/pam/pam-policies.test.ts+++ b/backend/src/ee/services/pam/pam-policies.test.ts@@ -96,6 +96,7 @@ describe("validatePolicyValues", () => {describe("resolveAccessControls", () => {const DEFAULTS = {requiresApproval: false,+ allowAutoApproval: false,allowBreakGlass: false,requireReason: false,requireMfa: false,@@ -150,6 +151,16 @@ describe("resolveAccessControls", () => {).toBe(false);});+ test("auto-approval only resolves alongside the approval it decides", () => {+ expect(+ resolveAccessControls({+ [PamPolicyType.RequiresApproval]: true,+ [PamPolicyType.AllowAutoApproval]: true+ }).allowAutoApproval+ ).toBe(true);+ expect(resolveAccessControls({ [PamPolicyType.AllowAutoApproval]: true }).allowAutoApproval).toBe(false);+ });+test("treats the boolean gates as strict: only literal true enables them", () => {expect(resolveAccessControls({ [PamPolicyType.RequireMfa]: false }).requireMfa).toBe(false);// a non-boolean stored value fails its schema and resolves to the default, never throwsdiff --git a/backend/src/ee/services/pam/pam-policies.ts b/backend/src/ee/services/pam/pam-policies.tsindex 05163c4f3e..2a3509c94d 100644--- a/backend/src/ee/services/pam/pam-policies.ts+++ b/backend/src/ee/services/pam/pam-policies.ts@@ -5,6 +5,7 @@ import { PamAccountType } from "./pam-enums";export enum PamPolicyType {RequiresApproval = "requires-approval",+ AllowAutoApproval = "allow-auto-approval",AllowBreakGlass = "allow-break-glass",RequireMfa = "require-mfa",RequireReason = "require-reason",@@ -71,6 +72,13 @@ export const PAM_POLICY_DEFINITIONS: Record<PamPolicyType, TPamPolicyDefinition>appliesTo: "all",schema: z.boolean()},+ [PamPolicyType.AllowAutoApproval]: {+ label: "Allow Auto-Approval",+ description:+ "Requests are approved instantly when they pass one of the folder's auto-approval rules, such as a linked Jira ticket that is approved. Set the rules under the folder's Approvals tab.",+ appliesTo: "all",+ schema: z.boolean()+ },[PamPolicyType.AllowBreakGlass]: {label: "Allow Break-Glass",description:@@ -187,6 +195,7 @@ export const resolvePolicy = (policyMap: unknown, policy: PamPolicyType): unknowexport type TPamAccessControls = {requiresApproval: boolean;+ allowAutoApproval: boolean;allowBreakGlass: boolean;requireReason: boolean;requireMfa: boolean;@@ -245,6 +254,7 @@ export const resolveAccessControls = (policyMap: unknown): TPamAccessControls =>const requiresApproval = resolvePolicy(policyMap, PamPolicyType.RequiresApproval) === true;return {requiresApproval,+ allowAutoApproval: requiresApproval && resolvePolicy(policyMap, PamPolicyType.AllowAutoApproval) === true,allowBreakGlass: requiresApproval && resolvePolicy(policyMap, PamPolicyType.AllowBreakGlass) === true,requireReason: resolvePolicy(policyMap, PamPolicyType.RequireReason) === true,requireMfa: resolvePolicy(policyMap, PamPolicyType.RequireMfa) === true,diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 7425c41270..7d8b4b8141 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4680,3 +4680,35 @@ export const PKI_SYNC_FILTERS = {previewOffset: "The offset to start from. If you enter 10, it will start from the 10th matching certificate.",previewLimit: "The number of matching certificates to return."};++export const APPROVAL_POLICY_AUTO_APPROVAL = {+ autoApproval:+ "Rules that approve a request instantly when another system already vouches for it. Sending this replaces the policy's inputs and rules; omit it to leave them unchanged.",+ inputs:+ "Request information: records requesters can link when they submit, such as a Jira ticket. Each one adds an optional field to the request form.",+ inputConnectionId: "The ID of the App Connection the record is read through.",+ inputSubject:+ "What the requester links, from the connection's subjects in the auto-approval catalog (e.g. 'submitted-ticket').",+ rules: "The rules a request is checked against on submission. Any passing rule approves it; a rule never rejects.",+ ruleName: "A name that tells approvers why the rule approved a request.",+ conditions: "Every condition in a rule must pass for the rule to approve.",+ conditionConnectionId:+ "The ID of the App Connection the condition reads, matching one of the inputs, or any available connection when the subject is 'requester'.",+ conditionSubject:+ "What the condition checks: one of the inputs' subjects, or 'requester' for the requester's own account.",+ constraint: "Which check to run, from the subject's constraints in the auto-approval catalog (e.g. 'status').",+ values: "The values the check accepts. Several values mean any of them; checks that take no value use an empty list.",+ requestInputs:+ "Values for the policy's request information, such as a Jira ticket key or link. Malformed values are rejected.",+ requestInputValue: "The value the requester entered, such as 'PAY-123' or a link to the ticket.",+ outcome:+ "How the policy's auto-approval rules evaluated this request at submission. Null when the policy had no rules or the resource does not allow auto-approval.",+ catalogScope: "The scope of the policy the rules are for.",+ catalogScopeId: "The ID of the scope.",+ optionsConnectionId: "The ID of the App Connection to list values from.",+ optionsSubject: "The subject the condition checks.",+ optionsConstraint: "The check to list values for.",+ optionsSearch: "Filters the values by this text.",+ optionsSiblings:+ "A JSON object of the values already picked in the rule's other conditions, keyed by constraint, which narrows the values listed (e.g. statuses for the picked projects)."+};diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 11545fa4ef..13afe18f40 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -293,6 +293,8 @@ import {approvalRequestStepEligibleApproversDALFactory,approvalRequestStepsDALFactory} from "@app/services/approval-policy/approval-request-dal";+import { approvalPolicyAutoApprovalDALFactory } from "@app/services/approval-policy/auto-approval/auto-approval-dal";+import { autoApprovalServiceFactory } from "@app/services/approval-policy/auto-approval/auto-approval-service";import { certRequestApprovalResourceFactory } from "@app/services/approval-policy/cert-request/cert-request-policy-factory";import { codeSigningApprovalResourceFactory } from "@app/services/approval-policy/code-signing/code-signing-policy-factory";import { secretAccessApprovalGlobalResourceFactory } from "@app/services/approval-policy/secret-access/secret-access-policy-factory";@@ -855,6 +857,7 @@ export const registerRoutes = async (const approvalPolicyStepsDAL = approvalPolicyStepsDALFactory(db);const approvalPolicyStepApproversDAL = approvalPolicyStepApproversDALFactory(db);const approvalPolicyBypassersDAL = approvalPolicyBypassersDALFactory(db);+ const approvalPolicyAutoApprovalDAL = approvalPolicyAutoApprovalDALFactory(db);const approvalPolicySecretEnvironmentDAL = approvalPolicySecretEnvironmentDALFactory(db);const approvalRequestDAL = approvalRequestDALFactory(db);const secretChangeGlobalPolicyBridgeDAL = secretChangeGlobalPolicyBridgeDALFactory(db);@@ -3915,6 +3918,15 @@ export const registerRoutes = async (}) as TApprovalResourceRegistry[ApprovalPolicyType]};+ const autoApprovalService = autoApprovalServiceFactory({+ approvalPolicyAutoApprovalDAL,+ appConnectionDAL,+ appConnectionService,+ kmsService,+ gatewayV2Service,+ gatewayPoolService+ });+const approvalPolicyService = approvalPolicyServiceFactory({approvalPolicyDAL,approvalPolicyStepsDAL,@@ -3938,6 +3950,7 @@ export const registerRoutes = async (slackIntegrationDAL,kmsService,eventEmitter: eventOutboxService,+ autoApprovalService,resources: approvalResources});diff --git a/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts b/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.tsindex cc2d0feff1..c85929a60a 100644--- a/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts+++ b/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts@@ -1,6 +1,7 @@import { z } from "zod";import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { APPROVAL_POLICY_AUTO_APPROVAL } from "@app/lib/api-docs";import { BadRequestError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";@@ -19,6 +20,11 @@ import {TUpdatePolicyDTO} from "@app/services/approval-policy/approval-policy-types";import { getApprovalRequestSubjectMetadata } from "@app/services/approval-policy/approval-request-fns";+import { getAutoApprovalSummary } from "@app/services/approval-policy/auto-approval/auto-approval-fns";+import {+ AutoApprovalCatalogSchema,+ AutoApprovalSiblingsSchema+} from "@app/services/approval-policy/auto-approval/auto-approval-schemas";import {CreateCertRequestPolicySchema,UpdateCertRequestPolicySchema@@ -337,6 +343,74 @@ export const registerApprovalPolicyEndpoints = ({}});+ if (allowRequestCreation) {+ server.route({+ method: "GET",+ url: "/auto-approval/catalog",+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "getApprovalPolicyAutoApprovalCatalog",+ description:+ "List the App Connections auto-approval rules can use for a policy's scope, with what each one can check",+ querystring: z.object({+ scope: z.nativeEnum(ApprovalPolicyScope).describe(APPROVAL_POLICY_AUTO_APPROVAL.catalogScope),+ id: z.string().uuid().describe(APPROVAL_POLICY_AUTO_APPROVAL.catalogScopeId)+ }),+ response: {+ 200: AutoApprovalCatalogSchema+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const { connections } = await server.services.approvalPolicy.getAutoApprovalCatalog(+ policyType,+ req.query.scope,+ req.query.id,+ req.permission+ );++ return { connections };+ }+ });++ server.route({+ method: "GET",+ url: "/auto-approval/options",+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "listApprovalPolicyAutoApprovalOptions",+ description: "List the values a condition can check, read from the connected service",+ querystring: z.object({+ scope: z.nativeEnum(ApprovalPolicyScope).describe(APPROVAL_POLICY_AUTO_APPROVAL.catalogScope),+ id: z.string().uuid().describe(APPROVAL_POLICY_AUTO_APPROVAL.catalogScopeId),+ connectionId: z.string().uuid().describe(APPROVAL_POLICY_AUTO_APPROVAL.optionsConnectionId),+ subject: z.string().trim().min(1).max(64).describe(APPROVAL_POLICY_AUTO_APPROVAL.optionsSubject),+ constraint: z.string().trim().min(1).max(64).describe(APPROVAL_POLICY_AUTO_APPROVAL.optionsConstraint),+ search: z.string().trim().max(255).optional().describe(APPROVAL_POLICY_AUTO_APPROVAL.optionsSearch),+ siblings: AutoApprovalSiblingsSchema+ }),+ response: {+ 200: z.object({+ options: z.object({ value: z.string(), label: z.string() }).array()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const { scope, id, ...rest } = req.query;+ return server.services.approvalPolicy.listAutoApprovalOptions(+ policyType,+ { scope, scopeId: id, ...rest },+ req.permission+ );+ }+ });+ }+// Requestsserver.route({method: "GET",@@ -454,6 +528,32 @@ export const registerApprovalPolicyEndpoints = ({}});+ const autoApprovalSummary = request.autoApprovedAt+ ? getAutoApprovalSummary(request.autoApprovalEvidence)+ : null;+ if (autoApprovalSummary) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: request.projectId,+ event: (await server.services.approvalPolicy.buildAuditEvent({+ action: ApprovalAuditAction.RequestAutoApproved,+ request,+ actorId: req.permission.id+ })) ?? {+ type: EventType.APPROVAL_REQUEST_AUTO_APPROVE,+ metadata: {+ policyType: request.type,+ approvalRequestId: request.id,+ requesterName: request.requesterName,+ requesterEmail: request.requesterEmail,+ ...autoApprovalSummary,+ ...getApprovalRequestSubjectMetadata(request)+ }+ }+ });+ }+if (policyType === ApprovalPolicyType.CertRequest || policyType === ApprovalPolicyType.CertCodeSigning) {await sendTelemetry({event: PostHogEventTypes.PkiApprovalRequestCreated,diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.tsindex 717e87bbb1..959d8430ee 100644--- a/backend/src/services/app-connection/app-connection-fns.ts+++ b/backend/src/services/app-connection/app-connection-fns.ts@@ -372,6 +372,8 @@ const PKI_APP_CONNECTIONS = [const AGENT_VAULT_APP_CONNECTIONS = [AppConnection.AWS];+const PAM_APP_CONNECTIONS = [AppConnection.Jira];+export const isAppConnectionAllowedInProject = (app: AppConnection, projectType?: ProjectType) => {switch (projectType) {case ProjectType.SecretManager:@@ -387,7 +389,7 @@ export const isAppConnectionAllowedInProject = (app: AppConnection, projectType?case ProjectType.KMS:return false;case ProjectType.PAM:- return false;+ return PAM_APP_CONNECTIONS.includes(app);case ProjectType.AgentVault:return AGENT_VAULT_APP_CONNECTIONS.includes(app);default:diff --git a/backend/src/services/approval-policy/approval-policy-enums.ts b/backend/src/services/approval-policy/approval-policy-enums.tsindex 797ca96b46..96567efdc7 100644--- a/backend/src/services/approval-policy/approval-policy-enums.ts+++ b/backend/src/services/approval-policy/approval-policy-enums.ts@@ -2,13 +2,15 @@ export enum ApprovalNotificationEvent {Requested = "requested",Approved = "approved",Rejected = "rejected",- Bypassed = "bypassed"+ Bypassed = "bypassed",+ AutoApproved = "auto-approved"}export enum ApprovalAuditAction {RequestCreated = "request-created",RequestReviewed = "request-reviewed",RequestBypassed = "request-bypassed",+ RequestAutoApproved = "request-auto-approved",GrantRevoked = "grant-revoked"}diff --git a/backend/src/services/approval-policy/approval-policy-schemas.ts b/backend/src/services/approval-policy/approval-policy-schemas.tsindex 0012818ca0..b335f27db1 100644--- a/backend/src/services/approval-policy/approval-policy-schemas.ts+++ b/backend/src/services/approval-policy/approval-policy-schemas.ts@@ -10,6 +10,13 @@ import {import { ms } from "@app/lib/ms";import { ApprovalPolicyScope, ApproverType, EnforcementLevel } from "./approval-policy-enums";+import {+ AutoApprovalConfigResponseSchema,+ AutoApprovalConfigSchema,+ AutoApprovalInputValuesSchema,+ AutoApprovalOutcomeSchema,+ AutoApprovalInputDetailsSchema+} from "./auto-approval/auto-approval-schemas";const ApprovalPolicyStepSchema = z.object({name: z.string().min(1).max(128).nullable().optional(),@@ -42,7 +49,8 @@ const MaxRequestTtlSchema = z.string().refine(export const BaseApprovalPolicySchema = ApprovalPoliciesSchema.extend({steps: ApprovalPolicyStepSchema.array(),enforcementLevel: z.nativeEnum(EnforcementLevel).default(EnforcementLevel.Hard),- bypassers: BypasserSchema.array().default([])+ bypassers: BypasserSchema.array().default([]),+ autoApproval: AutoApprovalConfigResponseSchema.optional()});export const BaseCreateApprovalPolicySchema = z.object({@@ -53,7 +61,8 @@ export const BaseCreateApprovalPolicySchema = z.object({steps: ApprovalPolicyStepSchema.array(),bypassForMachineIdentities: z.boolean().optional().default(false),enforcementLevel: z.nativeEnum(EnforcementLevel).optional().default(EnforcementLevel.Hard),- bypassers: BypasserSchema.array().max(100).optional().default([])+ bypassers: BypasserSchema.array().max(100).optional().default([]),+ autoApproval: AutoApprovalConfigSchema.optional()});export const BaseUpdateApprovalPolicySchema = z.object({@@ -62,7 +71,8 @@ export const BaseUpdateApprovalPolicySchema = z.object({steps: ApprovalPolicyStepSchema.array().optional(),bypassForMachineIdentities: z.boolean().optional(),enforcementLevel: z.nativeEnum(EnforcementLevel).optional(),- bypassers: BypasserSchema.array().max(100).optional()+ bypassers: BypasserSchema.array().max(100).optional(),+ autoApproval: AutoApprovalConfigSchema.optional()});// Request@@ -83,11 +93,12 @@ const ApprovalRequestStepSchema = ApprovalRequestStepsSchema.extend({approvals: ApprovalRequestApprovalsSchema.array()});-export const BaseApprovalRequestSchema = ApprovalRequestsSchema.extend({+export const BaseApprovalRequestSchema = ApprovalRequestsSchema.omit({ autoApprovalEvidence: true }).extend({steps: ApprovalRequestStepSchema.array(),canBreakGlass: z.boolean().default(false),isBreakGlass: z.boolean().default(false),- bypassReason: z.string().nullable().optional()+ bypassReason: z.string().nullable().optional(),+ autoApproval: AutoApprovalOutcomeSchema.optional()});export const BaseCreateApprovalRequestSchema = z.object({@@ -106,7 +117,8 @@ export const BaseCreateApprovalRequestSchema = z.object({{ message: "Duration must be between 1 minute and 30 days" }).nullable()- .optional()+ .optional(),+ autoApprovalInputs: AutoApprovalInputValuesSchema.optional()});// Grants@@ -115,5 +127,6 @@ export const BaseApprovalRequestGrantSchema = ApprovalRequestGrantsSchema;// Check Policy Match Responseexport const BaseCheckPolicyMatchResponseSchema = z.object({requiresApproval: z.boolean(),- hasActiveGrant: z.boolean()+ hasActiveGrant: z.boolean(),+ autoApprovalInputs: AutoApprovalInputDetailsSchema.array().optional()});diff --git a/backend/src/services/approval-policy/approval-policy-service.ts b/backend/src/services/approval-policy/approval-policy-service.tsindex 10da716c92..e79782a88e 100644--- a/backend/src/services/approval-policy/approval-policy-service.ts+++ b/backend/src/services/approval-policy/approval-policy-service.ts@@ -69,6 +69,7 @@ import {TApprovalResourceRegistry,TApprovalScopeConfiguration,TApprovalSubjectActor,+ TAutoApprovalAffordance,TBypassAffordances,TCreatePolicyDTO,TCreateRequestDTO,@@ -84,6 +85,9 @@ import {TApprovalRequestStepsDALFactory} from "./approval-request-dal";import { createApprovalRequestWithSteps } from "./approval-request-fns";+import { toAutoApprovalOutcome } from "./auto-approval/auto-approval-fns";+import { TAutoApprovalServiceFactory } from "./auto-approval/auto-approval-service";+import { TAutoApprovalConfig, TAutoApprovalEvidence } from "./auto-approval/auto-approval-types";type TApprovalPolicyServiceFactoryDep = {approvalPolicyDAL: TApprovalPolicyDALFactory;@@ -111,6 +115,18 @@ type TApprovalPolicyServiceFactoryDep = {userDAL: Pick<TUserDALFactory, "findById" | "find">;groupDAL: Pick<TGroupDALFactory, "find">;eventEmitter: TEventEmitter;+ autoApprovalService: Pick<+ TAutoApprovalServiceFactory,+ | "validateConfig"+ | "replaceConfig"+ | "findByPolicyIds"+ | "toPolicyResponse"+ | "getInputDetails"+ | "parseInputValues"+ | "evaluate"+ | "getCatalog"+ | "listOptions"+ >;resources: TApprovalResourceRegistry;};@@ -139,6 +155,7 @@ export const approvalPolicyServiceFactory = ({userDAL,groupDAL,eventEmitter,+ autoApprovalService,resources}: TApprovalPolicyServiceFactoryDep) => {const $resource = (policyType: ApprovalPolicyType) => {@@ -239,14 +256,18 @@ export const approvalPolicyServiceFactory = ({status?: string | null;requesterId?: string | null;policyId?: string | null;+ autoApprovedAt?: Date | null;+ autoApprovalEvidence?: unknown;}>(request: R,actor: TApprovalActor,ctx: TDecorationContext = $buildDecorationContext(actor)- ): Promise<R & TBypassAffordances> => {+ ): Promise<R & TBypassAffordances & TAutoApprovalAffordance> => {+ const autoApproval = toAutoApprovalOutcome(request);+if (!resources[request.type as ApprovalPolicyType]?.isBreakGlassEligible) {- return { ...request, canBreakGlass: false, isBreakGlass: false, bypassReason: null };+ return { ...request, canBreakGlass: false, isBreakGlass: false, bypassReason: null, autoApproval };}let canBreakGlass = false;@@ -292,10 +313,31 @@ export const approvalPolicyServiceFactory = ({...request,canBreakGlass,isBreakGlass,- bypassReason+ bypassReason,+ autoApproval};};+ const $assertSupportsAutoApproval = (policyType: ApprovalPolicyType, autoApproval?: TAutoApprovalConfig) => {+ const configuresAutoApproval = Boolean(autoApproval?.rules.length || autoApproval?.inputs.length);+ if (configuresAutoApproval && policyType === ApprovalPolicyType.CertRequest) {+ throw new BadRequestError({+ message: "Auto-approval rules aren't available for certificate request policies"+ });+ }+ };++ const $withAutoApproval = async <T extends { id: string }>(policies: T[], tx?: Knex) => {+ const stored = await autoApprovalService.findByPolicyIds(+ policies.map((policy) => policy.id),+ tx+ );+ return policies.map((policy) => ({+ ...policy,+ autoApproval: autoApprovalService.toPolicyResponse(stored.get(policy.id))+ }));+ };+const $resolveScope = async (scope: ApprovalPolicyScope,scopeId: string,@@ -602,7 +644,8 @@ export const approvalPolicyServiceFactory = ({steps,bypassForMachineIdentities,enforcementLevel,- bypassers+ bypassers,+ autoApproval}: TCreatePolicyDTO,actor: TApprovalActor) => {@@ -663,6 +706,11 @@ export const approvalPolicyServiceFactory = ({bypassers: bypassers ?? []});+ $assertSupportsAutoApproval(policyType, autoApproval);+ const autoApprovalConfig = autoApproval+ ? await autoApprovalService.validateConfig({ projectId, config: autoApproval, actor })+ : undefined;+const writePolicy = async (tx: Knex) => {const newPolicy = await approvalPolicyDAL.create({@@ -727,7 +775,12 @@ export const approvalPolicyServiceFactory = ({);}- return newPolicy;+ if (autoApprovalConfig) {+ await autoApprovalService.replaceConfig(newPolicy.id, autoApprovalConfig, tx);+ }++ const [withAutoApproval] = await $withAutoApproval([newPolicy], tx);+ return withAutoApproval;};const policy = await (onePolicyPerScope@@ -772,7 +825,7 @@ export const approvalPolicyServiceFactory = ({scopeId: dbScopeId});- return { policies, projectId };+ return { policies: await $withAutoApproval(policies), projectId };};const getById = async (policyId: string, actor: TApprovalActor, policyType: ApprovalPolicyType) => {@@ -792,12 +845,13 @@ export const approvalPolicyServiceFactory = ({$assertPolicyType(policy.type, policyType);- const [steps, bypassers] = await Promise.all([+ const [steps, bypassers, [withAutoApproval]] = await Promise.all([approvalPolicyDAL.findStepsByPolicyId(policyId),- approvalPolicyDAL.findBypassersByPolicyId(policyId)+ approvalPolicyDAL.findBypassersByPolicyId(policyId),+ $withAutoApproval([policy])]);- return { policy: { ...policy, steps, bypassers } };+ return { policy: { ...withAutoApproval, steps, bypassers } };};const updateById = async (@@ -810,7 +864,8 @@ export const approvalPolicyServiceFactory = ({steps,bypassForMachineIdentities,enforcementLevel,- bypassers+ bypassers,+ autoApproval}: TUpdatePolicyDTO,actor: TApprovalActor,policyType: ApprovalPolicyType@@ -853,6 +908,11 @@ export const approvalPolicyServiceFactory = ({bypassers: bypassers ?? []});+ $assertSupportsAutoApproval(policy.type as ApprovalPolicyType, autoApproval);+ const autoApprovalConfig = autoApproval+ ? await autoApprovalService.validateConfig({ projectId: policy.projectId, config: autoApproval, actor })+ : undefined;+const updatedPolicy = await approvalPolicyDAL.transaction(async (tx) => {const updateDoc: Partial<TApprovalPolicies> = {};@@ -937,7 +997,12 @@ export const approvalPolicyServiceFactory = ({}}- return updated;+ if (autoApprovalConfig) {+ await autoApprovalService.replaceConfig(policyId, autoApprovalConfig, tx);+ }++ const [withAutoApproval] = await $withAutoApproval([updated], tx);+ return withAutoApproval;});const [fetchedSteps, fetchedBypassers] = await Promise.all([@@ -1002,6 +1067,7 @@ export const approvalPolicyServiceFactory = ({requesterName,requesterEmail,skipApproverNotification,+ autoApprovalEvidence,tx}: TCreateRequestFromPolicyDTO) => {const requestWithSteps = await createApprovalRequestWithSteps(@@ -1019,7 +1085,8 @@ export const approvalPolicyServiceFactory = ({requesterName,requesterEmail,scopeType: policy.scopeType ?? null,- scopeId: policy.scopeId ?? null+ scopeId: policy.scopeId ?? null,+ autoApprovalEvidence},{approvalRequestDAL,@@ -1045,6 +1112,72 @@ export const approvalPolicyServiceFactory = ({};};+ const $createAutoApprovedRequest = async ({+ projectId,+ policy,+ requestData,+ justification,+ expiresAt,+ requesterName,+ requesterEmail,+ machineIdentityId,+ evidence,+ actor+ }: {+ projectId: string;+ policy: TApprovalPolicy;+ requestData: TCreateRequestDTO["requestData"];+ justification?: string | null;+ expiresAt?: Date;+ requesterName: string;+ requesterEmail: string;+ machineIdentityId?: string;+ evidence: TAutoApprovalEvidence;+ actor: TApprovalActor;+ }) => {+ const resource = $resource(policy.type as ApprovalPolicyType);++ const approved = await approvalRequestDAL.transaction(async (tx) => {+ const created = await createApprovalRequestWithSteps(+ {+ projectId,+ organizationId: actor.orgId,+ policyId: policy.id,+ policyType: policy.type as ApprovalPolicyType,+ policySteps: policy.steps,+ requestData,+ status: ApprovalRequestStatus.Approved,+ justification,+ expiresAt,+ requesterUserId: actor.type === ActorType.IDENTITY ? undefined : actor.id,+ machineIdentityId,+ requesterName,+ requesterEmail,+ scopeType: policy.scopeType ?? null,+ scopeId: policy.scopeId ?? null,+ autoApprovalEvidence: evidence,+ autoApprovedAt: new Date()+ },+ { approvalRequestDAL, approvalRequestStepsDAL, approvalRequestStepEligibleApproversDAL },+ tx+ );++ await resource.postApprovalTxRoutine?.(created as unknown as TApprovalRequest, tx);+ await $emitEvent({ event: ApprovalNotificationEvent.AutoApproved, request: created }, tx);+ return created;+ });++ await resource.postApprovalRoutine?.(approved as unknown as TApprovalRequest, actor);+ await $notify({+ event: ApprovalNotificationEvent.AutoApproved,+ request: approved,+ approvers: approved.steps.flatMap((step) => step.approvers),+ actorId: actor.id+ });++ return approved;+ };+const createRequest = async (policyType: ApprovalPolicyType,{@@ -1056,7 +1189,9 @@ export const approvalPolicyServiceFactory = ({requesterName,requesterEmail,machineIdentityId,- skipApproverNotification+ skipApproverNotification,+ autoApprovalInputs,+ skipAutoApproval}: TCreateRequestDTO & {requesterName: string;requesterEmail: string;@@ -1138,6 +1273,53 @@ export const approvalPolicyServiceFactory = ({}}+ const storedAutoApproval = (await autoApprovalService.findByPolicyIds([policy.id])).get(policy.id);+ const parsedInputs = await autoApprovalService.parseInputValues({+ stored: storedAutoApproval,+ values: autoApprovalInputs ?? [],+ orgId: actor.orgId,+ projectId+ });++ let autoApprovalEvidence: TAutoApprovalEvidence | null = null;+ if (storedAutoApproval?.rules.length && !skipAutoApproval) {+ const allowed =+ (await resource.allowsAutoApproval?.({ projectId, requestData: requestData as TApprovalRequestData })) ?? true;++ if (allowed) {+ autoApprovalEvidence = await autoApprovalService.evaluate({+ stored: storedAutoApproval,+ parsedInputs,+ orgId: actor.orgId,+ projectId,+ ctx: {+ requester: {+ userId: actor.type === ActorType.USER ? actor.id : null,+ machineIdentityId: machineIdentityId ?? null,+ email: actor.type === ActorType.USER ? requesterEmail || null : null+ }+ }+ });+ }+ }++ if (autoApprovalEvidence?.approvedByRuleId) {+ const approved = await $createAutoApprovedRequest({+ projectId,+ policy,+ requestData,+ justification,+ expiresAt,+ requesterName,+ requesterEmail,+ machineIdentityId,+ evidence: autoApprovalEvidence,+ actor+ });++ return { request: await $decorateRequest(approved, actor) };+ }+const created = await createRequestFromPolicy({projectId,organizationId: actor.orgId,@@ -1149,7 +1331,8 @@ export const approvalPolicyServiceFactory = ({machineIdentityId,requesterName,requesterEmail,- skipApproverNotification+ skipApproverNotification,+ autoApprovalEvidence});const decorated = await $decorateRequest(created.request, actor);@@ -1937,6 +2120,20 @@ export const approvalPolicyServiceFactory = ({return { grant: updatedGrant, request };};+ // The request information a requester can link for a policy, or none when the resource keeps its rules off+ const $getAutoApprovalInputs = async (+ policyType: ApprovalPolicyType,+ projectId: string,+ policyId: string,+ data: TApprovalPolicyInputs | TApprovalRequestData+ ) => {+ const stored = (await autoApprovalService.findByPolicyIds([policyId])).get(policyId);+ if (!stored?.rules.length || !stored.inputs.length) return [];++ const allowed = (await resources[policyType]?.allowsAutoApproval?.({ projectId, requestData: data })) ?? true;+ return allowed ? autoApprovalService.getInputDetails(stored) : [];+ };+const checkPolicyMatch = async (policyType: ApprovalPolicyType,{ projectId, inputs }: { projectId: string; inputs: TApprovalPolicyInputs },@@ -1970,10 +2167,64 @@ export const approvalPolicyServiceFactory = ({return {requiresApproval: !activeGrant,hasActiveGrant: !!activeGrant,- constraints+ constraints,+ autoApprovalInputs: await $getAutoApprovalInputs(policyType, projectId, policy.id, inputs)};};+ const getAutoApprovalCatalog = async (+ policyType: ApprovalPolicyType,+ scope: ApprovalPolicyScope,+ inputScopeId: string,+ actor: TApprovalActor+ ) => {+ const { projectId, scopeType, scopeId } = await $resolveScope(scope, inputScopeId, policyType);+ await $assertCanManagePolicy(+ projectId,+ scopeType,+ scopeId,+ actor,+ ResourcePermissionApprovalPolicyActions.Read,+ policyType+ );++ return { ...(await autoApprovalService.getCatalog({ projectId, actor })), projectId };+ };++ const listAutoApprovalOptions = async (+ policyType: ApprovalPolicyType,+ {+ scope,+ scopeId: inputScopeId,+ connectionId,+ subject,+ constraint,+ search,+ siblings+ }: {+ scope: ApprovalPolicyScope;+ scopeId: string;+ connectionId: string;+ subject: string;+ constraint: string;+ search?: string;+ siblings: Record<string, string[]>;+ },+ actor: TApprovalActor+ ) => {+ const { projectId, scopeType, scopeId } = await $resolveScope(scope, inputScopeId, policyType);+ await $assertCanManagePolicy(+ projectId,+ scopeType,+ scopeId,+ actor,+ ResourcePermissionApprovalPolicyActions.Read,+ policyType+ );++ return autoApprovalService.listOptions({ projectId, actor, connectionId, subject, constraint, search, siblings });+ };+const $actorGrantFilter = (actor: TApprovalSubjectActor) =>actor.type === ActorType.IDENTITY ? { granteeMachineIdentityId: actor.id } : { granteeUserId: actor.id };@@ -2176,7 +2427,8 @@ export const approvalPolicyServiceFactory = ({grantExpiresAt: grant?.expiresAt ?? null,grantStatus: grant?.status ?? null,isBreakGlass: Boolean(grant?.isBreakGlass),- bypassReason: grant?.bypassReason ?? null+ bypassReason: grant?.bypassReason ?? null,+ autoApproval: toAutoApprovalOutcome(request as { autoApprovedAt?: Date | null; autoApprovalEvidence?: unknown })};});};@@ -2314,7 +2566,11 @@ export const approvalPolicyServiceFactory = ({}));}- if (steps.length === 0) return { steps: [] };+ if (steps.length === 0) return { steps: [], autoApprovalInputs: [] };++ const autoApprovalInputs = policy+ ? await $getAutoApprovalInputs(policyType, projectId, policy.id, inputs)+ : [];const approvers = steps.flatMap((step) => step.approvers);const userIds = approvers.filter((a) => a.type === ApproverType.User).map((a) => a.id);@@ -2336,6 +2592,7 @@ export const approvalPolicyServiceFactory = ({});return {+ autoApprovalInputs,steps: steps.map((step) => ({requiredApprovals: step.requiredApprovals,approvers: step.approvers.map((a) =>@@ -2366,9 +2623,10 @@ export const approvalPolicyServiceFactory = ({requiredApprovals: step.requiredApprovals,approvers: step.approvers})),- bypassers: policy.bypassers.map((bypasser) => ({ type: bypasser.type, id: bypasser.id }))+ bypassers: policy.bypassers.map((bypasser) => ({ type: bypasser.type, id: bypasser.id })),+ autoApproval: policy.autoApproval}- : { steps: [], bypassers: [] };+ : { steps: [], bypassers: [], autoApproval: autoApprovalService.toPolicyResponse() };};const setScopeConfiguration = async (@@ -2378,12 +2636,14 @@ export const approvalPolicyServiceFactory = ({{steps,bypassers,+ autoApproval,name,conditions,constraints}: {steps: TApprovalScopeConfiguration["steps"];bypassers?: PolicyBypasser[];+ autoApproval?: TAutoApprovalConfig;name: string;conditions: TApprovalPolicy["conditions"]["conditions"];constraints: TApprovalPolicy["constraints"]["constraints"];@@ -2398,21 +2658,31 @@ export const approvalPolicyServiceFactory = ({const hasApprovers = steps.some((step) => step.approvers.length > 0);if (!hasApprovers) {+ // A request no rule approves still needs someone who can approve it+ if (autoApproval?.rules.length) {+ throw new BadRequestError({ message: "Add at least one approver before adding auto-approval rules" });+ }if (existing) await deleteById(existing.id, actor, policyType);return { policyId: existing?.id ?? null };}const policySteps = steps.map((step) => ({ ...step, notifyApprovers: true }));const bypassFields = bypassers ? { bypassers } : {};+ const autoApprovalUpdate = autoApproval ? { autoApproval } : {};if (existing) {- const { policy } = await updateById(existing.id, { steps: policySteps, ...bypassFields }, actor, policyType);+ const { policy } = await updateById(+ existing.id,+ { steps: policySteps, ...bypassFields, ...autoApprovalUpdate },+ actor,+ policyType+ );return { policyId: policy.id };}const { policy } = await create(policyType,- { scope, scopeId, name, conditions, constraints, steps: policySteps, ...bypassFields },+ { scope, scopeId, name, conditions, constraints, steps: policySteps, ...bypassFields, ...autoApprovalUpdate },actor);return { policyId: policy.id };@@ -2466,6 +2736,8 @@ export const approvalPolicyServiceFactory = ({listGrants,getGrantById,revokeGrant,- checkPolicyMatch+ checkPolicyMatch,+ getAutoApprovalCatalog,+ listAutoApprovalOptions};};diff --git a/backend/src/services/approval-policy/approval-policy-types.ts b/backend/src/services/approval-policy/approval-policy-types.tsindex 368185f8b2..b422861e23 100644--- a/backend/src/services/approval-policy/approval-policy-types.ts+++ b/backend/src/services/approval-policy/approval-policy-types.ts@@ -20,6 +20,13 @@ import {ApproverType,EnforcementLevel} from "./approval-policy-enums";+import {+ TAutoApprovalConfig,+ TAutoApprovalEvidence,+ TAutoApprovalInputValue,+ TAutoApprovalOutcome,+ TAutoApprovalPolicyResponse+} from "./auto-approval/auto-approval-types";import {TCertRequestPolicy,TCertRequestPolicyConditions,@@ -89,6 +96,10 @@ export type TBypassAffordances = {bypassReason: string | null;};+export type TAutoApprovalAffordance = {+ autoApproval: TAutoApprovalOutcome | null;+};+export type BreakGlassBypassMetadata = {grantId: string;bypassReason: string;@@ -129,6 +140,7 @@ export interface TCreatePolicyDTO {bypassForMachineIdentities?: boolean;enforcementLevel?: EnforcementLevel;bypassers?: PolicyBypasser[];+ autoApproval?: TAutoApprovalConfig;}export interface TUpdatePolicyDTO {@@ -140,6 +152,7 @@ export interface TUpdatePolicyDTO {bypassForMachineIdentities?: boolean;enforcementLevel?: EnforcementLevel;bypassers?: PolicyBypasser[];+ autoApproval?: TAutoApprovalConfig;}// Request DTOs@@ -153,6 +166,9 @@ export interface TCreateRequestDTO {// Set by a caller that decides the request in the same breath (break-glass), so approvers are not// asked to act on something that is already resolvedskipApproverNotification?: boolean;+ autoApprovalInputs?: TAutoApprovalInputValue[];+ // Break-glass approves the request itself, so its rules are not evaluated+ skipAutoApproval?: boolean;}export interface TCreateRequestFromPolicyDTO {@@ -167,6 +183,7 @@ export interface TCreateRequestFromPolicyDTO {requesterName: string;requesterEmail: string;skipApproverNotification?: boolean;+ autoApprovalEvidence?: TAutoApprovalEvidence | null;tx?: Knex;}@@ -195,6 +212,12 @@ export type TApprovalResource<breakGlass?: { bypassReason: string }) => Promise<{ grantId: string } | void>;postApprovalRoutine?: (request: TApprovalRequest, actor?: TApprovalActor) => Promise<void>;++ // Whether the policy's auto-approval rules may decide this request+ allowsAutoApproval?: (args: {+ projectId: string;+ requestData: TApprovalRequestData | TApprovalPolicyInputs;+ }) => Promise<boolean>;postRejectionRoutine?: (request: TApprovalRequest) => Promise<void>;// Whether a stored grant's attributes or a request's payload is for the thing these inputs name.@@ -320,6 +343,7 @@ export type TApprovalAccessStatus = {export type TApprovalScopeConfiguration = {steps: { requiredApprovals: number; approvers: PolicyBypasser[] }[];bypassers: PolicyBypasser[];+ autoApproval: TAutoApprovalPolicyResponse;};export type TApprovalResourceRegistry = Partial<Record<ApprovalPolicyType, TApprovalResource>>;diff --git a/backend/src/services/approval-policy/approval-request-fns.ts b/backend/src/services/approval-policy/approval-request-fns.tsindex f6a37be48a..61a176671e 100644--- a/backend/src/services/approval-policy/approval-request-fns.ts+++ b/backend/src/services/approval-policy/approval-request-fns.ts@@ -17,6 +17,7 @@ import {TApprovalRequestStepEligibleApproversDALFactory,TApprovalRequestStepsDALFactory} from "./approval-request-dal";+import { TAutoApprovalEvidence } from "./auto-approval/auto-approval-types";import { TCertRequestRequestData } from "./cert-request/cert-request-policy-types";import { TCodeSigningRequestData } from "./code-signing/code-signing-policy-types";@@ -36,6 +37,9 @@ export interface TCreateApprovalRequestWithStepsParams {requesterEmail: string;scopeType?: string | null;scopeId?: string | null;+ autoApprovalEvidence?: TAutoApprovalEvidence | null;+ // Set when a rule approved the request on creation, which completes every step+ autoApprovedAt?: Date | null;}export type TApprovalRequestWithSteps = TApprovalRequests & {@@ -62,22 +66,28 @@ type TInsertApprovalRequestStepsDeps = {};export const insertApprovalRequestSteps = async (- { requestId, policySteps }: { requestId: string; policySteps: ApprovalPolicyStep[] },+ {+ requestId,+ policySteps,+ completedAt+ }: { requestId: string; policySteps: ApprovalPolicyStep[]; completedAt?: Date | null },{ approvalRequestStepsDAL, approvalRequestStepEligibleApproversDAL }: TInsertApprovalRequestStepsDeps,tx: Knex) =>Promise.all(policySteps.map(async (step, i) => {const stepNum = i + 1;+ const pendingStatus = stepNum === 1 ? ApprovalRequestStepStatus.InProgress : ApprovalRequestStepStatus.Pending;const newStep = await approvalRequestStepsDAL.create({requestId,stepNumber: stepNum,name: step.name ?? null,- status: stepNum === 1 ? ApprovalRequestStepStatus.InProgress : ApprovalRequestStepStatus.Pending,+ status: completedAt ? ApprovalRequestStepStatus.Completed : pendingStatus,requiredApprovals: step.requiredApprovals,notifyApprovers: step.notifyApprovers ?? false,- startedAt: stepNum === 1 ? new Date() : null+ startedAt: completedAt ?? (stepNum === 1 ? new Date() : null),+ completedAt: completedAt ?? null},tx);@@ -119,7 +129,9 @@ export const createApprovalRequestWithSteps = async (requesterName,requesterEmail,scopeType,- scopeId+ scopeId,+ autoApprovalEvidence,+ autoApprovedAt}: TCreateApprovalRequestWithStepsParams,dependencies: {approvalRequestDAL: Pick<TApprovalRequestDALFactory, "create" | "transaction">;@@ -146,13 +158,15 @@ export const createApprovalRequestWithSteps = async (requestData: { version: 1, requestData },expiresAt,scopeType: scopeType ?? null,- scopeId: scopeId ?? null+ scopeId: scopeId ?? null,+ autoApprovalEvidence: autoApprovalEvidence ?? null,+ autoApprovedAt: autoApprovedAt ?? null},tx);const newSteps = await insertApprovalRequestSteps(- { requestId: newRequest.id, policySteps },+ { requestId: newRequest.id, policySteps, completedAt: autoApprovedAt },{ approvalRequestStepsDAL, approvalRequestStepEligibleApproversDAL },tx);diff --git a/backend/src/services/approval-policy/auto-approval/auto-approval-dal.ts b/backend/src/services/approval-policy/auto-approval/auto-approval-dal.tsnew file mode 100644index 0000000000..2955e24ffa--- /dev/null+++ b/backend/src/services/approval-policy/auto-approval/auto-approval-dal.ts@@ -0,0 +1,133 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { BadRequestError, DatabaseError } from "@app/lib/errors";+import { ormify } from "@app/lib/knex";++import { AUTO_APPROVAL_REQUESTER_SUBJECT, TAutoApprovalConfig, TStoredAutoApproval } from "./auto-approval-types";++const toValues = (values: unknown) =>+ Array.isArray(values) ? values.filter((value): value is string => typeof value === "string") : [];++export type TApprovalPolicyAutoApprovalDALFactory = ReturnType<typeof approvalPolicyAutoApprovalDALFactory>;++export const approvalPolicyAutoApprovalDALFactory = (db: TDbClient) => {+ const inputsOrm = ormify(db, TableName.ApprovalPolicyAutoApprovalInputs);+ const rulesOrm = ormify(db, TableName.ApprovalPolicyAutoApprovalRules);+ const conditionsOrm = ormify(db, TableName.ApprovalPolicyAutoApprovalConditions);++ const findByPolicyIds = async (policyIds: string[], tx?: Knex): Promise<Map<string, TStoredAutoApproval>> => {+ const byPolicyId = new Map<string, TStoredAutoApproval>();+ if (!policyIds.length) return byPolicyId;++ try {+ const dbInstance = tx || db.replicaNode();++ const inputs = await dbInstance(TableName.ApprovalPolicyAutoApprovalInputs)+ .whereIn("policyId", policyIds)+ .orderBy("position", "asc");+ const rules = await dbInstance(TableName.ApprovalPolicyAutoApprovalRules)+ .whereIn("policyId", policyIds)+ .orderBy("position", "asc");+ const conditions = rules.length+ ? await dbInstance(TableName.ApprovalPolicyAutoApprovalConditions)+ .whereIn(+ "ruleId",+ rules.map((rule) => rule.id)+ )+ .orderBy("position", "asc")+ : [];++ const inputById = new Map(inputs.map((input) => [input.id, input]));+ const getEntry = (policyId: string) => {+ let entry = byPolicyId.get(policyId);+ if (!entry) {+ entry = { inputs: [], rules: [] };+ byPolicyId.set(policyId, entry);+ }+ return entry;+ };++ inputs.forEach((input) => {+ getEntry(input.policyId).inputs.push({+ id: input.id,+ connectionId: input.connectionId,+ subject: input.subject+ });+ });++ rules.forEach((rule) => {+ getEntry(rule.policyId).rules.push({+ id: rule.id,+ name: rule.name,+ conditions: conditions+ .filter((condition) => condition.ruleId === rule.id)+ .map((condition) => {+ const input = condition.inputId ? inputById.get(condition.inputId) : undefined;+ return {+ id: condition.id,+ inputId: condition.inputId ?? null,+ connectionId: input?.connectionId ?? (condition.connectionId as string),+ subject: input?.subject ?? AUTO_APPROVAL_REQUESTER_SUBJECT,+ constraint: condition.constraint,+ values: toValues(condition.values)+ };+ })+ });+ });++ return byPolicyId;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find approval policy auto-approval rules" });+ }+ };++ // Replaces a policy's inputs and rules, the way policy steps are replaced+ const replaceForPolicy = async (policyId: string, config: TAutoApprovalConfig, tx: Knex) => {+ await rulesOrm.delete({ policyId }, tx);+ await inputsOrm.delete({ policyId }, tx);++ const inputs = await inputsOrm.insertMany(+ config.inputs.map((input, position) => ({+ policyId,+ position,+ connectionId: input.connectionId,+ subject: input.subject+ })),+ tx+ );+ const inputIdByKey = new Map(inputs.map((input) => [`${input.connectionId}:${input.subject}`, input.id]));++ const rules = await rulesOrm.insertMany(+ config.rules.map((rule, position) => ({ policyId, position, name: rule.name })),+ tx+ );+ const ruleIdByPosition = new Map(rules.map((rule) => [rule.position, rule.id]));++ const conditionRows = config.rules.flatMap((rule, rulePosition) =>+ rule.conditions.map((condition, position) => {+ const isRequester = condition.subject === AUTO_APPROVAL_REQUESTER_SUBJECT;+ const inputId = isRequester ? null : inputIdByKey.get(`${condition.connectionId}:${condition.subject}`);+ if (!isRequester && !inputId) {+ throw new BadRequestError({+ message: `Rule '${rule.name}' checks '${condition.subject}', which is not in the policy's request information`+ });+ }++ return {+ ruleId: ruleIdByPosition.get(rulePosition) as string,+ position,+ inputId: inputId ?? null,+ connectionId: isRequester ? condition.connectionId : null,+ constraint: condition.constraint,+ values: JSON.stringify(condition.values)+ };+ })+ );++ await conditionsOrm.insertMany(conditionRows, tx);+ };++ return { findByPolicyIds, replaceForPolicy };+};diff --git a/backend/src/services/approval-policy/auto-approval/auto-approval-fns.test.ts b/backend/src/services/approval-policy/auto-approval/auto-approval-fns.test.tsnew file mode 100644index 0000000000..72c32175bc--- /dev/null+++ b/backend/src/services/approval-policy/auto-approval/auto-approval-fns.test.ts@@ -0,0 +1,200 @@+import {+ evaluateAutoApprovalRules,+ getAutoApprovalSummary,+ toAutoApprovalOutcome,+ TResolvedAutoApprovalSubject+} from "./auto-approval-fns";+import {+ AUTO_APPROVAL_REQUESTER_SUBJECT,+ AutoApprovalConstraintValue,+ TAutoApprovalContext,+ TAutoApprovalSubject,+ TStoredAutoApproval+} from "./auto-approval-types";++vi.mock("@app/lib/logger", () => ({ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() } }));++type TFacts = { status: string };++const ticket: TAutoApprovalSubject<unknown, TFacts> = {+ label: "Jira ticket",+ input: { label: "Jira ticket", placeholder: "PAY-123", parse: (value) => value },+ resolve: async () => ({ status: "Approved" }),+ constraints: {+ status: {+ label: "has status",+ value: AutoApprovalConstraintValue.Many,+ test: (facts, values) =>+ values.includes(facts.status) ? { pass: true } : { pass: false, reason: `status is ${facts.status}` }+ },+ broken: {+ label: "is broken",+ value: AutoApprovalConstraintValue.None,+ test: () => {+ throw new Error("boom");+ }+ }+ }+};++const ctx: TAutoApprovalContext = { requester: { userId: "user-id", machineIdentityId: null, email: "[email protected]" } };++const condition = (id: string, constraint: string, values: string[], inputId: string | null = "input-1") => ({+ id,+ inputId,+ connectionId: "connection-1",+ subject: inputId ? "submitted-ticket" : AUTO_APPROVAL_REQUESTER_SUBJECT,+ constraint,+ values+});++const resolved = (status: string, error: string | null = null) =>+ new Map<string, TResolvedAutoApprovalSubject>([+ ["input-1", { label: "Jira ticket", definition: ticket, facts: { status }, error }]+ ]);++describe("evaluateAutoApprovalRules", () => {+ const rules: TStoredAutoApproval["rules"] = [+ { id: "rule-1", name: "Scheduled change", conditions: [condition("c-1", "status", ["Scheduled"])] },+ { id: "rule-2", name: "Approved ticket", conditions: [condition("c-2", "status", ["Approved"])] }+ ];++ test("approves with the first rule whose conditions all pass", () => {+ const result = evaluateAutoApprovalRules(rules, resolved("Approved"), ctx);++ expect(result.approvedByRuleId).toBe("rule-2");+ expect(result.rules.map((rule) => rule.passed)).toEqual([false, true]);+ expect(result.rules[0].conditions[0]).toMatchObject({+ description: "Jira ticket has status Scheduled",+ passed: false,+ reason: "status is Approved"+ });+ });++ test("requires every condition in a rule", () => {+ const result = evaluateAutoApprovalRules(+ [+ {+ id: "rule-1",+ name: "Both",+ conditions: [condition("c-1", "status", ["Approved"]), condition("c-2", "status", ["Done"])]+ }+ ],+ resolved("Approved"),+ ctx+ );++ expect(result.approvedByRuleId).toBeNull();+ });++ test("fails closed when the subject could not be fetched, the check is gone, or the test throws", () => {+ expect(evaluateAutoApprovalRules(rules, resolved("Approved", "Couldn't reach Jira"), ctx)).toMatchObject({+ approvedByRuleId: null,+ rules: [{ conditions: [{ reason: "Couldn't reach Jira" }] }, { conditions: [{ reason: "Couldn't reach Jira" }] }]+ });++ const missing = evaluateAutoApprovalRules(+ [{ id: "rule-1", name: "Gone", conditions: [condition("c-1", "removed", [])] }],+ resolved("Approved"),+ ctx+ );+ expect(missing.rules[0].conditions[0]).toMatchObject({+ passed: false,+ reason: "This check is no longer available"+ });++ const throwing = evaluateAutoApprovalRules(+ [{ id: "rule-1", name: "Broken", conditions: [condition("c-1", "broken", [])] }],+ resolved("Approved"),+ ctx+ );+ expect(throwing.approvedByRuleId).toBeNull();+ });++ test("never approves with a rule that has no conditions", () => {+ expect(+ evaluateAutoApprovalRules([{ id: "rule-1", name: "Empty", conditions: [] }], resolved("Approved"), ctx)+ ).toMatchObject({ approvedByRuleId: null });+ });+});++describe("toAutoApprovalOutcome", () => {+ const evidence = {+ version: 1,+ evaluatedAt: "2026-10-13T00:00:00.000Z",+ approvedByRuleId: "rule-1",+ inputs: [+ {+ inputId: "input-1",+ connectionId: "connection-1",+ subject: "submitted-ticket",+ label: "Jira ticket",+ value: "https://acme.atlassian.net/browse/PAY-123",+ id: "PAY-123",+ url: "https://acme.atlassian.net/browse/PAY-123"+ }+ ],+ subjects: [+ {+ connectionId: "connection-1",+ subject: "submitted-ticket",+ inputId: "input-1",+ facts: { secret: 1 },+ error: null+ }+ ],+ rules: [+ {+ id: "rule-1",+ name: "Approved ticket",+ passed: true,+ conditions: [+ {+ id: "c-1",+ connectionId: "connection-1",+ subject: "submitted-ticket",+ constraint: "status",+ values: ["Approved"],+ description: "Jira ticket has status Approved",+ passed: true,+ reason: null+ }+ ]+ }+ ]+ };++ test("returns results and reasons without the fetched facts", () => {+ const approvedAt = new Date();+ const outcome = toAutoApprovalOutcome({ autoApprovedAt: approvedAt, autoApprovalEvidence: evidence });++ expect(outcome).toEqual({+ approvedAt,+ approvedByRuleId: "rule-1",+ inputs: [{ label: "Jira ticket", value: "PAY-123", url: "https://acme.atlassian.net/browse/PAY-123" }],+ rules: [+ {+ id: "rule-1",+ name: "Approved ticket",+ passed: true,+ conditions: [{ id: "c-1", description: "Jira ticket has status Approved", passed: true, reason: null }]+ }+ ]+ });+ expect(JSON.stringify(outcome)).not.toContain("secret");+ });++ test("is null for a request that was never evaluated", () => {+ expect(toAutoApprovalOutcome({ autoApprovalEvidence: null })).toBeNull();+ expect(toAutoApprovalOutcome({})).toBeNull();+ });++ test("summarizes the approving rule for audit logs", () => {+ expect(getAutoApprovalSummary(evidence)).toEqual({+ ruleId: "rule-1",+ ruleName: "Approved ticket",+ linkedRecords: [{ label: "Jira ticket", value: "PAY-123" }],+ conditions: ["Jira ticket has status Approved"]+ });+ });+});diff --git a/backend/src/services/approval-policy/auto-approval/auto-approval-fns.ts b/backend/src/services/approval-policy/auto-approval/auto-approval-fns.tsnew file mode 100644index 0000000000..7ca179ac6a--- /dev/null+++ b/backend/src/services/approval-policy/auto-approval/auto-approval-fns.ts@@ -0,0 +1,110 @@+import { logger } from "@app/lib/logger";++import {+ AUTO_APPROVAL_REQUESTER_SUBJECT,+ TAutoApprovalContext,+ TAutoApprovalEvidence,+ TAutoApprovalOutcome,+ TAutoApprovalSubject,+ TStoredAutoApproval+} from "./auto-approval-types";++export const getAutoApprovalSubjectKey = (condition: { inputId: string | null; connectionId: string }) =>+ condition.inputId ?? `${AUTO_APPROVAL_REQUESTER_SUBJECT}:${condition.connectionId}`;++export const describeAutoApprovalCondition = (subjectLabel: string, constraintLabel: string, values: string[]) =>+ [subjectLabel, constraintLabel, values.join(" or ")].filter(Boolean).join(" ");++export type TResolvedAutoApprovalSubject = {+ label: string;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ definition: TAutoApprovalSubject<any, any> | null;+ facts: unknown;+ error: string | null;+};++// Every condition in a rule must pass and the first passing rule approves+export const evaluateAutoApprovalRules = (+ rules: TStoredAutoApproval["rules"],+ subjects: Map<string, TResolvedAutoApprovalSubject>,+ ctx: TAutoApprovalContext+): Pick<TAutoApprovalEvidence, "rules" | "approvedByRuleId"> => {+ const evaluated = rules.map((rule) => {+ const conditions = rule.conditions.map((condition) => {+ const subject = subjects.get(getAutoApprovalSubjectKey(condition));+ const constraint = subject?.definition?.constraints[condition.constraint];+ const base = {+ id: condition.id,+ connectionId: condition.connectionId,+ subject: condition.subject,+ constraint: condition.constraint,+ values: condition.values,+ description: describeAutoApprovalCondition(+ subject?.label ?? condition.subject,+ constraint?.label ?? condition.constraint,+ condition.values+ )+ };++ if (!subject || !constraint) return { ...base, passed: false, reason: "This check is no longer available" };+ if (subject.error) return { ...base, passed: false, reason: subject.error };++ try {+ const result = constraint.test(subject.facts, condition.values, ctx);+ return { ...base, passed: result.pass, reason: result.pass ? null : (result.reason ?? "Condition not met") };+ } catch (error) {+ logger.error(error, `Auto-approval condition test failed [conditionId=${condition.id}]`);+ return { ...base, passed: false, reason: "Couldn't evaluate this condition" };+ }+ });++ return {+ id: rule.id,+ name: rule.name,+ passed: conditions.length > 0 && conditions.every((condition) => condition.passed),+ conditions+ };+ });++ return { rules: evaluated, approvedByRuleId: evaluated.find((rule) => rule.passed)?.id ?? null };+};++const isAutoApprovalEvidence = (value: unknown): value is TAutoApprovalEvidence =>+ Boolean(value) &&+ typeof value === "object" &&+ (value as { version?: unknown }).version === 1 &&+ Array.isArray((value as { rules?: unknown }).rules);++// What the API returns about an evaluation: results and reasons+export const toAutoApprovalOutcome = (request: {+ autoApprovedAt?: Date | null;+ autoApprovalEvidence?: unknown;+}): TAutoApprovalOutcome | null => {+ const evidence = request.autoApprovalEvidence;+ if (!isAutoApprovalEvidence(evidence)) return null;++ return {+ approvedAt: request.autoApprovedAt ?? null,+ approvedByRuleId: evidence.approvedByRuleId,+ inputs: (evidence.inputs ?? []).map(({ label, id, url }) => ({ label, value: id, url })),+ rules: evidence.rules.map((rule) => ({+ id: rule.id,+ name: rule.name,+ passed: rule.passed,+ conditions: rule.conditions.map(({ id, description, passed, reason }) => ({ id, description, passed, reason }))+ }))+ };+};++// The approving rule and what it checked, for audit logs and notifications+export const getAutoApprovalSummary = (evidence: unknown) => {+ if (!isAutoApprovalEvidence(evidence)) return null;++ const rule = evidence.rules.find((candidate) => candidate.id === evidence.approvedByRuleId);+ return {+ ruleId: evidence.approvedByRuleId,+ ruleName: rule?.name,+ linkedRecords: (evidence.inputs ?? []).map(({ label, id }) => ({ label, value: id })),+ conditions: (rule?.conditions ?? []).map((condition) => condition.description)+ };+};diff --git a/backend/src/services/approval-policy/auto-approval/auto-approval-providers.ts b/backend/src/services/approval-policy/auto-approval/auto-approval-providers.tsnew file mode 100644index 0000000000..daa8708297--- /dev/null+++ b/backend/src/services/approval-policy/auto-approval/auto-approval-providers.ts@@ -0,0 +1,13 @@+import { AppConnection } from "@app/services/app-connection/app-connection-enums";++import { TAutoApprovalProvider } from "./auto-approval-types";+import { JIRA_AUTO_APPROVAL_PROVIDER } from "./providers/jira-auto-approval-provider";++// eslint-disable-next-line @typescript-eslint/no-explicit-any+export const AUTO_APPROVAL_PROVIDER_REGISTRY: Partial<Record<AppConnection, TAutoApprovalProvider<any>>> = {+ [AppConnection.Jira]: JIRA_AUTO_APPROVAL_PROVIDER+};++export const AUTO_APPROVAL_APPS = Object.keys(AUTO_APPROVAL_PROVIDER_REGISTRY) as AppConnection[];++export const getAutoApprovalProvider = (app: string) => AUTO_APPROVAL_PROVIDER_REGISTRY[app as AppConnection];diff --git a/backend/src/services/approval-policy/auto-approval/auto-approval-schemas.ts b/backend/src/services/approval-policy/auto-approval/auto-approval-schemas.tsnew file mode 100644index 0000000000..2f49f30fd5--- /dev/null+++ b/backend/src/services/approval-policy/auto-approval/auto-approval-schemas.ts@@ -0,0 +1,165 @@+import { z } from "zod";++import { APPROVAL_POLICY_AUTO_APPROVAL as DOCS } from "@app/lib/api-docs";++import { AutoApprovalConstraintValue } from "./auto-approval-types";++const IdentifierSchema = z+ .string()+ .trim()+ .min(1)+ .max(64)+ .regex(/^[a-z0-9-]+$/, "Must contain only lowercase letters, numbers, and hyphens");++const ConditionValueSchema = z.string().trim().min(1, "Values cannot be empty").max(255);++export const AutoApprovalConfigSchema = z+ .object({+ inputs: z+ .object({+ connectionId: z.string().uuid().describe(DOCS.inputConnectionId),+ subject: IdentifierSchema.describe(DOCS.inputSubject)+ })+ .array()+ .max(10, "A policy can ask for at most 10 pieces of request information")+ .describe(DOCS.inputs),+ rules: z+ .object({+ name: z.string().trim().min(1, "Rule name is required").max(128).describe(DOCS.ruleName),+ conditions: z+ .object({+ connectionId: z.string().uuid().describe(DOCS.conditionConnectionId),+ subject: IdentifierSchema.describe(DOCS.conditionSubject),+ constraint: IdentifierSchema.describe(DOCS.constraint),+ values: ConditionValueSchema.array().max(50).describe(DOCS.values)+ })+ .array()+ .min(1, "A rule needs at least one condition, or it would approve every request")+ .max(20, "A rule can have at most 20 conditions")+ .describe(DOCS.conditions)+ })+ .array()+ .max(20, "A policy can have at most 20 auto-approval rules")+ .describe(DOCS.rules)+ })+ .describe(DOCS.autoApproval);++export const AutoApprovalConfigResponseSchema = z.object({+ inputs: z+ .object({+ id: z.string().uuid(),+ connectionId: z.string().uuid(),+ subject: z.string()+ })+ .array(),+ rules: z+ .object({+ id: z.string().uuid(),+ name: z.string(),+ conditions: z+ .object({+ id: z.string().uuid(),+ connectionId: z.string().uuid(),+ subject: z.string(),+ constraint: z.string(),+ values: z.string().array()+ })+ .array()+ })+ .array()+});++export const AutoApprovalInputValuesSchema = z+ .object({+ connectionId: z.string().uuid().describe(DOCS.inputConnectionId),+ subject: IdentifierSchema.describe(DOCS.inputSubject),+ value: z.string().trim().max(2048).describe(DOCS.requestInputValue)+ })+ .array()+ .max(10)+ .describe(DOCS.requestInputs);++export const AutoApprovalOutcomeSchema = z+ .object({+ approvedAt: z.date().nullable(),+ approvedByRuleId: z.string().nullable(),+ inputs: z.object({ label: z.string(), value: z.string(), url: z.string().nullable() }).array(),+ rules: z+ .object({+ id: z.string(),+ name: z.string(),+ passed: z.boolean(),+ conditions: z+ .object({+ id: z.string(),+ description: z.string(),+ passed: z.boolean(),+ reason: z.string().nullable()+ })+ .array()+ })+ .array()+ })+ .nullable()+ .describe(DOCS.outcome);++export const AutoApprovalInputDetailsSchema = z.object({+ connectionId: z.string().uuid(),+ subject: z.string(),+ label: z.string(),+ placeholder: z.string()+});++export const AutoApprovalCatalogSchema = z.object({+ connections: z+ .object({+ id: z.string().uuid(),+ name: z.string(),+ app: z.string(),+ subjects: z+ .object({+ id: z.string(),+ label: z.string(),+ input: z.object({ label: z.string(), placeholder: z.string() }).nullable(),+ constraints: z+ .object({+ id: z.string(),+ label: z.string(),+ value: z.nativeEnum(AutoApprovalConstraintValue),+ hasOptions: z.boolean()+ })+ .array()+ })+ .array()+ })+ .array()+});++const MAX_SIBLINGS_LENGTH = 4096;++export const AutoApprovalSiblingsSchema = z+ .string()+ .max(MAX_SIBLINGS_LENGTH)+ .optional()+ .transform((raw, ctx) => {+ if (!raw) return {} as Record<string, string[]>;++ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "siblings must be a JSON object" });+ return z.NEVER;+ }++ const result = z.record(IdentifierSchema, ConditionValueSchema.array().max(50)).safeParse(parsed);+ if (!result.success) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "siblings must map each constraint to a list of values"+ });+ return z.NEVER;+ }+ return result.data;+ })+ .describe(DOCS.optionsSiblings);diff --git a/backend/src/services/approval-policy/auto-approval/auto-approval-service.ts b/backend/src/services/approval-policy/auto-approval/auto-approval-service.tsnew file mode 100644index 0000000000..b30e7a7767--- /dev/null+++ b/backend/src/services/approval-policy/auto-approval/auto-approval-service.ts@@ -0,0 +1,517 @@+import { ForbiddenError } from "@casl/ability";+import { Knex } from "knex";++import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { BadRequestError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { OrgServiceActor } from "@app/lib/types";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";+import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";+import { APP_CONNECTION_NAME_MAP } from "@app/services/app-connection/app-connection-maps";+import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";+import { TAppConnection } from "@app/services/app-connection/app-connection-types";+import { TApprovalActor } from "@app/services/approval-policy/approval-policy-types";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";++import { TApprovalPolicyAutoApprovalDALFactory } from "./auto-approval-dal";+import {+ evaluateAutoApprovalRules,+ getAutoApprovalSubjectKey,+ TResolvedAutoApprovalSubject+} from "./auto-approval-fns";+import { AUTO_APPROVAL_APPS, getAutoApprovalProvider } from "./auto-approval-providers";+import {+ AUTO_APPROVAL_REQUESTER_SUBJECT,+ AutoApprovalConstraintValue,+ TAutoApprovalConfig,+ TAutoApprovalContext,+ TAutoApprovalEvidence,+ TAutoApprovalInputValue,+ TAutoApprovalPolicyResponse,+ TAutoApprovalProviderDeps,+ TParsedAutoApprovalInput,+ TStoredAutoApproval+} from "./auto-approval-types";++const RESOLVE_TIMEOUT_MS = 20_000;++type TAutoApprovalServiceFactoryDep = {+ approvalPolicyAutoApprovalDAL: TApprovalPolicyAutoApprovalDALFactory;+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "find">;+ appConnectionService: Pick<+ TAppConnectionServiceFactory,+ "validateAppConnectionUsageById" | "listAvailableAppConnectionsForUser"+ >;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;+};++export type TAutoApprovalServiceFactory = ReturnType<typeof autoApprovalServiceFactory>;++const withTimeout = async <T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> => {+ let timer: NodeJS.Timeout | undefined;+ try {+ return await Promise.race([+ promise,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new BadRequestError({ message })), timeoutMs);+ })+ ]);+ } finally {+ clearTimeout(timer);+ }+};++const getAppName = (app: string) => APP_CONNECTION_NAME_MAP[app as keyof typeof APP_CONNECTION_NAME_MAP] ?? app;++export const autoApprovalServiceFactory = ({+ approvalPolicyAutoApprovalDAL,+ appConnectionDAL,+ appConnectionService,+ kmsService,+ gatewayV2Service,+ gatewayPoolService+}: TAutoApprovalServiceFactoryDep) => {+ const providerDeps: TAutoApprovalProviderDeps = { gatewayV2Service, gatewayPoolService };++ const $loadConnection = async ({+ connectionId,+ orgId,+ projectId+ }: {+ connectionId: string;+ orgId: string;+ projectId: string;+ }): Promise<TAppConnection | null> => {+ const raw = await appConnectionDAL.findById(connectionId);+ if (!raw || raw.orgId !== orgId || (raw.projectId && raw.projectId !== projectId)) return null;+ return decryptAppConnection(raw, kmsService);+ };++ const validateConfig = async ({+ projectId,+ config,+ actor+ }: {+ projectId: string;+ config: TAutoApprovalConfig;+ actor: TApprovalActor;+ }): Promise<TAutoApprovalConfig> => {+ const connectionIds = [+ ...new Set([+ ...config.inputs.map((input) => input.connectionId),+ ...config.rules.flatMap((rule) => rule.conditions.map((condition) => condition.connectionId))+ ])+ ];++ const appByConnectionId = new Map<string, { app: string; name: string }>();+ for await (const connectionId of connectionIds) {+ const connection = await appConnectionService.validateAppConnectionUsageById(+ AUTO_APPROVAL_APPS,+ { connectionId, projectId },+ actor as OrgServiceActor+ );+ appByConnectionId.set(connectionId, { app: connection.app, name: connection.name });+ }++ const getSubject = (connectionId: string, subjectId: string) => {+ const connection = appByConnectionId.get(connectionId);+ const subject = connection ? getAutoApprovalProvider(connection.app)?.subjects[subjectId] : undefined;+ return { connection, subject };+ };++ const inputKeys = new Set<string>();+ config.inputs.forEach((input) => {+ const key = `${input.connectionId}:${input.subject}`;+ const { connection, subject } = getSubject(input.connectionId, input.subject);++ if (!subject?.input) {+ throw new BadRequestError({+ message: `${getAppName(connection?.app ?? "")} connection '${connection?.name ?? input.connectionId}' has no '${input.subject}' to ask requesters for`+ });+ }+ if (inputKeys.has(key)) {+ throw new BadRequestError({+ message: `Request information asks for ${subject.input.label} from '${connection?.name}' more than once`+ });+ }+ inputKeys.add(key);+ });++ const rules = config.rules.map((rule) => {+ const name = rule.name.trim();++ const conditions = rule.conditions.map((condition) => {+ const isRequester = condition.subject === AUTO_APPROVAL_REQUESTER_SUBJECT;+ const { connection, subject } = getSubject(condition.connectionId, condition.subject);+ const connectionName = connection?.name ?? condition.connectionId;++ if (!subject || (isRequester ? subject.input !== null : subject.input === null)) {+ throw new BadRequestError({+ message: `Rule '${name}' checks '${condition.subject}', which ${getAppName(connection?.app ?? "")} connection '${connectionName}' does not offer`+ });+ }+ if (!isRequester && !inputKeys.has(`${condition.connectionId}:${condition.subject}`)) {+ throw new BadRequestError({+ message: `Rule '${name}' checks the ${subject.label} from '${connectionName}', so add it to the request information first`+ });+ }++ const constraint = subject.constraints[condition.constraint];+ if (!constraint) {+ throw new BadRequestError({+ message: `Rule '${name}' uses '${condition.constraint}', which is not a check on the ${subject.label}. Use one of: ${Object.keys(+ subject.constraints+ ).join(", ")}`+ });+ }++ const values = [...new Set(condition.values.map((value) => value.trim()).filter(Boolean))];+ const check = `${subject.label} ${constraint.label}`;++ if (constraint.value === AutoApprovalConstraintValue.None && values.length) {+ throw new BadRequestError({ message: `Rule '${name}': '${check}' takes no values` });+ }+ if (constraint.value === AutoApprovalConstraintValue.One && values.length !== 1) {+ throw new BadRequestError({+ message: `Rule '${name}': '${check}' takes exactly one value`+ });+ }+ if (constraint.value === AutoApprovalConstraintValue.Many && values.length === 0) {+ throw new BadRequestError({+ message: `Rule '${name}': '${check}' needs at least one value`+ });+ }++ return { ...condition, values };+ });++ return { name, conditions };+ });++ return { inputs: config.inputs, rules };+ };++ const replaceConfig = (policyId: string, config: TAutoApprovalConfig, tx: Knex) =>+ approvalPolicyAutoApprovalDAL.replaceForPolicy(policyId, config, tx);++ const findByPolicyIds = (policyIds: string[], tx?: Knex) =>+ approvalPolicyAutoApprovalDAL.findByPolicyIds(policyIds, tx);++ const toPolicyResponse = (stored?: TStoredAutoApproval): TAutoApprovalPolicyResponse => ({+ inputs: (stored?.inputs ?? []).map(({ id, connectionId, subject }) => ({ id, connectionId, subject })),+ rules: (stored?.rules ?? []).map((rule) => ({+ id: rule.id,+ name: rule.name,+ conditions: rule.conditions.map(({ id, connectionId, subject, constraint, values }) => ({+ id,+ connectionId,+ subject,+ constraint,+ values+ }))+ }))+ });++ // The inputs a request form shows for a policy, labelled by the provider+ const getInputDetails = async (stored: TStoredAutoApproval | undefined) => {+ if (!stored?.inputs.length) return [];++ const connections = await appConnectionDAL.find({ $in: { id: stored.inputs.map((input) => input.connectionId) } });+ const appById = new Map(connections.map((connection) => [connection.id, connection.app]));++ return stored.inputs.flatMap((input) => {+ const app = appById.get(input.connectionId);+ const definition = app ? getAutoApprovalProvider(app)?.subjects[input.subject]?.input : undefined;+ if (!definition) return [];+ return [+ {+ connectionId: input.connectionId,+ subject: input.subject,+ label: definition.label,+ placeholder: definition.placeholder+ }+ ];+ });+ };++ // Rejects a malformed value up front with the provider's format message, before anything is created+ const parseInputValues = async ({+ stored,+ values,+ orgId,+ projectId+ }: {+ stored: TStoredAutoApproval | undefined;+ values: TAutoApprovalInputValue[];+ orgId: string;+ projectId: string;+ }): Promise<TParsedAutoApprovalInput[]> => {+ const provided = values.filter((entry) => entry.value.trim());+ if (!provided.length) return [];++ const seen = new Set<string>();+ const parsed: TParsedAutoApprovalInput[] = [];++ for await (const entry of provided) {+ const key = `${entry.connectionId}:${entry.subject}`;+ const input = stored?.inputs.find(+ (candidate) => candidate.connectionId === entry.connectionId && candidate.subject === entry.subject+ );+ if (!input) {+ throw new BadRequestError({+ message: `This approval policy doesn't ask for '${entry.subject}' from connection '${entry.connectionId}'`+ });+ }+ if (seen.has(key)) {+ throw new BadRequestError({+ message: `'${entry.subject}' from connection '${entry.connectionId}' was provided more than once`+ });+ }+ seen.add(key);++ const connection = await $loadConnection({ connectionId: entry.connectionId, orgId, projectId });+ const definition = connection ? getAutoApprovalProvider(connection.app)?.subjects[entry.subject]?.input : null;+ if (!connection || !definition) {+ throw new BadRequestError({+ message:+ "The connection behind this request information is no longer available. Ask an admin to update the approval policy."+ });+ }++ const id = definition.parse(entry.value, connection);+ parsed.push({+ inputId: input.id,+ connectionId: entry.connectionId,+ subject: entry.subject,+ label: definition.label,+ value: entry.value.trim(),+ id,+ url: definition.getUrl?.(id, connection) ?? null+ });+ }++ return parsed;+ };++ // Network calls happen here, so callers must not hold a transaction open around it+ const evaluate = async ({+ stored,+ parsedInputs,+ orgId,+ projectId,+ ctx+ }: {+ stored: TStoredAutoApproval;+ parsedInputs: TParsedAutoApprovalInput[];+ orgId: string;+ projectId: string;+ ctx: TAutoApprovalContext;+ }): Promise<TAutoApprovalEvidence> => {+ const targets = new Map<+ string,+ { connectionId: string; subject: string; inputId: string | null; constraintIds: Set<string> }+ >();+ stored.rules.forEach((rule) =>+ rule.conditions.forEach((condition) => {+ const key = getAutoApprovalSubjectKey(condition);+ const target = targets.get(key) ?? {+ connectionId: condition.connectionId,+ subject: condition.subject,+ inputId: condition.inputId,+ constraintIds: new Set<string>()+ };+ target.constraintIds.add(condition.constraint);+ targets.set(key, target);+ })+ );++ const connections = new Map<string, Promise<TAppConnection | null>>();+ const loadConnection = (connectionId: string) => {+ let connection = connections.get(connectionId);+ if (!connection) {+ connection = $loadConnection({ connectionId, orgId, projectId }).catch((error) => {+ logger.error(error, `Failed to load auto-approval connection [connectionId=${connectionId}]`);+ return null;+ });+ connections.set(connectionId, connection);+ }+ return connection;+ };++ const resolvedEntries = await Promise.all(+ [...targets.entries()].map(+ async ([key, target]): Promise<[string, TResolvedAutoApprovalSubject & typeof target]> => {+ const connection = await loadConnection(target.connectionId);+ const definition = connection+ ? (getAutoApprovalProvider(connection.app)?.subjects[target.subject] ?? null)+ : null;+ const label = definition?.label ?? target.subject;++ if (!connection || !definition) {+ return [+ key,+ {+ ...target,+ label,+ definition,+ facts: null,+ error: "The connection this check uses is no longer available"+ }+ ];+ }++ const parsedInput = target.inputId+ ? parsedInputs.find((input) => input.inputId === target.inputId)+ : undefined;+ if (target.inputId && !parsedInput) {+ return [+ key,+ {+ ...target,+ label,+ definition,+ facts: null,+ error: `No ${definition.input?.label ?? label} was provided`+ }+ ];+ }++ try {+ const facts: unknown = await withTimeout(+ definition.resolve(connection, parsedInput?.id ?? null, ctx, [...target.constraintIds], providerDeps),+ RESOLVE_TIMEOUT_MS,+ `${getAppName(connection.app)} didn't respond in time`+ );+ return [key, { ...target, label, definition, facts, error: null }];+ } catch (error) {+ if (!(error instanceof BadRequestError)) {+ logger.error(error, `Auto-approval subject resolution failed [connectionId=${target.connectionId}]`);+ }+ return [+ key,+ {+ ...target,+ label,+ definition,+ facts: null,+ error: error instanceof BadRequestError ? error.message : `Couldn't reach ${getAppName(connection.app)}`+ }+ ];+ }+ }+ )+ );++ const resolved = new Map(resolvedEntries);+ const { rules, approvedByRuleId } = evaluateAutoApprovalRules(stored.rules, resolved, ctx);++ return {+ version: 1,+ evaluatedAt: new Date().toISOString(),+ approvedByRuleId,+ inputs: parsedInputs,+ subjects: [...resolved.values()].map(({ connectionId, subject, inputId, facts, error }) => ({+ connectionId,+ subject,+ inputId,+ facts,+ error+ })),+ rules+ };+ };++ const getCatalog = async ({ projectId, actor }: { projectId: string; actor: TApprovalActor }) => {+ // Someone who manages a policy without rights to the project's own connections still sees the org's+ const listConnections = async (app: (typeof AUTO_APPROVAL_APPS)[number]) => {+ try {+ return await appConnectionService.listAvailableAppConnectionsForUser(app, actor as OrgServiceActor, projectId);+ } catch (error) {+ if (error instanceof ForbiddenError) {+ return appConnectionService.listAvailableAppConnectionsForUser(app, actor as OrgServiceActor);+ }+ throw error;+ }+ };++ const connectionsByApp = await Promise.all(AUTO_APPROVAL_APPS.map(listConnections));++ return {+ connections: connectionsByApp.flat().flatMap((connection) => {+ const provider = getAutoApprovalProvider(connection.app);+ if (!provider) return [];++ return [+ {+ id: connection.id,+ name: connection.name,+ app: connection.app,+ subjects: Object.entries(provider.subjects).map(([id, subject]) => ({+ id,+ label: subject.label,+ input: subject.input ? { label: subject.input.label, placeholder: subject.input.placeholder } : null,+ constraints: Object.entries(subject.constraints).map(([constraintId, constraint]) => ({+ id: constraintId,+ label: constraint.label,+ value: constraint.value,+ hasOptions: Boolean(constraint.listOptions)+ }))+ }))+ }+ ];+ })+ };+ };++ const listOptions = async ({+ projectId,+ actor,+ connectionId,+ subject: subjectId,+ constraint: constraintId,+ search,+ siblings+ }: {+ projectId: string;+ actor: TApprovalActor;+ connectionId: string;+ subject: string;+ constraint: string;+ search?: string;+ siblings: Record<string, string[]>;+ }) => {+ const connection = await appConnectionService.validateAppConnectionUsageById(+ AUTO_APPROVAL_APPS,+ { connectionId, projectId },+ actor as OrgServiceActor+ );++ const constraint = getAutoApprovalProvider(connection.app)?.subjects[subjectId]?.constraints[constraintId];+ if (!constraint) {+ throw new BadRequestError({+ message: `${getAppName(connection.app)} has no '${constraintId}' check on '${subjectId}'`+ });+ }++ if (!constraint.listOptions) return { options: [] };++ return {+ options: await constraint.listOptions(connection, { search: search?.trim() || undefined, siblings }, providerDeps)+ };+ };++ return {+ validateConfig,+ replaceConfig,+ findByPolicyIds,+ toPolicyResponse,+ getInputDetails,+ parseInputValues,+ evaluate,+ getCatalog,+ listOptions+ };+};diff --git a/backend/src/services/approval-policy/auto-approval/auto-approval-types.ts b/backend/src/services/approval-policy/auto-approval/auto-approval-types.tsnew file mode 100644index 0000000000..f28d1765f7--- /dev/null+++ b/backend/src/services/approval-policy/auto-approval/auto-approval-types.ts@@ -0,0 +1,157 @@+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";++// Conditions on the requester's own account in a service carry this subject and no input+export const AUTO_APPROVAL_REQUESTER_SUBJECT = "requester";++export enum AutoApprovalConstraintValue {+ None = "none",+ One = "one",+ Many = "many"+}++export type TAutoApprovalOption = { value: string; label: string };++export type TAutoApprovalProviderDeps = {+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;+};++export type TAutoApprovalContext = {+ requester: {+ userId: string | null;+ machineIdentityId: string | null;+ // Empty for machine identities, which can never match a person in another service+ email: string | null;+ };+};++export type TAutoApprovalTestResult = { pass: boolean; reason?: string };++export type TAutoApprovalConstraint<TConn, TFacts> = {+ label: string;+ value: AutoApprovalConstraintValue;+ // Picker values, filtered by search and by the values picked in the rule's other conditions+ listOptions?: (+ conn: TConn,+ args: { search?: string; siblings: Record<string, string[]> },+ deps: TAutoApprovalProviderDeps+ ) => Promise<TAutoApprovalOption[]>;+ // Pure; the reason is shown to requesters and approvers+ test: (facts: TFacts, values: string[], ctx: TAutoApprovalContext) => TAutoApprovalTestResult;+};++export type TAutoApprovalSubjectInput<TConn> = {+ label: string;+ placeholder: string;+ // Throws a BadRequestError naming the expected format, or the site the value should point at+ parse: (userInput: string, conn: TConn) => string;+ getUrl?: (id: string, conn: TConn) => string;+};++export type TAutoApprovalSubject<TConn, TFacts> = {+ label: string;+ input: TAutoApprovalSubjectInput<TConn> | null;+ // Fetches the subject once per request, limited to what the constraints in use need. id is null for+ // the requester, who is found through ctx. Throws a BadRequestError whose message is the reason shown.+ resolve: (+ conn: TConn,+ id: string | null,+ ctx: TAutoApprovalContext,+ constraintIds: string[],+ deps: TAutoApprovalProviderDeps+ ) => Promise<TFacts>;+ constraints: Record<string, TAutoApprovalConstraint<TConn, TFacts>>;+};++export type TAutoApprovalProvider<TConn = unknown> = {+ app: AppConnection;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ subjects: Record<string, TAutoApprovalSubject<TConn, any>>;+};++export type TAutoApprovalInputConfig = { connectionId: string; subject: string };++export type TAutoApprovalConditionConfig = {+ connectionId: string;+ subject: string;+ constraint: string;+ values: string[];+};++export type TAutoApprovalRuleConfig = { name: string; conditions: TAutoApprovalConditionConfig[] };++export type TAutoApprovalConfig = {+ inputs: TAutoApprovalInputConfig[];+ rules: TAutoApprovalRuleConfig[];+};++export type TStoredAutoApproval = {+ inputs: (TAutoApprovalInputConfig & { id: string })[];+ rules: {+ id: string;+ name: string;+ conditions: (TAutoApprovalConditionConfig & { id: string; inputId: string | null })[];+ }[];+};++export type TAutoApprovalPolicyResponse = {+ inputs: (TAutoApprovalInputConfig & { id: string })[];+ rules: { id: string; name: string; conditions: (TAutoApprovalConditionConfig & { id: string })[] }[];+};++export type TAutoApprovalInputValue = { connectionId: string; subject: string; value: string };++export type TParsedAutoApprovalInput = {+ inputId: string;+ connectionId: string;+ subject: string;+ label: string;+ value: string;+ id: string;+ url: string | null;+};++// Snapshot taken at evaluation, so a request still reads correctly after the rules change+export type TAutoApprovalEvidence = {+ version: 1;+ evaluatedAt: string;+ approvedByRuleId: string | null;+ inputs: TParsedAutoApprovalInput[];+ subjects: {+ connectionId: string;+ subject: string;+ inputId: string | null;+ // The service's data as fetched; kept for audit and never returned by the API+ facts: unknown;+ error: string | null;+ }[];+ rules: {+ id: string;+ name: string;+ passed: boolean;+ conditions: {+ id: string;+ connectionId: string;+ subject: string;+ constraint: string;+ values: string[];+ description: string;+ passed: boolean;+ reason: string | null;+ }[];+ }[];+};++export type TAutoApprovalOutcome = {+ approvedAt: Date | null;+ approvedByRuleId: string | null;+ inputs: { label: string; value: string; url: string | null }[];+ rules: {+ id: string;+ name: string;+ passed: boolean;+ conditions: { id: string; description: string; passed: boolean; reason: string | null }[];+ }[];+};diff --git a/backend/src/services/approval-policy/auto-approval/providers/jira-auto-approval-provider.test.ts b/backend/src/services/approval-policy/auto-approval/providers/jira-auto-approval-provider.test.tsnew file mode 100644index 0000000000..b3ee9276e7--- /dev/null+++ b/backend/src/services/approval-policy/auto-approval/providers/jira-auto-approval-provider.test.ts@@ -0,0 +1,109 @@+import { BadRequestError } from "@app/lib/errors";++import { TAutoApprovalContext } from "../auto-approval-types";+import {+ JIRA_AUTO_APPROVAL_PROVIDER,+ JIRA_SUBMITTED_TICKET_SUBJECT,+ JiraTicketConstraint,+ parseJiraTicket,+ TJiraTicketFacts+} from "./jira-auto-approval-provider";++const conn = { credentials: { instanceUrl: "https://acme.atlassian.net" } } as Parameters<typeof parseJiraTicket>[1];++const ctx: TAutoApprovalContext = {+ requester: { userId: "user-id", machineIdentityId: null, email: "[email protected]" }+};++const facts = (overrides: Partial<TJiraTicketFacts> = {}): TJiraTicketFacts => ({+ key: "PAY-123",+ status: "Approved",+ projectKey: "PAY",+ issueType: "Change Request",+ labels: ["prod-access"],+ assignee: null,+ approval: null,+ ...overrides+});++const { constraints } = JIRA_AUTO_APPROVAL_PROVIDER.subjects[JIRA_SUBMITTED_TICKET_SUBJECT];+const check = (constraint: JiraTicketConstraint, ticket: TJiraTicketFacts, values: string[] = []) =>+ constraints[constraint].test(ticket, values, ctx);++describe("parseJiraTicket", () => {+ test("accepts a ticket key in any case", () => {+ expect(parseJiraTicket("PAY-123", conn)).toBe("PAY-123");+ expect(parseJiraTicket(" pay-123 ", conn)).toBe("PAY-123");+ expect(parseJiraTicket("OPS_2-9", conn)).toBe("OPS_2-9");+ });++ test("reads the key from links to the ticket on the connection's site", () => {+ expect(parseJiraTicket("https://acme.atlassian.net/browse/PAY-123", conn)).toBe("PAY-123");+ expect(+ parseJiraTicket("https://acme.atlassian.net/jira/software/projects/PAY/boards/1?selectedIssue=PAY-7", conn)+ ).toBe("PAY-7");+ expect(parseJiraTicket("https://acme.atlassian.net/servicedesk/customer/portal/2/PAY-55", conn)).toBe("PAY-55");+ });++ test("rejects links to another Jira site", () => {+ expect(() => parseJiraTicket("https://evil.atlassian.net/browse/PAY-123", conn)).toThrow(BadRequestError);+ expect(() => parseJiraTicket("https://evil.atlassian.net/browse/PAY-123", conn)).toThrow(/acme\.atlassian\.net/);+ });++ test("rejects values that are not a ticket", () => {+ [+ "",+ "PAY",+ "PAY-0",+ "123",+ "P-1",+ "https://acme.atlassian.net/browse/",+ "ftp://acme.atlassian.net/browse/PAY-1"+ ].forEach((value) => expect(() => parseJiraTicket(value, conn)).toThrow(BadRequestError));+ });+});++describe("Jira ticket checks", () => {+ test("status matches any listed status, ignoring case", () => {+ expect(check(JiraTicketConstraint.Status, facts(), ["approved", "Scheduled"]).pass).toBe(true);+ expect(check(JiraTicketConstraint.Status, facts({ status: "In Progress" }), ["Approved", "Scheduled"])).toEqual({+ pass: false,+ reason: "status is In Progress, needs Approved or Scheduled"+ });+ });++ test("project, type, and label checks fail with the value they found", () => {+ expect(check(JiraTicketConstraint.Project, facts({ projectKey: "OPS" }), ["PAY"]).reason).toBe(+ "project is OPS, needs PAY"+ );+ expect(check(JiraTicketConstraint.Type, facts({ issueType: null }), ["Incident"]).reason).toBe(+ "type is not set, needs Incident"+ );+ expect(check(JiraTicketConstraint.Label, facts({ labels: [] }), ["oncall"]).reason).toBe(+ "has no labels, needs oncall"+ );+ expect(check(JiraTicketConstraint.Label, facts({ labels: ["incident"] }), ["oncall"]).reason).toBe(+ "labels are incident, needs oncall"+ );+ expect(check(JiraTicketConstraint.Label, facts({ labels: ["incident", "OnCall"] }), ["oncall"]).pass).toBe(true);+ });++ test("assignee and approval checks fail closed when they were not fetched", () => {+ expect(check(JiraTicketConstraint.AssignedToRequester, facts()).pass).toBe(false);+ expect(check(JiraTicketConstraint.Approved, facts()).pass).toBe(false);+ });++ test("assignee and approval checks pass only on a positive match", () => {+ expect(+ check(JiraTicketConstraint.AssignedToRequester, facts({ assignee: { matchesRequester: true, reason: null } }))+ .pass+ ).toBe(true);+ expect(+ check(+ JiraTicketConstraint.AssignedToRequester,+ facts({ assignee: { matchesRequester: false, reason: "PAY-123 is unassigned" } })+ ).reason+ ).toBe("PAY-123 is unassigned");+ expect(check(JiraTicketConstraint.Approved, facts({ approval: { approved: true, reason: null } })).pass).toBe(true);+ });+});diff --git a/backend/src/services/approval-policy/auto-approval/providers/jira-auto-approval-provider.ts b/backend/src/services/approval-policy/auto-approval/providers/jira-auto-approval-provider.tsnew file mode 100644index 0000000000..7e402a0b23--- /dev/null+++ b/backend/src/services/approval-policy/auto-approval/providers/jira-auto-approval-provider.ts@@ -0,0 +1,326 @@+import { BadRequestError } from "@app/lib/errors";+import { removeTrailingSlash } from "@app/lib/fn";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import {+ findJiraUsersByEmail,+ getJiraErrorMessage,+ getJiraIssue,+ isJiraCloud,+ isJiraNotFoundError,+ listJiraIssueApprovals,+ listJiraIssueTypes,+ listJiraProjects,+ listJiraStatuses,+ searchJiraLabels,+ TJiraConnection,+ TJiraIssue,+ TJiraUser+} from "@app/services/app-connection/jira";++import {+ AutoApprovalConstraintValue,+ TAutoApprovalContext,+ TAutoApprovalOption,+ TAutoApprovalProvider,+ TAutoApprovalProviderDeps,+ TAutoApprovalTestResult+} from "../auto-approval-types";++export const JIRA_SUBMITTED_TICKET_SUBJECT = "submitted-ticket";++export enum JiraTicketConstraint {+ AssignedToRequester = "assigned-to-requester",+ Approved = "approved",+ Status = "status",+ Project = "project",+ Type = "type",+ Label = "label"+}++export type TJiraTicketFacts = {+ key: string;+ status: string | null;+ projectKey: string | null;+ issueType: string | null;+ labels: string[];+ // Only fetched when a condition in use needs them+ assignee: { matchesRequester: boolean; reason: string | null } | null;+ approval: { approved: boolean; reason: string | null } | null;+};++const JIRA_TICKET_FIELDS = ["status", "project", "issuetype", "labels", "assignee"];+const JIRA_ISSUE_KEY_REGEX = /^[A-Z][A-Z0-9_]+-[1-9][0-9]*$/;+const MAX_TICKET_INPUT_LENGTH = 2048;+const MAX_STORED_LABELS = 100;+const MAX_OPTIONS = 100;+const MAX_SIBLING_PROJECTS = 5;++const TICKET_FORMAT_MESSAGE = "Enter a Jira ticket key like PAY-123, or a link to the ticket";++const anyOf = (values: string[]) => values.join(" or ");++const includesIgnoreCase = (values: string[], value: string | null) =>+ value !== null && values.some((candidate) => candidate.toLowerCase() === value.toLowerCase());++const matchesSearch = (search: string | undefined, ...values: string[]) =>+ !search || values.some((value) => value.toLowerCase().includes(search.toLowerCase()));++const toNameOptions = (names: { name: string }[], search?: string): TAutoApprovalOption[] =>+ names+ .filter(({ name }) => matchesSearch(search, name))+ .slice(0, MAX_OPTIONS)+ .map(({ name }) => ({ value: name, label: name }));++const withOptionsError = async <T>(what: string, fetch: () => Promise<T>) => {+ try {+ return await fetch();+ } catch (error) {+ throw new BadRequestError({ message: `Couldn't load ${what} from Jira: ${getJiraErrorMessage(error)}` });+ }+};++export const parseJiraTicket = (userInput: string, conn: Pick<TJiraConnection, "credentials">) => {+ const trimmed = userInput.trim();+ if (!trimmed || trimmed.length > MAX_TICKET_INPUT_LENGTH) {+ throw new BadRequestError({ message: TICKET_FORMAT_MESSAGE });+ }++ if (JIRA_ISSUE_KEY_REGEX.test(trimmed.toUpperCase())) return trimmed.toUpperCase();++ let url: URL;+ try {+ url = new URL(trimmed);+ } catch {+ throw new BadRequestError({ message: TICKET_FORMAT_MESSAGE });+ }++ if (!["http:", "https:"].includes(url.protocol)) {+ throw new BadRequestError({ message: TICKET_FORMAT_MESSAGE });+ }++ const site = new URL(conn.credentials.instanceUrl);+ if (url.host.toLowerCase() !== site.host.toLowerCase()) {+ throw new BadRequestError({+ message: `That link is for ${url.host}, but this Jira connection is for ${site.host}. Link a ticket on ${site.host}.`+ });+ }++ const segments = url.pathname+ .split("/")+ .reverse()+ .map((segment) => {+ try {+ return decodeURIComponent(segment);+ } catch {+ return segment;+ }+ });++ const key = [url.searchParams.get("selectedIssue"), ...segments]+ .map((candidate) => candidate?.toUpperCase())+ .find((candidate): candidate is string => Boolean(candidate && JIRA_ISSUE_KEY_REGEX.test(candidate)));++ if (!key) {+ throw new BadRequestError({ message: `That link doesn't point to a Jira ticket. ${TICKET_FORMAT_MESSAGE}.` });+ }++ return key;+};++const isSameJiraUser = (conn: TJiraConnection, a: TJiraUser, b: TJiraUser) => {+ if (isJiraCloud(conn)) return Boolean(a.accountId) && a.accountId === b.accountId;+ return (Boolean(a.key) && a.key === b.key) || (Boolean(a.name) && a.name === b.name);+};++const matchAssigneeToRequester = async (+ conn: TJiraConnection,+ issue: TJiraIssue,+ ctx: TAutoApprovalContext,+ deps: TAutoApprovalProviderDeps+): Promise<NonNullable<TJiraTicketFacts["assignee"]>> => {+ const { key } = issue;+ const email = ctx.requester.email?.trim().toLowerCase();+ const assignee = issue.fields?.assignee;++ if (!email)+ return { matchesRequester: false, reason: "Requests from machine identities can't match a Jira assignee" };+ if (!assignee) return { matchesRequester: false, reason: `${key} is unassigned` };++ if (assignee.emailAddress) {+ return assignee.emailAddress.toLowerCase() === email+ ? { matchesRequester: true, reason: null }+ : { matchesRequester: false, reason: `${key} is assigned to someone else` };+ }++ // Jira hides this assignee's email, so find the requester's own Jira account by email instead+ try {+ const users = (await findJiraUsersByEmail(conn, email, deps)).filter((user) => user.active !== false);+ const exactMatches = users.filter((user) => user.emailAddress?.toLowerCase() === email);+ // A user search matches email prefixes, so a hidden email only counts when it is the only candidate+ const candidates = exactMatches.length ? exactMatches : users.filter((user) => !user.emailAddress);++ if (candidates.length === 0) {+ return { matchesRequester: false, reason: "No Jira user has the requester's email address" };+ }+ if (candidates.length > 1) {+ return { matchesRequester: false, reason: "The requester's email address matches more than one Jira user" };+ }++ return isSameJiraUser(conn, candidates[0], assignee)+ ? { matchesRequester: true, reason: null }+ : { matchesRequester: false, reason: `${key} is assigned to someone else` };+ } catch (error) {+ return {+ matchesRequester: false,+ reason: `Couldn't look up the requester in Jira: ${getJiraErrorMessage(error)}`+ };+ }+};++const readLatestApproval = async (+ conn: TJiraConnection,+ key: string,+ deps: TAutoApprovalProviderDeps+): Promise<NonNullable<TJiraTicketFacts["approval"]>> => {+ try {+ const approvals = await listJiraIssueApprovals(conn, key, deps);+ if (!approvals.length) return { approved: false, reason: `${key} has no Jira approvals` };++ const sorted = [...approvals].sort((a, b) => (a.createdDate?.epochMillis ?? 0) - (b.createdDate?.epochMillis ?? 0));+ const latest = sorted[sorted.length - 1];++ if (latest.finalDecision === "approved") return { approved: true, reason: null };++ return {+ approved: false,+ reason:+ latest.finalDecision === "declined"+ ? `The latest Jira approval on ${key} was declined`+ : `The latest Jira approval on ${key} is still pending`+ };+ } catch (error) {+ if (isJiraNotFoundError(error)) {+ return { approved: false, reason: `${key} isn't a Jira Service Management request, so it has no approvals` };+ }+ return { approved: false, reason: `Couldn't read Jira approvals on ${key}: ${getJiraErrorMessage(error)}` };+ }+};++const testValue = (actual: string | null, values: string[], noun: string): TAutoApprovalTestResult =>+ includesIgnoreCase(values, actual)+ ? { pass: true }+ : { pass: false, reason: `${noun} is ${actual ?? "not set"}, needs ${anyOf(values)}` };++export const JIRA_AUTO_APPROVAL_PROVIDER: TAutoApprovalProvider<TJiraConnection> = {+ app: AppConnection.Jira,+ subjects: {+ [JIRA_SUBMITTED_TICKET_SUBJECT]: {+ label: "Jira ticket",+ input: {+ label: "Jira ticket",+ placeholder: "PAY-123 or a link to the ticket",+ parse: parseJiraTicket,+ getUrl: (id, conn) => `${removeTrailingSlash(conn.credentials.instanceUrl)}/browse/${encodeURIComponent(id)}`+ },+ resolve: async (conn, id, ctx, constraintIds, deps): Promise<TJiraTicketFacts> => {+ if (!id) throw new BadRequestError({ message: "No Jira ticket was provided" });++ let issue: TJiraIssue;+ try {+ issue = await getJiraIssue(conn, id, JIRA_TICKET_FIELDS, deps);+ } catch (error) {+ if (isJiraNotFoundError(error)) {+ throw new BadRequestError({+ message: `Jira ticket ${id} doesn't exist, or the Jira connection can't see it`+ });+ }+ throw new BadRequestError({ message: `Couldn't read Jira ticket ${id}: ${getJiraErrorMessage(error)}` });+ }++ const key = issue.key || id;+ const [assignee, approval] = await Promise.all([+ constraintIds.includes(JiraTicketConstraint.AssignedToRequester)+ ? matchAssigneeToRequester(conn, { ...issue, key }, ctx, deps)+ : null,+ constraintIds.includes(JiraTicketConstraint.Approved) ? readLatestApproval(conn, key, deps) : null+ ]);++ return {+ key,+ status: issue.fields?.status?.name ?? null,+ projectKey: issue.fields?.project?.key ?? null,+ issueType: issue.fields?.issuetype?.name ?? null,+ labels: (issue.fields?.labels ?? []).slice(0, MAX_STORED_LABELS),+ assignee,+ approval+ };+ },+ constraints: {+ [JiraTicketConstraint.AssignedToRequester]: {+ label: "is assigned to the requester",+ value: AutoApprovalConstraintValue.None,+ test: (facts: TJiraTicketFacts) =>+ facts.assignee?.matchesRequester+ ? { pass: true }+ : { pass: false, reason: facts.assignee?.reason ?? "Couldn't check the ticket's assignee" }+ },+ [JiraTicketConstraint.Approved]: {+ label: "is approved in Jira",+ value: AutoApprovalConstraintValue.None,+ test: (facts: TJiraTicketFacts) =>+ facts.approval?.approved+ ? { pass: true }+ : { pass: false, reason: facts.approval?.reason ?? "Couldn't check the ticket's Jira approvals" }+ },+ [JiraTicketConstraint.Status]: {+ label: "has status",+ value: AutoApprovalConstraintValue.Many,+ listOptions: async (conn, { search, siblings }, deps) => {+ const projectKeys = (siblings[JiraTicketConstraint.Project] ?? []).slice(0, MAX_SIBLING_PROJECTS);+ const statuses = await withOptionsError("statuses", () => listJiraStatuses(conn, { projectKeys }, deps));+ return toNameOptions(statuses, search);+ },+ test: (facts: TJiraTicketFacts, values) => testValue(facts.status, values, "status")+ },+ [JiraTicketConstraint.Project]: {+ label: "is in project",+ value: AutoApprovalConstraintValue.Many,+ listOptions: async (conn, { search }, deps) => {+ const projects = await withOptionsError("projects", () => listJiraProjects(conn, { search }, deps));+ return projects.slice(0, MAX_OPTIONS).map(({ key, name }) => ({ value: key, label: `${name} (${key})` }));+ },+ test: (facts: TJiraTicketFacts, values) => testValue(facts.projectKey, values, "project")+ },+ [JiraTicketConstraint.Type]: {+ label: "is of type",+ value: AutoApprovalConstraintValue.Many,+ listOptions: async (conn, { search, siblings }, deps) => {+ const projectKeys = (siblings[JiraTicketConstraint.Project] ?? []).slice(0, MAX_SIBLING_PROJECTS);+ const issueTypes = await withOptionsError("issue types", () =>+ listJiraIssueTypes(conn, { projectKeys }, deps)+ );+ return toNameOptions(issueTypes, search);+ },+ test: (facts: TJiraTicketFacts, values) => testValue(facts.issueType, values, "type")+ },+ [JiraTicketConstraint.Label]: {+ label: "has label",+ value: AutoApprovalConstraintValue.Many,+ listOptions: async (conn, { search }, deps) => {+ const labels = await withOptionsError("labels", () => searchJiraLabels(conn, { search }, deps));+ return labels.slice(0, MAX_OPTIONS).map((label) => ({ value: label, label }));+ },+ test: (facts: TJiraTicketFacts, values) => {+ if (facts.labels.some((label) => includesIgnoreCase(values, label))) return { pass: true };+ return {+ pass: false,+ reason: facts.labels.length+ ? `labels are ${facts.labels.slice(0, 5).join(", ")}, needs ${anyOf(values)}`+ : `has no labels, needs ${anyOf(values)}`+ };+ }+ }+ }+ }+ }+};diff --git a/backend/src/services/smtp/emails/AccessPamRequestAutoApprovedTemplate.tsx b/backend/src/services/smtp/emails/AccessPamRequestAutoApprovedTemplate.tsxnew file mode 100644index 0000000000..55da741936--- /dev/null+++ b/backend/src/services/smtp/emails/AccessPamRequestAutoApprovedTemplate.tsx@@ -0,0 +1,76 @@+import { Heading, Section, Text } from "@react-email/components";+import React from "react";++import { BaseButton } from "./BaseButton";+import { BaseEmailWrapper, BaseEmailWrapperProps } from "./BaseEmailWrapper";+import { BaseLink } from "./BaseLink";++interface AccessPamRequestAutoApprovedTemplateProps+ extends Omit<BaseEmailWrapperProps, "title" | "preview" | "children"> {+ requesterFullName: string;+ requesterEmail: string;+ folderName?: string;+ accountName: string;+ accessDuration: string;+ accessTypeLabel: string;+ ruleName: string;+ linkedRecords?: string;+ requestUrl: string;+}++export const AccessPamRequestAutoApprovedTemplate = ({+ siteUrl,+ requesterFullName,+ requesterEmail,+ folderName,+ accountName,+ accessDuration,+ accessTypeLabel,+ ruleName,+ linkedRecords,+ requestUrl+}: AccessPamRequestAutoApprovedTemplateProps) => {+ const target = [folderName, accountName].filter(Boolean).join(" / ");++ return (+ <BaseEmailWrapper+ title="PAM Access Auto-Approved"+ preview="A PAM access request was approved by an auto-approval rule."+ siteUrl={siteUrl}+ >+ <Heading className="text-black text-[18px] leading-[28px] text-center font-normal p-0 mx-0">+ A PAM access request was auto-approved in <strong>Privileged Access Manager</strong>+ </Heading>+ <Section className="px-[24px] mb-[28px] mt-[36px] pt-[12px] pb-[8px] border border-solid border-gray-200 rounded-md bg-gray-50">+ <Text className="text-black text-[14px] leading-[24px]">+ <strong>{requesterFullName}</strong> (<BaseLink href={`mailto:${requesterEmail}`}>{requesterEmail}</BaseLink>)+ was granted {accessTypeLabel} to <strong>{target}</strong> for <strong>{accessDuration}</strong> by the+ auto-approval rule <strong>{ruleName}</strong>.+ </Text>+ {linkedRecords && (+ <Text className="text-[14px] text-slate-700 leading-[24px]">+ <strong className="text-black">Linked records:</strong> {linkedRecords}+ </Text>+ )}+ </Section>+ <Section className="text-center">+ <BaseButton href={requestUrl}>View Request</BaseButton>+ </Section>+ </BaseEmailWrapper>+ );+};++export default AccessPamRequestAutoApprovedTemplate;++AccessPamRequestAutoApprovedTemplate.PreviewProps = {+ requesterFullName: "Dan Cooper",+ requesterEmail: "[email protected]",+ folderName: "payments",+ accountName: "postgres",+ accessDuration: "1h",+ accessTypeLabel: "access",+ ruleName: "Approved change ticket",+ linkedRecords: "Jira ticket PAY-123",+ requestUrl: "https://infisical.com",+ siteUrl: "https://infisical.com"+} as AccessPamRequestAutoApprovedTemplateProps;diff --git a/backend/src/services/smtp/emails/index.ts b/backend/src/services/smtp/emails/index.tsindex 8f87155eab..3b5960bde5 100644--- a/backend/src/services/smtp/emails/index.ts+++ b/backend/src/services/smtp/emails/index.ts@@ -1,5 +1,6 @@export * from "./AccessApprovalRequestTemplate";export * from "./AccessApprovalRequestUpdatedTemplate";+export * from "./AccessPamRequestAutoApprovedTemplate";export * from "./AccessPamRequestBypassedTemplate";export * from "./AccessPamRequestTemplate";export * from "./AccountDeletionConfirmationTemplate";diff --git a/backend/src/services/smtp/smtp-service.ts b/backend/src/services/smtp/smtp-service.tsindex 422c38d24e..d2ba30c1ac 100644--- a/backend/src/services/smtp/smtp-service.ts+++ b/backend/src/services/smtp/smtp-service.ts@@ -10,6 +10,7 @@ import { logger } from "@app/lib/logger";import {AccessApprovalRequestTemplate,AccessApprovalRequestUpdatedTemplate,+ AccessPamRequestAutoApprovedTemplate,AccessPamRequestBypassedTemplate,AccessPamRequestTemplate,AccountDeletionConfirmationTemplate,@@ -92,6 +93,7 @@ export enum SmtpTemplates {AccessApprovalRequestUpdated = "accessApprovalRequestUpdated",AccessSecretRequestBypassed = "accessSecretRequestBypassed",AccessPamRequestBypassed = "accessPamRequestBypassed",+ AccessPamRequestAutoApproved = "accessPamRequestAutoApproved",AccessPamRequest = "accessPamRequest",PkiApprovalRequestNeedsReview = "pkiApprovalRequestNeedsReview",SecretApprovalRequestNeedsReview = "secretApprovalRequestNeedsReview",@@ -167,6 +169,7 @@ const EmailTemplateMap: Record<SmtpTemplates, React.FC<any>> = {[SmtpTemplates.ExternalImportSuccessful]: ExternalImportSucceededTemplate,[SmtpTemplates.AccessSecretRequestBypassed]: SecretApprovalRequestBypassedTemplate,[SmtpTemplates.AccessPamRequestBypassed]: AccessPamRequestBypassedTemplate,+ [SmtpTemplates.AccessPamRequestAutoApproved]: AccessPamRequestAutoApprovedTemplate,[SmtpTemplates.AccessPamRequest]: AccessPamRequestTemplate,[SmtpTemplates.PkiApprovalRequestNeedsReview]: PkiApprovalRequestNeedsReviewTemplate,[SmtpTemplates.IntegrationSyncFailed]: IntegrationSyncFailedTemplate,diff --git a/docs/docs.json b/docs/docs.jsonindex d1c7f615a3..fe99a69d2e 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -685,7 +685,13 @@"documentation/platform/pam/accounts/windows-ad"]},- "documentation/platform/pam/access-requests/overview",+ {+ "group": "Access requests",+ "pages": [+ "documentation/platform/pam/access-requests/overview",+ "documentation/platform/pam/access-requests/auto-approval"+ ]+ },"documentation/platform/pam/ai-agents/overview",{"group": "Credential rotation",diff --git a/docs/documentation/platform/pam/access-requests/auto-approval.mdx b/docs/documentation/platform/pam/access-requests/auto-approval.mdxnew file mode 100644index 0000000000..f7c6302cdd--- /dev/null+++ b/docs/documentation/platform/pam/access-requests/auto-approval.mdx@@ -0,0 +1,132 @@+---+title: "Auto-approval"+sidebarTitle: "Auto-approval"+description: "Approve PAM access requests as soon as they're submitted when the records that requesters link from other services pass the folder's rules."+---++Auto-approval approves an [access request](/documentation/platform/pam/access-requests/overview) as soon as it's submitted, if the request passes one of the folder's rules. A rule checks a record that the requester links from another service, such as a Jira ticket. For example, a rule can require that the linked Jira ticket is assigned to the requester and approved in Jira. If no rule passes, the request waits for the folder's approvers, as it would without auto-approval.++Auto-approval has two settings, each managed by a different role:++- A [Product Admin](/documentation/platform/pam/concepts/access-control#product-membership) turns on **Allow Auto-Approval** in an account [template](/documentation/platform/pam/templates/overview), so the accounts that use the template can be auto-approved+- A [Folder Admin](/documentation/platform/pam/concepts/access-control#folder-and-account-memberships) adds rules on the folder's **Approvals** tab to set the conditions a request has to meet++## Supported services++Infisical reads linked records through an [app connection](/integrations/app-connections/overview) to their service:++| Service | Record that requesters link | App connection |+| --- | --- | --- |+| Jira Cloud and Jira Data Center | Jira ticket | [Jira connection](/integrations/app-connections/jira) |++## Prerequisites++- Accounts that [require approval](/documentation/platform/pam/access-requests/overview#setting-up-an-access-gate), in a folder with at least one approver (a request that no rule approves still needs someone to approve it)+- An app connection to a [supported service](#supported-services), whose user can read the records that requesters will link++## Turn on auto-approval in a template++To let a template's accounts be auto-approved:++<Steps>+ <Step>+ In Privileged Access Management, select **Account Templates** in the sidebar, then open the template.+ </Step>+ <Step>+ On the **General** tab, turn on **Allow Auto-Approval**. The policy only appears while **Require Approval** is on.+ </Step>+ <Step>+ Select **Save Changes**.+ </Step>+</Steps>++If an account's template doesn't allow auto-approval, the folder's rules don't apply to the account: its request form doesn't ask for any records, and its requests wait for an approver.++## Add rules to a folder++The **Auto-Approval** card on the folder's **Approvals** tab has two parts:++- **Request Information**: the records that requesters can link when they request access, such as a Jira ticket (each one you add puts an optional field on the request form)+- **Rules**: the conditions a request has to meet to be approved without an approver++A request is approved if every condition in at least one rule passes.++To add rules:++<Steps>+ <Step>+ On the **Accounts** page, select the folder's three dot menu, select **Configure**, then open the **Approvals** tab.+ </Step>+ <Step>+ In the **Auto-Approval** card, under **Request Information**, select **Add Field** and choose the record to ask for, such as **Jira ticket** for your Jira connection.+ </Step>+ <Step>+ Under **Rules**, select **Add Rule**, then replace the rule's default name with one that describes what the rule checks, such as `Approved change ticket`. Approvers see this name on every request the rule approves.+ </Step>+ <Step>+ Select **Add Condition** and choose a [check](#checks), such as **Jira ticket has status**, then choose its values if it takes any.+ </Step>+ <Step>+ Repeat the previous step for each check the rule needs, then select **Save Changes**.+ </Step>+</Steps>++## Checks++Each condition runs one check on a linked record, and the checks available depend on the record's service. If a check takes values, the record passes when it matches any of them.++<Warning>+ If a record has an **is assigned to the requester** check, add that check to every rule that checks the record. Without it, a requester can link a record that belongs to someone else and still pass the rule.+</Warning>++### Jira ticket++| Check | Passes when |+| --- | --- |+| **is assigned to the requester** | The ticket's assignee has the same email address in Jira as the requester has in Infisical (a request from a [machine identity](/documentation/platform/identities/machine-identities) never passes, because a machine identity has no email address) |+| **is approved in Jira** | The ticket is a Jira Service Management request, and its latest approval was approved |+| **has status** | The ticket's status is one of the values |+| **is in project** | The ticket is in one of the projects |+| **is of type** | The ticket's type is one of the values |+| **has label** | The ticket has at least one of the labels |++To require sign-off in Jira, use **is approved in Jira** rather than **has status**. Only the approvers on a Jira Service Management request can decide its approval, while the requester might be able to change the ticket's status.++## Request access with a linked record++If an account's template allows auto-approval and its folder has rules, the account's [request form](/documentation/platform/pam/access-requests/overview#filing-a-request) has an optional field for each record the folder asks for, such as **Jira ticket**. Enter the record's ID, such as the ticket key `PAY-123`, or a link to the record. If the link points to a different site from the one the folder's connection uses, Infisical shows an error and doesn't submit the request.++After you submit the request, the confirmation message shows whether a rule approved it:++- If a rule approved it, the access you asked for starts right away+- If no rule approved it, the request waits for an approver, and the message shows why the rule that came closest didn't pass++If you turn on **Break glass** in the form, the record fields disappear, because [break-glass](/documentation/platform/pam/access-requests/overview#break-glass-access) requests skip the rules.++## Review auto-approval results++The outcome of the rules shows up in these places:++- **Approval Requests**: the **Auto-approval status** section of each request shows the rule that approved it and the linked records, or, if no rule passed, why each rule failed (select a rule to see all of its conditions)+- Notifications: approvers get an email and an in-app notification when a rule approves a request+- The folder's **Approvals** tab: under **Access Requests**, auto-approved requests have the **Auto-approved** status, and a Folder Admin can revoke the access from an auto-approved request, as with any other approved request+- The [audit log](/documentation/platform/pam/auditing): each auto-approval adds a **PAM Access Request Auto-Approved** event with the rule, its conditions, the linked records, the account, and the folder++## How Infisical checks the rules++Infisical checks the rules once, when the request is submitted, by reading each linked record from its service at that moment:++- Later changes in the service don't affect the result, so closing a ticket doesn't revoke access that a rule granted, and a pending request isn't approved when its record passes later+- If no record was linked, or Infisical can't read the record (the service doesn't respond or rejects the connection's credentials, the record doesn't exist, or the connection's user can't see it), every condition on that record fails+- A record can be linked to any number of requests, and each request passes as long as the record still passes the rule++## Next steps++<CardGroup cols={2}>+ <Card title="Access requests" icon="key" href="/documentation/platform/pam/access-requests/overview">+ Gate accounts behind approval and seat the folder's approvers.+ </Card>+ <Card title="App connections" icon="plug" href="/integrations/app-connections/overview">+ Connect Infisical to the services that auto-approval reads records from.+ </Card>+</CardGroup>diff --git a/docs/documentation/platform/pam/access-requests/overview.mdx b/docs/documentation/platform/pam/access-requests/overview.mdxindex e4ee0a427d..a5375c78d3 100644--- a/docs/documentation/platform/pam/access-requests/overview.mdx+++ b/docs/documentation/platform/pam/access-requests/overview.mdx@@ -1,6 +1,6 @@---title: "Access requests"-sidebarTitle: "Access requests"+sidebarTitle: "Overview"description: "Require approval before a member can use a sensitive account."---@@ -72,7 +72,7 @@ graph TDFrom the **Accounts** page, a member sees every account they can reach. Gated accounts show a **key icon** instead of the rocket (launch) button — select the key or select **Request Access** from the menu to start a request.-To request, the member provides a **reason** and a **duration**, both fixed at submission. The account then shows **Pending Approval** until it clears.+To request, the member provides a **reason** and a **duration**, both fixed at submission. If the account can be [auto-approved](/documentation/platform/pam/access-requests/auto-approval), the form also has optional fields for linking records, such as a Jira ticket, and a request whose records pass one of the folder's rules is approved as soon as it's submitted. Otherwise, the account shows **Pending Approval** until it clears.Once approved, the key icon switches to the rocket icon and the member can launch sessions until the grant expires.@@ -89,7 +89,7 @@ Every request carries the reason and duration set by the requester and moves thr| State | What it means ||-------|---------------|| **Pending Approval** | Filed and waiting on an approver. |-| **Approved** | An approver signed off. The access it asked for is now active and the member can launch sessions. |+| **Approved** | An approver or an [auto-approval rule](/documentation/platform/pam/access-requests/auto-approval) approved the request. The access it asked for is now active and the member can launch sessions. || **Expired** | The requested duration ran out and the access closed on its own. || **Rejected** | An approver declined the request. No access was granted. || **Revoked** | Active access was ended early by a Folder Admin before its duration ran out. |diff --git a/docs/documentation/platform/pam/auditing.mdx b/docs/documentation/platform/pam/auditing.mdxindex 581ba3a932..d6d8a64860 100644--- a/docs/documentation/platform/pam/auditing.mdx+++ b/docs/documentation/platform/pam/auditing.mdx@@ -16,7 +16,7 @@ PAM logs every action — who accessed what, who changed what, and when. This au| **Templates** | Template created, updated, deleted || **Memberships** | Membership added, updated, removed || **Product Access** | Product member added, removed, role changed |-| **[Access requests](/documentation/platform/pam/access-requests/overview)** | Request filed, reviewed, revoked, approval policy bypassed |+| **[Access requests](/documentation/platform/pam/access-requests/overview)** | Request filed, reviewed, auto-approved, revoked, approval policy bypassed |Each event includes:- **Timestamp** — when it happeneddiff --git a/docs/documentation/platform/pam/templates/overview.mdx b/docs/documentation/platform/pam/templates/overview.mdxindex 9e3636d7f3..2d70e4c799 100644--- a/docs/documentation/platform/pam/templates/overview.mdx+++ b/docs/documentation/platform/pam/templates/overview.mdx@@ -35,6 +35,7 @@ If you need different rules — say, 4-hour sessions with MFA for production —| Option | What it does ||--------|--------------|| **Require Approval** | Users must request and receive approval before launching a session or [viewing credentials](/documentation/platform/pam/accounts/overview#viewing-credentials) |+ | **Allow Auto-Approval** | Requests that pass one of the folder's [auto-approval rules](/documentation/platform/pam/access-requests/auto-approval) are approved as soon as they're submitted (appears once **Require Approval** is on) || **Allow Break-Glass** | Named responders can clear their own request without an approver, for emergencies || **Require MFA** | Users must re-authenticate with MFA before connecting || **Require Reason** | A reason must be provided before connecting |diff --git a/frontend/src/hooks/api/approvalPolicies/index.tsx b/frontend/src/hooks/api/approvalPolicies/index.tsxindex 902c0cfa7c..a8d6b5207b 100644--- a/frontend/src/hooks/api/approvalPolicies/index.tsx+++ b/frontend/src/hooks/api/approvalPolicies/index.tsx@@ -10,6 +10,8 @@ export {type ApprovalPolicyStep,ApprovalPolicyType,ApproverType,+ AUTO_APPROVAL_REQUESTER_SUBJECT,+ AutoApprovalConstraintValue,type CertRequestPolicyConditions,type CodeSigningPolicyConstraints,EnforcementLevel,@@ -17,6 +19,17 @@ export {type PamAccessPolicyConstraints,type PolicyBypasser,type TApprovalPolicy,+ type TAutoApprovalCatalogConnection,+ type TAutoApprovalCatalogConstraint,+ type TAutoApprovalCatalogSubject,+ type TAutoApprovalCondition,+ type TAutoApprovalConfig,+ type TAutoApprovalConfigResponse,+ type TAutoApprovalInput,+ type TAutoApprovalInputValue,+ type TAutoApprovalOption,+ type TAutoApprovalOutcome,+ type TAutoApprovalInputDetails,type TCheckPolicyMatchDTO,type TCheckPolicyMatchResult,type TCreateApprovalPolicyDTO,diff --git a/frontend/src/hooks/api/approvalPolicies/queries.tsx b/frontend/src/hooks/api/approvalPolicies/queries.tsxindex 435b03e1ea..f6cc40db21 100644--- a/frontend/src/hooks/api/approvalPolicies/queries.tsx+++ b/frontend/src/hooks/api/approvalPolicies/queries.tsx@@ -2,7 +2,15 @@ import { queryOptions } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";-import { TApprovalPolicy, TGetApprovalPolicyByIdDTO, TListApprovalPoliciesDTO } from "./types";+import {+ TApprovalPolicy,+ TAutoApprovalCatalogConnection,+ TAutoApprovalOption,+ TGetApprovalPolicyByIdDTO,+ TGetAutoApprovalCatalogDTO,+ TListApprovalPoliciesDTO,+ TListAutoApprovalOptionsDTO+} from "./types";export const approvalPolicyQuery = {allKey: () => ["approval-policies"] as const,@@ -10,6 +18,45 @@ export const approvalPolicyQuery = {[...approvalPolicyQuery.allKey(), "by-id", params] as const,listKey: (params: TListApprovalPoliciesDTO) =>[...approvalPolicyQuery.allKey(), "list", params] as const,+ autoApprovalCatalogKey: (params: TGetAutoApprovalCatalogDTO) =>+ [...approvalPolicyQuery.allKey(), "auto-approval-catalog", params] as const,+ autoApprovalOptionsKey: (params: TListAutoApprovalOptionsDTO) =>+ [...approvalPolicyQuery.allKey(), "auto-approval-options", params] as const,+ autoApprovalCatalog: (params: TGetAutoApprovalCatalogDTO) =>+ queryOptions({+ queryKey: approvalPolicyQuery.autoApprovalCatalogKey(params),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ connections: TAutoApprovalCatalogConnection[] }>(+ `/api/v1/approval-policies/${params.policyType}/auto-approval/catalog`,+ { params: { scope: params.scope, id: params.scopeId } }+ );+ return data.connections;+ }+ }),+ autoApprovalOptions: (params: TListAutoApprovalOptionsDTO) =>+ queryOptions({+ queryKey: approvalPolicyQuery.autoApprovalOptionsKey(params),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ options: TAutoApprovalOption[] }>(+ `/api/v1/approval-policies/${params.policyType}/auto-approval/options`,+ {+ params: {+ scope: params.scope,+ id: params.scopeId,+ connectionId: params.connectionId,+ subject: params.subject,+ constraint: params.constraint,+ search: params.search || undefined,+ siblings:+ params.siblings && Object.keys(params.siblings).length+ ? JSON.stringify(params.siblings)+ : undefined+ }+ }+ );+ return data.options;+ }+ }),getById: (params: TGetApprovalPolicyByIdDTO) =>queryOptions({queryKey: approvalPolicyQuery.getByIdKey(params),diff --git a/frontend/src/hooks/api/approvalPolicies/types.ts b/frontend/src/hooks/api/approvalPolicies/types.tsindex e33ad4c2e5..102244536e 100644--- a/frontend/src/hooks/api/approvalPolicies/types.ts+++ b/frontend/src/hooks/api/approvalPolicies/types.ts@@ -6,7 +6,8 @@ export enum ApprovalPolicyType {export enum ApprovalPolicyScope {Project = "project",- PkiApplication = "pki-application"+ PkiApplication = "pki-application",+ PamFolder = "pam-folder"}export enum ApproverType {@@ -59,6 +60,93 @@ export type CodeSigningPolicyConstraints = {maxSignings?: number;};+// Conditions on the requester's own account in a service carry this subject and no input+export const AUTO_APPROVAL_REQUESTER_SUBJECT = "requester";++export enum AutoApprovalConstraintValue {+ None = "none",+ One = "one",+ Many = "many"+}++export type TAutoApprovalInput = { connectionId: string; subject: string };++export type TAutoApprovalCondition = {+ connectionId: string;+ subject: string;+ constraint: string;+ values: string[];+};++export type TAutoApprovalConfig = {+ inputs: TAutoApprovalInput[];+ rules: { name: string; conditions: TAutoApprovalCondition[] }[];+};++export type TAutoApprovalConfigResponse = {+ inputs: (TAutoApprovalInput & { id: string })[];+ rules: { id: string; name: string; conditions: (TAutoApprovalCondition & { id: string })[] }[];+};++export type TAutoApprovalCatalogConstraint = {+ id: string;+ label: string;+ value: AutoApprovalConstraintValue;+ hasOptions: boolean;+};++export type TAutoApprovalCatalogSubject = {+ id: string;+ label: string;+ input: { label: string; placeholder: string } | null;+ constraints: TAutoApprovalCatalogConstraint[];+};++export type TAutoApprovalCatalogConnection = {+ id: string;+ name: string;+ app: string;+ subjects: TAutoApprovalCatalogSubject[];+};++export type TAutoApprovalOption = { value: string; label: string };++// A field the request form shows for one of the policy's inputs+export type TAutoApprovalInputDetails = {+ connectionId: string;+ subject: string;+ label: string;+ placeholder: string;+};++export type TAutoApprovalInputValue = { connectionId: string; subject: string; value: string };++export type TAutoApprovalOutcome = {+ approvedAt: string | null;+ approvedByRuleId: string | null;+ inputs: { label: string; value: string; url: string | null }[];+ rules: {+ id: string;+ name: string;+ passed: boolean;+ conditions: { id: string; description: string; passed: boolean; reason: string | null }[];+ }[];+};++export type TGetAutoApprovalCatalogDTO = {+ policyType: ApprovalPolicyType;+ scope: ApprovalPolicyScope;+ scopeId: string;+};++export type TListAutoApprovalOptionsDTO = TGetAutoApprovalCatalogDTO & {+ connectionId: string;+ subject: string;+ constraint: string;+ search?: string;+ siblings?: Record<string, string[]>;+};+export type TApprovalPolicy = {id: string;projectId: string;@@ -83,6 +171,7 @@ export type TApprovalPolicy = {bypassForMachineIdentities?: boolean;enforcementLevel: EnforcementLevel;bypassers: PolicyBypasser[];+ autoApproval?: TAutoApprovalConfigResponse;scopeType?: ApprovalPolicyScope | string | null;scopeId?: string | null;createdAt: string;@@ -104,6 +193,7 @@ export type TCreateApprovalPolicyDTO = {bypassForMachineIdentities?: boolean;enforcementLevel?: EnforcementLevel;bypassers?: PolicyBypasser[];+ autoApproval?: TAutoApprovalConfig;};export type TUpdateApprovalPolicyDTO = {@@ -123,6 +213,7 @@ export type TUpdateApprovalPolicyDTO = {bypassForMachineIdentities?: boolean;enforcementLevel?: EnforcementLevel;bypassers?: PolicyBypasser[];+ autoApproval?: TAutoApprovalConfig;};export type TGetApprovalPolicyByIdDTO = {@@ -153,4 +244,5 @@ export type TCheckPolicyMatchResult = {constraints?: {accessDuration: { max: string };};+ autoApprovalInputs?: TAutoApprovalInputDetails[];};diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex 8b01fbd474..c5017be7e2 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -414,12 +414,14 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.APPROVAL_REQUEST_LIST]: "List Approval Requests",[EventType.APPROVAL_REQUEST_CREATE]: "Create Approval Request",[EventType.APPROVAL_REQUEST_APPROVE]: "Approve Approval Request",+ [EventType.APPROVAL_REQUEST_AUTO_APPROVE]: "Auto-Approve Approval Request",[EventType.APPROVAL_REQUEST_REJECT]: "Reject Approval Request",[EventType.APPROVAL_REQUEST_CANCEL]: "Cancel Approval Request",[EventType.APPROVAL_REQUEST_GRANT_LIST]: "List Approval Request Grants",[EventType.APPROVAL_REQUEST_GRANT_GET]: "Get Approval Request Grant",[EventType.APPROVAL_REQUEST_GRANT_REVOKE]: "Revoke Approval Request Grant",[EventType.PAM_ACCESS_POLICY_BYPASSED]: "PAM Access Policy Bypassed",+ [EventType.PAM_ACCESS_REQUEST_AUTO_APPROVED]: "PAM Access Request Auto-Approved",[EventType.CREATE_DYNAMIC_SECRET]: "Create Dynamic Secret",[EventType.UPDATE_DYNAMIC_SECRET]: "Update Dynamic Secret",[EventType.DELETE_DYNAMIC_SECRET]: "Delete Dynamic Secret",@@ -540,6 +542,7 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID,EventType.PAM_ACCESS_REQUEST_CREATE,EventType.PAM_ACCESS_REQUEST_REVIEW,+ EventType.PAM_ACCESS_REQUEST_AUTO_APPROVED,EventType.PAM_ACCESS_GRANT_REVOKE,EventType.PAM_ACCOUNT_ROTATE_CREDENTIALS,EventType.PAM_ACCOUNT_SET_ROTATION_ACCOUNT,diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex 0915b412ab..83c46a42e0 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -402,12 +402,14 @@ export enum EventType {APPROVAL_REQUEST_LIST = "approval-request-list",APPROVAL_REQUEST_CREATE = "approval-request-create",APPROVAL_REQUEST_APPROVE = "approval-request-approve",+ APPROVAL_REQUEST_AUTO_APPROVE = "approval-request-auto-approve",APPROVAL_REQUEST_REJECT = "approval-request-reject",APPROVAL_REQUEST_CANCEL = "approval-request-cancel",APPROVAL_REQUEST_GRANT_LIST = "approval-request-grant-list",APPROVAL_REQUEST_GRANT_GET = "approval-request-grant-get",APPROVAL_REQUEST_GRANT_REVOKE = "approval-request-grant-revoke",PAM_ACCESS_POLICY_BYPASSED = "pam-access-policy-bypassed",+ PAM_ACCESS_REQUEST_AUTO_APPROVED = "pam-access-request-auto-approved",// Dynamic SecretsCREATE_DYNAMIC_SECRET = "create-dynamic-secret",diff --git a/frontend/src/hooks/api/auditLogs/types.tsx b/frontend/src/hooks/api/auditLogs/types.tsxindex 9ef11adaae..1e4b4d6777 100644--- a/frontend/src/hooks/api/auditLogs/types.tsx+++ b/frontend/src/hooks/api/auditLogs/types.tsx@@ -978,6 +978,26 @@ interface PamAccessPolicyBypassedEvent {};}+interface PamAccessRequestAutoApprovedEvent {+ type: EventType.PAM_ACCESS_REQUEST_AUTO_APPROVED;+ metadata: {+ requestId: string;+ grantId?: string;+ accountId?: string;+ accountName?: string;+ folderId?: string;+ folderName?: string;+ requesterName?: string;+ requesterEmail?: string;+ duration?: string;+ accessType: string;+ ruleId: string | null;+ ruleName?: string;+ linkedRecords: { label: string; value: string }[];+ conditions: string[];+ };+}+interface CreateProjectFolderGrantEvent {type: EventType.CREATE_PROJECT_FOLDER_GRANT;metadata: {@@ -1118,6 +1138,7 @@ export type Event =| IntegrationSyncedEvent| ClearIdentityLdapAuthLockoutsEvent| PamAccessPolicyBypassedEvent+ | PamAccessRequestAutoApprovedEvent| CreateProjectFolderGrantEvent| DeleteProjectFolderGrantEvent| CreateSecretFolderAccessEventdiff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.tsindex 492ed65856..a4a3773107 100644--- a/frontend/src/hooks/api/pam/enums.ts+++ b/frontend/src/hooks/api/pam/enums.ts@@ -101,6 +101,7 @@ export const formatRotationInterval = (seconds: number | null | undefined): striexport enum PamPolicyType {RequiresApproval = "requires-approval",+ AllowAutoApproval = "allow-auto-approval",AllowBreakGlass = "allow-break-glass",RequireMfa = "require-mfa",RequireReason = "require-reason",diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsxindex 26d4072683..8863fd6200 100644--- a/frontend/src/hooks/api/pam/mutations.tsx+++ b/frontend/src/hooks/api/pam/mutations.tsx@@ -27,6 +27,7 @@ import {TGetPamAccountCredentialsDTO,TImportPamDiscoveredAccountResult,TImportPamDiscoveredAccountsDTO,+ TPamAccessRequest,TPamAccessResponse,TPamAccountCredentials,TPamAccountTemplate,@@ -793,7 +794,10 @@ export const useCreatePamAccessRequest = () => {const queryClient = useQueryClient();return useMutation({mutationFn: async (params: TCreatePamAccessRequestDTO) => {- const { data } = await apiRequest.post("/api/v1/pam/access-requests", params);+ const { data } = await apiRequest.post<{ request: TPamAccessRequest }>(+ "/api/v1/pam/access-requests",+ params+ );return data;},onSuccess: () => {@@ -908,11 +912,12 @@ export const useSetPamApprovalConfig = () => {folderId,steps,notificationConfigs,- breakGlassUsers+ breakGlassUsers,+ autoApproval}: TSetPamApprovalConfigDTO) => {const { data } = await apiRequest.put(`/api/v1/pam/folders/${folderId}/approval-configuration`,- { steps, notificationConfigs, breakGlassUsers }+ { steps, notificationConfigs, breakGlassUsers, autoApproval });return data;},diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsxindex 999b02cba0..150fb77a8f 100644--- a/frontend/src/hooks/api/pam/queries.tsx+++ b/frontend/src/hooks/api/pam/queries.tsx@@ -8,6 +8,7 @@ import {createResourcePermissionQueryHook,ResourcePermissionResponse} from "@app/helpers/resourcePermissions";+import { TAutoApprovalInputDetails } from "@app/hooks/api/approvalPolicies/types";import { conditionsMatcher } from "@app/hooks/api/roles/permission-matcher";import {@@ -652,11 +653,11 @@ export const useGetPamAccountApprovers = (queryKey: pamKeys.accountApprovers(accountId ?? "", accessType),enabled: Boolean(accountId),queryFn: async () => {- const { data } = await apiRequest.get<{ steps: TPamApprovalWorkflowStep[] }>(- `/api/v1/pam/access-requests/accounts/${accountId}/approvers`,- { params: { accessType } }- );- return data.steps;+ const { data } = await apiRequest.get<{+ steps: TPamApprovalWorkflowStep[];+ autoApprovalInputs: TAutoApprovalInputDetails[];+ }>(`/api/v1/pam/access-requests/accounts/${accountId}/approvers`, { params: { accessType } });+ return data;}});};diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.tsindex 1f9c455382..de4eb046bd 100644--- a/frontend/src/hooks/api/pam/types/index.ts+++ b/frontend/src/hooks/api/pam/types/index.ts@@ -1,3 +1,9 @@+import {+ TAutoApprovalConfig,+ TAutoApprovalConfigResponse,+ TAutoApprovalInputValue,+ TAutoApprovalOutcome+} from "../../approvalPolicies/types";import { OrderByDirection } from "../../generic/types";import {PamAccessRequestDecision,@@ -743,6 +749,8 @@ export type TPamAccessRequest = {grantStatus?: string | null;isBreakGlass?: boolean;bypassReason?: string | null;+ autoApprovedAt?: string | null;+ autoApproval?: TAutoApprovalOutcome | null;};export type TPamNotificationConfig = {@@ -761,6 +769,7 @@ export type TPamApprovalConfig = {integrationSlug: string;})[];breakGlassUsers: { type: PamApproverType; id: string }[];+ autoApproval: TAutoApprovalConfigResponse;};export type TPamAccessGrant = {@@ -783,6 +792,7 @@ export type TCreatePamAccessRequestDTO = {reason?: string;duration: string;accessType?: PamAccessType;+ autoApprovalInputs?: TAutoApprovalInputValue[];};export type TReviewPamAccessRequestDTO = {@@ -807,4 +817,6 @@ export type TSetPamApprovalConfigDTO = {}[];notificationConfigs?: TPamNotificationConfig[];breakGlassUsers?: { type: PamApproverType; id: string }[];+ // Omit to leave the folder's auto-approval rules unchanged+ autoApproval?: TAutoApprovalConfig;};diff --git a/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx b/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsxindex aaa2eebc48..62f1ac8a49 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/FolderApprovalsTab.tsx@@ -1,12 +1,14 @@import { useEffect, useMemo, useState } from "react";import { components, OptionProps } from "react-select";+import { useQuery } from "@tanstack/react-query";import {Ban,FilterIcon,ShieldAlert,Trash2,User as UserIcon,- Users as UsersIcon+ Users as UsersIcon,+ Zap} from "lucide-react";import { twMerge } from "tailwind-merge";@@ -48,6 +50,11 @@ import {setUserTablePreference} from "@app/helpers/userTablePreferences";import { AlertChannelType, AlertResourceType } from "@app/hooks/api/alerts";+import {+ approvalPolicyQuery,+ ApprovalPolicyScope,+ ApprovalPolicyType+} from "@app/hooks/api/approvalPolicies";import { useGetOrganizationGroups } from "@app/hooks/api/organization/queries";import {PamAccessRequestStatus,@@ -68,6 +75,15 @@ import { AlertAction } from "@app/views/Alerts";import { AccessTypeBadge } from "../../components/AccessTypeBadge";import { AccountPlatformIcon } from "../../components/AccountPlatformIcon";import { getRequestStatusInfo, isGrantActive } from "../../components/approvalRequestStatus";+import { AutoApprovalCard } from "../../components/auto-approval/AutoApprovalCard";+import {+ EMPTY_AUTO_APPROVAL_DRAFT,+ getRuleError,+ serializeAutoApprovalDraft,+ TAutoApprovalDraft,+ toAutoApprovalConfig,+ toAutoApprovalDraft+} from "../../components/auto-approval/autoApprovalDraft";import { getRequesterSubtitle } from "../../components/requesterDisplay";import { FolderNotificationsSection } from "./FolderNotificationsSection";@@ -150,6 +166,18 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {const [breakGlassUsers, setBreakGlassApprovers] = useState<ApproverEntry[]>([]);const [isDirty, setIsDirty] = useState(false);const [notificationConfigs, setNotificationConfigs] = useState<TPamNotificationConfig[]>([]);+ const [autoApprovalDraft, setAutoApprovalDraft] =+ useState<TAutoApprovalDraft>(EMPTY_AUTO_APPROVAL_DRAFT);+ const [showAutoApprovalErrors, setShowAutoApprovalErrors] = useState(false);++ const autoApprovalScope = {+ policyType: ApprovalPolicyType.PamAccess,+ scope: ApprovalPolicyScope.PamFolder,+ scopeId: folderId+ };+ const { data: autoApprovalCatalog } = useQuery(+ approvalPolicyQuery.autoApprovalCatalog(autoApprovalScope)+ );const savedApprovers = useMemo(() => {if (!config?.steps?.[0]) return [];@@ -171,6 +199,8 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {[config]);+ const savedAutoApprovalDraft = useMemo(() => toAutoApprovalDraft(config?.autoApproval), [config]);+const integrationSlugById = useMemo(() =>Object.fromEntries(@@ -192,6 +222,11 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {setNotificationConfigs(savedNotificationConfigs);}, [savedNotificationConfigs]);+ useEffect(() => {+ setAutoApprovalDraft(savedAutoApprovalDraft);+ setShowAutoApprovalErrors(false);+ }, [savedAutoApprovalDraft]);+const isNotifDirty = useMemo(() => JSON.stringify(notificationConfigs) !== JSON.stringify(savedNotificationConfigs),[notificationConfigs, savedNotificationConfigs]@@ -200,7 +235,13 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {() => JSON.stringify(breakGlassUsers) !== JSON.stringify(savedBreakGlassUsers),[breakGlassUsers, savedBreakGlassUsers]);- const isAnyDirty = isDirty || isNotifDirty || isBreakGlassDirty;+ const isAutoApprovalDirty = useMemo(+ () =>+ serializeAutoApprovalDraft(autoApprovalDraft) !==+ serializeAutoApprovalDraft(savedAutoApprovalDraft),+ [autoApprovalDraft, savedAutoApprovalDraft]+ );+ const isAnyDirty = isDirty || isNotifDirty || isBreakGlassDirty || isAutoApprovalDirty;useEffect(() => {onDirtyChange?.(isAnyDirty);@@ -324,13 +365,28 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {return;}+ if (autoApprovalDraft.rules.length > 0 && approvers.length === 0) {+ createNotification({+ type: "error",+ text: "Auto-approval rules need at least one approver for the requests they don't approve"+ });+ return;+ }++ if (autoApprovalDraft.rules.some((rule) => getRuleError(rule, autoApprovalCatalog))) {+ setShowAutoApprovalErrors(true);+ createNotification({ type: "error", text: "Finish the auto-approval rules before saving" });+ return;+ }+setConfig.mutate({folderId,steps: [{ approvers }],breakGlassUsers,// Legacy Slack configs can only be removed, so they're sent only when one was.- notificationConfigs: isNotifDirty ? notificationConfigs : undefined+ notificationConfigs: isNotifDirty ? notificationConfigs : undefined,+ autoApproval: isAutoApprovalDirty ? toAutoApprovalConfig(autoApprovalDraft) : undefined},{onSuccess: () => {@@ -348,6 +404,8 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {setApprovers(savedApprovers);setBreakGlassApprovers(savedBreakGlassUsers);setNotificationConfigs(savedNotificationConfigs);+ setAutoApprovalDraft(savedAutoApprovalDraft);+ setShowAutoApprovalErrors(false);setIsDirty(false);};@@ -362,6 +420,14 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {return (<div className="flex flex-1 flex-col gap-4 p-4">+ <AutoApprovalCard+ {...autoApprovalScope}+ draft={autoApprovalDraft}+ onChange={setAutoApprovalDraft}+ showErrors={showAutoApprovalErrors}+ hasApprovers={approvers.length > 0}+ />+<Card><CardHeader className="border-b"><CardTitle className="text-base">@@ -661,7 +727,25 @@ export const FolderApprovalsTab = ({ folderId, onDirtyChange }: Props) => {</TableCell><TableCell><div className="flex items-center gap-1.5">- <Badge variant={status.variant}>{status.label}</Badge>+ {status.isAutoApproved ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant={status.variant}>+ <Zap className="mr-1 size-3" />+ {status.label}+ </Badge>+ </TooltipTrigger>+ <TooltipContent>+ {`Approved by the rule "${+ request.autoApproval?.rules.find(+ (rule) => rule.id === request.autoApproval?.approvedByRuleId+ )?.name ?? "auto-approval"+ }"`}+ </TooltipContent>+ </Tooltip>+ ) : (+ <Badge variant={status.variant}>{status.label}</Badge>+ )}{request.isBreakGlass && (<Tooltip><TooltipTrigger asChild>diff --git a/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx b/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsxindex dd6b2aa588..795e2e95ed 100644--- a/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx+++ b/frontend/src/pages/pam/PamApprovalRequestsPage/components/ApprovalRequestDetailSheet.tsx@@ -26,6 +26,7 @@ import { TPamAccessRequest } from "@app/hooks/api/pam/types";import { AccountPlatformIcon } from "../../components/AccountPlatformIcon";import { getRequestStatusInfo, isGrantActive } from "../../components/approvalRequestStatus";+import { AutoApprovalResults } from "../../components/auto-approval/AutoApprovalResults";import { formatDuration } from "../../components/formatDuration";import { PamDetailSheet } from "../../components/PamDetailSheet";import { isMachineIdentityRequest } from "../../components/requesterDisplay";@@ -247,6 +248,13 @@ export const ApprovalRequestDetailSheet = ({ request, isOpen, onOpenChange }: PrThis request has been {status.label.toLowerCase()} and can no longer be actioned.</p>)}++ {request?.autoApproval && (+ <div>+ <p className="mb-2 text-sm font-medium text-foreground">Auto-approval status</p>+ <AutoApprovalResults outcome={request.autoApproval} />+ </div>+ )}</div></div></PamDetailSheet>diff --git a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsxindex 451245eb89..8b61fe33ab 100644--- a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx+++ b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx@@ -407,8 +407,13 @@ const SettingsTab = ({const typeName = accountTypeMap[template.type]?.name ?? template.type;const isRotatableTemplateType = isRotatablePamAccountType(template.type);const requiresApproval = policies[PamPolicyType.RequiresApproval] === true;+ // These only change how an approval is reached, so they follow Require Approval+ const approvalDependentPolicies = [+ PamPolicyType.AllowAutoApproval,+ PamPolicyType.AllowBreakGlass+ ];const applicablePolicies = (accountTypeMap[template.type]?.applicablePolicies ?? []).filter(- (p) => POLICY_EDITORS[p.key] && (p.key !== PamPolicyType.AllowBreakGlass || requiresApproval)+ (p) => POLICY_EDITORS[p.key] && (!approvalDependentPolicies.includes(p.key) || requiresApproval));const onSubmit = (data: SettingsForm) => {@@ -565,7 +570,7 @@ const SettingsTab = ({if (value === null || value === undefined) delete next[p.key];else next[p.key] = value;if (p.key === PamPolicyType.RequiresApproval && value !== true) {- delete next[PamPolicyType.AllowBreakGlass];+ approvalDependentPolicies.forEach((key) => delete next[key]);}setValue("policies", next, { shouldDirty: true });}}diff --git a/frontend/src/pages/pam/components/RequestAccessSheet.tsx b/frontend/src/pages/pam/components/RequestAccessSheet.tsxindex 155b1d8fa0..f6ba4b50d6 100644--- a/frontend/src/pages/pam/components/RequestAccessSheet.tsx+++ b/frontend/src/pages/pam/components/RequestAccessSheet.tsx@@ -53,6 +53,10 @@ import {useGetPamAccountApprovers} from "@app/hooks/api/pam";+import {+ AutoApprovalRequestInputs,+ toAutoApprovalInputValues+} from "./auto-approval/AutoApprovalRequestInputs";import { AccessTypeBadge } from "./AccessTypeBadge";import { useAccountSheetDetails } from "./accountSheetDetails";import { PamDetailSheet } from "./PamDetailSheet";@@ -119,7 +123,8 @@ const ApprovalWorkflow = ({isPending: boolean;accessType: PamAccessType;}) => {- const { data: steps } = useGetPamAccountApprovers(accountId, accessType);+ const { data } = useGetPamAccountApprovers(accountId, accessType);+ const steps = data?.steps;if (!steps?.length) return null;return (@@ -182,6 +187,7 @@ export const RequestAccessSheet = ({const formId = useId();const breakGlass = useBreakGlassPamAccessRequest();const [bypassReason, setBypassReason] = useState("");+ const [autoApprovalValues, setAutoApprovalValues] = useState<Record<string, string>>({});const isCredentialRequest = accessType === PamAccessType.Credential;const isPending =(isCredentialRequest ? account?.credentialAccessStatus : account?.accessStatus) ===@@ -210,11 +216,16 @@ export const RequestAccessSheet = ({defaultValues: { duration: "1h", reason: "" }});+ const { data: approverData } = useGetPamAccountApprovers(account?.id, accessType);+ const autoApprovalInputDetails = approverData?.autoApprovalInputs ?? [];+ const hasAutoApprovalValues = Object.values(autoApprovalValues).some((value) => value.trim());+const handleOpenChange = (open: boolean) => {if (!open) {reset();setBypassReason("");setBreakGlassOnSubmit(false);+ setAutoApprovalValues({});}onOpenChange(open);};@@ -239,28 +250,51 @@ export const RequestAccessSheet = ({const onSubmit = (data: FormData) => {if (!account) return;+ const autoApprovalInputs = breakGlassOnSubmit+ ? []+ : toAutoApprovalInputValues(autoApprovalInputDetails, autoApprovalValues);+createRequest.mutate({accountId: account.id,duration: data.duration,reason: data.reason || undefined,accessType,- breakGlass: breakGlassOnSubmit || undefined+ breakGlass: breakGlassOnSubmit || undefined,+ autoApprovalInputs: autoApprovalInputs.length ? autoApprovalInputs : undefined},{- onSuccess: () => {- const submittedText = isCredentialRequest+ onSuccess: ({ request }) => {+ const outcome = request?.autoApproval;+ const approvingRule = outcome?.rules.find((rule) => rule.id === outcome.approvedByRuleId);+ // The rule that came closest to passing best reflects what the requester was going for+ const closestRule = outcome?.rules+ .map((rule) => ({+ rule,+ failed: rule.conditions.filter((condition) => !condition.passed).length,+ passed: rule.conditions.filter((condition) => condition.passed).length+ }))+ .sort((a, b) => a.failed - b.failed || b.passed - a.passed)[0]?.rule;+ const firstFailure = closestRule?.conditions.find((condition) => !condition.passed)?.reason;++ let text = isCredentialRequest? "Credential access request submitted": "Access request submitted";- createNotification({- text: breakGlassOnSubmit- ? "Access granted. The approvers you skipped have been notified."- : submittedText,- type: "success"- });+ if (breakGlassOnSubmit) {+ text = "Access granted. The approvers you skipped have been notified.";+ } else if (request?.autoApprovedAt) {+ text = `Access approved by the auto-approval rule "${approvingRule?.name ?? "auto-approval"}"`;+ } else if (outcome && firstFailure) {+ text = `${text}. It wasn't auto-approved: ${firstFailure}`;+ }++ createNotification({ text, type: "success" });reset();+ setAutoApprovalValues({});onOpenChange(false);- if (breakGlassOnSubmit && account) onGranted?.(account, accessType);+ if ((breakGlassOnSubmit || request?.autoApprovedAt) && account) {+ onGranted?.(account, accessType);+ }}});@@ -277,7 +311,7 @@ export const RequestAccessSheet = ({typeBadge={typeName}badges={<AccessTypeBadge accessType={accessType} />}metadata={metadata}- isDirty={isDirty && !isPending}+ isDirty={(isDirty || hasAutoApprovalValues) && !isPending}contentFooter={!isPending && (<>@@ -435,6 +469,13 @@ export const RequestAccessSheet = ({</Field>)}/>+ {!breakGlassOnSubmit && autoApprovalInputDetails.length > 0 && (+ <AutoApprovalRequestInputs+ inputs={autoApprovalInputDetails}+ values={autoApprovalValues}+ onChange={setAutoApprovalValues}+ />+ )}<ApprovalWorkflow accountId={account?.id} isPending={false} accessType={accessType} />{account?.canBreakGlass && (<Carddiff --git a/frontend/src/pages/pam/components/approvalRequestStatus.ts b/frontend/src/pages/pam/components/approvalRequestStatus.tsindex 6d167fe5fd..df914123b9 100644--- a/frontend/src/pages/pam/components/approvalRequestStatus.ts+++ b/frontend/src/pages/pam/components/approvalRequestStatus.ts@@ -1,20 +1,25 @@import { PamAccessGrantStatus, PamAccessRequestStatus } from "@app/hooks/api/pam";import { TPamAccessRequest } from "@app/hooks/api/pam/types";-type StatusInfo = { variant: "warning" | "success" | "danger" | "neutral"; label: string };+type StatusInfo = {+ variant: "warning" | "success" | "danger" | "neutral";+ label: string;+ isAutoApproved?: boolean;+};const STATUS_BADGE: Record<string, StatusInfo> = {[PamAccessRequestStatus.Pending]: { variant: "warning", label: "Pending Review" },[PamAccessRequestStatus.Approved]: { variant: "success", label: "Approved" },[PamAccessRequestStatus.Rejected]: { variant: "danger", label: "Rejected" },[PamAccessRequestStatus.Expired]: { variant: "neutral", label: "Expired" },+ [PamAccessRequestStatus.Cancelled]: { variant: "neutral", label: "Cancelled" },[PamAccessGrantStatus.Revoked]: { variant: "danger", label: "Revoked" }};// The underlying request status stays "approved" after approval; the grant carries the real// post-approval state. A revoked grant shows "Revoked", and a grant past its expiry shows "Expired".export const getRequestStatusInfo = (- request: Pick<TPamAccessRequest, "status" | "grantExpiresAt" | "grantStatus">+ request: Pick<TPamAccessRequest, "status" | "grantExpiresAt" | "grantStatus" | "autoApprovedAt">): StatusInfo => {if (request.status === PamAccessRequestStatus.Approved) {if (request.grantStatus === PamAccessGrantStatus.Revoked)@@ -22,6 +27,9 @@ export const getRequestStatusInfo = (const grantExpired =!!request.grantExpiresAt && new Date(request.grantExpiresAt).getTime() <= Date.now();if (grantExpired) return STATUS_BADGE[PamAccessRequestStatus.Expired];+ if (request.autoApprovedAt) {+ return { variant: "success", label: "Auto-approved", isAutoApproved: true };+ }}return STATUS_BADGE[request.status] ?? STATUS_BADGE[PamAccessRequestStatus.Pending];diff --git a/frontend/src/pages/pam/components/auto-approval/AutoApprovalCard.tsx b/frontend/src/pages/pam/components/auto-approval/AutoApprovalCard.tsxnew file mode 100644index 0000000000..2990170bd0--- /dev/null+++ b/frontend/src/pages/pam/components/auto-approval/AutoApprovalCard.tsx@@ -0,0 +1,273 @@+import { useQuery } from "@tanstack/react-query";+import { Info, Link2, Plus, X } from "lucide-react";++import {+ Badge,+ Button,+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ IconButton,+ ProviderIcon,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { Skeleton } from "@app/components/v3/generic/Skeleton";+import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";+import { AppConnection } from "@app/hooks/api/appConnections/enums";+import {+ approvalPolicyQuery,+ ApprovalPolicyScope,+ ApprovalPolicyType+} from "@app/hooks/api/approvalPolicies";++import { findSubject, newKey, TAutoApprovalDraft } from "./autoApprovalDraft";+import { DisabledReason, SectionLabel } from "./AutoApprovalLabels";+import { AutoApprovalRuleCard } from "./AutoApprovalRuleCard";++type Props = {+ policyType: ApprovalPolicyType;+ scope: ApprovalPolicyScope;+ scopeId: string;+ draft: TAutoApprovalDraft;+ onChange: (draft: TAutoApprovalDraft) => void;+ showErrors: boolean;+ hasApprovers: boolean;+};++const ConnectionIcon = ({ app }: { app: string }) => {+ const details = APP_CONNECTION_MAP[app as AppConnection];+ if (!details) return null;+ return <ProviderIcon icon={details.image} alt="" className="size-4 shrink-0" />;+};++export const AutoApprovalCard = ({+ policyType,+ scope,+ scopeId,+ draft,+ onChange,+ showErrors,+ hasApprovers+}: Props) => {+ const { data: catalog = [], isPending } = useQuery(+ approvalPolicyQuery.autoApprovalCatalog({ policyType, scope, scopeId })+ );++ const availableInputs = catalog.flatMap((connection) =>+ connection.subjects+ .filter(+ (subject) =>+ subject.input &&+ !draft.inputs.some(+ (input) => input.connectionId === connection.id && input.subject === subject.id+ )+ )+ .map((subject) => ({ connection, subject }))+ );++ const removeInput = (connectionId: string, subject: string) =>+ onChange({+ inputs: draft.inputs.filter(+ (input) => !(input.connectionId === connectionId && input.subject === subject)+ ),+ // A condition cannot check information the request no longer asks for+ rules: draft.rules.map((rule) => ({+ ...rule,+ conditions: rule.conditions.filter(+ (condition) => !(condition.connectionId === connectionId && condition.subject === subject)+ )+ }))+ });++ const addRule = () =>+ onChange({+ ...draft,+ rules: [+ ...draft.rules,+ { key: newKey(), name: `Rule ${draft.rules.length + 1}`, conditions: [] }+ ]+ });++ let addInputBlocker: string | undefined;+ if (catalog.length === 0) {+ addInputBlocker = "Add an app connection that supports auto-approval.";+ } else if (availableInputs.length === 0) {+ addInputBlocker = "Every available field is already added.";+ }++ return (+ <Card>+ <CardHeader>+ <CardTitle className="flex items-center gap-1.5 text-base">+ Auto-Approval+ <Tooltip>+ <TooltipTrigger asChild>+ <Info className="size-3.5 text-muted" aria-label="When auto-approval applies" />+ </TooltipTrigger>+ <TooltipContent className="max-w-72">+ Only applies to accounts whose template has Allow Auto-Approval on. Requests no rule+ approves wait for the approvers below.+ </TooltipContent>+ </Tooltip>+ </CardTitle>+ <CardDescription>+ Automatically approve requests that meet specific conditions, using what requesters+ provide.+ </CardDescription>+ </CardHeader>+ <CardContent className="flex flex-col gap-6">+ {isPending ? (+ <Skeleton className="h-24 w-full" />+ ) : (+ <>+ <section className="flex flex-col gap-3">+ <div className="flex items-start justify-between gap-4">+ <div className="flex flex-col gap-1">+ <SectionLabel>Request Information</SectionLabel>+ <p className="text-sm text-muted">+ Records requesters link when asking for access.+ </p>+ </div>+ <DisabledReason reason={addInputBlocker}>+ <DropdownMenu>+ <DropdownMenuTrigger asChild disabled={Boolean(addInputBlocker)}>+ <Button type="button" variant="outline" size="sm" className="border-dashed">+ <Plus />+ Add Field+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {availableInputs.map(({ connection, subject }) => (+ <DropdownMenuItem+ key={`${connection.id}:${subject.id}`}+ onClick={() =>+ onChange({+ ...draft,+ inputs: [+ ...draft.inputs,+ { connectionId: connection.id, subject: subject.id }+ ]+ })+ }+ >+ <ConnectionIcon app={connection.app} />+ {subject.input?.label}+ <span className="text-muted">· {connection.name}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </DisabledReason>+ </div>++ {draft.inputs.length > 0 && (+ <div className="flex flex-col divide-y divide-border rounded-md border border-border">+ {draft.inputs.map((input) => {+ const { connection, subject } = findSubject(+ catalog,+ input.connectionId,+ input.subject+ );+ return (+ <div+ key={`${input.connectionId}:${input.subject}`}+ className="flex items-center gap-3 px-4 py-2.5"+ >+ <span className="text-sm text-foreground">+ {subject?.input?.label ?? input.subject}+ </span>+ {connection ? (+ <Badge variant="neutral">+ <Link2 />+ {connection.name}+ </Badge>+ ) : (+ <span className="text-xs text-muted">+ Connection unavailable. You may not have access to it.+ </span>+ )}+ <Badge variant="outline" className="ml-auto">+ Optional+ </Badge>+ <IconButton+ variant="ghost"+ size="xs"+ aria-label="Remove field"+ className="text-muted hover:text-danger"+ onClick={() => removeInput(input.connectionId, input.subject)}+ >+ <X className="size-4" />+ </IconButton>+ </div>+ );+ })}+ </div>+ )}+ </section>++ <section className="flex flex-col gap-3">+ <div className="flex items-center justify-between gap-4">+ <SectionLabel>Rules</SectionLabel>+ <DisabledReason+ reason={+ hasApprovers+ ? undefined+ : "Add an approver first. Requests no rule approves still need someone to approve them."+ }+ >+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="border-dashed"+ isDisabled={!hasApprovers}+ onClick={addRule}+ >+ <Plus />+ Add Rule+ </Button>+ </DisabledReason>+ </div>++ {draft.rules.map((rule, index) => (+ <AutoApprovalRuleCard+ key={rule.key}+ index={index}+ rule={rule}+ inputs={draft.inputs}+ catalog={catalog}+ policyType={policyType}+ scope={scope}+ scopeId={scopeId}+ showErrors={showErrors}+ onChange={(next) =>+ onChange({+ ...draft,+ rules: draft.rules.map((candidate) =>+ candidate.key === next.key ? next : candidate+ )+ })+ }+ onRemove={() =>+ onChange({+ ...draft,+ rules: draft.rules.filter((candidate) => candidate.key !== rule.key)+ })+ }+ />+ ))}+ </section>+ </>+ )}+ </CardContent>+ </Card>+ );+};diff --git a/frontend/src/pages/pam/components/auto-approval/AutoApprovalLabels.tsx b/frontend/src/pages/pam/components/auto-approval/AutoApprovalLabels.tsxnew file mode 100644index 0000000000..6d4a8c4374--- /dev/null+++ b/frontend/src/pages/pam/components/auto-approval/AutoApprovalLabels.tsx@@ -0,0 +1,26 @@+import { ReactElement, ReactNode } from "react";++import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";++export const SectionLabel = ({ children }: { children: ReactNode }) => (+ <p className="text-xs font-medium tracking-wider text-muted uppercase">{children}</p>+);++// A disabled button gets no pointer events, so the tooltip hangs off a wrapper+export const DisabledReason = ({+ reason,+ children+}: {+ reason?: string;+ children: ReactElement;+}) => {+ if (!reason) return children;+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="inline-flex shrink-0">{children}</span>+ </TooltipTrigger>+ <TooltipContent className="max-w-64">{reason}</TooltipContent>+ </Tooltip>+ );+};diff --git a/frontend/src/pages/pam/components/auto-approval/AutoApprovalRequestInputs.tsx b/frontend/src/pages/pam/components/auto-approval/AutoApprovalRequestInputs.tsxnew file mode 100644index 0000000000..d48f74d8be--- /dev/null+++ b/frontend/src/pages/pam/components/auto-approval/AutoApprovalRequestInputs.tsx@@ -0,0 +1,54 @@+import { Field, FieldContent, FieldDescription, FieldLabel, Input } from "@app/components/v3";+import {+ TAutoApprovalInputValue,+ TAutoApprovalInputDetails+} from "@app/hooks/api/approvalPolicies";++export const getInputKey = (input: { connectionId: string; subject: string }) =>+ `${input.connectionId}:${input.subject}`;++export const toAutoApprovalInputValues = (+ inputs: TAutoApprovalInputDetails[],+ values: Record<string, string>+): TAutoApprovalInputValue[] =>+ inputs+ .map((input) => ({+ connectionId: input.connectionId,+ subject: input.subject,+ value: values[getInputKey(input)]?.trim() ?? ""+ }))+ .filter((entry) => entry.value);++type Props = {+ inputs: TAutoApprovalInputDetails[];+ values: Record<string, string>;+ onChange: (values: Record<string, string>) => void;+};++export const AutoApprovalRequestInputs = ({ inputs, values, onChange }: Props) => (+ <>+ {inputs.map((input) => {+ const key = getInputKey(input);+ return (+ <Field key={key}>+ <FieldLabel htmlFor={`auto-approval-${key}`}>+ {input.label} <span className="font-normal text-muted">(optional)</span>+ </FieldLabel>+ <FieldContent>+ <Input+ id={`auto-approval-${key}`}+ value={values[key] ?? ""}+ onChange={(e) => onChange({ ...values, [key]: e.target.value })}+ placeholder={input.placeholder}+ maxLength={2048}+ />+ <FieldDescription>+ Requests are approved instantly when the linked record passes this folder's+ auto-approval rules.+ </FieldDescription>+ </FieldContent>+ </Field>+ );+ })}+ </>+);diff --git a/frontend/src/pages/pam/components/auto-approval/AutoApprovalResults.tsx b/frontend/src/pages/pam/components/auto-approval/AutoApprovalResults.tsxnew file mode 100644index 0000000000..db328fd58b--- /dev/null+++ b/frontend/src/pages/pam/components/auto-approval/AutoApprovalResults.tsx@@ -0,0 +1,123 @@+import { Check, ExternalLink, X, Zap } from "lucide-react";++import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@app/components/v3";+import { TAutoApprovalOutcome } from "@app/hooks/api/approvalPolicies";++type Props = {+ outcome: TAutoApprovalOutcome;+};++const LinkedRecords = ({ inputs }: { inputs: TAutoApprovalOutcome["inputs"] }) => {+ if (!inputs.length) return null;++ return (+ <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs">+ {inputs.map((input) => (+ <span key={`${input.label}:${input.value}`} className="text-muted">+ {input.label}:{" "}+ {input.url ? (+ <a+ href={input.url}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-1 text-foreground underline-offset-2 hover:underline"+ >+ {input.value}+ <ExternalLink className="size-3" />+ </a>+ ) : (+ <span className="text-foreground">{input.value}</span>+ )}+ </span>+ ))}+ </div>+ );+};++const ConditionResult = ({+ condition+}: {+ condition: TAutoApprovalOutcome["rules"][number]["conditions"][number];+}) => (+ <li className="flex items-start gap-2 text-xs">+ {condition.passed ? (+ <Check className="mt-0.5 size-3.5 shrink-0 text-success" />+ ) : (+ <X className="mt-0.5 size-3.5 shrink-0 text-danger" />+ )}+ <div className="min-w-0">+ <p className="text-foreground">{condition.description}</p>+ {!condition.passed && condition.reason && <p className="text-muted">{condition.reason}</p>}+ </div>+ </li>+);++type TRuleOutcome = TAutoApprovalOutcome["rules"][number];++const RuleSummary = ({ rule }: { rule: TRuleOutcome }) => {+ const failed = rule.conditions.filter((condition) => !condition.passed);+ if (!failed.length) {+ return <span className="text-muted">All {rule.conditions.length} checks passed</span>;+ }+ const [first] = failed;+ return (+ <span className="min-w-0 truncate text-muted">+ {first.reason ?? first.description}+ {failed.length > 1 && ` (+${failed.length - 1} more)`}+ </span>+ );+};++// Each rule collapses to one line, so a policy with many rules stays short+const RuleResults = ({ rules }: { rules: TRuleOutcome[] }) => (+ <Accordion type="multiple" variant="ghost">+ {rules.map((rule) => {+ const passed = rule.conditions.every((condition) => condition.passed);+ return (+ <AccordionItem key={rule.id} value={rule.id} className="border-b-0">+ <AccordionTrigger className="group-data-[variant=ghost]/accordion:min-h-7 group-data-[variant=ghost]/accordion:py-1 gap-2 text-xs font-normal [&>[data-slot=accordion-chevron]]:order-last [&>[data-slot=accordion-chevron]]:ml-auto [&>[data-slot=accordion-chevron]]:rotate-90 [&>[data-slot=accordion-chevron]]:opacity-50 group-data-[variant=ghost]/accordion:[&[data-state=open]>[data-slot=accordion-chevron]]:rotate-0">+ {passed ? (+ <Check className="size-3.5 shrink-0 text-success" />+ ) : (+ <X className="size-3.5 shrink-0 text-danger" />+ )}+ <span className="shrink-0 font-medium text-foreground">{rule.name}</span>+ <RuleSummary rule={rule} />+ </AccordionTrigger>+ <AccordionContent className="group-data-[variant=ghost]/accordion:pt-1 group-data-[variant=ghost]/accordion:pb-2 pl-6">+ <ul className="flex flex-col gap-1.5">+ {rule.conditions.map((condition) => (+ <ConditionResult key={condition.id} condition={condition} />+ ))}+ </ul>+ </AccordionContent>+ </AccordionItem>+ );+ })}+ </Accordion>+);++// Why a request was auto-approved, or why each rule did not approve it+export const AutoApprovalResults = ({ outcome }: Props) => {+ const approvingRule = outcome.rules.find((rule) => rule.id === outcome.approvedByRuleId);+ const isApproved = Boolean(outcome.approvedAt && approvingRule);++ return (+ <div+ className={+ isApproved+ ? "flex flex-col gap-1.5 rounded-md border border-success/40 bg-success/5 px-3 py-2.5"+ : "flex flex-col gap-1.5 rounded-md border border-border bg-container px-3 py-2.5"+ }+ >+ <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">+ <p className="flex items-center gap-1.5 text-sm font-medium text-foreground">+ {isApproved && <Zap className="size-3.5 shrink-0 text-success" />}+ {isApproved ? "Approved" : "No rule passed"}+ </p>+ <LinkedRecords inputs={outcome.inputs} />+ </div>+ <RuleResults rules={isApproved && approvingRule ? [approvingRule] : outcome.rules} />+ </div>+ );+};diff --git a/frontend/src/pages/pam/components/auto-approval/AutoApprovalRuleCard.tsx b/frontend/src/pages/pam/components/auto-approval/AutoApprovalRuleCard.tsxnew file mode 100644index 0000000000..e329f63592--- /dev/null+++ b/frontend/src/pages/pam/components/auto-approval/AutoApprovalRuleCard.tsx@@ -0,0 +1,356 @@+import { Fragment } from "react";+import { Plus, ShieldAlert, Trash2, X } from "lucide-react";++import {+ Badge,+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ IconButton+} from "@app/components/v3";+import { cn } from "@app/components/v3/utils";+import {+ ApprovalPolicyScope,+ ApprovalPolicyType,+ AUTO_APPROVAL_REQUESTER_SUBJECT,+ AutoApprovalConstraintValue,+ TAutoApprovalCatalogConnection+} from "@app/hooks/api/approvalPolicies";++import {+ ASSIGNED_TO_REQUESTER_CONSTRAINT,+ findSubject,+ getConditionError,+ getRuleError,+ getUnboundInputSubjects,+ newKey,+ TAutoApprovalDraft,+ TDraftCondition,+ TDraftRule+} from "./autoApprovalDraft";+import { DisabledReason, SectionLabel } from "./AutoApprovalLabels";+import { AutoApprovalValuePicker } from "./AutoApprovalValuePicker";++type TSubjectChoice = {+ key: string;+ connectionId: string;+ subject: string;+ label: string;+ via: string;+};++type Props = {+ index: number;+ rule: TDraftRule;+ inputs: TAutoApprovalDraft["inputs"];+ catalog: TAutoApprovalCatalogConnection[];+ policyType: ApprovalPolicyType;+ scope: ApprovalPolicyScope;+ scopeId: string;+ showErrors: boolean;+ onChange: (rule: TDraftRule) => void;+ onRemove: () => void;+};++const getSubjectChoices = (+ inputs: TAutoApprovalDraft["inputs"],+ catalog: TAutoApprovalCatalogConnection[]+): TSubjectChoice[] => {+ const fromInputs = inputs.flatMap(({ connectionId, subject: subjectId }) => {+ const { connection, subject } = findSubject(catalog, connectionId, subjectId);+ if (!connection || !subject) return [];+ return [+ {+ key: `${connectionId}:${subjectId}`,+ connectionId,+ subject: subjectId,+ label: subject.label,+ via: connection.name+ }+ ];+ });++ const fromRequester = catalog.flatMap((connection) =>+ connection.subjects+ .filter((subject) => subject.id === AUTO_APPROVAL_REQUESTER_SUBJECT)+ .map((subject) => ({+ key: `${connection.id}:${subject.id}`,+ connectionId: connection.id,+ subject: subject.id,+ label: subject.label,+ via: connection.name+ }))+ );++ return [...fromInputs, ...fromRequester];+};++const ConditionRow = ({+ condition,+ rule,+ catalog,+ policyType,+ scope,+ scopeId,+ showErrors,+ onChange,+ onRemove+}: {+ condition: TDraftCondition;+ rule: TDraftRule;+ catalog: TAutoApprovalCatalogConnection[];+ policyType: ApprovalPolicyType;+ scope: ApprovalPolicyScope;+ scopeId: string;+ showErrors: boolean;+ onChange: (condition: TDraftCondition) => void;+ onRemove: () => void;+}) => {+ const { subject } = findSubject(catalog, condition.connectionId, condition.subject);+ const constraint = subject?.constraints.find(+ (candidate) => candidate.id === condition.constraint+ );+ const error = showErrors ? getConditionError(condition, catalog) : null;++ // Other conditions on the same subject narrow this one's options, like statuses for a picked project+ const siblings = Object.fromEntries(+ rule.conditions+ .filter(+ (other) =>+ other.key !== condition.key &&+ other.connectionId === condition.connectionId &&+ other.subject === condition.subject &&+ other.values.length > 0+ )+ .map((other) => [other.constraint, other.values])+ );++ return (+ <div className="flex flex-col gap-1 py-1.5 pr-1.5 pl-2.5">+ <div className="flex min-h-7 flex-wrap items-center gap-x-3 gap-y-1">+ <Badge variant="neutral">{subject?.label ?? "Unavailable record"}</Badge>+ <span className="text-sm text-foreground">{constraint?.label ?? condition.constraint}</span>+ {constraint && constraint.value !== AutoApprovalConstraintValue.None && (+ <div className="max-w-72 min-w-40 flex-1">+ <AutoApprovalValuePicker+ policyType={policyType}+ scope={scope}+ scopeId={scopeId}+ connectionId={condition.connectionId}+ subject={condition.subject}+ constraint={constraint}+ values={condition.values}+ siblings={siblings}+ onChange={(values) => onChange({ ...condition, values })}+ isError={Boolean(error)}+ />+ </div>+ )}+ <IconButton+ variant="ghost"+ size="xs"+ aria-label="Remove condition"+ className="ml-auto text-muted hover:text-danger"+ onClick={onRemove}+ >+ <X className="size-4" />+ </IconButton>+ </div>+ {error && <p className="px-1.5 text-xs text-danger">{error}</p>}+ </div>+ );+};++export const AutoApprovalRuleCard = ({+ index,+ rule,+ inputs,+ catalog,+ policyType,+ scope,+ scopeId,+ showErrors,+ onChange,+ onRemove+}: Props) => {+ const choices = getSubjectChoices(inputs, catalog);+ const ruleError = showErrors ? getRuleError(rule, catalog) : null;+ const unbound = getUnboundInputSubjects(rule, catalog);++ // Each check appears once per rule, so the menu only offers the ones not added yet+ const menuGroups = choices+ .map((choice) => ({+ choice,+ constraints:+ findSubject(catalog, choice.connectionId, choice.subject).subject?.constraints.filter(+ (constraint) =>+ !rule.conditions.some(+ (condition) =>+ condition.connectionId === choice.connectionId &&+ condition.subject === choice.subject &&+ condition.constraint === constraint.id+ )+ ) ?? []+ }))+ .filter((group) => group.constraints.length > 0);++ let addConditionBlocker: string | undefined;+ if (choices.length === 0) {+ addConditionBlocker = "Add a field under Request Information first, so rules can check it.";+ } else if (menuGroups.length === 0) {+ addConditionBlocker = "Every available check is already in this rule.";+ }++ const updateCondition = (next: TDraftCondition) =>+ onChange({+ ...rule,+ conditions: rule.conditions.map((condition) =>+ condition.key === next.key ? next : condition+ )+ });++ const addCondition = (condition: Omit<TDraftCondition, "key" | "values">) =>+ onChange({+ ...rule,+ conditions: [...rule.conditions, { key: newKey(), values: [], ...condition }]+ });++ return (+ <div className="rounded-md border border-border">+ <div className="flex items-center gap-3 border-b border-border px-4 py-2.5">+ <span className="shrink-0 text-sm text-muted">Rule {index + 1}</span>+ <input+ value={rule.name}+ onChange={(e) => onChange({ ...rule, name: e.target.value })}+ placeholder="Name this rule"+ aria-label="Rule name"+ maxLength={128}+ className={cn(+ "-mx-1 min-w-0 flex-1 rounded-sm bg-transparent px-1 py-0.5 text-sm text-foreground outline-none placeholder:text-muted hover:bg-foreground/5 focus:bg-foreground/5",+ showErrors && !rule.name.trim() && "placeholder:text-danger"+ )}+ />+ <IconButton+ variant="ghost"+ size="xs"+ aria-label="Remove rule"+ className="text-muted hover:text-danger"+ onClick={onRemove}+ >+ <Trash2 className="size-4" />+ </IconButton>+ </div>++ <div className="grid grid-cols-[7rem_minmax(0,1fr)] items-baseline gap-x-6 gap-y-5 p-4">+ <SectionLabel>When</SectionLabel>+ <p className="text-sm text-foreground">The request is submitted</p>++ <SectionLabel>Conditions</SectionLabel>+ <div className="flex flex-col items-start gap-2">+ {rule.conditions.length > 0 && (+ <div className="flex w-full flex-col divide-y divide-border rounded-md border border-border">+ {rule.conditions.map((condition) => (+ <ConditionRow+ key={condition.key}+ condition={condition}+ rule={rule}+ catalog={catalog}+ policyType={policyType}+ scope={scope}+ scopeId={scopeId}+ showErrors={showErrors}+ onChange={updateCondition}+ onRemove={() =>+ onChange({+ ...rule,+ conditions: rule.conditions.filter(+ (candidate) => candidate.key !== condition.key+ )+ })+ }+ />+ ))}+ </div>+ )}++ {unbound.map((condition) => {+ const { subject } = findSubject(catalog, condition.connectionId, condition.subject);+ return (+ <div+ key={`${condition.connectionId}:${condition.subject}`}+ className="flex max-w-full items-center gap-2 rounded-md border border-warning/20 bg-warning/5 px-2.5 py-1.5 text-xs"+ >+ <ShieldAlert className="size-3.5 shrink-0 text-warning" />+ <span className="text-muted">+ Anyone could link someone else's {subject?.label ?? "record"}.+ </span>+ <Button+ type="button"+ variant="text"+ size="xs"+ className="shrink-0 font-medium"+ onClick={() =>+ addCondition({+ connectionId: condition.connectionId,+ subject: condition.subject,+ constraint: ASSIGNED_TO_REQUESTER_CONSTRAINT+ })+ }+ >+ Add assignee check+ </Button>+ </div>+ );+ })}++ <DisabledReason reason={addConditionBlocker}>+ <DropdownMenu>+ <DropdownMenuTrigger asChild disabled={Boolean(addConditionBlocker)}>+ <Button type="button" variant="ghost" size="sm" className="-ml-2.5">+ <Plus />+ Add Condition+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ {menuGroups.map(({ choice, constraints }, groupIndex) => (+ <Fragment key={choice.key}>+ {groupIndex > 0 && <DropdownMenuSeparator />}+ {menuGroups.length > 1 && (+ <DropdownMenuLabel>+ {choice.label} · {choice.via}+ </DropdownMenuLabel>+ )}+ {constraints.map((constraint) => (+ <DropdownMenuItem+ key={constraint.id}+ onClick={() =>+ addCondition({+ connectionId: choice.connectionId,+ subject: choice.subject,+ constraint: constraint.id+ })+ }+ >+ {choice.label} {constraint.label}+ {constraint.value !== AutoApprovalConstraintValue.None && "..."}+ </DropdownMenuItem>+ ))}+ </Fragment>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </DisabledReason>++ {ruleError && <p className="text-xs text-danger">{ruleError}</p>}+ </div>++ <SectionLabel>Then</SectionLabel>+ <p className="text-sm text-foreground">Approve automatically</p>+ </div>+ </div>+ );+};diff --git a/frontend/src/pages/pam/components/auto-approval/AutoApprovalValuePicker.tsx b/frontend/src/pages/pam/components/auto-approval/AutoApprovalValuePicker.tsxnew file mode 100644index 0000000000..322ec813be--- /dev/null+++ b/frontend/src/pages/pam/components/auto-approval/AutoApprovalValuePicker.tsx@@ -0,0 +1,131 @@+import { useMemo, useState } from "react";+import { useQuery } from "@tanstack/react-query";++import { Combobox } from "@app/components/v3";+import { useDebounce } from "@app/hooks";+import {+ approvalPolicyQuery,+ ApprovalPolicyScope,+ ApprovalPolicyType,+ AutoApprovalConstraintValue,+ TAutoApprovalCatalogConstraint,+ TAutoApprovalOption+} from "@app/hooks/api/approvalPolicies";++type Props = {+ policyType: ApprovalPolicyType;+ scope: ApprovalPolicyScope;+ scopeId: string;+ connectionId: string;+ subject: string;+ constraint: TAutoApprovalCatalogConstraint;+ values: string[];+ // Values picked in the rule's other conditions, which narrow these options+ siblings: Record<string, string[]>;+ onChange: (values: string[]) => void;+ isError?: boolean;+};++const toOption = (value: string): TAutoApprovalOption => ({ value, label: value });++export const AutoApprovalValuePicker = ({+ policyType,+ scope,+ scopeId,+ connectionId,+ subject,+ constraint,+ values,+ siblings,+ onChange,+ isError+}: Props) => {+ const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search, 300);++ const {+ data: options = [],+ isFetching,+ isError: isOptionsError+ } = useQuery({+ ...approvalPolicyQuery.autoApprovalOptions({+ policyType,+ scope,+ scopeId,+ connectionId,+ subject,+ constraint: constraint.id,+ search: debouncedSearch.trim(),+ siblings+ }),+ enabled: constraint.hasOptions,+ staleTime: 30_000,+ retry: false+ });++ const selected = useMemo(+ () =>+ values.map((value) => options.find((option) => option.value === value) ?? toOption(value)),+ [values, options]+ );++ // Values are free text too: a label can be new, and the service may be unreachable while editing+ const creation = {+ onCreate: (input: string) => {+ const value = input.trim();+ if (!value || values.includes(value)) return;+ onChange(+ constraint.value === AutoApprovalConstraintValue.Many ? [...values, value] : [value]+ );+ },+ formatLabel: (input: string) => `Use "${input.trim()}"`+ };++ const emptyMessage = isOptionsError+ ? "Couldn't load values. Type one instead."+ : "No matches. Type a value to use it.";++ if (constraint.value === AutoApprovalConstraintValue.Many) {+ return (+ <Combobox+ multiple+ singleLine+ aria-label={constraint.label}+ options={options}+ value={selected}+ onValueChange={(next) => onChange(next.map((option) => option.value))}+ getOptionValue={(option) => option.value}+ getOptionLabel={(option) => option.label}+ shouldFilter={false}+ includeMissingSelectedOptions+ onInputValueChange={setSearch}+ isLoading={isFetching}+ isError={isError}+ size="sm"+ emptyMessage={emptyMessage}+ placeholder="Choose values..."+ creation={creation}+ />+ );+ }++ return (+ <Combobox+ aria-label={constraint.label}+ options={options}+ value={selected[0] ?? null}+ onValueChange={(option) => onChange(option ? [option.value] : [])}+ getOptionValue={(option) => option.value}+ getOptionLabel={(option) => option.label}+ shouldFilter={false}+ includeMissingSelectedOptions+ onInputValueChange={setSearch}+ isLoading={isFetching}+ isError={isError}+ size="sm"+ emptyMessage={emptyMessage}+ placeholder="Choose a value..."+ creation={creation}+ />+ );+};diff --git a/frontend/src/pages/pam/components/auto-approval/autoApprovalDraft.ts b/frontend/src/pages/pam/components/auto-approval/autoApprovalDraft.tsnew file mode 100644index 0000000000..112498ccc1--- /dev/null+++ b/frontend/src/pages/pam/components/auto-approval/autoApprovalDraft.ts@@ -0,0 +1,142 @@+import {+ AUTO_APPROVAL_REQUESTER_SUBJECT,+ AutoApprovalConstraintValue,+ TAutoApprovalCatalogConnection,+ TAutoApprovalCatalogSubject,+ TAutoApprovalConfig,+ TAutoApprovalConfigResponse+} from "@app/hooks/api/approvalPolicies";++// Client keys keep React rows stable while rules and conditions are edited+export type TDraftCondition = {+ key: string;+ connectionId: string;+ subject: string;+ constraint: string;+ values: string[];+};++export type TDraftRule = { key: string; name: string; conditions: TDraftCondition[] };++export type TAutoApprovalDraft = {+ inputs: { connectionId: string; subject: string }[];+ rules: TDraftRule[];+};++// Mirrors the Jira provider's constraint; other providers name theirs the same way+export const ASSIGNED_TO_REQUESTER_CONSTRAINT = "assigned-to-requester";++export const newKey = () => crypto.randomUUID();++export const EMPTY_AUTO_APPROVAL_DRAFT: TAutoApprovalDraft = { inputs: [], rules: [] };++export const toAutoApprovalDraft = (config?: TAutoApprovalConfigResponse): TAutoApprovalDraft => ({+ inputs: (config?.inputs ?? []).map(({ connectionId, subject }) => ({ connectionId, subject })),+ rules: (config?.rules ?? []).map((rule) => ({+ key: rule.id,+ name: rule.name,+ conditions: rule.conditions.map((condition) => ({+ key: condition.id,+ connectionId: condition.connectionId,+ subject: condition.subject,+ constraint: condition.constraint,+ values: condition.values+ }))+ }))+});++export const toAutoApprovalConfig = (draft: TAutoApprovalDraft): TAutoApprovalConfig => ({+ inputs: draft.inputs,+ rules: draft.rules.map((rule) => ({+ name: rule.name.trim(),+ conditions: rule.conditions.map(({ connectionId, subject, constraint, values }) => ({+ connectionId,+ subject,+ constraint,+ values+ }))+ }))+});++// Compared without client keys, so reordering keys alone never reads as a change+export const serializeAutoApprovalDraft = (draft: TAutoApprovalDraft) =>+ JSON.stringify(toAutoApprovalConfig(draft));++export const findSubject = (+ catalog: TAutoApprovalCatalogConnection[] | undefined,+ connectionId: string,+ subjectId: string+): { connection?: TAutoApprovalCatalogConnection; subject?: TAutoApprovalCatalogSubject } => {+ const connection = catalog?.find((candidate) => candidate.id === connectionId);+ return {+ connection,+ subject: connection?.subjects.find((candidate) => candidate.id === subjectId)+ };+};++export const isRequesterSubject = (subjectId: string) =>+ subjectId === AUTO_APPROVAL_REQUESTER_SUBJECT;++export const getConditionError = (+ condition: TDraftCondition,+ catalog: TAutoApprovalCatalogConnection[] | undefined+): string | null => {+ if (!condition.connectionId || !condition.subject) return "Choose what to check";+ if (!condition.constraint) return "Choose a check";++ const constraint = findSubject(+ catalog,+ condition.connectionId,+ condition.subject+ ).subject?.constraints.find((candidate) => candidate.id === condition.constraint);+ if (!constraint) return null;+ if (constraint.value === AutoApprovalConstraintValue.One && condition.values.length !== 1) {+ return "Choose a value";+ }+ if (constraint.value === AutoApprovalConstraintValue.Many && condition.values.length === 0) {+ return "Choose at least one value";+ }+ return null;+};++export const getRuleError = (+ rule: TDraftRule,+ catalog: TAutoApprovalCatalogConnection[] | undefined+): string | null => {+ if (!rule.name.trim()) return "Name this rule";+ if (rule.conditions.length === 0) {+ return "Add at least one condition, or this rule would approve every request";+ }+ return rule.conditions.some((condition) => getConditionError(condition, catalog))+ ? "Finish every condition"+ : null;+};++// A ticket condition without an assignee check lets anyone link someone else's approved ticket+export const getUnboundInputSubjects = (+ rule: TDraftRule,+ catalog: TAutoApprovalCatalogConnection[] | undefined+) => {+ const linked = new Map<string, TDraftCondition>();+ rule.conditions+ .filter((condition) => condition.subject && !isRequesterSubject(condition.subject))+ .forEach((condition) =>+ linked.set(`${condition.connectionId}:${condition.subject}`, condition)+ );++ return [...linked.values()].filter((condition) => {+ const { subject } = findSubject(catalog, condition.connectionId, condition.subject);+ const offersAssigneeCheck = subject?.constraints.some(+ (constraint) => constraint.id === ASSIGNED_TO_REQUESTER_CONSTRAINT+ );+ return (+ offersAssigneeCheck &&+ !rule.conditions.some(+ (other) =>+ other.connectionId === condition.connectionId &&+ other.subject === condition.subject &&+ other.constraint === ASSIGNED_TO_REQUESTER_CONSTRAINT+ )+ );+ });+};diff --git a/frontend/src/pages/pam/components/policyEditors/index.tsx b/frontend/src/pages/pam/components/policyEditors/index.tsxindex 3845d4ca1c..a658d0f300 100644--- a/frontend/src/pages/pam/components/policyEditors/index.tsx+++ b/frontend/src/pages/pam/components/policyEditors/index.tsx@@ -27,6 +27,7 @@ const CommandBlockingEditor = ({ accountType, ...props }: PolicyEditorProps) =>export const POLICY_EDITORS: Partial<Record<PamPolicyType, ComponentType<PolicyEditorProps>>> = {[PamPolicyType.RequiresApproval]: BooleanPolicyEditor,+ [PamPolicyType.AllowAutoApproval]: BooleanPolicyEditor,[PamPolicyType.AllowBreakGlass]: BooleanPolicyEditor,[PamPolicyType.RequireMfa]: BooleanPolicyEditor,[PamPolicyType.RequireReason]: BooleanPolicyEditor,