Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions docs/contributing/testing-principles.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,22 @@ when that makes a single test longer and more assertion-heavy.
- Console output is guarded globally
(`packages/worker/src/test-support/console-spies.ts`, wired via `setupFiles`):
unexpected `console.error`/`console.warn` calls fail the test, and
`console.info`/`console.debug` are silenced. When code under test
intentionally logs, import the exported `consoleError`/`consoleWarn` spies,
call `.mockImplementation(() => {})` in the test, and assert on the calls
(prefer the stable first-argument tag plus `expect.any(Error)`; do not pin
long prose). Keep test output free of stray logging.
`console.info`/`console.debug` are silenced. Never silence blindly — a blanket
`.mockImplementation(() => {})` can hide a real regression. Instead:
- When the log is part of the tested contract, import the exported
`consoleError`/`consoleWarn` spies, call `.mockImplementation(() => {})`,
and assert on the calls (prefer the stable first-argument tag plus
`expect.any(Error)`; do not pin long prose). Assert the call count too when
it is deterministic.
- When the log is incidental to the behavior under test, use
`silenceExpectedConsoleWarns([...])` / `silenceExpectedConsoleErrors([...])`
(same module) with the exact expected message tags, or
`silenceIncidentalRuntimeWarnings()`
(`packages/worker/src/test-support/incidental-runtime-warnings.ts`) for the
bundler/registry-runtime noise set. Anything outside the allowlist still
fails the test.

Keep test output free of stray logging.

## Examples

Expand Down
7 changes: 7 additions & 0 deletions packages/worker/src/app/email/cloudflare-email.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@ test('sendCloudflareEmail delivers through the mock API and handles configuratio
ok: false,
error: 'Failed to fetch',
})
// Exactly the one expected warning; anything else the mock swallowed
// would be a regression hidden by the opt-in above.
expect(consoleWarn).toHaveBeenCalledTimes(1)
expect(consoleWarn).toHaveBeenCalledWith(
'cloudflare-email-api-request-failed',
expect.any(Error),
Expand Down Expand Up @@ -171,4 +174,8 @@ test('sendCloudflareEmail delivers through the mock API and handles configuratio
},
),
).rejects.toThrow('not valid JSON')
// The parse failure throws before any operator warning, so the silenced
// consoleWarn must not have picked up anything new.
expect(consoleWarn).toHaveBeenCalledTimes(1)
expect(consoleInfo).toHaveBeenCalledTimes(1)
})
29 changes: 27 additions & 2 deletions packages/worker/src/app/handlers/account-profile.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,17 @@ import { createAccountProfileApiHandler } from './account-profile.ts'

// The handler fires `void logAuditEvent(...)` without awaiting it; those
// promises can resolve after the test ends and leak `audit-event` lines into
// the runner output once the console spies are restored. Stub the audit sink.
// the runner output once the console spies are restored. Route the sink to a
// spy so the expected audit events are asserted instead of silently dropped.
const auditSpy = vi.hoisted(() => ({
logAuditEvent: vi.fn(async () => undefined),
}))

vi.mock('#app/audit-log.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('#app/audit-log.ts')>()
return {
...actual,
logAuditEvent: async () => undefined,
logAuditEvent: (...args: Array<unknown>) => auditSpy.logAuditEvent(...args),
}
})

Expand Down Expand Up @@ -206,6 +211,8 @@ test('account profile API returns email and username for the signed-in user', as
username: 'current-user',
displayName: 'current-user',
})
// Reads are not audited.
expect(auditSpy.logAuditEvent).not.toHaveBeenCalled()
})

test('account profile API updates username for the signed-in user', async () => {
Expand Down Expand Up @@ -233,6 +240,14 @@ test('account profile API updates username for the signed-in user', async () =>
displayName: 'next_user',
})
expect(testDb.users.get(1)?.username).toBe('next_user')
expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'account',
action: 'update_username',
result: 'success',
}),
)
})

test('account profile API rejects invalid or duplicate usernames', async () => {
Expand Down Expand Up @@ -285,4 +300,14 @@ test('account profile API rejects invalid or duplicate usernames', async () => {
error: 'Username already registered.',
})
expect(testDb.users.get(1)?.username).toBe('current-user')
// Only the duplicate attempt is audited; validation rejections are not.
expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'account',
action: 'update_username',
result: 'failure',
reason: 'username_exists',
}),
)
})
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,17 @@ import { createAccountResendVerificationHandler } from './account-resend-verific

// The handler fires `void logAuditEvent(...)` without awaiting it; those
// promises can resolve after the test ends and leak `audit-event` lines into
// the runner output once the console spies are restored. Stub the audit sink.
// the runner output once the console spies are restored. Route the sink to a
// spy so the expected audit events are asserted instead of silently dropped.
const auditSpy = vi.hoisted(() => ({
logAuditEvent: vi.fn(async () => undefined),
}))

vi.mock('#app/audit-log.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('#app/audit-log.ts')>()
return {
...actual,
logAuditEvent: async () => undefined,
logAuditEvent: (...args: Array<unknown>) => auditSpy.logAuditEvent(...args),
}
})

