From 5b755deca5bd962f822cd0f7557a21070f95dde6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=85=E8=86=80?= Date: Fri, 23 Oct 2026 23:23:29 +0800 Subject: [PATCH] fix(oauth): confirm account links and installs A login link or installation id is not proof of account ownership. Verify installation management, bind browser state and require an explicit account-link confirmation before granting chat access. --- server/lib/web/oauth.ts | 427 ++++++++++++++++++------- server/routes/auth/github/link.post.ts | 3 + tests/install.test.ts | 176 ++++++++-- 3 files changed, 465 insertions(+), 141 deletions(-) create mode 100644 server/routes/auth/github/link.post.ts diff --git a/server/lib/web/oauth.ts b/server/lib/web/oauth.ts index 64a2101..60f01eb 100644 --- a/server/lib/web/oauth.ts +++ b/server/lib/web/oauth.ts @@ -11,19 +11,32 @@ import { import { getOAuthURL, handleOAuthCallback as handleGithubOAuthCallback, - getInstallationAccount, + getInstallationDetails, + userManagesInstallation, } from "../github/oauth"; -import { removeToken, saveDiscordLink, saveTelegramLink, saveFeishuLink } from "../github/store"; -import { createAdminSession, adminCookie, getAdminSession } from "./session"; +import { getToken, linkStatement, removeToken } from "../github/store"; +import { + createAdminSession, + adminCookie, + getAdminSession, + isAdminUser, + authLogin, + claimLogin, +} from "./session"; import { loadGroups, - saveGroups, + createGroup, + updateGroup, resolveScope, hasAnyAccess, ensureInstallationGroup, normalizeGroupMembers, roleAt, + bindMemberIds, + memberRole, } from "./groups"; +import { log } from "../lib/log"; +import { idempotencyStore, recordStatement, unrecordedGuard } from "../lib/idempotency"; import { clientIp } from "./auth"; import { recordAudit } from "../lib/audit"; import { sendMessage } from "../drivers/telegram/rest"; @@ -32,9 +45,22 @@ import { cfEnv } from "../cf"; import { initConfigStore } from "../config"; import type { Env, Group } from "../types"; +/** Which chat account a bot `/gh login` link binds, with a name to show. */ +interface PendingLink { + platform: "discord" | "telegram" | "feishu"; + userId: string; + /** Display name of the chat account, shown on the confirmation page. */ + name?: string; + /** Chat to notify once the link is confirmed (Telegram / Feishu). */ + chatId?: string; +} + interface PendingState { redirectTo: string; expiresAt: number; + /** Set when the flow was started by a bot command instead of a browser login. */ + link?: PendingLink; + // Legacy shapes of `link`, still accepted for states created before it. discordUserId?: string; telegramUserId?: string; telegramChatId?: string; @@ -42,8 +68,75 @@ interface PendingState { feishuChatId?: string; } -function linkedPage(login: string): string { - return `绑定成功
✓

GitHub 账号已绑定

已连接为 @${login},现在可以回到 Discord 用 GitHub 评论了。

`; +/** A confirmed OAuth identity waiting for the user to approve a bot link. */ +interface LinkConfirmation extends PendingLink { + githubUserId: string; + login: string; +} + +const STATE_COOKIE = "wh_oauth_state"; +const STATE_TTL = 600; +const LINK_TTL = 600; + +function stateCookie(state: string): string { + return `${STATE_COOKIE}=${state}; Path=/auth/github; HttpOnly; Secure; SameSite=Lax; Max-Age=${STATE_TTL}`; +} + +function clearStateCookie(): string { + return `${STATE_COOKIE}=; Path=/auth/github; HttpOnly; Secure; SameSite=Lax; Max-Age=0`; +} + +function cookieValue(header: string | undefined, name: string): string | undefined { + for (const part of (header ?? "").split(";")) { + const idx = part.indexOf("="); + if (idx !== -1 && part.slice(0, idx).trim() === name) return part.slice(idx + 1).trim(); + } + return undefined; +} + +function pendingLink(pending: PendingState): PendingLink | null { + if (pending.link) return pending.link; + if (pending.discordUserId) return { platform: "discord", userId: pending.discordUserId }; + if (pending.telegramUserId) { + return { + platform: "telegram", + userId: pending.telegramUserId, + chatId: pending.telegramChatId, + }; + } + if (pending.feishuUserId) { + return { platform: "feishu", userId: pending.feishuUserId, chatId: pending.feishuChatId }; + } + return null; +} + +const PAGE_STYLE = + "body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;font-family:system-ui,-apple-system,'Segoe UI',sans-serif;background:#f6f7f9;color:#1f2328}.card{background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:28px 32px;width:min(480px,92vw);box-sizing:border-box;text-align:center;box-shadow:0 1px 3px rgba(0,0,0,.06)}.ok{color:#16a34a;font-size:40px}h1{font-size:18px;margin:12px 0 6px}p{color:#57606a;font-size:14px;margin:6px 0}b{color:#1f2328}.btn{display:inline-block;margin-top:16px;background:#1f2328;color:#fff;border:0;border-radius:8px;padding:10px 18px;font-size:14px;cursor:pointer}.btn:hover{background:#32383f}.warn{color:#b45309;font-size:13px}"; + +const PLATFORM_NAMES: Record = { + discord: "Discord", + telegram: "Telegram", + feishu: "飞书", +}; + +function linkedPage(login: string, platform: PendingLink["platform"]): string { + return `绑定成功
✓

GitHub 账号已绑定

已连接为 @${escapeHtml(login)},现在可以回到 ${PLATFORM_NAMES[platform]} 用 GitHub 评论了。

`; +} + +/** + * Asks the GitHub user to approve the binding before it happens: a `/gh + * login` link may have been forwarded, so the page names both accounts and + * nothing is linked until this user confirms. + */ +function confirmLinkPage(nonce: string, link: LinkConfirmation): string { + const chatAccount = link.name + ? `${escapeHtml(link.name)}(ID ${escapeHtml(link.userId)})` + : `ID ${escapeHtml(link.userId)}`; + return `确认绑定

确认绑定 GitHub 账号

将 GitHub 账号 @${escapeHtml(link.login)}

绑定到 ${PLATFORM_NAMES[link.platform]} 账号 ${chatAccount}?

绑定后,该 ${PLATFORM_NAMES[link.platform]} 账号可以用你的 GitHub 身份评论、合并或关闭 PR。若这个链接不是你本人发起的,请直接关闭本页。

`; +} + +function messagePage(title: string, text: string): string { + return `${escapeHtml(title)}

${escapeHtml(title)}

${escapeHtml(text)}

`; } function generateRandomHex(length: number): string { @@ -54,12 +147,26 @@ function generateRandomHex(length: number): string { .join(""); } -function safeRedirectPath(value: string | undefined): string { +export function safeRedirectPath(value: string | undefined): string { if (!value) return "/"; if (!value.startsWith("/")) return "/"; if (value.startsWith("//")) return "/"; if (/^\/\\/.test(value)) return "/"; - return value; + // Browsers drop tabs and line breaks from URLs (`/\t/evil.example` becomes + // `//evil.example`): refused, and the path is checked as a browser reads + // it — it must stay on this origin, and only that normalized path is used. + if (/[\u0000-\u001f\u007f]/.test(value)) return "/"; + const base = "https://webhooker.invalid"; + let url: URL; + try { + url = new URL(value, base); + } catch { + return "/"; + } + // Dot segments can normalize into `//host` (`/a/..//evil.example`): read + // again, that would leave the site. + if (url.origin !== base || url.pathname.startsWith("//")) return "/"; + return `${url.pathname}${url.search}${url.hash}`; } function escapeHtml(s: string): string { @@ -79,19 +186,22 @@ function selfSignupEnabled(env: Env): boolean { * Opt-in self service: users without any group access get a personal group * they own, so they can configure their own routing without a super admin. * The group id is deterministic (`u-{userId}`), so it is created at most once. + * Personal groups are isolated: only their own `/webhook/{groupId}` ingress + * dispatches to them, never the operator's global endpoint. */ async function ensurePersonalGroup(env: Env, userId: string, login: string): Promise { if (!selfSignupEnabled(env)) return false; - const groups = await loadGroups(env.KV); const gid = `u-${userId}`; - if (groups.some((g) => g.id === gid)) return true; const personal: Group = { id: gid, name: `@${login}`, - members: [{ login, role: "owner" }], + members: [{ login, role: "owner", userId }], adminIds: [login], + isolated: true, }; - await saveGroups(env.KV, [...groups, personal]); + if (!(await createGroup(env.KV, personal))) return true; + // Filed under the instance the server gave the group (it follows renames). + const stored = (await loadGroups(env.KV, { fresh: true })).find((g) => g.id === gid); await recordAudit(env.DB, { ts: Date.now(), actorId: userId, @@ -100,6 +210,7 @@ async function ensurePersonalGroup(env: Env, userId: string, login: string): Pro targetType: "group", targetId: gid, groupId: gid, + groupInstance: stored?.instance, detail: { auto: true }, }); return true; @@ -131,6 +242,29 @@ function installPage(opts: { return `安装 GitHub App

GitHub App 安装成功

${accountLine}

将安装绑定到哪个分组?建议直接创建新分组,之后可以在控制台添加路由与成员。

${ownedNote}${ownedOptions}
`; } +/** + * Whether the signed-in user may bind this installation. Super admins (the + * operator) may; everyone else must prove access with their own GitHub token, + * because the Setup URL's `installation_id` can be set to anything. + */ +async function canManageInstallation( + env: Env, + session: { userId: string; login: string }, + installationId: number, +): Promise<{ ok: boolean; accountLogin: string }> { + const account = await getInstallationDetails( + env.GITHUB_APP_ID ?? "", + env.GITHUB_PRIVATE_KEY ?? "", + installationId, + ); + const accountLogin = account?.login ?? ""; + if (isAdminUser(env, session.userId, authLogin(session))) return { ok: true, accountLogin }; + const token = await getToken(env, session.userId); + if (!token) return { ok: false, accountLogin }; + const ok = await userManagesInstallation(token, session.userId, installationId, account); + return { ok, accountLogin }; +} + /** GET /auth/github — start the OAuth flow. */ export async function handleOAuthStart(event: H3Event): Promise { const env = cfEnv(event); @@ -140,9 +274,12 @@ export async function handleOAuthStart(event: H3Event): Promise { const state = generateRandomHex(16); const pending: PendingState = { redirectTo, - expiresAt: Date.now() + 10 * 60 * 1000, + expiresAt: Date.now() + STATE_TTL * 1000, }; - await env.KV.put(`state:${state}`, JSON.stringify(pending), { expirationTtl: 600 }); + await env.KV.put(`state:${state}`, JSON.stringify(pending), { expirationTtl: STATE_TTL }); + // Binds the flow to this browser: the callback only signs in the browser + // that started it (no login CSRF with a callback URL from another session). + appendResponseHeader(event, "Set-Cookie", stateCookie(state)); await sendRedirect(event, getOAuthURL(env.GITHUB_CLIENT_ID ?? "", state)); } @@ -156,29 +293,28 @@ export async function handleInstallPage(event: H3Event): Promise if (!rawId || !Number.isInteger(installationId) || installationId <= 0) { throw createError({ statusCode: 400, statusMessage: "Missing installation_id" }); } - const session = await getAdminSession(env.KV, getHeader(event, "cookie")); + const session = await getAdminSession(env.KV, getHeader(event, "cookie"), env.DB); if (!session) { const target = `/auth/github/install?installation_id=${installationId}`; await sendRedirect(event, `/auth/github?redirect=${encodeURIComponent(target)}`); return; } - const accountLogin = - (await getInstallationAccount( - env.GITHUB_APP_ID ?? "", - env.GITHUB_PRIVATE_KEY ?? "", - installationId, - )) ?? ""; - const groups = await loadGroups(env.KV); - const scope = resolveScope(env, groups, session.userId, session.login); + const access = await canManageInstallation(env, session, installationId); + if (!access.ok) { + await sendRedirect(event, "/admin?error=install-forbidden"); + return; + } + const groups = await loadGroups(env.KV, { fresh: true }); + const scope = resolveScope(env, groups, session.userId, authLogin(session)); const owned = groups.filter((g) => roleAt(scope, g.id) === "owner"); - return installPage({ installationId, accountLogin, owned }); + return installPage({ installationId, accountLogin: access.accountLogin, owned }); } /** POST /auth/github/install/bind — provision the chosen binding. */ export async function handleInstallBind(event: H3Event): Promise { const env = cfEnv(event); initConfigStore(env); - const session = await getAdminSession(env.KV, getHeader(event, "cookie")); + const session = await getAdminSession(env.KV, getHeader(event, "cookie"), env.DB); if (!session) { await sendRedirect(event, "/admin?error=forbidden"); return; @@ -189,49 +325,60 @@ export async function handleInstallBind(event: H3Event): Promise { if (!Number.isInteger(installationId) || installationId <= 0) { throw createError({ statusCode: 400, statusMessage: "Missing installation_id" }); } + const access = await canManageInstallation(env, session, installationId); + if (!access.ok) { + await sendRedirect(event, "/admin?error=install-forbidden"); + return; + } + const accountLogin = access.accountLogin; const chosenGroupId = String(body["group"] ?? "").trim(); - const groups = await loadGroups(env.KV); - const scope = resolveScope(env, groups, session.userId, session.login); + const groups = await loadGroups(env.KV, { fresh: true }); + const scope = resolveScope(env, groups, session.userId, authLogin(session)); - const bind = async (groupId: string, group: Group | null): Promise => { - if (!group) { + if (chosenGroupId) { + // Binding to an existing group requires owner permission on it. + if (!groups.some((g) => g.id === chosenGroupId) || roleAt(scope, chosenGroupId) !== "owner") { + await sendRedirect(event, "/admin?error=forbidden"); + return; + } + // Still an owner of the group as it is now (the write is a CAS on it). + let revoked = false; + const bound = await updateGroup(env.KV, chosenGroupId, (g) => { + const owner = + isAdminUser(env, session.userId, authLogin(session)) || + memberRole(g, session.userId, authLogin(session)) === "owner"; + if (!owner) { + revoked = true; + return null; + } + return { ...g, installationId }; + }); + if (revoked) { + await sendRedirect(event, "/admin?error=forbidden"); + return; + } + if (!bound) { await sendRedirect(event, "/admin?error=install"); return; } - const next = groups.map((g) => (g.id === group.id ? { ...g, installationId } : g)); - await saveGroups(env.KV, next); await recordAudit(env.DB, { ts: Date.now(), actorId: session.userId, actorLogin: session.login, action: "installation.bind", targetType: "group", - targetId: groupId, - groupId, + targetId: chosenGroupId, + groupId: chosenGroupId, + groupInstance: bound.instance, detail: { installationId }, ip: clientIp(event), }); await sendRedirect(event, "/admin?install=ok"); - }; - - if (chosenGroupId) { - // Binding to an existing group requires owner permission on it. - const group = groups.find((g) => g.id === chosenGroupId); - if (!group || roleAt(scope, chosenGroupId) !== "owner") { - await sendRedirect(event, "/admin?error=forbidden"); - return; - } - return bind(chosenGroupId, group); + return; } // Default: auto-create a dedicated inst-{id} group. - const accountLogin = - (await getInstallationAccount( - env.GITHUB_APP_ID ?? "", - env.GITHUB_PRIVATE_KEY ?? "", - installationId, - )) ?? ""; - const group = await ensureInstallationGroup(env.KV, installationId, accountLogin); + const group = await ensureInstallationGroup(env.KV, installationId, accountLogin, env.DB); if (!group) { await sendRedirect(event, "/admin?error=install"); return; @@ -244,27 +391,29 @@ export async function handleInstallBind(event: H3Event): Promise { targetType: "group", targetId: group.id, groupId: group.id, + groupInstance: group.instance, detail: { source: "setup_url", account: accountLogin || undefined }, ip: clientIp(event), }); - // Self-service SaaS: the installer manages their own auto-created group. - if (selfSignupEnabled(env)) { - const members = normalizeGroupMembers(group); - const alreadyMember = members.some( - (m) => m.login.toLowerCase() === session.login.toLowerCase() || m.login === session.userId, - ); - if (!alreadyMember) { - const updated: Group = { - ...group, - members: [...members, { login: session.login, role: "owner" }], - adminIds: [...new Set([...(group.adminIds ?? []), session.login])], + // Self-service SaaS: the verified installer manages the group created for + // their installation — only the dedicated `inst-{id}` group, only while it is + // still bound to this installation, and only while nobody manages it yet. + // Any other group (an org group bound via `owners`, an operator group, one + // claimed earlier) is never handed to a new owner this way. + if (selfSignupEnabled(env) && group.id === `inst-${installationId}`) { + let added = false; + await updateGroup(env.KV, group.id, (g) => { + const members = normalizeGroupMembers(g); + if (g.installationId !== installationId || members.length > 0) return null; + added = true; + return { + ...g, + members: [{ login: session.login, role: "owner", userId: session.userId }], + adminIds: [session.login], }; - const all = await loadGroups(env.KV); - await saveGroups( - env.KV, - all.map((g) => (g.id === group.id ? updated : g)), - ); + }); + if (added) { await recordAudit(env.DB, { ts: Date.now(), actorId: session.userId, @@ -273,6 +422,7 @@ export async function handleInstallBind(event: H3Event): Promise { targetType: "group", targetId: group.id, groupId: group.id, + groupInstance: group.instance, detail: { login: session.login, role: "owner", auto: true }, ip: clientIp(event), }); @@ -300,12 +450,19 @@ export async function handleOAuthCallback(event: H3Event): Promise { return { error: "Invalid or expired state" }; } const pending = raw as PendingState; + await env.KV.delete(`state:${state}`); if (Date.now() > pending.expiresAt) { - await env.KV.delete(`state:${state}`); setResponseStatus(event, 400); return { error: "Invalid or expired state" }; } - await env.KV.delete(`state:${state}`); + const link = pendingLink(pending); + // A browser sign-in must come back to the browser that started it. Bot + // links are opened elsewhere by design; they are confirmed explicitly below. + if (!link && cookieValue(getHeader(event, "cookie"), STATE_COOKIE) !== state) { + setResponseStatus(event, 400); + return { error: "Invalid or expired state" }; + } + if (!link) appendResponseHeader(event, "Set-Cookie", clearStateCookie()); const result = await handleGithubOAuthCallback( env.GITHUB_CLIENT_ID ?? "", @@ -313,47 +470,24 @@ export async function handleOAuthCallback(event: H3Event): Promise { code, state, env.KV, + env.DB, ); if (!result) { setResponseStatus(event, 400); return { error: "OAuth failed" }; } - // Discord account-linking flow: bind the Discord user to this GitHub account. - if (pending.discordUserId) { - await saveDiscordLink(env.DB, pending.discordUserId, result.userId); - const isBrowserLink = (getHeader(event, "accept") ?? "").includes("text/html"); - if (isBrowserLink) return linkedPage(result.login); - return { ok: true, discordUserId: pending.discordUserId, login: result.login }; - } - - // Telegram account-linking flow: bind the Telegram user to this GitHub account. - if (pending.telegramUserId) { - await saveTelegramLink(env.DB, pending.telegramUserId, result.userId); - if (pending.telegramChatId && env.TELEGRAM_TOKEN) { - await sendMessage( - env.TELEGRAM_TOKEN, - pending.telegramChatId, - `✅ GitHub 账号已绑定:**@${result.login}**。现在可以用 /gh comment 评论了。`, - ).catch(() => undefined); - } - return { ok: true, telegramUserId: pending.telegramUserId, login: result.login }; - } - - // Feishu account-linking flow: bind the Feishu user to this GitHub account. - if (pending.feishuUserId) { - await saveFeishuLink(env.DB, pending.feishuUserId, result.userId); - if (pending.feishuChatId) { - const tokenRes = await getTenantAccessToken(env); - if (tokenRes.ok && tokenRes.token) { - await sendFeishuText( - tokenRes.token, - pending.feishuChatId, - `✅ GitHub 账号已绑定:**@${result.login}**。现在可以用 /gh comment 评论了。`, - ).catch(() => undefined); - } - } - return { ok: true, feishuUserId: pending.feishuUserId, login: result.login }; + // Bot account linking: never bind on the callback itself. The person who + // authorized GitHub confirms which chat account gets their identity. + if (link) { + const nonce = generateRandomHex(16); + const confirmation: LinkConfirmation = { + ...link, + githubUserId: result.userId, + login: result.login, + }; + await env.KV.put(`link:${nonce}`, JSON.stringify(confirmation), { expirationTtl: LINK_TTL }); + return confirmLinkPage(nonce, confirmation); } const isBrowser = (getHeader(event, "accept") ?? "").includes("text/html"); @@ -365,14 +499,17 @@ export async function handleOAuthCallback(event: H3Event): Promise { pending.redirectTo.startsWith("/admin/invite") || pending.redirectTo.startsWith("/admin/invite?"); - let groups = await loadGroups(env.KV); - let scope = resolveScope(env, groups, result.userId, result.login); + let groups = await loadGroups(env.KV, { fresh: true }); + // A login first seen with another account grants nothing by name. + const trusted = await claimLogin(env.KV, result.userId, result.login); + const name = trusted ? result.login : ""; + let scope = resolveScope(env, groups, result.userId, name); if (!hasAnyAccess(scope) && !isInviteFlow) { const created = await ensurePersonalGroup(env, result.userId, result.login); if (created) { - groups = await loadGroups(env.KV); - scope = resolveScope(env, groups, result.userId, result.login); + groups = await loadGroups(env.KV, { fresh: true }); + scope = resolveScope(env, groups, result.userId, name); } } if (!hasAnyAccess(scope) && !isInviteFlow) { @@ -380,7 +517,13 @@ export async function handleOAuthCallback(event: H3Event): Promise { return; } - const sessionId = await createAdminSession(env.KV, result.userId, result.login); + // Tie the member entries naming this login to the account itself. + if (trusted) { + await bindMemberIds(env.KV, groups, result.userId, result.login).catch((err: unknown) => + log.warn({ err, userId: result.userId }, "Failed to bind member ids"), + ); + } + const sessionId = await createAdminSession(env.KV, result.userId, result.login, trusted); appendResponseHeader(event, "Set-Cookie", adminCookie(sessionId)); await recordAudit(env.DB, { ts: Date.now(), @@ -400,15 +543,77 @@ export async function handleOAuthCallback(event: H3Event): Promise { }; } -/** DELETE /auth/token/:userId — revoke a stored user token. */ +/** POST /auth/github/link — the GitHub user approved a bot account link. */ +export async function handleLinkConfirm(event: H3Event): Promise { + const env = cfEnv(event); + const body = (await readBody(event).catch(() => ({}))) as Record; + const nonce = String(body["nonce"] ?? ""); + const raw = /^[0-9a-f]{32}$/.test(nonce) ? await env.KV.get(`link:${nonce}`, "json") : null; + // One use, recorded in D1: a replayed confirmation (or a stale KV copy + // elsewhere) can never restore a link that was undone or replaced since. + const claims = idempotencyStore(env.DB, env.KV); + const usedKey = `link-used:${nonce}`; + const expired = (): string => { + setResponseStatus(event, 400); + return messagePage("链接已失效", "请回到聊天里重新发送 /gh login。"); + }; + if (!raw || (await claims.has(usedKey))) return expired(); + const link = raw as LinkConfirmation; + const notice = `✅ GitHub 账号已绑定:@${link.login}。现在可以用 /gh comment 评论了。`; + // The link and its one-use record commit in one transaction, refused once + // the record exists: a replay can never restore a link undone or replaced + // since — not even after a write whose answer was lost (the record then + // tells it went through). A failure before the commit leaves the pending + // link, so submitting it again works. + try { + await env.DB.batch([ + unrecordedGuard(env.DB, usedKey), + recordStatement(env.DB, usedKey, LINK_TTL), + linkStatement(env.DB, link.platform, link.userId, link.githubUserId), + ]); + } catch (err) { + if (!(await claims.has(usedKey).catch(() => false))) throw err; + // Recorded: committed here (its answer lost), or by a concurrent submit. + if (/already recorded|malformed JSON/i.test(String(err))) return expired(); + } + await env.KV.delete(`link:${nonce}`).catch(() => undefined); + if (link.platform === "telegram") { + if (link.chatId && env.TELEGRAM_TOKEN) { + await sendMessage(env.TELEGRAM_TOKEN, link.chatId, escapeHtml(notice)).catch(() => undefined); + } + } else if (link.platform === "feishu") { + if (link.chatId) { + const tokenRes = await getTenantAccessToken(env); + if (tokenRes.ok && tokenRes.token) { + await sendFeishuText(tokenRes.token, link.chatId, notice).catch(() => undefined); + } + } + } + await recordAudit(env.DB, { + ts: Date.now(), + actorId: link.githubUserId, + actorLogin: link.login, + action: "account.link", + targetType: link.platform, + targetId: link.userId, + ip: clientIp(event), + }); + return linkedPage(link.login, link.platform); +} + +/** DELETE /auth/token/:userId — revoke a stored user token (own token, or any for super admins). */ export async function handleTokenDelete(event: H3Event, userId: string): Promise { const env = cfEnv(event); - const session = await getAdminSession(env.KV, getHeader(event, "cookie")); + const session = await getAdminSession(env.KV, getHeader(event, "cookie"), env.DB); if (!session) { setResponseStatus(event, 401); return { error: "Unauthorized" }; } - await removeToken(env.KV, userId); + if (session.userId !== userId && !isAdminUser(env, session.userId, authLogin(session))) { + setResponseStatus(event, 403); + return { error: "Forbidden" }; + } + await removeToken(env.KV, userId, env.DB); await recordAudit(env.DB, { ts: Date.now(), actorId: session.userId, diff --git a/server/routes/auth/github/link.post.ts b/server/routes/auth/github/link.post.ts new file mode 100644 index 0000000..916bc61 --- /dev/null +++ b/server/routes/auth/github/link.post.ts @@ -0,0 +1,3 @@ +import { handleLinkConfirm } from "../../../lib/web/oauth"; + +export default defineEventHandler((event) => handleLinkConfirm(event)); diff --git a/tests/install.test.ts b/tests/install.test.ts index b2e8993..0eb1413 100644 --- a/tests/install.test.ts +++ b/tests/install.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeEach, afterEach } from "bun:test"; +import { describe, it, expect, beforeAll, beforeEach, afterEach } from "bun:test"; import { handleOAuthStart, handleInstallPage, @@ -9,6 +9,7 @@ import { import { createAdminSession, adminCookie } from "../server/lib/web/session"; import { loadGroups, invalidateGroupsCache } from "../server/lib/web/groups"; import { getInstallationAccount } from "../server/lib/github/oauth"; +import { saveToken } from "../server/lib/github/store"; import { makeEvent, responseStatus, responseHeader } from "./helpers"; import type { Env } from "../server/lib/types"; @@ -46,15 +47,42 @@ function createMockDB(): D1Database { } as unknown as D1Database; } +/** App credentials, so the install flow can look the installation's account up. */ +let appCredentials: Partial = {}; + function createEnv(overrides: Partial = {}): Env { return { GITHUB_WEBHOOK_SECRET: "secret", KV: createMockKV(), DB: createMockDB(), + ...appCredentials, ...overrides, }; } +/** The signed-in test user's role in the installation's organization. */ +let orgRole = "admin"; + +/** GitHub API stub: the installation lookup and the user's org membership. */ +function githubApiMock(input: RequestInfo | URL): Promise { + const url = String(input); + const body = url.includes("/user/memberships/orgs/myorg") + ? { state: "active", role: orgRole } + : { id: 555, account: { login: "myorg", id: 9, type: "Organization" } }; + return Promise.resolve( + new Response(JSON.stringify(body), { + status: 200, + headers: { "content-type": "application/json" }, + }), + ); +} + +/** A session for alice (GitHub id 1001) with a stored OAuth token. */ +async function signIn(kv: KVNamespace): Promise { + await saveToken(kv, "1001", "gho_alice", 3600); + return adminCookie(await createAdminSession(kv, "1001", "alice")); +} + function bufToPem(buf: ArrayBuffer): string { const bytes = new Uint8Array(buf); let s = ""; @@ -122,17 +150,15 @@ describe("getInstallationAccount", () => { describe("GET /auth/github/install", () => { const restoredFetch = globalThis.fetch; + beforeAll(async () => { + const { appId, pem } = await makeAppKeyPair(); + appCredentials = { GITHUB_APP_ID: appId, GITHUB_PRIVATE_KEY: pem }; + }); + beforeEach(() => { invalidateGroupsCache(); - globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise => { - void init; - return Promise.resolve( - new Response(JSON.stringify({ id: 555, account: { login: "myorg" } }), { - status: 200, - headers: { "content-type": "application/json" }, - }), - ); - }; + orgRole = "admin"; + globalThis.fetch = githubApiMock; }); afterEach(() => { @@ -172,10 +198,10 @@ describe("GET /auth/github/install", () => { ]), ); const env = createEnv({ KV: kv }); - const sessionId = await createAdminSession(kv, "1001", "alice"); + const cookie = await signIn(kv); const event = makeEvent("/auth/github/install?installation_id=555&setup_action=install", { - headers: { cookie: adminCookie(sessionId), accept: "text/html" }, + headers: { cookie, accept: "text/html" }, env, }); const html = (await handleInstallPage(event)) as string; @@ -185,6 +211,19 @@ describe("GET /auth/github/install", () => { expect(html).not.toContain('value="theirs"'); }); + it("refuses an installation the user cannot manage", async () => { + const kv = createMockKV(); + orgRole = "member"; + const env = createEnv({ KV: kv }); + const cookie = await signIn(kv); + const event = makeEvent("/auth/github/install?installation_id=555", { + headers: { cookie, accept: "text/html" }, + env, + }); + await handleInstallPage(event); + expect(responseHeader(event, "location")).toBe("/admin?error=install-forbidden"); + }); + it("rejects a missing installation id", async () => { const env = createEnv(); const event = makeEvent("/auth/github/install", { headers: { accept: "text/html" }, env }); @@ -197,15 +236,8 @@ describe("POST /auth/github/install/bind", () => { beforeEach(() => { invalidateGroupsCache(); - globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise => { - void init; - return Promise.resolve( - new Response(JSON.stringify({ id: 555, account: { login: "myorg" } }), { - status: 200, - headers: { "content-type": "application/json" }, - }), - ); - }; + orgRole = "admin"; + globalThis.fetch = githubApiMock; }); afterEach(() => { @@ -242,9 +274,9 @@ describe("POST /auth/github/install/bind", () => { ]), ); const env = createEnv({ KV: kv }); - const sessionId = await createAdminSession(kv, "1001", "alice"); + const cookie = await signIn(kv); - const event = bindEvent(env, adminCookie(sessionId), { installation_id: "555", group: "mine" }); + const event = bindEvent(env, cookie, { installation_id: "555", group: "mine" }); await handleInstallBind(event); expect(responseStatus(event)).toBe(302); expect(responseHeader(event, "location")).toBe("/admin?install=ok"); @@ -269,9 +301,9 @@ describe("POST /auth/github/install/bind", () => { ]), ); const env = createEnv({ KV: kv }); - const sessionId = await createAdminSession(kv, "1001", "alice"); + const cookie = await signIn(kv); - const event = bindEvent(env, adminCookie(sessionId), { + const event = bindEvent(env, cookie, { installation_id: "555", group: "theirs", }); @@ -292,9 +324,9 @@ describe("POST /auth/github/install/bind", () => { GITHUB_APP_ID: appId, GITHUB_PRIVATE_KEY: pem, }); - const sessionId = await createAdminSession(kv, "1001", "alice"); + const cookie = await signIn(kv); - const event = bindEvent(env, adminCookie(sessionId), { installation_id: "555", group: "" }); + const event = bindEvent(env, cookie, { installation_id: "555", group: "" }); await handleInstallBind(event); expect(responseStatus(event)).toBe(302); expect(responseHeader(event, "location")).toBe("/admin?install=ok"); @@ -304,15 +336,61 @@ describe("POST /auth/github/install/bind", () => { expect(group).toBeDefined(); expect(group?.installationId).toBe(555); expect(group?.name).toBe("myorg"); - expect(group?.members).toContainEqual({ login: "alice", role: "owner" }); + expect(group?.members).toContainEqual({ + login: "alice", + role: "owner", + userId: expect.any(String), + }); + }); + + it("refuses to bind an installation the user cannot manage", async () => { + const kv = createMockKV(); + orgRole = "member"; + await kv.put( + "config:groups", + JSON.stringify([ + { id: "mine", name: "Mine", adminIds: [], members: [{ login: "alice", role: "owner" }] }, + ]), + ); + const env = createEnv({ KV: kv, ALLOW_SELF_SIGNUP: "1" }); + const cookie = await signIn(kv); + for (const group of ["mine", ""]) { + const event = bindEvent(env, cookie, { installation_id: "555", group }); + await handleInstallBind(event); + expect(responseHeader(event, "location")).toBe("/admin?error=install-forbidden"); + } + const groups = await loadGroups(kv); + expect(groups.map((g) => [g.id, g.installationId])).toEqual([["mine", undefined]]); + }); + + it("never makes the installer an owner of a group someone already manages", async () => { + const kv = createMockKV(); + await kv.put( + "config:groups", + JSON.stringify([ + { + id: "inst-555", + name: "Taken", + adminIds: [], + installationId: 555, + members: [{ login: "bob", role: "owner" }], + }, + ]), + ); + const env = createEnv({ KV: kv, ALLOW_SELF_SIGNUP: "1" }); + const cookie = await signIn(kv); + const event = bindEvent(env, cookie, { installation_id: "555", group: "" }); + await handleInstallBind(event); + const group = (await loadGroups(kv)).find((g) => g.id === "inst-555"); + expect(group?.members).toEqual([{ login: "bob", role: "owner" }]); }); it("auto-creates inst-{id} without joining members when self-signup is off", async () => { const kv = createMockKV(); const env = createEnv({ KV: kv }); - const sessionId = await createAdminSession(kv, "1001", "alice"); + const cookie = await signIn(kv); - const event = bindEvent(env, adminCookie(sessionId), { installation_id: "555", group: "" }); + const event = bindEvent(env, cookie, { installation_id: "555", group: "" }); await handleInstallBind(event); expect(responseStatus(event)).toBe(302); const groups = await loadGroups(kv); @@ -360,4 +438,42 @@ describe("oauth misc", () => { expect(responseStatus(event)).toBe(401); expect(result.error).toBe("Unauthorized"); }); + + it("lets users delete only their own token", async () => { + const kv = createMockKV(); + const env = createEnv({ KV: kv }); + const cookie = await signIn(kv); + await saveToken(kv, "2002", "gho_bob", 3600); + const other = makeEvent("/auth/token/2002", { method: "DELETE", headers: { cookie }, env }); + await handleTokenDelete(other, "2002"); + expect(responseStatus(other)).toBe(403); + expect(await kv.get("token:2002")).not.toBeNull(); + const own = makeEvent("/auth/token/1001", { method: "DELETE", headers: { cookie }, env }); + await handleTokenDelete(own, "1001"); + expect(responseStatus(own)).toBe(200); + expect(await kv.get("token:1001")).toBeNull(); + }); + + it("rejects a browser callback whose state was started in another browser", async () => { + const kv = createMockKV(); + const env = createEnv({ KV: kv }); + await kv.put( + "state:abc", + JSON.stringify({ redirectTo: "/admin", expiresAt: Date.now() + 60_000 }), + ); + const event = makeEvent("/auth/github/callback?code=c&state=abc", { + headers: { accept: "text/html" }, + env, + }); + const result = (await handleOAuthCallback(event)) as { error?: string }; + expect(responseStatus(event)).toBe(400); + expect(result.error).toBe("Invalid or expired state"); + }); + + it("sets the state cookie when starting the flow", async () => { + const env = createEnv({ GITHUB_CLIENT_ID: "client-1" }); + const event = makeEvent("/auth/github?redirect=/admin", { env }); + await handleOAuthStart(event); + expect(String(responseHeader(event, "set-cookie"))).toContain("wh_oauth_state="); + }); });