Skip to content

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

fix: resolved test failing due to app issue

=f05edf6a598a
diff --git a/backend/src/ee/routes/v1/oidc-router.ts b/backend/src/ee/routes/v1/oidc-router.ts
index 7a05919e85..7c85c7863e 100644
--- a/backend/src/ee/routes/v1/oidc-router.ts
+++ b/backend/src/ee/routes/v1/oidc-router.ts
@@ -75,6 +75,7 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
rateLimit: authRateLimit
},
schema: {
+ operationId: "redirectOidcLogin",
querystring: z.object({
domain: z.string().trim().optional(),
orgSlug: z.string().trim().optional(),
@@ -123,6 +124,15 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
server.route({
url: "/callback",
method: "GET",
+ schema: {
+ operationId: "oidcCallback",
+ querystring: z
+ .object({
+ code: z.string().trim().max(4096).optional(),
+ state: z.string().trim().max(4096).optional()
+ })
+ .passthrough()
+ },
preValidation: [
async (req, res) => {
const oidcIdentifier = req.session.get<any>("oidcIdentifier");
@@ -195,6 +205,7 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
schema: {
hide: false,
+ operationId: "getOidcConfig",
tags: [ApiDocsTags.OidcSso],
description: "Get OIDC config",
security: [
@@ -249,6 +260,7 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
schema: {
hide: false,
+ operationId: "updateOidcConfig",
tags: [ApiDocsTags.OidcSso],
description: "Update OIDC config",
security: [
@@ -342,6 +354,7 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
schema: {
hide: false,
+ operationId: "createOidcConfig",
tags: [ApiDocsTags.OidcSso],
description: "Create OIDC config",
security: [
diff --git a/backend/src/ee/routes/v1/scim-router.ts b/backend/src/ee/routes/v1/scim-router.ts
index 63885b91a2..c0d429c3df 100644
--- a/backend/src/ee/routes/v1/scim-router.ts
+++ b/backend/src/ee/routes/v1/scim-router.ts
@@ -54,6 +54,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT]),
schema: {
+ operationId: "createScimToken",
body: z.object({
organizationId: z.string().trim(),
description: z.string().trim().default(""),
@@ -88,6 +89,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
schema: {
+ operationId: "listScimTokens",
querystring: z.object({
organizationId: z.string().trim()
}),
@@ -118,6 +120,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT]),
schema: {
+ operationId: "deleteScimToken",
params: z.object({
scimTokenId: z.string().trim()
}),
@@ -148,6 +151,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
schema: {
+ operationId: "listScimEvents",
querystring: z.object({
since: z.string().trim().optional(),
limit: z.coerce.number().min(1).max(100).default(30).optional(),
@@ -186,6 +190,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.SCIM_TOKEN]),
schema: {
+ operationId: "getScimServiceProviderConfig",
response: {
200: z.object({
schemas: z.array(z.string()),
@@ -273,6 +278,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
url: "/Users",
method: "GET",
schema: {
+ operationId: "listScimUsers",
querystring: z.object({
startIndex: z.coerce.number().default(1),
count: z.coerce.number().default(20),
@@ -304,6 +310,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
url: "/Users/:orgMembershipId",
method: "GET",
schema: {
+ operationId: "getScimUser",
params: z.object({
orgMembershipId: z.string().trim()
}),
@@ -328,6 +335,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
rateLimit: writeLimit
},
schema: {
+ operationId: "createScimUser",
body: z.object({
schemas: z.array(z.string()).default(["urn:ietf:params:scim:schemas:core:2.0:User"]),
userName: z.string().trim(),
@@ -360,6 +368,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
email: primaryEmail,
firstName: req.body?.name?.givenName,
lastName: req.body?.name?.familyName,
+ active: req.body.active,
orgId: req.permission.orgId
});
@@ -371,6 +380,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
url: "/Users/:orgMembershipId",
method: "DELETE",
schema: {
+ operationId: "deleteScimUser",
params: z.object({
orgMembershipId: z.string().trim()
}),
@@ -393,6 +403,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
url: "/Users/:orgMembershipId",
method: "PUT",
schema: {
+ operationId: "replaceScimUser",
params: z.object({
orgMembershipId: z.string().trim()
}),
@@ -457,6 +468,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
url: "/Users/:orgMembershipId",
method: "PATCH",
schema: {
+ operationId: "patchScimUser",
params: z.object({
orgMembershipId: z.string().trim()
}),
@@ -502,6 +514,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
url: "/Groups",
method: "POST",
schema: {
+ operationId: "createScimGroup",
body: z.object({
schemas: z.array(z.string()).default(["urn:ietf:params:scim:schemas:core:2.0:Group"]),
displayName: z.string().trim(),
@@ -534,6 +547,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
url: "/Groups",
method: "GET",
schema: {
+ operationId: "listScimGroups",
querystring: z.object({
startIndex: z.coerce.number().default(1),
count: z.coerce.number().default(20),
@@ -571,6 +585,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
url: "/Groups/:groupId",
method: "GET",
schema: {
+ operationId: "getScimGroup",
params: z.object({
groupId: z.string().trim()
}),
@@ -597,6 +612,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
url: "/Groups/:groupId",
method: "PUT",
schema: {
+ operationId: "replaceScimGroup",
params: z.object({
groupId: z.string().trim()
}),
@@ -633,6 +649,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
url: "/Groups/:groupId",
method: "PATCH",
schema: {
+ operationId: "patchScimGroup",
params: z.object({
groupId: z.string().trim()
}),
@@ -678,6 +695,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
url: "/Groups/:groupId",
method: "DELETE",
schema: {
+ operationId: "deleteScimGroup",
params: z.object({
groupId: z.string().trim()
}),
diff --git a/backend/src/ee/services/scim/scim-fns.test.ts b/backend/src/ee/services/scim/scim-fns.test.ts
new file mode 100644
index 0000000000..e9d2b45504
--- /dev/null
+++ b/backend/src/ee/services/scim/scim-fns.test.ts
@@ -0,0 +1,95 @@
+import { ScimRequestError } from "@app/lib/errors";
+
+import {
+ applyScimPatch,
+ assertParsableScimFilter,
+ buildScimUser,
+ isScimActive,
+ parseScimGroupFilter
+} from "./scim-fns";
+
+const scimErrorOf = (fn: () => unknown) => {
+ try {
+ fn();
+ } catch (err) {
+ if (err instanceof ScimRequestError) return err;
+ throw err;
+ }
+ throw new Error("expected a ScimRequestError");
+};
+
+describe("parseScimGroupFilter", () => {
+ test("keeps a display name containing the operator text intact", () => {
+ expect(parseScimGroupFilter('displayName eq "Requests"')).toEqual({ name: "Requests" });
+ expect(parseScimGroupFilter('displayName eq "equity eq team"')).toEqual({ name: "equity eq team" });
+ });
+
+ test("treats the attribute name case-insensitively", () => {
+ expect(parseScimGroupFilter('DisplayName eq "Eng"')).toEqual({ name: "Eng" });
+ });
+
+ test("looks up by id, and matches nothing for an id that is not a UUID", () => {
+ const id = "2b9f6c1e-1f0a-4d6e-9a43-6a3e6f1c2d7b";
+ expect(parseScimGroupFilter(`id eq "${id}"`)).toEqual({ id });
+ expect(parseScimGroupFilter('id eq "not-a-uuid"')).toBeNull();
+ });
+
+ test("returns no constraint without a filter", () => {
+ expect(parseScimGroupFilter(undefined)).toEqual({});
+ });
+
+ test.each(["displayName eq", 'displayName sw "Eng"', 'externalId eq "x"', 'displayName eq "a" or id eq "b"'])(
+ "refuses %s as invalidFilter",
+ (filter) => {
+ const err = scimErrorOf(() => parseScimGroupFilter(filter));
+ expect(err.status).toBe(400);
+ expect(err.scimType).toBe("invalidFilter");
+ }
+ );
+});
+
+describe("assertParsableScimFilter", () => {
+ test("accepts a valid filter and refuses one that does not parse", () => {
+ expect(() => assertParsableScimFilter('userName eq "[email protected]" and active eq true')).not.toThrow();
+ const err = scimErrorOf(() => assertParsableScimFilter("userName eq"));
+ expect(err.status).toBe(400);
+ expect(err.scimType).toBe("invalidFilter");
+ });
+});
+
+describe("applyScimPatch", () => {
+ const user = () =>
+ buildScimUser({
+ orgMembershipId: "m-1",
+ username: "[email protected]",
+ email: "[email protected]",
+ firstName: "Ada",
+ lastName: "L",
+ active: true,
+ createdAt: new Date(),
+ updatedAt: new Date()
+ });
+
+ test("applies a valid operation", () => {
+ const patched = applyScimPatch(user(), [{ op: "replace", path: "active", value: false }]);
+ expect(patched.active).toBe(false);
+ });
+
+ test("answers 400 with the library's scimType for a malformed path", () => {
+ const err = scimErrorOf(() => applyScimPatch(user(), [{ op: "replace", path: "name[", value: "x" }]));
+ expect(err.status).toBe(400);
+ expect(err.scimType).toBe("invalidSyntax");
+ });
+});
+
+describe("isScimActive", () => {
+ test.each([
+ [true, true],
+ [false, false],
+ ["True", true],
+ ["False", false],
+ ["false", false]
+ ])("reads %s as %s", (value, expected) => {
+ expect(isScimActive(value)).toBe(expected);
+ });
+});
diff --git a/backend/src/ee/services/scim/scim-fns.ts b/backend/src/ee/services/scim/scim-fns.ts
index d5a1f157d4..0b9b18764e 100644
--- a/backend/src/ee/services/scim/scim-fns.ts
+++ b/backend/src/ee/services/scim/scim-fns.ts
@@ -1,37 +1,81 @@
+import { ScimError, scimPatch, ScimPatchOperation, ScimResource } from "scim-patch";
+import { parse } from "scim2-parse-filter";
+
+import { ScimRequestError } from "@app/lib/errors";
+import { isUuidV4 } from "@app/lib/validator/validate-uuid";
+
import { TListScimGroups, TListScimUsers, TScimGroup, TScimUser } from "./scim-types";
export const buildScimUserList = ({
scimUsers,
startIndex,
- limit,
totalResults
}: {
scimUsers: TScimUser[];
startIndex: number;
- limit: number;
totalResults: number;
}): TListScimUsers => {
return {
Resources: scimUsers,
- itemsPerPage: limit,
+ itemsPerPage: scimUsers.length,
schemas: ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
startIndex,
totalResults
};
};
-export const parseScimFilter = (filterToParse: string | undefined) => {
- if (!filterToParse) return {};
- const [parsedName, parsedValue] = filterToParse.split("eq").map((s) => s.trim());
+const invalidScimFilter = (detail: string, error?: unknown) =>
+ new ScimRequestError({ detail, status: 400, scimType: "invalidFilter", error });
- let attributeName = parsedName;
- if (parsedName === "userName") {
- attributeName = "email";
- } else if (parsedName === "displayName") {
- attributeName = "name";
+const parseFilterOrThrow = (filter: string) => {
+ try {
+ return parse(filter);
+ } catch (err) {
+ throw invalidScimFilter(`The filter '${filter}' could not be parsed.`, err);
}
+};
+
+export const assertParsableScimFilter = (filter: string | undefined) => {
+ if (filter) parseFilterOrThrow(filter);
+};
+
+const SCIM_GROUP_FILTER_COLUMNS: Record<string, "name" | "id"> = {
+ displayname: "name",
+ id: "id"
+};
+
+/**
+ * Groups support a single `eq` comparison on displayName or id, which is what IdPs send to
+ * look a group up before creating it. Returns null when the filter can match no group.
+ */
+export const parseScimGroupFilter = (filter: string | undefined): { name?: string; id?: string } | null => {
+ if (!filter) return {};
- return { [attributeName]: parsedValue.replaceAll('"', "") };
+ const ast = parseFilterOrThrow(filter);
+ const column =
+ ast.op === "eq" && "attrPath" in ast ? SCIM_GROUP_FILTER_COLUMNS[ast.attrPath.toLowerCase()] : undefined;
+ if (!column || !("compValue" in ast) || typeof ast.compValue !== "string") {
+ throw invalidScimFilter(
+ `The filter '${filter}' is not supported. Groups can be filtered by 'displayName eq "<name>"' or 'id eq "<id>"'.`
+ );
+ }
+
+ if (column === "name") return { name: ast.compValue };
+ return isUuidV4(ast.compValue) ? { id: ast.compValue } : null;
+};
+
+// A PATCH value is not validated by the route schema, and Entra sends booleans as "True"/"False".
+export const isScimActive = (active: unknown) => String(active).toLowerCase() === "true";
+
+export const applyScimPatch = <T extends ScimResource>(resource: T, operations: ScimPatchOperation[]) => {
+ try {
+ return scimPatch(resource, operations);
+ } catch (err) {
+ if (err instanceof ScimError) {
+ throw new ScimRequestError({ detail: err.message, status: 400, scimType: err.scimCode, error: err });
+ }
+ throw err;
+ }
};
export const buildScimUser = ({
@@ -86,17 +130,15 @@ export const buildScimUser = ({
export const buildScimGroupList = ({
scimGroups,
startIndex,
- limit,
totalResults
}: {
scimGroups: TScimGroup[];
startIndex: number;
- limit: number;
totalResults: number;
}): TListScimGroups => {
return {
Resources: scimGroups,
- itemsPerPage: limit,
+ itemsPerPage: scimGroups.length,
schemas: ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
startIndex,
totalResults
diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.ts
index 2381ca41e7..55415a2fb7 100644
--- a/backend/src/ee/services/scim/scim-service.ts
+++ b/backend/src/ee/services/scim/scim-service.ts
@@ -1,7 +1,6 @@
import { ForbiddenError } from "@casl/ability";
import slugify from "@sindresorhus/slugify";
import { Knex } from "knex";
-import { scimPatch } from "scim-patch";
import {
AccessScope,
@@ -36,6 +35,7 @@ import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { recordScimOperationMetric, ScimOperation } from "@app/lib/telemetry/metrics";
import { sanitizeEmail, validateEmail } from "@app/lib/validator/validate-email";
+import { isUuidV4 } from "@app/lib/validator/validate-uuid";
import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";
import { prepareDeletedGroupAlertRecipientCleanup } from "@app/services/alert/alert-recipient-cleanup-fns";
@@ -47,6 +47,7 @@ import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
import { TMembershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";
import { TMembershipUserDALFactory } from "@app/services/membership-user/membership-user-dal";
+import { assertWillRetainOrgAdmin } from "@app/services/membership-user/membership-user-fns";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { deleteOrgMembershipsFn } from "@app/services/org/org-fns";
import { getDefaultOrgMembershipRole } from "@app/services/org/org-role-fns";
@@ -67,7 +68,16 @@ import { TLicenseServiceFactory } from "../license/license-service";
import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service-types";
import { TScimEventsDALFactory } from "./scim-events-dal";
-import { buildScimGroup, buildScimGroupList, buildScimUser, buildScimUserList, parseScimFilter } from "./scim-fns";
+import {
+ applyScimPatch,
+ assertParsableScimFilter,
+ buildScimGroup,
+ buildScimGroupList,
+ buildScimUser,
+ buildScimUserList,
+ isScimActive,
+ parseScimGroupFilter
+} from "./scim-fns";
import { ScimEvent, TScimGroup, TScimServiceFactory } from "./scim-types";
const verifyEmailDomainOwnership = async (args: {
@@ -242,12 +252,6 @@ export const scimServiceFactory = ({
});
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Scim);
- const plan = await licenseService.getPlan(orgId);
- if (!plan.scim)
- throw new BadRequestError({
- message: "Failed to get SCIM tokens due to plan restriction. Upgrade plan to get SCIM tokens."
- });
-
const scimTokens = await scimDAL.find({ orgId });
return scimTokens;
};
@@ -259,8 +263,11 @@ export const scimServiceFactory = ({
actorAuthMethod,
actorOrgId
}) => {
- let scimToken = await scimDAL.findById(scimTokenId);
- if (!scimToken) throw new NotFoundError({ message: `SCIM token with ID '${scimTokenId}' not found` });
+ let scimToken = isUuidV4(scimTokenId) ? await scimDAL.findById(scimTokenId) : undefined;
+ // Another organization's token reads as missing, so its id cannot be confirmed by probing.
+ if (!scimToken || scimToken.orgId !== actorOrgId) {
+ throw new NotFoundError({ message: `SCIM token with ID '${scimTokenId}' not found` });
+ }
const { permission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.ParentOrganization,
@@ -272,12 +279,6 @@ export const scimServiceFactory = ({
});
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Delete, OrgPermissionSubjects.Scim);
- const plan = await licenseService.getPlan(scimToken.orgId);
- if (!plan.scim)
- throw new BadRequestError({
- message: "Failed to delete the SCIM token due to plan restriction. Upgrade plan to delete the SCIM token."
- });
-
scimToken = await scimDAL.deleteById(scimTokenId);
return scimToken;
@@ -338,6 +339,8 @@ export const scimServiceFactory = ({
status: 403
});
+ assertParsableScimFilter(filter);
+
const findOpts = {
...(startIndex && { offset: startIndex - 1 }),
...(limit && { limit })
@@ -374,7 +377,6 @@ export const scimServiceFactory = ({
return buildScimUserList({
scimUsers,
startIndex,
- limit,
totalResults
});
};
@@ -396,9 +398,11 @@ export const scimServiceFactory = ({
// Use findMembershipWithScimFilter with the membershipId parameter
// This ensures we use the same alias-type and latest-alias selection as listScimUsers
- const [membership] = await orgDAL.findMembershipWithScimFilter(orgId, undefined, org.orgAuthMethod, {
- membershipId: orgMembershipId
- });
+ const [membership] = isUuidV4(orgMembershipId)
+ ? await orgDAL.findMembershipWithScimFilter(orgId, undefined, org.orgAuthMethod, {
+ membershipId: orgMembershipId
+ })
+ : [];
if (!membership)
throw new ScimRequestError({
@@ -435,6 +439,7 @@ export const scimServiceFactory = ({
email,
firstName,
lastName,
+ active,
orgId
}) => {
if (!email) throw new ScimRequestError({ detail: "Invalid request. Missing email.", status: 400 });
@@ -502,7 +507,7 @@ export const scimServiceFactory = ({
scopeOrgId: orgId,
scope: AccessScope.Organization,
status: OrgMembershipStatus.Invited,
- isActive: true
+ isActive: active
},
tx
);
@@ -566,7 +571,7 @@ export const scimServiceFactory = ({
scopeOrgId: orgId,
scope: AccessScope.Organization,
status: OrgMembershipStatus.Invited,
- isActive: true
+ isActive: active
},
tx
);
@@ -613,7 +618,7 @@ export const scimServiceFactory = ({
});
}
- if (email) {
+ if (email && createdOrgMembership.isActive) {
await smtpService.sendMail({
template: SmtpTemplates.ScimUserProvisioned,
subjectLine: "Infisical organization invitation",
@@ -789,7 +794,7 @@ export const scimServiceFactory = ({
createdAt: membership.createdAt,
updatedAt: membership.updatedAt
});
- scimPatch(scimUser, operations);
+ applyScimPatch(scimUser, operations);
const newEmail = await $resolveScimEmailChange({
org,
@@ -807,6 +812,15 @@ export const scimServiceFactory = ({
try {
await userDAL.transaction(async (tx) => {
+ if (membership.isActive && !isScimActive(scimUser.active)) {
+ await assertWillRetainOrgAdmin({
+ scopeOrgId: orgId,
+ excludeMembershipIds: [membership.id],
+ dal: membershipUserDAL,
+ tx
+ });
+ }
+
await membershipUserDAL.updateById(
membership.id,
{
@@ -866,7 +880,18 @@ export const scimServiceFactory = ({
sendPamCancellations();
- return scimUser;
+ // Answer with what was stored: the patch can add values this resource does not keep (a
+ // second email, a new userName), and echoing those would tell the IdP they were saved.
+ return buildScimUser({
+ orgMembershipId: membership.id,
+ username: userAliases?.[0]?.externalId ?? user.username,
+ email: newEmail ?? user.email,
+ firstName: scimUser.name.givenName,
+ lastName: scimUser.name.familyName,
+ active: scimUser.active,
+ createdAt: membership.createdAt,
+ updatedAt: new Date()
+ });
};
const replaceScimUser: TScimServiceFactory["replaceScimUser"] = async ({
@@ -939,6 +964,15 @@ export const scimServiceFactory = ({
try {
await userDAL.transaction(async (tx) => {
+ if (membership.isActive && !active) {
+ await assertWillRetainOrgAdmin({
+ scopeOrgId: orgId,
+ excludeMembershipIds: [membership.id],
+ dal: membershipUserDAL,
+ tx
+ });
+ }
+
await membershipUserDAL.updateById(
membership.id,
{
@@ -1018,11 +1052,13 @@ export const scimServiceFactory = ({
};
const deleteScimUser: TScimServiceFactory["deleteScimUser"] = async ({ orgMembershipId, orgId }) => {
- const [membership] = await orgDAL.findMembership({
- [`${TableName.Membership}.id` as "id"]: orgMembershipId,
- [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,
- [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization
- });
+ const [membership] = isUuidV4(orgMembershipId)
+ ? await orgDAL.findMembership({
+ [`${TableName.Membership}.id` as "id"]: orgMembershipId,
+ [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,
+ [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization
+ })
+ : [];
if (!membership) {
await scimEventsDAL.create({
@@ -1089,12 +1125,6 @@ export const scimServiceFactory = ({
filter,
isMembersExcluded
}) => {
- const plan = await licenseService.getPlan(orgId);
- if (!plan.groups)
- throw new BadRequestError({
- message: "Failed to list SCIM groups due to plan restriction. Upgrade plan to list SCIM groups."
- });
-
const org = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
if (!org) {
throw new ScimRequestError({
@@ -1109,8 +1139,13 @@ export const scimServiceFactory = ({
status: 403
});
+ const parsedFilter = parseScimGroupFilter(filter);
+ if (!parsedFilter) {
+ return buildScimGroupList({ scimGroups: [], startIndex, totalResults: 0 });
+ }
+
const groupFilter = {
- ...(filter && parseScimFilter(filter)),
+ ...parsedFilter,
orgId
};
@@ -1137,7 +1172,6 @@ export const scimServiceFactory = ({
})
),
startIndex,
- limit,
totalResults
});
}
@@ -1169,7 +1203,6 @@ export const scimServiceFactory = ({
return buildScimGroupList({
scimGroups,
startIndex,
- limit,
totalResults
});
};
@@ -1350,16 +1383,26 @@ export const scimServiceFactory = ({
};
const getScimGroup: TScimServiceFactory["getScimGroup"] = async ({ groupId, orgId, isMembersExcluded }) => {
- const plan = await licenseService.getPlan(orgId);
- if (!plan.groups)
- throw new BadRequestError({
- message: "Failed to get SCIM group due to plan restriction. Upgrade plan to get SCIM group."
+ const org = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
+ if (!org) {
+ throw new ScimRequestError({
+ detail: "Organization Not Found",
+ status: 404
});
+ }
- const group = await groupDAL.findOne({
- id: groupId,
- orgId
- });
+ if (!org.scimEnabled)
+ throw new ScimRequestError({
+ detail: "SCIM is disabled for the organization",
+ status: 403
+ });
+
+ const group = isUuidV4(groupId)
+ ? await groupDAL.findOne({
+ id: groupId,
+ orgId
+ })
+ : undefined;
if (!group) {
throw new ScimRequestError({
@@ -1437,13 +1480,15 @@ export const scimServiceFactory = ({
}: { displayName: string; members: { value: string }[]; shouldFailOnMissingMembers?: boolean; tx?: Knex }
) => {
const processReplacement = async (tx: Knex) => {
- let group = await groupDAL.findOne(
- {
- id: groupId,
- orgId
- },
- tx
- );
+ let group = isUuidV4(groupId)
+ ? await groupDAL.findOne(
+ {
+ id: groupId,
+ orgId
+ },
+ tx
+ )
+ : undefined;
if (!group) {
throw new ScimRequestError({
@@ -1453,6 +1498,15 @@ export const scimServiceFactory = ({
}
if (group.name !== displayName) {
+ const conflictingGroup = await groupDAL.findOne({ name: displayName, orgId }, tx);
+ if (conflictingGroup) {
+ throw new ScimRequestError({
+ detail: `Group with name '${displayName}' already exists in the organization`,
+ status: 409,
+ scimType: "uniqueness"
+ });
+ }
+
await externalGroupOrgRoleMappingDAL.update(
{
groupName: group.name,
@@ -1589,16 +1643,18 @@ export const scimServiceFactory = ({
status: 403
});
- const updatedGroup = await groupDAL.transaction(async (tx) => {
+ const { updatedGroup, appliedMembers } = await groupDAL.transaction(async (tx) => {
// Acquire advisory lock to serialize concurrent SCIM PUT requests for the same group
await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.ScimGroupUpdate(groupId)]);
- return $replaceGroupDAL(groupId, orgId, {
+ const group = await $replaceGroupDAL(groupId, orgId, {
displayName,
members,
shouldFailOnMissingMembers: false,
tx
});
+ const groupMembers = await userGroupMembershipDAL.findGroupMembershipsByGroupIdInOrg(group.id, orgId, tx);
+ return { updatedGroup: group, appliedMembers: groupMembers };
});
await scimEventsDAL.create({
@@ -1606,14 +1662,19 @@ export const scimServiceFactory = ({
eventType: ScimEvent.REPLACE_GROUP,
event: {
groupName: updatedGroup.name,
- numberOfMembers: members.length
+ numberOfMembers: appliedMembers.length
}
});
+ // Answer with the members that were applied: ids outside the org are dropped, and echoing
+ // the request would tell the IdP they were added.
return buildScimGroup({
groupId: updatedGroup.id,
name: updatedGroup.name,
- members,
+ members: appliedMembers.map((member) => ({
+ value: member.orgMembershipId,
+ display: `${member.firstName ?? ""} ${member.lastName ?? ""}`
+ })),
updatedAt: updatedGroup.updatedAt,
createdAt: updatedGroup.createdAt
});
@@ -1645,13 +1706,15 @@ export const scimServiceFactory = ({
// Acquire advisory lock to serialize concurrent SCIM PATCH requests for the same group
await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.ScimGroupUpdate(groupId)]);
- const group = await groupDAL.findOne(
- {
- id: groupId,
- orgId
- },
- tx
- );
+ const group = isUuidV4(groupId)
+ ? await groupDAL.findOne(
+ {
+ id: groupId,
+ orgId
+ },
+ tx
+ )
+ : undefined;
if (!group) {
throw new ScimRequestError({
@@ -1670,7 +1733,7 @@ export const scimServiceFactory = ({
createdAt: group.createdAt,
updatedAt: group.updatedAt
});
- scimPatch(patchedScimGroup, operations);
+ applyScimPatch(patchedScimGroup, operations);
// Apply the patched state with idempotent operations
await $replaceGroupDAL(groupId, orgId, {
@@ -1704,12 +1767,6 @@ export const scimServiceFactory = ({
};
const deleteScimGroup: TScimServiceFactory["deleteScimGroup"] = async ({ groupId, orgId }) => {
- const plan = await licenseService.getPlan(orgId);
- if (!plan.groups)
- throw new BadRequestError({
- message: "Failed to delete SCIM group due to plan restriction. Upgrade plan to delete SCIM group."
- });
-
const org = await requestMemoize(requestMemoKeys.orgFindById(orgId), () => orgDAL.findById(orgId));
if (!org) {
throw new ScimRequestError({
@@ -1725,6 +1782,8 @@ export const scimServiceFactory = ({
});
const [group] = await groupDAL.transaction(async (tx) => {
+ if (!isUuidV4(groupId)) return [];
+
const finalizeAlertRecipients = await prepareDeletedGroupAlertRecipientCleanup(
{ userGroupMembershipDAL, alertChannelRecipientDAL },
groupId,
diff --git a/backend/src/ee/services/scim/scim-types.ts b/backend/src/ee/services/scim/scim-types.ts
index c8dec0b6d1..7df1224f33 100644
--- a/backend/src/ee/services/scim/scim-types.ts
+++ b/backend/src/ee/services/scim/scim-types.ts
@@ -61,6 +61,7 @@ export type TCreateScimUserDTO = {
email?: string;
firstName?: string;
lastName?: string;
+ active: boolean;
orgId: string;
};