Skip to content

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

create managed identity connections first and verify them on reconnect

DimitrisStaratzis16b7c97da96c
diff --git a/backend/AGENTS.md b/backend/AGENTS.md
index 285d6c92b1..53dbe7e84a 100644
--- a/backend/AGENTS.md
+++ b/backend/AGENTS.md
@@ -1220,11 +1220,11 @@ The issuer URL and each consumer's `sub` format are one-way doors: customers cop
for free and never logs on its own.
- **Connections sign for their own ID only.** The subject is `getAppConnectionOidcSubject(connection.id)`,
built server-side from the connection row, and the token is only ever sent to the provider's token
- endpoint, never returned to a caller. The form picks a new connection's ID so the subject can be shown
- before it exists; create rejects an ID that is already in use before validation signs anything. The
- Azure Key Vault `managed-identity` method is the reference consumer: copy its
- `getManagedIdentityAccessToken`, which caches the provider's access token in the credentials like the
- secret-based methods do.
+ endpoint, never returned to a caller. Never let a caller choose the ID: a deleted connection's ID would
+ regain whatever the provider still trusts. So the connection is created first, without a token exchange,
+ and reconnecting verifies it once the customer has added the federated credential. The Azure Key Vault
+ `managed-identity` method is the reference consumer: copy its `getManagedIdentityAccessToken`, which
+ caches the provider's access token in the credentials like the secret-based methods do.
### Enterprise (EE) Features
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index a0840d2be6..aae6ff5b7e 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2913,7 +2913,6 @@ export const AppConnections = {
credentials: `The credentials used to connect with ${appName}.`,
method: `The method used to authenticate with ${appName}.`,
stsEndpoint: `An optional custom endpoint URL for the AWS STS API to use when connecting with ${appName}.`,
- id: `The ID to give the ${appName} Connection. Required for the managed-identity method: Infisical signs its tokens with the subject 'app-connection:<id>', so that subject must be on the federated credential before the connection is created.`,
isPlatformManagedCredentials: `Whether or not the ${appName} Connection credentials should be managed by Infisical. Once enabled this cannot be reversed.`,
projectId: `The ID of the project to create the ${appName} Connection in.`,
isAutoRotationEnabled: `Whether or not automatic credential rotation is enabled for the ${appName} Connection.`,
diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts
index 4de55435cb..946c50f53a 100644
--- a/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts
@@ -16,7 +16,6 @@ import { AuthMode } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
type TAppConnectionCreateSchema<I extends TAppConnectionInput> = z.ZodType<{
- id?: string;
name: string;
method: I["method"];
credentials: I["credentials"];
@@ -344,7 +343,6 @@ export const buildCreateAppConnectionRoute = <I extends TAppConnectionInput>(
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
handler: async (req) => {
const {
- id,
name,
method,
credentials,
@@ -360,7 +358,6 @@ export const buildCreateAppConnectionRoute = <I extends TAppConnectionInput>(
const appConnection = await server.services.appConnection.createAppConnection(
{
- id,
name,
method,
app,
diff --git a/backend/src/services/app-connection/app-connection-service.test.ts b/backend/src/services/app-connection/app-connection-service.test.ts
index 41c659003e..a716aef5a1 100644
--- a/backend/src/services/app-connection/app-connection-service.test.ts
+++ b/backend/src/services/app-connection/app-connection-service.test.ts
@@ -11,7 +11,6 @@ import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
import { AppConnection } from "./app-connection-enums";
import { appConnectionServiceFactory } from "./app-connection-service";
-import { AzureKeyVaultConnectionMethod } from "./azure-key-vault";
const ACTOR_ORG_ID = "org-1";
const CONNECTION_ID = "conn-1";
@@ -29,8 +28,7 @@ class PermissionReached extends Error {}
const buildService = (
connection: { orgId: string; projectId: string | null; app?: AppConnection },
- abilities: { org?: unknown; project?: unknown } = {},
- extraDeps: Record<string, unknown> = {}
+ abilities: { org?: unknown; project?: unknown } = {}
) => {
const permissionService = {
getOrgPermission: vi.fn(async () => {
@@ -59,8 +57,7 @@ const buildService = (
}))
},
permissionService,
- licenseService: { getPlan: vi.fn(async () => ({})) },
- ...extraDeps
+ licenseService: { getPlan: vi.fn(async () => ({})) }
};
const deps = new Proxy(overrides, {
@@ -206,35 +203,3 @@ describe("validateAppConnectionUsageById refuses connections the caller cannot u
).rejects.toThrow(BadRequestError);
});
});
-
-describe("createAppConnection", () => {
- test("refuses an ID another connection has, before signing a token for it", async () => {
- const signToken = vi.fn();
- const { service } = buildService(
- { orgId: ACTOR_ORG_ID, projectId: null },
- {
- org: createMongoAbility([
- { action: OrgPermissionAppConnectionActions.Create, subject: OrgPermissionSubjects.AppConnections }
- ])
- },
- { oidcIssuerService: { signToken } }
- );
-
- await expect(
- service.createAppConnection(
- {
- id: CONNECTION_ID,
- name: "key-vault",
- app: AppConnection.AzureKeyVault,
- method: AzureKeyVaultConnectionMethod.ManagedIdentity,
- credentials: {
- tenantId: "00000000-0000-0000-0000-000000000000",
- clientId: "00000000-0000-0000-0000-000000000000"
- }
- },
- actor
- )
- ).rejects.toThrow(`App Connection ID '${CONNECTION_ID}' is already in use`);
- expect(signToken).not.toHaveBeenCalled();
- });
-});
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index 0ec8c493f3..64b8278dbc 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -649,11 +649,6 @@ export const appConnectionServiceFactory = ({
}
}
- // Validation signs a token for the connection's ID, so it must not be one another connection already has
- if (params.id && (await appConnectionDAL.findById(params.id))) {
- throw new BadRequestError({ message: `App Connection ID '${params.id}' is already in use. Use a new ID.` });
- }
-
const runValidation = (validationGatewayId: string | null | undefined) =>
validateAppConnectionCredentials(
{
@@ -662,7 +657,6 @@ export const appConnectionServiceFactory = ({
method,
orgId: actor.orgId,
projectId,
- connectionId: params.id,
version: 2,
gatewayId: validationGatewayId,
projectType: project?.type
diff --git a/backend/src/services/app-connection/app-connection-types.ts b/backend/src/services/app-connection/app-connection-types.ts
index e853163772..2101c97bd7 100644
--- a/backend/src/services/app-connection/app-connection-types.ts
+++ b/backend/src/services/app-connection/app-connection-types.ts
@@ -781,7 +781,6 @@ export type TCreateAppConnectionDTO = Pick<
| "rotation"
| "isAutoRotationEnabled"
> & {
- id?: string;
configuration?: Record<string, unknown>;
};
diff --git a/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts b/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts
index 6f6e82adb0..0707bd9b32 100644
--- a/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts
+++ b/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts
@@ -347,7 +347,11 @@ export const getAzureConnectionAccessToken = async (
projectId: appConnection.projectId
})) as TAzureKeyVaultConnectionManagedIdentityCredentials;
- if (managedIdentityCredentials.expiresAt > currentTime + 300000) {
+ if (
+ managedIdentityCredentials.accessToken &&
+ managedIdentityCredentials.expiresAt &&
+ managedIdentityCredentials.expiresAt > currentTime + 300000
+ ) {
return { accessToken: managedIdentityCredentials.accessToken };
}
@@ -565,13 +569,16 @@ export const validateAzureKeyVaultConnectionCredentials = async (
clientId: string;
};
+ // A new connection has no ID yet, so Azure cannot trust its subject. Reconnecting verifies it once the
+ // customer has added the federated credential.
+ if (!connectionId) return { tenantId: managedIdentityTenantId, clientId: managedIdentityClientId };
+
try {
const managedIdentityToken = await getManagedIdentityAccessToken(
{
orgId,
projectId,
- // The create schema requires an ID for this method, and updates pass the connection's own
- connectionId: connectionId as string,
+ connectionId,
tenantId: managedIdentityTenantId,
clientId: managedIdentityClientId
},
diff --git a/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-schemas.ts b/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-schemas.ts
index 774e503536..532a6f5fba 100644
--- a/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-schemas.ts
+++ b/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-schemas.ts
@@ -79,8 +79,8 @@ export const AzureKeyVaultConnectionManagedIdentityInputCredentialsSchema = z.ob
export const AzureKeyVaultConnectionManagedIdentityOutputCredentialsSchema = z.object({
tenantId: z.string(),
clientId: z.string(),
- accessToken: z.string(),
- expiresAt: z.number()
+ accessToken: z.string().optional(),
+ expiresAt: z.number().optional()
});
export const ValidateAzureKeyVaultConnectionCredentialsSchema = z.discriminatedUnion("method", [
@@ -123,26 +123,15 @@ export const CreateAzureKeyVaultConnectionSchema = ValidateAzureKeyVaultConnecti
supportsCredentialRotation: true,
supportsGateways: true
})
-)
- .and(z.object({ id: z.string().uuid().optional().describe(AppConnections.CREATE(AppConnection.AzureKeyVault).id) }))
- .superRefine((data, ctx) => {
- if (data.method !== AzureKeyVaultConnectionMethod.ClientSecret && data.isAutoRotationEnabled) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: "Credential rotation is only supported for the client-secret method",
- path: ["isAutoRotationEnabled"]
- });
- }
-
- if (data.method === AzureKeyVaultConnectionMethod.ManagedIdentity && !data.id) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message:
- "The managed-identity method requires an ID. Set the federated credential's subject to 'app-connection:<id>' before creating the connection.",
- path: ["id"]
- });
- }
- });
+).superRefine((data, ctx) => {
+ if (data.method !== AzureKeyVaultConnectionMethod.ClientSecret && data.isAutoRotationEnabled) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Credential rotation is only supported for the client-secret method",
+ path: ["isAutoRotationEnabled"]
+ });
+ }
+});
export const UpdateAzureKeyVaultConnectionSchema = z
.object({
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx
index 009c41683d..25d1ba1708 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx
@@ -59,7 +59,7 @@ type ClientSecretForm = z.infer<typeof clientSecretSchema>;
type CertificateForm = z.infer<typeof certificateSchema>;
type ManagedIdentityForm = z.infer<typeof managedIdentitySchema>;
-type TInputFormData = ClientSecretForm | CertificateForm | (ManagedIdentityForm & { id?: string });
+type TInputFormData = ClientSecretForm | CertificateForm | ManagedIdentityForm;
type Props = {
appConnection?: TAzureKeyVaultConnection;
@@ -251,12 +251,8 @@ export const AzureKeyVaultConnectionForm = ({ appConnection, onSubmit, projectId
const { subscription } = useSubscription();
const { currentOrg } = useOrganization();
- // The subject Infisical signs is the connection's ID, so a new connection's ID is chosen here and shown
- // before it exists
- const [connectionId] = useState(() => appConnection?.id ?? window.crypto.randomUUID());
-
const { data: issuerUrl } = useGetOidcIssuerUrl(currentOrg.id, {
- enabled: selectedMethod === AzureKeyVaultConnectionMethod.ManagedIdentity
+ enabled: isUpdate && selectedMethod === AzureKeyVaultConnectionMethod.ManagedIdentity
});
const onSubmitHandler = async (formData: FormData) => {
@@ -283,10 +279,8 @@ export const AzureKeyVaultConnectionForm = ({ appConnection, onSubmit, projectId
await onSubmit(formData);
break;
case AzureKeyVaultConnectionMethod.Certificate:
- await onSubmit(formData);
- break;
case AzureKeyVaultConnectionMethod.ManagedIdentity:
- await onSubmit(isUpdate ? formData : { ...formData, id: connectionId });
+ await onSubmit(formData);
break;
default:
throw new Error(`Unhandled Azure Connection method: ${(formData as FormData).method}`);
@@ -679,16 +673,26 @@ export const AzureKeyVaultConnectionForm = ({ appConnection, onSubmit, projectId
</Field>
)}
/>
- <Field className="mb-4">
- <FieldLabel>Federated Credential</FieldLabel>
- <FieldDescription>
- Add a federated credential to the managed identity with the Other issuer scenario
- and these values.
+ {appConnection ? (
+ <Field className="mb-4">
+ <FieldLabel>Federated Credential</FieldLabel>
+ <FieldDescription>
+ Add a federated credential to the managed identity with the Other issuer scenario
+ and these values, then select Reconnect to Azure to verify it.
+ </FieldDescription>
+ {issuerUrl && <CopyableValue label="Issuer" value={issuerUrl} />}
+ <CopyableValue
+ label="Subject Identifier"
+ value={`app-connection:${appConnection.id}`}
+ />
+ <CopyableValue label="Audience" value={AZURE_FEDERATED_TOKEN_AUDIENCE} />
+ </Field>
+ ) : (
+ <FieldDescription className="mb-4">
+ After you create the connection, open Edit Credentials to copy the values for the
+ federated credential in Azure.
</FieldDescription>
- {issuerUrl && <CopyableValue label="Issuer" value={issuerUrl} />}
- <CopyableValue label="Subject Identifier" value={`app-connection:${connectionId}`} />
- <CopyableValue label="Audience" value={AZURE_FEDERATED_TOKEN_AUDIENCE} />
- </Field>
+ )}
</>
)}