All files / src/entities/vulnerabilities registry.ts

100% Statements 53/53
92.85% Branches 39/42
100% Functions 6/6
100% Lines 52/52

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 20417x 17x 17x   17x 17x 17x 17x 17x                             17x           17x                     6x                                   8x 1x   7x 2x   5x                           17x                           9x 8x   8x   8x   6x 2x       2x 1x   1x     4x 2x       2x 1x   1x     2x       2x       2x     2x 1x   1x                                               9x 8x   8x 8x   8x   2x         2x       3x 3x       1x 1x       2x 2x                         17x 1x    
import * as z from 'zod';
import { BrowseVulnerabilitiesSchema } from './schema-readonly';
import { ManageVulnerabilitySchema } from './schema';
import { ToolRegistry, EnhancedToolDefinition } from '../../types';
import { assertActionAllowed } from '../utils';
import { ConnectionManager } from '../../services/ConnectionManager';
import { cleanGidsFromObject } from '../../utils/idConversion';
import { getGitLabApiUrlFromContext } from '../../oauth/token-context';
import {
  LIST_PROJECT_VULNS,
  LIST_GROUP_VULNS,
  LIST_INSTANCE_VULNS,
  GET_VULN,
  DISMISS_VULN,
  CONFIRM_VULN,
  RESOLVE_VULN,
  REVERT_VULN,
  type VulnListVars,
} from '../../graphql/vulnerabilities';
 
// Vulnerability Management is Ultimate-tier; the capability gate hides the tool on
// lower tiers. The GraphQL surface stabilised around 13.x; the floor is declared
// here and the tier gate does the rest.
const ULTIMATE_REQ = {
  tier: 'ultimate',
  minVersion: '13.0',
  notes: 'Vulnerability Management',
} as const;
 
const vulnerabilityGid = (id: number): string => `gid://gitlab/Vulnerability/${id}`;
 
/** Build the shared GraphQL list filter variables from the parsed input. */
function listVars(input: {
  state?: string[];
  severity?: string[];
  report_type?: string[];
  sort?: string;
  first?: number;
  after?: string;
}): VulnListVars {
  return {
    state: input.state ?? null,
    severity: input.severity ?? null,
    reportType: input.report_type ?? null,
    sort: input.sort ?? null,
    first: input.first ?? 20,
    after: input.after ?? null,
  };
}
 
/**
 * Unwrap a mutation payload: surface a non-empty `errors` array as an error, treat
 * a null payload as an error too (rather than silently returning undefined), and
 * return the cleaned vulnerability on success.
 */
function unwrapVuln(
  payload: { vulnerability: unknown; errors: string[] } | null | undefined,
): unknown {
  if (!payload) {
    throw new Error('GitLab API error: empty mutation response');
  }
  if (payload.errors.length > 0) {
    throw new Error(`GitLab API error: ${payload.errors.join(', ')}`);
  }
  return cleanGidsFromObject(payload.vulnerability);
}
 
/**
 * Vulnerabilities tools registry - 2 CQRS tools.
 *
 * browse_vulnerabilities (Query): list (project/group/instance), get
 * manage_vulnerability (Command): dismiss, confirm, resolve, revert
 *
 * Backed by the GitLab GraphQL Vulnerability API (richer than REST). list scopes
 * by project_id / group_id, or neither for an instance-wide view. State changes
 * map to the vulnerability* mutations. Gated behind USE_VULNERABILITIES. Ultimate
 * tier - the capability gate returns a clear error on Free/Premium.
 */
