All files / packages/sds-release-manager/src/services git-lfs-service.ts

94.81% Statements 183/193
91.82% Branches 146/159
100% Functions 21/21
95.67% Lines 177/185

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                                                                  44x 44x 55x 55x 2x   53x   42x 46x 46x             6x     36x                     32x 32x   1x   31x           3x     28x 28x 33x 1x   32x 32x 4x   28x   23x           179x         179x 179x 7x   172x           64x     64x 64x 64x 64x 64x           21x 21x 21x 5x 2x   3x     16x 11x 11x   16x 16x               39x   39x 1x       31x 31x     31x   31x 31x                   34x       1x   30x 1x     29x       21x     38x 14x   24x       24x 24x       24x 24x         4x   20x     21x   24x 24x     24x 24x     24x 24x 5x   19x 19x 24x 24x 4x     15x         15x       24x 24x                   1x   14x 2x     12x 3x       3x 3x                   1x   2x 1x       10x 10x       12x 15x 15x 12x               5x 5x 4x 4x 1x   3x   3x 3x                   5x           3x 3x 2x 2x 2x 3x 3x 2x   2x           53x 53x 49x   53x             53x 53x 53x               53x 53x       1x   52x 52x 157x 157x 105x     52x 52x 52x 1x   51x       51x           16x 16x 16x 1x   15x 13x 13x                         13x 1x     12x 12x     12x 12x 16x 16x 16x   16x     16x 12x 12x   1x     12x                   5x       7x     16x     7x     7x 7x 1x   6x 6x 1x   5x 5x         239x    
/**
 * Git LFS access over the Artifactory batch API.
 *
 * Hydrates (downloads) and uploads the V1 CSS LFS objects for the gitcore drop.
 * Auth is HTTP Basic sourced from the local `git credential` helper. The service
 * is deliberately secret-safe: credentials, action headers, signed URLs, and raw
 * HTTP response bodies are never logged or embedded in thrown errors.
 *
 * LFS terms used below: an *object* is the real file content, addressed by its
 * SHA-256 (*oid*); a *pointer* is the small text stub committed to git in its
 * place; the *batch API* negotiates per-object upload/download URLs.
 */
import { createHash } from 'node:crypto';
import { execa } from 'execa';
import { DEFAULT_GIT_LFS_BATCH_ENDPOINT, DEFAULT_GIT_LFS_CREDENTIAL_HOST } from '../config.js';
import type { Logger } from '../utils/logger.js';
 
export type GitLfsPointer = {
  oid: string;
  size: number;
};
 
type Credentials = {
  username: string;
  password: string;
};
 
type UploadObject = { oid: string; size: number; content: Buffer };
 
// Dedupe by oid and re-verify each object: oid must be the SHA-256 of its bytes
// and size must match. A repeated oid with different bytes is a hard conflict.
// Shared by uploadObjects and queryObjects so both enforce the same invariants.
function validateAndDeduplicateObjects(objects: UploadObject[]): Map<string, UploadObject> {
  const unique = new Map<string, UploadObject>();
  for (const object of objects) {
    const existing = unique.get(object.oid);
    if (existing && (existing.size !== object.size || !existing.content.equals(object.content))) {
      throw new Error(`Git LFS object conflict for ${object.oid}`);
    }
    if (!existing) unique.set(object.oid, object);
  }
  for (const object of unique.values()) {
    const oid = createHash('sha256').update(object.content).digest('hex');
    if (
      !/^[a-f0-9]{64}$/.test(object.oid) ||
      !Number.isSafeInteger(object.size) ||
      object.size < 0 ||
      object.content.length !== object.size ||
      oid !== object.oid
    ) {
      throw new Error('Invalid Git LFS upload object');
    }
  }
  return unique;
}
 
