-
Notifications
You must be signed in to change notification settings - Fork 3
test(cli): cover the auth flow + auth-gated init step #372
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
coderdan
wants to merge
2
commits into
main
Choose a base branch
from
cli-auth-tests
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
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
| import { makeTokenResult } from '../../../tests/helpers/auth-mock.js' | ||
|
|
||
| // Mock only `@cipherstash/auth` here — we want the real `resolveExistingAuth` | ||
| // under test, with a stub for the NAPI strategy it constructs. | ||
| const napi = vi.hoisted(() => ({ | ||
| getToken: vi.fn(), | ||
| })) | ||
| vi.mock('@cipherstash/auth', () => ({ | ||
| default: { | ||
| AutoStrategy: { detect: () => ({ getToken: napi.getToken }) }, | ||
| AccessKeyStrategy: { create: vi.fn() }, | ||
| OAuthStrategy: { fromProfile: vi.fn() }, | ||
| beginDeviceCodeFlow: vi.fn(), | ||
| bindClientDevice: vi.fn(), | ||
| }, | ||
| })) | ||
|
|
||
| const { resolveExistingAuth } = await import('../strategy.js') | ||
|
|
||
| describe('resolveExistingAuth', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| }) | ||
|
|
||
| it('maps a known issuer to the matching region label', async () => { | ||
| napi.getToken.mockResolvedValueOnce(makeTokenResult()) | ||
|
|
||
| const result = await resolveExistingAuth() | ||
|
|
||
| expect(result).toEqual({ | ||
| workspace: 'WS_TEST', | ||
| regionLabel: 'ap-southeast-2 (Sydney, Australia)', | ||
| }) | ||
| }) | ||
|
|
||
| it('returns regionLabel="unknown" when the issuer matches no region', async () => { | ||
| napi.getToken.mockResolvedValueOnce( | ||
| makeTokenResult({ issuer: 'https://nowhere.example.com' }), | ||
| ) | ||
|
|
||
| const result = await resolveExistingAuth() | ||
|
|
||
| expect(result).toEqual({ | ||
| workspace: 'WS_TEST', | ||
| regionLabel: 'unknown', | ||
| }) | ||
| }) | ||
|
|
||
| // The catch in resolveExistingAuth is a deliberate "treat any auth error as | ||
| // not authenticated" — this is a regression net for the day someone | ||
| // narrows it. The codes come from `@cipherstash/auth/index.d.ts:7-22`. | ||
| it.each([ | ||
| 'NOT_AUTHENTICATED', | ||
| 'EXPIRED_TOKEN', | ||
| 'INVALID_ACCESS_KEY', | ||
| 'MISSING_WORKSPACE_CRN', | ||
| 'REQUEST_ERROR', | ||
| ])('returns undefined when getToken rejects with %s', async (code) => { | ||
| napi.getToken.mockRejectedValueOnce( | ||
| Object.assign(new Error(code), { code }), | ||
| ) | ||
|
|
||
| const result = await resolveExistingAuth() | ||
|
|
||
| expect(result).toBeUndefined() | ||
| }) | ||
| }) | ||
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,44 @@ | ||
| /** | ||
| * Thin wrapper around `@cipherstash/auth` strategy detection. | ||
| * | ||
| * Centralises the NAPI-default-export shape and the swallow-on-failure | ||
| * pattern used to decide whether the user is already authenticated. Other | ||
| * commands that need an "are we logged in?" check can reuse | ||
| * `resolveExistingAuth` instead of duplicating the try/catch + region-label | ||
| * lookup. Tests can mock this single module rather than the NAPI library. | ||
| */ | ||
|
|
||
| import auth from '@cipherstash/auth' | ||
| import { regions } from '../commands/auth/login.js' | ||
|
|
||
| const { AutoStrategy } = auth | ||
|
|
||
| export interface ExistingAuth { | ||
| workspace: string | ||
| regionLabel: string | ||
| } | ||
|
|
||
| /** Construct a fresh `AutoStrategy` — exposed for tests that need to assert on detection. */ | ||
| export function getAuthStrategy() { | ||
| return AutoStrategy.detect() | ||
| } | ||
|
|
||
| /** | ||
| * Resolve the currently-authenticated workspace if a valid token is | ||
| * available, or `undefined` if not. Errors from `getToken()` (no creds, | ||
| * expired tokens, network issues) are swallowed and treated as "not | ||
| * authenticated" — the caller decides what to do next (typically: prompt | ||
| * the user to log in). | ||
| */ | ||
| export async function resolveExistingAuth(): Promise<ExistingAuth | undefined> { | ||
| try { | ||
| const result = await getAuthStrategy().getToken() | ||
| const regionEntry = regions.find((r) => result.issuer.includes(r.value)) | ||
| return { | ||
| workspace: result.workspaceId, | ||
| regionLabel: regionEntry?.label ?? 'unknown', | ||
| } | ||
| } catch { | ||
| return undefined | ||
| } | ||
| } |
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,171 @@ | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' | ||
| import { | ||
| makeAuthError, | ||
| makeDeviceCodeResult, | ||
| } from '../../../../tests/helpers/auth-mock.js' | ||
| import { messages } from '../../../messages.js' | ||
|
|
||
| // Hoisted stubs — `vi.mock` factories run before module imports, but we need | ||
| // the same fn instances inside the factory and the test bodies so tests can | ||
| // reconfigure behaviour per-case via mockResolvedValueOnce / mockRejectedValueOnce. | ||
| const stubs = vi.hoisted(() => ({ | ||
| beginDeviceCodeFlow: vi.fn(), | ||
| bindClientDevice: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@cipherstash/auth', () => ({ | ||
| default: { | ||
| beginDeviceCodeFlow: stubs.beginDeviceCodeFlow, | ||
| bindClientDevice: stubs.bindClientDevice, | ||
| // The login module destructures only the two functions above, but we | ||
| // include the strategy classes so any side-importer doesn't blow up. | ||
| AutoStrategy: { detect: vi.fn() }, | ||
| AccessKeyStrategy: { create: vi.fn() }, | ||
| OAuthStrategy: { fromProfile: vi.fn() }, | ||
| }, | ||
| })) | ||
|
|
||
| const clack = vi.hoisted(() => ({ | ||
| select: vi.fn(), | ||
| isCancel: vi.fn(), | ||
| cancel: vi.fn(), | ||
| log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), success: vi.fn() }, | ||
| spinnerStart: vi.fn(), | ||
| spinnerStop: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@clack/prompts', () => ({ | ||
| select: clack.select, | ||
| isCancel: clack.isCancel, | ||
| cancel: clack.cancel, | ||
| log: clack.log, | ||
| spinner: () => ({ start: clack.spinnerStart, stop: clack.spinnerStop }), | ||
| })) | ||
|
|
||
| // Import after mocks are registered. | ||
| const { bindDevice, login, selectRegion } = await import('../login.js') | ||
|
|
||
| describe('selectRegion', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| }) | ||
|
|
||
| it('returns the chosen region when not cancelled', async () => { | ||
| clack.select.mockResolvedValueOnce('us-east-1.aws') | ||
| clack.isCancel.mockReturnValueOnce(false) | ||
|
|
||
| const result = await selectRegion() | ||
|
|
||
| expect(result).toBe('us-east-1.aws') | ||
| expect(clack.cancel).not.toHaveBeenCalled() | ||
| // Sanity: select was called with the message handle, not a literal. | ||
| expect(clack.select).toHaveBeenCalledWith( | ||
| expect.objectContaining({ message: messages.auth.selectRegion }), | ||
| ) | ||
| }) | ||
|
|
||
| it('cancels via clack and exits 0 when the prompt is cancelled', async () => { | ||
| const exitSpy = vi | ||
| .spyOn(process, 'exit') | ||
| .mockImplementation((() => undefined) as never) | ||
| const cancelSym = Symbol('clack:cancel') | ||
| clack.select.mockResolvedValueOnce(cancelSym) | ||
| clack.isCancel.mockReturnValueOnce(true) | ||
|
|
||
| await selectRegion() | ||
|
|
||
| expect(clack.cancel).toHaveBeenCalledWith(messages.auth.cancelled) | ||
| expect(exitSpy).toHaveBeenCalledWith(0) | ||
| exitSpy.mockRestore() | ||
| }) | ||
| }) | ||
|
|
||
| describe('login', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| }) | ||
|
|
||
| it('runs the full device-code sequence on the happy path', async () => { | ||
| const dcr = makeDeviceCodeResult() | ||
| stubs.beginDeviceCodeFlow.mockResolvedValueOnce(dcr) | ||
|
|
||
| await login('us-east-1.aws', 'drizzle') | ||
|
|
||
| expect(stubs.beginDeviceCodeFlow).toHaveBeenCalledWith( | ||
| 'us-east-1.aws', | ||
| // Hardcoded 'cli' OAuth client id — anything else is INVALID_CLIENT. | ||
| 'cli', | ||
| ) | ||
| expect(dcr.openInBrowser).toHaveBeenCalledTimes(1) | ||
| expect(clack.spinnerStart).toHaveBeenCalledTimes(1) | ||
| expect(dcr.pollForToken).toHaveBeenCalledTimes(1) | ||
| expect(clack.spinnerStop).toHaveBeenCalledWith('Authenticated!') | ||
| }) | ||
|
|
||
| it('warns when the browser cannot be opened', async () => { | ||
| const dcr = makeDeviceCodeResult({ openInBrowser: vi.fn(() => false) }) | ||
| stubs.beginDeviceCodeFlow.mockResolvedValueOnce(dcr) | ||
|
|
||
| await login('eu-west-1.aws', undefined) | ||
|
|
||
| expect(clack.log.warn).toHaveBeenCalledWith( | ||
| expect.stringContaining('Could not open browser'), | ||
| ) | ||
| }) | ||
|
|
||
| it.each(['EXPIRED_TOKEN', 'ACCESS_DENIED', 'REQUEST_ERROR', 'SERVER_ERROR'])( | ||
| 'propagates AuthError(%s) from pollForToken without stopping the spinner', | ||
| async (code) => { | ||
| const dcr = makeDeviceCodeResult({ | ||
| // biome-ignore lint/suspicious/noExplicitAny: cast keeps the narrow AuthErrorCode union accessible to it.each | ||
| pollForToken: vi.fn().mockRejectedValueOnce(makeAuthError(code as any)), | ||
| }) | ||
| stubs.beginDeviceCodeFlow.mockResolvedValueOnce(dcr) | ||
|
|
||
| await expect(login('us-east-1.aws', undefined)).rejects.toMatchObject({ | ||
| code, | ||
| }) | ||
| expect(clack.spinnerStart).toHaveBeenCalledTimes(1) | ||
| expect(clack.spinnerStop).not.toHaveBeenCalled() | ||
| }, | ||
| ) | ||
| }) | ||
|
|
||
| describe('bindDevice', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| vi.restoreAllMocks() | ||
| }) | ||
|
|
||
| it('stops the spinner with success when bindClientDevice resolves', async () => { | ||
| stubs.bindClientDevice.mockResolvedValueOnce(undefined) | ||
|
|
||
| await bindDevice() | ||
|
|
||
| expect(stubs.bindClientDevice).toHaveBeenCalledTimes(1) | ||
| expect(clack.spinnerStop).toHaveBeenCalledWith( | ||
| expect.stringContaining('bound'), | ||
| ) | ||
| expect(clack.log.error).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('logs the error and exits 1 on bindClientDevice failure', async () => { | ||
| const exitSpy = vi | ||
| .spyOn(process, 'exit') | ||
| .mockImplementation((() => undefined) as never) | ||
| stubs.bindClientDevice.mockRejectedValueOnce( | ||
| makeAuthError('ACCESS_DENIED', 'no permission'), | ||
| ) | ||
|
|
||
| await bindDevice() | ||
|
|
||
| expect(clack.spinnerStop).toHaveBeenCalledWith( | ||
| expect.stringContaining('Failed to bind'), | ||
| ) | ||
| expect(clack.log.error).toHaveBeenCalledWith('no permission') | ||
| expect(exitSpy).toHaveBeenCalledWith(1) | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use the shared AuthError fixture instead of ad-hoc error objects.
This suite already uses shared fixtures; keep error fixtures consistent too to avoid shape drift in auth tests.
Proposed patch
As per coding guidelines, “When testing authentication flows… Use
tests/helpers/auth-mock.tsforTokenResult,DeviceCodeResult, andAuthErrorfixtures in auth unit tests.”Also applies to: 60-62
🤖 Prompt for AI Agents