The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix: include iss parameter in OAuth authorization redirect per RFC 9207 (#24153) (#24663)
Wsvdesign38f839ae9554
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex 89b80f584b8..587e01b3753 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -3792,7 +3792,7 @@ type Mutation {generateTransientToken: TransientToken!getAuthTokensFromLoginToken(loginToken: String!, origin: String!): AuthTokens!getAuthTokensFromSSOExchangeToken(ssoExchangeToken: String!): AuthTokens!- authorizeApp(clientId: String!, codeChallenge: String, redirectUrl: String!, state: String, scope: String): AuthorizeApp!+ authorizeApp(clientId: String!, codeChallenge: String, redirectUrl: String!, state: String, scope: String, issuer: String): AuthorizeApp!renewToken(appToken: String!): AuthTokens!signOut(refreshToken: String): Boolean!generateApiKeyToken(apiKeyId: UUID!, expiresAt: String!): ApiKeyToken!diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex 41fce50b3bd..919b5f00b5d 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -6798,7 +6798,7 @@ export interface MutationGenqlSelection{generateTransientToken?: TransientTokenGenqlSelectiongetAuthTokensFromLoginToken?: (AuthTokensGenqlSelection & { __args: {loginToken: Scalars['String'], origin: Scalars['String']} })getAuthTokensFromSSOExchangeToken?: (AuthTokensGenqlSelection & { __args: {ssoExchangeToken: Scalars['String']} })- authorizeApp?: (AuthorizeAppGenqlSelection & { __args: {clientId: Scalars['String'], codeChallenge?: (Scalars['String'] | null), redirectUrl: Scalars['String'], state?: (Scalars['String'] | null), scope?: (Scalars['String'] | null)} })+ authorizeApp?: (AuthorizeAppGenqlSelection & { __args: {clientId: Scalars['String'], codeChallenge?: (Scalars['String'] | null), redirectUrl: Scalars['String'], state?: (Scalars['String'] | null), scope?: (Scalars['String'] | null), issuer?: (Scalars['String'] | null)} })renewToken?: (AuthTokensGenqlSelection & { __args: {appToken: Scalars['String']} })signOut?: { __args: {refreshToken?: (Scalars['String'] | null)} } | boolean | numbergenerateApiKeyToken?: (ApiKeyTokenGenqlSelection & { __args: {apiKeyId: Scalars['UUID'], expiresAt: Scalars['String']} })diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex 13c2c1cd897..fe3ff7b3096 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -9707,6 +9707,9 @@ export default {],"scope": [1+ ],+ "issuer": [+ 1]}],diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 96647de2563..b62fd87d7cf 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -2983,6 +2983,7 @@ export type MutationAssignRoleToApiKeyArgs = {export type MutationAuthorizeAppArgs = {clientId: Scalars['String']['input'];codeChallenge?: InputMaybe<Scalars['String']['input']>;+ issuer?: InputMaybe<Scalars['String']['input']>;redirectUrl: Scalars['String']['input'];scope?: InputMaybe<Scalars['String']['input']>;state?: InputMaybe<Scalars['String']['input']>;@@ -7346,6 +7347,7 @@ export type AuthorizeAppMutationVariables = Exact<{codeChallenge?: InputMaybe<Scalars['String']['input']>;redirectUrl: Scalars['String']['input'];state?: InputMaybe<Scalars['String']['input']>;+ issuer?: InputMaybe<Scalars['String']['input']>;}>;@@ -9696,7 +9698,7 @@ export const FindOneApplicationByUniversalIdentifierDocument = {"kind":"Documentexport const FindOneApplicationNameDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneApplicationName"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findOneApplication"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]} as unknown as DocumentNode<FindOneApplicationNameQuery, FindOneApplicationNameQueryVariables>;export const FindOneApplicationSummaryDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneApplicationSummary"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findOneApplication"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"universalIdentifier"},"value":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode<FindOneApplicationSummaryQuery, FindOneApplicationSummaryQueryVariables>;export const IsApplicationStoppedDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"IsApplicationStopped"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"applicationUniversalIdentifier"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"isApplicationStopped"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"applicationUniversalIdentifier"},"value":{"kind":"Variable","name":{"kind":"Name","value":"applicationUniversalIdentifier"}}}]}]}}]} as unknown as DocumentNode<IsApplicationStoppedQuery, IsApplicationStoppedQueryVariables>;-export const AuthorizeAppDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"authorizeApp"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"clientId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"codeChallenge"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"redirectUrl"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"state"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"authorizeApp"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"clientId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"clientId"}}},{"kind":"Argument","name":{"kind":"Name","value":"codeChallenge"},"value":{"kind":"Variable","name":{"kind":"Name","value":"codeChallenge"}}},{"kind":"Argument","name":{"kind":"Name","value":"redirectUrl"},"value":{"kind":"Variable","name":{"kind":"Name","value":"redirectUrl"}}},{"kind":"Argument","name":{"kind":"Name","value":"state"},"value":{"kind":"Variable","name":{"kind":"Name","value":"state"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"redirectUrl"}}]}}]}}]} as unknown as DocumentNode<AuthorizeAppMutation, AuthorizeAppMutationVariables>;+export const AuthorizeAppDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"authorizeApp"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"clientId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"codeChallenge"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"redirectUrl"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"state"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"issuer"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"authorizeApp"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"clientId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"clientId"}}},{"kind":"Argument","name":{"kind":"Name","value":"codeChallenge"},"value":{"kind":"Variable","name":{"kind":"Name","value":"codeChallenge"}}},{"kind":"Argument","name":{"kind":"Name","value":"redirectUrl"},"value":{"kind":"Variable","name":{"kind":"Name","value":"redirectUrl"}}},{"kind":"Argument","name":{"kind":"Name","value":"state"},"value":{"kind":"Variable","name":{"kind":"Name","value":"state"}}},{"kind":"Argument","name":{"kind":"Name","value":"issuer"},"value":{"kind":"Variable","name":{"kind":"Name","value":"issuer"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"redirectUrl"}}]}}]}}]} as unknown as DocumentNode<AuthorizeAppMutation, AuthorizeAppMutationVariables>;export const EmailPasswordResetLinkDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"EmailPasswordResetLink"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"email"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"emailPasswordResetLink"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"email"},"value":{"kind":"Variable","name":{"kind":"Name","value":"email"}}},{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}},{"kind":"Argument","name":{"kind":"Name","value":"captchaToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"success"}}]}}]}}]} as unknown as DocumentNode<EmailPasswordResetLinkMutation, EmailPasswordResetLinkMutationVariables>;export const GenerateApiKeyTokenDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GenerateApiKeyToken"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"apiKeyId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"expiresAt"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"generateApiKeyToken"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"apiKeyId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"apiKeyId"}}},{"kind":"Argument","name":{"kind":"Name","value":"expiresAt"},"value":{"kind":"Variable","name":{"kind":"Name","value":"expiresAt"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}}]}}]}}]} as unknown as DocumentNode<GenerateApiKeyTokenMutation, GenerateApiKeyTokenMutationVariables>;export const GeneratePlaygroundTokenDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GeneratePlaygroundToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"generatePlaygroundToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}}]}}]} as unknown as DocumentNode<GeneratePlaygroundTokenMutation, GeneratePlaygroundTokenMutationVariables>;diff --git a/packages/twenty-front/src/modules/auth/graphql/mutations/authorizeApp.ts b/packages/twenty-front/src/modules/auth/graphql/mutations/authorizeApp.tsindex 6e1f870d2f2..9dd17e4316d 100644--- a/packages/twenty-front/src/modules/auth/graphql/mutations/authorizeApp.ts+++ b/packages/twenty-front/src/modules/auth/graphql/mutations/authorizeApp.ts@@ -6,12 +6,14 @@ export const AUTHORIZE_APP = gql`$codeChallenge: String$redirectUrl: String!$state: String+ $issuer: String) {authorizeApp(clientId: $clientIdcodeChallenge: $codeChallengeredirectUrl: $redirectUrlstate: $state+ issuer: $issuer) {redirectUrl}diff --git a/packages/twenty-front/src/pages/auth/Authorize.tsx b/packages/twenty-front/src/pages/auth/Authorize.tsxindex 5e0f6c05e86..ebc62a96f50 100644--- a/packages/twenty-front/src/pages/auth/Authorize.tsx+++ b/packages/twenty-front/src/pages/auth/Authorize.tsx@@ -152,6 +152,7 @@ export const Authorize = () => {const redirectUrl =searchParam.get('redirect_uri') ?? searchParam.get('redirectUrl');const state = searchParam.get('state');+ const issuer = searchParam.get('iss');const {data,@@ -199,6 +200,7 @@ export const Authorize = () => {codeChallenge: codeChallenge ?? undefined,redirectUrl,state: state ?? undefined,+ issuer: issuer ?? undefined,},onCompleted: (responseData) => {redirect(appendThemeToUrl(responseData.authorizeApp.redirectUrl));diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/__tests__/oauth-discovery.controller.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/__tests__/oauth-discovery.controller.spec.tsindex b74494ab69f..f288f131649 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/__tests__/oauth-discovery.controller.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/__tests__/oauth-discovery.controller.spec.ts@@ -71,4 +71,67 @@ describe('OAuthDiscoveryController', () => {);});});++ describe('getAuthorizationServerMetadata', () => {+ it('leaves the endpoint untouched when the api host serves /authorize itself', async () => {+ const singleDomainModule = await Test.createTestingModule({+ controllers: [OAuthDiscoveryController],+ providers: [+ {+ provide: TwentyConfigService,+ useValue: {+ get: jest.fn().mockReturnValue('https://crm.acme.com'),+ },+ },+ {+ provide: DomainServerConfigService,+ useValue: {+ getBaseUrl: jest+ .fn()+ .mockReturnValue(new URL('https://crm.acme.com')),+ },+ },+ {+ provide: ApplicationRegistrationService,+ useValue: { findOneByUniversalIdentifier: jest.fn() },+ },+ ],+ }).compile();++ const metadata = await singleDomainModule+ .get(OAuthDiscoveryController)+ .getAuthorizationServerMetadata(buildMockRequest('crm.acme.com'));++ expect(metadata).toMatchObject({+ issuer: 'https://crm.acme.com',+ authorization_endpoint: 'https://crm.acme.com/authorize',+ authorization_response_iss_parameter_supported: true,+ });+ });++ it('serves /authorize on its own origin when it has one', async () => {+ const request = buildMockRequest('workspace.twenty.com');++ expect(+ await controller.getAuthorizationServerMetadata(request),+ ).toMatchObject({+ issuer: 'https://workspace.twenty.com',+ authorization_endpoint: 'https://workspace.twenty.com/authorize',+ authorization_response_iss_parameter_supported: true,+ });+ });++ it('forwards its issuer to the frontend origin it delegates to', async () => {+ const request = buildMockRequest('api.example.com');++ expect(+ await controller.getAuthorizationServerMetadata(request),+ ).toMatchObject({+ issuer: 'https://api.example.com',+ authorization_endpoint:+ 'https://app.example.com/authorize?iss=https%3A%2F%2Fapi.example.com',+ authorization_response_iss_parameter_supported: true,+ });+ });+ });});diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.tsindex cb21ee6e0be..9709eb596eb 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts@@ -33,6 +33,11 @@ export class OAuthDiscoveryController {? cleanServerUrl(this.domainServerConfigService.getBaseUrl().toString()): issuer;+ const authorizationEndpoint =+ authorizeBase === issuer+ ? `${issuer}/authorize`+ : `${authorizeBase}/authorize?iss=${encodeURIComponent(issuer)}`;+const cliRegistration =await this.applicationRegistrationService.findOneByUniversalIdentifier(TWENTY_CLI_APPLICATION_REGISTRATION.universalIdentifier,@@ -40,7 +45,7 @@ export class OAuthDiscoveryController {return {issuer,- authorization_endpoint: `${authorizeBase}/authorize`,+ authorization_endpoint: authorizationEndpoint,token_endpoint: `${issuer}/${ApiPath.OAuth}/token`,registration_endpoint: `${issuer}/${ApiPath.OAuth}/register`,revocation_endpoint: `${issuer}/${ApiPath.OAuth}/revoke`,diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.tsindex f670de1b22b..4c2014cb2b6 100644--- a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts@@ -97,6 +97,7 @@ import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.gimport { UserAuthGuard } from 'src/engine/guards/user-auth.guard';import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';+import { getRequestBaseUrl } from 'src/utils/get-request-base-url.util';import { streamToBuffer } from 'src/utils/stream-to-buffer';import { ApiKeyToken } from './dto/api-key-token.dto';@@ -940,12 +941,14 @@ export class AuthResolver {@Args() authorizeAppInput: AuthorizeAppInput,@AuthUser() user: AuthContextUser,@AuthWorkspace() workspace: WorkspaceEntity,+ @Context() context: { req: Request },): Promise<AuthorizeAppDTO> {- return await this.authService.generateAuthorizationCode(+ return await this.authService.generateAuthorizationCode({authorizeAppInput,user,workspace,- );+ requestBaseUrl: getRequestBaseUrl(context.req),+ });}@Mutation(() => AuthTokens)diff --git a/packages/twenty-server/src/engine/core-modules/auth/dto/authorize-app.input.ts b/packages/twenty-server/src/engine/core-modules/auth/dto/authorize-app.input.tsindex 42332afa245..bf57d6f4d19 100644--- a/packages/twenty-server/src/engine/core-modules/auth/dto/authorize-app.input.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/dto/authorize-app.input.ts@@ -31,4 +31,10 @@ export class AuthorizeAppInput {@MaxLength(1024)@IsOptional()scope?: string;++ @Field(() => String, { nullable: true })+ @IsString()+ @MaxLength(2048)+ @IsOptional()+ issuer?: string;}diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/auth.service.ts b/packages/twenty-server/src/engine/core-modules/auth/services/auth.service.tsindex 09c5f56b240..9d3cd7d42f8 100644--- a/packages/twenty-server/src/engine/core-modules/auth/services/auth.service.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/services/auth.service.ts@@ -72,6 +72,7 @@ import { WorkspaceInvitationService } from 'src/engine/core-modules/workspace-inimport { AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { workspaceValidator } from 'src/engine/core-modules/workspace/workspace.validate';+import { assertIssuerIsPublishedOrThrow } from 'src/engine/core-modules/auth/utils/assert-issuer-is-published.util';import { PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';import { isEmailInApprovedAccessDomains } from 'src/engine/core-modules/approved-access-domain/utils/is-email-in-approved-access-domains.util';@@ -505,11 +506,17 @@ export class AuthService {return { isValid: !!workspace };}- async generateAuthorizationCode(- authorizeAppInput: AuthorizeAppInput,- user: AuthContextUser,- workspace: WorkspaceEntity,- ): Promise<AuthorizeAppDTO> {+ async generateAuthorizationCode({+ authorizeAppInput,+ user,+ workspace,+ requestBaseUrl,+ }: {+ authorizeAppInput: AuthorizeAppInput;+ user: AuthContextUser;+ workspace: WorkspaceEntity;+ requestBaseUrl: string;+ }): Promise<AuthorizeAppDTO> {const { clientId, codeChallenge } = authorizeAppInput;const applicationRegistration =@@ -642,6 +649,16 @@ export class AuthService {redirectUriValidation.parsed.searchParams.set('code', authorizationCode);+ const issuer = authorizeAppInput.issuer ?? requestBaseUrl;++ assertIssuerIsPublishedOrThrow({+ issuer,+ requestBaseUrl,+ serverUrl: this.twentyConfigService.get('SERVER_URL'),+ });++ redirectUriValidation.parsed.searchParams.set('iss', issuer);+if (authorizeAppInput.state) {redirectUriValidation.parsed.searchParams.set('state',diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/assert-issuer-is-published.util.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/assert-issuer-is-published.util.spec.tsnew file mode 100644index 00000000000..5da287d56d4--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/assert-issuer-is-published.util.spec.ts@@ -0,0 +1,56 @@+import { AuthException } from 'src/engine/core-modules/auth/auth.exception';+import { assertIssuerIsPublishedOrThrow } from 'src/engine/core-modules/auth/utils/assert-issuer-is-published.util';++describe('assertIssuerIsPublishedOrThrow', () => {+ const requestBaseUrl = 'https://app.twenty.com';+ const serverUrl = 'https://api.twenty.com';++ it('accepts the origin the request arrived on', () => {+ expect(() =>+ assertIssuerIsPublishedOrThrow({+ issuer: 'https://app.twenty.com',+ requestBaseUrl,+ serverUrl,+ }),+ ).not.toThrow();+ });++ it('accepts the api host, which delegates /authorize to this origin', () => {+ expect(() =>+ assertIssuerIsPublishedOrThrow({+ issuer: 'https://api.twenty.com',+ requestBaseUrl,+ serverUrl,+ }),+ ).not.toThrow();+ });++ it('tolerates a trailing slash on SERVER_URL', () => {+ expect(() =>+ assertIssuerIsPublishedOrThrow({+ issuer: 'https://api.twenty.com',+ requestBaseUrl,+ serverUrl: 'https://api.twenty.com/',+ }),+ ).not.toThrow();+ });++ it('throws on an issuer this instance never published', () => {+ expect(() =>+ assertIssuerIsPublishedOrThrow({+ issuer: 'https://attacker.example.com',+ requestBaseUrl,+ serverUrl,+ }),+ ).toThrow(AuthException);+ });++ it('throws when SERVER_URL is unset and the issuer is not the request origin', () => {+ expect(() =>+ assertIssuerIsPublishedOrThrow({+ issuer: 'https://api.twenty.com',+ requestBaseUrl,+ }),+ ).toThrow(AuthException);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/assert-issuer-is-published.util.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/assert-issuer-is-published.util.tsnew file mode 100644index 00000000000..9ccbd39d75c--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/assert-issuer-is-published.util.ts@@ -0,0 +1,28 @@+import { isDefined } from 'twenty-shared/utils';++import {+ AuthException,+ AuthExceptionCode,+} from 'src/engine/core-modules/auth/auth.exception';+import { cleanServerUrl } from 'src/utils/clean-server-url';++export const assertIssuerIsPublishedOrThrow = ({+ issuer,+ requestBaseUrl,+ serverUrl,+}: {+ issuer: string;+ requestBaseUrl: string;+ serverUrl?: string;+}): void => {+ const publishedIssuers = [requestBaseUrl, cleanServerUrl(serverUrl)].filter(+ isDefined,+ );++ if (!publishedIssuers.includes(issuer)) {+ throw new AuthException(+ `Unknown issuer '${issuer}'`,+ AuthExceptionCode.FORBIDDEN_EXCEPTION,+ );+ }+};diff --git a/packages/twenty-server/test/integration/oauth/suites/oauth.integration-spec.ts b/packages/twenty-server/test/integration/oauth/suites/oauth.integration-spec.tsindex fd1c5571a45..dd7b46b7026 100644--- a/packages/twenty-server/test/integration/oauth/suites/oauth.integration-spec.ts+++ b/packages/twenty-server/test/integration/oauth/suites/oauth.integration-spec.ts@@ -4,7 +4,7 @@ import bcrypt from 'bcrypt';import gql from 'graphql-tag';import request from 'supertest';import { makeMetadataAPIRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';-import { base64UrlEncode } from 'twenty-shared/utils';+import { assertIsDefinedOrThrow, base64UrlEncode } from 'twenty-shared/utils';import { type DataSource } from 'typeorm';import { AppTokenType } from 'src/engine/core-modules/app-token/app-token.entity';@@ -258,6 +258,75 @@ describe('OAuth (integration)', () => {expect(res.body.scopes_supported).toBeDefined();expect(res.body.response_types_supported).toContain('code');});++ it('should promise `iss` when it serves its own authorization endpoint', async () => {+ const res = await request(baseUrl)+ .get('/.well-known/oauth-authorization-server')+ .expect(200);++ expect(res.body.authorization_endpoint).toBe(+ `${res.body.issuer}/authorize`,+ );+ expect(res.body.authorization_response_iss_parameter_supported).toBe(+ true,+ );+ });+ });++ describe('Authorization endpoint (authorizeApp)', () => {+ const authorizeAppMutation = gql`+ mutation AuthorizeApp(+ $clientId: String!+ $redirectUrl: String!+ $state: String+ ) {+ authorizeApp(+ clientId: $clientId+ redirectUrl: $redirectUrl+ state: $state+ ) {+ redirectUrl+ }+ }+ `;++ it('should return an `iss` matching the advertised issuer alongside code and state', async () => {+ const state = 'integration-state-123';++ const response = await makeMetadataAPIRequest({+ query: authorizeAppMutation,+ variables: {+ clientId: testRegistration.oAuthClientId,+ redirectUrl: testRegistration.oAuthRedirectUris[0],+ state,+ },+ });++ expect(response.body.errors).toBeUndefined();++ const callbackUrl = new URL(response.body.data.authorizeApp.redirectUrl);+ const code = callbackUrl.searchParams.get('code');++ const metadata = await request(baseUrl)+ .get('/.well-known/oauth-authorization-server')+ .expect(200);++ expect(`${callbackUrl.origin}${callbackUrl.pathname}`).toBe(+ testRegistration.oAuthRedirectUris[0],+ );+ expect(code).toMatch(/^[0-9a-f]+$/);+ expect(callbackUrl.searchParams.get('iss')).toBe(metadata.body.issuer);+ expect(callbackUrl.searchParams.get('state')).toBe(state);++ assertIsDefinedOrThrow(code);++ const [issuedToken] = await ds.query(+ `SELECT id FROM core."appToken" WHERE value = $1`,+ [crypto.createHash('sha256').update(code).digest('hex')],+ );++ createdEntityIds.tokens.push(issuedToken.id);+ });});describe('Token endpoint validation', () => {