Public: anyone can read this; the crew can change it.

open-platform.sh sign-in is a linked method, not a back door: it never creates an account outside the signup rules #744

Closed opened this in answer to
Closed without merging

mason/forge:mason/668-open-platform-sh-sign-in-is-a-linked-met → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
16 files changed +529 −79
src/core/event_audience.ts +8 −1
@@ -35,7 +35,14 @@ export function eventAudience(kind: string): EventAudience {
3535 )
3636 return "admins";
3737 // A fleet operation spans repositories; its receipt is its actor's.
38 if (kind === "repo.pinned" || kind === "repo.unpinned" || kind.startsWith("fleet."))
38 // So is linking a sign-in method: how one person gets in is theirs.
39 if (
40 kind === "repo.pinned" ||
41 kind === "repo.unpinned" ||
42 kind.startsWith("fleet.") ||
43 kind === "user.linked" ||
44 kind === "user.unlinked"
45 )
3946 return "actor";
4047 return "readers";
4148 }
src/core/schema.ts +17
@@ -1215,4 +1215,21 @@ export const migrations: readonly string[] = [
12151215 );
12161216 CREATE INDEX IF NOT EXISTS report_waiting ON report(repo_id, state, id);
12171217 `,
1218 // 48 — linked sign-in methods (`core/links.ts`, #668). The edge no longer
1219 // matches a login to an account by name, so every account it made before
1220 // this — the ones without a password, which nothing but the edge creates —
1221 // keeps its way in as a link written down here.
1222 `
1223 CREATE TABLE IF NOT EXISTS user_link (
1224 method TEXT NOT NULL CHECK (method IN ('edge')),
1225 subject TEXT NOT NULL,
1226 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
1227 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1228 PRIMARY KEY (method, subject)
1229 );
1230 CREATE UNIQUE INDEX IF NOT EXISTS user_link_one ON user_link(user_id, method);
1231 INSERT OR IGNORE INTO user_link (method, subject, user_id, created_at)
1232 SELECT 'edge', lower(username), id, created_at FROM user
1233 WHERE kind = 'user' AND is_agent = 0 AND password_hash = '';
1234 `,
12181235 ];
src/core/users.ts +3 −29
@@ -5,8 +5,6 @@
55
66 import type { Database } from "bun:sqlite";
77 import { isSafeName } from "../git/guard.ts";
8 import { noreplyAddress } from "./commit_identity.ts";
9 import { reservedName } from "./reserved.ts";
108 import { id } from "../kernel/id.ts";
119 import { err, ok, type Result } from "../kernel/result.ts";
1210
@@ -75,8 +73,9 @@ export interface CreateUserInput {
7573 username: string;
7674 email: string;
7775 /**
78 * Absent, no password is stored and none ever verifies: the account is
79 * signed in by something that vouches for it — the platform edge.
76 * Absent, no password is stored and none ever verifies. Signup always
77 * gives one; the accounts without are those the platform edge made before
78 * it became a linked method (#668), signed in by their link.
8079 */
8180 password?: string;
8281 /** @default "" */
@@ -249,31 +248,6 @@ export function getUserByName(
249248 return row ? toUser(row) : undefined;
250249 }
251250
252 /**
253 * The person behind an identity the platform edge vouched for: found by
254 * name, or made on first sight — with no password, because the edge is how
255 * they sign in, and a noreply address until they set one. The first account
256 * on a fresh forge is the admin, exactly as at sign-up. A name that is an
257 * organization or a crew member here is nobody's login.
258 */
259 export async function ensureEdgeUser(
260 db: Database,
261 login: string,
262 host: string,
263 ): Promise<User | undefined> {
264 const existing = getUserByName(db, login);
265 if (existing) return existing.kind === "user" ? existing : undefined;
266 // The edge vouches for a login, not for its right to a name: a platform
267 // account called after the crew or the owner is not let in under it.
268 if (reservedName(db, login) !== undefined) return undefined;
269 const made = await createUser(db, {
270 username: login,
271 email: noreplyAddress(login, host),
272 adminIfFirst: true,
273 });
274 return made.ok ? made.value : undefined;
275 }
276
277251 /** Constant-shape verification: always burns an argon2 verify, hit or miss. */
278252 export async function verifyPassword(
279253 db: Database,
src/http/context.ts +7
@@ -17,6 +17,13 @@ export interface Auth {
1717 readonly scope: TokenScope | undefined;
1818 /** `edge`: the platform in front of the forge signed this person in. */
1919 readonly via: "session" | "edge" | "token" | "password" | "none";
20 /**
21 * The identity the platform edge vouched for on this request, linked to
22 * an account or not. Present with `via` other than `edge`, it is a person
23 * the edge knows whom no account here has linked (`core/links.ts`): they
24 * sign up or sign in the forge's own way, and may then link it.
25 */
26 readonly edge?: string;
2027 }
2128
2229 export interface Ctx {
src/http/edge.ts +23
@@ -6,9 +6,15 @@
66 * signed in by the platform. Without the secret the headers are a claim
77 * anyone could write, and they are ignored. Signing in and out are the
88 * edge's own entry points on this host.
9 *
10 * The edge is a linked method, not a way to make an account (#668): the
11 * identity it vouches for reaches only the account that linked it
12 * (`core/links.ts`), and a person it knows whom nobody linked signs up the
13 * forge's own way.
914 */
1015
1116 import { createHash, timingSafeEqual } from "node:crypto";
17 import type { Ctx } from "./context.ts";
1218
1319 /** The account the edge vouches for on this request, if it does. */
1420 export function edgeIdentity(
@@ -30,6 +36,23 @@ function sameSecret(a: string, b: string): boolean {
3036 return timingSafeEqual(ha, hb);
3137 }
3238
39 /**
40 * Is the edge where a stranger starts signing in? Only when there is one and
41 * it has not already vouched for this person: someone it knows whom no
42 * account has linked would come straight back unlinked, so for them the
43 * door is the forge's own.
44 */
45 export function edgeIsTheDoor(ctx: Pick<Ctx, "app" | "auth">): boolean {
46 return ctx.app.config.edgeToken !== undefined && ctx.auth.edge === undefined;
47 }
48
49 /** Where signing in starts, coming back to `next` on this host after. */
50 export function signInUrl(ctx: Pick<Ctx, "app" | "auth">, next: string): string {
51 return edgeIsTheDoor(ctx)
52 ? edgeLoginUrl(next)
53 : `/signin?next=${encodeURIComponent(next)}`;
54 }
55
3356 /** Where the edge starts a sign-in, coming back to `path` on this host. */
3457 export function edgeLoginUrl(path: string): string {
3558 return `/_plat/login?rd=${encodeURIComponent(samePath(path))}`;
src/http/server.ts +20 −7
@@ -10,8 +10,8 @@ import { trackPullHead } from "../core/pulls.ts";
1010 import { createRepo } from "../actions/repos.ts";
1111 import { sessionUser } from "../core/sessions.ts";
1212 import { scopeAllows, verifyToken } from "../core/tokens.ts";
13 import { forgeHost } from "../core/commit_identity.ts";
14 import { ensureEdgeUser, verifyPassword } from "../core/users.ts";
13 import { linkedUser } from "../core/links.ts";
14 import { verifyPassword } from "../core/users.ts";
1515 import { edgeIdentity } from "./edge.ts";
1616 import { healthResponse } from "./health.ts";
1717 import { runGit } from "../git/env.ts";
@@ -280,6 +280,11 @@ import {
280280 } from "../web/pages/origins.ts";
281281 import { pushThrough } from "../origins/push-through.ts";
282282 import { notFoundPage } from "../web/chrome.ts";
283 import {
284 edgeLinkSubmit,
285 edgeUnlinkSubmit,
286 linksPage,
287 } from "../web/pages/links.ts";
283288 import { targetForShortCode } from "../origins/oauth.ts";
284289 import { apiRoutes } from "./api.ts";
285290 import { feedRoutes } from "./feed.ts";
@@ -331,13 +336,18 @@ const NO_AUTH: Auth = { user: undefined, scope: undefined, via: "none" };
331336
332337 async function resolveAuth(app: App, request: Request): Promise<Auth> {
333338 // The platform edge, when there is one, has already signed this person
334 // in; its word outranks a cookie of ours.
339 // in; its word outranks a cookie of ours — but only for an identity an
340 // account here has linked. An unknown one makes nothing (#668): it rides
341 // along so the pages can send that person to the forge's own signup.
335342 const login = edgeIdentity(request, app.config.edgeToken);
336 if (login !== undefined) {
337 const user = await ensureEdgeUser(app.db, login, forgeHost(app.config));
338 if (user) return { user, scope: "admin", via: "edge" };
339 }
343 if (login === undefined) return resolveCredential(app, request);
344 const user = linkedUser(app.db, "edge", login);
345 if (user) return { user, scope: "admin", via: "edge", edge: login };
346 return { ...(await resolveCredential(app, request)), edge: login };
347 }
340348
349 /** The forge's own credentials: a session cookie, a token, a password. */
350 async function resolveCredential(app: App, request: Request): Promise<Auth> {
341351 const session = cookieValue(request, "forge_session");
342352 if (session !== undefined) {
343353 const user = sessionUser(app.db, session);
@@ -503,6 +513,9 @@ export function buildRouter(): Router<Handler> {
503513 router.add("POST", "/settings/notify", notifyUpdate);
504514 router.add("GET", "/settings/password", passwordPage);
505515 router.add("POST", "/settings/password", passwordUpdate);
516 router.add("GET", "/settings/links", linksPage);
517 router.add("POST", "/settings/links/edge/link", edgeLinkSubmit);
518 router.add("POST", "/settings/links/edge/unlink", edgeUnlinkSubmit);
506519 router.add("GET", "/settings/tokens", tokensPage);
507520 router.add("POST", "/settings/tokens", tokenCreate);
508521 router.add("POST", "/settings/tokens/:id/delete", tokenDelete);
src/main.ts +8 −2
@@ -61,8 +61,14 @@ const sshPort = Number(process.env.FORGE_SSH_PORT ?? (hosted ? 0 : 2222));
6161 // terminates TLS. Parsed once here so a typo fails the boot, not a request.
6262 const canonicalUrl = hosted ? hostedAt : (process.env.FORGE_URL ?? "").trim();
6363 // FORGE_EDGE_TOKEN is the platform edge's secret: with it, the edge's
64 // identity headers sign people in; without it they are ignored.
65 const edgeToken = (process.env.FORGE_EDGE_TOKEN ?? "").trim();
64 // identity headers sign in the accounts that linked them; without it they
65 // are ignored. The edge is a linked method (#668), and FORGE_LINK_EDGE=off
66 // turns it off with the secret still set: everyone signs in the forge's own
67 // way, and the links stay for when it comes back on.
68 const edgeToken =
69 process.env.FORGE_LINK_EDGE === "off"
70 ? ""
71 : (process.env.FORGE_EDGE_TOKEN ?? "").trim();
6672
6773 const dataDir =
6874 process.env.FORGE_DATA ??
src/web/chrome.ts +2 −4
@@ -9,7 +9,7 @@
99 */
1010
1111 import { getAppByRepo } from "../core/apps.ts";
12 import { edgeLoginUrl } from "../http/edge.ts";
12 import { signInUrl } from "../http/edge.ts";
1313 import {
1414 canAdmin,
1515 canRead,
@@ -87,11 +87,9 @@ export function signInFirst(ctx: Ctx): Response {
8787
8888 /** Where signing in starts, coming back to this page after. */
8989 export function signInHref(ctx: Ctx): string {
90 const next = ctx.url.pathname + ctx.url.search;
9190 // Behind a platform edge the edge is how people sign in; an account it
9291 // made has no password here, so the password form would only refuse them.
93 if (ctx.app.config.edgeToken !== undefined) return edgeLoginUrl(next);
94 return `/signin?next=${encodeURIComponent(next)}`;
92 return signInUrl(ctx, ctx.url.pathname + ctx.url.search);
9593 }
9694
9795 // ---- repo header ----
src/web/layout.ts +4 −5
@@ -11,7 +11,7 @@ import { appsOf, askCountFor } from "./studio/asks.ts";
1111 import { listReposVisibleTo } from "../core/repos.ts";
1212 import type { User } from "../core/users.ts";
1313 import type { Ctx } from "../http/context.ts";
14 import { edgeLoginUrl, edgeLogoutUrl } from "../http/edge.ts";
14 import { edgeIsTheDoor, edgeLoginUrl, edgeLogoutUrl } from "../http/edge.ts";
1515 import { json } from "../http/respond.ts";
1616 import { sha256 } from "../kernel/hash.ts";
1717 import { secret } from "../kernel/id.ts";
@@ -465,10 +465,9 @@ function topbar(
465465 : { label: "Sign out", post: "/logout", icon: "signOut" },
466466 )}`
467467 : btn("Sign in", {
468 href:
469 ctx.app.config.edgeToken === undefined
470 ? "/signin"
471 : edgeLoginUrl(ctx.url.pathname + ctx.url.search),
468 href: edgeIsTheDoor(ctx)
469 ? edgeLoginUrl(ctx.url.pathname + ctx.url.search)
470 : "/signin",
472471 })}
473472 </span>
474473 </header>`;
src/web/pages/account.ts +1 −1
@@ -49,7 +49,7 @@ import {
4949 field as uiField,
5050 } from "../ui.ts";
5151
52 type Section = "profile" | "password" | "tokens" | "keys";
52 type Section = "profile" | "password" | "links" | "tokens" | "keys";
5353
5454 // The section list lives beside the newest page that joins it, so adding one
5555 // cannot leave the others pointing at a nav that has forgotten it.
src/web/pages/origins.ts +7
@@ -64,6 +64,7 @@ import {
6464 export type AccountSection =
6565 | "profile"
6666 | "password"
67 | "links"
6768 | "tokens"
6869 | "keys"
6970 | "origins"
@@ -130,6 +131,12 @@ export function accountSections(
130131 icon: "lock",
131132 current: current === "password",
132133 },
134 {
135 label: "Sign-in methods",
136 href: "/settings/links",
137 icon: "link",
138 current: current === "links",
139 },
133140 {
134141 label: "Access tokens",
135142 href: "/settings/tokens",
src/web/pages/site.ts +38 −28
@@ -38,7 +38,8 @@ import { isThemeName } from "../../design/themes.ts";
3838 import { crossOrigin, type Ctx } from "../../http/context.ts";
3939 import { askCountFor, askSentence } from "../studio/asks.ts";
4040 import { studioDoor, studioHome } from "../studio/home.ts";
41 import { edgeLoginUrl } from "../../http/edge.ts";
41 import { edgeIsTheDoor, edgeLoginUrl } from "../../http/edge.ts";
42 import { linkSignIn } from "../../actions/links.ts";
4243 import { sshCommand } from "../../ssh/command.ts";
4344 import {
4445 hostOf,
@@ -619,29 +620,35 @@ function authForm(
619620 // of the whole user table — and the sign-in screen paints on every session.
620621 const firstAccount = kind === "signup" && !hasAnyUser(ctx.app.db);
621622
622 // Behind a platform edge, that is the door: the button first, and the
623 // password form kept for the accounts that have one — an account the edge
624 // made has none, and the note says so before anyone types.
625 const edge =
626 ctx.app.config.edgeToken === undefined
627 ? undefined
628 : (ctx.app.config.edgeName ?? "the platform");
629 const throughEdge = when(
630 edge,
631 (name) =>
632 html`<div class="stack mb">
633 ${btn(`Continue with ${name}`, {
634 href: edgeLoginUrl(next ?? "/"),
635 variant: "primary",
636 size: "lg",
637 })}
638 <p class="muted small">
639 ${kind === "signin"
640 ? `Accounts made through ${name} sign in there and have no password here. The form below is for an account that was given one.`
641 : `Signing in through ${name} makes your account on first sight; the form below makes one with a password instead.`}
642 </p>
643 </div>`,
644 );
623 // Behind a platform edge, that is the door to sign in by: the button
624 // first, and the password form kept for the accounts that have one. The
625 // edge makes no account (#668), so signing up is always the form here —
626 // and a person the edge already knows, whom nobody has linked, is told
627 // what the form will do with that identity.
628 const edgeName = ctx.app.config.edgeName ?? "the platform";
629 const known = ctx.auth.via === "edge" ? undefined : ctx.auth.edge;
630 const throughEdge = known
631 ? html`<p class="muted small mb">
632 ${kind === "signup"
633 ? `${edgeName} knows you as ${known}, and no account here is linked to it yet. The account you create below is linked to it, so ${edgeName} signs you in to it from now on.`
634 : `${edgeName} knows you as ${known}, and no account here is linked to it yet. Sign in with your password, then link it under Settings → Sign-in methods — or create an account.`}
635 </p>`
636 : edgeIsTheDoor(ctx)
637 ? kind === "signin"
638 ? html`<div class="stack mb">
639 ${btn(`Continue with ${edgeName}`, {
640 href: edgeLoginUrl(next ?? "/"),
641 variant: "primary",
642 size: "lg",
643 })}
644 <p class="muted small">
645 ${`Accounts linked to ${edgeName} sign in there. The form below is for an account with a password.`}
646 </p>
647 </div>`
648 : html`<p class="muted small mb">
649 ${`Signing in through ${edgeName} does not make an account here. Create one below; while ${edgeName} has you signed in, it is linked to it.`}
650 </p>`
651 : null;
645652
646653 const body = html`${throughEdge}
647654 <form method="post" action="${action}">
@@ -788,10 +795,9 @@ export async function signinSubmit(ctx: Ctx): Promise<Response> {
788795 body: authForm(ctx, "signin", {
789796 values: { username },
790797 errors: {
791 password:
792 ctx.app.config.edgeToken === undefined
793 ? "That username and password don't match."
794 : `That username and password don't match. An account made through ${ctx.app.config.edgeName ?? "the platform"} has no password here — use the button above.`,
798 password: edgeIsTheDoor(ctx)
799 ? `That username and password don't match. An account linked to ${ctx.app.config.edgeName ?? "the platform"} may have no password here — use the button above.`
800 : "That username and password don't match.",
795801 },
796802 }),
797803 },
@@ -834,6 +840,10 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
834840 422,
835841 );
836842 }
843 // A person the edge vouched for on this very request, whom no account had
844 // linked, made this account: the identity is theirs, so it is linked.
845 if (ctx.auth.via !== "edge" && ctx.auth.edge !== undefined)
846 linkSignIn(ctx.app, created.value, "edge", ctx.auth.edge);
837847 const session = createSession(ctx.app.db, created.value.id);
838848 return redirect(
839849 safeNext(ctx.url.searchParams.get("next")) ?? "/",
src/web/studio/home.ts +2 −2
@@ -15,7 +15,7 @@ import { getReposByIds, type Repo } from "../../core/repos.ts";
1515 import { type User } from "../../core/users.ts";
1616 import { isPausedAtCeiling, spentTodayForRepos } from "../../crew/autonomy.ts";
1717 import type { Ctx } from "../../http/context.ts";
18 import { edgeLoginUrl } from "../../http/edge.ts";
18 import { edgeIsTheDoor, edgeLoginUrl } from "../../http/edge.ts";
1919 import { sshCommand } from "../../ssh/command.ts";
2020 import { repoBase } from "../chrome.ts";
2121 import { liveRegionsJs } from "../client.ts";
@@ -264,7 +264,7 @@ export function studioDoor(ctx: Ctx): Response {
264264 <h1>Apps, live.</h1>
265265 <p>A software forge that builds and serves its own apps.</p>
266266 <div class="bar">
267 ${ctx.app.config.edgeToken === undefined
267 ${!edgeIsTheDoor(ctx)
268268 ? html`${btn("Create an account", {
269269 href: "/signup",
270270 variant: "primary",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs