All files / src/entities/access_tokens registry.ts

98.36% Statements 60/61
93.54% Branches 29/31
100% Functions 6/6
98.27% Lines 57/58

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 20317x 17x 17x 17x   17x 17x       17x     17x                       8x 8x 4x   4x 4x 4x 5x         5x 1x       4x 4x 107x   4x   3x       17x             5x 5x                         10x 3x   7x 3x   4x                           17x                           14x 13x   13x   2x 2x       5x 5x             3x 3x       3x                                             13x 9x   9x   1x 1x       1x       1x 1x       1x       3x 3x       3x       4x 4x                         17x 1x    
import * as z from 'zod';
import { BrowseAccessTokensSchema } from './schema-readonly';
import { ManageAccessTokenSchema } from './schema';
import { gitlab, toQuery } from '../../utils/gitlab-api';
import { ToolRegistry, EnhancedToolDefinition } from '../../types';
import { assertActionAllowed, GITLAB_MAX_PER_PAGE } from '../utils';
import { instanceAtLeast } from '../instance-version';
 
// Personal/project/group access tokens are Free tier; every endpoint used here
// predates the supported version floor.
const FREE_REQ = { tier: 'free' } as const;
 
/** A project/group token list page; `active` drives the client-side state filter. */
const ListedTokensSchema = z.array(z.looseObject({ active: z.boolean() }));
 
/**
 * List project/group tokens, honouring `state`. The server-side filter landed in
 * GitLab 17.2 (older instances ignore it and return every token), so there it is
 * applied client-side on each token's `active` flag, before pagination: GitLab's
 * pages are walked until the requested filtered page is complete or the list ends.
 */
async function listScopedTokens(
  path: string,
  query: { state?: 'active' | 'inactive'; per_page: number; page?: number },
) {
  const { state, per_page: perPage, page = 1 } = query;
  if (!state || instanceAtLeast('17.2')) {
    return gitlab.get(path, { query: toQuery(query, []) });
  }
  const wanted = page * perPage;
  const matches: Array<z.infer<typeof ListedTokensSchema>[number]> = [];
  for (let serverPage = 1; matches.length < wanted; serverPage++) {
    const parsed = ListedTokensSchema.safeParse(
      await gitlab.get(path, {
        query: toQuery({ per_page: GITLAB_MAX_PER_PAGE, page: serverPage }, []),
      }),
    );
    if (!parsed.success) {
      throw new Error(
        `GitLab API error: unexpected access tokens response (${parsed.error.issues[0]?.message ?? 'invalid'})`,
      );
    }
    const batch = parsed.data;
    for (const token of batch) {
      if (token.active === (state === 'active')) matches.push(token);
    }
    if (batch.length < GITLAB_MAX_PER_PAGE) break;
  }
  return matches.slice(wanted - perPage, wanted);
}
 
const NEW_TOKEN_NOTICE =
  'This response contains a token value shown only once. Store it securely; it cannot be retrieved again.';
 
/**
 * Wrap a create/rotate response so the secret it carries is explicitly flagged.
 * The result is serialized to the tool output, so the marker travels with it.
 */
function flagSensitive(response: unknown): unknown {
  Eif (response && typeof response === 'object') {
    return {
      ...(response as Record<string, unknown>),
      _meta: { sensitive: true, notice: NEW_TOKEN_NOTICE },
    };
  }
  return response;
}
 
/**
 * Resolve the REST collection path for a single-token action (get/rotate/revoke).
 * A token belongs to exactly one scope: project, group, or the current user.
 */
function tokenBasePath(input: { project_id?: string; group_id?: string }): string {
  if (input.project_id) {
    return `projects/${encodeURIComponent(input.project_id)}/access_tokens`;
  }
  if (input.group_id) {
    return `groups/${encodeURIComponent(input.group_id)}/access_tokens`;
  }
  return 'personal_access_tokens';
}
 