// Validate the batch response and index it by oid: one entry per requested
// object, matching oid + size, no per-object error. Parse failures and shape
// violations collapse to a generic message so no response body leaks.
async function parseBatchResponse(
  response: Response,
  requested: Map<string, UploadObject>,
): Promise<Map<string, Record<string, unknown>>> {
  let batch: unknown;
  try {
    batch = await response.json();
  } catch {
    throw new Error('Unexpected Git LFS batch response');
  }
  if (
    !isRecord(batch) ||
    (batch.transfer !== undefined && batch.transfer !== 'basic') ||
    !Array.isArray(batch.objects) ||
    batch.objects.length !== requested.size
  ) {
    throw new Error('Unexpected Git LFS batch response');
  }
 
  const responseObjects = new Map<string, Record<string, unknown>>();
  for (const object of batch.objects) {
    if (!isRecord(object) || typeof object.oid !== 'string' || responseObjects.has(object.oid)) {
      throw new Error('Unexpected Git LFS batch response');
    }
    const input = requested.get(object.oid);
    if (!input || object.size !== input.size || object.error) {
      throw new Error('Unexpected Git LFS batch response');
    }
    responseObjects.set(object.oid, object);
  }
  return responseObjects;
}
 
// Strictly parse the canonical 3-line LFS pointer (version / oid sha256 / size,
// trailing newline). Anything else throws.
export function parseLfsPointer(content: Buffer): GitLfsPointer {
  const match = content
    .toString('utf8')
    .match(
      /^version https:\/\/git-lfs\.github\.com\/spec\/v1\noid sha256:([a-f0-9]{64})\nsize (0|[1-9][0-9]*)\n$/,
    );
  const size = match ? Number(match[2]) : Number.NaN;
  if (!match || !Number.isSafeInteger(size)) {
    throw new Error('Invalid Git LFS pointer');
  }
  return { oid: match[1], size };
}
 
export class GitLfsService {
  // Caches hydrated objects by oid (keeping the declared size) so a repeated
  // pointer is downloaded once; callers get a defensive copy.
  private readonly cache = new Map<string, { size: number; content: Promise<Buffer> }>();
 
  constructor(
    private readonly logger: Logger,
    private readonly batchEndpoint = DEFAULT_GIT_LFS_BATCH_ENDPOINT,
    private readonly credentialHost = DEFAULT_GIT_LFS_CREDENTIAL_HOST,
    private readonly fetchFn: typeof fetch = fetch,
    private readonly execaFn: typeof execa = execa,
  ) {}
 
  // Download the object a pointer refers to, verifying its size + SHA-256.
  // Returns a defensive copy; a cached oid with a conflicting size is rejected.
  hydrate(pointerBytes: Buffer): Promise<Buffer> {
    const pointer = parseLfsPointer(pointerBytes);
    const cached = this.cache.get(pointer.oid);
    if (cached) {
      if (cached.size !== pointer.size) {
        return Promise.reject(new Error(`Git LFS size mismatch for ${pointer.oid}`));
      }
      return cached.content.then((content) => Buffer.from(content));
    }
 
    const hydration = this.download(pointer).catch((error: unknown) => {
      this.cache.delete(pointer.oid);
      throw error;
    });
    this.cache.set(pointer.oid, { size: pointer.size, content: hydration });
    return hydration.then((content) => Buffer.from(content));
  }
 
