Skip to content

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

feat(pam): fill account fields from a pasted connection string (#7504)

Saif Ur Rahman5500d144d326
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 f4bae64c81..e79d517bb1 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
@@ -81,6 +81,12 @@ describe("buildPamAccountTypeMetadata", () => {
});
});
+ test("only advertises connection string schemes for types that accept them", () => {
+ expect(byType.get(PamAccountType.Postgres)?.connectionStringSchemes).toEqual(["postgres", "postgresql"]);
+ expect(byType.get(PamAccountType.MySQL)?.connectionStringSchemes).toBeUndefined();
+ expect(byType.get(PamAccountType.SSH)?.connectionStringSchemes).toBeUndefined();
+ });
+
test("derives MySQL connection and credential fields from the schema", () => {
const mysql = byType.get(PamAccountType.MySQL);
expect(mysql).toBeDefined();
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 9bd6c6f338..382bed375a 100644
--- a/backend/src/ee/services/pam-account/pam-account-schemas.ts
+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts
@@ -54,6 +54,7 @@ export const ACCOUNT_TYPE_CONFIGS = {
[PamAccountType.Postgres]: {
name: "PostgreSQL",
icon: "Postgres.png",
+ connectionStringSchemes: ["postgres", "postgresql"],
connectionDetails: z.object({
host: z.string().trim().min(1).max(255),
port: z.coerce.number(),
@@ -626,6 +627,7 @@ export const ACCOUNT_TYPE_CONFIGS = {
name: string;
icon: string;
requiresGateway?: boolean;
+ connectionStringSchemes?: readonly string[];
connectionDetails: z.ZodTypeAny;
credentials: z.ZodTypeAny;
sanitizedCredentials: z.ZodTypeAny;
@@ -852,6 +854,13 @@ export const accountTypeRequiresGateway = (accountType: PamAccountType): boolean
return config?.requiresGateway !== false;
};
+const accountTypeConnectionStringSchemes = (accountType: PamAccountType): string[] | undefined => {
+ const config = ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType] as
+ | { connectionStringSchemes?: readonly string[] }
+ | undefined;
+ return config?.connectionStringSchemes ? [...config.connectionStringSchemes] : undefined;
+};
+
export const getAccountAccessibilityIssues = (account: {
accountType: PamAccountType | string;
gatewayId?: string | null;
@@ -933,6 +942,8 @@ export const PamAccountTypeMetadataSchema = z.object({
supportsWebAccess: z.boolean(),
requiresGateway: z.boolean(),
supportsDependencies: z.boolean(),
+
+ connectionStringSchemes: z.array(z.string()).optional(),
connectionFields: z.array(PamFieldDescriptorSchema),
credentialFields: z.array(PamFieldDescriptorSchema),
applicablePolicies: z.array(PamPolicyDescriptorSchema)
@@ -1090,6 +1101,7 @@ export const buildPamAccountTypeMetadata = (webAccessSupportedTypes: Set<PamAcco
supportsWebAccess: webAccessSupportedTypes.has(type),
requiresGateway: accountTypeRequiresGateway(type),
supportsDependencies: isWindowsRotatableType(type),
+ connectionStringSchemes: accountTypeConnectionStringSchemes(type),
connectionFields: fieldsFromSchema(config.connectionDetails, config.ui),
credentialFields: fieldsFromSchema(config.credentials, config.ui),
applicablePolicies: getApplicablePolicies(type)
diff --git a/docs/documentation/platform/pam/accounts/postgresql.mdx b/docs/documentation/platform/pam/accounts/postgresql.mdx
index 8b4bc55e89..aa0f2b0e94 100644
--- a/docs/documentation/platform/pam/accounts/postgresql.mdx
+++ b/docs/documentation/platform/pam/accounts/postgresql.mdx
@@ -16,6 +16,10 @@ PostgreSQL accounts let you manage access to your PostgreSQL databases. Users co
Choose which [folder](/documentation/platform/pam/folders/overview) to add the account to, then select a PostgreSQL [template](/documentation/platform/pam/templates/overview) (e.g., the default `postgres` or a custom one).
</Step>
<Step title="Enter connection details">
+ <Tip>
+ Already have a connection string? Paste it into the **Host** field and the remaining fields are filled in for you, credentials included. Both `postgresql://user:password@host:5432/database` and `host=... port=... dbname=...` forms work.
+ </Tip>
+
| Field | Description |
|-------|-------------|
| **Name** | A descriptive name (e.g., `orders-db-readonly`) |
diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts
index ae17d576da..a7989942f6 100644
--- a/frontend/src/hooks/api/pam/types/index.ts
+++ b/frontend/src/hooks/api/pam/types/index.ts
@@ -168,6 +168,7 @@ export type TPamAccountTypeMetadata = {
supportsWebAccess: boolean;
requiresGateway: boolean;
supportsDependencies: boolean;
+ connectionStringSchemes?: string[];
connectionFields: TPamFieldDescriptor[];
credentialFields: TPamFieldDescriptor[];
applicablePolicies: TPamPolicyDescriptor[];
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/ConnectionDetailsForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/ConnectionDetailsForm.tsx
index 234ed5961f..d3e9b44fbb 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/ConnectionDetailsForm.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/ConnectionDetailsForm.tsx
@@ -1,26 +1,50 @@
-import { Control, useWatch } from "react-hook-form";
+import { Control, UseFormClearErrors, UseFormSetValue, useWatch } from "react-hook-form";
-import { useListPamAccountTypes } from "@app/hooks/api/pam";
+import { PamFieldWidget, useListPamAccountTypes } from "@app/hooks/api/pam";
import { TAccountFormValues } from "./accountFormSchema";
-import { PamSchemaFields } from "./PamSchemaFields";
+import { applyConnectionString } from "./applyConnectionString";
+import { PamSchemaFields, TSmartPaste } from "./PamSchemaFields";
type Props = {
control: Control<TAccountFormValues>;
+ setValue: UseFormSetValue<TAccountFormValues>;
+ clearErrors: UseFormClearErrors<TAccountFormValues>;
};
-export const ConnectionDetailsForm = ({ control }: Props) => {
+export const ConnectionDetailsForm = ({ control, setValue, clearErrors }: Props) => {
const accountType = useWatch({ control, name: "accountType" });
const { data: accountTypes } = useListPamAccountTypes();
const metadata = accountTypes?.find((t) => t.type === accountType);
if (!metadata) return null;
+ const schemes = metadata.connectionStringSchemes ?? [];
+
+ const pasteField = schemes.length
+ ? metadata.connectionFields.find((field) => field.widget === PamFieldWidget.Text)
+ : undefined;
+
+ const smartPaste: TSmartPaste | undefined = pasteField && {
+ fieldKey: pasteField.key,
+ hint: `${pasteField.label}, or paste a connection string`,
+ onPaste: (text) =>
+ applyConnectionString({
+ text,
+ schemes,
+ connectionFields: metadata.connectionFields,
+ credentialFields: metadata.credentialFields,
+ setValue,
+ clearErrors
+ })
+ };
+
return (
<PamSchemaFields
control={control}
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 ee18223179..a98b7374dc 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/CreateAccountSheet.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/CreateAccountSheet.tsx
@@ -503,7 +503,11 @@ export const CreateAccountSheet = ({ isOpen, onOpenChange, defaultFolderId, onCr
<div className="mt-2">
<h3 className="mb-3 text-sm font-medium text-foreground">Connection Details</h3>
<div className="flex flex-col gap-4">
- <ConnectionDetailsForm control={control} />
+ <ConnectionDetailsForm
+ control={control}
+ setValue={setValue}
+ clearErrors={clearErrors}
+ />
{needsGateway && (
<Field>
<FieldLabel>
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx
index 5464314511..0416469fc6 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/EditAccountForm.tsx
@@ -87,6 +87,7 @@ export const EditAccountForm = ({ accountId, onDirtyChange }: Props) => {
control,
handleSubmit,
reset,
+ setValue,
setError,
clearErrors,
formState: { isDirty }
@@ -290,7 +291,7 @@ export const EditAccountForm = ({ accountId, onDirtyChange }: Props) => {
<CardDescription>How Infisical reaches this account.</CardDescription>
</CardHeader>
<CardContent>
- <ConnectionDetailsForm control={control} />
+ <ConnectionDetailsForm control={control} setValue={setValue} clearErrors={clearErrors} />
</CardContent>
</Card>
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamSchemaFields.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamSchemaFields.tsx
index c540cc5d2d..d407235a98 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/PamSchemaFields.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamSchemaFields.tsx
@@ -21,10 +21,17 @@ import { PamPasswordInput } from "./PamPasswordInput";
type NamePrefix = "connectionDetails" | "credentials";
+export type TSmartPaste = {
+ fieldKey: string;
+ hint: string;
+ onPaste: (text: string) => boolean;
+};
+
type Props = {
control: Control<TAccountFormValues>;
namePrefix: NamePrefix;
fields: TPamFieldDescriptor[];
+ smartPaste?: TSmartPaste;
};
const RequiredMark = () => <span className="text-product-pam">*</span>;
@@ -49,6 +56,7 @@ type FieldProps = {
field: ControllerRenderProps<TAccountFormValues>;
descriptor: TPamFieldDescriptor;
isError: boolean;
+ smartPaste?: TSmartPaste;
};
const fieldValueAsString = (value: unknown): string => {
@@ -57,7 +65,7 @@ const fieldValueAsString = (value: unknown): string => {
return String(value);
};
-const FieldWidget = ({ field, descriptor, isError }: FieldProps) => {
+const FieldWidget = ({ field, descriptor, isError, smartPaste }: FieldProps) => {
if (descriptor.secret) {
return (
<PamPasswordInput
@@ -109,12 +117,29 @@ const FieldWidget = ({ field, descriptor, isError }: FieldProps) => {
}
return (
- <Input value={fieldValueAsString(field.value)} onChange={field.onChange} isError={isError} />
+ <Input
+ value={fieldValueAsString(field.value)}
+ onChange={field.onChange}
+ isError={isError}
+ placeholder={smartPaste?.hint}
+ onPaste={
+ smartPaste &&
+ ((e) => {
+ const { value, selectionStart, selectionEnd } = e.currentTarget;
+ const isReplacingWholeValue =
+ !value || (selectionStart === 0 && selectionEnd === value.length);
+ if (!isReplacingWholeValue) return;
+
+ const text = e.clipboardData.getData("text");
+ if (text.trim() && smartPaste.onPaste(text)) e.preventDefault();
+ })
+ }
+ />
);
};
// Renders connection/credential fields from backend-supplied metadata
-export const PamSchemaFields = ({ control, namePrefix, fields }: Props) => {
+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
@@ -149,7 +174,12 @@ export const PamSchemaFields = ({ control, namePrefix, fields }: Props) => {
<FieldTooltip text={descriptor.tooltip} />
</FieldLabel>
<FieldContent>
- <FieldWidget field={field} descriptor={descriptor} isError={!!fieldState.error} />
+ <FieldWidget
+ field={field}
+ descriptor={descriptor}
+ isError={!!fieldState.error}
+ smartPaste={smartPaste?.fieldKey === descriptor.key ? smartPaste : undefined}
+ />
<FieldError>{fieldState.error?.message}</FieldError>
</FieldContent>
</Field>
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/applyConnectionString.ts b/frontend/src/pages/pam/PamAccountsPage/components/applyConnectionString.ts
new file mode 100644
index 0000000000..d44a03b4a7
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/applyConnectionString.ts
@@ -0,0 +1,44 @@
+import { Path, UseFormClearErrors, UseFormSetValue } from "react-hook-form";
+
+import { TPamFieldDescriptor } from "@app/hooks/api/pam";
+
+import { TAccountFormValues } from "./accountFormSchema";
+import { parseConnectionString } from "./parseConnectionString";
+
+type TArgs = {
+ text: string;
+ schemes: string[];
+ connectionFields: TPamFieldDescriptor[];
+ credentialFields: TPamFieldDescriptor[];
+ setValue: UseFormSetValue<TAccountFormValues>;
+ clearErrors: UseFormClearErrors<TAccountFormValues>;
+};
+
+export const applyConnectionString = ({
+ text,
+ schemes,
+ connectionFields,
+ credentialFields,
+ setValue,
+ clearErrors
+}: TArgs): boolean => {
+ const values = parseConnectionString(text, schemes);
+ if (!values) return false;
+
+ const paths: Path<TAccountFormValues>[] = [];
+ Object.entries(values).forEach(([key, value]) => {
+ const isConnectionField = connectionFields.some((field) => field.key === key);
+ if (!isConnectionField && !credentialFields.some((field) => field.key === key)) return;
+
+ const path =
+ `${isConnectionField ? "connectionDetails" : "credentials"}.${key}` as Path<TAccountFormValues>;
+ setValue(path, value as never, { shouldDirty: true });
+ paths.push(path);
+ });
+
+ if (!paths.length) return false;
+
+ // setValue does not clear the submit handler's "required" errors
+ clearErrors(paths);
+ return true;
+};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/parseConnectionString.ts b/frontend/src/pages/pam/PamAccountsPage/components/parseConnectionString.ts
new file mode 100644
index 0000000000..4a3a79ba67
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountsPage/components/parseConnectionString.ts
@@ -0,0 +1,215 @@
+type TConnectionStringValues = {
+ host?: string;
+ port?: number;
+ database?: string;
+ username?: string;
+ password?: string;
+ sslEnabled?: boolean;
+ sslRejectUnauthorized?: boolean;
+};
+
+class NotAConnectionString extends Error {}
+
+// "require" encrypts but does not verify the cert
+const SSL_MODES: Record<string, TConnectionStringValues> = {
+ disable: { sslEnabled: false },
+ allow: { sslEnabled: false },
+ prefer: { sslEnabled: true, sslRejectUnauthorized: false },
+ require: { sslEnabled: true, sslRejectUnauthorized: false },
+ "verify-ca": { sslEnabled: true, sslRejectUnauthorized: true },
+ "verify-full": { sslEnabled: true, sslRejectUnauthorized: true }
+};
+
+const TRUTHY_SSL = new Set(["true", "1", "on", "yes", "require", "required"]);
+const FALSY_SSL = new Set(["false", "0", "off", "no", "disable", "disabled"]);
+
+const decode = (value: string) => {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return value;
+ }
+};
+
+const unwrap = (raw: string) => {
+ let value = raw
+ .trim()
+ .replace(/^psql\s+/i, "")
+ .trim();
+
+ const quote = value[0];
+ if ((quote === '"' || quote === "'") && value.length > 1 && value.endsWith(quote)) {
+ value = value.slice(1, -1).trim();
+ }
+
+ return value.replace(/^jdbc:/i, "").trim();
+};
+
+const parsePort = (value: string) => {
+ if (!/^\d+$/.test(value)) throw new NotAConnectionString();
+ const port = Number(value);
+ if (port < 1 || port > 65535) throw new NotAConnectionString();
+ return port;
+};
+
+type TParseState = { values: TConnectionStringValues; sawSslMode: boolean };
+
+const applyParameter = (key: string, value: string, state: TParseState) => {
+ const target = state.values;
+
+ switch (key.toLowerCase()) {
+ case "user":
+ case "username":
+ if (value) target.username = value;
+ break;
+ case "password":
+ if (value) target.password = value;
+ break;
+ case "dbname":
+ case "database":
+ if (value) target.database = value;
+ break;
+ case "host":
+ if (value) [target.host] = value.split(",");
+ break;
+ case "hostaddr":
+ if (value && !target.host) [target.host] = value.split(",");
+ break;
+ case "port": {
+ const [firstPort] = value.split(",");
+ if (firstPort) target.port = parsePort(firstPort);
+ break;
+ }
+ case "sslmode": {
+ const mode = SSL_MODES[value.toLowerCase()];
+ if (!mode) break;
+ Object.assign(target, mode);
+ // eslint-disable-next-line no-param-reassign
+ state.sawSslMode = true;
+ break;
+ }
+ case "ssl":
+ if (state.sawSslMode) break;
+ if (TRUTHY_SSL.has(value.toLowerCase())) target.sslEnabled = true;
+ if (FALSY_SSL.has(value.toLowerCase())) target.sslEnabled = false;
+ break;
+ default:
+ break;
+ }
+};
+
+const applyQuery = (query: string, state: TParseState) => {
+ query.split("&").forEach((pair) => {
+ const separatorIdx = pair.indexOf("=");
+ if (separatorIdx === -1) return;
+ applyParameter(
+ decode(pair.slice(0, separatorIdx)),
+ decode(pair.slice(separatorIdx + 1)),
+ state
+ );
+ });
+};
+
+const applyHost = (hostPart: string, values: TConnectionStringValues) => {
+ const target = values;
+
+ const [firstHost] = hostPart.split(",");
+ if (!firstHost) return;
+
+ if (firstHost.startsWith("[")) {
+ const closingIdx = firstHost.indexOf("]");
+ if (closingIdx === -1) throw new NotAConnectionString();
+
+ target.host = firstHost.slice(1, closingIdx);
+ const remainder = firstHost.slice(closingIdx + 1);
+ if (!remainder) return;
+ if (!remainder.startsWith(":")) throw new NotAConnectionString();
+ if (remainder.length > 1) target.port = parsePort(remainder.slice(1));
+ return;
+ }
+
+ const portIdx = firstHost.lastIndexOf(":");
+ if (portIdx === -1) {
+ target.host = decode(firstHost);
+ return;
+ }
+
+ const host = decode(firstHost.slice(0, portIdx));
+ // Unbracketed IPv6: host and port are indistinguishable
+ if (host.includes(":")) throw new NotAConnectionString();
+ if (host) target.host = host;
+ const port = firstHost.slice(portIdx + 1);
+ if (port) target.port = parsePort(port);
+};
+
+const parseUri = (value: string, schemes: string[]): TConnectionStringValues => {
+ const match = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/(.*)$/.exec(value);
+ if (!match || !schemes.some((scheme) => scheme.toLowerCase() === match[1].toLowerCase())) {
+ throw new NotAConnectionString();
+ }
+
+ const rest = match[2];
+ const state: TParseState = { values: {}, sawSslMode: false };
+ const { values } = state;
+
+ const queryIdx = rest.indexOf("?");
+ const beforeQuery = queryIdx === -1 ? rest : rest.slice(0, queryIdx);
+ const query = queryIdx === -1 ? "" : rest.slice(queryIdx + 1);
+
+ const pathIdx = beforeQuery.indexOf("/");
+ const authority = pathIdx === -1 ? beforeQuery : beforeQuery.slice(0, pathIdx);
+ const path = pathIdx === -1 ? "" : beforeQuery.slice(pathIdx + 1);
+
+ // A password may contain an unencoded "@"
+ const credentialsIdx = authority.lastIndexOf("@");
+ if (credentialsIdx !== -1) {
+ const credentials = authority.slice(0, credentialsIdx);
+ const passwordIdx = credentials.indexOf(":");
+ const username = decode(passwordIdx === -1 ? credentials : credentials.slice(0, passwordIdx));
+ const password = passwordIdx === -1 ? "" : decode(credentials.slice(passwordIdx + 1));
+ if (username) values.username = username;
+ if (password) values.password = password;
+ }
+
+ applyHost(authority.slice(credentialsIdx + 1), values);
+
+ const [database] = path.split("/");
+ if (database) values.database = decode(database);
+
+ applyQuery(query, state);
+
+ return values;
+};
+
+const parseKeywordValue = (value: string): TConnectionStringValues => {
+ const state: TParseState = { values: {}, sawSslMode: false };
+ const tokens = value.matchAll(
+ /([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|\S*)/g
+ );
+
+ Array.from(tokens).forEach(([, key, rawValue]) => {
+ const quote = rawValue[0];
+ const unquoted =
+ (quote === "'" || quote === '"') && rawValue.length > 1 && rawValue.endsWith(quote)
+ ? rawValue.slice(1, -1).replace(/\\(.)/g, "$1")
+ : rawValue;
+ applyParameter(key, unquoted, state);
+ });
+
+ return state.values;
+};
+
+export const parseConnectionString = (
+ raw: string,
+ schemes: string[]
+): TConnectionStringValues | null => {
+ const value = unwrap(raw);
+ if (!value) return null;
+
+ try {
+ const values = value.includes("://") ? parseUri(value, schemes) : parseKeywordValue(value);
+ return Object.keys(values).length ? values : null;
+ } catch {
+ return null;
+ }
+};