Skip to content

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

serialize change to avoid race

Thiago Araujo da Silvac06463bf94b2
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index eda15f53c2..84f444fdb0 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -558,6 +558,8 @@ Built-in roles: `Admin`, `Member`, `Viewer`, `NoAccess`. For PAM and Agent Vault
**Identity auth-method access goes through `assertIdentityAuthAccessAllowed`** (`src/services/identity/identity-auth-permission-fns.ts`), because repointing an identity's auth trust lets the caller authenticate as that identity. It's both the gate and the boundary: it checks the identity action itself on both privilege systems, and on legacy also makes the actor out-rank every grant the target holds. The boundary alone isn't enough, since it passes for any target you cover, and for an org identity it only sees org-scope grants, so a no-access org identity that's admin in projects would be open to anyone. Callers don't repeat the action check. The 13 auth services and the template update call it once per attach/update/revoke, outside the `identity.projectId` branch so both scopes are covered, and a new auth method should too. Only the fine-grained action gates these paths, at both scopes; the old coarse org checks (`edit`, `create`, `read`, `delete`) are gone. Credential issuance (`createTokenAuthToken`, `createUniversalAuthClientSecret`) goes through it under `create-token`, since minting a credential is the same escalation as repointing the trust, and so do the per-credential paths: `updateTokenAuthToken` under `create-token`, `getUniversalAuthClientSecrets` / `getUniversalAuthClientSecretById` under `get-token`, and `revokeUniversalAuthClientSecret` under `delete-token`. **`PROJECT_ACTION_BY_ORG_ACTION` must map each org action to its project equivalent**, since project identities get checked against the mapped one. `revokeTokenAuthToken` and `clearUniversalAuthLockouts` are still unbounded in both scopes (and the former gates on `edit` where its UA counterpart gates on `delete-token`); that predates the helper and is a deliberate gap, not an oversight to copy. The target's grants come from `permissionService.getActorGrantAbilities`, not from a membership lookup, and it returns one ability per grant rather than per role. Two things a role-slug resolver misses: a group-derived membership carries a NULL `actorIdentityId`, so `membershipIdentityDAL.getIdentityById` never sees it, and an additional privilege carries a raw permission blob with no slug at all, so no `*PermissionByRoles` path can express it. Either omission clears an actor that out-ranks the target's direct roles but not its effective access. `getActorGrantAbilities` reads the same `permissionDAL.getPermission` query the ability itself is built from, so the bounded set cannot drift from the effective one.
+**Auth template propagation is serialized with row locks on `identity_auth_templates`.** A template edit rewrites every linked identity's auth, and a link copies the template's values onto the identity row, so the two must not interleave: a link landing between the edit's permission loop and its writes would be rewritten by an actor never checked against it, and an edit landing between a link's validation and its insert would leave the identity holding values the template no longer has. `updateTemplate` and `deleteTemplate` take the row `FOR UPDATE` as the first statement of their transaction, and the edit re-reads usages through `tx` under that lock and returns a 409 if an identity appeared since the checked set was built; its propagation writes are also scoped to the checked ids so the privilege invariant does not rest on the lock. Every path that copies template values onto an identity (the three attaches, and the three identity updates when they load a template) calls `assertTemplateUnchangedForLink` (`ee/services/identity-auth-template/identity-auth-template-fns.ts`) as the first statement of its transaction: a `FOR SHARE` read plus an `updatedAt` comparison against the row it validated outside the transaction, 409 on mismatch. Lock order is template row first, identity row second; unlink and non-linking identity updates take no template lock and never wait on it, so no cycle is possible. Nothing slow may sit under either lock, which is why LDAP attach runs `testLDAPConfig` before its transaction opens. A new path that copies template values onto an identity must call the helper inside its transaction.
+
**Deny an RBAC check by throwing through CASL, never with `ForbiddenRequestError`.** `audit-log-permission-denied.ts` records a permission-denied audit event for every CASL `ForbiddenError` and `PermissionBoundaryError` a request throws, and skips plain `ForbiddenRequestError` because most of those are auth-mode, plan and ownership refusals. A service that calls `permission.can()` and throws `ForbiddenRequestError` itself therefore produces no denial event, and nothing fails to tell you. When the check has a fallback (a second action, an approver, an application grant), test the fallbacks first and make `ForbiddenError.from(permission).throwUnlessCan(...)` the last check, so the denial is recorded with a real action and subject. Keep `ForbiddenRequestError` for refusals that are not about a permission.
**Project permission caching** uses a fingerprint-based two-tier cache (`withCacheFingerprint` in `src/lib/cache/with-cache.ts`):
diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-dal.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-dal.ts
index cf6d982911..b8393fa342 100644
--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-dal.ts
+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-dal.ts
@@ -100,11 +100,26 @@ export const identityAuthTemplateDALFactory = (db: TDbClient) => {
return doc?.[0];
};
+ const findByIdForUpdate = async (id: string, tx: Knex) => {
+ const doc = await tx(TableName.IdentityAuthTemplate).where({ id }).forUpdate().first();
+ return doc;
+ };
+
+ const findByIdForShare = async (id: string, tx: Knex) => {
+ const doc = await tx(TableName.IdentityAuthTemplate).where({ id }).forShare().first();
+ return doc;
+ };
+
+ const primaryNode = () => db.primaryNode();
+
return {
...identityAuthTemplateOrm,
findByOrgId,
findByAuthMethod,
findTemplateUsages,
- findByIdAndOrgId
+ findByIdAndOrgId,
+ findByIdForUpdate,
+ findByIdForShare,
+ primaryNode
};
};
diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-fns.test.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-fns.test.ts
new file mode 100644
index 0000000000..93d8f35298
--- /dev/null
+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-fns.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { ConflictError, NotFoundError } from "@app/lib/errors";
+
+import { assertTemplateUnchangedForLink } from "./identity-auth-template-fns";
+
+const UPDATED_AT = new Date("2026-10-01T00:00:00Z");
+const template = { id: "template-id", name: "auth-template", updatedAt: UPDATED_AT };
+const tx = { marker: "tx" };
+
+describe("assertTemplateUnchangedForLink", () => {
+ it("locks the row through the caller's transaction and passes when the template is unchanged", async () => {
+ const findByIdForShare = vi.fn().mockResolvedValue({ ...template, updatedAt: new Date(UPDATED_AT) });
+
+ await expect(assertTemplateUnchangedForLink({ findByIdForShare }, template, tx as never)).resolves.toBeUndefined();
+
+ expect(findByIdForShare).toHaveBeenCalledWith(template.id, tx);
+ });
+
+ it("rejects with a conflict when the template was edited since it was read", async () => {
+ const findByIdForShare = vi.fn().mockResolvedValue({ ...template, updatedAt: new Date("2026-10-01T00:00:01Z") });
+
+ const error = await assertTemplateUnchangedForLink({ findByIdForShare }, template, tx as never).catch(
+ (err: unknown) => err
+ );
+
+ expect(error).toBeInstanceOf(ConflictError);
+ expect((error as ConflictError).message).toContain("'auth-template' was modified");
+ });
+
+ it("rejects as not found when the template was deleted since it was read", async () => {
+ const findByIdForShare = vi.fn().mockResolvedValue(undefined);
+
+ await expect(assertTemplateUnchangedForLink({ findByIdForShare }, template, tx as never)).rejects.toBeInstanceOf(
+ NotFoundError
+ );
+ });
+});
diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-fns.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-fns.ts
new file mode 100644
index 0000000000..18d0b83aab
--- /dev/null
+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-fns.ts
@@ -0,0 +1,24 @@
+import { Knex } from "knex";
+
+import { TIdentityAuthTemplates } from "@app/db/schemas/identity-auth-templates";
+import { ConflictError, NotFoundError } from "@app/lib/errors";
+
+import { TIdentityAuthTemplateDALFactory } from "./identity-auth-template-dal";
+
+export const assertTemplateUnchangedForLink = async (
+ identityAuthTemplateDAL: Pick<TIdentityAuthTemplateDALFactory, "findByIdForShare">,
+ template: Pick<TIdentityAuthTemplates, "id" | "name" | "updatedAt">,
+ tx: Knex
+) => {
+ const lockedTemplate = await identityAuthTemplateDAL.findByIdForShare(template.id, tx);
+ if (!lockedTemplate) {
+ throw new NotFoundError({
+ message: `Auth template '${template.name}' was deleted while this request was in progress`
+ });
+ }
+ if (lockedTemplate.updatedAt.getTime() !== template.updatedAt.getTime()) {
+ throw new ConflictError({
+ message: `Auth template '${template.name}' was modified while this request was in progress. Retry the request.`
+ });
+ }
+};
diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts
index 01c1552259..e8398a1589 100644
--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts
+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts
@@ -7,7 +7,7 @@ import {
OrgPermissionSubjects
} from "@app/ee/services/permission/org-permission";
import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
-import { BadRequestError } from "@app/lib/errors";
+import { BadRequestError, ConflictError } from "@app/lib/errors";
import { IdentityKubernetesAuthTokenReviewMode } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-types";
import { IdentityAuthTemplateMethod } from "./identity-auth-template-enums";
@@ -79,8 +79,11 @@ const createService = ({
...gatewayColumns
};
+ const primaryNode = { marker: "primary" };
const identityAuthTemplateDAL = {
findByIdAndOrgId: vi.fn().mockResolvedValue(templateRow),
+ findByIdForUpdate: vi.fn().mockResolvedValue(templateRow),
+ primaryNode: vi.fn().mockReturnValue(primaryNode),
findTemplateUsages: vi.fn().mockResolvedValue(linkedIdentities),
updateById: vi.fn().mockImplementation((id: string, data: Record<string, unknown>) => ({
...templateRow,
@@ -131,6 +134,7 @@ const createService = ({
identityOidcAuthDAL,
identityLdapAuthDAL,
identityAuthTemplateDAL,
+ primaryNode,
auditLogCreate,
getProjectPermission
};
@@ -177,7 +181,7 @@ describe("identityAuthTemplateServiceFactory kubernetes host validation", () =>
await patchTemplate(service, { kubernetesHost: PRIVATE_HOST });
expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
- { templateId: TEMPLATE_ID },
+ { templateId: TEMPLATE_ID, identityIds: ["identity-id"] },
expect.objectContaining({ kubernetesHost: PRIVATE_HOST }),
expect.anything()
);
@@ -246,7 +250,7 @@ describe("identityAuthTemplateServiceFactory gateway column storage", () => {
await patchTemplate(service, { gatewayId: GATEWAY_V2_ID });
expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
- { templateId: TEMPLATE_ID },
+ { templateId: TEMPLATE_ID, identityIds: ["identity-id"] },
expect.objectContaining({ gatewayV2Id: GATEWAY_V2_ID, gatewayPoolId: null }),
expect.anything()
);
@@ -276,7 +280,7 @@ describe("identityAuthTemplateServiceFactory gateway column storage", () => {
expect(update).not.toHaveProperty("gatewayV2Id");
// linked rows still get the row's existing gateway, so they cannot drift from the template
expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
- { templateId: TEMPLATE_ID },
+ { templateId: TEMPLATE_ID, identityIds: ["identity-id"] },
expect.objectContaining({ gatewayV2Id: GATEWAY_V2_ID }),
expect.anything()
);
@@ -302,7 +306,7 @@ describe("identityAuthTemplateServiceFactory oidc templates", () => {
await patchTemplate(service, { boundIssuer: "https://other-issuer.example.com" });
expect(identityOidcAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
- { templateId: TEMPLATE_ID },
+ { templateId: TEMPLATE_ID, identityIds: ["identity-id"] },
{
oidcDiscoveryUrl: PUBLIC_HOST,
boundIssuer: "https://other-issuer.example.com",
@@ -319,7 +323,7 @@ describe("identityAuthTemplateServiceFactory oidc templates", () => {
await patchTemplate(service, { caCert: "" });
expect(identityOidcAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
- { templateId: TEMPLATE_ID },
+ { templateId: TEMPLATE_ID, identityIds: ["identity-id"] },
expect.objectContaining({ encryptedCaCertificate: null }),
expect.anything()
);
@@ -592,7 +596,7 @@ describe("identityAuthTemplateServiceFactory ldap url validation", () => {
await patchTemplate(service, { searchBase: "dc=other" });
expect(identityLdapAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
- { templateId: TEMPLATE_ID },
+ { templateId: TEMPLATE_ID, identityIds: ["identity-id"] },
{ searchBase: "dc=other" },
expect.anything()
);
@@ -634,3 +638,137 @@ describe("identityAuthTemplateServiceFactory ldap url validation", () => {
expect(identityAuthTemplateDAL.create).not.toHaveBeenCalled();
});
});
+
+describe("identityAuthTemplateServiceFactory propagation serialization", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("builds the checked set from the primary, not a replica", async () => {
+ const { service, identityAuthTemplateDAL, primaryNode } = createLdapService();
+
+ await patchTemplate(service, { searchBase: "dc=other" });
+
+ expect(identityAuthTemplateDAL.findTemplateUsages).toHaveBeenNthCalledWith(
+ 1,
+ TEMPLATE_ID,
+ IdentityAuthTemplateMethod.LDAP,
+ primaryNode
+ );
+ });
+
+ it("locks the template row and re-reads usages inside the transaction before writing", async () => {
+ const { service, identityAuthTemplateDAL, identityLdapAuthDAL } = createLdapService();
+ const order: string[] = [];
+ identityAuthTemplateDAL.findByIdForUpdate.mockImplementation(async () => {
+ order.push("lock");
+ return { id: TEMPLATE_ID };
+ });
+ identityAuthTemplateDAL.findTemplateUsages.mockImplementation(async (_id: string, _m: string, tx: unknown) => {
+ order.push(tx === identityAuthTemplateDAL.primaryNode() ? "read:primary" : "read:tx");
+ return [{ identityId: "identity-id", identityName: "identity", identityProjectId: null }];
+ });
+ identityLdapAuthDAL.updateByTemplateId.mockImplementation(async () => {
+ order.push("write");
+ return [{ identityId: "identity-id" }];
+ });
+
+ await patchTemplate(service, { searchBase: "dc=other" });
+
+ expect(order).toEqual(["read:primary", "lock", "read:tx", "write"]);
+ });
+
+ it("rejects the edit when an identity was linked after the permission check", async () => {
+ const { service, identityAuthTemplateDAL, identityLdapAuthDAL, auditLogCreate } = createLdapService();
+ identityAuthTemplateDAL.findTemplateUsages
+ .mockResolvedValueOnce([{ identityId: "identity-id", identityName: "identity", identityProjectId: null }])
+ .mockResolvedValueOnce([
+ { identityId: "identity-id", identityName: "identity", identityProjectId: null },
+ { identityId: "late-identity-id", identityName: "late", identityProjectId: null }
+ ]);
+
+ const error = await patchTemplate(service, { searchBase: "dc=other" }).catch((err: unknown) => err);
+
+ expect(error).toBeInstanceOf(ConflictError);
+ expect((error as ConflictError).message).toBe(
+ "1 identity was linked to auth template 'auth-template' while it was being edited. Retry the update."
+ );
+ expect(identityAuthTemplateDAL.updateById).not.toHaveBeenCalled();
+ expect(identityLdapAuthDAL.updateByTemplateId).not.toHaveBeenCalled();
+ expect(auditLogCreate).not.toHaveBeenCalled();
+ });
+
+ it("treats an identity unlinked mid-edit as a shrink, not a conflict", async () => {
+ const { service, identityAuthTemplateDAL, identityLdapAuthDAL } = createLdapService({
+ linkedIdentities: [
+ { identityId: "identity-id", identityName: "identity", identityProjectId: null },
+ { identityId: "leaving-id", identityName: "leaving", identityProjectId: null }
+ ]
+ });
+ identityAuthTemplateDAL.findTemplateUsages.mockResolvedValueOnce([
+ { identityId: "identity-id", identityName: "identity", identityProjectId: null },
+ { identityId: "leaving-id", identityName: "leaving", identityProjectId: null }
+ ]);
+ identityAuthTemplateDAL.findTemplateUsages.mockResolvedValueOnce([
+ { identityId: "identity-id", identityName: "identity", identityProjectId: null }
+ ]);
+
+ await patchTemplate(service, { searchBase: "dc=other" });
+
+ expect(identityLdapAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
+ { templateId: TEMPLATE_ID, identityIds: ["identity-id", "leaving-id"] },
+ { searchBase: "dc=other" },
+ expect.anything()
+ );
+ });
+
+ it("fails cleanly when the template is deleted before the lock is taken", async () => {
+ const { service, identityAuthTemplateDAL, identityLdapAuthDAL } = createLdapService();
+ identityAuthTemplateDAL.findByIdForUpdate.mockResolvedValueOnce(undefined);
+
+ await expect(patchTemplate(service, { searchBase: "dc=other" })).rejects.toThrow("Template not found");
+ expect(identityLdapAuthDAL.updateByTemplateId).not.toHaveBeenCalled();
+ });
+
+ it("does not lock or re-read on a rename, since nothing propagates", async () => {
+ const { service, identityAuthTemplateDAL } = createLdapService();
+
+ await service.updateTemplate({
+ templateId: TEMPLATE_ID,
+ name: "renamed",
+ actorId: "actor-id",
+ actor: "user",
+ actorAuthMethod: undefined,
+ actorOrgId: ORG_ID
+ } as unknown as Parameters<typeof service.updateTemplate>[0]);
+
+ expect(identityAuthTemplateDAL.findByIdForUpdate).not.toHaveBeenCalled();
+ expect(identityAuthTemplateDAL.findTemplateUsages).not.toHaveBeenCalled();
+ });
+
+ it("locks the template row before unlinking on delete", async () => {
+ const { service, identityAuthTemplateDAL, identityLdapAuthDAL } = createLdapService();
+ const order: string[] = [];
+ identityAuthTemplateDAL.findByIdForUpdate.mockImplementation(async () => {
+ order.push("lock");
+ return { id: TEMPLATE_ID };
+ });
+ identityLdapAuthDAL.updateByTemplateId.mockImplementation(async () => {
+ order.push("unlink");
+ return [{ identityId: "identity-id" }];
+ });
+
+ await service.deleteTemplate({
+ templateId: TEMPLATE_ID,
+ actorId: "actor-id",
+ actor: "user",
+ actorAuthMethod: undefined,
+ actorOrgId: ORG_ID
+ } as unknown as Parameters<typeof service.deleteTemplate>[0]);
+
+ expect(order).toEqual(["lock", "unlink"]);
+ expect(identityLdapAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
+ { templateId: TEMPLATE_ID },
+ { templateId: null },
+ expect.anything()
+ );
+ });
+});
diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts
index 7c2fb47b83..07193a1d8f 100644
--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts
+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts
@@ -15,7 +15,7 @@ import {
OrgPermissionSubjects
} from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { BadRequestError, ConflictError, NotFoundError } from "@app/lib/errors";
import { chunkArray } from "@app/lib/fn";
import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { sanitizeUrlForLog } from "@app/lib/logger";
@@ -434,14 +434,20 @@ export const identityAuthTemplateServiceFactory = ({
}
// captured before the propagation writes so the audit entries can carry readable
- // identity names alongside the ids
+ // identity names alongside the ids. read from the primary so a link that just committed
+ // is in the checked set rather than tripping the conflict check inside the transaction
const linkedIdentities = fieldPatch
- ? ((await identityAuthTemplateDAL.findTemplateUsages(templateId, template.authMethod)) as {
+ ? ((await identityAuthTemplateDAL.findTemplateUsages(
+ templateId,
+ template.authMethod,
+ identityAuthTemplateDAL.primaryNode()
+ )) as {
identityId: string;
identityName: string;
identityProjectId: string | null;
}[])
: [];
+ const checkedIdentityIds = linkedIdentities.map(({ identityId }) => identityId);
// a field patch rewrites every linked identity's auth, so the editor needs edit-auth on each.
// otherwise EditTemplates alone lets you point them at an LDAP server or OIDC issuer you control
@@ -590,6 +596,28 @@ export const identityAuthTemplateServiceFactory = ({
}
const { updatedTemplate, propagatedIdentityIds } = await identityAuthTemplateDAL.transaction(async (tx) => {
+ if (fieldPatch) {
+ const lockedTemplate = await identityAuthTemplateDAL.findByIdForUpdate(templateId, tx);
+ if (!lockedTemplate) {
+ throw new NotFoundError({ message: "Template not found" });
+ }
+ const currentUsages = (await identityAuthTemplateDAL.findTemplateUsages(
+ templateId,
+ template.authMethod,
+ tx
+ )) as {
+ identityId: string;
+ }[];
+ const uncheckedCount = currentUsages.filter(
+ ({ identityId }) => !checkedIdentityIds.includes(identityId)
+ ).length;
+ if (uncheckedCount > 0) {
+ throw new ConflictError({
+ message: `${uncheckedCount} ${uncheckedCount === 1 ? "identity was" : "identities were"} linked to auth template '${template.name}' while it was being edited. Retry the update.`
+ });
+ }
+ }
+
const authTemplate = await identityAuthTemplateDAL.updateById(
templateId,
{
@@ -640,14 +668,18 @@ export const identityAuthTemplateServiceFactory = ({
}
if (Object.keys(ldapUpdateData).length > 0) {
- const updatedRows = await identityLdapAuthDAL.updateByTemplateId({ templateId }, ldapUpdateData, tx);
+ const updatedRows = await identityLdapAuthDAL.updateByTemplateId(
+ { templateId, identityIds: checkedIdentityIds },
+ ldapUpdateData,
+ tx
+ );
identityIds = updatedRows.map((row) => row.identityId);
}
}
if (kubernetesPropagationData) {
const updatedRows = await identityKubernetesAuthDAL.updateByTemplateId(
- { templateId },
+ { templateId, identityIds: checkedIdentityIds },
kubernetesPropagationData,
tx
);
@@ -655,7 +687,11 @@ export const identityAuthTemplateServiceFactory = ({
}
if (oidcPropagationData) {
- const updatedRows = await identityOidcAuthDAL.updateByTemplateId({ templateId }, oidcPropagationData, tx);
+ const updatedRows = await identityOidcAuthDAL.updateByTemplateId(
+ { templateId, identityIds: checkedIdentityIds },
+ oidcPropagationData,
+ tx
+ );
identityIds = updatedRows.map((row) => row.identityId);
}
@@ -711,6 +747,10 @@ export const identityAuthTemplateServiceFactory = ({
}[];
const { deletedTemplate, unlinkedIdentityIds } = await identityAuthTemplateDAL.transaction(async (tx) => {
+ const lockedTemplate = await identityAuthTemplateDAL.findByIdForUpdate(templateId, tx);
+ if (!lockedTemplate) {
+ throw new NotFoundError({ message: "Template not found" });
+ }
// Unlink identity auth records; the copied config values are kept so linked
// identities keep authenticating
let identityIds: string[] = [];
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts
index 492704f38f..accc0dc709 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { IdentityAuthMethod } from "@app/db/schemas";
import { TKubernetesTemplateFields } from "@app/ee/services/identity-auth-template/identity-auth-template-types";
+import { ConflictError } from "@app/lib/errors";
import { identityKubernetesAuthServiceFactory } from "./identity-kubernetes-auth-service";
import { IdentityKubernetesAuthTokenReviewMode } from "./identity-kubernetes-auth-types";
@@ -63,9 +64,15 @@ const createService = ({
authMethod: "kubernetes",
// the fake cipher pair below round-trips plaintext, so the "encrypted" blob is the JSON
templateFields: Buffer.from(JSON.stringify(templateBlobFields)),
+ updatedAt: new Date("2026-10-01T00:00:00Z"),
...templateGatewayColumns
};
+ const identityAuthTemplateDAL = {
+ findByIdAndOrgId: vi.fn().mockResolvedValue(templateRow),
+ findByIdForShare: vi.fn().mockResolvedValue(templateRow)
+ };
+
const storedAuthRow = {
id: "k8s-auth-id",
identityId: IDENTITY_ID,
@@ -99,7 +106,7 @@ const createService = ({
identityDAL: { findById: vi.fn() },
identityKubernetesAuthDAL,
identityAccessTokenDAL: { delete: vi.fn() },
- identityAuthTemplateDAL: { findByIdAndOrgId: vi.fn().mockResolvedValue(templateRow) },
+ identityAuthTemplateDAL,
membershipIdentityDAL: {
findOne: vi.fn(),
update: vi.fn(),
@@ -147,7 +154,7 @@ const createService = ({
eventEmitter: { emit: vi.fn() }
} as unknown as Parameters<typeof identityKubernetesAuthServiceFactory>[0]);
- return { service, identityKubernetesAuthDAL };
+ return { service, identityKubernetesAuthDAL, identityAuthTemplateDAL, templateRow };
};
const baseActor = {
@@ -246,3 +253,62 @@ describe("identityKubernetesAuthServiceFactory template attach validation", () =
expect(identityKubernetesAuthDAL.updateById).not.toHaveBeenCalled();
});
});
+
+describe("identityKubernetesAuthServiceFactory template lock", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("holds the template row before inserting the link", async () => {
+ const { service, identityKubernetesAuthDAL, identityAuthTemplateDAL, templateRow } = createService();
+ const order: string[] = [];
+ identityAuthTemplateDAL.findByIdForShare.mockImplementation(async () => {
+ order.push("lock");
+ return templateRow;
+ });
+ identityKubernetesAuthDAL.create.mockImplementation(async (data: Record<string, unknown>) => {
+ order.push("create");
+ return { id: "k8s-auth-id", ...data };
+ });
+
+ await attachWithTemplate(service);
+
+ expect(order).toEqual(["lock", "create"]);
+ });
+
+ it("rejects an attach when the template was edited after it was validated", async () => {
+ const { service, identityKubernetesAuthDAL, identityAuthTemplateDAL, templateRow } = createService();
+ identityAuthTemplateDAL.findByIdForShare.mockResolvedValue({
+ ...templateRow,
+ updatedAt: new Date("2026-10-01T00:00:01Z")
+ });
+
+ await expect(attachWithTemplate(service)).rejects.toBeInstanceOf(ConflictError);
+ expect(identityKubernetesAuthDAL.create).not.toHaveBeenCalled();
+ });
+
+ it("rejects a link change on update when the template was edited after it was validated", async () => {
+ const { service, identityKubernetesAuthDAL, identityAuthTemplateDAL, templateRow } = createService({
+ identityAuthMethods: [IdentityAuthMethod.KUBERNETES_AUTH]
+ });
+ identityAuthTemplateDAL.findByIdForShare.mockResolvedValue({
+ ...templateRow,
+ updatedAt: new Date("2026-10-01T00:00:01Z")
+ });
+
+ await expect(updateWithTemplate(service)).rejects.toBeInstanceOf(ConflictError);
+ expect(identityKubernetesAuthDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ it("takes no template lock on an update that does not link a template", async () => {
+ const { service, identityAuthTemplateDAL } = createService({
+ identityAuthMethods: [IdentityAuthMethod.KUBERNETES_AUTH]
+ });
+
+ await service.updateKubernetesAuth({
+ ...baseActor,
+ identityId: IDENTITY_ID,
+ accessTokenTTL: 3600
+ } as unknown as Parameters<typeof service.updateKubernetesAuth>[0]);
+
+ expect(identityAuthTemplateDAL.findByIdForShare).not.toHaveBeenCalled();
+ });
+});
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
index ba900129c4..a5c06d255a 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
@@ -21,6 +21,7 @@ import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2
import { TGatewayV2ConnectionDetails } from "@app/ee/services/gateway-v2/gateway-v2-types";
import { TIdentityAuthTemplateDALFactory } from "@app/ee/services/identity-auth-template/identity-auth-template-dal";
import { IdentityAuthTemplateMethod } from "@app/ee/services/identity-auth-template/identity-auth-template-enums";
+import { assertTemplateUnchangedForLink } from "@app/ee/services/identity-auth-template/identity-auth-template-fns";
import { TKubernetesTemplateFields } from "@app/ee/services/identity-auth-template/identity-auth-template-types";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import {
@@ -108,7 +109,7 @@ type TIdentityKubernetesAuthServiceFactoryDep = {
"create" | "findOne" | "transaction" | "updateById" | "delete"
>;
identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;
- identityAuthTemplateDAL: Pick<TIdentityAuthTemplateDALFactory, "findByIdAndOrgId">;
+ identityAuthTemplateDAL: Pick<TIdentityAuthTemplateDALFactory, "findByIdAndOrgId" | "findByIdForShare">;
membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;
permissionService: Pick<
@@ -1087,6 +1088,9 @@ export const identityKubernetesAuthServiceFactory = ({
}
const identityKubernetesAuth = await identityKubernetesAuthDAL.transaction(async (tx) => {
+ if (template) {
+ await assertTemplateUnchangedForLink(identityAuthTemplateDAL, template, tx);
+ }
const doc = await identityKubernetesAuthDAL.create(
{
identityId: identityMembershipOrg.identity.id,
@@ -1581,6 +1585,9 @@ export const identityKubernetesAuthServiceFactory = ({
}
const updatedKubernetesAuth = await identityKubernetesAuthDAL.transaction(async (tx) => {
+ if (template) {
+ await assertTemplateUnchangedForLink(identityAuthTemplateDAL, template, tx);
+ }
const doc = await identityKubernetesAuthDAL.updateById(identityKubernetesAuth.id, updateQuery, tx);
await emitIdentityAuthMethodChanged(
eventEmitter,
diff --git a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.test.ts b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.test.ts
new file mode 100644
index 0000000000..1e5891e14b
--- /dev/null
+++ b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.test.ts
@@ -0,0 +1,214 @@
+import { createMongoAbility } from "@casl/ability";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { IdentityAuthMethod } from "@app/db/schemas";
+import { testLDAPConfig } from "@app/ee/services/ldap-config/ldap-fns";
+import { ConflictError } from "@app/lib/errors";
+
+import { identityLdapAuthServiceFactory } from "./identity-ldap-auth-service";
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ isDevelopmentMode: false, ALLOW_INTERNAL_IP_CONNECTIONS: false })
+}));
+
+vi.mock("../super-admin/super-admin-fns", () => ({
+ validateIdentityUpdateForSuperAdminPrivileges: vi.fn()
+}));
+
+vi.mock("@app/ee/services/ldap-config/ldap-fns", () => ({
+ testLDAPConfig: vi.fn().mockResolvedValue(true)
+}));
+
+const ORG_ID = "org-id";
+const IDENTITY_ID = "identity-id";
+const TEMPLATE_ID = "template-id";
+// a literal IP keeps the suite hermetic: blockLocalAndPrivateIpAddresses skips the DNS lookup
+const LDAP_URL = "ldap://8.8.8.8";
+
+const createService = ({ identityAuthMethods = [] as string[] }: { identityAuthMethods?: string[] } = {}) => {
+ const templateRow = {
+ id: TEMPLATE_ID,
+ orgId: ORG_ID,
+ name: "auth-template",
+ authMethod: "ldap",
+ // the fake cipher pair below round-trips plaintext, so the "encrypted" blob is the JSON
+ templateFields: Buffer.from(
+ JSON.stringify({ url: LDAP_URL, bindDN: "cn=admin", bindPass: "pw", searchBase: "dc=example" })
+ ),
+ updatedAt: new Date("2026-10-01T00:00:00Z")
+ };
+
+ const storedAuthRow = {
+ id: "ldap-auth-id",
+ identityId: IDENTITY_ID,
+ templateId: TEMPLATE_ID,
+ url: LDAP_URL,
+ searchBase: "dc=example",
+ searchFilter: "(uid={{username}})",
+ encryptedBindDN: Buffer.from("cn=admin"),
+ encryptedBindPass: Buffer.from("pw"),
+ encryptedLdapCaCertificate: null,
+ allowedFields: null,
+ accessTokenTTL: 7200,
+ accessTokenMaxTTL: 7200,
+ accessTokenNumUsesLimit: 0,
+ accessTokenTrustedIps: []
+ };
+
+ const identityLdapAuthDAL = {
+ create: vi.fn().mockImplementation((data: Record<string, unknown>) => ({ id: "ldap-auth-id", ...data })),
+ findOne: vi.fn().mockResolvedValue(storedAuthRow),
+ updateById: vi.fn().mockImplementation((id: string, data: Record<string, unknown>) => ({
+ ...storedAuthRow,
+ ...data
+ })),
+ delete: vi.fn(),
+ transaction: vi.fn().mockImplementation(async (cb: (tx: unknown) => Promise<unknown>) => cb({ marker: "tx" }))
+ };
+
+ const identityAuthTemplateDAL = {
+ findByIdAndOrgId: vi.fn().mockResolvedValue(templateRow),
+ findByIdForShare: vi.fn().mockResolvedValue(templateRow)
+ };
+
+ const service = identityLdapAuthServiceFactory({
+ identityAccessTokenDAL: { delete: vi.fn() },
+ identityDAL: { findById: vi.fn(), findOne: vi.fn().mockResolvedValue({ id: IDENTITY_ID }) },
+ identityLdapAuthDAL,
+ membershipIdentityDAL: {
+ findOne: vi.fn().mockResolvedValue({ scopeOrgId: ORG_ID }),
+ update: vi.fn(),
+ getIdentityById: vi.fn().mockResolvedValue({
+ scopeOrgId: ORG_ID,
+ identity: { id: IDENTITY_ID, orgId: ORG_ID, projectId: null, authMethods: identityAuthMethods }
+ })
+ },
+ licenseService: {
+ getPlan: vi.fn().mockResolvedValue({ ldap: true, machineIdentityAuthTemplates: true, ipAllowlisting: true })
+ },
+ permissionService: {
+ getOrgPermission: vi
+ .fn()
+ .mockResolvedValue({ permission: createMongoAbility([{ action: "manage", subject: "all" }]) }),
+ getProjectPermission: vi.fn(),
+ getActorGrantAbilities: vi.fn().mockResolvedValue([])
+ },
+ kmsService: {
+ createCipherPairWithDataKey: vi.fn().mockResolvedValue({
+ encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: plainText }),
+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob
+ })
+ },
+ identityAuthTemplateDAL,
+ keyStore: {},
+ orgDAL: {
+ findById: vi.fn().mockResolvedValue({ id: ORG_ID, shouldUseNewPrivilegeSystem: true }),
+ findOne: vi.fn(),
+ findEffectiveOrgMembership: vi.fn()
+ },
+ identityAccessTokenService: {
+ issueIdentityAccessToken: vi.fn(),
+ revokeTokensForIdentityAuthMethod: vi.fn(),
+ invalidateTrustedIpsCache: vi.fn()
+ },
+ eventEmitter: { emit: vi.fn() }
+ } as unknown as Parameters<typeof identityLdapAuthServiceFactory>[0]);
+
+ return { service, identityLdapAuthDAL, identityAuthTemplateDAL, templateRow };
+};
+
+const baseActor = {
+ actor: "user",
+ actorId: "actor-id",
+ actorAuthMethod: undefined,
+ actorOrgId: ORG_ID
+};
+
+const attachWithTemplate = (service: ReturnType<typeof createService>["service"]) =>
+ service.attachLdapAuth({
+ ...baseActor,
+ identityId: IDENTITY_ID,
+ templateId: TEMPLATE_ID,
+ searchFilter: "(uid={{username}})",
+ accessTokenTTL: 7200,
+ accessTokenMaxTTL: 7200,
+ accessTokenNumUsesLimit: 0,
+ accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }]
+ } as unknown as Parameters<typeof service.attachLdapAuth>[0]);
+
+describe("identityLdapAuthServiceFactory template lock", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("tests the LDAP connection before the transaction opens and locks the template before inserting", async () => {
+ const { service, identityLdapAuthDAL, identityAuthTemplateDAL, templateRow } = createService();
+ const order: string[] = [];
+ vi.mocked(testLDAPConfig).mockImplementation(async () => {
+ order.push("ldap-test");
+ return true;
+ });
+ identityLdapAuthDAL.transaction.mockImplementation(async (cb: (tx: unknown) => Promise<unknown>) => {
+ order.push("begin");
+ return cb({ marker: "tx" });
+ });
+ identityAuthTemplateDAL.findByIdForShare.mockImplementation(async (_id: string, tx: { marker: string }) => {
+ order.push(`lock:${tx.marker}`);
+ return templateRow;
+ });
+ identityLdapAuthDAL.create.mockImplementation(async (data: Record<string, unknown>) => {
+ order.push("create");
+ return { id: "ldap-auth-id", ...data };
+ });
+
+ await attachWithTemplate(service);
+
+ expect(order).toEqual(["ldap-test", "begin", "lock:tx", "create"]);
+ expect(identityLdapAuthDAL.create).toHaveBeenCalledWith(
+ expect.objectContaining({ templateId: TEMPLATE_ID, url: LDAP_URL }),
+ expect.anything()
+ );
+ });
+
+ it("rejects an attach when the template was edited after it was validated", async () => {
+ const { service, identityLdapAuthDAL, identityAuthTemplateDAL, templateRow } = createService();
+ identityAuthTemplateDAL.findByIdForShare.mockResolvedValue({
+ ...templateRow,
+ updatedAt: new Date("2026-10-01T00:00:01Z")
+ });
+
+ await expect(attachWithTemplate(service)).rejects.toBeInstanceOf(ConflictError);
+ expect(identityLdapAuthDAL.create).not.toHaveBeenCalled();
+ });
+
+ it("locks on update whenever a template is named, since LDAP copies its values on a re-assert too", async () => {
+ const { service, identityLdapAuthDAL, identityAuthTemplateDAL, templateRow } = createService({
+ identityAuthMethods: [IdentityAuthMethod.LDAP_AUTH]
+ });
+ identityAuthTemplateDAL.findByIdForShare.mockResolvedValue({
+ ...templateRow,
+ updatedAt: new Date("2026-10-01T00:00:01Z")
+ });
+
+ await expect(
+ service.updateLdapAuth({
+ ...baseActor,
+ identityId: IDENTITY_ID,
+ templateId: TEMPLATE_ID
+ } as unknown as Parameters<typeof service.updateLdapAuth>[0])
+ ).rejects.toBeInstanceOf(ConflictError);
+ expect(identityLdapAuthDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ it("takes no template lock on an update that names no template", async () => {
+ const { service, identityAuthTemplateDAL } = createService({
+ identityAuthMethods: [IdentityAuthMethod.LDAP_AUTH]
+ });
+
+ await service.updateLdapAuth({
+ ...baseActor,
+ identityId: IDENTITY_ID,
+ accessTokenTTL: 3600
+ } as unknown as Parameters<typeof service.updateLdapAuth>[0]);
+
+ expect(identityAuthTemplateDAL.findByIdForShare).not.toHaveBeenCalled();
+ });
+});
diff --git a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts
index 44a7473dbf..d6e21506e3 100644
--- a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts
+++ b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts
@@ -5,6 +5,7 @@ import slugify from "@sindresorhus/slugify";
import { AccessScope, ActionProjectType, IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas";
import { IdentityAuthTemplateMethod, TIdentityAuthTemplateDALFactory } from "@app/ee/services/identity-auth-template";
+import { assertTemplateUnchangedForLink } from "@app/ee/services/identity-auth-template/identity-auth-template-fns";
import { testLDAPConfig } from "@app/ee/services/ldap-config/ldap-fns";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import {
@@ -436,73 +437,76 @@ export const identityLdapAuthServiceFactory = ({
if (allowedFields) AllowedFieldsSchema.array().parse(allowedFields);
- const identityLdapAuth = await identityLdapAuthDAL.transaction(async (tx) => {
- const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.Organization,
- orgId: identityMembershipOrg.scopeOrgId
- });
+ const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId: identityMembershipOrg.scopeOrgId
+ });
- const template = templateId
- ? await identityAuthTemplateDAL.findByIdAndOrgId(templateId, identityMembershipOrg.scopeOrgId)
- : undefined;
- if (templateId && (!template || template.authMethod !== IdentityAuthTemplateMethod.LDAP)) {
- throw new NotFoundError({ message: `LDAP auth template with ID '${templateId}' not found` });
- }
+ const template = templateId
+ ? await identityAuthTemplateDAL.findByIdAndOrgId(templateId, identityMembershipOrg.scopeOrgId)
+ : undefined;
+ if (templateId && (!template || template.authMethod !== IdentityAuthTemplateMethod.LDAP)) {
+ throw new NotFoundError({ message: `LDAP auth template with ID '${templateId}' not found` });
+ }
- let ldapConfig: { bindDN: string; bindPass: string; searchBase: string; url: string; ldapCaCertificate?: string };
- if (template) {
- ldapConfig = JSON.parse(decryptor({ cipherTextBlob: template.templateFields }).toString());
- if (!ldapConfig.bindDN || !ldapConfig.bindPass || !ldapConfig.searchBase || !ldapConfig.url) {
- throw new BadRequestError({
- message: `LDAP auth template '${template.name}' is missing a bind DN, bind password, search base, or URL. Update the template before attaching it to an identity.`
- });
- }
- } else {
- if (!bindDN || !bindPass || !searchBase || !url) {
- throw new BadRequestError({
- message: "Invalid request. Missing bind DN, bind pass, search base, or URL."
- });
- }
- ldapConfig = {
- bindDN,
- bindPass,
- searchBase,
- url,
- ldapCaCertificate
- };
+ let ldapConfig: { bindDN: string; bindPass: string; searchBase: string; url: string; ldapCaCertificate?: string };
+ if (template) {
+ ldapConfig = JSON.parse(decryptor({ cipherTextBlob: template.templateFields }).toString());
+ if (!ldapConfig.bindDN || !ldapConfig.bindPass || !ldapConfig.searchBase || !ldapConfig.url) {
+ throw new BadRequestError({
+ message: `LDAP auth template '${template.name}' is missing a bind DN, bind password, search base, or URL. Update the template before attaching it to an identity.`
+ });
}
+ } else {
+ if (!bindDN || !bindPass || !searchBase || !url) {
+ throw new BadRequestError({
+ message: "Invalid request. Missing bind DN, bind pass, search base, or URL."
+ });
+ }
+ ldapConfig = {
+ bindDN,
+ bindPass,
+ searchBase,
+ url,
+ ldapCaCertificate
+ };
+ }
- const { cipherTextBlob: encryptedBindPass } = encryptor({
- plainText: Buffer.from(ldapConfig.bindPass)
- });
+ const { cipherTextBlob: encryptedBindPass } = encryptor({
+ plainText: Buffer.from(ldapConfig.bindPass)
+ });
+
+ const { cipherTextBlob: encryptedBindDN } = encryptor({
+ plainText: Buffer.from(ldapConfig.bindDN)
+ });
- const { cipherTextBlob: encryptedBindDN } = encryptor({
- plainText: Buffer.from(ldapConfig.bindDN)
+ let encryptedLdapCaCertificate: Buffer | undefined;
+ if (ldapConfig.ldapCaCertificate) {
+ const { cipherTextBlob: encryptedCertificate } = encryptor({
+ plainText: Buffer.from(ldapConfig.ldapCaCertificate)
});
- let encryptedLdapCaCertificate: Buffer | undefined;
- if (ldapConfig.ldapCaCertificate) {
- const { cipherTextBlob: encryptedCertificate } = encryptor({
- plainText: Buffer.from(ldapConfig.ldapCaCertificate)
- });
+ encryptedLdapCaCertificate = encryptedCertificate;
+ }
- encryptedLdapCaCertificate = encryptedCertificate;
- }
+ const isConnected = await testLDAPConfig({
+ bindDN: ldapConfig.bindDN,
+ bindPass: ldapConfig.bindPass,
+ caCert: ldapConfig.ldapCaCertificate || "",
+ url: ldapConfig.url
+ });
- const isConnected = await testLDAPConfig({
- bindDN: ldapConfig.bindDN,
- bindPass: ldapConfig.bindPass,
- caCert: ldapConfig.ldapCaCertificate || "",
- url: ldapConfig.url
+ if (!isConnected) {
+ throw new BadRequestError({
+ message:
+ "Failed to connect to LDAP server. Please ensure that the LDAP server is running and your credentials are correct."
});
+ }
- if (!isConnected) {
- throw new BadRequestError({
- message:
- "Failed to connect to LDAP server. Please ensure that the LDAP server is running and your credentials are correct."
- });
+ const identityLdapAuth = await identityLdapAuthDAL.transaction(async (tx) => {
+ if (template) {
+ await assertTemplateUnchangedForLink(identityAuthTemplateDAL, template, tx);
}
-
const doc = await identityLdapAuthDAL.create(
{
identityId: identityMembershipOrg.identity.id,
@@ -750,6 +754,9 @@ export const identityLdapAuthServiceFactory = ({
}
const updatedLdapAuth = await identityLdapAuthDAL.transaction(async (tx) => {
+ if (template) {
+ await assertTemplateUnchangedForLink(identityAuthTemplateDAL, template, tx);
+ }
const doc = await identityLdapAuthDAL.updateById(
identityLdapAuth.id,
{
diff --git a/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts b/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts
index 6f6d5c3892..e0e5aa08a4 100644
--- a/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts
+++ b/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts
@@ -14,6 +14,7 @@ import {
import { TIdentityAuthTemplates } from "@app/db/schemas/identity-auth-templates";
import { TIdentityAuthTemplateDALFactory } from "@app/ee/services/identity-auth-template/identity-auth-template-dal";
import { IdentityAuthTemplateMethod } from "@app/ee/services/identity-auth-template/identity-auth-template-enums";
+import { assertTemplateUnchangedForLink } from "@app/ee/services/identity-auth-template/identity-auth-template-fns";
import { TOidcTemplateFields } from "@app/ee/services/identity-auth-template/identity-auth-template-types";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import {
@@ -72,7 +73,7 @@ import {
type TIdentityOidcAuthServiceFactoryDep = {
identityDAL: Pick<TIdentityDALFactory, "findById">;
identityOidcAuthDAL: TIdentityOidcAuthDALFactory;
- identityAuthTemplateDAL: Pick<TIdentityAuthTemplateDALFactory, "findByIdAndOrgId">;
+ identityAuthTemplateDAL: Pick<TIdentityAuthTemplateDALFactory, "findByIdAndOrgId" | "findByIdForShare">;
membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;
identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;
@@ -740,6 +741,9 @@ export const identityOidcAuthServiceFactory = ({
await blockLocalAndPrivateIpAddresses(resolvedOidcDiscoveryUrl);
const identityOidcAuth = await identityOidcAuthDAL.transaction(async (tx) => {
+ if (template) {
+ await assertTemplateUnchangedForLink(identityAuthTemplateDAL, template, tx);
+ }
const doc = await identityOidcAuthDAL.create(
{
identityId: identityMembershipOrg.identity.id,
@@ -960,6 +964,9 @@ export const identityOidcAuthServiceFactory = ({
}
const updatedOidcAuth = await identityOidcAuthDAL.transaction(async (tx) => {
+ if (template) {
+ await assertTemplateUnchangedForLink(identityAuthTemplateDAL, template, tx);
+ }
const doc = await identityOidcAuthDAL.updateById(identityOidcAuth.id, updateQuery, tx);
await emitIdentityAuthMethodChanged(
eventEmitter,