Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
6 changes: 6 additions & 0 deletions docs/contributing/adding-capabilities.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,12 @@ export; feedback status may remain exportable.

Current admin capabilities:

User-targeting admin capabilities accept `stableUserId`, email, or username
where operator ergonomics call for lookup. They never accept or return numeric
`users.id`; handlers resolve the stable identity to that internal D1 join key
only after boundary validation. Admin URLs and audit reasons follow the same
rule.

- `admin_user_list`
- `admin_user_get`
- `admin_user_create`
Expand Down
25 changes: 16 additions & 9 deletions docs/contributing/architecture/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ Session cookie behavior is implemented in

The cookie payload stores:

- `id` (user id as string)
- `v: 2`
- `stableUserId` (the authoritative `users.stable_user_id`)
- `email`
- `issuedAt` (epoch ms when the cookie was issued or last renewed)
- `rememberMe` when the login used remember-me
Expand All @@ -43,6 +44,10 @@ Password reset confirmation writes `users.password_changed_at`. Session
resolution rejects cookies whose `issuedAt` is missing or at/before that
timestamp, so a reset invalidates every existing browser session.

`users.id` never crosses the cookie boundary. Session resolution looks up the
stable id and only then uses the numeric primary key for internal D1 joins.
Version-1 cookies fail closed and require a fresh login.

`packages/worker/src/app/handler.ts` calls `setAuthSessionSecret` on each
request so cookie signing and verification are available to handlers.

Expand Down Expand Up @@ -353,10 +358,11 @@ signed-in owner requests `/@{username}/packages/{kodyId}/...` on the app origin,
the app origin mints `<base64url payload>.<HMAC-SHA256>`:

- signed with `COOKIE_SECRET` over a purpose-labelled message
(`kody-package-app-handoff:v1`), so it is not interchangeable with any other
(`kody-package-app-handoff:v2`), so it is not interchangeable with any other
signed value
- payload binds `{ userId, username, kodyId, exp, jti }`; the package-app origin
rejects a token whose `username`/`kodyId` do not match the requested path
- payload binds `{ stableUserId, username, kodyId, exp, jti }`; the package-app
origin rejects a token whose `username`/`kodyId` do not match the requested
path
- 60 second lifetime
- single use: `jti` is burned in `BUNDLE_ARTIFACTS_KV` for 60 seconds on first
use. The burn happens **after** the path binding is checked, so a token
Expand All @@ -381,16 +387,17 @@ sets `kody_pkg_session` on the package-app origin:
- `httpOnly: true`, `sameSite: 'Lax'`, `path: '/'`, `secure` per request
- 12 hour max age
- signed with a **derived** secret,
`sha256Base64Url('kody-package-app-session:v1:' + COOKIE_SECRET)`, so a value
`sha256Base64Url('kody-package-app-session:v2:' + COOKIE_SECRET)`, so a value
signed for this cookie can never verify as a `kody_session`
- payload is `{ v, pkgUserId, pkgUsername, issuedAt }` — a shape the app session
schema rejects, so the two cannot be confused even by name substitution
- payload is `{ v, stableUserId, pkgUsername, issuedAt }` — a shape the app
session schema rejects, so the two cannot be confused even by name
substitution

