All files / src/services NamespaceTierDetector.ts

97.6% Statements 122/125
94.18% Branches 81/86
100% Functions 12/12
100% Lines 108/108

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        21x 21x     21x 21x 21x 21x 21x 21x 21x 21x   21x 21x 21x 21x 21x 21x                     21x                         1085x 1085x 1083x   2x   2x 1081x 1081x 1080x 1080x 1079x         1079x                 21x 5x 5x       8x       1077x 1077x 1077x 5x 1x 1x 1x   4x       1073x 1073x 44x 44x   1073x 1073x 1075x 1073x 2x 2x 2x 2x 2x 2x 2x     21x 49x 48x                 1078x 1078x               1077x 6x 6x 6x   1071x         2152x 2152x 2152x   2152x                 7x 7x 7x 6x 3x 3x   3x 3x               21x       1082x 1081x 1081x 1080x 1080x 1077x 1077x 1077x 1077x 1077x     1073x 1073x 1073x 1073x   1071x 1069x 1069x   1069x 1069x       2x 2x   1073x 1073x     21x       4x 4x 4x 4x 4x   4x    
/**
 * Subscription observations scoped to a credential and root namespace.
 * These disposable facts guide discovery, not GitLab authorization.
 */
import { createHash } from 'node:crypto';
import { z } from 'zod';
import type { NamespaceTierInfo } from '../oauth/types';
import type { GitLabTier } from './GitLabVersionDetector';
import { getTokenContext } from '../oauth/token-context';
import { enhancedFetch, getAuthHeaders } from '../utils/fetch';
import { getGitLabBaseUrl } from '../utils/gitlab-base-url';
import { normalizeInstanceUrl } from '../utils/url';
import { readBoundedJson } from '../utils/bounded-json';
import { canonicalProjectPath, encodeApiSegment } from '../utils/api-path';
import { logWarn } from '../logger';
import { isOAuthEnabled } from '../oauth/config';
 
const CACHE_TTL_MS = 5 * 60 * 1000;
const CACHE_CAPACITY = 1024;
const namespaceTierCache = new Map<string, Map<string, NamespaceTierInfo>>();
const ProjectMetadataSchema = z.object({ path_with_namespace: z.string() });
const GroupMetadataSchema = z.object({ full_path: z.string() });
const NamespaceMetadataSchema = z.object({ plan: z.string().nullish() });
 
interface Identity {
  baseUrl: string;
  headers: Record<string, string>;
  credential: string;
  sessionId: string;
}
 
// Plan names: https://gitlab.com/gitlab-org/gitlab/-/blob/v16.0.0-ee/ee/app/models/ee/plan.rb
// Legacy plans without an equivalent in the supported three-tier model stay unknown.
const PLAN_TIERS = new Map<string, GitLabTier>([
  ['free', 'free'],
  ['default', 'free'],
  ['premium', 'premium'],
  ['premium_trial', 'premium'],
  ['silver', 'premium'],
  ['ultimate', 'ultimate'],
  ['ultimate_trial', 'ultimate'],
  ['gold', 'ultimate'],
  ['opensource', 'ultimate'],
]);
 
function identity(): Identity | null {
  const context = getTokenContext();
  if (isOAuthEnabled() && !context?.gitlabToken) return null;
  if (
    context?.gitlabScopes &&
    !context.gitlabScopes.some((scope) => scope === 'api' || scope === 'read_api')
  )
    return null;
  const baseUrl = getGitLabBaseUrl();
  if (!baseUrl) return null;
  const headers = getAuthHeaders(baseUrl);
  if (Object.keys(headers).length === 0) return null;
  const credential = createHash('sha256')
    .update(context ? String(context.gitlabUserId) : '')
    .update('\0')
    .update(JSON.stringify(headers))
    .digest('hex');
  return {
    baseUrl: normalizeInstanceUrl(baseUrl),
    headers,
    credential,
    sessionId: context ? context.sessionId : credential,
  };
}
 
/** Optional billing lookups use exactly the transport's selected instance and credential. */
export function canResolveNamespaceTier(instanceUrl: string): boolean {
  const caller = identity();
  return caller !== null && caller.baseUrl === normalizeInstanceUrl(instanceUrl);
}
 
function unknown(): NamespaceTierInfo {
  return { tier: null, cachedAt: new Date() };
}
 
function cached(sessionId: string, key: string): NamespaceTierInfo | undefined {
  const entries = namespaceTierCache.get(sessionId);
  const value = entries?.get(key);
  if (!value) return undefined;
  if (Date.now() - value.cachedAt.getTime() > CACHE_TTL_MS) {
    entries?.delete(key);
    Eif (entries?.size === 0) namespaceTierCache.delete(sessionId);
    return undefined;
  }
  return value;
}
 
