-
Notifications
You must be signed in to change notification settings - Fork 37
Implement project access guards #23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
trknhr
wants to merge
1
commit into
main
Choose a base branch
from
feature/limit-project
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,143
−93
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| // Copyright (c) 2025 Nulab inc. | ||
| // Licensed under the MIT License. | ||
|
|
||
| import dotenv from 'dotenv'; | ||
| import { default as env } from 'env-var'; | ||
| import yargs from 'yargs'; | ||
| import { hideBin } from 'yargs/helpers'; | ||
| import { VERSION } from './version.js'; | ||
|
|
||
| dotenv.config(); | ||
|
|
||
| // Define Read Guard policies | ||
| const READ_GUARD_POLICIES = ['off', 'filter', 'deny'] as const; | ||
| export type ReadGuardPolicy = (typeof READ_GUARD_POLICIES)[number]; | ||
|
|
||
| // Define Write Guard policies | ||
| const WRITE_GUARD_POLICIES = ['on', 'off'] as const; | ||
| export type WriteGuardPolicy = (typeof WRITE_GUARD_POLICIES)[number]; | ||
|
|
||
| export const config = yargs(hideBin(process.argv)) | ||
| .option('backlog-domain', { | ||
| type: 'string', | ||
| describe: 'Backlog domain', | ||
| default: env.get('BACKLOG_DOMAIN').required().asString(), | ||
| }) | ||
| .option('backlog-api-key', { | ||
| type: 'string', | ||
| describe: 'Backlog API key', | ||
| default: env.get('BACKLOG_API_KEY').required().asString(), | ||
| }) | ||
| .option('max-tokens', { | ||
| type: 'number', | ||
| describe: 'Maximum number of tokens allowed in the response', | ||
| default: env.get('MAX_TOKENS').default('50000').asIntPositive(), | ||
| }) | ||
| .option('optimize-response', { | ||
| type: 'boolean', | ||
| describe: | ||
| 'Enable GraphQL-style response optimization to include only requested fields', | ||
| default: env.get('OPTIMIZE_RESPONSE').default('false').asBool(), | ||
| }) | ||
| .option('prefix', { | ||
| type: 'string', | ||
| describe: 'Optional string prefix to prepend to all generated outputs', | ||
| default: env.get('PREFIX').default('').asString(), | ||
| }) | ||
| .option('export-translations', { | ||
| type: 'boolean', | ||
| describe: 'Export translations and exit', | ||
| default: false, | ||
| }) | ||
| .option('enable-toolsets', { | ||
| type: 'array', | ||
| describe: `Specify which toolsets to enable. Defaults to 'all'.`, | ||
| default: env.get('ENABLE_TOOLSETS').default('all').asArray(','), | ||
| }) | ||
| .option('dynamic-toolsets', { | ||
| type: 'boolean', | ||
| describe: | ||
| 'Enable dynamic toolsets such as enable_toolset, list_available_toolsets, etc.', | ||
| default: env.get('ENABLE_DYNAMIC_TOOLSETS').default('false').asBool(), | ||
| }) | ||
| .option('allowed-project-ids', { | ||
| type: 'array', | ||
| describe: 'Comma-separated list of allowed Backlog project IDs', | ||
| default: env.get('BACKLOG_ALLOWED_PROJECT_IDS').default('').asArray(',').filter(Boolean), | ||
| }) | ||
| .option('allowed-project-keys', { | ||
| type: 'array', | ||
| describe: 'Comma-separated list of allowed Backlog project keys', | ||
| default: env.get('BACKLOG_ALLOWED_PROJECT_KEYS').default('').asArray(',').filter(Boolean), | ||
| }) | ||
| .option('key-resolve-ttl-sec', { | ||
| type: 'number', | ||
| describe: 'Cache TTL in seconds for project key-to-ID resolution', | ||
| default: env.get('BACKLOG_KEY_RESOLVE_TTL_SEC').default(300).asInt(), | ||
| }) | ||
| .version(VERSION) | ||
| .help() | ||
| .alias('h', 'help') | ||
| .parseSync(); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| // Copyright (c) 2025 Nulab inc. | ||
| // Licensed under the MIT License. | ||
|
|
||
| import { ReadGuardPolicy, WriteGuardPolicy } from '../config.js'; | ||
|
Check failure on line 4 in src/errors/ProjectAccessForbiddenError.ts
|
||
|
|
||
| export interface ProjectAccessForbiddenErrorData { | ||
| allowedProjectIds: (string | number)[]; | ||
| requestedProjectId?: number; | ||
| requestedProjectKey?: string; | ||
| requestedProjectIds?: number[]; | ||
| } | ||
|
|
||
| export class ProjectAccessForbiddenError extends Error { | ||
| public readonly code = -32040; | ||
| public readonly data: ProjectAccessForbiddenErrorData; | ||
|
|
||
| constructor(message: string, data: ProjectAccessForbiddenErrorData) { | ||
| super(message); | ||
| this.name = 'ProjectAccessForbiddenError'; | ||
| this.data = data; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| // Copyright (c) 2025 Nulab inc. | ||
| // Licensed under the MIT License. | ||
|
|
||
| import { jest } from '@jest/globals'; | ||
| import { Backlog } from 'backlog-js'; | ||
| import { ProjectGuardService } from './ProjectGuardService.js'; | ||
| import { logger } from '../utils/logger.js'; | ||
|
|
||
| const mockBacklog = { | ||
| getProjects: jest.fn(), | ||
| getProject: jest.fn(), | ||
| } as unknown as Backlog; | ||
|
|
||
| describe('ProjectGuardService', () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| (mockBacklog.getProjects as jest.Mock).mockResolvedValue([ | ||
| { id: 1, projectKey: 'HOME' }, | ||
| { id: 2, projectKey: 'TEST-1' }, | ||
| ]); | ||
| jest.spyOn(logger, 'warn').mockImplementation(() => {}); | ||
| }); | ||
|
|
||
| describe('Initialization and Validation', () => { | ||
| it('should initialize with allowed project IDs', async () => { | ||
| const service = new ProjectGuardService(mockBacklog, { | ||
| allowedProjectIds: [123, 456], | ||
| allowedProjectKeys: [], | ||
| writeGuard: 'on', | ||
| readGuard: 'filter', | ||
| keyResolveTtlSec: 300, | ||
| }); | ||
| await service.initialize(); | ||
| expect(service.getAllowedProjectIds()).toEqual(new Set([123, 456])); | ||
| }); | ||
|
|
||
| it('should resolve and add allowed project keys', async () => { | ||
| const service = new ProjectGuardService(mockBacklog, { | ||
| allowedProjectIds: [123], | ||
| allowedProjectKeys: ['HOME'], | ||
| writeGuard: 'on', | ||
| readGuard: 'filter', | ||
| keyResolveTtlSec: 300, | ||
| }); | ||
| await service.initialize(); | ||
| expect(service.getAllowedProjectIds()).toEqual(new Set([123, 1])); | ||
| }); | ||
|
|
||
| it('should throw if a project key cannot be resolved', async () => { | ||
| const service = new ProjectGuardService(mockBacklog, { | ||
| allowedProjectIds: [], | ||
| allowedProjectKeys: ['UNKNOWN'], | ||
| writeGuard: 'on', | ||
| readGuard: 'filter', | ||
| keyResolveTtlSec: 300, | ||
| }); | ||
| await expect(service.initialize()).rejects.toThrow( | ||
| 'Failed to resolve project key: UNKNOWN' | ||
| ); | ||
| }); | ||
|
|
||
| it('should throw if guards are on but no projects are allowed', async () => { | ||
| const service = new ProjectGuardService(mockBacklog, { | ||
| allowedProjectIds: [], | ||
| allowedProjectKeys: [], | ||
| writeGuard: 'on', | ||
| readGuard: 'off', | ||
| keyResolveTtlSec: 300, | ||
| }); | ||
| await expect(service.initialize()).rejects.toThrow( | ||
| 'FATAL: Guards are enabled but no allowed projects are configured.' | ||
| ); | ||
| }); | ||
|
|
||
| it('should warn in dev if projects are allowed but guards are off', async () => { | ||
| process.env.NODE_ENV = 'development'; | ||
| const service = new ProjectGuardService(mockBacklog, { | ||
| allowedProjectIds: [1], | ||
| allowedProjectKeys: [], | ||
| writeGuard: 'off', | ||
| readGuard: 'off', | ||
| keyResolveTtlSec: 300, | ||
| }); | ||
| await service.initialize(); | ||
| expect(logger.warn).toHaveBeenCalledWith( | ||
| 'WARNING: Allowed projects are configured but both read and write guards are off.' | ||
| ); | ||
| }); | ||
|
|
||
| it('should throw in prod if projects are allowed but guards are off', async () => { | ||
| process.env.NODE_ENV = 'production'; | ||
| const service = new ProjectGuardService(mockBacklog, { | ||
| allowedProjectIds: [1], | ||
| allowedProjectKeys: [], | ||
| writeGuard: 'off', | ||
| readGuard: 'off', | ||
| keyResolveTtlSec: 300, | ||
| }); | ||
| await expect(service.initialize()).rejects.toThrow( | ||
| 'FATAL: WARNING: Allowed projects are configured but both read and write guards are off.' | ||
| ); | ||
| }); | ||
|
|
||
| it('should throw in prod if fully unguarded without UNGUARDED_OK flag', async () => { | ||
| process.env.NODE_ENV = 'production'; | ||
| const service = new ProjectGuardService(mockBacklog, { | ||
| allowedProjectIds: [], | ||
| allowedProjectKeys: [], | ||
| writeGuard: 'off', | ||
| readGuard: 'off', | ||
| keyResolveTtlSec: 300, | ||
| }); | ||
| await expect(service.initialize()).rejects.toThrow( | ||
| 'FATAL: Running in production without guards requires BACKLOG_UNGUARDED_OK=I_UNDERSTAND_THE_RISKS' | ||
| ); | ||
| }); | ||
|
|
||
| it('should not throw in prod if fully unguarded with UNGUARDED_OK flag', async () => { | ||
| process.env.NODE_ENV = 'production'; | ||
| const service = new ProjectGuardService(mockBacklog, { | ||
| allowedProjectIds: [], | ||
| allowedProjectKeys: [], | ||
| writeGuard: 'off', | ||
| readGuard: 'off', | ||
| unguardedOk: 'I_UNDERSTAND_THE_RISKS', | ||
| keyResolveTtlSec: 300, | ||
| }); | ||
| await expect(service.initialize()).resolves.not.toThrow(); | ||
| }); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import { Backlog } from 'backlog-js'; | ||
|
|
||
| type ProjectGuardConfig = { | ||
| allowedProjectIds: (string | number)[]; | ||
| allowedProjectKeys: string[]; | ||
| keyResolveTtlSec: number; | ||
| }; | ||
|
|
||
| export class ProjectGuardService { | ||
| private readonly allowedProjectIds = new Set<number>(); | ||
| private readonly allowedProjectKeys = new Set<string>(); | ||
| private readonly config: ProjectGuardConfig; | ||
| private readonly backlog: Backlog; | ||
|
|
||
| constructor(backlog: Backlog, config: ProjectGuardConfig) { | ||
| this.backlog = backlog; | ||
| this.config = config; | ||
| } | ||
|
|
||
| async initialize(): Promise<void> { | ||
| this.config.allowedProjectIds.forEach((id) => { | ||
| const numericId = Number(id); | ||
| if (!isNaN(numericId)) { | ||
| this.allowedProjectIds.add(numericId); | ||
| } | ||
| }); | ||
|
|
||
| if (this.config.allowedProjectKeys.length > 0) { | ||
| // Todo: add TTL caching and try catch errors | ||
| const projects = await this.backlog.getProjects(); | ||
| const projectMap = new Map<string, number>(); | ||
| projects.forEach((p: any) => projectMap.set(p.projectKey, p.id)); | ||
|
|
||
| for (const key of this.config.allowedProjectKeys) { | ||
| const id = projectMap.get(key); | ||
| if (id) { | ||
| this.allowedProjectKeys.add(key); | ||
| this.allowedProjectIds.add(id); | ||
| } else { | ||
| throw new Error(`Failed to resolve project key: ${key}`); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public isAllowed(projectId: number): boolean; | ||
| public isAllowed(projectKey: string): boolean; | ||
| public isAllowed(project: number | string): boolean { | ||
| if (typeof project === 'number') { | ||
| return ( | ||
| this.allowedProjectIds.size === 0 || this.allowedProjectIds.has(project) | ||
| ); | ||
| } | ||
|
|
||
| if (typeof project === 'string') { | ||
| if (this.allowedProjectIds.size === 0) { | ||
| return true; | ||
| } | ||
| return this.allowedProjectKeys.has(project); | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| public getAllowedProjectIds(): Set<number> { | ||
| return this.allowedProjectIds; | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The imported types
ReadGuardPolicyandWriteGuardPolicyare not used in this file. This import should be removed as it's unnecessary.