Skip to content

The open alternative to Salesforce, designed for AI.

fix(server): report a credential-less request to UserAuthGuard as UNAUTHENTICATED (#24981)

Félix Malfait77439550e210
diff --git a/packages/twenty-server/src/engine/guards/__tests__/run-guarded-query.test-util.ts b/packages/twenty-server/src/engine/guards/__tests__/run-guarded-query.test-util.ts
new file mode 100644
index 00000000000..1aa7886aeab
--- /dev/null
+++ b/packages/twenty-server/src/engine/guards/__tests__/run-guarded-query.test-util.ts
@@ -0,0 +1,73 @@
+// oxlint-disable twenty/graphql-resolvers-should-be-guarded
+import { type CanActivate, Module, type Type, 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 { UnhandledExceptionFilter } from 'src/filters/unhandled-exception.filter';
+
+// Runs one query through a real Nest + Yoga app so a guard's refusal takes the
+// same path as in production: the root module mirrors the real one, so an
+// exception no typed filter claims lands in the catch-all filter. The module
+// classes are built per call because the resolver's guard is the parameter.
+export const runGuardedQuery = async ({
+ guard,
+ request,
+}: {
+ guard: Type<CanActivate>;
+ request: Record<string, unknown>;
+}) => {
+ @Resolver()
+ class TestResolver {
+ @Query(() => String)
+ @UseGuards(guard)
+ guardedQuery(): string {
+ return 'ok';
+ }
+ }
+
+ @Module({ providers: [TestResolver] })
+ class FeatureModule {}
+
+ @Module({
+ imports: [
+ GraphQLModule.forRoot<YogaDriverConfig>({
+ driver: YogaDriver,
+ autoSchemaFile: true,
+ }),
+ FeatureModule,
+ ],
+ providers: [{ provide: APP_FILTER, useClass: UnhandledExceptionFilter }],
+ })
+ class RootModule {}
+
+ 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;
+};
diff --git a/packages/twenty-server/src/engine/guards/__tests__/user-auth.guard.spec.ts b/packages/twenty-server/src/engine/guards/__tests__/user-auth.guard.spec.ts
new file mode 100644
index 00000000000..5849d654bbd
--- /dev/null
+++ b/packages/twenty-server/src/engine/guards/__tests__/user-auth.guard.spec.ts
@@ -0,0 +1,55 @@
+import { type ExecutionContext, ForbiddenException } from '@nestjs/common';
+
+import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import { runGuardedQuery } from 'src/engine/guards/__tests__/run-guarded-query.test-util';
+import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';
+
+const runQuery = (request: Record<string, unknown>) =>
+ runGuardedQuery({ guard: UserAuthGuard, request });
+
+describe('UserAuthGuard', () => {
+ it('should let a user-scoped request through', async () => {
+ const result = await runQuery({ user: { id: 'user-id' } });
+
+ expect(result.errors).toBeUndefined();
+ expect(result.data?.guardedQuery).toBe('ok');
+ });
+
+ it('should report an unauthenticated request as UNAUTHENTICATED', async () => {
+ const result = await runQuery({});
+
+ 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 API key, which authenticates without a user', async () => {
+ const result = await runQuery({ apiKey: { id: 'api-key-id' } });
+
+ expect(result.errors?.[0]?.originalError).toBeInstanceOf(
+ ForbiddenException,
+ );
+ expect(result.errors?.[0]?.message).toBe('Forbidden resource');
+ });
+
+ it('should keep refusing an application, which authenticates without a user', async () => {
+ const result = await runQuery({ application: { id: 'application-id' } });
+
+ expect(result.errors?.[0]?.originalError).toBeInstanceOf(
+ ForbiddenException,
+ );
+ });
+
+ it('should keep refusing an unauthenticated REST request without throwing', () => {
+ const guard = new UserAuthGuard();
+
+ 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/__tests__/workspace-auth.guard.spec.ts b/packages/twenty-server/src/engine/guards/__tests__/workspace-auth.guard.spec.ts
index a95a3e85d1c..565740601e1 100644
--- 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.ts
@@ -1,79 +1,15 @@
-// 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 { type ExecutionContext, ForbiddenException } from '@nestjs/common';
import { ErrorCode } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import { runGuardedQuery } from 'src/engine/guards/__tests__/run-guarded-query.test-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;
-};
+const runQuery = (request: Record<string, unknown>) =>
+ runGuardedQuery({ guard: WorkspaceAuthGuard, request });
describe('WorkspaceAuthGuard', () => {
it('should let a workspace-scoped request through', async () => {
- const result = await runGuardedQuery({
+ const result = await runQuery({
user: { id: 'user-id' },
workspace: { id: 'workspace-id' },
});
@@ -83,7 +19,7 @@ describe('WorkspaceAuthGuard', () => {
});
it('should report an unauthenticated request as UNAUTHENTICATED', async () => {
- const result = await runGuardedQuery({});
+ const result = await runQuery({});
expect(result.errors?.[0]?.extensions?.code).toBe(
ErrorCode.UNAUTHENTICATED,
@@ -93,7 +29,7 @@ describe('WorkspaceAuthGuard', () => {
// 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' } });
+ const result = await runQuery({ user: { id: 'user-id' } });
expect(result.errors?.[0]?.originalError).toBeInstanceOf(
ForbiddenException,
diff --git a/packages/twenty-server/src/engine/guards/user-auth.guard.ts b/packages/twenty-server/src/engine/guards/user-auth.guard.ts
index 6671112896d..2fdbe1a30a9 100644
--- a/packages/twenty-server/src/engine/guards/user-auth.guard.ts
+++ b/packages/twenty-server/src/engine/guards/user-auth.guard.ts
@@ -1,14 +1,18 @@
import { type CanActivate, type ExecutionContext } from '@nestjs/common';
-import { GqlExecutionContext } from '@nestjs/graphql';
import { type Observable } from 'rxjs';
+import { getRequestOrThrowWhenUnauthenticated } from 'src/engine/guards/utils/get-request-or-throw-when-unauthenticated.util';
+
export class UserAuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
- const ctx = GqlExecutionContext.create(context);
- const request = ctx.getContext().req;
+ const request = getRequestOrThrowWhenUnauthenticated(context);
+
+ if (!request) {
+ return false;
+ }
return request.user !== undefined;
}
diff --git a/packages/twenty-server/src/engine/guards/utils/get-request-or-throw-when-unauthenticated.util.ts b/packages/twenty-server/src/engine/guards/utils/get-request-or-throw-when-unauthenticated.util.ts
new file mode 100644
index 00000000000..2c00b475a48
--- /dev/null
+++ b/packages/twenty-server/src/engine/guards/utils/get-request-or-throw-when-unauthenticated.util.ts
@@ -0,0 +1,45 @@
+import { type ExecutionContext } from '@nestjs/common';
+import { type GqlContextType } from '@nestjs/graphql';
+
+import { msg } from '@lingui/core/macro';
+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);
+
+// Shared by the auth guards so the two cannot drift on how a credential-less
+// request is reported. Returning false reports FORBIDDEN, which clients read as
+// a permission problem and never recover from, so a request nothing
+// authenticated has to say UNAUTHENTICATED instead. GraphQL only, since the
+// catch-all filter turns a GraphQL error thrown on the REST path into a 500.
+export const getRequestOrThrowWhenUnauthenticated = (
+ context: ExecutionContext,
+) => {
+ const request = getRequest(context);
+
+ if (!request) {
+ return undefined;
+ }
+
+ 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.`,
+ });
+ }
+
+ return request;
+};
diff --git a/packages/twenty-server/src/engine/guards/workspace-auth.guard.ts b/packages/twenty-server/src/engine/guards/workspace-auth.guard.ts
index 6609e489983..53dce444cfe 100644
--- a/packages/twenty-server/src/engine/guards/workspace-auth.guard.ts
+++ b/packages/twenty-server/src/engine/guards/workspace-auth.guard.ts
@@ -4,49 +4,21 @@ 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);
+import { getRequestOrThrowWhenUnauthenticated } from 'src/engine/guards/utils/get-request-or-throw-when-unauthenticated.util';
@Injectable()
export class WorkspaceAuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
- const request = getRequest(context);
+ const request = getRequestOrThrowWhenUnauthenticated(context);
if (!request) {
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;