  // Upload the given objects, idempotently. The batch response's omitted upload
  // action means the server already has that object (skip it); otherwise PUT the
  // raw bytes and run any verify action. Uploads run concurrently but the result
  // lists stay in input order. Safe to re-run: already-present objects are skipped.
  async uploadObjects(objects: UploadObject[]): Promise<{ uploaded: string[]; alreadyPresent: string[] }> {
    const unique = validateAndDeduplicateObjects(objects);
 
    if (unique.size === 0) {
      return { uploaded: [], alreadyPresent: [] };
    }
 
    // Enforce HTTPS before any credential is attached to a request.
    const batchUrl = new URL(this.batchEndpoint);
    Iif (batchUrl.protocol !== 'https:') {
      throw new Error('Git LFS batch endpoint must use HTTPS');
    }
    const credentials = await this.credentials(batchUrl, this.credentialHost);
    let batchResponse: Response;
    try {
      batchResponse = await this.fetchFn(this.batchEndpoint, {
        method: 'POST',
        headers: {
          Accept: 'application/vnd.git-lfs+json',
          'Content-Type': 'application/vnd.git-lfs+json',
          Authorization: this.basicHeader(credentials),
        },
        body: JSON.stringify({
          operation: 'upload',
          transfers: ['basic'],
          objects: Array.from(unique.values(), ({ oid, size }) => ({ oid, size })),
        }),
      });
    } catch {
      throw new Error('Git LFS batch request failed');
    }
    if (!batchResponse.ok) {
      throw new Error(`Git LFS batch request failed with HTTP ${batchResponse.status}`);
    }
 
    const responseObjects = await parseBatchResponse(batchResponse, unique);
 
    // Validate one upload/verify action: must be an HTTPS URL with string-only
    // headers, else treated as absent/invalid.
    const actionDetails = (
      action: unknown,
    ): { url: URL; headers: Record<string, string> | undefined } | undefined => {
      if (action === undefined) {
        return undefined;
      }
      Iif (!isRecord(action) || typeof action.href !== 'string') {
        return undefined;
      }
      let url: URL;
      try {
        url = new URL(action.href);
      } catch {
        return undefined;
      }
      const headers = action.header;
      if (
        url.protocol !== 'https:' ||
        (headers !== undefined &&
          (!isRecord(headers) || !Object.values(headers).every((value) => typeof value === 'string')))
      ) {
        return undefined;
      }
      return { url, headers: headers as Record<string, string> | undefined };
    };
 
    const outcomes = await Promise.all(
      Array.from(unique.values(), async (requested): Promise<'uploaded' | 'alreadyPresent'> => {
        const object = responseObjects.get(requested.oid);
        Iif (!object) {
          throw new Error(`Unexpected Git LFS batch response for ${requested.oid}`);
        }
        const actions = object.actions;
        Iif (actions !== undefined && !isRecord(actions)) {
          throw new Error(`Unexpected Git LFS batch response for ${requested.oid}`);
        }
        const uploadAction = isRecord(actions) ? actions.upload : undefined;
        if (uploadAction === undefined) {
          return 'alreadyPresent';
        }
        const upload = actionDetails(uploadAction);
        const verifyAction = isRecord(actions) ? actions.verify : undefined;
        const verify = actionDetails(verifyAction);
        if (!upload || (verifyAction !== undefined && !verify)) {
          throw new Error(`Unexpected Git LFS batch response for ${requested.oid}`);
        }
 
        this.logger.step(`Upload Git LFS object ${requested.oid} (${requested.size} bytes)`);
        // Use the action's own headers when given; otherwise fetch credentials
        // scoped to the action URL (never reuse the batch host's credentials
        // cross-host). Mandatory content headers are set last so an action header
        // cannot override them.
        const uploadHeaders = upload.headers ?? {
          Authorization: this.basicHeader(await this.credentials(upload.url)),
        };
        let uploadResponse: Response;
        try {
          uploadResponse = await this.fetchFn(upload.url.href, {
            method: 'PUT',
            body: requested.content as unknown as BodyInit,
            headers: {
              ...uploadHeaders,
              'Content-Type': 'application/octet-stream',
              'Content-Length': String(requested.size),
            },
          });
        } catch {
          throw new Error('Git LFS upload failed');
        }
        if (uploadResponse.status < 200 || uploadResponse.status > 299) {
          throw new Error(`Git LFS upload failed with HTTP ${uploadResponse.status}`);
        }
 
        if (verify) {
          const verifyHeaders = verify.headers ?? {
            Authorization: this.basicHeader(await this.credentials(verify.url)),
          };
          let verifyResponse: Response;
          try {
            verifyResponse = await this.fetchFn(verify.url.href, {
              method: 'POST',
              headers: {
                Accept: 'application/vnd.git-lfs+json',
                'Content-Type': 'application/vnd.git-lfs+json',
                ...verifyHeaders,
              },
              body: JSON.stringify({ oid: requested.oid, size: requested.size }),
            });
          } catch {
            throw new Error('Git LFS verify failed');
          }
          if (!verifyResponse.ok) {
            throw new Error(`Git LFS verify failed with HTTP ${verifyResponse.status}`);
          }
        }
 
        this.logger.success(`Uploaded Git LFS object ${requested.oid} (${requested.size} bytes)`);
        return 'uploaded';
      }),
    );
    // Reassemble the uploaded / already-present lists in the original input order.
    const ordered = Array.from(unique.keys());
    const uploaded = ordered.filter((_, index) => outcomes[index] === 'uploaded');
    const alreadyPresent = ordered.filter((_, index) => outcomes[index] === 'alreadyPresent');
    return { uploaded, alreadyPresent };
  }
 