Expand Down Expand Up @@ -209,6 +214,24 @@ test('resend verification issues a fresh token for unverified accounts and rate-
})
// No new token is created for rate-limited requests.
expect(testDb.state.verificationInserts).toBe(3)
// Three successful resends plus the rate-limited attempt are audited.
expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(4)
expect(auditSpy.logAuditEvent).toHaveBeenNthCalledWith(
3,
expect.objectContaining({
category: 'auth',
action: 'email_verification_resend',
result: 'success',
}),
)
expect(auditSpy.logAuditEvent).toHaveBeenNthCalledWith(
4,
expect.objectContaining({
category: 'auth',
action: 'email_verification_resend',
result: 'rate_limited',
}),
)
})

test('resend verification rejects already-verified accounts', async () => {
Expand Down Expand Up @@ -270,5 +293,14 @@ test('resend verification surfaces send failures without pretending success', as
'cloudflare-email-api-failed',
expect.any(String),
)
expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'auth',
action: 'email_verification_resend',
result: 'failure',
reason: 'send_failed',
}),
)
vi.unstubAllGlobals()
})
47 changes: 45 additions & 2 deletions packages/worker/src/app/handlers/auth-handler.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,17 @@ import {

// The auth handler fires `void logAuditEvent(...)` without awaiting it; those
// promises can resolve after the test ends and leak `audit-event` lines into
// the runner output once the console spies are restored. Stub the audit sink.
// the runner output once the console spies are restored. Route the sink to a
// spy so the expected audit events are asserted instead of silently dropped.
const auditSpy = vi.hoisted(() => ({
logAuditEvent: vi.fn(async () => undefined),
}))

vi.mock('#app/audit-log.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('#app/audit-log.ts')>()
return {
...actual,
logAuditEvent: async () => undefined,
logAuditEvent: (...args: Array<unknown>) => auditSpy.logAuditEvent(...args),
}
})

Expand Down Expand Up @@ -370,6 +375,14 @@ test('auth handler login and signup workflow', async () => {
expect(await unknownUserLoginResponse.json()).toEqual({
error: 'Invalid email or password.',
})
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'auth',
action: 'login',
result: 'failure',
reason: 'invalid_credentials',
}),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Add toHaveBeenCalledTimes assertions to match the pattern in other handler tests.

All four assertion blocks use only toHaveBeenCalledWith without toHaveBeenCalledTimes. This means extra unexpected audit events would pass silently — the exact regression class this PR aims to prevent. The account-profile and account-resend-verification tests correctly pair both assertions; this file should follow suit.

For the signup-success case (lines 416-430), the expected count is 2 (signup + invite_use). For the login-failure (378-385), login-success (535-542), and signup-failure (582-588) cases, the expected count is 1 each.

🔧 Proposed additions
 // Lines 378-385 — login failure
+expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'login',
 		result: 'failure',
 		reason: 'invalid_credentials',
 	}),
 )

 // Lines 416-430 — signup success + invite_use
+expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(2)
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'signup',
 		result: 'success',
 		email: 'invited@example.com',
 	}),
 )
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'invite_use',
 		result: 'success',
 	}),
 )

 // Lines 535-542 — login success
+expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'login',
 		result: 'success',
 		email,
 	}),
 )

 // Lines 582-588 — signup failure
+expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'signup',
 		result: 'failure',
 	}),
 )

