mirror of
https://github.com/docmost/docmost.git
synced 2026-08-28 01:07:08 +08:00
feat(ee): MCP OAuth (#2432)
* feat: mcp oauth * fix: small refactor * fix: cleanup consent
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const OAUTH_SCOPE_KEY = 'oauthScope';
|
||||
|
||||
export type OAuthRouteScope = 'read' | 'write';
|
||||
|
||||
export const OAuthScope = (scope: OAuthRouteScope) =>
|
||||
SetMetadata(OAUTH_SCOPE_KEY, scope);
|
||||
@@ -0,0 +1,6 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const REQUIRE_SESSION_AUTH_KEY = 'requireSessionAuth';
|
||||
|
||||
export const RequireSessionAuth = () =>
|
||||
SetMetadata(REQUIRE_SESSION_AUTH_KEY, true);
|
||||
@@ -23,6 +23,11 @@ export const AuditEvent = {
|
||||
API_KEY_UPDATED: 'api_key.updated',
|
||||
API_KEY_DELETED: 'api_key.deleted',
|
||||
|
||||
// OAuth
|
||||
OAUTH_CLIENT_REGISTERED: 'oauth_client.registered',
|
||||
OAUTH_GRANT_CREATED: 'oauth_grant.created',
|
||||
OAUTH_GRANT_REVOKED: 'oauth_grant.revoked',
|
||||
|
||||
// SCIM Tokens
|
||||
SCIM_TOKEN_CREATED: 'scim_token.created',
|
||||
SCIM_TOKEN_UPDATED: 'scim_token.updated',
|
||||
@@ -124,6 +129,8 @@ export const AuditResource = {
|
||||
COMMENT: 'comment',
|
||||
SHARE: 'share',
|
||||
API_KEY: 'api_key',
|
||||
OAUTH_CLIENT: 'oauth_client',
|
||||
OAUTH_GRANT: 'oauth_grant',
|
||||
SCIM_TOKEN: 'scim_token',
|
||||
SSO_PROVIDER: 'sso_provider',
|
||||
WORKSPACE_INVITATION: 'workspace_invitation',
|
||||
|
||||
@@ -12,6 +12,8 @@ export enum EventName {
|
||||
SPACE_UPDATED = 'space.updated',
|
||||
SPACE_DELETED = 'space.deleted',
|
||||
|
||||
USER_PASSWORD_RESET = 'user.password.reset',
|
||||
|
||||
WORKSPACE_CREATED = 'workspace.created',
|
||||
WORKSPACE_UPDATED = 'workspace.updated',
|
||||
WORKSPACE_DELETED = 'workspace.deleted',
|
||||
|
||||
@@ -23,7 +23,9 @@ export const Feature = {
|
||||
PERSONAL_SPACES: 'spaces:personal',
|
||||
DOCX_EXPORT: 'export:docx',
|
||||
BASES: 'bases',
|
||||
OAUTH: 'oauth',
|
||||
AI_CONTROLS: 'ai:controls',
|
||||
MCP_CONTROLS: 'mcp:controls',
|
||||
} as const;
|
||||
|
||||
export type FeatureKey = (typeof Feature)[keyof typeof Feature];
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import {
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||
import { OAUTH_SCOPE_KEY } from '../decorators/oauth-scope.decorator';
|
||||
import { REQUIRE_SESSION_AUTH_KEY } from '../decorators/require-session-auth.decorator';
|
||||
import { JwtType } from '../../core/auth/dto/jwt-payload';
|
||||
|
||||
const handlerSentinel = () => 'handler';
|
||||
const classSentinel = class Controller {};
|
||||
|
||||
function createCtx(): ExecutionContext {
|
||||
return {
|
||||
getHandler: () => handlerSentinel,
|
||||
getClass: () => classSentinel,
|
||||
} as any;
|
||||
}
|
||||
|
||||
function createGuard(scopeMetadata?: unknown, requireSession?: boolean) {
|
||||
const reflector = {
|
||||
getAllAndOverride: jest.fn((key: string) =>
|
||||
key === REQUIRE_SESSION_AUTH_KEY ? requireSession : scopeMetadata,
|
||||
),
|
||||
} as any;
|
||||
const environmentService = {
|
||||
isCloud: jest.fn().mockReturnValue(false),
|
||||
} as any;
|
||||
const guard = new JwtAuthGuard(reflector, environmentService);
|
||||
return { guard, reflector };
|
||||
}
|
||||
|
||||
function oauthUser(scopes: string[]) {
|
||||
return {
|
||||
user: { id: 'user_1' },
|
||||
workspace: { id: 'ws_1' },
|
||||
oauth: { grantId: 'grant_1', scopes },
|
||||
};
|
||||
}
|
||||
|
||||
describe('JwtAuthGuard.handleRequest', () => {
|
||||
it('rethrows the strategy error', () => {
|
||||
const { guard } = createGuard();
|
||||
const err = new UnauthorizedException('bad token');
|
||||
|
||||
expect(() => guard.handleRequest(err, null, null, createCtx())).toThrow(err);
|
||||
});
|
||||
|
||||
it('throws UnauthorizedException when there is no user', () => {
|
||||
const { guard } = createGuard();
|
||||
|
||||
expect(() => guard.handleRequest(null, null, null, createCtx())).toThrow(
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
|
||||
it('returns a non-oauth user untouched without consulting scope metadata', () => {
|
||||
const { guard, reflector } = createGuard();
|
||||
const user = { user: { id: 'user_1' }, workspace: { id: 'ws_1' } };
|
||||
|
||||
expect(guard.handleRequest(null, user, null, createCtx())).toBe(user);
|
||||
expect(reflector.getAllAndOverride).not.toHaveBeenCalledWith(
|
||||
OAUTH_SCOPE_KEY,
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it('forbids an oauth user on a route without scope metadata', () => {
|
||||
const { guard, reflector } = createGuard(undefined);
|
||||
|
||||
expect(() =>
|
||||
guard.handleRequest(null, oauthUser(['read', 'write']), null, createCtx()),
|
||||
).toThrow(ForbiddenException);
|
||||
expect(reflector.getAllAndOverride).toHaveBeenCalledWith(OAUTH_SCOPE_KEY, [
|
||||
handlerSentinel,
|
||||
classSentinel,
|
||||
]);
|
||||
});
|
||||
|
||||
it('passes read scope on a read route', () => {
|
||||
const { guard } = createGuard('read');
|
||||
const user = oauthUser(['read']);
|
||||
|
||||
expect(guard.handleRequest(null, user, null, createCtx())).toBe(user);
|
||||
});
|
||||
|
||||
it('forbids read scope on a write route with insufficient_scope', () => {
|
||||
const { guard } = createGuard('write');
|
||||
|
||||
expect(() =>
|
||||
guard.handleRequest(null, oauthUser(['read']), null, createCtx()),
|
||||
).toThrow('insufficient_scope');
|
||||
});
|
||||
|
||||
it('passes write scope on a read route', () => {
|
||||
const { guard } = createGuard('read');
|
||||
const user = oauthUser(['write']);
|
||||
|
||||
expect(guard.handleRequest(null, user, null, createCtx())).toBe(user);
|
||||
});
|
||||
|
||||
it('passes write scope on a write route', () => {
|
||||
const { guard } = createGuard('write');
|
||||
const user = oauthUser(['write']);
|
||||
|
||||
expect(guard.handleRequest(null, user, null, createCtx())).toBe(user);
|
||||
});
|
||||
|
||||
describe('session-only routes', () => {
|
||||
const sessionUser = {
|
||||
user: { id: 'user_1' },
|
||||
workspace: { id: 'ws_1' },
|
||||
authType: JwtType.ACCESS,
|
||||
};
|
||||
|
||||
it('allows a signed-in session', () => {
|
||||
const { guard } = createGuard(undefined, true);
|
||||
|
||||
expect(guard.handleRequest(null, sessionUser, null, createCtx())).toBe(
|
||||
sessionUser,
|
||||
);
|
||||
});
|
||||
|
||||
it('forbids an api key', () => {
|
||||
const { guard } = createGuard(undefined, true);
|
||||
const apiKeyUser = {
|
||||
user: { id: 'user_1' },
|
||||
workspace: { id: 'ws_1' },
|
||||
authType: JwtType.API_KEY,
|
||||
};
|
||||
|
||||
expect(() =>
|
||||
guard.handleRequest(null, apiKeyUser, null, createCtx()),
|
||||
).toThrow('This action requires an interactive user session');
|
||||
});
|
||||
|
||||
it('forbids an oauth token even when it carries write scope', () => {
|
||||
const { guard } = createGuard('write', true);
|
||||
const user = { ...oauthUser(['write']), authType: JwtType.OAUTH_ACCESS };
|
||||
|
||||
expect(() => guard.handleRequest(null, user, null, createCtx())).toThrow(
|
||||
'This action requires an interactive user session',
|
||||
);
|
||||
});
|
||||
|
||||
it('leaves api keys working on routes without the marker', () => {
|
||||
const { guard } = createGuard(undefined, undefined);
|
||||
const apiKeyUser = {
|
||||
user: { id: 'user_1' },
|
||||
workspace: { id: 'ws_1' },
|
||||
authType: JwtType.API_KEY,
|
||||
};
|
||||
|
||||
expect(guard.handleRequest(null, apiKeyUser, null, createCtx())).toBe(
|
||||
apiKeyUser,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('lets handler metadata override class metadata', () => {
|
||||
const metadataByTarget = new Map<unknown, string>([
|
||||
[handlerSentinel, 'write'],
|
||||
[classSentinel, 'read'],
|
||||
]);
|
||||
const reflector = {
|
||||
getAllAndOverride: jest.fn((key: string, targets: unknown[]) => {
|
||||
if (key === REQUIRE_SESSION_AUTH_KEY) {
|
||||
return undefined;
|
||||
}
|
||||
for (const target of targets) {
|
||||
if (metadataByTarget.has(target)) {
|
||||
return metadataByTarget.get(target);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}),
|
||||
} as any;
|
||||
const environmentService = { isCloud: jest.fn().mockReturnValue(false) } as any;
|
||||
const guard = new JwtAuthGuard(reflector, environmentService);
|
||||
|
||||
expect(() =>
|
||||
guard.handleRequest(null, oauthUser(['read']), null, createCtx()),
|
||||
).toThrow('insufficient_scope');
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,26 @@
|
||||
import {
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
Logger,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||||
import {
|
||||
OAUTH_SCOPE_KEY,
|
||||
OAuthRouteScope,
|
||||
} from '../decorators/oauth-scope.decorator';
|
||||
import { REQUIRE_SESSION_AUTH_KEY } from '../decorators/require-session-auth.decorator';
|
||||
import { JwtType } from '../../core/auth/dto/jwt-payload';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { EnvironmentService } from '../../integrations/environment/environment.service';
|
||||
import { addDays } from 'date-fns';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
private logger = new Logger('JwtAuthGuard');
|
||||
|
||||
constructor(
|
||||
private reflector: Reflector,
|
||||
private environmentService: EnvironmentService,
|
||||
@@ -36,6 +46,39 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
throw err || new UnauthorizedException();
|
||||
}
|
||||
|
||||
const requiresSession = this.reflector.getAllAndOverride<boolean>(
|
||||
REQUIRE_SESSION_AUTH_KEY,
|
||||
[ctx.getHandler(), ctx.getClass()],
|
||||
);
|
||||
if (requiresSession && user.authType !== JwtType.ACCESS) {
|
||||
this.logger.debug(
|
||||
`session-only endpoint ${ctx.getClass()?.name}.${ctx.getHandler()?.name} refused authType ${user.authType}`,
|
||||
);
|
||||
throw new ForbiddenException(
|
||||
'This action requires an interactive user session',
|
||||
);
|
||||
}
|
||||
|
||||
if (user.oauth) {
|
||||
const required = this.reflector.getAllAndOverride<
|
||||
OAuthRouteScope | undefined
|
||||
>(OAUTH_SCOPE_KEY, [ctx.getHandler(), ctx.getClass()]);
|
||||
if (!required) {
|
||||
this.logger.warn(
|
||||
`oauth scope check: no @OAuthScope metadata on ${ctx.getClass()?.name}.${ctx.getHandler()?.name}`,
|
||||
);
|
||||
throw new ForbiddenException('OAuth tokens cannot access this endpoint');
|
||||
}
|
||||
const scopes: string[] = user.oauth.scopes ?? [];
|
||||
const satisfied =
|
||||
required === 'read'
|
||||
? scopes.includes('read') || scopes.includes('write')
|
||||
: scopes.includes('write');
|
||||
if (!satisfied) {
|
||||
throw new ForbiddenException('insufficient_scope');
|
||||
}
|
||||
}
|
||||
|
||||
this.setJoinedWorkspacesCookie(user, ctx);
|
||||
return user;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import {
|
||||
resolveFrameHeader,
|
||||
resolveFrameHeadersForPath,
|
||||
SecurityHeader,
|
||||
} from './security-headers';
|
||||
|
||||
describe('resolveFrameHeader', () => {
|
||||
it('denies framing with X-Frame-Options when embedding is off', () => {
|
||||
expect(resolveFrameHeader(false, [])).toEqual({
|
||||
name: 'X-Frame-Options',
|
||||
value: 'SAMEORIGIN',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null when embedding is on but no origins are configured', () => {
|
||||
expect(resolveFrameHeader(true, [])).toBeNull();
|
||||
});
|
||||
|
||||
it('emits a frame-ancestors CSP for the allowed origins', () => {
|
||||
expect(resolveFrameHeader(true, ['https://a.example', 'https://b.example']))
|
||||
.toEqual({
|
||||
name: 'Content-Security-Policy',
|
||||
value: "frame-ancestors 'self' https://a.example https://b.example",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveFrameHeadersForPath', () => {
|
||||
const configured: SecurityHeader = {
|
||||
name: 'Content-Security-Policy',
|
||||
value: "frame-ancestors 'self' https://a.example",
|
||||
};
|
||||
|
||||
it.each(['/oauth/consent', '/oauth/consent/nested'])(
|
||||
'force-denies %s regardless of configured header',
|
||||
(path) => {
|
||||
expect(resolveFrameHeadersForPath(path, configured)).toEqual([
|
||||
{ name: 'X-Frame-Options', value: 'DENY' },
|
||||
{ name: 'Content-Security-Policy', value: "frame-ancestors 'none'" },
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it('force-denies consent even when the global header is absent', () => {
|
||||
expect(resolveFrameHeadersForPath('/oauth/consent', null)).toEqual([
|
||||
{ name: 'X-Frame-Options', value: 'DENY' },
|
||||
{ name: 'Content-Security-Policy', value: "frame-ancestors 'none'" },
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not match an unrelated path that merely contains the prefix', () => {
|
||||
expect(
|
||||
resolveFrameHeadersForPath('/oauth/consenting-adults', configured),
|
||||
).toEqual([configured]);
|
||||
});
|
||||
|
||||
it('passes the configured header through for other paths', () => {
|
||||
expect(resolveFrameHeadersForPath('/home', configured)).toEqual([
|
||||
configured,
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns nothing for other paths when no header is configured', () => {
|
||||
expect(resolveFrameHeadersForPath('/home', null)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -17,3 +17,19 @@ export function resolveFrameHeader(
|
||||
value: `frame-ancestors 'self' ${allowedOrigins.join(' ')}`,
|
||||
};
|
||||
}
|
||||
|
||||
// Deny OAuth consent in iframe
|
||||
export const OAUTH_CONSENT_PATH = '/oauth/consent';
|
||||
|
||||
export function resolveFrameHeadersForPath(
|
||||
path: string,
|
||||
configuredHeader: SecurityHeader | null,
|
||||
): SecurityHeader[] {
|
||||
if (path === OAUTH_CONSENT_PATH || path.startsWith(`${OAUTH_CONSENT_PATH}/`)) {
|
||||
return [
|
||||
{ name: 'X-Frame-Options', value: 'DENY' },
|
||||
{ name: 'Content-Security-Policy', value: "frame-ancestors 'none'" },
|
||||
];
|
||||
}
|
||||
return configuredHeader ? [configuredHeader] : [];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user