Repository navigation
fix(auth): update auth stack and remove token logging #455
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
Merged
Merged
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
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 |
|---|---|---|
| @@ -1,5 +1,4 @@ | ||
| import { describe, it, expect, vi, beforeEach } from 'vitest' | ||
| import { createTestDb } from '../helpers/assistant-workspace' | ||
| import { createAuth } from '../../src/auth' | ||
| import { DatabaseSync } from 'node:sqlite' | ||
| import type { Database } from 'bun:sqlite' | ||
|
|
@@ -120,8 +119,36 @@ describe('createAuth', () => { | |
| } | ||
| }) | ||
|
|
||
| it('rejects a session cookie immediately after its session row is deleted', async () => { | ||
| const db = createAuthDatabase() | ||
| const auth = createAuth(db) | ||
|
|
||
| try { | ||
| const signUpResponse = await auth.handler(new Request('http://localhost:5173/api/auth/sign-up/email', { | ||
| method: 'POST', | ||
| headers: { 'content-type': 'application/json', origin: 'http://localhost:5173' }, | ||
| body: JSON.stringify({ email: '[email protected]', password: 'test-password', name: 'Revoked' }), | ||
| })) | ||
| expect(signUpResponse.status).toBe(200) | ||
|
|
||
| const setCookies = signUpResponse.headers.getSetCookie() | ||
| expect(setCookies.length).toBeGreaterThan(0) | ||
| const headers = new Headers({ cookie: setCookies.map((cookie) => cookie.split(';')[0]).join('; ') }) | ||
|
|
||
| const session = await auth.api.getSession({ headers }) | ||
| expect(session?.user.email).toBe('[email protected]') | ||
|
|
||
| db.prepare('DELETE FROM "session" WHERE "userId" = ?').run(session!.user.id) | ||
| expect(db.prepare('SELECT COUNT(*) AS count FROM "session"').get()).toEqual({ count: 0 }) | ||
|
|
||
| expect(await auth.api.getSession({ headers })).toBeNull() | ||
| } finally { | ||
| db.close() | ||
| } | ||
| }, 30000) | ||
|
|
||
| it('creates an auth instance without social providers and responds to requests', async () => { | ||
| const db = createTestDb() | ||
| const db = createAuthDatabase() | ||
| const auth = createAuth(db) | ||
|
|
||
| expect(typeof auth.api.getSession).toBe('function') | ||
|
|
@@ -141,7 +168,7 @@ describe('createAuth', () => { | |
| ENV.AUTH.DISCORD_CLIENT_ID = 'discord-id' | ||
| ENV.AUTH.DISCORD_CLIENT_SECRET = 'discord-secret' | ||
|
|
||
| const db = createTestDb() | ||
| const db = createAuthDatabase() | ||
| const auth = createAuth(db) | ||
|
|
||
| expect(typeof auth.api.getSession).toBe('function') | ||
|
|
@@ -157,7 +184,7 @@ describe('createAuth', () => { | |
| ENV.AUTH.GOOGLE_CLIENT_SECRET = 'google-secret' | ||
| ENV.AUTH.DISCORD_CLIENT_ID = 'discord-id' | ||
|
|
||
| const db = createTestDb() | ||
| const db = createAuthDatabase() | ||
| const auth = createAuth(db) | ||
|
|
||
| const res = await auth.handler(new Request('http://localhost/api/auth/ok')) | ||
|
|
@@ -171,7 +198,7 @@ describe('createAuth', () => { | |
| ENV.SERVER.PORT = 4321 | ||
| ENV.AUTH.SECURE_COOKIES = true | ||
|
|
||
| const db = createTestDb() | ||
| const db = createAuthDatabase() | ||
| const auth = createAuth(db) | ||
|
|
||
| const res = await auth.handler(new Request('http://localhost/api/auth/ok')) | ||
|
|
@@ -183,7 +210,7 @@ describe('createAuth', () => { | |
| it('uses the first trusted origin as the base URL', async () => { | ||
| ENV.AUTH.TRUSTED_ORIGINS = ' http://example.test ,http://localhost:5003' | ||
|
|
||
| const db = createTestDb() | ||
| const db = createAuthDatabase() | ||
| const auth = createAuth(db) | ||
|
|
||
| const res = await auth.handler(new Request('http://example.test/api/auth/ok')) | ||
|
|
||
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 |
|---|---|---|
|
|
@@ -72,6 +72,17 @@ function insertCredentialAccount(db: ReturnType<typeof createTestDb>, id: string | |
| ).run(id, userId, 'credential', userId, password, Date.now(), Date.now()) | ||
| } | ||
|
|
||
| function insertSession(db: ReturnType<typeof createTestDb>, id: string, userId: string, token: string): void { | ||
| db.prepare( | ||
| 'INSERT INTO "session" (id, expiresAt, token, createdAt, updatedAt, userId) VALUES (?, ?, ?, ?, ?, ?)' | ||
| ).run(id, Date.now() + 86_400_000, token, Date.now(), Date.now(), userId) | ||
| } | ||
|
|
||
| function listSessionIds(db: ReturnType<typeof createTestDb>, userId: string): string[] { | ||
| const rows = db.prepare('SELECT id FROM "session" WHERE "userId" = ? ORDER BY id').all(userId) as { id: string }[] | ||
| return rows.map((row) => row.id) | ||
| } | ||
|
|
||
| function createSession(): Session { | ||
| return { | ||
| session: { | ||
|
|
@@ -127,7 +138,7 @@ describe('createAuthRoutes', () => { | |
| expect(await res.text()).toBe('created') | ||
| }) | ||
|
|
||
| it('logs sign-in responses when a set-cookie header is present', async () => { | ||
| it('does not log sign-in response headers', async () => { | ||
| const handler = vi.fn(async () => new Response('ok', { | ||
| status: 200, | ||
| headers: { 'set-cookie': 'opencode.session=abc; Path=/; HttpOnly' }, | ||
|
|
@@ -136,30 +147,6 @@ describe('createAuthRoutes', () => { | |
|
|
||
| await app.fetch(new Request('http://localhost/api/auth/sign-in/email', { method: 'POST', body: '{}' })) | ||
|
|
||
| expect(mockLoggerInfo).toHaveBeenCalledWith(expect.stringContaining('Sign-in response')) | ||
| expect(mockLoggerInfo).toHaveBeenCalledWith(expect.stringContaining('present')) | ||
| expect(mockLoggerDebug).toHaveBeenCalledWith(expect.stringContaining('Set-Cookie header')) | ||
| }) | ||
|
|
||
| it('logs sign-in responses when no set-cookie header is present', async () => { | ||
| const handler = vi.fn(async () => new Response('unauthorized', { status: 401 })) | ||
| const app = createAuthRoutes({ handler } as unknown as AuthInstance) | ||
|
|
||
| await app.fetch(new Request('http://localhost/api/auth/sign-in/email', { method: 'POST', body: '{}' })) | ||
|
|
||
| expect(mockLoggerInfo).toHaveBeenCalledWith(expect.stringContaining('missing')) | ||
| expect(mockLoggerDebug).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('does not log for non sign-in paths', async () => { | ||
| const handler = vi.fn(async () => new Response('ok', { | ||
| status: 200, | ||
| headers: { 'set-cookie': 'opencode.session=abc' }, | ||
| })) | ||
| const app = createAuthRoutes({ handler } as unknown as AuthInstance) | ||
|
|
||
| await app.fetch(new Request('http://localhost/api/auth/get-session')) | ||
|
|
||
| expect(mockLoggerInfo).not.toHaveBeenCalled() | ||
| expect(mockLoggerDebug).not.toHaveBeenCalled() | ||
| }) | ||
|
|
@@ -204,6 +191,7 @@ describe('syncAdminFromEnv', () => { | |
| ENV.AUTH.ADMIN_PASSWORD = 'admin-password' | ||
| insertUser(db, 'user-1', '[email protected]') | ||
| insertCredentialAccount(db, 'account-1', 'user-1', 'old-hash') | ||
| insertSession(db, 'session-1', 'user-1', 'token-1') | ||
| const auth = { api: { signUpEmail } } as unknown as AuthInstance | ||
|
|
||
| await syncAdminFromEnv(auth, db) | ||
|
|
@@ -212,6 +200,19 @@ describe('syncAdminFromEnv', () => { | |
| expect(hashPasswordMock).not.toHaveBeenCalled() | ||
| const account = db.prepare('SELECT password FROM "account" WHERE "userId" = ?').get('user-1') as { password: string } | ||
| expect(account.password).toBe('old-hash') | ||
| expect(listSessionIds(db, 'user-1')).toEqual(['session-1']) | ||
| }) | ||
|
|
||
| it('finds the existing admin user when ADMIN_EMAIL differs only by case', async () => { | ||
| ENV.AUTH.ADMIN_EMAIL = '[email protected]' | ||
| ENV.AUTH.ADMIN_PASSWORD = 'admin-password' | ||
| insertUser(db, 'user-1', '[email protected]') | ||
| const auth = { api: { signUpEmail } } as unknown as AuthInstance | ||
|
|
||
| await syncAdminFromEnv(auth, db) | ||
|
|
||
| expect(signUpEmail).not.toHaveBeenCalled() | ||
| expect(db.prepare('SELECT COUNT(*) AS count FROM "user"').get()).toEqual({ count: 1 }) | ||
| }) | ||
|
|
||
| it('resets the credential account password for an existing user', async () => { | ||
|
|
@@ -232,6 +233,39 @@ describe('syncAdminFromEnv', () => { | |
| expect(mockLoggerWarn).toHaveBeenCalledWith(expect.stringContaining('ADMIN_PASSWORD_RESET')) | ||
| }) | ||
|
|
||
| it('revokes the existing sessions of the admin whose password was reset', async () => { | ||
| ENV.AUTH.ADMIN_EMAIL = '[email protected]' | ||
| ENV.AUTH.ADMIN_PASSWORD = 'new-password' | ||
| ENV.AUTH.ADMIN_PASSWORD_RESET = true | ||
| insertUser(db, 'user-1', '[email protected]') | ||
| insertUser(db, 'user-2', '[email protected]') | ||
| insertCredentialAccount(db, 'account-1', 'user-1', 'old-hash') | ||
| insertSession(db, 'session-1', 'user-1', 'token-1') | ||
| insertSession(db, 'session-2', 'user-1', 'token-2') | ||
| insertSession(db, 'session-3', 'user-2', 'token-3') | ||
| const auth = { api: { signUpEmail } } as unknown as AuthInstance | ||
|
|
||
| await syncAdminFromEnv(auth, db) | ||
|
|
||
| expect(listSessionIds(db, 'user-1')).toEqual([]) | ||
| expect(listSessionIds(db, 'user-2')).toEqual(['session-3']) | ||
| }) | ||
|
|
||
| it('rolls back the password reset when revoking the sessions fails', async () => { | ||
| ENV.AUTH.ADMIN_EMAIL = '[email protected]' | ||
| ENV.AUTH.ADMIN_PASSWORD = 'new-password' | ||
| ENV.AUTH.ADMIN_PASSWORD_RESET = true | ||
| insertUser(db, 'user-1', '[email protected]') | ||
| insertCredentialAccount(db, 'account-1', 'user-1', 'old-hash') | ||
| db.exec('DROP TABLE "session"') | ||
| const auth = { api: { signUpEmail } } as unknown as AuthInstance | ||
|
|
||
| await expect(syncAdminFromEnv(auth, db)).rejects.toThrow() | ||
|
|
||
| const account = db.prepare('SELECT password FROM "account" WHERE "userId" = ?').get('user-1') as { password: string } | ||
| expect(account.password).toBe('old-hash') | ||
| }) | ||
|
|
||
| it('creates a new admin user when none exists', async () => { | ||
| ENV.AUTH.ADMIN_EMAIL = '[email protected]' | ||
| ENV.AUTH.ADMIN_PASSWORD = 'admin-password' | ||
|
|
||
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
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.
Uh oh!
There was an error while loading. Please reload this page.