Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 4 additions & 0 deletions catalog/architecture/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,13 +173,15 @@ 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.
- No access tokens or secrets stored in session -- only user profile data (login, name, avatar URL). GitHub OAuth tokens are used server-side only during callback and immediately discarded.
- 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.

Expand Down Expand Up @@ -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 |
Expand Down Expand Up @@ -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

Expand Down
68 changes: 48 additions & 20 deletions src/entrypoints/app/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

Expand All @@ -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) {
Expand All @@ -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()
})
}
Expand Down
6 changes: 4 additions & 2 deletions src/entrypoints/app/routes/auth/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<Layout currentSection="home" user={user}>
<RequestAccessPage user={user} />
Expand All @@ -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'))
}
Expand Down
4 changes: 1 addition & 3 deletions src/entrypoints/app/routes/forms/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -82,7 +81,6 @@ interface FormRouterDeps {
specId: string,
specVersion: string,
) => Promise<FieldMapping | null>
accessStore?: AccessStore
/** Resolves owner/slug from route context. Routes use
* project-scoped URL shapes (/:owner/:slug/forms/...). */
resolveOwnerSlug?: (c: Context) => { owner: string; slug: string }
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 1 addition & 3 deletions src/entrypoints/app/routes/settings/index.tsx
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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')
Expand Down
8 changes: 3 additions & 5 deletions src/entrypoints/app/server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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)
Expand All @@ -306,7 +306,6 @@ app.route(
createSettingsRoutes({
preferences: variantPreferences,
registries,
accessStore,
}),
)

Expand All @@ -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
Expand Down Expand Up @@ -610,7 +609,6 @@ app.route(
if (!buf) return null
return JSON.parse(buf.toString())
},
accessStore,
resolveProjectForSpec: findProjectBySpecId,
getProjectName: (slug) => projectService.getProjectName(slug),
}),
Expand Down
2 changes: 1 addition & 1 deletion test/access-control.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
4 changes: 3 additions & 1 deletion test/admin-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}
Expand Down
Loading
Loading