The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(sso): insert SAML identity providers instead of saving on a client-supplied id (#26623)
Paul Rastoin8fc3ab44e5c1
diff --git a/packages/twenty-server/src/engine/core-modules/sso/filters/sso-graphql-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/sso/filters/sso-graphql-api-exception.filter.tsnew file mode 100644index 00000000000..26e6c24e89a--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/sso/filters/sso-graphql-api-exception.filter.ts@@ -0,0 +1,13 @@+/* @license Enterprise */++import { Catch, type ExceptionFilter } from '@nestjs/common';++import { SsoException } from 'src/engine/core-modules/sso/sso.exception';+import { ssoGraphqlApiExceptionHandler } from 'src/engine/core-modules/sso/utils/sso-graphql-api-exception-handler.util';++@Catch(SsoException)+export class SsoGraphqlApiExceptionFilter implements ExceptionFilter {+ catch(exception: SsoException) {+ return ssoGraphqlApiExceptionHandler(exception);+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/sso/services/sso.service.ts b/packages/twenty-server/src/engine/core-modules/sso/services/sso.service.tsindex 2c0f2ee6507..f57b4b015d2 100644--- a/packages/twenty-server/src/engine/core-modules/sso/services/sso.service.ts+++ b/packages/twenty-server/src/engine/core-modules/sso/services/sso.service.ts@@ -6,8 +6,10 @@ import { InjectRepository } from '@nestjs/typeorm';import { msg } from '@lingui/core/macro';import { custom, Issuer } from 'openid-client';import { isDefined } from 'twenty-shared/utils';-import { Repository } from 'typeorm';+import { QueryFailedError, Repository } from 'typeorm';+import { POSTGRESQL_ERROR_CODES } from 'src/engine/api/graphql/workspace-query-runner/constants/postgres-error-codes.constants';+import { type QueryFailedErrorWithCode } from 'src/engine/api/graphql/workspace-query-runner/utils/workspace-query-runner-graphql-api-exception-handler.util';import {WorkspaceSsoIdentityProviderEntity,IdentityProviderType,@@ -129,26 +131,55 @@ export class SsoService {async createSamlIdentityProvider(data: Pick<WorkspaceSsoIdentityProviderEntity,- 'ssoURL' | 'certificate' | 'fingerprint' | 'id'+ 'ssoURL' | 'certificate' | 'fingerprint' | 'id' | 'name' | 'issuer'>,workspaceId: string,) {await this.isSsoEnabled(workspaceId);- const identityProvider =- await this.workspaceSsoIdentityProviderRepository.save({- ...data,- type: IdentityProviderType.SAML,- workspaceId,- });-- return {- id: identityProvider.id,- type: identityProvider.type,- name: identityProvider.name,- issuer: this.buildIssuerURL(identityProvider),- status: identityProvider.status,+ const identityProvider = {+ id: data.id,+ name: data.name,+ issuer: data.issuer,+ ssoURL: data.ssoURL,+ certificate: data.certificate,+ fingerprint: data.fingerprint,+ type: IdentityProviderType.SAML,+ workspaceId,};++ try {+ const { generatedMaps } =+ await this.workspaceSsoIdentityProviderRepository.insert(+ identityProvider,+ );++ const { status } = generatedMaps[0] as Pick<+ WorkspaceSsoIdentityProviderEntity,+ 'status'+ >;++ return {+ id: identityProvider.id,+ type: identityProvider.type,+ name: identityProvider.name,+ issuer: this.buildIssuerURL(identityProvider),+ status,+ };+ } catch (error) {+ if (+ error instanceof QueryFailedError &&+ (error as QueryFailedErrorWithCode).code ===+ POSTGRESQL_ERROR_CODES.UNIQUE_VIOLATION+ ) {+ throw new SsoException(+ 'Identity provider already exists',+ SsoExceptionCode.IDENTITY_PROVIDER_ALREADY_EXISTS,+ );+ }++ throw error;+ }}async findSsoIdentityProviderById(identityProviderId: string) {diff --git a/packages/twenty-server/src/engine/core-modules/sso/sso.exception.ts b/packages/twenty-server/src/engine/core-modules/sso/sso.exception.tsindex d5428f54ab0..f565ca1dabf 100644--- a/packages/twenty-server/src/engine/core-modules/sso/sso.exception.ts+++ b/packages/twenty-server/src/engine/core-modules/sso/sso.exception.ts@@ -9,6 +9,7 @@ import { CustomException } from 'src/utils/custom-exception';export enum SsoExceptionCode {USER_NOT_FOUND = 'USER_NOT_FOUND',IDENTITY_PROVIDER_NOT_FOUND = 'IDENTITY_PROVIDER_NOT_FOUND',+ IDENTITY_PROVIDER_ALREADY_EXISTS = 'IDENTITY_PROVIDER_ALREADY_EXISTS',INVALID_ISSUER_URL = 'INVALID_ISSUER_URL',INVALID_IDP_TYPE = 'INVALID_IDP_TYPE',UNKNOWN_SSO_CONFIGURATION_ERROR = 'UNKNOWN_SSO_CONFIGURATION_ERROR',@@ -21,6 +22,8 @@ const getSsoExceptionUserFriendlyMessage = (code: SsoExceptionCode) => {return msg`User not found.`;case SsoExceptionCode.IDENTITY_PROVIDER_NOT_FOUND:return msg`Identity provider not found.`;+ case SsoExceptionCode.IDENTITY_PROVIDER_ALREADY_EXISTS:+ return msg`Identity provider already exists.`;case SsoExceptionCode.INVALID_ISSUER_URL:return msg`Invalid issuer URL.`;case SsoExceptionCode.INVALID_IDP_TYPE:diff --git a/packages/twenty-server/src/engine/core-modules/sso/sso.resolver.ts b/packages/twenty-server/src/engine/core-modules/sso/sso.resolver.tsindex 950f5471643..98988037afd 100644--- a/packages/twenty-server/src/engine/core-modules/sso/sso.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/sso/sso.resolver.ts@@ -20,6 +20,7 @@ import {SetupSamlSsoInput,} from 'src/engine/core-modules/sso/dtos/setup-sso.input';import { SetupSsoDTO } from 'src/engine/core-modules/sso/dtos/setup-sso.dto';+import { SsoGraphqlApiExceptionFilter } from 'src/engine/core-modules/sso/filters/sso-graphql-api-exception.filter';import { SsoService } from 'src/engine/core-modules/sso/services/sso.service';import { type SsoException } from 'src/engine/core-modules/sso/sso.exception';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';@@ -33,6 +34,7 @@ import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modulePermissionsGraphqlApiExceptionFilter,PreventNestToAutoLogGraphqlErrorsFilter,AuthGraphqlApiExceptionFilter,+ SsoGraphqlApiExceptionFilter,)@UsePipes(ResolverValidationPipe)@UseGuards(SettingsPermissionGuard(PermissionFlagType.SECURITY))diff --git a/packages/twenty-server/src/engine/core-modules/sso/utils/sso-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/sso/utils/sso-graphql-api-exception-handler.util.tsnew file mode 100644index 00000000000..207506c0c4d--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/sso/utils/sso-graphql-api-exception-handler.util.ts@@ -0,0 +1,34 @@+/* @license Enterprise */++import { assertUnreachable } from 'twenty-shared/utils';++import {+ ConflictError,+ ForbiddenError,+ NotFoundError,+ UserInputError,+} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';+import {+ type SsoException,+ SsoExceptionCode,+} from 'src/engine/core-modules/sso/sso.exception';++export const ssoGraphqlApiExceptionHandler = (exception: SsoException) => {+ switch (exception.code) {+ case SsoExceptionCode.USER_NOT_FOUND:+ case SsoExceptionCode.IDENTITY_PROVIDER_NOT_FOUND:+ throw new NotFoundError(exception);+ case SsoExceptionCode.IDENTITY_PROVIDER_ALREADY_EXISTS:+ throw new ConflictError(exception);+ case SsoExceptionCode.INVALID_ISSUER_URL:+ case SsoExceptionCode.INVALID_IDP_TYPE:+ throw new UserInputError(exception);+ case SsoExceptionCode.SSO_DISABLE:+ throw new ForbiddenError(exception);+ case SsoExceptionCode.UNKNOWN_SSO_CONFIGURATION_ERROR:+ throw exception;+ default: {+ assertUnreachable(exception.code);+ }+ }+};diff --git a/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/__snapshots__/failing-saml-identity-provider-creation.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/__snapshots__/failing-saml-identity-provider-creation.integration-spec.ts.snapnew file mode 100644index 00000000000..2967eda732f--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/__snapshots__/failing-saml-identity-provider-creation.integration-spec.ts.snap@@ -0,0 +1,13 @@+// Jest Snapshot v1, https://goo.gl/fbAQLP++exports[`SAML identity provider creation should fail when the id is already used by an identity provider 1`] = `+{+ "extensions": {+ "code": "CONFLICT",+ "subCode": "IDENTITY_PROVIDER_ALREADY_EXISTS",+ "userFriendlyMessage": "Identity provider already exists.",+ },+ "message": "Identity provider already exists",+ "name": "ConflictError",+}+`;diff --git a/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/constants/saml-identity-provider-certificate.constant.ts b/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/constants/saml-identity-provider-certificate.constant.tsnew file mode 100644index 00000000000..979a7347f73--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/constants/saml-identity-provider-certificate.constant.ts@@ -0,0 +1,19 @@+export const SAML_IDENTITY_PROVIDER_CERTIFICATE = `-----BEGIN CERTIFICATE-----+MIIDITCCAgmgAwIBAgIUNus+WyR/Je/qVVIUnhZSX9Gs5swwDQYJKoZIhvcNAQEL+BQAwHzEdMBsGA1UEAwwUaW50ZWdyYXRpb24tdGVzdC1pZHAwIBcNMjYwOTIzMTYx+MzI4WhgPMjEyNjA4MzAxNjEzMjhaMB8xHTAbBgNVBAMMFGludGVncmF0aW9uLXRl+c3QtaWRwMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmgLtH6VJJR7q+iI/c3K039loxKyrCn115AVDG7QlAUsnBQ+g7ttuHLnWCVO5OcMEYOt6X7GEQhlbT+xxg90L87w2KG39eyE0Xg2GKcEQRYa9a9yWdpqh3JSeKFYpAN+Oa/oO7cyG4QHY+H+HN/W0/0x4hI9pvpI51r3mcghOlpXXMiun3O4WEAd3oO2Gl3QHQSenizmdhLRxk13+WHRXz/kQSB8jcNIlbteeq9NZ6Qik0iybiFeAS0qJZfdMQa4NjSnnZxDjiSoNXBG/+eEOzOVRtF2VyICDmj+TpWiqIdEH34AO5HQEuDXa6R8lAt3wEJQVVzSAPysbNsZOg+9Bb3BbmZ/QIDAQABo1MwUTAdBgNVHQ4EFgQUdDjI+nqX4hGpP9LyuGDqiPZ4Ogww+HwYDVR0jBBgwFoAUdDjI+nqX4hGpP9LyuGDqiPZ4OgwwDwYDVR0TAQH/BAUwAwEB+/zANBgkqhkiG9w0BAQsFAAOCAQEAYb7pIU+LgVj9nX0KB4mAktjUC4VRMLndAuPp+cy0SxYk2FVA8i8X0jpfkJkaRtO8GHm5U4D31cpNUSqHHSS2aw7BDtmIXTKKQSYjI+xw7RdCHfxjt2LVNCeb1EP7c1zwU3sPUmKsR/XZ6HHvOsnQjk0Jzl8mY1jf3FcTUc+1Cqq0UIhJ7dh8bz5JnYQrIAKLaIN5YUPE0aBSzMmzD5OzHCK4dqtQx5Q1QkDMDZd+RyaVLkSy6DBEhYr6WvmP35+crpL2pldEahrziYUrwG6JfDpVJRgjBh573zNcmHrs+caMZJNuUD0aFCdHiCU414tjOpShEjtjyjpOwoHdwMXAInkWpxQ==+-----END CERTIFICATE-----`;diff --git a/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/failing-saml-identity-provider-creation.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/failing-saml-identity-provider-creation.integration-spec.tsnew file mode 100644index 00000000000..d0b86d0fd2e--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/failing-saml-identity-provider-creation.integration-spec.ts@@ -0,0 +1,65 @@+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';+import { SAML_IDENTITY_PROVIDER_CERTIFICATE } from 'test/integration/metadata/suites/sso-identity-provider/constants/saml-identity-provider-certificate.constant';+import { createOneSamlIdentityProvider } from 'test/integration/metadata/suites/sso-identity-provider/utils/create-one-saml-identity-provider.util';+import { v4 as uuidv4 } from 'uuid';++import { SEED_YCOMBINATOR_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';++// The harness only holds sessions of the Apple workspace, so the existing+// identity provider is inserted directly into the other seeded workspace.+describe('SAML identity provider creation should fail', () => {+ const existingIdentityProvider = {+ id: uuidv4(),+ name: 'Existing identity provider',+ issuer: 'https://existing-identity-provider.example.com',+ ssoURL: 'https://existing-identity-provider.example.com/sso',+ certificate: SAML_IDENTITY_PROVIDER_CERTIFICATE,+ workspaceId: SEED_YCOMBINATOR_WORKSPACE_ID,+ };++ beforeAll(async () => {+ await globalThis.testDataSource.query(+ `INSERT INTO core."workspaceSSOIdentityProvider"+ ("id", "name", "type", "issuer", "ssoURL", "certificate", "workspaceId")+ VALUES ($1, $2, 'SAML', $3, $4, $5, $6)`,+ [+ existingIdentityProvider.id,+ existingIdentityProvider.name,+ existingIdentityProvider.issuer,+ existingIdentityProvider.ssoURL,+ existingIdentityProvider.certificate,+ existingIdentityProvider.workspaceId,+ ],+ );+ });++ afterAll(async () => {+ await globalThis.testDataSource.query(+ `DELETE FROM core."workspaceSSOIdentityProvider" WHERE id = $1`,+ [existingIdentityProvider.id],+ );+ });++ it('when the id is already used by an identity provider', async () => {+ const { errors } = await createOneSamlIdentityProvider({+ expectToFail: true,+ input: {+ id: existingIdentityProvider.id,+ name: 'Identity provider',+ issuer: 'https://identity-provider.example.com',+ ssoURL: 'https://identity-provider.example.com/sso',+ certificate: SAML_IDENTITY_PROVIDER_CERTIFICATE,+ },+ });++ expectOneNotInternalServerErrorSnapshot({ errors });++ const [identityProvider] = await globalThis.testDataSource.query(+ `SELECT "id", "name", "issuer", "ssoURL", "certificate", "workspaceId"+ FROM core."workspaceSSOIdentityProvider" WHERE id = $1`,+ [existingIdentityProvider.id],+ );++ expect(identityProvider).toEqual(existingIdentityProvider);+ });+});diff --git a/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/successful-saml-identity-provider-creation.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/successful-saml-identity-provider-creation.integration-spec.tsnew file mode 100644index 00000000000..83419547d16--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/successful-saml-identity-provider-creation.integration-spec.ts@@ -0,0 +1,34 @@+import { SAML_IDENTITY_PROVIDER_CERTIFICATE } from 'test/integration/metadata/suites/sso-identity-provider/constants/saml-identity-provider-certificate.constant';+import { createOneSamlIdentityProvider } from 'test/integration/metadata/suites/sso-identity-provider/utils/create-one-saml-identity-provider.util';+import { v4 as uuidv4 } from 'uuid';++describe('SAML identity provider creation should succeed', () => {+ const identityProviderId = uuidv4();++ afterAll(async () => {+ await globalThis.testDataSource.query(+ `DELETE FROM core."workspaceSSOIdentityProvider" WHERE id = $1`,+ [identityProviderId],+ );+ });++ it('should create an active SAML identity provider', async () => {+ const { data } = await createOneSamlIdentityProvider({+ expectToFail: false,+ input: {+ id: identityProviderId,+ name: 'Identity provider',+ issuer: 'https://identity-provider.example.com',+ ssoURL: 'https://identity-provider.example.com/sso',+ certificate: SAML_IDENTITY_PROVIDER_CERTIFICATE,+ },+ });++ expect(data.createSAMLIdentityProvider).toMatchObject({+ id: identityProviderId,+ type: 'SAML',+ name: 'Identity provider',+ status: 'Active',+ });+ });+});diff --git a/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/utils/create-one-saml-identity-provider-query-factory.util.ts b/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/utils/create-one-saml-identity-provider-query-factory.util.tsnew file mode 100644index 00000000000..31c217f8337--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/utils/create-one-saml-identity-provider-query-factory.util.ts@@ -0,0 +1,30 @@+import gql from 'graphql-tag';+import { type PerformMetadataQueryParams } from 'test/integration/metadata/types/perform-metadata-query.type';++import { type SetupSamlSsoInput } from 'src/engine/core-modules/sso/dtos/setup-sso.input';++export type CreateOneSamlIdentityProviderFactoryInput = SetupSamlSsoInput;++const DEFAULT_SSO_IDENTITY_PROVIDER_GQL_FIELDS = `+ id+ type+ issuer+ name+ status+`;++export const createOneSamlIdentityProviderQueryFactory = ({+ input,+ gqlFields = DEFAULT_SSO_IDENTITY_PROVIDER_GQL_FIELDS,+}: PerformMetadataQueryParams<CreateOneSamlIdentityProviderFactoryInput>) => ({+ query: gql`+ mutation CreateSAMLIdentityProvider($input: SetupSAMLSsoInput!) {+ createSAMLIdentityProvider(input: $input) {+ ${gqlFields}+ }+ }+ `,+ variables: {+ input,+ },+});diff --git a/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/utils/create-one-saml-identity-provider.util.ts b/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/utils/create-one-saml-identity-provider.util.tsnew file mode 100644index 00000000000..51bbd194323--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/sso-identity-provider/utils/create-one-saml-identity-provider.util.ts@@ -0,0 +1,44 @@+import {+ type CreateOneSamlIdentityProviderFactoryInput,+ createOneSamlIdentityProviderQueryFactory,+} from 'test/integration/metadata/suites/sso-identity-provider/utils/create-one-saml-identity-provider-query-factory.util';+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';+import { type CommonResponseBody } from 'test/integration/metadata/types/common-response-body.type';+import { type PerformMetadataQueryParams } from 'test/integration/metadata/types/perform-metadata-query.type';+import { warnIfErrorButNotExpectedToFail } from 'test/integration/metadata/utils/warn-if-error-but-not-expected-to-fail.util';+import { warnIfNoErrorButExpectedToFail } from 'test/integration/metadata/utils/warn-if-no-error-but-expected-to-fail.util';++import { type SetupSsoDTO } from 'src/engine/core-modules/sso/dtos/setup-sso.dto';++export const createOneSamlIdentityProvider = async ({+ input,+ gqlFields,+ expectToFail = false,+ token,+}: PerformMetadataQueryParams<CreateOneSamlIdentityProviderFactoryInput>): CommonResponseBody<{+ createSAMLIdentityProvider: SetupSsoDTO;+}> => {+ const graphqlOperation = createOneSamlIdentityProviderQueryFactory({+ input,+ gqlFields,+ });++ const response = await makeMetadataApiRequest(graphqlOperation, token);++ if (expectToFail === true) {+ warnIfNoErrorButExpectedToFail({+ response,+ errorMessage:+ 'SAML identity provider creation should have failed but did not',+ });+ }++ if (expectToFail === false) {+ warnIfErrorButNotExpectedToFail({+ response,+ errorMessage: 'SAML identity provider creation has failed but should not',+ });+ }++ return { data: response.body.data, errors: response.body.errors };+};