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
287 changes: 287 additions & 0 deletions .context/decisions/0044-identity-self-service-reaches-the-cli.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions .context/decisions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ invisible one — which is why it is checked rather than trusted.
- [ADR 0041](0041-dois-cite-the-uploader-by-real-name-or-not-at-all.md) - DOIs cite the uploader by real name, or not at all
- [ADR 0042](0042-upload-access-is-requested-once-by-the-person-who-wants-it.md) - Upload access is requested once, by the person who wants it
- [ADR 0043](0043-one-person-one-account.md) - One person, one account: ORCID, email and GitHub each back at most one live account
- [ADR 0044](0044-identity-self-service-reaches-the-cli.md) - Identity self-service reaches the CLI, and ORCID does it through the browser

## Backfill note (2026-07-31)

Expand Down
6 changes: 4 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ Load-bearing ones to know before touching the relevant area:
0034 (`datasets` stays one table under an enforced column budget; derive, don't store),
0040 (`verified` is the base tier; admin approval is the only writer of upload access),
0042 (upload access is requested once, by the person who wants it),
0043 (one person, one account: an ORCID iD, an email or a GitHub handle backs at most one live account).
0043 (one person, one account: an ORCID iD, an email or a GitHub handle backs at most one live account),
0044 (identity self-service reaches the CLI; ORCID links through a browser handoff whose
signed state names the account).

---

Expand Down Expand Up @@ -533,7 +535,7 @@ and what is historical. The entries worth knowing by name:

| Group | Covers |
|---|---|
| `nemar auth` | login, signup, status/whoami, profile, request-upload-access, switch, logout, verification, SSH setup, key retrieval and regeneration |
| `nemar auth` | login, signup, status/whoami, profile (plus `set-email`/`verify-email`, `set-github`, `set-username`, `set-name`, `set-location`, `orcid link\|relink\|unlink` — ADR 0044), request-upload-access, switch, logout, verification, SSH setup, key retrieval and regeneration |
| `nemar dataset` | validate, upload, download, status (alias: view), list, search, release, update, clone, get, commit, push, drop, ci, manifest |
| `nemar dataset publish` | request, status, resend |
| `nemar dataset` (access) | request-access, access, invite, collaborators |
Expand Down
52 changes: 52 additions & 0 deletions backend/src/db/migrations/0078_orcid_link_intents.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
-- Single-use ORCID link intents for the CLI handoff
-- (ADR 0044, epic #1250 phase #1266; PR #1269 review item A3).
--
-- WHAT THIS CLOSES. `POST /auth/orcid/cli-start` mints a signed, short-lived
-- intent naming the account it was created for, and the browser that finishes
-- the ORCID flow carries no NEMAR session -- that is the whole point, since it
-- was opened from a terminal. The signature makes the intent unforgeable, but
-- a signature alone does not make it UNREPEATABLE: anyone holding the URL
-- (browser history, a referrer, a shoulder) could complete it again inside the
-- ten-minute window, and the consequence is permanent. ADR 0041 makes a DOI
-- cite the account the iD is attached to, and ADR 0043 then refuses the
-- rightful owner their own iD because it is "already on a live account".
--
-- So the intent gets a server-side nonce and is CONSUMED at the callback.
-- One browser completion per intent, whatever its outcome; a replay finds
-- `consumed_at` already set and is refused before anything is linked.
--
-- WHY A TABLE. `auth_codes` is the only comparable short-lived store and it is
-- keyed by email address for a 6-digit secret with an attempt counter -- none
-- of which fits a 256-bit nonce for an account-scoped OAuth intent. Reusing it
-- would mean an `email` column carrying something that is not an email and a
-- `code_hash` carrying something nobody types. This table is four columns and
-- holds nothing for longer than ten minutes.
--
-- LIFECYCLE. Rows are pruned opportunistically at mint time (every
-- `cli-start` deletes what has expired), so the table needs no cron and
-- cannot grow past the intents minted in one ten-minute window. Nothing here
-- is a secret: the nonce is meaningless without the HMAC-signed state that
-- carries it, and that signature is keyed with ENCRYPTION_KEY.

CREATE TABLE IF NOT EXISTS orcid_link_intents (
-- 256 bits of URL-safe randomness, generated by `generateCsrf()`. Primary
-- key rather than a surrogate id: the nonce IS the identity of the intent,
-- and a UNIQUE constraint on it is what makes "consume once" enforceable.
nonce TEXT PRIMARY KEY,
-- The account the intent was minted FOR. Also inside the signed state; kept
-- here so the interstitial can name the account without trusting anything
-- the browser sent, and so a deleted account's intents go with it.
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
-- 'link' or 'relink'. Never 'login': a CLI flow always acts on an account
-- that already exists.
mode TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL,
-- Set by the callback the first time the intent completes. A second
-- completion finds it non-NULL and is refused.
consumed_at TEXT
);

-- Drives the opportunistic prune and the "is this still usable" read.
CREATE INDEX IF NOT EXISTS idx_orcid_link_intents_expires
ON orcid_link_intents(expires_at);
248 changes: 186 additions & 62 deletions backend/src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ import {
isActiveAccountStatus,
} from "../services/account-tier";
import { hashApiKey } from "../services/token";
import { COOKIE_NAME, hashCookieId, parseCookieHeader } from "../services/web-session";
import {
COOKIE_NAME,
hashCookieId,
isAllowedOrigin,
parseCookieHeader,
} from "../services/web-session";
import {
type AuthUser,
type Bindings,
Expand Down Expand Up @@ -124,41 +129,54 @@ async function resolveCookieUser(c: AuthContext): Promise<CookieAuthResult> {
}

/**
* Middleware to require authentication via either a bearer API token or
* the web-dashboard `nemar_session` cookie (#572).
* What an `Authorization` header resolved to.
*
* Resolution order:
* 1. `Authorization: Bearer <api_key>` — CLI path, unchanged.
* 2. `Cookie: nemar_session=…` — dashboard path, added for #572.
* 3. Neither resolves -> 401 with the same shape we returned before
* cookies existed.
* `absent` is "no header at all" and is the only outcome a caller may fall
* through on: every other failure is a deliberate answer (a malformed header,
* a dead key, an inactive account) that must reach the client verbatim rather
* than being retried as anonymous.
*/
export type BearerAuthResult =
| { kind: "absent" }
| { kind: "refused"; response: Response }
| { kind: "user"; user: AuthUser };

/**
* Resolve `Authorization: Bearer <api_key>` to a full AuthUser.
*
* Sets `c.var.user` with the resolved AuthUser regardless of which path
* matched, so route handlers don't need to branch.
* Extracted from `authMiddleware` for #1266 so the CLI-facing self-service
* routes in auth-web.ts / auth-orcid.ts accept a token through the SAME
* lookup the rest of the API uses — same key hashing, same revoked/expired
* filter, same active-account rule, same `last_used_at` touch. A second copy
* of this SELECT is how a route ends up honouring a token the middleware
* would have refused.
*/
export async function authMiddleware(c: AuthContext, next: Next) {
export async function resolveBearerUser(c: AuthContext): Promise<BearerAuthResult> {
const authHeader = c.req.header("Authorization");
if (!authHeader) return { kind: "absent" };

// -------------------------------------------------------------------
// Path 1: Authorization: Bearer <api_key>
// -------------------------------------------------------------------
if (authHeader) {
if (!authHeader.startsWith("Bearer ")) {
return c.json({ error: "Invalid Authorization header format. Use: Bearer <api_key>" }, 401);
}
if (!authHeader.startsWith("Bearer ")) {
return {
kind: "refused",
response: c.json(
{ error: "Invalid Authorization header format. Use: Bearer <api_key>" },
401,
),
};
}

const apiKey = authHeader.substring(7);
const apiKey = authHeader.substring(7);

if (!apiKey || apiKey.length < 32) {
return c.json({ error: "Invalid API key format" }, 401);
}
if (!apiKey || apiKey.length < 32) {
return { kind: "refused", response: c.json({ error: "Invalid API key format" }, 401) };
}

// Hash the key for lookup
const hashedKey = await hashApiKey(apiKey);
// Hash the key for lookup
const hashedKey = await hashApiKey(apiKey);

// Find token and associated user
const result = await c.env.DB.prepare(
`
// Find token and associated user
const result = await c.env.DB.prepare(
`
SELECT
u.id,
u.username,
Expand All @@ -175,54 +193,79 @@ export async function authMiddleware(c: AuthContext, next: Next) {
AND (t.expires_at IS NULL OR t.expires_at > datetime('now'))
AND u.deleted_at IS NULL
`,
)
.bind(hashedKey)
.first<{
id: number;
username: string;
email: string;
github_username: string;
role: string | null;
orcid: string | null;
status: string;
token_id: number;
}>();
)
.bind(hashedKey)
.first<{
id: number;
username: string;
email: string;
github_username: string;
role: string | null;
orcid: string | null;
status: string;
token_id: number;
}>();

if (!result) {
return c.json({ error: "Invalid or expired API key" }, 401);
}
if (!result) {
return { kind: "refused", response: c.json({ error: "Invalid or expired API key" }, 401) };
}

// ADR 0040 phase 2: `verified` is the base tier and holds a usable API
// key, so the token is accepted here and the upload gate — not this
// middleware — is what a base-tier account runs into.
if (!isActiveAccountStatus(result.status)) {
return c.json(inactiveAccountBody(result.status), 403);
}
// ADR 0040 phase 2: `verified` is the base tier and holds a usable API
// key, so the token is accepted here and the upload gate — not this
// middleware — is what a base-tier account runs into.
if (!isActiveAccountStatus(result.status)) {
return { kind: "refused", response: c.json(inactiveAccountBody(result.status), 403) };
}

// Validate role from DB
const role = parseRole(result.role, result.username);
if (role === null) {
return c.json({ error: "Account configuration error. Contact an administrator." }, 500);
}
// Validate role from DB
const role = parseRole(result.role, result.username);
if (role === null) {
return {
kind: "refused",
response: c.json({ error: "Account configuration error. Contact an administrator." }, 500),
};
}

// Update last_used_at for the token
await c.env.DB.prepare("UPDATE tokens SET last_used_at = datetime('now') WHERE id = ?")
.bind(result.token_id)
.run();
// Update last_used_at for the token
await c.env.DB.prepare("UPDATE tokens SET last_used_at = datetime('now') WHERE id = ?")
.bind(result.token_id)
.run();

// Set user in context
const user: AuthUser = {
return {
kind: "user",
user: {
id: result.id,
username: result.username,
email: result.email,
github_username: result.github_username,
role,
orcid: result.orcid || undefined,
};
},
};
}

c.set("user", user);
/**
* Middleware to require authentication via either a bearer API token or
* the web-dashboard `nemar_session` cookie (#572).
*
* Resolution order:
* 1. `Authorization: Bearer <api_key>` — CLI path, unchanged.
* 2. `Cookie: nemar_session=…` — dashboard path, added for #572.
* 3. Neither resolves -> 401 with the same shape we returned before
* cookies existed.
*
* Sets `c.var.user` with the resolved AuthUser regardless of which path
* matched, so route handlers don't need to branch.
*/
export async function authMiddleware(c: AuthContext, next: Next) {
// -------------------------------------------------------------------
// Path 1: Authorization: Bearer <api_key>
// -------------------------------------------------------------------
const bearer = await resolveBearerUser(c);
if (bearer.kind === "refused") return bearer.response;
if (bearer.kind === "user") {
c.set("user", bearer.user);
c.set("authMethod", "token");

await next();
return;
}
Expand Down Expand Up @@ -252,6 +295,87 @@ export async function authMiddleware(c: AuthContext, next: Next) {
return c.json({ error: "Missing Authorization header" }, 401);
}

/**
* The account acting on a self-service route, whichever credential it used.
*
* Only the three fields those routes actually need off the credential: the id
* every write is scoped by, the current address the email change compares
* against, and the current GitHub handle `githubHandleChanged` compares
* against. Everything else is re-read from `users` inside the handler, which
* is what lets ONE handler serve both credentials without caring which one
* arrived (#1266).
*/
export interface ActingAccount {
id: number;
email: string;
github_username: string | null;
via: "cookie" | "token";
}

export type ActingAccountResolution =
| { ok: true; actor: ActingAccount }
| { ok: false; response: Response };

/**
* Resolve the account acting on a route that accepts EITHER the CLI's bearer
* token or the dashboard's `nemar_session` cookie (#1266, ADR 0044).
*
* Deliberately NOT `authMiddleware` mounted on these routes, for one reason
* that only shows up on the cookie half: `authMiddleware`'s cookie path
* refuses a `pending` account (403, ADR 0040), while `webSessionMiddleware`
* admits it. An account that typed its address wrong at sign-up is `pending`
* BECAUSE the address is wrong, and the email change is the one thing it must
* still be able to do. So the cookie path keeps `webSessionMiddleware`'s
* acceptance byte for byte, and the token path uses the shared
* `resolveBearerUser` above — which, being the standard token rule, admits
* only an active account. A `pending` CLI account has no token to present
* anyway: the key is issued after verification.
*
* The Origin allow-list applies to the COOKIE path only, and that is the whole
* point of it: a cookie rides along with any cross-site request the browser is
* tricked into making, and a bearer token does not. Requiring an Origin header
* a CLI has no reason to send would refuse every terminal.
*
* Bearer wins when both are present, matching `authMiddleware`.
*
* Requires `webSessionMiddleware` to have run for the cookie half.
*/
export async function resolveActingAccount(c: AuthContext): Promise<ActingAccountResolution> {
const bearer = await resolveBearerUser(c);
if (bearer.kind === "refused") return { ok: false, response: bearer.response };
if (bearer.kind === "user") {
c.set("user", bearer.user);
c.set("authMethod", "token");
return {
ok: true,
actor: {
id: bearer.user.id,
email: bearer.user.email,
github_username: bearer.user.github_username || null,
via: "token",
},
};
}

if (!isAllowedOrigin(c.req.header("Origin"))) {
return { ok: false, response: c.json({ error: "Origin not allowed" }, 403) };
}
const webUser = c.var.webUser;
if (!webUser) {
return { ok: false, response: c.json({ error: "Authentication required" }, 401) };
}
c.set("authMethod", "cookie");
return {
ok: true,
actor: {
id: webUser.id,
email: webUser.email,
github_username: webUser.github_username,
via: "cookie",
},
};
}

/**
* Middleware to require admin role
*
Expand Down
12 changes: 12 additions & 0 deletions backend/src/middleware/rateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,18 @@ const AUTH_PATHS = [
// entry as a prefix, so "/auth/email/verify" also matches
// "/auth/email/verify/request".
"/auth/email/verify",
// CLI ORCID surface (#1266, ADR 0044). `cli-start` mints an identity-link
// intent, `cli-handoff` (and its /continue confirm step, covered by the
// prefix match) is the only thing that can turn a leaked one into an ORCID
// redirect, and `unlink` drops an iD outright -- all three are now reachable
// with a bearer token, so without these entries they would sit in the
// 1000/min token bucket instead of the 10/min floor every other identity
// mutation has. A person links or unlinks an iD once.
// The rest of /auth/orcid/* is deliberately NOT here: the callback is a
// browser landing, and moving it would change the web flow's bucket.
"/auth/orcid/cli-start",
"/auth/orcid/cli-handoff",
"/auth/orcid/unlink",
// NOT an /auth path, and deliberately in this list anyway (ADR 0042, #1253):
// POST /users/me/upload-access/request spends a live GitHub API call on the
// shared installation token for every attempt, and a refused one writes
Expand Down
Loading
Loading