  // Read-only presence check used by dry-run: run the upload batch negotiation
  // (which tells us which objects already exist) but never PUT anything.
  async queryObjects(
    objects: UploadObject[],
  ): Promise<{ uploadRequired: string[]; alreadyPresent: string[] }> {
    const unique = validateAndDeduplicateObjects(objects);
    Iif (unique.size === 0) return { uploadRequired: [], alreadyPresent: [] };
    const batchUrl = new URL(this.batchEndpoint);
    if (batchUrl.protocol !== 'https:') {
      throw new Error('Git LFS batch endpoint must use HTTPS');
    }
    const credentials = await this.credentials(batchUrl, this.credentialHost);
    let response: Response;
    try {
      response = await this.fetchFn(this.batchEndpoint, {
        method: 'POST',
        headers: {
          Accept: 'application/vnd.git-lfs+json',
          'Content-Type': 'application/vnd.git-lfs+json',
          Authorization: this.basicHeader(credentials),
        },
        body: JSON.stringify({
          operation: 'upload',
          transfers: ['basic'],
          objects: Array.from(unique.values(), ({ oid, size }) => ({ oid, size })),
        }),
      });
    } catch {
      throw new Error('Git LFS batch request failed');
    }
    Iif (!response.ok) throw new Error(`Git LFS batch request failed with HTTP ${response.status}`);
    const responseObjects = await parseBatchResponse(response, unique);
    const uploadRequired: string[] = [];
    const alreadyPresent: string[] = [];
    for (const requested of unique.values()) {
      const object = responseObjects.get(requested.oid)!;
      if (isRecord(object.actions) && object.actions.upload !== undefined) uploadRequired.push(requested.oid);
      else alreadyPresent.push(requested.oid);
    }
    return { uploadRequired, alreadyPresent };
  }
 
  // Build the `git credential fill` query URL, optionally overriding the host
  // (used so the batch request authenticates against the configured LFS host).
  private credentialUrl(url: URL, hostOverride?: string): URL {
    const credentialUrl = new URL(url);
    if (hostOverride) {
      credentialUrl.host = hostOverride;
    }
    return credentialUrl;
  }
 
