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 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 | 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 154x 154x 19x 138x 19x 231x 231x 148x 145x 145x 141x 141x 38x 38x 38x 10x 28x 12x 20x 16x 13x 2x 11x 145x 1594x 1594x 1x 1593x 10x 10x 9x 9x 9x 10x 10x 10x 28x 6x 6x 5x 141x 141x 106x 106x 106x 100x 100x 79x 141x 15x 126x 7x 119x 3x 3x 116x 10x 106x 66x 66x 38x 70x 19x 19x 9x 9x 9x 9x 10x 40x 2x 38x 3x 35x 9x 26x 1x 25x 6x 19x 85x 4x 81x 2x 79x 19x 35x 19x 47x 19x 61x 79x 79x 1x 78x 5x 73x 7x 66x 7x 7x 6x 6x 6x 1x 6x 1x 6x 1x 6x 6x 6x 6x 6x 7x 7x 7x 16x 16x 15x 1012x 15x 1x 12x 5x 12x 5x 27x 27x 27x 27x 27x 2x 25x 25x 25x 44x 44x 42x 41x 41x 22x 22x 2x 5x 5x 5x 5x 2022x 2022x 6x 2016x 5x 14x 14x 1013x 1013x 1005x 900x 900x 105x 105x 14x 105x 104x 104x 13x 1009x 1009x 1007x 1006x 1006x 5x 4x 8x 8x 8x 8x 8x 1x 7x 7x 6x 6x 6x 6x 6x 6x 6x 19x 1x 18x 18x 18x 17x 17x 16x 16x 1x 4x 4x 7x 7x 7x 9x 1x 1x 8x 8x 5x 17x 119x 119x 117x 117x 8x 8x 17x 17x 17x 17x 16x 1019x 1019x 16x 1x 13x 4x 3x 3x 2x 28x 28x 28x 28x 28x 28x 236x 1102x 234x 1100x 26x 26x 26x 26x 24x 1x 23x 26x 11x 11x 1x 10x 10x 15x 15x 15x 15x 15x 68x 1x 1x 67x 67x 66x 63x 14x 14x 122x 4x 3x 13x 13x 13x 13x 63x 77x 1x 76x 1x 75x 75x 74x 74x 1x 73x 74x 124x 123x 122x 73x 15x 15x 15x 103x 103x 102x 102x 15x 67x 67x 67x 64x 3x 3x 1x | /**
* Calls under a working scope that one GitLab request cannot answer: listings whose rows
* are filtered after GitLab paginated them, the projects of a scope made of projects, and
* mark_all_done, which GitLab would apply to every todo.
*/
import type { EffectivePolicy } from './policy';
import { BrowseDuoSessionsSchema, ManageDuoSessionSchema } from '../entities/duo/schema';
import type { ScopeEnforcer } from '../profiles/scope-enforcer';
import type { ScopeConfig } from '../profiles/types';
import { parseGitLabApiError } from '../utils/error-handler';
import { mapBounded } from '../utils/bounded-map';
import { assertActionAllowed } from '../entities/utils';
import { withTargetPaths } from './scope-ids';
import {
matchesScopeProject,
readScopeProject,
simpleProject,
type ProjectTextMatch,
} from './scope-projects';
import {
multiTargetRunners,
multiTargetSearch,
multiTargetVulnerabilities,
scopeAuditEvents,
scopeProjectSnippets,
scopeSnippetTitleSearch,
} from './composed-feeds';
import {
isComposedListing,
listingOrder,
multiTargetListing,
orderRows,
} from './composed-listings';
import type { ZodType } from 'zod';
import {
BrowseEventsSchema,
BrowseNamespacesSchema,
BrowseProjectsSchema,
BrowseTodosSchema,
} from '../entities/core/schema-readonly';
import {
ManageProjectSchema,
ManageNamespaceSchema,
ManageTodosSchema,
} from '../entities/core/schema';
import { BrowseIterationsSchema } from '../entities/iterations/schema-readonly';
import { BrowseMilestonesSchema } from '../entities/milestones/schema-readonly';
import { ManageMilestoneSchema } from '../entities/milestones/schema';
import { BrowseRefsSchema } from '../entities/refs/schema-readonly';
import { ManageRefSchema } from '../entities/refs/schema';
import { BrowseSearchSchema } from '../entities/search/schema-readonly';
import { BrowseMergeRequestsSchema } from '../entities/mrs/schema-readonly';
import {
ManageMergeRequestSchema,
ManageMrDiscussionSchema,
ManageDraftNotesSchema,
} from '../entities/mrs/schema';
import { BrowsePipelinesSchema } from '../entities/pipelines/schema-readonly';
import { ManagePipelineSchema } from '../entities/pipelines/schema';
import { BrowseFilesSchema } from '../entities/files/schema-readonly';
import { ManageFilesSchema } from '../entities/files/schema';
import { BrowseWorkItemsSchema } from '../entities/workitems/schema-readonly';
import { ManageWorkItemSchema } from '../entities/workitems/schema';
import { BrowseRegistrySchema } from '../entities/container_registry/schema-readonly';
import { ManageRegistrySchema } from '../entities/container_registry/schema';
import { ManageVulnerabilitySchema } from '../entities/vulnerabilities/schema';
import { BrowseRunnersSchema } from '../entities/runners/schema-readonly';
import { BrowseVulnerabilitiesSchema } from '../entities/vulnerabilities/schema-readonly';
import { BrowseAuditEventsSchema } from '../entities/audit_events/schema-readonly';
import { BrowseDeployKeysSchema } from '../entities/deploy-keys/schema-readonly';
import { BrowseSnippetsSchema } from '../entities/snippets/schema-readonly';
import {
COMPOSED_SEARCH_SCOPES,
filteredReadArgs,
isFilteredListing,
scopedArgs,
scopedResult,
scopeProjectsOnly,
scopeTargets,
singleTarget,
type Target,
} from './scope-targets';
import {
DIRECT_PROJECTS_READ,
directGroup,
directGroupSearchRows,
isScopeVulnerability,
keepNodes,
ownedRunnersInScope,
} from './scoped-feeds';
type Args = Record<string, unknown>;
/** Runs one tool call with the caller's instance and token scopes. */
export type RunTool = (tool: string, args: Args) => Promise<unknown>;
/** GitLab's largest page, so a scoped page needs as few requests as possible. */
const UPSTREAM_PAGE_SIZE = 100;
/** Bounds the requests one scoped page may cost: up to 1000 rows read. */
const MAX_UPSTREAM_PAGES = 10;
/** GitLab's own default page size, used when the call names none. */
const DEFAULT_PAGE_SIZE = 20;
/** Listing options a scope made of projects can apply to its projects itself. */
const PROJECT_LIST_OPTIONS = new Set([
'action',
'search',
'page',
'per_page',
'simple',
'order_by',
'sort',
]);
/** The input schemas of the tools whose calls the scope rewrites, filters or emulates. */
const SCOPED_TOOL_SCHEMAS: Readonly<Record<string, ZodType>> = {
browse_iterations: BrowseIterationsSchema,
browse_milestones: BrowseMilestonesSchema,
manage_milestone: ManageMilestoneSchema,
browse_refs: BrowseRefsSchema,
manage_ref: ManageRefSchema,
manage_namespace: ManageNamespaceSchema,
browse_work_items: BrowseWorkItemsSchema,
manage_work_item: ManageWorkItemSchema,
browse_registry: BrowseRegistrySchema,
manage_registry: ManageRegistrySchema,
manage_vulnerability: ManageVulnerabilitySchema,
browse_pipelines: BrowsePipelinesSchema,
manage_pipeline: ManagePipelineSchema,
browse_files: BrowseFilesSchema,
manage_files: ManageFilesSchema,
manage_merge_request: ManageMergeRequestSchema,
manage_mr_discussion: ManageMrDiscussionSchema,
manage_draft_notes: ManageDraftNotesSchema,
browse_projects: BrowseProjectsSchema,
browse_search: BrowseSearchSchema,
browse_merge_requests: BrowseMergeRequestsSchema,
browse_todos: BrowseTodosSchema,
manage_todos: ManageTodosSchema,
browse_namespaces: BrowseNamespacesSchema,
browse_events: BrowseEventsSchema,
browse_deploy_keys: BrowseDeployKeysSchema,
browse_snippets: BrowseSnippetsSchema,
browse_runners: BrowseRunnersSchema,
browse_audit_events: BrowseAuditEventsSchema,
browse_vulnerabilities: BrowseVulnerabilitiesSchema,
browse_duo_sessions: BrowseDuoSessionsSchema,
manage_duo_session: ManageDuoSessionSchema,
manage_project: ManageProjectSchema,
};
/** Requests one scoped call keeps in flight, so a large scope stays within rate limits. */
const REQUEST_CONCURRENCY = 5;
/**
* Target lookups and todo pages one mark_all_done reads, one after another: a scope's
* target lists have no size limit, and the call must end within the handler timeout.
*/
const TODO_READ_REQUESTS = 50;
/** The selected action's validated arguments, shared by scope preflight and execution. */
export function parseScopedArguments(tool: string, requested: Args): Args {
const schema = SCOPED_TOOL_SCHEMAS[tool];
return schema ? (schema.parse(requested) as Args) : requested;
}
const numberOr = (value: unknown, fallback: number): number =>
typeof value === 'number' && value > 0 ? value : fallback;
/** Runs a call for the caller's working scope, narrowing or emulating where needed. */
export async function executeScoped(
unguarded: RunTool,
tool: string,
requested: Args,
policy: EffectivePolicy,
validated = false,
): Promise<unknown> {
const { scope, scopeEnforcer } = policy;
if (!scope || !scopeEnforcer) return unguarded(tool, requested);
// The emulations below run other actions in place of the requested one; an action the
// operator or the preset denied must stay denied rather than run through them.
if (typeof requested.action === 'string') assertActionAllowed(tool, requested.action);
const run = withPresetDenials(unguarded, policy);
// Read as the tool reads it, before anything is rewritten or paged: a scoped call is
// validated and coerced exactly like an unscoped one, and an invalid call is refused.
const call = validated ? requested : parseScopedArguments(tool, requested);
const emulation = emulate(run, tool, call, scope, scopeEnforcer);
if (emulation) return emulation;
const args = scopedArgs(tool, call, scope);
const group = directGroup(scope);
// A group without its subgroups: GitLab's group search covers them, so its rows are kept.
// A group search can only name the scope group itself, as its subgroups are outside.
if (group && tool === 'browse_search' && (call.action === 'global' || call.action === 'group')) {
return directGroupSearch(run, args, group, scopeEnforcer);
}
if (isFilteredListing(tool, args)) {
return fillScopedPage(
run,
tool,
filteredReadArgs(tool, args),
(rows) => scopedResult(tool, args, rows, scopeEnforcer) as unknown[],
);
}
const result = await run(tool, args);
// The group's vulnerabilities cover its subgroups, whether the scope or the caller named it.
if (
group &&
tool === 'browse_vulnerabilities' &&
args.action === 'list' &&
args.project_id === undefined
) {
return keepNodes(result, isScopeVulnerability(scopeEnforcer));
}
return result;
}
/** A request an emulation needs that the preset denies; it fails the whole call. */
class PresetDeniedActionError extends Error {}
/** Runs only actions the preset allows; the operator's denials are checked by the tools. */
function withPresetDenials(run: RunTool, policy: EffectivePolicy): RunTool {
return (tool, args) => {
const action = typeof args.action === 'string' ? args.action : undefined;
if (action !== undefined && policy.deniedActions.get(tool)?.has(action)) {
return Promise.reject(
new PresetDeniedActionError(
`preset '${policy.presetName}' denies the '${action}' action of ${tool}, which this call runs under the working scope`,
),
);
}
return run(tool, args);
};
}
/**
* A global or group search under a group scope without subgroups: the group search, its rows kept to
* the group and its direct projects and paged like the search, in the search's answer shape.
*/
async function directGroupSearch(
run: RunTool,
args: Args,
group: string,
enforcer: ScopeEnforcer,
): Promise<unknown> {
const { keep, complete } = await directGroupSearchRows(run, group, args.scope, enforcer, {
requests: 0,
});
// The search tool answers with its rows under `results`.
const rows: RunTool = async (tool, toolArgs) => {
const answer = await run(tool, toolArgs);
const results = (answer as { results?: unknown } | undefined)?.results;
return Array.isArray(results) ? results : answer;
};
const page = await fillScopedPage(rows, 'browse_search', args, keep);
const marked = complete
? page
: withPartialReason(
page,
`Results are kept to the first ${DIRECT_PROJECTS_READ} direct projects of group '${group}'; results of its other projects are not shown.`,
);
return searchAnswer(marked, { group_id: args.group_id, scope: args.scope });
}
/**
* A scoped page in the search tool's answer shape (`count` and `results`, beside what the
* search was for), keeping a partial page's reason. Anything else passes as it came.
*/
function searchAnswer(page: unknown, about: Args): unknown {
if (Array.isArray(page)) return { ...about, count: page.length, results: page };
const partial = page as { items?: unknown; partial?: unknown; message?: unknown } | undefined;
if (partial?.partial !== true || !Array.isArray(partial.items)) return page;
return {
...about,
count: partial.items.length,
results: partial.items,
partial: true,
message: partial.message,
};
}
/**
* The answer to a call that the scope replaces by other requests, or undefined when the
* call runs as itself. The call has been validated as the tool validates it.
*/
function emulate(
run: RunTool,
tool: string,
requested: Args,
scope: ScopeConfig,
enforcer: ScopeEnforcer,
): Promise<unknown> | undefined {
const instanceOnly = emulateInstanceOnly(run, tool, requested, scope, enforcer);
if (instanceOnly) return instanceOnly;
const target = singleTarget(scope);
// One project's trail and snippets are its own listings; other scopes read their places'.
const placed =
target && 'project' in target
? undefined
: emulateScopePlaces(run, tool, requested, scope, enforcer);
if (placed) return placed;
const composed = target ? undefined : emulateMultiTarget(run, tool, requested, scope, enforcer);
if (composed) return composed;
return (
emulateTargetFeed(run, tool, requested, scope, enforcer) ??
emulateScopeProjects(run, tool, requested, scope)
);
}
/** Calls GitLab answers only for everything the account sees, answered from the scope. */
function emulateInstanceOnly(
run: RunTool,
tool: string,
requested: Args,
scope: ScopeConfig,
enforcer: ScopeEnforcer,
): Promise<unknown> | undefined {
if (tool === 'manage_todos' && requested.action === 'mark_all_done') {
return markScopeTodosDone(run, scope, enforcer);
}
// A project search has no groups scope, and a group search only from GitLab 19.4: the
// scope's groups matching the search answer it, read from the namespace listing.
if (tool === 'browse_search' && requested.action === 'global' && requested.scope === 'groups') {
return scopeGroupSearch(run, requested, enforcer);
}
// Snippet titles are searched, and audit events filtered by entity, only across the
// instance: every scope, one project too, answers them from its own places.
if (
tool === 'browse_search' &&
requested.action === 'global' &&
requested.scope === 'snippet_titles'
) {
return scopeSnippetTitleSearch(run, requested, scope, enforcer).then((found) =>
searchAnswer(found, { scope: 'snippet_titles' }),
);
}
if (
tool === 'browse_audit_events' &&
requested.action === 'list_instance' &&
(requested.entity_type !== undefined || requested.entity_id !== undefined)
) {
return scopeAuditEvents(run, requested, scope, enforcer);
}
return undefined;
}
/** Project listings and searches under a scope made of projects, read from its projects. */
function emulateScopeProjects(
run: RunTool,
tool: string,
requested: Args,
scope: ScopeConfig,
): Promise<unknown> | undefined {
const projects = scopeProjectsOnly(scope);
if (!projects) return undefined;
if (
tool === 'browse_projects' &&
requested.action === 'list' &&
Object.keys(requested).every((key) => PROJECT_LIST_OPTIONS.has(key))
) {
return listScopeProjects(run, projects, requested, 'listing');
}
// Project search has no projects scope: search the selected projects themselves.
if (isProjectSearch(tool, requested)) {
const { search, page, per_page, sort, order_by } = requested;
const searched = { search, page, per_page, sort, order_by };
return listScopeProjects(run, projects, searched, 'search').then((found) =>
searchAnswer(found, { scope: 'projects' }),
);
}
return undefined;
}
/** Targetless listings under a scope of several projects or groups, composed per target. */
function emulateMultiTarget(
run: RunTool,
tool: string,
requested: Args,
scope: ScopeConfig,
enforcer: ScopeEnforcer,
): Promise<unknown> | undefined {
if (
tool === 'browse_vulnerabilities' &&
requested.action === 'list' &&
requested.project_id === undefined &&
requested.group_id === undefined
) {
return multiTargetVulnerabilities(run, requested, scope, enforcer);
}
if (
tool === 'browse_runners' &&
(requested.action === 'list_owned' || requested.action === 'list_all')
) {
return multiTargetRunners(run, requested, scope);
}
// A scope made of projects only answers a search of projects from its projects' listing.
if (
isComposedSearch(tool, requested) ||
(isProjectSearch(tool, requested) && !scopeProjectsOnly(scope))
) {
return multiTargetSearch(run, requested, scope, enforcer);
}
if (isScopeKeyListing(tool, requested)) {
return scopeDeployKeys(run, requested, scope, enforcer);
}
// A scope made of projects lists its projects itself, with the options it can apply.
if (
!(tool === 'browse_projects' && scopeProjectsOnly(scope)) &&
isComposedListing(tool, requested, scope)
) {
return multiTargetListing(run, tool, requested, scope, enforcer);
}
return undefined;
}
/**
* Listings GitLab keeps per project or per group, read from each place of the scope: the
* instance audit trail and project snippets that name no project.
*/
function emulateScopePlaces(
run: RunTool,
tool: string,
requested: Args,
scope: ScopeConfig,
enforcer: ScopeEnforcer,
): Promise<unknown> | undefined {
if (tool === 'browse_audit_events' && requested.action === 'list_instance') {
return scopeAuditEvents(run, requested, scope, enforcer);
}
if (
tool === 'browse_snippets' &&
requested.action === 'list' &&
requested.scope === 'project' &&
!requested.projectId
) {
return scopeProjectSnippets(run, requested, scope, enforcer);
}
return undefined;
}
/** A global search every target answers itself, composed under several targets. */
const isComposedSearch = (tool: string, requested: Args): boolean =>
tool === 'browse_search' &&
requested.action === 'global' &&
COMPOSED_SEARCH_SCOPES.has(requested.scope as string);
/** A global search of projects, which a project's own search does not offer. */
const isProjectSearch = (tool: string, requested: Args): boolean =>
tool === 'browse_search' && requested.action === 'global' && requested.scope === 'projects';
/** A deploy key listing that names no project; the public listing is instance-wide only. */
const isScopeKeyListing = (tool: string, requested: Args): boolean =>
tool === 'browse_deploy_keys' &&
requested.action === 'list' &&
requested.project_id === undefined &&
requested.public !== true;
/** Feeds whose result needs the scope's project or group membership. */
function emulateTargetFeed(
run: RunTool,
tool: string,
requested: Args,
scope: ScopeConfig,
enforcer: ScopeEnforcer,
): Promise<unknown> | undefined {
const target = singleTarget(scope);
// The caller's own runners stay the feed asked for, kept to those the scope can use.
if (target && tool === 'browse_runners' && requested.action === 'list_owned') {
return ownedRunnersInScope(run, requested, target);
}
if (tool === 'browse_events' && requested.action === 'user' && (!target || 'group' in target)) {
return userEventsInScope(run, requested, enforcer);
}
// A single project's keys are its own listing; a group's are composed from its projects.
if (target && 'group' in target && isScopeKeyListing(tool, requested)) {
return scopeDeployKeys(run, requested, scope, enforcer);
}
return undefined;
}
/**
* A search of groups answered by the scope's groups whose name or path match, in the
* search's order: newest first, or oldest first for `sort: asc`. Groups get their IDs in
* creation order, so creation order is ID order; the namespace listing has its own order,
* so the matching groups are read in full (up to 1000 listed) and ordered before paging.
*/
async function scopeGroupSearch(
run: RunTool,
requested: Args,
enforcer: ScopeEnforcer,
): Promise<unknown> {
const read = await readScopeGroups(run, requested.search, enforcer);
if ('answer' in read) return read.answer;
const { groups } = read;
const reasons: string[] = [];
if (!orderGroupsByCreation(groups, requested.sort === 'asc'))
reasons.push('GitLab omitted the ID of some groups, so they keep the listing order.');
if (requested.order_by === 'updated_at')
reasons.push(
'Groups are listed without their update time, so updated_at ordering is replaced by creation order.',
);
if (!read.exhausted)
reasons.push(
`Only the first ${MAX_UPSTREAM_PAGES * UPSTREAM_PAGE_SIZE} namespaces matching the search were read; narrow the search.`,
);
const perPage = numberOr(requested.per_page, DEFAULT_PAGE_SIZE);
const start = (numberOr(requested.page, 1) - 1) * perPage;
const items = groups.slice(start, start + perPage);
const page = reasons.length === 0 ? items : partialPage(items, reasons.join(' '));
return searchAnswer(page, { scope: 'groups' });
}
/** The scope's groups matching a search, from up to MAX_UPSTREAM_PAGES namespace pages. */
async function readScopeGroups(
run: RunTool,
search: unknown,
enforcer: ScopeEnforcer,
): Promise<{ groups: Args[]; exhausted: boolean } | { answer: unknown }> {
const listing: Args = { action: 'list', search };
const groups: Args[] = [];
// Pages are read one after another: whether the next one is needed depends on this one.
for (let upstream = 1; upstream <= MAX_UPSTREAM_PAGES; upstream++) {
const rows = await run('browse_namespaces', {
...listing,
page: upstream,
per_page: UPSTREAM_PAGE_SIZE,
});
if (!Array.isArray(rows)) return { answer: rows };
for (const namespace of scopedResult('browse_namespaces', listing, rows, enforcer) as Args[])
if (namespace.kind === 'group') groups.push(namespace);
if (rows.length < UPSTREAM_PAGE_SIZE) return { groups, exhausted: true };
}
return { groups, exhausted: false };
}
/** Orders groups by creation (their IDs); false when some group has no numeric ID. */
function orderGroupsByCreation(groups: Args[], ascending: boolean): boolean {
if (!groups.every((group) => typeof group.id === 'number')) return false;
const direction = ascending ? 1 : -1;
groups.sort((a, b) => ((a.id as number) - (b.id as number)) * direction);
return true;
}
/**
* The requested page of a listing filtered to the scope. GitLab paginates before the scope
* filters, so its pages are read in turn until the scoped page is full or GitLab has no
* more rows. At most MAX_UPSTREAM_PAGES pages are read for one call; a page still short
* then is returned as partial, so it is not taken for the end of the results.
*/
async function fillScopedPage(
run: RunTool,
tool: string,
args: Args,
keep: (rows: unknown[]) => unknown[] | Promise<unknown[]>,
): Promise<unknown> {
const perPage = numberOr(args.per_page, DEFAULT_PAGE_SIZE);
const page = numberOr(args.page, 1);
const wanted = page * perPage;
const readable = MAX_UPSTREAM_PAGES * UPSTREAM_PAGE_SIZE;
if ((page - 1) * perPage >= readable) {
return partialPage(
[],
`A scoped listing reads the first ${readable} rows GitLab returns, and page ${page} starts after them.`,
);
}
const rows: unknown[] = [];
let exhausted = false;
// Pages are read one after another: whether the next one is needed depends on this one.
for (let upstream = 1; upstream <= MAX_UPSTREAM_PAGES && rows.length < wanted; upstream++) {
const result = await run(tool, { ...args, page: upstream, per_page: UPSTREAM_PAGE_SIZE });
if (!Array.isArray(result)) return result;
rows.push(...(await keep(result)));
exhausted = result.length < UPSTREAM_PAGE_SIZE;
if (exhausted) break;
}
const items = rows.slice((page - 1) * perPage, wanted);
if (exhausted || rows.length >= wanted) return items;
return partialPage(
items,
`Read the first ${readable} rows GitLab returned and found ${rows.length} in the working scope; more may follow.`,
);
}
/** User activity kept to allowed projects, with request-local ID resolution and a hard lookup bound. */
async function userEventsInScope(
run: RunTool,
requested: Args,
enforcer: ScopeEnforcer,
): Promise<unknown> {
const paths = new Map<string, string | undefined>();
const lookupLimit = UPSTREAM_PAGE_SIZE;
let complete = true;
const idOf = (row: unknown): string | undefined => {
const value = (row as Args)?.project_id;
if ((typeof value !== 'number' && typeof value !== 'string') || !/^\d+$/.test(String(value)))
return undefined;
return String(value);
};
const keep = async (rows: unknown[]): Promise<unknown[]> => {
const pending: string[] = [];
for (const row of rows) {
const id = idOf(row);
if (id === undefined || paths.has(id) || enforcer.listsId(id, 'project')) continue;
if (paths.size === lookupLimit) {
complete = false;
continue;
}
paths.set(id, undefined);
pending.push(id);
}
await mapBounded(pending, REQUEST_CONCURRENCY, async (id) => {
const resolved = await withTargetPaths({ project_id: id });
const path = resolved.project_id;
if (typeof path === 'string' && !/^\d+$/.test(path)) paths.set(id, path);
});
return rows.filter((row) => {
const id = idOf(row);
if (id === undefined) return false;
if (enforcer.listsId(id, 'project')) return true;
const path = paths.get(id);
return path !== undefined && enforcer.isAllowed(path);
});
};
const result = await fillScopedPage(run, 'browse_events', requested, keep);
return complete
? result
: withPartialReason(
result,
`Activity was checked against at most ${lookupLimit} distinct projects; unchecked events are omitted.`,
);
}
/**
* A deduplicated page of the keys of the scope's projects: those it names and those of its
* groups, bounded across both the project and the key feeds.
*/
async function scopeDeployKeys(
run: RunTool,
requested: Args,
scope: ScopeConfig,
enforcer: ScopeEnforcer,
): Promise<unknown> {
const page = numberOr(requested.page, 1),
perPage = numberOr(requested.per_page, DEFAULT_PAGE_SIZE);
const wanted = page * perPage;
const readable = MAX_UPSTREAM_PAGES * UPSTREAM_PAGE_SIZE;
if ((page - 1) * perPage >= readable)
return partialPage([], `Requested page starts past the ${readable}-key read bound.`);
const projects = await scopeKeyProjects(run, scope, enforcer);
if ('answer' in projects) return projects.answer;
const keys: unknown[] = [];
const seen = new Set<unknown>();
let requests = 0;
const iterator = projects.paths.values();
let project = iterator.next();
let upstream = 1;
while (!project.done && keys.length < wanted) {
if (requests === MAX_UPSTREAM_PAGES)
return partialPage(
keys.slice((page - 1) * perPage, wanted),
'Reached the key request bound before reading all scope projects.',
);
requests++;
const rows = await run('browse_deploy_keys', {
action: 'list',
project_id: project.value,
page: upstream,
per_page: UPSTREAM_PAGE_SIZE,
});
if (!Array.isArray(rows)) return rows;
appendUniqueKeys(rows, seen, keys);
if (rows.length < UPSTREAM_PAGE_SIZE) {
project = iterator.next();
upstream = 1;
} else upstream++;
}
const result = keys.slice((page - 1) * perPage, wanted);
return projects.complete
? result
: partialPage(
result,
'Keys cover only the scope projects read within the project listing bound.',
);
}
/**
* The scope's projects for a key listing: the projects it names, then each group's own
* projects, the group listings sharing one page bound.
*/
async function scopeKeyProjects(
run: RunTool,
scope: ScopeConfig,
enforcer: ScopeEnforcer,
): Promise<{ paths: Set<string>; complete: boolean } | { answer: unknown }> {
const paths = new Set<string>();
const budget = { pages: 0 };
// Groups are listed in turn: they share one page bound.
for (const target of scopeTargets(scope)) {
if ('project' in target) {
paths.add(target.project);
continue;
}
const listed = await groupProjects(run, target, enforcer, paths, budget);
if (listed !== true) return listed === false ? { paths, complete: false } : listed;
}
return { paths, complete: true };
}
function appendUniqueKeys(rows: unknown[], seen: Set<unknown>, keys: unknown[]): void {
for (const row of rows) {
const id = (row as Args).id;
if (!seen.has(id)) {
seen.add(id);
keys.push(row);
}
}
}
/**
* Adds the paths the group owns, excluding projects only shared into it: true once the
* group is listed to its end, false when the shared page bound stops it first.
*/
async function groupProjects(
run: RunTool,
target: { group: string; subgroups: boolean },
enforcer: ScopeEnforcer,
projects: Set<string>,
budget: { pages: number },
): Promise<boolean | { answer: unknown }> {
let upstream = 0;
while (budget.pages < MAX_UPSTREAM_PAGES) {
budget.pages++;
upstream++;
const rows = await run('browse_projects', {
action: 'list',
group_id: target.group,
include_subgroups: target.subgroups,
page: upstream,
per_page: UPSTREAM_PAGE_SIZE,
});
if (!Array.isArray(rows)) return { answer: rows };
for (const row of rows) {
const path = (row as Args).path_with_namespace;
if (typeof path === 'string' && enforcer.isAllowed(path)) projects.add(path);
}
if (rows.length < UPSTREAM_PAGE_SIZE) return true;
}
return false;
}
/** A scoped page the bounded read could not fill, so it is not taken for the end. */
function partialPage(items: unknown[], reason: string): unknown {
return {
items,
partial: true,
message: `${reason} Narrow the listing (for example with a search) to see the rest.`,
};
}
/** A scoped page marked partial for one more reason, whether or not it already was. */
function withPartialReason(page: unknown, reason: string): unknown {
if (Array.isArray(page)) return partialPage(page, reason);
const partial = page as { items?: unknown; partial?: unknown; message?: unknown };
if (partial?.partial !== true || !Array.isArray(partial.items)) return page;
return { ...partial, message: `${reason} ${String(partial.message)}` };
}
/**
* browse_projects list for a scope made of projects: the projects themselves, filtered by
* the listing's search, ordered as GitLab orders it (newest created first unless the call
* names an order) and paged like it, from at most 1000 of them. Archived projects are left out, as a plain listing
* and GitLab's project search leave them out. A project GitLab no longer has (404) is left
* out; any other failure fails the call rather than returning a shorter list.
*/
async function listScopeProjects(
run: RunTool,
projects: string[],
requested: Args,
match: ProjectTextMatch,
): Promise<unknown> {
const perPage = numberOr(requested.per_page, DEFAULT_PAGE_SIZE);
const page = numberOr(requested.page, 1);
const wanted = page * perPage;
const matching: unknown[] = [];
const limit = Math.min(projects.length, MAX_UPSTREAM_PAGES * UPSTREAM_PAGE_SIZE);
// GitLab orders a listing and a search newest first when no order is named, so any page
// needs every project read and ordered first; a few at a time stays within rate limits.
for (let start = 0; start < limit; start += REQUEST_CONCURRENCY) {
const batch = await Promise.all(
projects
.slice(start, Math.min(start + REQUEST_CONCURRENCY, limit))
.map((project_id) => readScopeProject(run, project_id)),
);
matching.push(
...batch.filter((project) => matchesScopeProject(project, requested.search, match)),
);
}
const { rows, unordered } = orderScopeProjects(matching, requested);
const listed = rows.slice((page - 1) * perPage, wanted);
// A project is read in full; a listing answers with the simple representation unless
// simple=false, as GitLab does (its schema default is true).
const result = requested.simple === false ? listed : listed.map(simpleProject);
if (unordered) return partialPage(result, unordered);
if (limit < projects.length)
return partialPage(
result,
`Sorted matches from the first ${limit} scope projects; other projects were not read.`,
);
return result;
}
/**
* The matches in the order the listing or search names (newest created first by default),
* or in scope order with the reason when that order cannot be reproduced.
*/
function orderScopeProjects(
matching: unknown[],
requested: Args,
): { rows: unknown[]; unordered?: string } {
// A single match is in order whatever GitLab reported for it.
if (matching.length < 2) return { rows: matching };
const ordering = listingOrder('browse_projects', requested);
if (!ordering)
return {
rows: matching,
unordered: `The ${String(requested.order_by)} order is GitLab's own ranking and cannot be reproduced for the scope's projects; results retain scope order.`,
};
const ordered = orderRows(matching as Args[], ordering);
return ordered
? { rows: ordered }
: {
rows: matching,
unordered: 'GitLab omitted the requested ordering field; results retain scope order.',
};
}
/**
* mark_all_done for a scoped chat: GitLab's own would also clear todos outside the scope,
* so the scope's pending todos are marked done one by one. Each project or group of the
* scope has its todos read with GitLab's own filter, so todos outside the scope never fill
* the pages read. One call marks at most UPSTREAM_PAGE_SIZE todos, so it finishes within the
* handler timeout; marked todos leave the pending feed, so a repeated call continues where
* this one stopped.
*/
async function markScopeTodosDone(
run: RunTool,
scope: ScopeConfig,
enforcer: ScopeEnforcer,
): Promise<unknown> {
const targets = uniqueTargets(scope);
// Collected before marking: a todo marked done leaves the pending pages being read.
const ids = new Set<unknown>();
// Only a group without its subgroups, whose filter also lists theirs, needs pages past its
// first; those share a bound of their own.
const furtherPages = { left: MAX_UPSTREAM_PAGES };
const requests = { left: TODO_READ_REQUESTS };
let reason: string | undefined;
// Targets are read one after another: whether the next one is needed depends on this one.
for (let read = 0; read < targets.length && !reason; read++) {
// A target costs its lookup and at least its first page of todos.
if (requests.left < 2) {
reason = `Todos were read for ${read} of the ${targets.length} projects and groups of the working scope within ${TODO_READ_REQUESTS} requests; todos of the others are still pending. Narrow the scope to reach them.`;
break;
}
requests.left--;
const filter = await todoFilter(run, targets[read]);
if (filter === undefined) continue;
reason = await collectTargetTodos(run, filter, enforcer, ids, furtherPages, requests);
}
// A few requests at a time, so a large scope does not run into GitLab's rate limits;
// a todo that fails is reported and the rest are still marked.
const failed: Array<{ id: unknown; error: string }> = [];
await mapBounded([...ids], REQUEST_CONCURRENCY, (id) =>
run('manage_todos', { action: 'mark_done', id }).catch((error: unknown) => {
// A denied action fails every todo alike: the call is refused rather than reported.
if (error instanceof PresetDeniedActionError) throw error;
failed.push({ id, error: error instanceof Error ? error.message : String(error) });
}),
);
const marked = ids.size - failed.length;
const failedNote = failed.length > 0 ? `; ${failed.length} could not be marked` : '';
const message = `Marked ${marked} of ${ids.size} todos of the working scope as done${failedNote}; todos outside it were left pending`;
return {
success: failed.length === 0,
marked,
failed,
...(reason ? { partial: true, message: `${message}. ${reason}` } : { message }),
};
}
/**
* Adds one target's pending todos of the scope to `ids`, up to UPSTREAM_PAGE_SIZE; why it
* stopped before the target's last todo, if it did. A todo of a project inside a group of the
* scope is listed for both and kept once.
*/
async function collectTargetTodos(
run: RunTool,
filter: Args,
enforcer: ScopeEnforcer,
ids: Set<unknown>,
furtherPages: { left: number },
requests: { left: number },
): Promise<string | undefined> {
// Pages are read one after another: whether the next one is needed depends on this one.
for (let page = 1; ; page++) {
if (page > 1 && furtherPages.left-- === 0)
return `Todos of subgroups outside the working scope filled the ${MAX_UPSTREAM_PAGES * UPSTREAM_PAGE_SIZE} pending todos read past each group's first page; any scope todos after them are still pending.`;
if (requests.left-- === 0)
return `Todos of the working scope were read within ${TODO_READ_REQUESTS} requests; any scope todos after them are still pending. Narrow the scope to reach them.`;
const todos = await run('browse_todos', {
action: 'list',
state: 'pending',
per_page: UPSTREAM_PAGE_SIZE,
page,
...filter,
});
if (!Array.isArray(todos)) return undefined;
const inScope = scopedResult('browse_todos', { action: 'list' }, todos, enforcer) as Array<{
id?: unknown;
}>;
if (!addTodoIds(inScope, ids))
return `One call marks at most ${UPSTREAM_PAGE_SIZE} todos; call mark_all_done again to mark the rest.`;
if (todos.length < UPSTREAM_PAGE_SIZE) return undefined;
}
}
/** Adds the todos' ids not seen yet; false when one did not fit within a call's limit. */
function addTodoIds(todos: Array<{ id?: unknown }>, ids: Set<unknown>): boolean {
for (const { id } of todos) {
if (ids.has(id)) continue;
if (ids.size === UPSTREAM_PAGE_SIZE) return false;
ids.add(id);
}
return true;
}
/** The scope's projects and groups, each once however often a preset names it. */
function uniqueTargets(scope: ScopeConfig): Target[] {
const seen = new Set<string>();
const targets: Target[] = [];
for (const target of scopeTargets(scope)) {
const key = 'project' in target ? `p:${target.project}` : `g:${target.group}`;
if (seen.has(key)) continue;
seen.add(key);
targets.push(target);
}
return targets;
}
/**
* The todo listing's filter for one target: GitLab filters todos by numeric project or group
* id only (lib/api/todos.rb), so the target is read for its id. A target GitLab no longer
* knows has no todos to read.
*/
async function todoFilter(run: RunTool, target: Target): Promise<Args | undefined> {
const [tool, args, filter] =
'project' in target
? ['browse_projects', { action: 'get', project_id: target.project }, 'project_id']
: ['browse_namespaces', { action: 'get', namespace_id: target.group }, 'group_id'];
try {
const id = ((await run(tool, args)) as Args | undefined)?.id;
return typeof id === 'number' ? { [filter]: id } : undefined;
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
if (parseGitLabApiError(message)?.status === 404) return undefined;
throw error;
}
}
|