function remember(sessionId: string, key: string, value: NamespaceTierInfo): void {
  let entries = namespaceTierCache.get(sessionId);
  if (!entries) {
    entries = new Map();
    namespaceTierCache.set(sessionId, entries);
  }
  entries.set(key, value);
  let count = 0;
  for (const values of namespaceTierCache.values()) count += values.size;
  if (count <= CACHE_CAPACITY) return;
  const oldestSession = namespaceTierCache.keys().next().value;
  Iif (oldestSession === undefined) return;
  const oldest = namespaceTierCache.get(oldestSession);
  Iif (!oldest) return;
  const oldestKey = oldest.keys().next().value;
  Eif (oldestKey !== undefined) oldest.delete(oldestKey);
  Iif (oldest.size === 0) namespaceTierCache.delete(oldestSession);
}
 
export function clearNamespaceTierCache(sessionId?: string): void {
  if (sessionId !== undefined) namespaceTierCache.delete(sessionId);
  else namespaceTierCache.clear();
}
 
async function readMetadata(
  collection: 'namespaces' | 'projects' | 'groups',
  id: string,
  caller: Identity,
  limit: number,
): Promise<{ status: number; value: unknown }> {
  const query = collection === 'groups' ? '?with_projects=false' : '';
  const response = await enhancedFetch(
    `${caller.baseUrl}/api/v4/${collection}/${encodeApiSegment(id)}${query}`,
    {
      method: 'GET',
      headers: caller.headers,
      rateLimitBaseUrl: caller.baseUrl,
    },
  );
  if (!response.ok) {
    await response.body?.cancel();
    logWarn('Namespace subscription metadata is unavailable', { status: response.status });
    return { status: response.status, value: null };
  }
  return { status: response.status, value: await readBoundedJson(response, limit) };
}
 
/** GitLab namespaces inherit the subscription of their root namespace. */
function rootOf(path: string): string | null {
  const canonical = canonicalProjectPath(path);
  const separator = canonical.indexOf('/');
  const root = separator === -1 ? canonical : canonical.slice(0, separator);
  // Namespace::URL_MAX_LENGTH, app/models/namespace.rb at v16.0.0-ee.
  return root.length > 0 && root.length <= 255 ? root : null;
}
 
/** Match the handlers' group-first resolution, falling through only on a confirmed 404. */
async function numericTargetPath(
  id: string,
  kind: 'project' | 'group' | 'either',
  caller: Identity,
): Promise<string | null> {
  const collection = kind === 'project' ? 'projects' : 'groups';
  const { status, value } = await readMetadata(collection, id, caller, 1024 * 1024);
  if (kind === 'either' && status === 404) return numericTargetPath(id, 'project', caller);
  if (kind === 'project') {
    const parsed = ProjectMetadataSchema.safeParse(value);
    return parsed.success ? parsed.data.path_with_namespace : null;
  }
  const parsed = GroupMetadataSchema.safeParse(value);
  return parsed.success ? parsed.data.full_path : null;
}
 
/**
 * Read a root subscription, resolving typed numeric targets first.
 * GitLab 16.0 exposes plan only with admin_namespace permission:
 * https://gitlab.com/gitlab-org/gitlab/-/blob/v16.0.0-ee/ee/lib/ee/api/entities/namespace.rb#L28-30
 */
export async function getNamespaceTier(
  namespacePath: string,
  targetKind?: 'project' | 'group' | 'either',
): Promise<NamespaceTierInfo> {
  const canonical = canonicalProjectPath(namespacePath);
  const root = rootOf(canonical);
  if (root === null) return unknown();
  const caller = identity();
  if (caller === null) return unknown();
  const numeric = targetKind !== undefined && /^\d+$/.test(canonical);
  const target = numeric ? `${targetKind}:${canonical}` : `namespace:${root}`;
  const key = JSON.stringify([caller.baseUrl, caller.credential, target]);
  const previous = cached(caller.sessionId, key);
  if (previous) return previous;
 
  let observation: NamespaceTierInfo;
  try {
    const path = numeric ? await numericTargetPath(canonical, targetKind, caller) : root;
    const namespace = path === null ? null : rootOf(path);
    if (namespace === null) observation = unknown();
    else {
      const { value } = await readMetadata('namespaces', namespace, caller, 64 * 1024);
      const parsed = NamespaceMetadataSchema.safeParse(value);
      const plan = parsed.success ? parsed.data.plan : null;
      const tier =
        plan === null || plan === undefined ? undefined : PLAN_TIERS.get(plan.toLowerCase());
      observation = { tier: tier ?? null, cachedAt: new Date() };
    }
  } catch {
    // Provider bodies and parser exceptions can contain secrets; never include them.
    logWarn('Namespace subscription metadata could not be read');
    observation = unknown();
  }
  remember(caller.sessionId, key, observation);
  return observation;
}
 
export function getNamespaceTierCacheMetrics(): {
  totalEntries: number;
  entriesBySession: Map<string, number>;
} {
  const entriesBySession = new Map<string, number>();
  let totalEntries = 0;
  for (const [sessionId, entries] of namespaceTierCache) {
    entriesBySession.set(sessionId, entries.size);
    totalEntries += entries.size;
  }
  return { totalEntries, entriesBySession };
}