|
1 | | -import { afterEach, describe, expect, it } from 'vitest'; |
| 1 | +import { afterEach, describe, expect, it, vi } from 'vitest'; |
2 | 2 | import { |
3 | 3 | DRY_RUN_API_KEY, |
4 | 4 | DRY_RUN_BANNER, |
| 5 | + assertValidApiKeyHeaderValue, |
5 | 6 | assertValidEndpointUrl, |
6 | 7 | emitDryRunBanner, |
7 | 8 | makeHttpClient, |
@@ -331,6 +332,58 @@ describe('makeHttpClient — real path (regression)', () => { |
331 | 332 | // assertValidEndpointUrl — endpoint syntax guard (NOT an SSRF guard) |
332 | 333 | // --------------------------------------------------------------------------- |
333 | 334 |
|
| 335 | +describe('makeHttpClient - API key validation', () => { |
| 336 | + it.each([ |
| 337 | + ['newline', 'sk-user-abc\ndef'], |
| 338 | + ['carriage return', 'sk-user-abc\rdef'], |
| 339 | + ['smart dash', 'sk-user-abc\u2013def'], |
| 340 | + ['smart quote', 'sk-user-\u201cabc\u201d'], |
| 341 | + ['emoji', 'sk-user-abc\u{1f600}'], |
| 342 | + ['whitespace-only', ' '], |
| 343 | + ])('rejects a malformed configured API key with %s before fetch/retry', (_label, apiKey) => { |
| 344 | + const fetchImpl = vi.fn(); |
| 345 | + let caught: unknown; |
| 346 | + try { |
| 347 | + makeHttpClient( |
| 348 | + { profile: 'default', output: 'json', debug: false, dryRun: false }, |
| 349 | + { |
| 350 | + env: { TESTSPRITE_API_KEY: apiKey } as NodeJS.ProcessEnv, |
| 351 | + credentialsPath: NO_CREDS_PATH, |
| 352 | + fetchImpl, |
| 353 | + }, |
| 354 | + ); |
| 355 | + } catch (err) { |
| 356 | + caught = err; |
| 357 | + } |
| 358 | + expect(fetchImpl).not.toHaveBeenCalled(); |
| 359 | + expect(caught).toBeInstanceOf(ApiError); |
| 360 | + const apiErr = caught as ApiError; |
| 361 | + expect(apiErr.code).toBe('VALIDATION_ERROR'); |
| 362 | + expect(apiErr.exitCode).toBe(5); |
| 363 | + expect(apiErr.nextAction).toContain('api-key'); |
| 364 | + }); |
| 365 | +}); |
| 366 | + |
| 367 | +describe('assertValidApiKeyHeaderValue', () => { |
| 368 | + it('accepts a normal ASCII API key value', () => { |
| 369 | + expect(() => assertValidApiKeyHeaderValue('sk-user-abc-def_123')).not.toThrow(); |
| 370 | + }); |
| 371 | + |
| 372 | + it('throws a VALIDATION_ERROR (exit 5) for a key that cannot be sent as x-api-key', () => { |
| 373 | + let caught: unknown; |
| 374 | + try { |
| 375 | + assertValidApiKeyHeaderValue('sk-user-abc\u2013def'); |
| 376 | + } catch (err) { |
| 377 | + caught = err; |
| 378 | + } |
| 379 | + expect(caught).toBeInstanceOf(ApiError); |
| 380 | + const apiErr = caught as ApiError; |
| 381 | + expect(apiErr.code).toBe('VALIDATION_ERROR'); |
| 382 | + expect(apiErr.exitCode).toBe(5); |
| 383 | + expect(apiErr.nextAction).toContain('api-key'); |
| 384 | + }); |
| 385 | +}); |
| 386 | + |
334 | 387 | describe('assertValidEndpointUrl', () => { |
335 | 388 | it('accepts http(s) URLs, including private / localhost hosts (self-hosted, dev, mock)', () => { |
336 | 389 | for (const url of [ |
|
0 commit comments