The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Restrict front component token pair and renewal to sessions (#26191)
Paul Rastoin5ae5758b7f3c
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/application-oauth.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/application-oauth.resolver.tsindex 5f099bce515..ee5152f9303 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-oauth/application-oauth.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/application-oauth.resolver.ts@@ -3,15 +3,12 @@ import { Args, Mutation } from '@nestjs/graphql';import { PermissionFlagType } from 'twenty-shared/constants';import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';-import {- ApplicationException,- ApplicationExceptionCode,-} from 'src/engine/core-modules/application/application.exception';import { ApplicationExceptionFilter } from 'src/engine/core-modules/application/application-exception-filter';import { GenerateApplicationTokenInput } from 'src/engine/core-modules/application/application-development/dtos/generate-application-token.input';import { ApplicationTokenPairDTO } from 'src/engine/core-modules/application/application-oauth/dtos/application-token-pair.dto';import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';import { ApplicationTokenService } from 'src/engine/core-modules/auth/token/services/application-token.service';+import { type AuthContextUser } from 'src/engine/core-modules/auth/types/auth-context.type';import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';import { ThrottlerGraphqlApiExceptionFilter } from 'src/engine/core-modules/throttler/filters/throttler-graphql-api-exception.filter';import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';@@ -20,11 +17,12 @@ import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspimport { AuthUser } from 'src/engine/decorators/auth/auth-user.decorator';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';+import { RequireAccessTokenGuard } from 'src/engine/guards/require-access-token.guard';import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';-const APP_TOKEN_RATE_LIMIT_MAX = 30;-const APP_TOKEN_RATE_LIMIT_WINDOW_MS = 30_000;+const APPLICATION_TOKEN_RATE_LIMIT_MAX = 30;+const APPLICATION_TOKEN_RATE_LIMIT_WINDOW_MS = 30_000;@UsePipes(ResolverValidationPipe)@MetadataResolver()@@ -51,8 +49,8 @@ export class ApplicationOAuthResolver {await this.throttlerService.tokenBucketThrottleOrThrow(`app-dev:${workspaceId}:${applicationId}`,1,- APP_TOKEN_RATE_LIMIT_MAX,- APP_TOKEN_RATE_LIMIT_WINDOW_MS,+ APPLICATION_TOKEN_RATE_LIMIT_MAX,+ APPLICATION_TOKEN_RATE_LIMIT_WINDOW_MS,);return this.applicationTokenService.generateApplicationTokenPair({@@ -64,22 +62,29 @@ export class ApplicationOAuthResolver {}@Mutation(() => ApplicationTokenPairDTO)- @UseGuards(NoPermissionGuard)+ @UseGuards(RequireAccessTokenGuard, NoPermissionGuard)async renewApplicationToken(@Args('applicationRefreshToken') applicationRefreshToken: string,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthUser() user: AuthContextUser,+ @AuthUserWorkspaceId() userWorkspaceId: string,): Promise<ApplicationTokenPairDTO> {const applicationRefreshTokenPayload =- await this.applicationTokenService.validateApplicationRefreshToken(- applicationRefreshToken,+ await this.applicationTokenService.validateApplicationRefreshTokenForSessionOrThrow(+ {+ applicationRefreshToken,+ workspaceId,+ userId: user.id,+ userWorkspaceId,+ },);- if (applicationRefreshTokenPayload.workspaceId !== workspaceId) {- throw new ApplicationException(- 'Refresh token workspace does not match authenticated workspace',- ApplicationExceptionCode.FORBIDDEN,- );- }+ await this.throttlerService.tokenBucketThrottleOrThrow(+ `app-renew:${workspaceId}:${userWorkspaceId}:${applicationRefreshTokenPayload.applicationId}`,+ 1,+ APPLICATION_TOKEN_RATE_LIMIT_MAX,+ APPLICATION_TOKEN_RATE_LIMIT_WINDOW_MS,+ );return this.applicationTokenService.renewApplicationTokens(applicationRefreshTokenPayload,diff --git a/packages/twenty-server/src/engine/core-modules/auth/token/services/application-token.service.ts b/packages/twenty-server/src/engine/core-modules/auth/token/services/application-token.service.tsindex bf446471952..92f06cfbf6b 100644--- a/packages/twenty-server/src/engine/core-modules/auth/token/services/application-token.service.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/token/services/application-token.service.ts@@ -201,6 +201,41 @@ export class ApplicationTokenService {}}+ async validateApplicationRefreshTokenForSessionOrThrow({+ applicationRefreshToken,+ workspaceId,+ userId,+ userWorkspaceId,+ }: {+ applicationRefreshToken: string;+ workspaceId: string;+ userId: string;+ userWorkspaceId: string;+ }): Promise<ApplicationRefreshTokenJwtPayload> {+ const applicationRefreshTokenPayload =+ await this.validateApplicationRefreshToken(applicationRefreshToken);++ if (applicationRefreshTokenPayload.workspaceId !== workspaceId) {+ throw new ApplicationException(+ 'Refresh token workspace does not match authenticated workspace',+ ApplicationExceptionCode.FORBIDDEN,+ );+ }++ const hasMismatchedUser = applicationRefreshTokenPayload.userId !== userId;+ const hasMismatchedUserWorkspace =+ applicationRefreshTokenPayload.userWorkspaceId !== userWorkspaceId;++ if (hasMismatchedUser || hasMismatchedUserWorkspace) {+ throw new ApplicationException(+ 'Refresh token does not match authenticated session',+ ApplicationExceptionCode.FORBIDDEN,+ );+ }++ return applicationRefreshTokenPayload;+ }+async validateApplicationAccessToken(token: string,): Promise<ApplicationAccessTokenJwtPayload> {diff --git a/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.tsindex 5b8d6f865ea..6b97811f65f 100644--- a/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/front-component/front-component.resolver.ts@@ -15,8 +15,8 @@ import { AuthUser } from 'src/engine/decorators/auth/auth-user.decorator';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';import { AllowSuspendedWorkspace } from 'src/engine/decorators/auth/allow-suspended-workspace.decorator';import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';+import { RequireAccessTokenGuard } from 'src/engine/guards/require-access-token.guard';import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';-import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';import { fromFlatFrontComponentToFrontComponentDto } from 'src/engine/metadata-modules/flat-front-component/utils/from-flat-front-component-to-front-component-dto.util';import { CreateFrontComponentInput } from 'src/engine/metadata-modules/front-component/dtos/create-front-component.input';@@ -70,7 +70,7 @@ export class FrontComponentResolver {}@Query(() => FrontComponentDTO, { nullable: true })- @UseGuards(UserAuthGuard, NoPermissionGuard)+ @UseGuards(RequireAccessTokenGuard, NoPermissionGuard)async frontComponent(@Args('id', { type: () => UUIDScalarType }) id: string,@AuthWorkspace() workspace: WorkspaceEntity,diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/jwt-key-rotation/jwt-asymmetric-signing.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/jwt-key-rotation/jwt-asymmetric-signing.integration-spec.tsindex 67f1a2a405a..b3a876405b5 100644--- a/packages/twenty-server/test/integration/graphql/suites/auth/jwt-key-rotation/jwt-asymmetric-signing.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/auth/jwt-key-rotation/jwt-asymmetric-signing.integration-spec.ts@@ -9,11 +9,11 @@ import { findManyApplications } from 'test/integration/graphql/utils/find-many-aimport { generateApiKeyToken } from 'test/integration/graphql/utils/generate-api-key-token.util';import { getAuthTokensFromLoginToken } from 'test/integration/graphql/utils/get-auth-tokens-from-login-token.util';import { getCurrentUser } from 'test/integration/graphql/utils/get-current-user.util';-import { renewApplicationToken } from 'test/integration/graphql/utils/renew-application-token.util';import { renewToken } from 'test/integration/graphql/utils/renew-token.util';import { signUp } from 'test/integration/graphql/utils/sign-up.util';import { signUpInNewWorkspace } from 'test/integration/graphql/utils/sign-up-in-new-workspace.util';import { generateApplicationToken } from 'test/integration/metadata/suites/application/utils/generate-application-token.util';+import { renewApplicationToken } from 'test/integration/metadata/suites/application/utils/renew-application-token.util';import { type AccessTokenJwtPayload } from 'src/engine/core-modules/auth/types/access-token-jwt-payload.type';import { type ApplicationAccessTokenJwtPayload } from 'src/engine/core-modules/auth/types/application-access-token-jwt-payload.type';@@ -316,18 +316,18 @@ describe('JWT Asymmetric Signing - seeded-workspace tokens (integration)', () =>expectToFail: false,});- const response = await renewApplicationToken({- applicationRefreshToken:- data.generateApplicationToken.applicationRefreshToken.token,- accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,+ const { data: renewedData } = await renewApplicationToken({+ input: {+ applicationRefreshToken:+ data.generateApplicationToken.applicationRefreshToken.token,+ },+ expectToFail: false,});- expect(response.body.errors).toBeUndefined();-- const renewed = response.body.data?.renewApplicationToken;+ const renewed = renewedData.renewApplicationToken;- expect(isNonEmptyString(renewed?.applicationAccessToken.token)).toBe(true);- expect(isNonEmptyString(renewed?.applicationRefreshToken.token)).toBe(true);+ expect(isNonEmptyString(renewed.applicationAccessToken.token)).toBe(true);+ expect(isNonEmptyString(renewed.applicationRefreshToken.token)).toBe(true);expect(decodeJwtCompleteOrThrow(renewed.applicationAccessToken.token).header.alg,diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/jwt-key-rotation/jwt-legacy-hs256-fallback.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/jwt-key-rotation/jwt-legacy-hs256-fallback.integration-spec.tsindex 80a46d8fb33..50c5c6bbbd4 100644--- a/packages/twenty-server/test/integration/graphql/suites/auth/jwt-key-rotation/jwt-legacy-hs256-fallback.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/auth/jwt-key-rotation/jwt-legacy-hs256-fallback.integration-spec.ts@@ -8,7 +8,7 @@ import { findManyApplications } from 'test/integration/graphql/utils/find-many-aimport { forgeLegacyHs256Token } from 'test/integration/graphql/utils/forge-legacy-hs256-token.util';import { getAuthTokensFromLoginToken } from 'test/integration/graphql/utils/get-auth-tokens-from-login-token.util';import { getCurrentUser } from 'test/integration/graphql/utils/get-current-user.util';-import { renewApplicationToken } from 'test/integration/graphql/utils/renew-application-token.util';+import { renewApplicationToken } from 'test/integration/metadata/suites/application/utils/renew-application-token.util';import { renewToken } from 'test/integration/graphql/utils/renew-token.util';import { signUp } from 'test/integration/graphql/utils/sign-up.util';import { signUpInNewWorkspace } from 'test/integration/graphql/utils/sign-up-in-new-workspace.util';@@ -289,11 +289,17 @@ describe('JWT Legacy HS256 no-kid fallback - seeded-workspace tokens (integratio});it('verifies a hand-crafted no-kid HS256 APPLICATION_REFRESH token via the legacy fallback (round-trip through renewApplicationToken)', async () => {+ const sessionAccessTokenPayload = jwt.decode(+ APPLE_JANE_ADMIN_ACCESS_TOKEN,+ ) as AccessTokenJwtPayload;+const forgedPayload: ApplicationRefreshTokenJwtPayload = {sub: seededApplicationId,type: JwtTokenTypeEnum.APPLICATION_REFRESH,workspaceId: seededWorkspaceId,applicationId: seededApplicationId,+ userId: sessionAccessTokenPayload.userId,+ userWorkspaceId: sessionAccessTokenPayload.userWorkspaceId,};const forgedToken = forgeLegacyHs256Token(@@ -308,16 +314,14 @@ describe('JWT Legacy HS256 no-kid fallback - seeded-workspace tokens (integratioexpect(decoded.header.alg).toBe('HS256');expect(decoded.header.kid).toBeUndefined();- const response = await renewApplicationToken({- applicationRefreshToken: forgedToken,- accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,+ const { data } = await renewApplicationToken({+ input: { applicationRefreshToken: forgedToken },+ expectToFail: false,});- expect(response.body.errors).toBeUndefined();-- const renewed = response.body.data?.renewApplicationToken;+ const renewed = data.renewApplicationToken;- expect(isNonEmptyString(renewed?.applicationAccessToken.token)).toBe(true);- expect(isNonEmptyString(renewed?.applicationRefreshToken.token)).toBe(true);+ expect(isNonEmptyString(renewed.applicationAccessToken.token)).toBe(true);+ expect(isNonEmptyString(renewed.applicationRefreshToken.token)).toBe(true);});});diff --git a/packages/twenty-server/test/integration/graphql/utils/renew-application-token.util.ts b/packages/twenty-server/test/integration/graphql/utils/renew-application-token.util.tsdeleted file mode 100644index 76ac2435227..00000000000--- a/packages/twenty-server/test/integration/graphql/utils/renew-application-token.util.ts+++ /dev/null@@ -1,28 +0,0 @@-import gql from 'graphql-tag';-import { makeMetadataAPIRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';--export const renewApplicationToken = async ({- applicationRefreshToken,- accessToken,-}: {- applicationRefreshToken: string;- accessToken: string;-}) => {- const mutation = gql`- mutation RenewApplicationToken($applicationRefreshToken: String!) {- renewApplicationToken(applicationRefreshToken: $applicationRefreshToken) {- applicationAccessToken {- token- }- applicationRefreshToken {- token- }- }- }- `;-- return await makeMetadataAPIRequest(- { query: mutation, variables: { applicationRefreshToken } },- accessToken,- );-};diff --git a/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-application-token-renewal.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-application-token-renewal.integration-spec.ts.snapnew file mode 100644index 00000000000..b0325ab0532--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-application-token-renewal.integration-spec.ts.snap@@ -0,0 +1,73 @@+// Jest Snapshot v1, https://goo.gl/fbAQLP++exports[`Application token renewal should fail when the caller is an API key 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN_EXCEPTION",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint requires a session access token",+ "name": "ForbiddenError",+}+`;++exports[`Application token renewal should fail when the caller is an application token instead of a session 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN_EXCEPTION",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint requires a session access token",+ "name": "ForbiddenError",+}+`;++exports[`Application token renewal should fail when the refresh token has no user binding 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "Refresh token does not match authenticated session",+ "name": "ForbiddenError",+}+`;++exports[`Application token renewal should fail when the refresh token has no user workspace binding 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "Refresh token does not match authenticated session",+ "name": "ForbiddenError",+}+`;++exports[`Application token renewal should fail when the refresh token is bound to another user 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "Refresh token does not match authenticated session",+ "name": "ForbiddenError",+}+`;++exports[`Application token renewal should fail when the refresh token is bound to another user workspace 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "Refresh token does not match authenticated session",+ "name": "ForbiddenError",+}+`;diff --git a/packages/twenty-server/test/integration/metadata/suites/application/failing-application-token-renewal.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/failing-application-token-renewal.integration-spec.tsnew file mode 100644index 00000000000..f49982feb79--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/application/failing-application-token-renewal.integration-spec.ts@@ -0,0 +1,153 @@+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';+import { findManyApplications } from 'test/integration/graphql/utils/find-many-applications.util';+import { generateApplicationToken } from 'test/integration/metadata/suites/application/utils/generate-application-token.util';+import { renewApplicationToken } from 'test/integration/metadata/suites/application/utils/renew-application-token.util';+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';+import {+ eachTestingContextFilter,+ type EachTestingContext,+} from 'twenty-shared/testing';++import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';+import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';++type GlobalTestContext = {+ sessionBoundAccessToken: string;+ sessionBoundRefreshToken: string;+ otherUserRefreshToken: string;+ otherUserWorkspaceRefreshToken: string;+ noUserRefreshToken: string;+ noUserWorkspaceRefreshToken: string;+};++type TestContext = {+ refreshToken: (globalContext: GlobalTestContext) => string;+ token?: (globalContext: GlobalTestContext) => string;+};++const failingApplicationTokenRenewalTestCases: EachTestingContext<TestContext>[] =+ [+ {+ title: 'when the caller is an application token instead of a session',+ context: {+ refreshToken: (globalContext) => globalContext.sessionBoundRefreshToken,+ token: (globalContext) => globalContext.sessionBoundAccessToken,+ },+ },+ {+ title: 'when the caller is an API key',+ context: {+ refreshToken: (globalContext) => globalContext.sessionBoundRefreshToken,+ token: () => API_KEY_ACCESS_TOKEN,+ },+ },+ {+ title: 'when the refresh token is bound to another user',+ context: {+ refreshToken: (globalContext) => globalContext.otherUserRefreshToken,+ },+ },+ {+ title: 'when the refresh token is bound to another user workspace',+ context: {+ refreshToken: (globalContext) =>+ globalContext.otherUserWorkspaceRefreshToken,+ },+ },+ {+ title: 'when the refresh token has no user binding',+ context: {+ refreshToken: (globalContext) => globalContext.noUserRefreshToken,+ },+ },+ {+ title: 'when the refresh token has no user workspace binding',+ context: {+ refreshToken: (globalContext) =>+ globalContext.noUserWorkspaceRefreshToken,+ },+ },+ ];++describe('Application token renewal should fail', () => {+ let globalTestContext: GlobalTestContext;++ beforeAll(async () => {+ const { data: applicationsData } = await findManyApplications({+ expectToFail: false,+ });+ const [application] = applicationsData.findManyApplications;++ jestExpectToBeDefined(application);++ const applicationId = application.id;+ const workspaceId = SEED_APPLE_WORKSPACE_ID;++ const { data: sessionBoundTokenData } = await generateApplicationToken({+ applicationId,+ expectToFail: false,+ });+ const sessionBoundTokenPair =+ sessionBoundTokenData.generateApplicationToken;++ const [+ otherUserTokenPair,+ otherUserWorkspaceTokenPair,+ noUserTokenPair,+ noUserWorkspaceTokenPair,+ ] = await Promise.all([+ generateApplicationTokenPair({+ workspaceId,+ applicationId,+ userId: USER_DATA_SEED_IDS.TIM,+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,+ }),+ generateApplicationTokenPair({+ workspaceId,+ applicationId,+ userId: USER_DATA_SEED_IDS.JANE,+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.TIM,+ }),+ generateApplicationTokenPair({+ workspaceId,+ applicationId,+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,+ }),+ generateApplicationTokenPair({+ workspaceId,+ applicationId,+ userId: USER_DATA_SEED_IDS.JANE,+ }),+ ]);++ globalTestContext = {+ sessionBoundAccessToken:+ sessionBoundTokenPair.applicationAccessToken.token,+ sessionBoundRefreshToken:+ sessionBoundTokenPair.applicationRefreshToken.token,+ otherUserRefreshToken: otherUserTokenPair.applicationRefreshToken.token,+ otherUserWorkspaceRefreshToken:+ otherUserWorkspaceTokenPair.applicationRefreshToken.token,+ noUserRefreshToken: noUserTokenPair.applicationRefreshToken.token,+ noUserWorkspaceRefreshToken:+ noUserWorkspaceTokenPair.applicationRefreshToken.token,+ };+ });++ it.each(eachTestingContextFilter(failingApplicationTokenRenewalTestCases))(+ '$title',+ async ({ context }) => {+ const { errors } = await renewApplicationToken({+ input: {+ applicationRefreshToken: context.refreshToken(globalTestContext),+ },+ token: context.token?.(globalTestContext),+ expectToFail: true,+ });++ expectOneNotInternalServerErrorSnapshot({ errors });+ },+ );+});diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-application-token-renewal.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-application-token-renewal.integration-spec.tsnew file mode 100644index 00000000000..ab32f7dace9--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-application-token-renewal.integration-spec.ts@@ -0,0 +1,82 @@+import { decodeJwtCompleteOrThrow } from 'test/integration/graphql/utils/decode-jwt-complete-or-throw.util';+import { findManyApplications } from 'test/integration/graphql/utils/find-many-applications.util';+import { generateApplicationToken } from 'test/integration/metadata/suites/application/utils/generate-application-token.util';+import { renewApplicationToken } from 'test/integration/metadata/suites/application/utils/renew-application-token.util';+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';++import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';+import { type ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';+import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';++describe('Application token renewal should succeed', () => {+ let applicationId: string;+ let sessionBoundRefreshToken: string;++ beforeAll(async () => {+ const { data: applicationsData } = await findManyApplications({+ expectToFail: false,+ });+ const [application] = applicationsData.findManyApplications;++ jestExpectToBeDefined(application);++ applicationId = application.id;++ const { data } = await generateApplicationToken({+ applicationId,+ expectToFail: false,+ });++ sessionBoundRefreshToken =+ data.generateApplicationToken.applicationRefreshToken.token;+ });++ afterEach(() => {+ jest.restoreAllMocks();+ });++ it('should renew a refresh token bound to the authenticated session and keep its binding', async () => {+ const tokenBucketThrottleOrThrowSpy = jest.spyOn(+ getAppProviderByClassName<ThrottlerService>('ThrottlerService'),+ 'tokenBucketThrottleOrThrow',+ );++ const { data } = await renewApplicationToken({+ input: { applicationRefreshToken: sessionBoundRefreshToken },+ expectToFail: false,+ });++ const expectedBinding = {+ applicationId,+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ userId: USER_DATA_SEED_IDS.JANE,+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,+ };++ expect(+ decodeJwtCompleteOrThrow(+ data.renewApplicationToken.applicationAccessToken.token,+ ).payload,+ ).toMatchObject({+ ...expectedBinding,+ type: JwtTokenTypeEnum.APPLICATION_ACCESS,+ });+ expect(+ decodeJwtCompleteOrThrow(+ data.renewApplicationToken.applicationRefreshToken.token,+ ).payload,+ ).toMatchObject({+ ...expectedBinding,+ type: JwtTokenTypeEnum.APPLICATION_REFRESH,+ });+ expect(tokenBucketThrottleOrThrowSpy).toHaveBeenCalledWith(+ `app-renew:${SEED_APPLE_WORKSPACE_ID}:${USER_WORKSPACE_DATA_SEED_IDS.JANE}:${applicationId}`,+ 1,+ 30,+ 30_000,+ );+ });+});diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/renew-application-token-query-factory.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/renew-application-token-query-factory.util.tsnew file mode 100644index 00000000000..de878dd6ba9--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/renew-application-token-query-factory.util.ts@@ -0,0 +1,33 @@+import gql from 'graphql-tag';+import { type PerformMetadataQueryParams } from 'test/integration/metadata/types/perform-metadata-query.type';++export type RenewApplicationTokenFactoryInput = {+ applicationRefreshToken: string;+};++const DEFAULT_APPLICATION_TOKEN_PAIR_GQL_FIELDS = `+ applicationAccessToken {+ token+ expiresAt+ }+ applicationRefreshToken {+ token+ expiresAt+ }+`;++export const renewApplicationTokenQueryFactory = ({+ input,+ gqlFields = DEFAULT_APPLICATION_TOKEN_PAIR_GQL_FIELDS,+}: PerformMetadataQueryParams<RenewApplicationTokenFactoryInput>) => ({+ query: gql`+ mutation RenewApplicationToken($applicationRefreshToken: String!) {+ renewApplicationToken(applicationRefreshToken: $applicationRefreshToken) {+ ${gqlFields}+ }+ }+ `,+ variables: {+ applicationRefreshToken: input.applicationRefreshToken,+ },+});diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/renew-application-token.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/renew-application-token.util.tsnew file mode 100644index 00000000000..02bcfa62e9e--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/renew-application-token.util.ts@@ -0,0 +1,43 @@+import {+ type RenewApplicationTokenFactoryInput,+ renewApplicationTokenQueryFactory,+} from 'test/integration/metadata/suites/application/utils/renew-application-token-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 ApplicationTokenPairDTO } from 'src/engine/core-modules/application/application-oauth/dtos/application-token-pair.dto';++export const renewApplicationToken = async ({+ input,+ gqlFields,+ expectToFail = false,+ token,+}: PerformMetadataQueryParams<RenewApplicationTokenFactoryInput>): CommonResponseBody<{+ renewApplicationToken: ApplicationTokenPairDTO;+}> => {+ const graphqlOperation = renewApplicationTokenQueryFactory({+ input,+ gqlFields,+ });++ const response = await makeMetadataAPIRequest(graphqlOperation, token);++ if (expectToFail === true) {+ warnIfNoErrorButExpectedToFail({+ response,+ errorMessage: 'Renewing application token should have failed but did not',+ });+ }++ if (expectToFail === false) {+ warnIfErrorButNotExpectedToFail({+ response,+ errorMessage: 'Renewing application token has failed but should not',+ });+ }++ return { data: response.body.data, errors: response.body.errors };+};diff --git a/packages/twenty-server/test/integration/metadata/suites/front-component/__snapshots__/failing-front-component-application-token-pair.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/front-component/__snapshots__/failing-front-component-application-token-pair.integration-spec.ts.snapnew file mode 100644index 00000000000..93b0257de39--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/front-component/__snapshots__/failing-front-component-application-token-pair.integration-spec.ts.snap@@ -0,0 +1,49 @@+// Jest Snapshot v1, https://goo.gl/fbAQLP++exports[`Front component read with token pair should fail when called with a user-bound token of another application 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN_EXCEPTION",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint requires a session access token",+ "name": "ForbiddenError",+}+`;++exports[`Front component read with token pair should fail when called with a user-bound token of the owning application 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN_EXCEPTION",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint requires a session access token",+ "name": "ForbiddenError",+}+`;++exports[`Front component read with token pair should fail when called with an API key token 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN_EXCEPTION",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint requires a session access token",+ "name": "ForbiddenError",+}+`;++exports[`Front component read with token pair should fail when called with an application token without user binding 1`] = `+{+ "extensions": {+ "code": "FORBIDDEN",+ "subCode": "FORBIDDEN_EXCEPTION",+ "userFriendlyMessage": "You do not have permission to perform this action.",+ },+ "message": "This endpoint requires a session access token",+ "name": "ForbiddenError",+}+`;diff --git a/packages/twenty-server/test/integration/metadata/suites/front-component/failing-front-component-application-token-pair.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/front-component/failing-front-component-application-token-pair.integration-spec.tsnew file mode 100644index 00000000000..88561df3936--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/front-component/failing-front-component-application-token-pair.integration-spec.ts@@ -0,0 +1,126 @@+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';+import { findManyApplications } from 'test/integration/graphql/utils/find-many-applications.util';+import { generateApplicationToken } from 'test/integration/metadata/suites/application/utils/generate-application-token.util';+import { findFrontComponent } from 'test/integration/metadata/suites/front-component/utils/find-front-component.util';+import { findFrontComponents } from 'test/integration/metadata/suites/front-component/utils/find-front-components.util';+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';+import {+ eachTestingContextFilter,+ type EachTestingContext,+} from 'twenty-shared/testing';++import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';++type GlobalTestContext = {+ otherApplicationUserBoundToken: string;+ owningApplicationUserBoundToken: string;+ owningApplicationUnboundToken: string;+};++type TestContext = {+ token: (globalContext: GlobalTestContext) => string;+};++const failingFrontComponentReadTestCases: EachTestingContext<TestContext>[] = [+ {+ title: 'when called with a user-bound token of another application',+ context: {+ token: (globalContext) => globalContext.otherApplicationUserBoundToken,+ },+ },+ {+ title: 'when called with a user-bound token of the owning application',+ context: {+ token: (globalContext) => globalContext.owningApplicationUserBoundToken,+ },+ },+ {+ title: 'when called with an application token without user binding',+ context: {+ token: (globalContext) => globalContext.owningApplicationUnboundToken,+ },+ },+ {+ title: 'when called with an API key token',+ context: {+ token: () => API_KEY_ACCESS_TOKEN,+ },+ },+];++describe('Front component read with token pair should fail', () => {+ let frontComponentId: string;+ let globalTestContext: GlobalTestContext;++ beforeAll(async () => {+ const { data: frontComponentsData } = await findFrontComponents({+ expectToFail: false,+ });+ const [frontComponent] = frontComponentsData.frontComponents;++ jestExpectToBeDefined(frontComponent);++ frontComponentId = frontComponent.id;++ const owningApplicationId = frontComponent.applicationId;++ const { data: applicationsData } = await findManyApplications({+ expectToFail: false,+ });+ const otherApplication = applicationsData.findManyApplications.find(+ ({ id }) => id !== owningApplicationId,+ );++ jestExpectToBeDefined(otherApplication);++ const [+ { data: otherTokenData },+ { data: owningTokenData },+ owningUnboundTokenPair,+ ] = await Promise.all([+ generateApplicationToken({+ applicationId: otherApplication.id,+ expectToFail: false,+ }),+ generateApplicationToken({+ applicationId: owningApplicationId,+ expectToFail: false,+ }),+ generateApplicationTokenPair({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ applicationId: owningApplicationId,+ }),+ ]);++ globalTestContext = {+ otherApplicationUserBoundToken:+ otherTokenData.generateApplicationToken.applicationAccessToken.token,+ owningApplicationUserBoundToken:+ owningTokenData.generateApplicationToken.applicationAccessToken.token,+ owningApplicationUnboundToken:+ owningUnboundTokenPair.applicationAccessToken.token,+ };+ });++ it.each(eachTestingContextFilter(failingFrontComponentReadTestCases))(+ '$title',+ async ({ context }) => {+ const { errors } = await findFrontComponent({+ input: { id: frontComponentId },+ gqlFields: `+ id+ applicationTokenPair {+ applicationAccessToken {+ token+ }+ }+ `,+ token: context.token(globalTestContext),+ expectToFail: true,+ });++ expectOneNotInternalServerErrorSnapshot({ errors });+ },+ );+});diff --git a/packages/twenty-server/test/integration/metadata/suites/front-component/successful-front-component-application-token-pair.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/front-component/successful-front-component-application-token-pair.integration-spec.tsnew file mode 100644index 00000000000..de68790fbe7--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/front-component/successful-front-component-application-token-pair.integration-spec.ts@@ -0,0 +1,82 @@+import { decodeJwtCompleteOrThrow } from 'test/integration/graphql/utils/decode-jwt-complete-or-throw.util';+import { findFrontComponent } from 'test/integration/metadata/suites/front-component/utils/find-front-component.util';+import { findFrontComponents } from 'test/integration/metadata/suites/front-component/utils/find-front-components.util';+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';++import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';+import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';++const FRONT_COMPONENT_WITH_TOKEN_PAIR_GQL_FIELDS = `+ id+ applicationId+ applicationVariables+ applicationTokenPair {+ applicationAccessToken {+ token+ expiresAt+ }+ applicationRefreshToken {+ token+ expiresAt+ }+ }+`;++describe('Front component application token pair should be issued to a session', () => {+ let frontComponentId: string;+ let owningApplicationId: string;++ beforeAll(async () => {+ const { data } = await findFrontComponents({ expectToFail: false });+ const [frontComponent] = data.frontComponents;++ jestExpectToBeDefined(frontComponent);++ frontComponentId = frontComponent.id;+ owningApplicationId = frontComponent.applicationId;+ });++ it('should issue a token pair bound to the session for the owning application', async () => {+ const { data } = await findFrontComponent({+ input: { id: frontComponentId },+ gqlFields: FRONT_COMPONENT_WITH_TOKEN_PAIR_GQL_FIELDS,+ expectToFail: false,+ });++ expect(data.frontComponent).toMatchObject({+ id: frontComponentId,+ applicationId: owningApplicationId,+ applicationVariables: expect.any(Object),+ });++ const { applicationTokenPair } = data.frontComponent;++ jestExpectToBeDefined(applicationTokenPair);++ const expectedBinding = {+ applicationId: owningApplicationId,+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ userId: USER_DATA_SEED_IDS.JANE,+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,+ };++ expect(+ decodeJwtCompleteOrThrow(+ applicationTokenPair.applicationAccessToken.token,+ ).payload,+ ).toMatchObject({+ ...expectedBinding,+ type: JwtTokenTypeEnum.APPLICATION_ACCESS,+ });+ expect(+ decodeJwtCompleteOrThrow(+ applicationTokenPair.applicationRefreshToken.token,+ ).payload,+ ).toMatchObject({+ ...expectedBinding,+ type: JwtTokenTypeEnum.APPLICATION_REFRESH,+ });+ });+});diff --git a/packages/twenty-server/test/integration/utils/generate-application-token-pair.util.ts b/packages/twenty-server/test/integration/utils/generate-application-token-pair.util.tsnew file mode 100644index 00000000000..0c2ac6185d0--- /dev/null+++ b/packages/twenty-server/test/integration/utils/generate-application-token-pair.util.ts@@ -0,0 +1,12 @@+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';++import { type ApplicationTokenService } from 'src/engine/core-modules/auth/token/services/application-token.service';++// Signs through the service rather than the API so a test can bind a pair to+// any user, or leave it unbound, which the API never issues for a session.+export const generateApplicationTokenPair = (+ input: Parameters<ApplicationTokenService['generateApplicationTokenPair']>[0],+) =>+ getAppProviderByClassName<ApplicationTokenService>(+ 'ApplicationTokenService',+ ).generateApplicationTokenPair(input);