It authorizes hosted package-app serving for one account and nothing else: the
app origin has no code path that reads it, and the package-app origin has no
first-party routes. Every request re-resolves the account from D1
(`resolvePackageAppOwnerByUserId`) and fails closed for unknown, deleting, or
suspended accounts, and for sessions issued at or before
(`resolvePackageAppOwnerByStableUserId`) and fails closed for unknown, deleting,
or suspended accounts, and for sessions issued at or before
`users.password_changed_at` — the same rules browser sessions follow.
Deployments with `PACKAGE_APP_BASE_URL` unset never mint either credential; they
serve package apps inline behind `kody_session`.
Expand Down
12 changes: 6 additions & 6 deletions e2e/admin-rbac.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ test('admin RBAC controls access, role assignment, and privacy boundaries', asyn
await expect(page.getByRole('heading', { name: 'Admin users' })).toBeHidden()
await expect(page.getByText('Forbidden')).toBeVisible()
const memberUsageResponse = await page.request.get(
'/admin/users/usage.json?userId=1',
'/admin/users/usage.json?stableUserId=forbidden',
)
expect(memberUsageResponse.status()).toBe(403)
await page.goto('/admin/insights')
Expand Down Expand Up @@ -146,12 +146,12 @@ test('admin RBAC controls access, role assignment, and privacy boundaries', asyn
expect(memberRecord.plan).toBe('free')
expect(JSON.stringify(memberRecord)).not.toContain('memberPrivateSecret')
expect(JSON.stringify(memberRecord)).not.toContain('super-secret-value')
const memberId = Number(memberRecord.id)
const memberStableUserId = String(memberRecord.stableUserId)

// URL-backed selection: click updates the path, reload restores it, and a
// detail pane opens that account (use the non-first seeded user).
await page.getByRole('button', { name: memberUser.username }).click()
await expect(page).toHaveURL(new RegExp(`/admin/users/${memberId}`))
await expect(page).toHaveURL(new RegExp(`/admin/users/${memberStableUserId}`))
await expect(page.getByText('Account metadata only')).toBeVisible()
await expect(page.getByText('Usage & quotas')).toBeVisible()
await expect(
Expand All @@ -161,20 +161,20 @@ test('admin RBAC controls access, role assignment, and privacy boundaries', asyn
page.getByRole('heading', { name: 'Entitlements' }),
).toBeVisible()
await page.reload()
await expect(page).toHaveURL(new RegExp(`/admin/users/${memberId}`))
await expect(page).toHaveURL(new RegExp(`/admin/users/${memberStableUserId}`))
await expect(
page.getByRole('heading', { name: memberUser.username, exact: true }),
).toBeVisible()
await expect(page.getByText('Account metadata only')).toBeVisible()
await expect(page.getByText('memberPrivateSecret')).toHaveCount(0)
await expect(page.getByText('super-secret-value')).toHaveCount(0)
const usageApiResponse = await page.request.get(
`/admin/users/usage.json?userId=${memberId}`,
`/admin/users/usage.json?stableUserId=${memberStableUserId}`,
)
expect(usageApiResponse.ok()).toBe(true)
const usagePayload = await usageApiResponse.json()
expect(usagePayload.ok).toBe(true)
expect(usagePayload.userId).toBe(memberId)
expect(usagePayload.stableUserId).toBe(memberStableUserId)
expect(JSON.stringify(usagePayload)).not.toContain('memberPrivateSecret')
expect(JSON.stringify(usagePayload)).not.toContain('super-secret-value')
expect(JSON.stringify(usagePayload)).not.toContain(memberUser.email)
Expand Down
8 changes: 4 additions & 4 deletions packages/worker/client/routes/admin-feature-flags.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -419,9 +419,9 @@ export function AdminFeatureFlagsRoute(handle: Handle) {
{
label: 'Updated by',
value:
flag.global.updatedBy == null
flag.global.updatedByStableUserId == null
? 'Unknown'
: String(flag.global.updatedBy),
: flag.global.updatedByStableUserId,
},
{
label: 'Note',
Expand All @@ -448,7 +448,7 @@ export function AdminFeatureFlagsRoute(handle: Handle) {
<div mix={css({ display: 'grid', gap: spacing.sm })}>
{flag.overrides.map((override) => (
<div
key={`${flag.key}:${override.userId}`}
key={`${flag.key}:${override.stableUserId}`}
mix={css({
display: 'flex',
justifyContent: 'space-between',
Expand Down Expand Up @@ -485,7 +485,7 @@ export function AdminFeatureFlagsRoute(handle: Handle) {
{
action: 'clear_user_override',
key: flag.key,
userId: override.userId,
stableUserId: override.stableUserId,
},
'clearing-override',
`Removed override for ${override.username}.`,
Expand Down
4 changes: 2 additions & 2 deletions packages/worker/client/routes/admin-invites.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -515,9 +515,9 @@ export function AdminInvitesRoute(handle: Handle) {
label: 'Created by',
value:
invite.createdByEmail ??
(invite.createdBy == null
(invite.createdByStableUserId == null
? 'Unknown'
: String(invite.createdBy)),
: invite.createdByStableUserId),
},
{
label: 'Revoked',
Expand Down
Loading
Loading