export const vulnerabilitiesToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
  // ============================================================================
  // browse_vulnerabilities - CQRS Query Tool
  // ============================================================================
  [
    'browse_vulnerabilities',
    {
      name: 'browse_vulnerabilities',
      description:
        'Inspect security vulnerabilities (Ultimate). Actions: list (a project, a group, or the whole instance when neither id is given; filter by state, severity, report_type), get (a single vulnerability by ID with full detail). Related: manage_vulnerability to dismiss, confirm, resolve, or revert findings.',
      inputSchema: z.toJSONSchema(BrowseVulnerabilitiesSchema),
      requirements: { default: ULTIMATE_REQ },
      gate: { envVar: 'USE_VULNERABILITIES', defaultValue: true },
      handler: async (args: unknown): Promise<unknown> => {
        const input = BrowseVulnerabilitiesSchema.parse(args);
        assertActionAllowed('browse_vulnerabilities', input.action);
 
        const client = ConnectionManager.getInstance().getClient(getGitLabApiUrlFromContext());
 
        switch (input.action) {
          case 'list': {
            if (input.project_id) {
              const res = await client.request(LIST_PROJECT_VULNS, {
                fullPath: input.project_id,
                ...listVars(input),
              });
              if (!res.project) {
                throw new Error(`Project "${input.project_id}" not found or not accessible`);
              }
              return cleanGidsFromObject(res.project.vulnerabilities ?? { nodes: [] });
            }
 
            if (input.group_id) {
              const res = await client.request(LIST_GROUP_VULNS, {
                fullPath: input.group_id,
                ...listVars(input),
              });
              if (!res.group) {
                throw new Error(`Group "${input.group_id}" not found or not accessible`);
              }
              return cleanGidsFromObject(res.group.vulnerabilities ?? { nodes: [] });
            }
 
            const res = await client.request(LIST_INSTANCE_VULNS, {
              projectId: null,
              ...listVars(input),
            });
            return cleanGidsFromObject(res.vulnerabilities ?? { nodes: [] });
          }
 
          case 'get': {
            const res = await client.request(GET_VULN, {
              id: vulnerabilityGid(input.vulnerability_id),
            });
            if (!res.vulnerability) {
              throw new Error(`Vulnerability ${input.vulnerability_id} not found`);
            }
            return cleanGidsFromObject(res.vulnerability);
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  // ============================================================================
  // manage_vulnerability - CQRS Command Tool
  // ============================================================================
  [
    'manage_vulnerability',
    {
      name: 'manage_vulnerability',
      description:
        'Drive the vulnerability state machine (Ultimate). Actions: dismiss (with optional dismissal_reason + comment), confirm (genuine finding), resolve (fixed), revert (back to detected). Related: browse_vulnerabilities to discover vulnerability IDs.',
      inputSchema: z.toJSONSchema(ManageVulnerabilitySchema),
      requirements: { default: ULTIMATE_REQ },
      gate: { envVar: 'USE_VULNERABILITIES', defaultValue: true },
      handler: async (args: unknown): Promise<unknown> => {
        const input = ManageVulnerabilitySchema.parse(args);
        assertActionAllowed('manage_vulnerability', input.action);
 
        const client = ConnectionManager.getInstance().getClient(getGitLabApiUrlFromContext());
        const id = vulnerabilityGid(input.vulnerability_id);
 
        switch (input.action) {
          case 'dismiss': {
            const res = await client.request(DISMISS_VULN, {
              id,
              comment: input.comment ?? null,
              dismissalReason: input.dismissal_reason ?? null,
            });
            return unwrapVuln(res.vulnerabilityDismiss);
          }
 
          case 'confirm': {
            const res = await client.request(CONFIRM_VULN, { id });
            return unwrapVuln(res.vulnerabilityConfirm);
          }
 
          case 'resolve': {
            const res = await client.request(RESOLVE_VULN, { id });
            return unwrapVuln(res.vulnerabilityResolve);
          }
 
          case 'revert': {
            const res = await client.request(REVERT_VULN, { id });
            return unwrapVuln(res.vulnerabilityRevertToDetected);
          }
 
          /* 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 getVulnerabilitiesReadOnlyToolNames(): string[] {
  return ['browse_vulnerabilities'];
}