Repository navigation
feat(auth): validate stored bearer tokens on demand #49
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
b-pm
wants to merge
13
commits into
beeper:main
Choose a base branch
from
b-pm:feat/auth-status-check-48
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
0778db8
feat(auth): add live bearer validation helper
b-pm 632d353
feat(auth): add live check to auth status
b-pm fa5049d
test(auth): cover live bearer validation
b-pm e46327b
docs(auth): document live token validation
b-pm 6280364
docs(auth): document live token validation
b-pm 7a05608
docs(auth): document live token validation
b-pm 1d089dd
fix(auth): render live token check in human output
b-pm 78d2fbd
fix(auth): redact bearer-bearing errors and honor status timeout
b-pm 360830b
fix(auth): redact bearer-bearing errors and honor status timeout
b-pm f43e635
test(auth): cover secret-safe failures and timeout propagation
b-pm a824686
test(auth): exercise actual malformed bearer newline without leaking …
b-pm 11bd692
fix(auth): validate bearer against protected accounts endpoint
b-pm d419873
test(auth): reject stale bearers despite public setup 200 response
b-pm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| export type AccessTokenCheck = { | ||
| state: 'valid' | 'invalid' | 'unknown' | 'missing' | ||
| status?: number | ||
| error?: string | ||
| } | ||
|
|
||
| /** Translate the CLI's documented --timeout syntax into a safe timer duration. */ | ||
| export function parseTimeoutMs(value: string | undefined): number { | ||
| if (value === undefined) return 2_000 | ||
| const match = value.trim().match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/i) | ||
| if (!match) throw new Error('Invalid --timeout. Use a positive duration such as 500ms, 30s, 2m, or 1h.') | ||
| const unit = (match[2] ?? 'ms').toLowerCase() | ||
| const multiplier = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000 }[unit as 'ms' | 's' | 'm' | 'h'] | ||
| const milliseconds = Math.round(Number(match[1]) * multiplier) | ||
| if (!Number.isSafeInteger(milliseconds) || milliseconds < 1 || milliseconds > 2_147_483_647) { | ||
| throw new Error('Invalid --timeout. Duration must be between 1ms and 2147483647ms.') | ||
| } | ||
| return milliseconds | ||
| } | ||
|
|
||
| export async function checkAccessToken( | ||
| baseURL: string, | ||
| token: string | undefined, | ||
| options: { | ||
| timeoutMs?: number | ||
| fetcher?: typeof fetch | ||
| } = {}, | ||
| ): Promise<AccessTokenCheck> { | ||
| if (!token) return { state: 'missing' } | ||
|
|
||
| const fetcher = options.fetcher ?? fetch | ||
| const controller = new AbortController() | ||
| const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 2_000) | ||
|
|
||
| try { | ||
| // /v1/app/setup is public and may return 200 during needs-login; accounts is bearer-protected. | ||
| // We only inspect the status code, never log or retain the response body. | ||
| const response = await fetcher(new URL('/v1/accounts', baseURL), { | ||
| headers: { authorization: `Bearer ${token}` }, | ||
| signal: controller.signal, | ||
| }) | ||
|
|
||
| if (response.status === 401 || response.status === 403) { | ||
| return { state: 'invalid', status: response.status } | ||
| } | ||
| if (response.ok) return { state: 'valid', status: response.status } | ||
|
|
||
| return { state: 'unknown', status: response.status } | ||
| } catch { | ||
| // Fetch implementations can echo the Authorization header (including the bearer) in errors. | ||
| // Never return a raw exception from a request that included a credential. | ||
| return { state: 'unknown', error: 'Token check failed; verify target connectivity and token configuration.' } | ||
| } finally { | ||
| clearTimeout(timeout) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| import { describe, expect, it } from 'bun:test' | ||
| import { checkAccessToken, parseTimeoutMs } from '../src/lib/auth-health.js' | ||
|
|
||
| describe('checkAccessToken', () => { | ||
|
|
||
| it('checks a bearer-protected endpoint, not the public setup endpoint', async () => { | ||
| let requestedPath = '' | ||
| const result = await checkAccessToken('http://127.0.0.1:23373', 'stale-bearer', { | ||
| fetcher: async input => { | ||
| requestedPath = new URL(String(input)).pathname | ||
| return new Response('{}', { status: requestedPath === '/v1/app/setup' ? 200 : 401 }) | ||
| }, | ||
| }) | ||
| expect(requestedPath).toBe('/v1/accounts') | ||
| expect(result).toEqual({ state: 'invalid', status: 401 }) | ||
| expect(JSON.stringify(result)).not.toContain('stale-bearer') | ||
| }) | ||
|
|
||
| it('reports missing without making a request', async () => { | ||
| let calls = 0 | ||
| const result = await checkAccessToken('http://127.0.0.1:23373', undefined, { | ||
| fetcher: async () => { | ||
| calls += 1 | ||
| return new Response(null, { status: 200 }) | ||
| }, | ||
| }) | ||
|
|
||
| expect(result).toEqual({ state: 'missing' }) | ||
| expect(calls).toBe(0) | ||
| }) | ||
|
|
||
| it('reports valid when the target accepts the bearer', async () => { | ||
| let authHeader: string | null = null | ||
| const result = await checkAccessToken('http://127.0.0.1:23373', 'secret-token', { | ||
| fetcher: async (_input, init) => { | ||
| authHeader = new Headers(init?.headers).get('authorization') | ||
| return new Response('{}', { status: 200 }) | ||
| }, | ||
| }) | ||
|
|
||
| expect(result).toEqual({ state: 'valid', status: 200 }) | ||
| expect(authHeader).toBe('Bearer secret-token') | ||
| }) | ||
|
|
||
| it('reports invalid on authentication rejection without exposing the token', async () => { | ||
| const result = await checkAccessToken('http://127.0.0.1:23373', 'secret-token', { | ||
| fetcher: async () => new Response('Invalid token', { status: 401 }), | ||
| }) | ||
|
|
||
| expect(result).toEqual({ state: 'invalid', status: 401 }) | ||
| expect(JSON.stringify(result)).not.toContain('secret-token') | ||
| }) | ||
|
|
||
| it('reports unknown for non-auth failures', async () => { | ||
| const statusResult = await checkAccessToken('http://127.0.0.1:23373', 'token', { | ||
| fetcher: async () => new Response('server error', { status: 500 }), | ||
| }) | ||
| expect(statusResult).toEqual({ state: 'unknown', status: 500 }) | ||
|
|
||
| const networkResult = await checkAccessToken('http://127.0.0.1:23373', 'token', { | ||
| fetcher: async () => { | ||
| throw new Error('connection refused') | ||
| }, | ||
| }) | ||
| expect(networkResult).toEqual({ state: 'unknown', error: 'Token check failed; verify target connectivity and token configuration.' }) | ||
| }) | ||
| }) | ||
|
|
||
| describe('auth status credential/timeout regression', () => { | ||
| it('never returns malformed bearer data from fetch errors', async () => { | ||
| const token = 'line-one\nline-two-secret' | ||
| const result = await checkAccessToken('http://127.0.0.1:23373', token, { | ||
| fetcher: async () => { | ||
| throw new TypeError(`Header authorization has invalid value: 'Bearer ${token}'`) | ||
| }, | ||
| }) | ||
| expect(result.state).toBe('unknown') | ||
| expect(JSON.stringify(result)).not.toContain(token) | ||
| expect(JSON.stringify(result)).not.toContain('line-two-secret') | ||
| expect(JSON.stringify(result)).not.toContain('Bearer') | ||
| }) | ||
|
|
||
| it('parses the global timeout flag, including documented minute/hour units', () => { | ||
| expect(parseTimeoutMs(undefined)).toBe(2_000) | ||
| expect(parseTimeoutMs('500ms')).toBe(500) | ||
| expect(parseTimeoutMs('30s')).toBe(30_000) | ||
| expect(parseTimeoutMs('2m')).toBe(120_000) | ||
| expect(parseTimeoutMs('1h')).toBe(3_600_000) | ||
| expect(() => parseTimeoutMs('0ms')).toThrow() | ||
| expect(() => parseTimeoutMs('abc')).toThrow() | ||
| expect(() => parseTimeoutMs('999999999h')).toThrow() | ||
| }) | ||
|
|
||
| it('honors the supplied small timeout rather than the default two seconds', async () => { | ||
| const result = await checkAccessToken('http://127.0.0.1:23373', 'secret-token', { | ||
| timeoutMs: 5, | ||
| fetcher: async (_url, init) => new Promise<Response>((_resolve, reject) => { | ||
| if (init?.signal?.aborted) return reject(new Error('aborted')) | ||
| init?.signal?.addEventListener('abort', () => reject(new Error('aborted')), { once: true }) | ||
| }), | ||
| }) | ||
| expect(result.state).toBe('unknown') | ||
| expect(JSON.stringify(result)).not.toContain('secret-token') | ||
| }) | ||
| }) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.