/**
 * Access-tokens tools registry - 2 CQRS tools.
 *
 * browse_access_tokens (Query): list_personal, list_project, list_group, get
 * manage_access_token (Command): create_project, create_group, rotate, revoke
 *
 * Backed by the GitLab REST access-token endpoints (no GraphQL surface exists).
 * The personal/project/group scopes fold in as actions; get/rotate/revoke infer
 * the scope from project_id / group_id. Gated behind USE_ACCESS_TOKENS. Free tier;
 * project/group creation requires owner/admin on the namespace.
 */
export const accessTokensToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
  // ============================================================================
  // browse_access_tokens - CQRS Query Tool
  // ============================================================================
  [
    'browse_access_tokens',
    {
      name: 'browse_access_tokens',
      description:
        "Inspect access tokens (CI/automation credentials). Actions: list_personal (the current user's PATs; admins may filter by user_id), list_project / list_group (a project's or group's tokens), get (a single token by ID - pass project_id or group_id for project/group tokens, neither for personal). Related: manage_access_token to create, rotate, or revoke.",
      inputSchema: z.toJSONSchema(BrowseAccessTokensSchema),
      requirements: { default: FREE_REQ },
      gate: { envVar: 'USE_ACCESS_TOKENS', defaultValue: true },
      handler: async (args: unknown): Promise<unknown> => {
        const input = BrowseAccessTokensSchema.parse(args);
        assertActionAllowed('browse_access_tokens', input.action);
 
        switch (input.action) {
          case 'list_personal': {
            const { action: _action, ...query } = input;
            return gitlab.get('personal_access_tokens', { query: toQuery(query, []) });
          }
 
          case 'list_project': {
            const { action: _action, project_id, ...query } = input;
            return listScopedTokens(
              `projects/${encodeURIComponent(project_id)}/access_tokens`,
              query,
            );
          }
 
          case 'list_group': {
            const { action: _action, group_id, ...query } = input;
            return listScopedTokens(`groups/${encodeURIComponent(group_id)}/access_tokens`, query);
          }
 
          case 'get':
            return gitlab.get(`${tokenBasePath(input)}/${input.token_id}`);
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  // ============================================================================
  // manage_access_token - CQRS Command Tool
  // ============================================================================
  [
    'manage_access_token',
    {
      name: 'manage_access_token',
      description:
        'Create, rotate, or revoke access tokens. Actions: create_project / create_group (issue a new token with name + scopes, returns the value once), rotate (revoke the old token and return a new value), revoke (delete a token permanently). For rotate/revoke pass project_id or group_id for project/group tokens, neither for personal. Related: browse_access_tokens to discover token IDs.',
      inputSchema: z.toJSONSchema(ManageAccessTokenSchema),
      requirements: { default: FREE_REQ },
      gate: { envVar: 'USE_ACCESS_TOKENS', defaultValue: true },
      handler: async (args: unknown): Promise<unknown> => {
        const input = ManageAccessTokenSchema.parse(args);
        assertActionAllowed('manage_access_token', input.action);
 
        switch (input.action) {
          case 'create_project': {
            const { action: _action, project_id, ...body } = input;
            const res = await gitlab.post(
              `projects/${encodeURIComponent(project_id)}/access_tokens`,
              { body, contentType: 'json' },
            );
            return flagSensitive(res);
          }
 
          case 'create_group': {
            const { action: _action, group_id, ...body } = input;
            const res = await gitlab.post(`groups/${encodeURIComponent(group_id)}/access_tokens`, {
              body,
              contentType: 'json',
            });
            return flagSensitive(res);
          }
 
          case 'rotate': {
            const body = input.expires_at ? { expires_at: input.expires_at } : {};
            const res = await gitlab.post(`${tokenBasePath(input)}/${input.token_id}/rotate`, {
              body,
              contentType: 'json',
            });
            return flagSensitive(res);
          }
 
          case 'revoke': {
            await gitlab.delete(`${tokenBasePath(input)}/${input.token_id}`);
            return { revoked: true, token_id: input.token_id };
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
]);
 
/** Read-only tool names from the registry (for read-only mode filtering). */
export function getAccessTokensReadOnlyToolNames(): string[] {
  return ['browse_access_tokens'];
}