Skip to content

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

feat(pam): iam auth for postgres

Andrey634b0022d62d
diff --git a/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.ts b/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.ts
index 771d783eb6..59d9caeca8 100644
--- a/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.ts
+++ b/backend/src/ee/services/pam-account-rotation/pam-rotation-handlers.ts
@@ -6,7 +6,7 @@ import {
SQL_CONNECTION_ALTER_LOGIN_STATEMENT
} from "@app/services/app-connection/shared/sql";
-import { PamAccountType } from "../pam/pam-enums";
+import { PamAccountType, PamPostgresAuthMethod } from "../pam/pam-enums";
import { TWindowsAdConnectionDetails, TWindowsConnectionDetails } from "../pam-account/pam-account-schemas";
import { DEFAULT_WINRM_PORT, ldapBindCheckViaGateway, winrmRpcWithGateway } from "../pam-discovery/pam-discovery-fns";
import {
@@ -61,6 +61,12 @@ const sqlRotationHandler: TPamRotationHandler = {
if (accountType === PamAccountType.MsSQL && authMethod !== "sql-login") {
throw new BadRequestError({ message: "MSSQL rotation supports SQL Server authentication only" });
}
+ // An IAM login has no stored password: the gateway mints a short-lived token for each connection
+ if (accountType === PamAccountType.Postgres && authMethod === PamPostgresAuthMethod.AwsIam) {
+ throw new BadRequestError({
+ message: "PostgreSQL accounts using AWS IAM authentication have no password to rotate"
+ });
+ }
},
applyPasswordChange: async (input, deps) => {
diff --git a/backend/src/ee/services/pam-account/pam-account-connection-test.ts b/backend/src/ee/services/pam-account/pam-account-connection-test.ts
index 18e70fdfa4..24d0cff62d 100644
--- a/backend/src/ee/services/pam-account/pam-account-connection-test.ts
+++ b/backend/src/ee/services/pam-account/pam-account-connection-test.ts
@@ -24,8 +24,11 @@ export type TestConnectionRequest =
| {
mode: TestConnectionMode.SQL;
dialect: "postgres" | "mysql" | "mssql";
+ authMethod?: string;
username: string;
password?: string;
+ awsRegion?: string;
+ roleArn?: string;
database: string;
sslEnabled?: boolean;
sslRejectUnauthorized?: boolean;
@@ -105,7 +108,13 @@ export const buildGatewayConnectionTest = async (
sslRejectUnauthorized?: boolean;
sslCertificate?: string;
};
- const c = creds as { authMethod?: string; username: string; password?: string } | null;
+ const c = creds as {
+ authMethod?: string;
+ username: string;
+ password?: string;
+ awsRegion?: string;
+ roleArn?: string;
+ } | null;
if (!c || (accountType === PamAccountType.MsSQL && c.authMethod !== "sql-login")) return tcp(host, port);
return {
host,
@@ -113,8 +122,11 @@ export const buildGatewayConnectionTest = async (
request: {
mode: TestConnectionMode.SQL,
dialect: SQL_DIALECTS[accountType],
+ authMethod: c.authMethod,
username: c.username,
password: c.password,
+ awsRegion: c.awsRegion,
+ roleArn: c.roleArn,
database: cd.database,
sslEnabled: cd.sslEnabled,
sslRejectUnauthorized: cd.sslRejectUnauthorized,
diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.test.ts b/backend/src/ee/services/pam-account/pam-account-schemas.test.ts
index 3e950577a8..bc6b1e808e 100644
--- a/backend/src/ee/services/pam-account/pam-account-schemas.test.ts
+++ b/backend/src/ee/services/pam-account/pam-account-schemas.test.ts
@@ -1,14 +1,17 @@
import { describe, expect, test } from "vitest";
-import { PamAccountType } from "../pam/pam-enums";
+import { PamAccountType, PamPostgresAuthMethod } from "../pam/pam-enums";
import {
accountTypeRequiresRecording,
+ applyForcedFields,
buildPamAccountTypeMetadata,
getAccountAccessibilityIssues,
isCredentialConfigured,
PamAccountAccessibilityIssue,
PamAccountTypeMetadataSchema,
- PamFieldDescriptorSchema
+ PamFieldDescriptorSchema,
+ sanitizeCredentials,
+ validateCredentials
} from "./pam-account-schemas";
// These assertions exercise the Zod-introspection path (buildPamAccountTypeMetadata reads schema internals to derive field descriptors)
@@ -77,8 +80,29 @@ describe("buildPamAccountTypeMetadata", () => {
expect(fieldByKey(postgres!.credentialFields, "password")).toMatchObject({
widget: "password",
secret: true,
- required: false
+ required: false,
+ showWhen: { field: "authMethod", equals: "password" }
+ });
+ expect(fieldByKey(postgres!.credentialFields, "awsRegion")).toMatchObject({
+ widget: "text",
+ required: true,
+ showWhen: { field: "authMethod", equals: "aws-iam" }
});
+ expect(fieldByKey(postgres!.credentialFields, "roleArn")).toMatchObject({
+ required: true,
+ showWhen: { field: "authMethod", equals: "aws-iam" }
+ });
+ });
+
+ test("pins Postgres SSL to the auth method that requires it, across field groups", () => {
+ const postgres = byType.get(PamAccountType.Postgres);
+ expect(fieldByKey(postgres!.connectionFields, "sslEnabled")?.forceWhen).toEqual([
+ {
+ when: { field: "credentials.authMethod", equals: "aws-iam" },
+ value: true,
+ reason: expect.any(String) as string
+ }
+ ]);
});
test("only advertises connection string schemes for types that accept them", () => {
@@ -247,6 +271,87 @@ describe("isCredentialConfigured", () => {
});
});
+describe("credentials without an auth method", () => {
+ test("Postgres credentials parse as password auth", () => {
+ expect(validateCredentials(PamAccountType.Postgres, { username: "u", password: "p" })).toEqual({
+ authMethod: PamPostgresAuthMethod.Password,
+ username: "u",
+ password: "p"
+ });
+ });
+
+ test("an explicit auth method is left alone", () => {
+ expect(
+ validateCredentials(PamAccountType.Postgres, {
+ authMethod: PamPostgresAuthMethod.AwsIam,
+ username: "iam_user",
+ awsRegion: "us-east-1",
+ roleArn: "arn:aws:iam::123456789012:role/pam"
+ })
+ ).toEqual({
+ authMethod: PamPostgresAuthMethod.AwsIam,
+ username: "iam_user",
+ awsRegion: "us-east-1",
+ roleArn: "arn:aws:iam::123456789012:role/pam"
+ });
+ });
+
+ test("switching to AWS IAM drops the password that is no longer part of the credential", () => {
+ expect(
+ validateCredentials(PamAccountType.Postgres, {
+ authMethod: PamPostgresAuthMethod.AwsIam,
+ username: "u",
+ password: "stale",
+ awsRegion: "us-east-1",
+ roleArn: "arn:aws:iam::123456789012:role/pam"
+ })
+ ).not.toHaveProperty("password");
+ });
+
+ test("account types that never changed shape still reject a missing discriminator", () => {
+ expect(() => validateCredentials(PamAccountType.SSH, { username: "u", password: "p" })).toThrow();
+ });
+
+ test("sanitized credentials report the effective auth method", () => {
+ expect(sanitizeCredentials(PamAccountType.Postgres, { username: "u", password: "p" })).toMatchObject({
+ authMethod: PamPostgresAuthMethod.Password,
+ username: "u"
+ });
+ });
+});
+
+describe("applyForcedFields", () => {
+ const forPostgres = (credentials: Record<string, unknown>, connectionDetails: Record<string, unknown> = {}) =>
+ applyForcedFields(PamAccountType.Postgres, {
+ connectionDetails: { host: "db.example.com", sslEnabled: false, ...connectionDetails },
+ credentials
+ });
+
+ test("AWS IAM turns SSL on, since the login cannot work without it", () => {
+ const result = forPostgres({ authMethod: PamPostgresAuthMethod.AwsIam, username: "u", awsRegion: "us-east-1" });
+ expect(result.connectionDetails.sslEnabled).toBe(true);
+ });
+
+ test("password auth leaves the connection alone", () => {
+ const result = forPostgres({ authMethod: PamPostgresAuthMethod.Password, username: "u", password: "p" });
+ expect(result.connectionDetails.sslEnabled).toBe(false);
+ });
+
+ test("credentials the caller passed are never mutated", () => {
+ const connectionDetails = { host: "db.example.com", sslEnabled: false };
+ applyForcedFields(PamAccountType.Postgres, {
+ connectionDetails,
+ credentials: { authMethod: PamPostgresAuthMethod.AwsIam, username: "u", awsRegion: "us-east-1" }
+ });
+ expect(connectionDetails.sslEnabled).toBe(false);
+ });
+
+ test("account types with no forced fields pass their values through", () => {
+ const values = { connectionDetails: { host: "db", sslEnabled: false }, credentials: { username: "u" } };
+ expect(applyForcedFields(PamAccountType.MySQL, values)).toEqual(values);
+ });
+});
+
describe("getAccountAccessibilityIssues", () => {
test("recording is only required for account types that stream to a bucket", () => {
expect(accountTypeRequiresRecording(PamAccountType.Windows)).toBe(true);
diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.ts b/backend/src/ee/services/pam-account/pam-account-schemas.ts
index 6376140e1b..6d889c941a 100644
--- a/backend/src/ee/services/pam-account/pam-account-schemas.ts
+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts
@@ -7,7 +7,7 @@ import { z } from "zod";
import { BadRequestError } from "@app/lib/errors";
-import { GcpServiceAccountAuthMethod, PamAccountType, PamSshAuthMethod } from "../pam/pam-enums";
+import { GcpServiceAccountAuthMethod, PamAccountType, PamPostgresAuthMethod, PamSshAuthMethod } from "../pam/pam-enums";
import { getApplicablePolicies, PamPolicyDescriptorSchema } from "../pam/pam-policies";
import {
PamAccountSettingsOverridesSchema,
@@ -49,6 +49,37 @@ const delimitedStringList = z.preprocess(
z.array(z.string().trim().min(1).max(255).regex(hostPattern, "Must be a valid hostname or IP address")).min(1)
);
+// A type that gained its authMethod discriminator after launch has stored rows without one,
+// which a discriminated union rejects outright. Defaulting it keeps them parsing
+// everywhere they are re-read, including the rotation cron, which validates the stored blob every run.
+const LEGACY_AUTH_METHODS = {
+ [PamAccountType.Postgres]: PamPostgresAuthMethod.Password
+} as const satisfies Partial<Record<PamAccountType, string>>;
+
+type TLegacyAuthMethodType = keyof typeof LEGACY_AUTH_METHODS;
+
+const withLegacyAuthMethod = <T extends z.ZodTypeAny>(accountType: TLegacyAuthMethodType, schema: T) =>
+ z.preprocess(
+ (value) =>
+ typeof value === "object" && value !== null && !Array.isArray(value) && !("authMethod" in value)
+ ? { ...value, authMethod: LEGACY_AUTH_METHODS[accountType] }
+ : value,
+ schema
+ );
+
+// Same defaulting, for credentials handed straight to the gateway without being re-parsed
+export const normalizeCredentialAuthMethod = (
+ accountType: PamAccountType,
+ credentials: Record<string, unknown>
+): Record<string, unknown> => {
+ const fallback = LEGACY_AUTH_METHODS[accountType as TLegacyAuthMethodType];
+ if (!fallback || credentials.authMethod !== undefined) return credentials;
+ return { ...credentials, authMethod: fallback };
+};
+
+type TFieldConditionHint = { field: string; equals: string | boolean };
+type TFieldForcedRuleHint = { when: TFieldConditionHint; value: string | number | boolean; reason: string };
+
// Source of truth for account types: per-type schemas + sparse UI hints
export const ACCOUNT_TYPE_CONFIGS = {
[PamAccountType.Postgres]: {
@@ -63,19 +94,67 @@ export const ACCOUNT_TYPE_CONFIGS = {
sslRejectUnauthorized: z.boolean(),
sslCertificate: optionalTrimmedString
}),
- credentials: z.object({
- username: z.string().trim().min(1).max(63),
- password: z
- .string()
- .trim()
- .max(256)
- .transform((v) => v || undefined)
- .optional()
+ credentials: withLegacyAuthMethod(
+ PamAccountType.Postgres,
+ z.discriminatedUnion("authMethod", [
+ z.object({
+ authMethod: z.literal(PamPostgresAuthMethod.Password),
+ username: z.string().trim().min(1).max(63),
+ password: z
+ .string()
+ .trim()
+ .max(256)
+ .transform((v) => v || undefined)
+ .optional()
+ }),
+ z.object({
+ authMethod: z.literal(PamPostgresAuthMethod.AwsIam),
+ username: z.string().trim().min(1).max(63),
+ awsRegion: z
+ .string()
+ .trim()
+ .min(1)
+ .max(32)
+ .regex(new RE2(/^[a-z0-9-]+$/), "Must be a valid AWS region"),
+ roleArn: z.string().trim().min(1).max(2048)
+ })
+ ])
+ ),
+ sanitizedCredentials: z.object({
+ authMethod: z.string().optional(),
+ username: z.string(),
+ awsRegion: z.string().optional(),
+ roleArn: z.string().optional()
}),
- sanitizedCredentials: z.object({ username: z.string() }),
ui: {
port: { defaultValue: 5432 },
- sslEnabled: { label: "SSL Enabled" },
+ authMethod: {
+ label: "Auth Method",
+ defaultValue: PamPostgresAuthMethod.Password,
+ options: [
+ { label: "Password", value: PamPostgresAuthMethod.Password },
+ { label: "AWS IAM (RDS / Aurora)", value: PamPostgresAuthMethod.AwsIam }
+ ]
+ },
+ awsRegion: {
+ label: "AWS Region",
+ tooltip: "The region of the RDS or Aurora instance, used to sign the authentication token (e.g. us-east-1)."
+ },
+ roleArn: {
+ label: "Role ARN",
+ tooltip:
+ "The IAM role the gateway assumes to generate the authentication token. It needs rds-db:connect on this account's database user, and its trust policy must allow the gateway's own identity."
+ },
+ sslEnabled: {
+ label: "SSL Enabled",
+ forceWhen: [
+ {
+ when: { field: "credentials.authMethod", equals: PamPostgresAuthMethod.AwsIam },
+ value: true,
+ reason: "AWS IAM authentication requires an encrypted connection."
+ }
+ ]
+ },
sslRejectUnauthorized: {
label: "Reject Unauthorized",
showWhen: { field: "sslEnabled", equals: true }
@@ -83,7 +162,9 @@ export const ACCOUNT_TYPE_CONFIGS = {
sslCertificate: {
label: "SSL Certificate",
widget: PamFieldWidget.Textarea,
- showWhen: { field: "sslEnabled", equals: true }
+ showWhen: { field: "sslEnabled", equals: true },
+ tooltip:
+ "The CA certificate used to verify the server. Amazon RDS and Aurora publish theirs at https://truststore.pki.rds.amazonaws.com."
},
password: { widget: PamFieldWidget.Password, secret: true }
}
@@ -679,7 +760,8 @@ export const ACCOUNT_TYPE_CONFIGS = {
secret?: boolean;
optional?: boolean;
defaultValue?: string | number | boolean;
- showWhen?: { field: string; equals: string | boolean };
+ showWhen?: TFieldConditionHint;
+ forceWhen?: readonly TFieldForcedRuleHint[];
tooltip?: string;
options?: { label: string; value: string }[];
}
@@ -744,7 +826,8 @@ export const validateCredentials = (accountType: PamAccountType, data: unknown)
};
export const sanitizeCredentials = (accountType: PamAccountType, data: unknown) => {
- return getAccountTypeConfig(accountType).sanitizedCredentials.parse(data) as z.output<
+ const normalized = normalizeCredentialAuthMethod(accountType, (data ?? {}) as Record<string, unknown>);
+ return getAccountTypeConfig(accountType).sanitizedCredentials.parse(normalized) as z.output<
(typeof ACCOUNT_TYPE_CONFIGS)[TSupportedAccountType]["sanitizedCredentials"]
>;
};
@@ -963,6 +1046,13 @@ export const parseInternalMetadata = (accountType: PamAccountType, data: unknown
// -- Frontend field metadata derived from the schemas above
+// A bare `field` resolves within the field's own group; qualify it ("credentials.authMethod") to
+// reference the other group
+const PamFieldConditionSchema = z.object({
+ field: z.string(),
+ equals: z.union([z.string(), z.boolean()])
+});
+
export const PamFieldDescriptorSchema = z.object({
key: z.string(),
label: z.string(),
@@ -976,7 +1066,19 @@ export const PamFieldDescriptorSchema = z.object({
defaultValue: z.union([z.string(), z.number(), z.boolean()]).optional(),
// Only render when the referenced field equals this value
- showWhen: z.object({ field: z.string(), equals: z.union([z.string(), z.boolean()]) }).optional(),
+ showWhen: PamFieldConditionSchema.optional(),
+
+ // Value the field is pinned to while the condition holds. The server applies these rules before
+ // validating, so a hand-written request cannot bypass one.
+ forceWhen: z
+ .array(
+ z.object({
+ when: PamFieldConditionSchema,
+ value: z.union([z.string(), z.number(), z.boolean()]),
+ reason: z.string()
+ })
+ )
+ .optional(),
// Info tooltip shown next to the label
tooltip: z.string().optional()
@@ -1006,7 +1108,8 @@ type TFieldUiHint = {
secret?: boolean;
optional?: boolean;
defaultValue?: string | number | boolean;
- showWhen?: PamFieldDescriptor["showWhen"];
+ showWhen?: TFieldConditionHint;
+ forceWhen?: readonly TFieldForcedRuleHint[];
tooltip?: string;
options?: { label: string; value: string }[];
};
@@ -1073,21 +1176,24 @@ const describeField = (
: {}),
...(hint.defaultValue !== undefined ? { defaultValue: hint.defaultValue } : {}),
...(resolvedShowWhen ? { showWhen: resolvedShowWhen } : {}),
+ ...(hint.forceWhen ? { forceWhen: [...hint.forceWhen] } : {}),
...(hint.tooltip ? { tooltip: hint.tooltip } : {})
};
};
const fieldsFromSchema = (schema: z.ZodTypeAny, ui: Record<string, TFieldUiHint> = {}): PamFieldDescriptor[] => {
- const { typeName } = schema._def as { typeName?: string };
+ // Peels wrappers such as the legacy-discriminator preprocess so the described shape is the one underneath
+ const { base } = unwrapField(schema);
+ const { typeName } = base._def as { typeName?: string };
if (typeName === "ZodObject") {
- const { shape } = schema as z.ZodObject<z.ZodRawShape>;
+ const { shape } = base as z.ZodObject<z.ZodRawShape>;
return Object.entries(shape).map(([key, fieldSchema]) => describeField(key, fieldSchema, ui));
}
// Discriminated union (e.g. SSH authMethod)
if (typeName === "ZodDiscriminatedUnion") {
- const def = schema._def as {
+ const def = base._def as {
discriminator: string;
options: z.ZodObject<z.ZodRawShape>[];
};
@@ -1158,10 +1264,58 @@ export const buildPamAccountTypeMetadata = (webAccessSupportedTypes: Set<PamAcco
applicablePolicies: getApplicablePolicies(type)
}));
-export const isCredentialConfigured = (accountType: PamAccountType, credentials: Record<string, unknown>): boolean => {
+export type TPamFieldGroup = "connectionDetails" | "credentials";
+export type TPamFieldValues = Record<TPamFieldGroup, Record<string, unknown>>;
+
+const conditionHolds = (
+ condition: { field: string; equals: string | boolean },
+ group: TPamFieldGroup,
+ values: TPamFieldValues
+): boolean => {
+ const separatorIdx = condition.field.indexOf(".");
+ const [targetGroup, key] =
+ separatorIdx === -1
+ ? [group, condition.field]
+ : [condition.field.slice(0, separatorIdx) as TPamFieldGroup, condition.field.slice(separatorIdx + 1)];
+
+ return values[targetGroup]?.[key] === condition.equals;
+};
+
+// Conditions read the caller's values rather than the accumulating result, so rules cannot chain off
+// one another and their order never matters.
+export const applyForcedFields = (accountType: PamAccountType, values: TPamFieldValues): TPamFieldValues => {
+ const config = getAccountTypeConfig(accountType);
+ const fieldsByGroup: Record<TPamFieldGroup, PamFieldDescriptor[]> = {
+ connectionDetails: fieldsFromSchema(config.connectionDetails, config.ui),
+ credentials: fieldsFromSchema(config.credentials, config.ui)
+ };
+
+ const result: TPamFieldValues = {
+ connectionDetails: { ...values.connectionDetails },
+ credentials: { ...values.credentials }
+ };
+
+ (Object.keys(fieldsByGroup) as TPamFieldGroup[]).forEach((group) => {
+ fieldsByGroup[group].forEach((field) => {
+ const rule = field.forceWhen?.find((candidate) => conditionHolds(candidate.when, group, values));
+ if (rule) result[group][field.key] = rule.value;
+ });
+ });
+
+ return result;
+};
+
+export const isCredentialConfigured = (
+ accountType: PamAccountType,
+ rawCredentials: Record<string, unknown>
+): boolean => {
const config = ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType];
if (!config) return false;
+ // Callers include paths that read the stored blob directly, where an older account has no auth
+ // method and would match none of the variants' secret fields
+ const credentials = normalizeCredentialAuthMethod(accountType, rawCredentials);
+
const applicableSecretFields = fieldsFromSchema(config.credentials, config.ui).filter(
(field) => field.secret && (!field.showWhen || credentials[field.showWhen.field] === field.showWhen.equals)
);
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts
index b87482a420..e0d42216ff 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -46,8 +46,10 @@ import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
import { buildGatewayConnectionTest, CLOUD_CONNECTION_VALIDATORS } from "./pam-account-connection-test";
import { TPamAccountDALFactory } from "./pam-account-dal";
import {
+ applyForcedFields,
getAccountAccessibilityIssues,
isCredentialConfigured,
+ normalizeCredentialAuthMethod,
PamAccountAccessibilityIssue,
parseInternalMetadata,
sanitizeCredentials,
@@ -448,8 +450,12 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
ctx
);
- const validatedConnectionDetails = validateConnectionDetails(accountType, connectionDetails);
- const validatedCredentials = validateCredentials(accountType, credentials);
+ const forced = applyForcedFields(accountType, {
+ connectionDetails,
+ credentials: normalizeCredentialAuthMethod(accountType, credentials)
+ });
+ const validatedConnectionDetails = validateConnectionDetails(accountType, forced.connectionDetails);
+ const validatedCredentials = validateCredentials(accountType, forced.credentials);
assertPasswordMeetsRequirements(validatedCredentials, template.settings);
// discovery import creates accounts in bulk from a scan that already reached them, so it skips the test
@@ -627,37 +633,52 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
if (recordingConnectionId !== undefined) updateData.recordingConnectionId = recordingConnectionId;
if (settingsOverrides !== undefined) updateData.settingsOverrides = settingsOverrides;
- if (connectionDetails) {
- const validated = validateConnectionDetails(accountType, connectionDetails);
- updateData.encryptedConnectionDetails = await encrypt(projectId, validated);
- }
-
+ // Forced fields cross the two groups, so a change to either side is resolved against the merged
+ // view and both are rewritten
let principalChanged = false;
- if (credentials) {
+ let connectionTargetChanged = false;
+ let effectiveConnectionDetails: Record<string, unknown> | null = null;
+ let effectiveCredentials: Record<string, unknown> | null = null;
+
+ if (connectionDetails || credentials) {
+ const existingConnectionDetails = await decrypt(projectId, existing.encryptedConnectionDetails);
const existingCredentials = await decrypt(projectId, existing.encryptedCredentials);
- const validated = validateCredentials(accountType, { ...existingCredentials, ...credentials });
- const templateSettings = templateId
- ? (await pamAccountTemplateDAL.findById(templateId))?.settings
- : existing.templateSettings;
- assertPasswordMeetsRequirements(validated, templateSettings);
- updateData.encryptedCredentials = await encrypt(projectId, validated);
- updateData.credentialConfigured = isCredentialConfigured(accountType, validated);
+
+ const forced = applyForcedFields(accountType, {
+ connectionDetails: connectionDetails ?? existingConnectionDetails,
+ credentials: normalizeCredentialAuthMethod(accountType, { ...existingCredentials, ...(credentials ?? {}) })
+ });
+
+ effectiveConnectionDetails = validateConnectionDetails(accountType, forced.connectionDetails);
+ effectiveCredentials = validateCredentials(accountType, forced.credentials);
+
+ if (credentials) {
+ const templateSettings = templateId
+ ? (await pamAccountTemplateDAL.findById(templateId))?.settings
+ : existing.templateSettings;
+ assertPasswordMeetsRequirements(effectiveCredentials, templateSettings);
+ }
+
+ updateData.encryptedConnectionDetails = await encrypt(projectId, effectiveConnectionDetails);
+ updateData.encryptedCredentials = await encrypt(projectId, effectiveCredentials);
+ updateData.credentialConfigured = isCredentialConfigured(accountType, effectiveCredentials);
+
+ const oldConn = validateConnectionDetails(accountType, existingConnectionDetails) as {
+ host?: string;
+ port?: number;
+ };
+ const newConn = effectiveConnectionDetails as { host?: string; port?: number };
+ if (oldConn.host !== newConn.host || oldConn.port !== newConn.port) connectionTargetChanged = true;
+
const oldUsername = (existingCredentials as { username?: string }).username;
- const newUsername = (validated as { username?: string }).username;
+ const newUsername = (effectiveCredentials as { username?: string }).username;
if (oldUsername !== newUsername) principalChanged = true;
}
- let routingChanged =
+ const routingChanged =
+ connectionTargetChanged ||
(gatewayId !== undefined && gatewayId !== existing.gatewayId) ||
(gatewayPoolId !== undefined && gatewayPoolId !== existing.gatewayPoolId);
- if (connectionDetails) {
- const oldConn = validateConnectionDetails(
- accountType,
- await decrypt(projectId, existing.encryptedConnectionDetails)
- ) as { host?: string; port?: number };
- const newConn = validateConnectionDetails(accountType, connectionDetails) as { host?: string; port?: number };
- if (oldConn.host !== newConn.host || oldConn.port !== newConn.port) routingChanged = true;
- }
if ((routingChanged || principalChanged) && existing.rotationAccountId) {
updateData.rotationAccountId = null;
}
@@ -670,9 +691,9 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
gatewayPoolId !== undefined ||
templateId !== undefined
) {
- const effectiveConnectionDetails = connectionDetails
- ? validateConnectionDetails(accountType, connectionDetails)
- : validateConnectionDetails(accountType, await decrypt(projectId, existing.encryptedConnectionDetails));
+ const testConnectionDetails =
+ effectiveConnectionDetails ??
+ validateConnectionDetails(accountType, await decrypt(projectId, existing.encryptedConnectionDetails));
// only test with credentials supplied in this request to prevent exfiltration
let testCredentials = credentials ? validateCredentials(accountType, credentials) : null;
@@ -681,7 +702,7 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>
}
await assertConnectionOk(
accountType,
- effectiveConnectionDetails,
+ testConnectionDetails,
testCredentials,
{
gatewayId: gatewayId !== undefined ? gatewayId : existing.gatewayId,
diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.ts
index 39dff62dfb..a9283bc085 100644
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-service.ts
@@ -46,6 +46,7 @@ import {
buildSessionGatewayConnectionDetails,
extractGatewayTarget,
getAccountAccessibilityIssues,
+ normalizeCredentialAuthMethod,
PamAccountAccessibilityIssue,
parseInternalMetadata,
qualifyUsernameWithDomain,
@@ -208,7 +209,10 @@ export const pamSessionServiceFactory = ({
}
const connectionDetails = await decrypt(session.projectId, account.encryptedConnectionDetails);
- const credentials = await decrypt(session.projectId, account.encryptedCredentials);
+ const credentials = normalizeCredentialAuthMethod(
+ account.accountType as PamAccountType,
+ await decrypt(session.projectId, account.encryptedCredentials)
+ );
if (credentials.authMethod === "certificate" && account.encryptedInternalMetadata) {
const internalMetadata = parseInternalMetadata(
diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.md
index 36c14ba8e7..714d6977c5 100644
--- a/backend/src/ee/services/pam/CLAUDE.md
+++ b/backend/src/ee/services/pam/CLAUDE.md
@@ -84,6 +84,24 @@ the frontend renders create/edit forms from `GET /pam/accounts/types` metadata,
frontend components**. Adding a type is mostly a config entry + an icon; the gateway extension points are
`extractGatewayTarget` and `buildSessionGatewayConnectionDetails` in the same file.
+**Auth methods** are a discriminated union on `credentials`. `forceWhen` (a UI hint, applied server-side
+by `applyForcedFields` on create/update and mirrored by the form) pins fields an auth method leaves no
+choice about; its condition may cross field groups (`credentials.authMethod` from a connection field).
+TLS trust stays where it is for every other database account: the operator supplies `sslCertificate`,
+and Infisical ships no CA material. A gateway too old for an account's auth method is not gated on;
+it falls back to password auth and the connection test fails on the login, as with every other
+gateway capability added so far.
+
+**Adding an auth method to an existing type is a compatibility event.** Stored credentials (and API
+callers) predating the discriminator carry none, which a `z.discriminatedUnion` rejects outright, so the
+union goes through `withLegacyAuthMethod` and every path that reads the blob without re-parsing goes
+through `normalizeCredentialAuthMethod`. The rotation cron validates the stored blob on every run, so
+skipping this breaks rotation for every existing account of that type, not just edits.
+
+Postgres AWS IAM auth is the reference implementation: the **gateway** mints the RDS token per connection
+from its own AWS identity (`packages/pam/aws_rds_auth.go`), so no secret is stored, none crosses the wire,
+and the 15-minute token lifetime never collides with session duration.
+
**Connection test** (`assertConnectionOk`) runs inside account `create`/`update` and **throws to block the write**
if the target can't be reached/authenticated. Per-type behaviour lives in `pam-account-connection-test.ts`:
`buildGatewayConnectionTest` resolves the gateway target + a `mode`-tagged request, and `CLOUD_CONNECTION_VALIDATORS`
diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.ts
index acfd7e02ae..5a8a4898da 100644
--- a/backend/src/ee/services/pam/pam-enums.ts
+++ b/backend/src/ee/services/pam/pam-enums.ts
@@ -53,6 +53,11 @@ export enum PamSshAuthMethod {
Certificate = "certificate"
}
+export enum PamPostgresAuthMethod {
+ Password = "password",
+ AwsIam = "aws-iam"
+}
+
// The caller's just-in-time approval state for an account gated behind an access request flow
export enum PamAccessStatus {
None = "none",
diff --git a/docs/documentation/platform/pam/accounts/postgresql.mdx b/docs/documentation/platform/pam/accounts/postgresql.mdx
index aa0f2b0e94..df4b5320ff 100644
--- a/docs/documentation/platform/pam/accounts/postgresql.mdx
+++ b/docs/documentation/platform/pam/accounts/postgresql.mdx
@@ -33,14 +33,76 @@ PostgreSQL accounts let you manage access to your PostgreSQL databases. Users co
<Step title="Enter credentials">
| Field | Description |
|-------|-------------|
+ | **Auth Method** | **Password** for a standard PostgreSQL login, or **AWS IAM** for RDS and Aurora instances that use [IAM database authentication](#aws-iam-authentication) |
| **Username** | PostgreSQL username |
- | **Password** | PostgreSQL password |
+ | **Password** | PostgreSQL password (password auth only) |
+ | **AWS Region** | Region of the RDS or Aurora instance (AWS IAM only) |
+ | **Role ARN** | IAM role the gateway assumes to generate a token (AWS IAM only) |
</Step>
<Step title="Save">
Click **Create**.
</Step>
</Steps>
+## AWS IAM Authentication
+
+RDS and Aurora instances that require IAM database authentication use the **AWS IAM** auth method. No password is stored: the [gateway](/documentation/platform/gateways/overview) generates a short-lived authentication token for each connection.
+
+Set the following up before creating the account.
+
+<Steps>
+ <Step title="Grant the database user IAM access">
+ ```sql
+ CREATE USER app_user WITH LOGIN;
+ GRANT rds_iam TO app_user;
+ ```
+ </Step>
+ <Step title="Create the IAM role">
+ Create the role you'll set as **Role ARN**, with permission to connect as that database user:
+
+ ```json
+ {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Action": "rds-db:connect",
+ "Resource": "arn:aws:rds-db:<REGION>:<AWS_ACCOUNT_ID>:dbuser:<DB_RESOURCE_ID>/app_user"
+ }]
+ }
+ ```
+
+ The resource ARN uses the instance's **resource ID** (`db-...`), not its name. Find it under **Configuration** on the instance in the RDS console.
+ </Step>
+ <Step title="Allow the gateway to assume the role">
+ The gateway uses its own AWS identity, picked up from its environment: EKS Pod Identity or IRSA, an EC2 instance profile, or AWS environment variables. Give that identity permission to assume the role, and allow it in the role's trust policy.
+
+ ```json
+ {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Action": "sts:AssumeRole",
+ "Resource": "arn:aws:iam::<AWS_ACCOUNT_ID>:role/infisical-pam-*"
+ }]
+ }
+ ```
+ </Step>
+</Steps>
+
+<Note>
+ Set **Host** to the instance's RDS or Aurora endpoint. Tokens are signed for that exact endpoint, so a CNAME or other alias is rejected.
+</Note>
+
+<Note>
+ IAM authentication requires an encrypted connection, so **SSL Enabled** is turned on and cannot be disabled. To verify the server certificate, turn on **Reject Unauthorized** and paste your region's certificate from the [RDS trust store](https://truststore.pki.rds.amazonaws.com) into **SSL Certificate**.
+</Note>
+
+<Warning>
+ If the connection test fails with a password authentication error, check your gateway's version. Gateways released before IAM support connect with a password instead.
+</Warning>
+
+[Credential rotation](/documentation/platform/pam/product-reference/credential-rotation/overview) does not apply to these accounts, since there is no stored password.
+
## Connecting
<Tabs>
diff --git a/docs/documentation/platform/pam/product-reference/credential-rotation/overview.mdx b/docs/documentation/platform/pam/product-reference/credential-rotation/overview.mdx
index 144060d1f8..f5805736f0 100644
--- a/docs/documentation/platform/pam/product-reference/credential-rotation/overview.mdx
+++ b/docs/documentation/platform/pam/product-reference/credential-rotation/overview.mdx
@@ -15,6 +15,8 @@ Rotation is configured in two places that work together:
An account rotates only once both parts are in place: its template has rotation enabled and the account has a rotation account set.
+Accounts that authenticate without a stored password have nothing to rotate and cannot be given a rotation account. This covers PostgreSQL accounts using [AWS IAM authentication](/documentation/platform/pam/accounts/postgresql#aws-iam-authentication) and Microsoft SQL Server accounts using Windows authentication.
+
### Rotation account
The rotation account is the account whose credentials are used to connect to the target and change the password. You have three options:
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index 89f97a6b8b..7425653bbd 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -143,6 +143,8 @@ export enum PamFieldWidget {
Password = "password"
}
+export type TPamFieldCondition = { field: string; equals: string | boolean };
+
export type TPamFieldDescriptor = {
key: string;
label: string;
@@ -152,7 +154,8 @@ export type TPamFieldDescriptor = {
optional?: boolean;
options?: { label: string; value: string }[];
defaultValue?: string | number | boolean;
- showWhen?: { field: string; equals: string | boolean };
+ showWhen?: TPamFieldCondition;
+ forceWhen?: { when: TPamFieldCondition; value: string | number | boolean; reason: string }[];
tooltip?: string;
};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/ConnectionDetailsForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/ConnectionDetailsForm.tsx
index d3e9b44fbb..b59e1ab130 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/ConnectionDetailsForm.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/ConnectionDetailsForm.tsx
@@ -42,6 +42,7 @@ export const ConnectionDetailsForm = ({ control, setValue, clearErrors }: Props)
return (
<PamSchemaFields
control={control}
+ setValue={setValue}
namePrefix="connectionDetails"
fields={metadata.connectionFields}
smartPaste={smartPaste}
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/CreateAccountSheet.tsx b/frontend/src/pages/pam/PamAccountsPage/components/CreateAccountSheet.tsx
index a98b7374dc..8a0ac18d85 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/CreateAccountSheet.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/CreateAccountSheet.tsx
@@ -193,11 +193,13 @@ export const CreateAccountSheet = ({ isOpen, onOpenChange, defaultFolderId, onCr
clearErrors();
const missingConnection = getMissingRequiredFields(
selectedMetadata.connectionFields,
- values.connectionDetails
+ "connectionDetails",
+ values
);
const missingCredentials = getMissingRequiredFields(
selectedMetadata.credentialFields,
- values.credentials
+ "credentials",
+ values
);
const gatewayMissing = needsGateway && !gateway.gatewayId && !gateway.gatewayPoolId;
setGatewayError(gatewayMissing);
@@ -548,7 +550,7 @@ export const CreateAccountSheet = ({ isOpen, onOpenChange, defaultFolderId, onCr
<div className="mt-2">
<h3 className="mb-3 text-sm font-medium text-foreground">Credentials</h3>
<div className="flex flex-col gap-4">
- <CredentialsForm control={control} />
+ <CredentialsForm control={control} setValue={setValue} />
<SshCaSetupCallout
accountType={watch("accountType")}
authMethod={watch("credentials")?.authMethod as string | undefined}
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/CredentialsForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/CredentialsForm.tsx
index c8dc060ca3..d96d8878da 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/CredentialsForm.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/CredentialsForm.tsx
@@ -1,4 +1,4 @@
-import { Control, useWatch } from "react-hook-form";
+import { Control, UseFormSetValue, useWatch } from "react-hook-form";
import { useListPamAccountTypes } from "@app/hooks/api/pam";
@@ -7,9 +7,10 @@ import { PamSchemaFields } from "./PamSchemaFields";
type Props = {
control: Control<TAccountFormValues>;
+ setValue: UseFormSetValue<TAccountFormValues>;
};
-export const CredentialsForm = ({ control }: Props) => {
+export const CredentialsForm = ({ control, setValue }: Props) => {
const accountType = useWatch({ control, name: "accountType" });
const { data: accountTypes } = useListPamAccountTypes();
@@ -19,6 +20,7 @@ export const CredentialsForm = ({ control }: Props) => {
return (
<PamSchemaFields
control={control}
+ setValue={setValue}
namePrefix="credentials"
fields={metadata.credentialFields}
/>
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx
index 0416469fc6..e2805b320c 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx
@@ -123,11 +123,13 @@ export const EditAccountForm = ({ accountId, onDirtyChange }: Props) => {
clearErrors();
const missingConnection = getMissingRequiredFields(
metadata.connectionFields,
- values.connectionDetails
+ "connectionDetails",
+ values
);
const missingCredentials = getMissingRequiredFields(
metadata.credentialFields,
- values.credentials
+ "credentials",
+ values
);
if (missingConnection.length || missingCredentials.length) {
missingConnection.forEach((key) =>
@@ -302,7 +304,7 @@ export const EditAccountForm = ({ accountId, onDirtyChange }: Props) => {
<CardDescription>Authentication used to connect to this account.</CardDescription>
</CardHeader>
<CardContent>
- <CredentialsForm control={control} />
+ <CredentialsForm control={control} setValue={setValue} />
</CardContent>
</Card>
)}
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamSchemaFields.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamSchemaFields.tsx
index 8a14e3e592..bb54af842c 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/PamSchemaFields.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamSchemaFields.tsx
@@ -1,7 +1,21 @@
-import { Control, Controller, ControllerRenderProps, useWatch } from "react-hook-form";
+import { useEffect } from "react";
+import {
+ Control,
+ Controller,
+ ControllerRenderProps,
+ Path,
+ UseFormSetValue,
+ useWatch
+} from "react-hook-form";
import { Info } from "lucide-react";
-import { Field, FieldContent, FieldError, FieldLabel } from "@app/components/v3/generic/Field";
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel
+} from "@app/components/v3/generic/Field";
import { Input } from "@app/components/v3/generic/Input";
import {
Select,
@@ -16,11 +30,15 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3/gene
import { useOrganization } from "@app/context";
import { PamFieldWidget, TPamFieldDescriptor } from "@app/hooks/api/pam";
-import { TAccountFormValues } from "./accountFormSchema";
+import {
+ isFieldVisible,
+ resolveForcedRule,
+ TAccountFormValues,
+ TPamFieldGroup,
+ TPamFieldGroupValues
+} from "./accountFormSchema";
import { PamPasswordInput } from "./PamPasswordInput";
-type NamePrefix = "connectionDetails" | "credentials";
-
export type TSmartPaste = {
fieldKey: string;
hint: string;
@@ -29,7 +47,8 @@ export type TSmartPaste = {
type Props = {
control: Control<TAccountFormValues>;
- namePrefix: NamePrefix;
+ setValue: UseFormSetValue<TAccountFormValues>;
+ namePrefix: TPamFieldGroup;
fields: TPamFieldDescriptor[];
smartPaste?: TSmartPaste;
};
@@ -56,6 +75,7 @@ type FieldProps = {
field: ControllerRenderProps<TAccountFormValues>;
descriptor: TPamFieldDescriptor;
isError: boolean;
+ isDisabled?: boolean;
smartPaste?: TSmartPaste;
};
@@ -65,7 +85,7 @@ const fieldValueAsString = (value: unknown): string => {
return String(value);
};
-const FieldWidget = ({ field, descriptor, isError, smartPaste }: FieldProps) => {
+const FieldWidget = ({ field, descriptor, isError, isDisabled, smartPaste }: FieldProps) => {
if (descriptor.secret) {
return (
<PamPasswordInput
@@ -84,13 +104,18 @@ const FieldWidget = ({ field, descriptor, isError, smartPaste }: FieldProps) =>
onChange={field.onChange}
rows={4}
isError={isError}
+ disabled={isDisabled}
/>
);
}
if (descriptor.widget === PamFieldWidget.Select) {
return (
- <Select value={(field.value as string) ?? ""} onValueChange={field.onChange}>
+ <Select
+ value={(field.value as string) ?? ""}
+ onValueChange={field.onChange}
+ disabled={isDisabled}
+ >
<SelectTrigger className="w-full" isError={isError}>
<SelectValue placeholder={`Select ${descriptor.label.toLowerCase()}`} />
</SelectTrigger>
@@ -112,6 +137,7 @@ const FieldWidget = ({ field, descriptor, isError, smartPaste }: FieldProps) =>
value={(field.value as number | string) ?? ""}
onChange={(e) => field.onChange(e.target.value === "" ? "" : Number(e.target.value))}
isError={isError}
+ disabled={isDisabled}
/>
);
}
@@ -121,6 +147,7 @@ const FieldWidget = ({ field, descriptor, isError, smartPaste }: FieldProps) =>
value={fieldValueAsString(field.value)}
onChange={field.onChange}
isError={isError}
+ disabled={isDisabled}
placeholder={smartPaste?.hint}
onPaste={
smartPaste &&
@@ -139,58 +166,84 @@ const FieldWidget = ({ field, descriptor, isError, smartPaste }: FieldProps) =>
};
// Renders connection/credential fields from backend-supplied metadata
-export const PamSchemaFields = ({ control, namePrefix, fields, smartPaste }: Props) => {
- const values = (useWatch({ control, name: namePrefix }) ?? {}) as Record<string, unknown>;
- const visibleFields = fields.filter(
- (field) => !field.showWhen || values[field.showWhen.field] === field.showWhen.equals
- );
+export const PamSchemaFields = ({ control, setValue, namePrefix, fields, smartPaste }: Props) => {
+ const [connectionDetails, credentials] = useWatch({
+ control,
+ name: ["connectionDetails", "credentials"]
+ });
+ const values: TPamFieldGroupValues = {
+ connectionDetails: connectionDetails ?? {},
+ credentials: credentials ?? {}
+ };
+
+ const forcedRules = fields.map((field) => resolveForcedRule(field, namePrefix, values));
+
+ // The server applies these rules too, so this only keeps the form honest about what it will save
+ useEffect(() => {
+ fields.forEach((field, idx) => {
+ const rule = forcedRules[idx];
+ if (rule && values[namePrefix][field.key] !== rule.value) {
+ setValue(`${namePrefix}.${field.key}` as Path<TAccountFormValues>, rule.value as never, {
+ shouldDirty: true
+ });
+ }
+ });
+ });
return (
<div className="flex flex-col gap-4">
- {visibleFields.map((descriptor) => (
- <Controller
- key={descriptor.key}
- control={control}
- name={`${namePrefix}.${descriptor.key}` as const}
- render={({ field, fieldState }) =>
- descriptor.widget === PamFieldWidget.Boolean ? (
- <Field orientation="horizontal">
- <FieldLabel>
- {descriptor.label}
- {(descriptor.required || (descriptor.secret && !descriptor.optional)) && (
- <RequiredMark />
- )}
- <FieldTooltip text={descriptor.tooltip} />
- </FieldLabel>
- <Switch
- variant="pam"
- checked={Boolean(field.value)}
- onCheckedChange={field.onChange}
- />
- </Field>
- ) : (
- <Field>
- <FieldLabel>
- {descriptor.label}
- {(descriptor.required || (descriptor.secret && !descriptor.optional)) && (
- <RequiredMark />
- )}
- <FieldTooltip text={descriptor.tooltip} />
- </FieldLabel>
- <FieldContent>
- <FieldWidget
- field={field}
- descriptor={descriptor}
- isError={!!fieldState.error}
- smartPaste={smartPaste?.fieldKey === descriptor.key ? smartPaste : undefined}
+ {fields.map((descriptor, idx) => {
+ if (!isFieldVisible(descriptor, namePrefix, values)) return null;
+ const forcedRule = forcedRules[idx];
+
+ return (
+ <Controller
+ key={descriptor.key}
+ control={control}
+ name={`${namePrefix}.${descriptor.key}` as const}
+ render={({ field, fieldState }) =>
+ descriptor.widget === PamFieldWidget.Boolean ? (
+ <Field orientation="horizontal">
+ <FieldLabel>
+ {descriptor.label}
+ {(descriptor.required || (descriptor.secret && !descriptor.optional)) && (
+ <RequiredMark />
+ )}
+ <FieldTooltip text={forcedRule?.reason ?? descriptor.tooltip} />
+ </FieldLabel>
+ <Switch
+ variant="pam"
+ checked={Boolean(field.value)}
+ onCheckedChange={field.onChange}
+ disabled={Boolean(forcedRule)}
/>
- <FieldError>{fieldState.error?.message}</FieldError>
- </FieldContent>
- </Field>
- )
- }
- />
- ))}
+ </Field>
+ ) : (
+ <Field>
+ <FieldLabel>
+ {descriptor.label}
+ {(descriptor.required || (descriptor.secret && !descriptor.optional)) && (
+ <RequiredMark />
+ )}
+ <FieldTooltip text={descriptor.tooltip} />
+ </FieldLabel>
+ <FieldContent>
+ <FieldWidget
+ field={field}
+ descriptor={descriptor}
+ isError={!!fieldState.error}
+ isDisabled={Boolean(forcedRule)}
+ smartPaste={smartPaste?.fieldKey === descriptor.key ? smartPaste : undefined}
+ />
+ {forcedRule && <FieldDescription>{forcedRule.reason}</FieldDescription>}
+ <FieldError>{fieldState.error?.message}</FieldError>
+ </FieldContent>
+ </Field>
+ )
+ }
+ />
+ );
+ })}
</div>
);
};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/accountFormSchema.ts b/frontend/src/pages/pam/PamAccountsPage/components/accountFormSchema.ts
index 836879b5b5..d8eada7e40 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/accountFormSchema.ts
+++ b/frontend/src/pages/pam/PamAccountsPage/components/accountFormSchema.ts
@@ -2,7 +2,12 @@ import { FieldValues, Path, UseFormSetError } from "react-hook-form";
import axios from "axios";
import { z } from "zod";
-import { PamAccountType, PamFieldWidget, TPamFieldDescriptor } from "@app/hooks/api/pam";
+import {
+ PamAccountType,
+ PamFieldWidget,
+ TPamFieldCondition,
+ TPamFieldDescriptor
+} from "@app/hooks/api/pam";
import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";
import { ApiErrorTypes, TApiErrors } from "@app/hooks/api/types";
@@ -40,18 +45,52 @@ export const buildEditCredentialValues = (
})
);
-const isFieldVisible = (field: TPamFieldDescriptor, values: Record<string, unknown>) =>
- !field.showWhen || values[field.showWhen.field] === field.showWhen.equals;
+export type TPamFieldGroup = "connectionDetails" | "credentials";
+export type TPamFieldGroupValues = Record<TPamFieldGroup, Record<string, unknown>>;
+
+// A field's condition reads its own group unless the reference is qualified, since a connection
+// detail can depend on how the account authenticates
+const conditionHolds = (
+ condition: TPamFieldCondition,
+ group: TPamFieldGroup,
+ values: TPamFieldGroupValues
+): boolean => {
+ const separatorIdx = condition.field.indexOf(".");
+ const [targetGroup, key] =
+ separatorIdx === -1
+ ? [group, condition.field]
+ : [
+ condition.field.slice(0, separatorIdx) as TPamFieldGroup,
+ condition.field.slice(separatorIdx + 1)
+ ];
+
+ return values[targetGroup]?.[key] === condition.equals;
+};
+
+export const resolveForcedRule = (
+ field: TPamFieldDescriptor,
+ group: TPamFieldGroup,
+ values: TPamFieldGroupValues
+) => field.forceWhen?.find((rule) => conditionHolds(rule.when, group, values));
+
+export const isFieldVisible = (
+ field: TPamFieldDescriptor,
+ group: TPamFieldGroup,
+ values: TPamFieldGroupValues
+) => !field.showWhen || conditionHolds(field.showWhen, group, values);
export const getMissingRequiredFields = (
fields: TPamFieldDescriptor[],
- values: Record<string, unknown>
+ group: TPamFieldGroup,
+ values: TPamFieldGroupValues
): string[] =>
fields
.filter((field) => {
- if (field.widget === PamFieldWidget.Boolean || !isFieldVisible(field, values)) return false;
+ if (field.widget === PamFieldWidget.Boolean || !isFieldVisible(field, group, values)) {
+ return false;
+ }
if (!field.required && !(field.secret && !field.optional)) return false;
- const value = values[field.key];
+ const value = values[group][field.key];
return value === undefined || value === null || String(value).trim() === "";
})
.map((field) => field.key);