Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 | 106x 106x 106x 28x 28x 28x 28x 28x 331x 331x 88x 331x 136x 136x 331x 15x 331x 74x 65x 9x 331x 43x 40x 3x 331x 12015x 12009x 58x 11951x 12009x 12009x 12009x 12009x 12009x 106x 890x 106x 106x 268x 268x 268x 1271x 268x 69x 268x 268x 99x 268x 2x 1x 1x 9386x 9386x 5x 9381x 9381x 1211x 8170x 8x 8162x 8133x 10541x 3808x 2585x 6733x 6733x 6732x 6732x 3119x 2458x 3x 3x 2455x 1081x 1081x 1x 1080x 11x 1069x 20x 1049x 1038x 1040x 1019x 30x 2x 28x 1x 1x 27x 38x 13x 13x 22x 15x 15x 2148x 1x 7x 9397x 9397x 9397x 9397x 9397x 9397x 1088x 1088x 1088x 1088x 5x 3292x 3261x 3048x 106x 106x 106x 106x 29x 197x 28x 190x 27x 106x 33x 33x 231x 231x 33x 106x 66x 66x 462x 462x 66x 106x 157x 157x 2198x 2198x 157x 1099x 1099x 157x 106x 65x 401x 401x 38x 36x 53x 53x 19x | /**
* Scope Enforcer - enforces project/namespace/group restrictions
*
* When a project config defines a scope, the ScopeEnforcer ensures
* that all operations are limited to the allowed projects/namespaces/groups.
*
* Security model:
* - Scope is ADDITIVE RESTRICTION only - can only narrow, never expand
* - Applied at tool invocation time, not registration time
* - Throws clear error when operation would exceed scope
*/
import { ProjectPreset, ScopeConfig } from './types';
import { logDebug, logWarn } from '../logger';
import { canonicalProjectPath } from '../utils/api-path';
// Re-export ScopeConfig for backward compatibility
export type { ScopeConfig } from './types';
/**
* Error thrown when an operation exceeds the allowed scope
*/
export class ScopeViolationError extends Error {
constructor(
public readonly attemptedTarget: string,
public readonly allowedScope: ScopeConfig,
) {
const scopeDescription = getScopeDescription(allowedScope);
super(`Operation on '${attemptedTarget}' is outside the allowed scope (${scopeDescription})`);
this.name = 'ScopeViolationError';
}
}
/**
* Get a human-readable description of the scope
*/
function getScopeDescription(scope: ScopeConfig): string {
const parts: string[] = [];
if (scope.project) {
parts.push(`project: ${scope.project}`);
}
if (scope.group) {
const subgroupSuffix = scope.includeSubgroups !== false ? '/*' : '';
parts.push(`group: ${scope.group}${subgroupSuffix}`);
}
if (scope.namespace) {
parts.push(`namespace: ${scope.namespace}/*`);
}
if (scope.projects && scope.projects.length > 0) {
if (scope.projects.length <= 3) {
parts.push(`projects: ${scope.projects.join(', ')}`);
} else {
parts.push(`${scope.projects.length} allowed projects`);
}
}
if (scope.groups && scope.groups.length > 0) {
if (scope.groups.length <= 3) {
parts.push(`groups: ${scope.groups.join(', ')}`);
} else {
parts.push(`${scope.groups.length} allowed groups`);
}
}
return parts.length > 0 ? parts.join('; ') : 'unrestricted';
}
/**
* Normalize a project path for comparison
*
* - Decodes a URL-encoded path ("group%2Fproject"), which tools accept as well
* - Removes leading/trailing slashes
* - Converts to lowercase
* - Handles numeric IDs (returns as-is)
*/
function normalizeProjectPath(path: string): string {
const trimmed = trimSlashes(canonicalProjectPath(path));
// If it's a numeric ID, return as-is
if (/^\d+$/.test(trimmed)) {
return trimmed;
}
return trimmed.toLowerCase();
}
/**
* The path without leading and trailing slashes, in one pass: a pattern anchored at the end
* backtracks over every run of slashes inside a path a caller supplies.
*/
function trimSlashes(path: string): string {
let start = 0;
let end = path.length;
while (start < end && path[start] === '/') start++;
while (end > start && path[end - 1] === '/') end--;
return path.slice(start, end);
}
/** A namespace identity canonicalized before a scope or namespace lookup. */
export function decodePath(path: string): string {
return canonicalProjectPath(path);
}
/**
* Check if a path matches a namespace (used for both projects and groups)
*
* Examples:
* - "mygroup/project" matches namespace "mygroup"
* - "mygroup/subgroup/project" matches namespace "mygroup"
* - "mygroup/subgroup/project" matches namespace "mygroup/subgroup"
* - "other/project" does NOT match namespace "mygroup"
*/
export function isInNamespace(projectPath: string, namespace: string): boolean {
const normalizedProject = normalizeProjectPath(projectPath);
const normalizedNamespace = normalizeProjectPath(namespace);
// Project must start with namespace followed by /
return (
normalizedProject === normalizedNamespace ||
normalizedProject.startsWith(normalizedNamespace + '/')
);
}
/**
* Scope Enforcer class
*
* Enforces project/namespace/group restrictions defined in project config.
* Use isAllowed()/isGroupAllowed() to check before operations,
* or enforce()/enforceGroup() to throw on violation.
*/
export class ScopeEnforcer {
private readonly scope: ScopeConfig;
private readonly allowedProjectsSet: Set<string>;
private readonly allowedGroupsSet: Set<string>;
private readonly includeSubgroups: boolean;
private readonly namespace?: string;
constructor(scope: ScopeConfig) {
this.scope = scope;
this.includeSubgroups = scope.includeSubgroups !== false; // Default true
this.namespace = scope.namespace ? normalizeProjectPath(scope.namespace) : undefined;
// Initialize allowed projects set
this.allowedProjectsSet = new Set((scope.projects ?? []).map((p) => normalizeProjectPath(p)));
// Add single project to set if specified
if (scope.project) {
this.allowedProjectsSet.add(normalizeProjectPath(scope.project));
}
// Initialize allowed groups set
this.allowedGroupsSet = new Set((scope.groups ?? []).map((g) => normalizeProjectPath(g)));
// Add single group to set if specified
if (scope.group) {
this.allowedGroupsSet.add(normalizeProjectPath(scope.group));
}
logDebug('ScopeEnforcer initialized', {
scope: getScopeDescription(scope),
allowedProjectsCount: this.allowedProjectsSet.size,
allowedGroupsCount: this.allowedGroupsSet.size,
includeSubgroups: this.includeSubgroups,
});
}
/**
* Create a ScopeEnforcer from a ProjectPreset
* Returns null if preset has no scope restrictions
*/
static fromPreset(preset: ProjectPreset): ScopeEnforcer | null {
if (!preset.scope) {
return null;
}
return new ScopeEnforcer(preset.scope);
}
/**
* Check if a project path is within the allowed scope
*
* @param projectPath Project path or ID to check (e.g., "group/project" or "123")
* @returns true if allowed, false if outside scope
*/
isAllowed(projectPath: string): boolean {
let normalized: string;
try {
normalized = normalizeProjectPath(projectPath);
} catch {
return false;
}
// If no project restrictions are defined, allow all projects
Iif (!this.hasProjectRestrictions()) {
return true;
}
// Check explicit project list (includes single project from scope.project if set)
if (this.allowedProjectsSet.size > 0 && this.allowedProjectsSet.has(normalized)) {
return true;
}
// Check namespace
if (
this.namespace &&
(normalized === this.namespace || normalized.startsWith(this.namespace + '/'))
) {
return true;
}
// Check if project is within an allowed group (when group scope is set)
if (this.allowedGroupsSet.size > 0) {
for (const allowedGroup of this.allowedGroupsSet) {
if (this.includeSubgroups) {
// Project must be in group or its subgroups
if (normalized === allowedGroup || normalized.startsWith(allowedGroup + '/')) {
return true;
}
} else {
// Project must be directly in group (first-level only)
const parts = normalized.split('/');
if (parts.length >= 2) {
const projectGroup = parts.slice(0, -1).join('/');
if (projectGroup === allowedGroup) {
return true;
}
}
}
}
}
// Check if numeric ID is in allowed projects (can't validate without API call)
// For security, we deny numeric IDs unless they're in the explicit list
if (/^\d+$/.test(normalized)) {
logWarn('Numeric project ID not in allowed scope - denying access', {
projectId: normalized,
});
return false;
}
return false;
}
/**
* Check if a group path is within the allowed scope
*
* @param groupPath Group path or ID to check (e.g., "mygroup" or "parent/child")
* @returns true if allowed, false if outside scope
*/
isGroupAllowed(groupPath: string): boolean {
let normalized: string;
try {
normalized = normalizeProjectPath(groupPath);
} catch {
return false;
}
// Without group restrictions, any group only when nothing is restricted: a scope of
// projects reaches no group.
if (!this.hasGroupRestrictions()) {
return !this.hasProjectRestrictions();
}
// Check explicit group list (includes single group from scope.group if set)
if (this.allowedGroupsSet.size > 0 && this.allowedGroupsSet.has(normalized)) {
return true;
}
// Check if group is a subgroup of an allowed group (when includeSubgroups is true)
if (this.includeSubgroups && this.allowedGroupsSet.size > 0) {
for (const allowedGroup of this.allowedGroupsSet) {
if (normalized === allowedGroup || normalized.startsWith(allowedGroup + '/')) {
return true;
}
}
}
// Check namespace (groups in namespace are allowed)
if (
this.namespace &&
(normalized === this.namespace || normalized.startsWith(this.namespace + '/'))
) {
return true;
}
// Check if numeric ID is in allowed groups (can't validate without API call)
// For security, we deny numeric IDs unless they're in the explicit list
if (/^\d+$/.test(normalized)) {
logWarn('Numeric group ID not in allowed scope - denying access', { groupId: normalized });
return false;
}
return false;
}
/**
* Enforce project scope restriction, throwing if violated
*
* @param projectPath Project path to check
* @throws ScopeViolationError if outside allowed scope
*/
enforce(projectPath: string): void {
if (!this.isAllowed(projectPath)) {
logWarn('Project scope violation attempted', {
attempted: projectPath,
scope: getScopeDescription(this.scope),
});
throw new ScopeViolationError(projectPath, this.scope);
}
}
/**
* Enforce group scope restriction, throwing if violated
*
* @param groupPath Group path to check
* @throws ScopeViolationError if outside allowed scope
*/
enforceGroup(groupPath: string): void {
if (!this.isGroupAllowed(groupPath)) {
logWarn('Group scope violation attempted', {
attempted: groupPath,
scope: getScopeDescription(this.scope),
});
throw new ScopeViolationError(groupPath, this.scope);
}
}
/** Whether the scope lists this numeric id itself, as a project or a group it may name. */
listsId(id: string, kind: NumericTargetKind): boolean {
return (
(kind !== 'group' && this.allowedProjectsSet.has(id)) ||
(kind !== 'project' && this.allowedGroupsSet.has(id))
);
}
/**
* Get the scope configuration
*/
getScope(): ScopeConfig {
return this.scope;
}
/**
* Get scope description for display
*/
getScopeDescription(): string {
return getScopeDescription(this.scope);
}
/**
* Check if scope has any project restrictions
*/
hasProjectRestrictions(): boolean {
const hasProject = Boolean(this.scope.project);
const hasNamespace = Boolean(this.scope.namespace);
const hasProjects = Boolean(this.scope.projects && this.scope.projects.length > 0);
const hasGroup = Boolean(this.scope.group);
const hasGroups = Boolean(this.scope.groups && this.scope.groups.length > 0);
// Groups also restrict projects (projects must be within allowed groups)
return hasProject || hasNamespace || hasProjects || hasGroup || hasGroups;
}
/**
* Check if scope has any group restrictions
*/
hasGroupRestrictions(): boolean {
const hasGroup = Boolean(this.scope.group);
const hasNamespace = Boolean(this.scope.namespace);
const hasGroups = Boolean(this.scope.groups && this.scope.groups.length > 0);
return hasGroup || hasNamespace || hasGroups;
}
/**
* Check if scope has any restrictions (projects or groups)
*/
hasRestrictions(): boolean {
return this.hasProjectRestrictions() || this.hasGroupRestrictions();
}
}
/**
* A project or group identifier as the tool will use it: tool schemas coerce a JSON
* number id to its string form, so a number is checked exactly like that string.
*/
function identifierOf(value: unknown): string | undefined {
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
if (typeof value === 'string' && value.trim()) return value.trim();
return undefined;
}
/**
* Arguments that name a project. Destinations count too: a cross-project merge request or
* job token target.
*/
const PROJECT_FIELDS = [
'project_id',
'projectId',
'project',
'namespace',
'namespacePath',
'fullPath',
'target_project_id',
];
/** Of those, the ones that name a project or a group (labels, wiki, milestones of either). */
const PROJECT_OR_GROUP_FIELDS: ReadonlySet<string> = new Set([
'namespace',
'namespacePath',
'fullPath',
]);
/**
* Arguments that name a group. Destinations count too: a fork's target namespace, a job
* token target group, a new subgroup's parent, and a namespace read by id or path.
*/
const GROUP_FIELDS = [
'group_id',
'groupId',
'group',
'target_group_id',
'parent_id',
'namespace_path',
'namespace_id',
];
/** Whether a declared target was supplied, including an invalid value that must be validated. */
export function hasExplicitScopeTarget(
args: Record<string, unknown>,
declared: ReadonlySet<string>,
): boolean {
for (const field of PROJECT_FIELDS) {
if (declared.has(field) && args[field] !== undefined) return true;
}
for (const field of GROUP_FIELDS) {
if (declared.has(field) && args[field] !== undefined) return true;
}
return false;
}
/**
* Extract project path from tool arguments
*
* Tools may specify project in different ways:
* - project_id: "group/project" or "123"
* - namespace: "group/project"
* - projectId: "group/project"
*
* @param args Tool arguments object
* @returns Array of project paths found in arguments
*/
export function extractProjectsFromArgs(args: Record<string, unknown>): string[] {
const projects: string[] = [];
for (const field of PROJECT_FIELDS) {
const id = identifierOf(args[field]);
if (id) projects.push(id);
}
return projects;
}
/**
* Extract group path from tool arguments
*
* Tools may specify group in different ways:
* - group_id: "mygroup" or "parent/child" or "123"
* - groupId: "mygroup"
* - group: "mygroup"
*
* @param args Tool arguments object
* @returns Array of group paths found in arguments
*/
export function extractGroupsFromArgs(args: Record<string, unknown>): string[] {
const groups: string[] = [];
for (const field of GROUP_FIELDS) {
const id = identifierOf(args[field]);
if (id) groups.push(id);
}
return groups;
}
/** What a numeric id argument may name. */
export type NumericTargetKind = 'project' | 'group' | 'either';
/**
* Every argument naming its project or group by numeric id. A scope is saved as paths, so
* these are resolved to paths before the check, which compares paths only.
*/
export function numericTargets(
args: Record<string, unknown>,
): Array<{ field: string; id: string; kind: NumericTargetKind }> {
const found: Array<{ field: string; id: string; kind: NumericTargetKind }> = [];
const add = (field: string, kind: NumericTargetKind): void => {
const id = identifierOf(args[field]);
if (id && /^\d+$/.test(id)) found.push({ field, id, kind });
};
for (const field of PROJECT_FIELDS) {
add(field, PROJECT_OR_GROUP_FIELDS.has(field) ? 'either' : 'project');
}
for (const field of GROUP_FIELDS) add(field, 'group');
return found;
}
/**
* Enforce scope on tool arguments
*
* Checks all project-related and group-related fields in arguments against the scope.
*
* @param enforcer ScopeEnforcer instance
* @param args Tool arguments
* @throws ScopeViolationError if any project or group is outside scope
*/
export function enforceArgsScope(enforcer: ScopeEnforcer, args: Record<string, unknown>): void {
// Check project paths; an argument that may name a group passes as an allowed group too
for (const field of PROJECT_FIELDS) {
const id = identifierOf(args[field]);
if (!id) continue;
if (PROJECT_OR_GROUP_FIELDS.has(field) && enforcer.isGroupAllowed(id)) continue;
enforcer.enforce(id);
}
// Check group paths
const groups = extractGroupsFromArgs(args);
for (const group of groups) {
enforcer.enforceGroup(group);
}
}
|