From e06708f48f847bdac64f17015d0f10bd8b6cc703 Mon Sep 17 00:00:00 2001 From: Daniel Naab Date: Fri, 4 Dec 2026 12:09:36 -0600 Subject: [PATCH] fix(auth): treat only approved users as signed in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A valid session cookie was treated as authorization. The request-access flow issues a temporary session to unapproved GitHub users, and revoked users may hold old cookies; sessionReader set `user` for all of them, and the approval check lived only in requireAuth(accessStore) on /admin, /new, /settings and /forms. Routes gated on `user` presence or ownership — POST /:owner/:slug/fork (and edit/authoring on the fork), compare comments, and the project-scoped /:owner/:slug/forms router (mounted without an access store) — admitted pending, revoked and no-entry users. sessionReader(accessStore) now resolves access once per request: only an approved entry sets `user`. Pending/no-entry sessions are exposed as `requester`, read only by the request-access pages; revoked cookies are cleared. ALLOWED_USERS logins with no row (cookie minted on another deployment) are treated as approved. requireAuth() no longer takes a store; the unused accessStore deps on the forms and settings routers are removed. Threat model updated. Pot-Run: 7979 --- catalog/architecture/threat-model.md | 4 + src/entrypoints/app/middleware/auth.ts | 68 ++-- src/entrypoints/app/routes/auth/index.tsx | 6 +- src/entrypoints/app/routes/forms/index.tsx | 4 +- src/entrypoints/app/routes/settings/index.tsx | 4 +- src/entrypoints/app/server.tsx | 8 +- test/access-control.test.ts | 2 +- test/admin-routes.test.ts | 4 +- test/auth-approval-gate.test.ts | 300 ++++++++++++++++++ test/auth-middleware.test.ts | 171 ++++++++-- test/auth-routes.test.ts | 16 +- test/entrypoints/settings-variants.test.ts | 10 +- test/server.test.ts | 54 +++- 13 files changed, 580 insertions(+), 71 deletions(-) create mode 100644 test/auth-approval-gate.test.ts diff --git a/catalog/architecture/threat-model.md b/catalog/architecture/threat-model.md index c1d437c10..4c7726342 100644 --- a/catalog/architecture/threat-model.md +++ b/catalog/architecture/threat-model.md @@ -173,6 +173,7 @@ See [system overview](system-overview.md) and [data model](data-model.md) for fu - **Privilege escalation** -- users gaining authoring access without proper GitHub repo permissions. - **Open redirect** -- attacker crafts sign-in URL with `returnTo` pointing to external site. - **Session fixation** -- attacker sets a known session cookie before user authenticates. +- **Authentication mistaken for authorization** -- a valid session cookie held by a GitHub user who is *not* approved. The request-access flow deliberately issues a temporary session to unapproved requesters so the request page knows who they are, and revoked users may still hold cookies minted before revocation. Until 2026-12-04 the session reader set `user` for any decryptable cookie and the approval check lived only in `requireAuth(accessStore)` on `/admin/*`, `/new`, `/settings` and top-level `/forms`. Routes that checked only `user` presence or ownership — `POST /:owner/:slug/fork` (then edit/authoring routes on the fork, which run paid LLM pipelines), `POST /:owner/:slug/compare/:range/comments`, and the project-scoped `/:owner/:slug/forms/*` router (mounted without an access store) — admitted pending, revoked and no-entry users. **Mitigations:** - Session cookies use AES-GCM encryption with PBKDF2-derived key (100k iterations, SHA-256) and random 12-byte IV per session. Cookie attributes: `HttpOnly`, `SameSite=Lax`, 7-day max-age. `Secure` flag set in production. @@ -180,6 +181,7 @@ See [system overview](system-overview.md) and [data model](data-model.md) for fu - OAuth state parameter carries `returnTo` path as JSON. Authorization codes are exchanged server-to-server with client secret. - Authorization checks verify GitHub repo write/admin permission via collaborator API -- authentication alone is insufficient. - Public routes include `/` (landing), `/:owner` (profile), `/:owner/:slug` (project overview), `/:owner/:slug/{tree,blob,commits,commit}/*` (git browsing), `/catalog/*`, `/health`, `/static/*`, and `/git/*`. Routes that mutate state (`/new`, `/:owner/:slug/settings`, `/:owner/:slug/fork`) require auth. Ownership is additionally enforced at the service layer for mutations — see "Hono application to ProjectService" above. +- Access is resolved centrally, once per request, by `sessionReader(accessStore)`: after decrypting the cookie it looks up the user's access entry. Only an `approved` entry populates `c.get('user')`, so every route that checks `user` is approval-gated by default. A pending or no-entry session is exposed only as `c.get('requester')`, which only the request-access auth pages read; everywhere else the requester appears signed out. A revoked user's cookie is deleted. The one exception for a missing entry is a login in `ALLOWED_USERS`: those are approved at sign-in, but each deployment has its own access database, so a cookie minted on another branch can arrive before the row exists; the env allowlist is treated as authoritative for them. `ALLOWED_EMAIL_DOMAINS` users cannot be re-verified without an OAuth token, so on a deployment with no row they appear signed out until they sign in there. `requireAuth()` now only checks for an approved `user`. Covered by `test/auth-approval-gate.test.ts`, `test/auth-middleware.test.ts` and `test/server.test.ts`. - Sign-out is POST-only (form submission), preventing GET-based CSRF. SameSite=Lax prevents cross-origin POST cookie sending. - Session cookie is only created after successful OAuth callback with a fresh random IV, so pre-set cookies are simply invalid. @@ -269,6 +271,7 @@ See [system overview](system-overview.md) and [data model](data-model.md) for fu | Command injection in deploy | Webhook-Deploy | Low | Critical | HMAC verification, quoted variables, Nix packaging | Partially mitigated | | Repository compromise | Webhook-Deploy | Low | Critical | Branch protection, required reviews | Partially mitigated | | Session hijacking | Browser-Hono Auth | Medium | High | AES-GCM encrypted cookies, HttpOnly, SameSite=Lax | Mitigated | +| Unapproved/revoked session used as authorization | Browser-Hono Auth | High | High | Central approval check in `sessionReader`; requesters exposed only to auth pages | Mitigated | | Open redirect via returnTo | Browser-Hono Auth | Low | Medium | None -- returnTo not validated | Unmitigated | | Prompt injection via form labels | Hono-LLM (form shaping) | Medium | Medium | Output validation, Zod schema enforcement | Partially mitigated | | FormSpec metadata leakage | Hono-LLM (form shaping) | Certain | Low | HTTPS, LLM provider data policies | Accepted | @@ -302,6 +305,7 @@ See [system overview](system-overview.md) and [data model](data-model.md) for fu | 2026-04-17 | Story 4 review + PR #54 | Updated shaping route references for unified `/edit/save` (single commit endpoint, `parentSha` optimistic-concurrency guard). Added refinement-loop abuse and refinement-feedback prompt-injection threats surfaced in story-4 code review. | | 2026-04-18 | Story 7 | Added PDF output trust boundary for completed PDF download. Threats: unauthorized access, field mapping tampering. Both mitigated. | | 2026-05-02 | PR #122 | Updated secrets management references from sops-nix to AWS Secrets Manager. Updated residual risk for secrets to reflect IAM role fetch pattern and .env files on disk. | +| 2026-12-04 | fix/auth-require-approved | Authentication boundary: documented a live hole where any valid session cookie (pending requesters, revoked users, users with no access entry) passed `user`-presence and ownership checks on fork, compare comments and project-scoped form routes. Fixed centrally: `sessionReader(accessStore)` sets `user` only for approved users and exposes others as `requester` for the request-access pages; revoked cookies are cleared. | ## Sources diff --git a/src/entrypoints/app/middleware/auth.ts b/src/entrypoints/app/middleware/auth.ts index 5bba98a51..293de7882 100644 --- a/src/entrypoints/app/middleware/auth.ts +++ b/src/entrypoints/app/middleware/auth.ts @@ -10,7 +10,14 @@ import { resolveUrl } from '../../../shared/base-path' declare module 'hono' { interface ContextVariableMap { + /** Signed-in user whose access is approved. Null for anyone else. */ user: SessionUser | null + /** + * Signed-in GitHub user who is NOT approved (pending request or no + * access entry yet). Only the auth pages that serve the request-access + * flow should read this; everywhere else such a user is signed out. + */ + requester?: SessionUser | null } } @@ -21,29 +28,59 @@ function parseAdminUsers(): string[] { .filter(Boolean) } -export function sessionReader() { +function parseAllowedUsers(): string[] { + return (process.env.ALLOWED_USERS ?? 'danielnaab') + .split(',') + .map((u) => u.trim()) + .filter(Boolean) +} + +/** + * Decrypts the session cookie and resolves the user's access once per + * request, so that `c.get('user')` is only ever an *approved* user. + * + * A valid cookie is not authorization: the request-access flow issues a + * temporary session to unapproved GitHub users, and revoked users may hold + * old cookies. Those sessions are exposed as `requester` (pending / no + * entry) or dropped entirely with the cookie cleared (revoked). + */ +export function sessionReader(accessStore: AccessStore) { return createMiddleware(async (c, next) => { + c.set('user', null) + c.set('requester', null) + const secret = process.env.SESSION_SECRET - if (!secret) { - c.set('user', null) + const cookie = secret ? getCookie(c, COOKIE_NAME) : undefined + const session = + secret && cookie ? await decryptSession(cookie, secret) : null + if (!session) { await next() return } - const cookie = getCookie(c, COOKIE_NAME) - if (!cookie) { - c.set('user', null) - await next() - return + const entry = accessStore.get(session.login) + if (entry?.status === 'approved') { + c.set('user', session) + } else if (entry?.status === 'revoked') { + deleteCookie(c, COOKIE_NAME) + } else if (!entry && parseAllowedUsers().includes(session.login)) { + // ALLOWED_USERS are approved at sign-in, but each deployment has its + // own access database, so a cookie minted elsewhere can arrive before + // the row exists. The env allowlist is authoritative for these logins. + c.set('user', session) + } else { + c.set('requester', session) } - const user = await decryptSession(cookie, secret) - c.set('user', user) await next() }) } -export function requireAuth(accessStore?: AccessStore) { +/** + * Redirects to sign-in unless the request carries an approved user. + * Approval is resolved by `sessionReader`, which must run first. + */ +export function requireAuth() { return createMiddleware(async (c, next) => { const user = c.get('user') if (!user) { @@ -54,15 +91,6 @@ export function requireAuth(accessStore?: AccessStore) { return c.redirect(`${resolveUrl('/auth/signin')}?returnTo=${returnTo}`) } - if (accessStore) { - const entry = accessStore.get(user.login) - if (entry && entry.status !== 'approved') { - deleteCookie(c, COOKIE_NAME) - const returnTo = encodeURIComponent(c.req.path) - return c.redirect(`${resolveUrl('/auth/signin')}?returnTo=${returnTo}`) - } - } - await next() }) } diff --git a/src/entrypoints/app/routes/auth/index.tsx b/src/entrypoints/app/routes/auth/index.tsx index 01fc00fd2..b79b7336e 100644 --- a/src/entrypoints/app/routes/auth/index.tsx +++ b/src/entrypoints/app/routes/auth/index.tsx @@ -237,8 +237,10 @@ export function createAuthRoutes( }) // GET /auth/request-access — shows "request access" page + // Requesters (signed in but not approved) are only visible here; the + // session reader treats them as signed out everywhere else. auth.get('/request-access', (c) => { - const user = c.get('user') + const user = c.get('requester') ?? c.get('user') return c.html( @@ -248,7 +250,7 @@ export function createAuthRoutes( // POST /auth/request-access — records the request auth.post('/request-access', async (c) => { - const user = c.get('user') + const user = c.get('requester') ?? c.get('user') if (!user) { return c.redirect(resolveUrl('/auth/signin')) } diff --git a/src/entrypoints/app/routes/forms/index.tsx b/src/entrypoints/app/routes/forms/index.tsx index 8175c3ddb..edb15908f 100644 --- a/src/entrypoints/app/routes/forms/index.tsx +++ b/src/entrypoints/app/routes/forms/index.tsx @@ -8,7 +8,6 @@ import { FormPageView } from '../../../../design-system/components/flex-form-pag import { FormReview } from '../../../../design-system/components/flex-form-review' import { Layout } from '../../../../design-system/components/flex-layout' import { PreviewBanner } from '../../../../design-system/components/flex-preview-banner' -import type { AccessStore } from '../../../../services/auth' import type { DataCollectionSpec } from '../../../../services/data-collection' import type { FieldMapping } from '../../../../services/form-documents' import { fillPdf } from '../../../../services/form-documents' @@ -82,7 +81,6 @@ interface FormRouterDeps { specId: string, specVersion: string, ) => Promise - accessStore?: AccessStore /** Resolves owner/slug from route context. Routes use * project-scoped URL shapes (/:owner/:slug/forms/...). */ resolveOwnerSlug?: (c: Context) => { owner: string; slug: string } @@ -182,7 +180,7 @@ export function createFormRouter(deps: FormRouterDeps) { } // All form routes require authentication - forms.use('*', requireAuth(deps.accessStore)) + forms.use('*', requireAuth()) // Forms index — only in legacy (non-project-scoped) mode. // In project-scoped mode, '/' is the form landing page. diff --git a/src/entrypoints/app/routes/settings/index.tsx b/src/entrypoints/app/routes/settings/index.tsx index 7710ad8e4..bc12b0970 100644 --- a/src/entrypoints/app/routes/settings/index.tsx +++ b/src/entrypoints/app/routes/settings/index.tsx @@ -1,6 +1,5 @@ import { Hono } from 'hono' import { Layout } from '../../../../design-system/components/flex-layout' -import type { AccessStore } from '../../../../services/auth' import type { TaskRegistries, VariantPreferencesService, @@ -13,12 +12,11 @@ import { VariantPickerPage } from './components' export interface SettingsRoutesDeps { preferences: VariantPreferencesService registries: TaskRegistries - accessStore?: AccessStore } export function createSettingsRoutes(deps: SettingsRoutesDeps): Hono { const app = new Hono() - app.use('*', requireAuth(deps.accessStore)) + app.use('*', requireAuth()) app.get('/variants', (c) => { const user = c.get('user') diff --git a/src/entrypoints/app/server.tsx b/src/entrypoints/app/server.tsx index cfeeb87af..029f1b1d3 100644 --- a/src/entrypoints/app/server.tsx +++ b/src/entrypoints/app/server.tsx @@ -201,7 +201,7 @@ async function findProjectBySpecId( } // Apply session reader globally -app.use('*', sessionReader()) +app.use('*', sessionReader(accessStore)) // USWDS icon sprite app.get('/static/sprite.svg', async (c) => { @@ -297,7 +297,7 @@ app.use( app.route('/auth', createAuthRoutes(userStore, accessStore, { activityStore })) // Mount admin routes (requireAdmin is applied inside createAdminRoutes) -app.use('/admin/*', requireAuth(accessStore)) +app.use('/admin/*', requireAuth()) app.route('/admin', createAdminRoutes(accessStore, userStore)) // Mount settings routes (variant picker) @@ -306,7 +306,6 @@ app.route( createSettingsRoutes({ preferences: variantPreferences, registries, - accessStore, }), ) @@ -325,7 +324,7 @@ app.get('/health', (c) => { }) // New project routes (requires auth) -app.use('/new', requireAuth(accessStore)) +app.use('/new', requireAuth()) // Resolve the callout payload the /new page needs to describe the user's // currently-selected extraction variant. Factored out because both GET and @@ -610,7 +609,6 @@ app.route( if (!buf) return null return JSON.parse(buf.toString()) }, - accessStore, resolveProjectForSpec: findProjectBySpecId, getProjectName: (slug) => projectService.getProjectName(slug), }), diff --git a/test/access-control.test.ts b/test/access-control.test.ts index 342c413d5..a63a2b507 100644 --- a/test/access-control.test.ts +++ b/test/access-control.test.ts @@ -27,7 +27,7 @@ function buildApp(accessStore: AccessStore) { process.env.SESSION_SECRET = 'test-secret-key-32-bytes-long!' process.env.GITHUB_CLIENT_ID = 'test-client-id' process.env.GITHUB_CLIENT_SECRET = 'test-client-secret' - app.use('*', sessionReader()) + app.use('*', sessionReader(accessStore)) app.route('/auth', createAuthRoutes(userStore, accessStore)) return app } diff --git a/test/admin-routes.test.ts b/test/admin-routes.test.ts index 279bf85f7..6ddf46930 100644 --- a/test/admin-routes.test.ts +++ b/test/admin-routes.test.ts @@ -52,7 +52,9 @@ function buildApp() { process.env.SESSION_SECRET = SECRET process.env.ADMIN_USERS = 'adminuser' - app.use('*', sessionReader()) + accessStore.setApproved('adminuser', 'admin') + accessStore.setApproved('regular', 'admin') + app.use('*', sessionReader(accessStore)) app.route('/admin', createAdminRoutes(accessStore, userStore)) return { app, accessStore, userStore } } diff --git a/test/auth-approval-gate.test.ts b/test/auth-approval-gate.test.ts new file mode 100644 index 000000000..0e1c7ead5 --- /dev/null +++ b/test/auth-approval-gate.test.ts @@ -0,0 +1,300 @@ +/** + * Regression: a valid session cookie is not authorization. + * + * The request-access flow issues a temporary session to unapproved + * GitHub users, and revoked users may still hold old cookies. Routes that + * only check `c.get('user')` presence (fork, compare comments, the + * project-scoped forms router) must treat such sessions as signed out. + */ +import { afterEach, beforeEach, describe, expect, it } from 'bun:test' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Hono } from 'hono' +import { sessionReader } from '../src/entrypoints/app/middleware/auth' +import { createFormRouter } from '../src/entrypoints/app/routes/forms/index' +import { createCompareRoutes } from '../src/entrypoints/app/routes/owner/compare/index' +import { createOwnerRoutes } from '../src/entrypoints/app/routes/owner/index' +import { + type AccessStore, + COOKIE_NAME, + createAccessStore, + createUserStore, + encryptSession, + type SessionUser, +} from '../src/services/auth' +import { createReviewService } from '../src/services/forms' +import { InMemoryFormSessionGateway } from '../src/services/forms/session' +import { InMemorySubmissionGateway } from '../src/services/forms/submission' +import { + createFormProjectRepo, + createProjectService, + type FormProjectRepo, + type ProjectService, +} from '../src/services/projects' +import { createProjectStore } from '../src/services/storage' +import { StrategyRegistry } from '../src/shared/strategy-registry' +import type { ExtractionResult, ProjectIndex } from '../src/types/models' +import { testDataSpec, testFormSpec } from './forms/fixtures' + +const SECRET = 'test-secret-key-32-bytes-long!' + +const stubResult: ExtractionResult = { + spec: { + id: 'spec-1', + title: 'Test Form', + description: 'A test form', + groups: [ + { + id: 'g1', + title: 'Personal Info', + requirements: [ + { + id: 'f1', + fieldName: 'firstName', + label: 'First name', + fieldType: 'text', + required: true, + }, + ], + }, + ], + }, + formSpec: { + id: 'f1', + specId: 'spec-1', + title: 'Test Form', + pages: [ + { + id: 'page-1', + title: 'Personal Information', + groups: ['g1'], + deliveryMode: 'conversational', + }, + ], + createdAt: '2026-04-14', + updatedAt: '2026-04-14', + }, + confidence: [{ fieldId: 'f1', confidence: 0.95 }], + fieldMapping: {}, +} + +const owner: SessionUser = { + login: 'danielnaab', + name: 'Daniel', + avatarUrl: '', +} + +let repoBasePath: string +let repo: FormProjectRepo +let savedAllowedUsers: string | undefined + +beforeEach(() => { + repoBasePath = mkdtempSync(join(tmpdir(), 'auth-gate-test-')) + repo = createFormProjectRepo(repoBasePath) + process.env.SESSION_SECRET = SECRET + savedAllowedUsers = process.env.ALLOWED_USERS + process.env.ALLOWED_USERS = 'danielnaab' +}) + +afterEach(() => { + rmSync(repoBasePath, { recursive: true, force: true }) + if (savedAllowedUsers === undefined) delete process.env.ALLOWED_USERS + else process.env.ALLOWED_USERS = savedAllowedUsers +}) + +/** Mirrors the server wiring for the routes under test. */ +function buildApp() { + const accessStore = createAccessStore(':memory:') + const projectStore = createProjectStore(':memory:') + const userStore = createUserStore(':memory:') + const service = createProjectService(projectStore, repo, { + resolveExtractor: () => ({ extract: async () => stubResult }), + resolveVariant: () => ({ variantId: 'sonnet', modelId: 'test-model' }), + }) + const specs = { dataSpec: testDataSpec, formSpec: testFormSpec, sha: 'abc' } + + const app = new Hono() + app.use('*', sessionReader(accessStore)) + // Project-scoped forms router is mounted without an accessStore in + // server.tsx — the session reader alone must keep requesters out. + app.route( + '/:owner/:slug/forms', + createFormRouter({ + sessionGateway: new InMemoryFormSessionGateway(), + submissionGateway: new InMemorySubmissionGateway(), + getSpecs: async () => specs, + listSpecs: async () => [specs], + resolveOwnerSlug: (c) => ({ + owner: c.req.param('owner') ?? '', + slug: c.req.param('slug') ?? '', + }), + getSpecsByProject: async () => specs, + }), + ) + app.route('/', createCompareRoutes(service, createReviewService(repo))) + app.route( + '/', + createOwnerRoutes(service, userStore, new StrategyRegistry()), + ) + return { app, accessStore, projectStore, service } +} + +async function createReadyProject( + service: ProjectService, + projectStore: ReturnType, +): Promise { + const project = await service.createProject( + 'Test Form', + Buffer.from('%PDF-1.4 sample'), + owner, + ) + const start = Date.now() + while (projectStore.get(project.id)?.status !== 'ready') { + if (Date.now() - start > 2000) throw new Error('extraction timed out') + await new Promise((r) => setTimeout(r, 10)) + } + await repo.mergeBranch(project.slug, 'import', 'main') + return projectStore.get(project.id) as ProjectIndex +} + +async function cookieFor(login: string): Promise { + const session = await encryptSession( + { login, name: login, avatarUrl: '' }, + SECRET, + ) + return `${COOKIE_NAME}=${session}` +} + +type Setup = (store: AccessStore, login: string) => void + +const unapproved: [string, Setup][] = [ + ['pending requester', (s, l) => s.requestAccess(l)], + [ + 'revoked user', + (s, l) => { + s.setApproved(l, 'admin') + s.revoke(l, 'danielnaab') + }, + ], + ['user with no access entry', () => {}], +] + +function expectSignInRedirect(res: Response) { + expect(res.status).toBe(302) + expect(res.headers.get('Location')).toContain('/auth/signin') +} + +describe('unapproved sessions are treated as signed out', () => { + for (const [label, setup] of unapproved) { + describe(label, () => { + it('cannot fork a project', async () => { + const { app, accessStore, projectStore, service } = buildApp() + const project = await createReadyProject(service, projectStore) + setup(accessStore, 'mallory') + + const res = await app.request(`/danielnaab/${project.slug}/fork`, { + method: 'POST', + headers: { Cookie: await cookieFor('mallory') }, + redirect: 'manual', + }) + expectSignInRedirect(res) + expect(service.listUserProjects('mallory')).toHaveLength(0) + }) + + it('cannot comment on a compare view', async () => { + const { app, accessStore, projectStore, service } = buildApp() + const project = await createReadyProject(service, projectStore) + setup(accessStore, 'mallory') + + const res = await app.request( + `/danielnaab/${project.slug}/compare/main...main/comments`, + { + method: 'POST', + headers: { + Cookie: await cookieFor('mallory'), + 'Content-Type': 'application/x-www-form-urlencoded', + }, + body: 'body=hello', + redirect: 'manual', + }, + ) + expectSignInRedirect(res) + }) + + it('cannot use project-scoped form routes', async () => { + const { app, accessStore } = buildApp() + setup(accessStore, 'mallory') + + const landing = await app.request('/acme/my-form/forms', { + headers: { Cookie: await cookieFor('mallory') }, + redirect: 'manual', + }) + expectSignInRedirect(landing) + + const start = await app.request('/acme/my-form/forms/sessions', { + method: 'POST', + headers: { Cookie: await cookieFor('mallory') }, + redirect: 'manual', + }) + expectSignInRedirect(start) + }) + }) + } +}) + +describe('approved sessions still work', () => { + it('can fork a project', async () => { + const { app, accessStore, projectStore, service } = buildApp() + const project = await createReadyProject(service, projectStore) + accessStore.requestAccess('maya') + accessStore.approve('maya', 'danielnaab') + + const res = await app.request(`/danielnaab/${project.slug}/fork`, { + method: 'POST', + headers: { Cookie: await cookieFor('maya') }, + redirect: 'manual', + }) + expect(res.status).toBe(302) + expect(res.headers.get('Location')).toContain('/maya/') + }) + + it('can comment on a compare view', async () => { + const { app, accessStore, projectStore, service } = buildApp() + const project = await createReadyProject(service, projectStore) + accessStore.setApproved('maya', 'domain') + + const res = await app.request( + `/danielnaab/${project.slug}/compare/main...main/comments`, + { + method: 'POST', + headers: { + Cookie: await cookieFor('maya'), + 'Content-Type': 'application/x-www-form-urlencoded', + }, + body: 'body=hello', + redirect: 'manual', + }, + ) + expect(res.status).toBe(302) + expect(res.headers.get('Location')).toContain('#comments') + }) + + it('can use project-scoped form routes', async () => { + const { app, accessStore } = buildApp() + accessStore.setApproved('maya', 'admin') + + const res = await app.request('/acme/my-form/forms', { + headers: { Cookie: await cookieFor('maya') }, + }) + expect(res.status).toBe(200) + }) + + it('treats an ALLOWED_USERS login without an access row as approved', async () => { + const { app } = buildApp() + const res = await app.request('/acme/my-form/forms', { + headers: { Cookie: await cookieFor('danielnaab') }, + }) + expect(res.status).toBe(200) + }) +}) diff --git a/test/auth-middleware.test.ts b/test/auth-middleware.test.ts index 1cb29f1f5..cbc04747e 100644 --- a/test/auth-middleware.test.ts +++ b/test/auth-middleware.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it } from 'bun:test' +import { afterEach, beforeEach, describe, expect, it } from 'bun:test' import { unlinkSync } from 'node:fs' import { Hono } from 'hono' import { @@ -7,12 +7,39 @@ import { sessionReader, } from '../src/entrypoints/app/middleware/auth' import { + type AccessStore, COOKIE_NAME, createAccessStore, encryptSession, } from '../src/services/auth' const TEST_DB = '/tmp/test-auth-middleware-access.sqlite' +const SECRET = 'test-secret-key-32-bytes-long!' + +/** Access store with the given logins pre-approved. */ +function approvedStore(...logins: string[]): AccessStore { + const store = createAccessStore(':memory:') + for (const login of logins) store.setApproved(login, 'admin') + return store +} + +async function cookieFor(login: string): Promise { + const session = await encryptSession( + { login, name: login, avatarUrl: '' }, + SECRET, + ) + return `${COOKIE_NAME}=${session}` +} + +/** App that echoes the resolved `user` and `requester` context values. */ +function echoApp(store: AccessStore) { + const app = new Hono() + app.use('*', sessionReader(store)) + app.get('/test', (c) => + c.json({ user: c.get('user'), requester: c.get('requester') ?? null }), + ) + return app +} afterEach(() => { try { @@ -29,7 +56,7 @@ describe('Auth Middleware', () => { const secret = 'test-secret-key-32-bytes-long!' process.env.SESSION_SECRET = secret - app.use('*', sessionReader()) + app.use('*', sessionReader(approvedStore('testuser'))) app.get('/test', (c) => { const user = c.get('user') return c.json({ user }) @@ -63,7 +90,7 @@ describe('Auth Middleware', () => { const app = new Hono() process.env.SESSION_SECRET = 'test-secret-key-32-bytes-long!' - app.use('*', sessionReader()) + app.use('*', sessionReader(approvedStore())) app.get('/test', (c) => { const user = c.get('user') return c.json({ user }) @@ -79,7 +106,7 @@ describe('Auth Middleware', () => { const app = new Hono() process.env.SESSION_SECRET = 'test-secret-key-32-bytes-long!' - app.use('*', sessionReader()) + app.use('*', sessionReader(approvedStore())) app.get('/test', (c) => { const user = c.get('user') return c.json({ user }) @@ -103,7 +130,7 @@ describe('Auth Middleware', () => { const secret = 'test-secret-key-32-bytes-long!' process.env.SESSION_SECRET = secret - app.use('*', sessionReader()) + app.use('*', sessionReader(approvedStore('testuser'))) app.use('/protected', requireAuth()) app.get('/protected', (c) => c.text('success')) @@ -130,7 +157,7 @@ describe('Auth Middleware', () => { const app = new Hono() process.env.SESSION_SECRET = 'test-secret-key-32-bytes-long!' - app.use('*', sessionReader()) + app.use('*', sessionReader(approvedStore('testuser'))) app.use('/protected', requireAuth()) app.get('/protected', (c) => c.text('success')) @@ -146,7 +173,7 @@ describe('Auth Middleware', () => { const app = new Hono() process.env.SESSION_SECRET = 'test-secret-key-32-bytes-long!' - app.use('*', sessionReader()) + app.use('*', sessionReader(approvedStore('testuser'))) app.use('/protected', requireAuth()) app.get('/protected', (c) => c.text('success')) @@ -170,8 +197,8 @@ describe('Auth Middleware', () => { store.approve('revokeduser', 'admin') store.revoke('revokeduser', 'admin') - app.use('*', sessionReader()) - app.use('/protected', requireAuth(store)) + app.use('*', sessionReader(store)) + app.use('/protected', requireAuth()) app.get('/protected', (c) => c.text('success')) const sessionCookie = await encryptSession( @@ -201,8 +228,8 @@ describe('Auth Middleware', () => { const store = createAccessStore(TEST_DB) store.setApproved('approveduser', 'domain') - app.use('*', sessionReader()) - app.use('/protected', requireAuth(store)) + app.use('*', sessionReader(store)) + app.use('/protected', requireAuth()) app.get('/protected', (c) => c.text('success')) const sessionCookie = await encryptSession( @@ -224,32 +251,105 @@ describe('Auth Middleware', () => { expect(await res.text()).toBe('success') }) - it('still works without access store (backward compat)', async () => { + it('redirects a signed-in user with no access entry', async () => { const app = new Hono() - const secret = 'test-secret-key-32-bytes-long!' - process.env.SESSION_SECRET = secret + process.env.SESSION_SECRET = SECRET + delete process.env.ALLOWED_USERS - app.use('*', sessionReader()) + app.use('*', sessionReader(approvedStore('testuser'))) app.use('/protected', requireAuth()) app.get('/protected', (c) => c.text('success')) - const sessionCookie = await encryptSession( - { - login: 'anyuser', - name: 'Any User', - avatarUrl: 'https://example.com/avatar.png', - }, - secret, + const res = await app.request('/protected', { + headers: { Cookie: await cookieFor('anyuser') }, + }) + + expect(res.status).toBe(302) + expect(res.headers.get('Location')).toContain('/auth/signin') + }) + }) + + describe('sessionReader access resolution', () => { + let savedAllowedUsers: string | undefined + beforeEach(() => { + process.env.SESSION_SECRET = SECRET + savedAllowedUsers = process.env.ALLOWED_USERS + process.env.ALLOWED_USERS = 'envuser' + }) + afterEach(() => { + if (savedAllowedUsers === undefined) delete process.env.ALLOWED_USERS + else process.env.ALLOWED_USERS = savedAllowedUsers + }) + + it('sets user for an approved login', async () => { + const store = createAccessStore(':memory:') + store.requestAccess('maya') + store.approve('maya', 'admin') + + const res = await echoApp(store).request('/test', { + headers: { Cookie: await cookieFor('maya') }, + }) + const data = await res.json() + expect(data.user?.login).toBe('maya') + expect(data.requester).toBeNull() + }) + + it('demotes a pending requester to requester', async () => { + const store = createAccessStore(':memory:') + store.requestAccess('pendinguser') + + const res = await echoApp(store).request('/test', { + headers: { Cookie: await cookieFor('pendinguser') }, + }) + const data = await res.json() + expect(data.user).toBeNull() + expect(data.requester?.login).toBe('pendinguser') + expect(res.headers.get('Set-Cookie')).toBeNull() + }) + + it('demotes a user with no access entry to requester', async () => { + const res = await echoApp(createAccessStore(':memory:')).request( + '/test', + { headers: { Cookie: await cookieFor('newcomer') } }, ) + const data = await res.json() + expect(data.user).toBeNull() + expect(data.requester?.login).toBe('newcomer') + }) - const res = await app.request('/protected', { - headers: { - Cookie: `${COOKIE_NAME}=${sessionCookie}`, - }, + it('signs out a revoked user and clears the cookie', async () => { + const store = createAccessStore(':memory:') + store.setApproved('baduser', 'admin') + store.revoke('baduser', 'admin') + + const res = await echoApp(store).request('/test', { + headers: { Cookie: await cookieFor('baduser') }, }) + const data = await res.json() + expect(data.user).toBeNull() + expect(data.requester).toBeNull() + expect(res.headers.get('Set-Cookie')).toContain(`${COOKIE_NAME}=;`) + }) - expect(res.status).toBe(200) - expect(await res.text()).toBe('success') + it('treats an ALLOWED_USERS login without an entry as approved', async () => { + const res = await echoApp(createAccessStore(':memory:')).request( + '/test', + { headers: { Cookie: await cookieFor('envuser') } }, + ) + const data = await res.json() + expect(data.user?.login).toBe('envuser') + }) + + it('does not let ALLOWED_USERS override an explicit revocation', async () => { + const store = createAccessStore(':memory:') + store.setApproved('envuser', 'env') + store.revoke('envuser', 'admin') + + const res = await echoApp(store).request('/test', { + headers: { Cookie: await cookieFor('envuser') }, + }) + const data = await res.json() + expect(data.user).toBeNull() }) }) @@ -260,7 +360,10 @@ describe('Auth Middleware', () => { process.env.SESSION_SECRET = secret process.env.ADMIN_USERS = 'adminuser' - app.use('*', sessionReader()) + app.use( + '*', + sessionReader(approvedStore('adminuser', 'regularuser', 'danielnaab')), + ) app.use('/admin', requireAdmin()) app.get('/admin', (c) => c.text('admin access')) @@ -289,7 +392,10 @@ describe('Auth Middleware', () => { process.env.SESSION_SECRET = secret process.env.ADMIN_USERS = 'adminuser' - app.use('*', sessionReader()) + app.use( + '*', + sessionReader(approvedStore('adminuser', 'regularuser', 'danielnaab')), + ) app.use('/admin', requireAdmin()) app.get('/admin', (c) => c.text('admin access')) @@ -317,7 +423,10 @@ describe('Auth Middleware', () => { process.env.SESSION_SECRET = secret delete process.env.ADMIN_USERS - app.use('*', sessionReader()) + app.use( + '*', + sessionReader(approvedStore('adminuser', 'regularuser', 'danielnaab')), + ) app.use('/admin', requireAdmin()) app.get('/admin', (c) => c.text('admin access')) diff --git a/test/auth-routes.test.ts b/test/auth-routes.test.ts index 2b3ae6cac..d2aa71668 100644 --- a/test/auth-routes.test.ts +++ b/test/auth-routes.test.ts @@ -43,7 +43,7 @@ describe('Auth Routes', () => { // Create app app = new Hono() - app.use('*', sessionReader()) + app.use('*', sessionReader(mockAccessStore)) app.route('/auth', createAuthRoutes(mockUserStore, mockAccessStore)) }) @@ -248,6 +248,20 @@ describe('Auth Routes', () => { }) }) + describe('GET /auth/request-access', () => { + it('shows an unapproved requester who they are signed in as', async () => { + const cookie = await encryptSession( + { login: 'outsider', name: 'Out Sider', avatarUrl: '' }, + process.env.SESSION_SECRET as string, + ) + const res = await app.request('/auth/request-access', { + headers: { Cookie: `${COOKIE_NAME}=${cookie}` }, + }) + expect(res.status).toBe(200) + expect(await res.text()).toContain('@outsider') + }) + }) + describe('POST /auth/request-access', () => { async function postRequestAccess(): Promise> { let notified: Record | undefined diff --git a/test/entrypoints/settings-variants.test.ts b/test/entrypoints/settings-variants.test.ts index 394ca4aa4..3d6c54f27 100644 --- a/test/entrypoints/settings-variants.test.ts +++ b/test/entrypoints/settings-variants.test.ts @@ -5,7 +5,11 @@ import { join } from 'node:path' import { Hono } from 'hono' import { sessionReader } from '../../src/entrypoints/app/middleware/auth' import { createSettingsRoutes } from '../../src/entrypoints/app/routes/settings/index' -import { COOKIE_NAME, encryptSession } from '../../src/services/auth' +import { + COOKIE_NAME, + createAccessStore, + encryptSession, +} from '../../src/services/auth' import type { Task } from '../../src/services/variant-preferences' import { createVariantPreferencesGateway, @@ -58,7 +62,9 @@ function buildApp() { const preferences = createVariantPreferencesService(gateway, registries) const app = new Hono() - app.use('*', sessionReader()) + const accessStore = createAccessStore(':memory:') + accessStore.setApproved('alice', 'admin') + app.use('*', sessionReader(accessStore)) app.route('/settings', createSettingsRoutes({ preferences, registries })) return { app, preferences } } diff --git a/test/server.test.ts b/test/server.test.ts index 2d621a424..0677500ce 100644 --- a/test/server.test.ts +++ b/test/server.test.ts @@ -1,6 +1,20 @@ -import { describe, expect, it } from 'bun:test' +import { beforeAll, describe, expect, it } from 'bun:test' import app from '../src/entrypoints/app/server' -import { COOKIE_NAME, encryptSession } from '../src/services/auth' +import { + COOKIE_NAME, + createAccessStore, + encryptSession, +} from '../src/services/auth' + +// The server resolves access against its project database; approve the +// user these tests sign in as, and register a pending requester. +beforeAll(() => { + const accessStore = createAccessStore( + process.env.PROJECT_DB_PATH ?? 'data/projects.sqlite', + ) + accessStore.setApproved('testuser', 'admin') + accessStore.requestAccess('server-test-requester') +}) describe('Server', () => { it('responds to health check', async () => { @@ -85,3 +99,39 @@ describe('Authentication', () => { expect(html).toContain('/projects') }) }) + +describe('Access gate (server wiring)', () => { + async function requesterCookie() { + const secret = 'test-secret-key-32-bytes-long!' + process.env.SESSION_SECRET = secret + const session = await encryptSession( + { login: 'server-test-requester', name: 'Requester', avatarUrl: '' }, + secret, + ) + return `${COOKIE_NAME}=${session}` + } + + it('shows a pending requester as signed out on the dashboard', async () => { + const res = await app.request('/', { + headers: { Cookie: await requesterCookie() }, + }) + expect(res.status).toBe(200) + expect(await res.text()).not.toContain('Recent projects') + }) + + it('keeps a pending requester out of project-scoped form routes', async () => { + const res = await app.request('/someone/some-form/forms', { + headers: { Cookie: await requesterCookie() }, + }) + expect(res.status).toBe(302) + expect(res.headers.get('Location')).toContain('/auth/signin') + }) + + it('keeps a pending requester out of /new', async () => { + const res = await app.request('/new', { + headers: { Cookie: await requesterCookie() }, + }) + expect(res.status).toBe(302) + expect(res.headers.get('Location')).toContain('/auth/signin') + }) +})