fix(auth): trim and validate stored api key in resolveApiKey#120
fix(auth): trim and validate stored api key in resolveApiKey#120mrdailey99 merged 2 commits intodevelopfrom
Conversation
The stored key was returned as-is with no trim() or prefix check, unlike the env var path which had both. A key with trailing whitespace (e.g. from manual editing) or a pre-pv_k_ format key would be sent to the Quality Hub API unchanged, causing a 401 and triggering local_fallback even when a valid key exists. Tests added for both cases. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
There was a problem hiding this comment.
Pull request overview
This PR aligns the “stored credentials” API key path with the environment variable path by trimming whitespace and enforcing the pv_k_ prefix in resolveApiKey(), preventing invalid keys from being sent to the Quality Hub API and incorrectly triggering fallback behavior.
Changes:
- Trim whitespace from the stored
api_keybefore use. - Validate that the stored key starts with
pv_k_, otherwise returnnull. - Add unit tests covering whitespace trimming and invalid stored-key prefix handling.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
src/services/auth/credentials.ts |
Trims and validates stored API key in resolveApiKey() before returning it. |
test/unit/services/auth/credentials.test.ts |
Adds tests for trimming stored keys and rejecting stored keys without the required prefix. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
src/services/auth/credentials.ts
Outdated
| const storedKey = readStoredCredentials()?.api_key.trim() ?? null; | ||
| if (storedKey?.startsWith(KEY_PREFIX)) return storedKey; |
There was a problem hiding this comment.
readStoredCredentials() returns parsed JSON without runtime validation, so api_key may be missing or non-string for manually edited/corrupt files. Calling .trim() directly on readStoredCredentials()?.api_key can throw a TypeError when api_key is undefined/null. Consider guarding with ?.api_key?.trim() and/or a typeof api_key === 'string' check before trimming, and returning null for invalid shapes (optionally add a test for missing/non-string api_key).
Use typeof check before calling .trim() so a missing or non-string api_key field in a manually edited credentials.json cannot throw a TypeError. Added tests for missing-field and numeric api_key cases. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The stored key was returned as-is with no trim() or prefix check, unlike the env var path which had both. A key with trailing whitespace (e.g. from manual editing) or a pre-pv_k_ format key would be sent to the Quality Hub API unchanged, causing a 401 and triggering local_fallback even when a valid key exists. Tests added for both cases.