Also applies to: 416-430, 535-542, 582-588

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/worker/src/app/handlers/auth-handler.node.test.ts` around lines 378
- 385, Add toHaveBeenCalledTimes assertions alongside each
auditSpy.logAuditEvent toHaveBeenCalledWith block in the affected auth-handler
tests: expect 1 call for login-failure, login-success, and signup-failure, and 2
calls for signup-success. Keep the count assertions adjacent to their
corresponding expectations.


const blockedSignupResponse = await productionContext.request({
email: 'new@example.com',
Expand Down Expand Up @@ -400,6 +413,21 @@ test('auth handler login and signup workflow', async () => {
})
expect(productionContext.testDb.users.has('invited@example.com')).toBe(true)
expect(productionContext.testDb.invites.get('PROD-INVITE')?.use_count).toBe(1)
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'auth',
action: 'signup',
result: 'success',
email: 'invited@example.com',
}),
)
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'auth',
action: 'invite_use',
result: 'success',
}),
)

const weakPasswordSignupResponse = await signupContext.request({
email: 'weak@example.com',
Expand Down Expand Up @@ -504,6 +532,14 @@ test('auth handler login and signup workflow', async () => {
const loginCookie = loginResponse.headers.get('Set-Cookie') ?? ''
expect(loginCookie).toContain('kody_session=')
expect(loginCookie).toContain('Max-Age=604800')
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'auth',
action: 'login',
result: 'success',
email,
}),
)

const rememberMeResponse = await productionContext.request({
email,
Expand Down Expand Up @@ -543,6 +579,13 @@ test('signup fails when the default user role cannot be assigned', async () => {
expect(response.headers.get('Set-Cookie')).toBeNull()
// The created user row is rolled back so signup can be retried.
expect(context.testDb.users.has('roleless@example.com')).toBe(false)
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'auth',
action: 'signup',
result: 'failure',
}),
)
})

test('signup rolls back when the verification email cannot be sent', async () => {
Expand Down
25 changes: 23 additions & 2 deletions packages/worker/src/app/handlers/auth-provider.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,17 @@ import { createPasswordHash } from '@kody-internal/shared/password-hash.ts'

// The handlers fire `void logAuditEvent(...)` without awaiting it; those
// promises can resolve after the test ends and leak `audit-event` lines into
// the runner output once the console spies are restored. Stub the audit sink.
// the runner output once the console spies are restored. Route the sink to a
// spy so the expected audit events are asserted instead of silently dropped.
const auditSpy = vi.hoisted(() => ({
logAuditEvent: vi.fn(async () => undefined),
}))

vi.mock('#app/audit-log.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('#app/audit-log.ts')>()
return {
...actual,
logAuditEvent: async () => undefined,
logAuditEvent: (...args: Array<unknown>) => auditSpy.logAuditEvent(...args),
}
})

Expand Down Expand Up @@ -312,6 +317,14 @@ test('github sign-in creates a verified account, then signs it back in', async (
)
.get() as Record<string, unknown>
expect(connection.user_id).toBe(user.id)
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'auth',
action: 'oauth_signup',
result: 'success',
reason: 'provider=github',
}),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Add toHaveBeenCalledTimes(1) to both OAuth audit assertions.

Same gap as auth-handler.node.test.ts — without count assertions, extra unexpected audit events go undetected, which contradicts the PR's objective.

🔧 Proposed additions
 // Lines 320-327 — oauth_signup
+expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'oauth_signup',
 		result: 'success',
 		reason: 'provider=github',
 	}),
 )

 // Lines 354-361 — oauth_login
+expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1)
 expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
 	expect.objectContaining({
 		category: 'auth',
 		action: 'oauth_login',
 		result: 'success',
 		reason: 'provider=github',
 	}),
 )

Also applies to: 354-361

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/worker/src/app/handlers/auth-provider.node.test.ts` around lines 320
- 327, Add expect(auditSpy.logAuditEvent).toHaveBeenCalledTimes(1) alongside
both OAuth audit assertions in the relevant tests, including the assertions
around the oauth_signup success event and the second OAuth case, to ensure
exactly one audit event is emitted.


// A second sign-in with the same provider identity reuses the account.
const secondStart = await startProviderFlow(
Expand All @@ -338,6 +351,14 @@ test('github sign-in creates a verified account, then signs it back in', async (
.prepare(`SELECT COUNT(*) AS count FROM users`)
.get() as { count: number }
expect(userCount.count).toBe(1)
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'auth',
action: 'oauth_login',
result: 'success',
reason: 'provider=github',
}),
)
})

test('google sign-in links a matching verified email to the existing account', async () => {
Expand Down
45 changes: 43 additions & 2 deletions packages/worker/src/app/handlers/two-factor.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,17 @@ import { createPasswordHash } from '@kody-internal/shared/password-hash.ts'

// The handlers fire `void logAuditEvent(...)` without awaiting it; those
// promises can resolve after the test ends and leak `audit-event` lines into
// the runner output once the console spies are restored. Stub the audit sink.
// the runner output once the console spies are restored. Route the sink to a
// spy so the expected audit events are asserted instead of silently dropped.
const auditSpy = vi.hoisted(() => ({
logAuditEvent: vi.fn(async () => undefined),
}))

vi.mock('#app/audit-log.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('#app/audit-log.ts')>()
return {
...actual,
logAuditEvent: async () => undefined,
logAuditEvent: (...args: Array<unknown>) => auditSpy.logAuditEvent(...args),
}
})

Expand Down Expand Up @@ -313,6 +318,28 @@ test('two-factor setup requires authentication and a valid code before activatin
type: '2fa',
secret: setupPayload.secret,
})
// Setup start, the rejected confirm, and the successful enable are audited.
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'account',
action: 'two_factor_setup_start',
result: 'success',
}),
)
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'account',
action: 'two_factor_enable',
result: 'failure',
}),
)
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'account',
action: 'two_factor_enable',
result: 'success',
}),
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
})

test('cancelling a pending setup removes it without touching active 2fa', async () => {
Expand Down Expand Up @@ -548,6 +575,20 @@ test('disabling 2fa requires a valid current code and clears stale pending rows'
.get() as { count: number }
).count,
).toBe(0)
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'account',
action: 'two_factor_disable',
result: 'failure',
}),
)
expect(auditSpy.logAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
category: 'account',
action: 'two_factor_disable',
result: 'success',
}),
)
})

test('setup and confirm are rejected while 2fa is already enabled', async () => {
Expand Down
Loading
Loading