  // Resolve Basic credentials via the local `git credential` helper for the
  // given URL's protocol/host/path. On any failure, throw a host-only message —
  // never surface the helper's output.
  private async credentials(url: URL, hostOverride?: string): Promise<Credentials> {
    const credentialUrl = this.credentialUrl(url, hostOverride);
    const path = credentialUrl.pathname.replace(/^\//, '').replace(/\/objects\/batch\/?$/, '');
    const input = [
      `protocol=${credentialUrl.protocol.slice(0, -1)}`,
      `host=${credentialUrl.host}`,
      ...(path ? [`path=${path}`] : []),
      '',
      '',
    ].join('\n');
    let stdout: string;
    try {
      ({ stdout } = await this.execaFn('git', ['credential', 'fill'], {
        input,
      }));
    } catch {
      throw new Error(`Git LFS credential unavailable for ${credentialUrl.host}`);
    }
    const fields = new Map<string, string>();
    for (const line of stdout.split(/\r?\n/)) {
      const separator = line.indexOf('=');
      if (separator > 0) {
        fields.set(line.slice(0, separator), line.slice(separator + 1));
      }
    }
    const username = fields.get('username');
    const password = fields.get('password');
    if (!username || !password) {
      throw new Error(`Git LFS credential unavailable for ${credentialUrl.host}`);
    }
    return { username, password };
  }
 
  private basicHeader(credentials: Credentials): string {
    return `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
  }
 
  // Download path for one pointer: negotiate the batch download action, GET the
  // bytes, then verify length and SHA-256 against the pointer before returning.
  private async download(pointer: GitLfsPointer): Promise<Buffer> {
    this.logger.step(`Hydrate Git LFS object ${pointer.oid}`);
    const batchUrl = new URL(this.batchEndpoint);
    if (batchUrl.protocol !== 'https:') {
      throw new Error('Git LFS batch endpoint must use HTTPS');
    }
    const credentials = await this.credentials(batchUrl, this.credentialHost);
    const authorization = this.basicHeader(credentials);
    const batchResponse = await this.fetchFn(this.batchEndpoint, {
      method: 'POST',
      headers: {
        Accept: 'application/vnd.git-lfs+json',
        'Content-Type': 'application/vnd.git-lfs+json',
        Authorization: authorization,
      },
      body: JSON.stringify({
        operation: 'download',
        transfers: ['basic'],
        objects: [pointer],
      }),
    });
    if (!batchResponse.ok) {
      throw new Error(`Git LFS batch request failed with HTTP ${batchResponse.status}`);
    }
 
    const batch: unknown = await batchResponse.json();
    Iif (!isRecord(batch)) {
      throw new Error(`Unexpected Git LFS batch response for ${pointer.oid}`);
    }
    const objects = batch.objects;
    const object = Array.isArray(objects) && objects.length === 1 ? objects[0] : undefined;
    const actions = isRecord(object) && isRecord(object.actions) ? object.actions : undefined;
    const action = actions && isRecord(actions.download) ? actions.download : undefined;
    const actionHeaders = action?.header;
    const headersValid =
      actionHeaders === undefined ||
      (isRecord(actionHeaders) && Object.values(actionHeaders).every((value) => typeof value === 'string'));
    let actionUrl: URL | undefined;
    if (action && typeof action.href === 'string') {
      try {
        actionUrl = new URL(action.href);
      } catch {
        actionUrl = undefined;
      }
    }
    if (
      (batch.transfer !== undefined && batch.transfer !== 'basic') ||
      !isRecord(object) ||
      object.oid !== pointer.oid ||
      object.size !== pointer.size ||
      object.error ||
      !actionUrl ||
      actionUrl.protocol !== 'https:' ||
      !headersValid
    ) {
      throw new Error(`Unexpected Git LFS batch response for ${pointer.oid}`);
    }
 
    const downloadHeaders =
      actionHeaders === undefined
        ? { Authorization: this.basicHeader(await this.credentials(actionUrl)) }
        : (actionHeaders as Record<string, string>);
    const downloadResponse = await this.fetchFn(actionUrl.href, {
      headers: downloadHeaders,
    });
    Iif (!downloadResponse.ok) {
      throw new Error(`Git LFS download failed with HTTP ${downloadResponse.status}`);
    }
    const content = Buffer.from(await downloadResponse.arrayBuffer());
    if (content.length !== pointer.size) {
      throw new Error(`Git LFS size mismatch for ${pointer.oid}`);
    }
    const oid = createHash('sha256').update(content).digest('hex');
    if (oid !== pointer.oid) {
      throw new Error(`Git LFS SHA-256 mismatch for ${pointer.oid}`);
    }
    this.logger.success(`Hydrated Git LFS object ${pointer.oid} (${pointer.size} bytes)`);
    return content;
  }
}
 
function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}