The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(server): report an unauthenticated GraphQL request as UNAUTHENTICATED, not FORBIDDEN (#24276)
Félix Malfaita3e2c01598ee
diff --git a/packages/twenty-server/src/engine/guards/__tests__/workspace-auth.guard.spec.ts b/packages/twenty-server/src/engine/guards/__tests__/workspace-auth.guard.spec.tsnew file mode 100644index 00000000000..a95a3e85d1c--- /dev/null+++ b/packages/twenty-server/src/engine/guards/__tests__/workspace-auth.guard.spec.ts@@ -0,0 +1,114 @@+// oxlint-disable twenty/graphql-resolvers-should-be-guarded+import {+ type ExecutionContext,+ ForbiddenException,+ Module,+ UseGuards,+} from '@nestjs/common';+import { APP_FILTER } from '@nestjs/core';+import {+ GraphQLModule,+ GraphQLSchemaHost,+ type GraphQLSchemaHost as GraphQLSchemaHostType,+ Query,+ Resolver,+} from '@nestjs/graphql';+import { Test } from '@nestjs/testing';++import { YogaDriver, type YogaDriverConfig } from '@graphql-yoga/nestjs';+import { type GraphQLSchema, graphql } from 'graphql';++import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';+import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';+import { UnhandledExceptionFilter } from 'src/filters/unhandled-exception.filter';++@Resolver()+class TestResolver {+ @Query(() => String)+ @UseGuards(WorkspaceAuthGuard)+ guardedQuery(): string {+ return 'ok';+ }+}++@Module({ providers: [TestResolver] })+class FeatureModule {}++// Mirrors the root module so an exception no typed filter claims lands in the+// catch-all filter, as it does in production.+@Module({+ imports: [+ GraphQLModule.forRoot<YogaDriverConfig>({+ driver: YogaDriver,+ autoSchemaFile: true,+ }),+ FeatureModule,+ ],+ providers: [{ provide: APP_FILTER, useClass: UnhandledExceptionFilter }],+})+class RootModule {}++const runGuardedQuery = async (request: Record<string, unknown>) => {+ const moduleRef = await Test.createTestingModule({+ imports: [RootModule],+ }).compile();++ const app = moduleRef.createNestApplication();++ await app.init();++ const schema = app.get<GraphQLSchemaHostType>(GraphQLSchemaHost)+ .schema as GraphQLSchema;++ const result = await graphql({+ schema,+ source: '{ guardedQuery }',+ contextValue: { req: request },+ });++ await app.close();++ return result;+};++describe('WorkspaceAuthGuard', () => {+ it('should let a workspace-scoped request through', async () => {+ const result = await runGuardedQuery({+ user: { id: 'user-id' },+ workspace: { id: 'workspace-id' },+ });++ expect(result.errors).toBeUndefined();+ expect(result.data?.guardedQuery).toBe('ok');+ });++ it('should report an unauthenticated request as UNAUTHENTICATED', async () => {+ const result = await runGuardedQuery({});++ expect(result.errors?.[0]?.extensions?.code).toBe(+ ErrorCode.UNAUTHENTICATED,+ );+ });++ // Asserted on the exception rather than the code, which the Yoga error handler+ // derives from the HTTP status further down than this harness reaches.+ it('should keep refusing an authenticated request with no workspace', async () => {+ const result = await runGuardedQuery({ user: { id: 'user-id' } });++ expect(result.errors?.[0]?.originalError).toBeInstanceOf(+ ForbiddenException,+ );+ expect(result.errors?.[0]?.message).toBe('Forbidden resource');+ });++ it('should keep refusing an unauthenticated REST request without throwing', () => {+ const guard = new WorkspaceAuthGuard();++ const httpContext = {+ getType: () => 'http',+ switchToHttp: () => ({ getRequest: () => ({}) }),+ } as unknown as ExecutionContext;++ expect(guard.canActivate(httpContext)).toBe(false);+ });+});diff --git a/packages/twenty-server/src/engine/guards/workspace-auth.guard.ts b/packages/twenty-server/src/engine/guards/workspace-auth.guard.tsindex 6842535a515..6609e489983 100644--- a/packages/twenty-server/src/engine/guards/workspace-auth.guard.ts+++ b/packages/twenty-server/src/engine/guards/workspace-auth.guard.ts@@ -4,10 +4,25 @@ import {Injectable,} from '@nestjs/common';+import { type GqlContextType } from '@nestjs/graphql';++import { msg } from '@lingui/core/macro';import { type Observable } from 'rxjs';+import { isDefined } from 'twenty-shared/utils';+import { AuthExceptionCode } from 'src/engine/core-modules/auth/auth.exception';+import { AuthenticationError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';import { getRequest } from 'src/utils/extract-request';+const hasAuthenticatedPrincipal = (request: {+ user?: unknown;+ apiKey?: unknown;+ application?: unknown;+}): boolean =>+ isDefined(request.user) ||+ isDefined(request.apiKey) ||+ isDefined(request.application);+@Injectable()export class WorkspaceAuthGuard implements CanActivate {canActivate(@@ -19,6 +34,20 @@ export class WorkspaceAuthGuard implements CanActivate {return false;}+ // Returning false here would report FORBIDDEN, which clients read as a+ // permission problem and never recover from. GraphQL only: the catch-all+ // filter turns a GraphQL error thrown on the REST path into a 500.+ if (+ !hasAuthenticatedPrincipal(request) &&+ context.getType<GqlContextType>() === 'graphql'+ ) {+ throw new AuthenticationError('Missing authentication token', {+ subCode: AuthExceptionCode.UNAUTHENTICATED,+ userFriendlyMessage: msg`You must be authenticated to perform this action.`,+ });+ }++ // Workspace-agnostic token: a genuine refusal, renewing returns the same one.if (!request.workspace) {return false;}diff --git a/packages/twenty-server/test/integration/graphql/suites/impersonation/__snapshots__/failing-unauthenticated-impersonation.integration-spec.ts.snap b/packages/twenty-server/test/integration/graphql/suites/impersonation/__snapshots__/failing-unauthenticated-impersonation.integration-spec.ts.snapindex 7e8fff138e4..58f4051cf66 100644--- a/packages/twenty-server/test/integration/graphql/suites/impersonation/__snapshots__/failing-unauthenticated-impersonation.integration-spec.ts.snap+++ b/packages/twenty-server/test/integration/graphql/suites/impersonation/__snapshots__/failing-unauthenticated-impersonation.integration-spec.ts.snap@@ -3,9 +3,11 @@exports[`Impersonation - unauthenticated request denial (integration) rejects an impersonation request with no authentication 1`] = `{"extensions": {- "code": "FORBIDDEN",- "userFriendlyMessage": "An error occurred.",+ "code": "UNAUTHENTICATED",+ "subCode": "UNAUTHENTICATED",+ "userFriendlyMessage": "You must be authenticated to perform this action.",},- "message": "Forbidden resource",+ "message": "Missing authentication token",+ "name": "AuthenticationError",}`;