From 94d1a4c7978563306c2fde4cdf3c55000e4f517d Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 26 Oct 2026 14:18:48 -0400 Subject: [PATCH 1/2] Self-host: one organization, closed sign-up, and admin-required two-factor sign-in --- .github/workflows/ci.yml | 2 + docs/self-host/config-reference.md | 8 +- docs/self-host/options.md | 6 +- docs/self-host/quick-start.md | 6 +- docs/self-host/sign-in.md | 61 +- infra/cfn/coderhelm-selfhost-launch.yaml | 17 +- infra/lib/api-stack.ts | 26 + infra/lib/config.ts | 16 +- infra/lib/database-stack.ts | 18 +- infra/test/config.test.ts | 8 + infra/test/synth.test.ts | 43 + installer/lib/wizard.mjs | 4 +- installer/test/installer.test.mjs | 3 +- lambda/pre-signup/cases.json | 19 + lambda/pre-signup/handler.js | 123 ++ lambda/pre-signup/handler.test.js | 69 + selfhost/launch/bootstrap.mjs | 5 +- selfhost/launch/bootstrap.test.mjs | 4 + services/gateway/src/auth/jwt.rs | 161 +- services/gateway/src/main.rs | 13 + services/gateway/src/middleware/auth.rs | 18 +- services/gateway/src/permissions.rs | 18 +- services/gateway/src/routes/api.rs | 7 +- services/gateway/src/routes/auth.rs | 344 +++- services/gateway/src/routes/mod.rs | 1 + services/gateway/src/routes/sign_in.rs | 2044 ++++++++++++++++++++++ services/gateway/src/routes/users.rs | 33 +- 27 files changed, 3018 insertions(+), 59 deletions(-) create mode 100644 lambda/pre-signup/cases.json create mode 100644 lambda/pre-signup/handler.js create mode 100644 lambda/pre-signup/handler.test.js create mode 100644 services/gateway/src/routes/sign_in.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1c9968b6e..b856da307 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,6 +72,8 @@ jobs: with: python-version: "3.12" - run: python3 -m unittest discover -s lambda/tests + # The Cognito pre-sign-up trigger, against the cases the gateway uses. + - run: node --test lambda/pre-signup/handler.test.js mcp-proxy: name: MCP Proxy (Node) diff --git a/docs/self-host/config-reference.md b/docs/self-host/config-reference.md index 3793e6932..a07bf545e 100644 --- a/docs/self-host/config-reference.md +++ b/docs/self-host/config-reference.md @@ -91,11 +91,13 @@ See [Email](./email.md). - **`admins`** *list of emails, required*\ Admins of the whole install: the admin pages (teams, the failed message queue, support). They may always sign up. - **`signup.emails`** *list of emails, default `[]`*\ - Others who may create an account. + First boot only: invited to the organization as members. After that, invite people in Settings, Team. - **`signup.domains`** *list of domains, default `[]`*\ - Anyone with an email at these domains may create an account. + First boot only: anyone with an email at these domains may join. After that, change them in Settings, Sign-in. Empty: only people the admins invite. +- **`signup.requireTwoFactor`** *boolean, default `false`*\ + First boot only: start with two-factor sign-in required for everyone. After that, Settings, Sign-in. -Sign-up is closed to everyone else. People already on a team invite others from the dashboard. +A self-hosted install is one organization: sign-up is closed to everyone else. Admins invite people and allow email domains in the dashboard (see [Sign-in and people](./sign-in.md)). ## Integrations diff --git a/docs/self-host/options.md b/docs/self-host/options.md index 15af9149d..9d4ba3468 100644 --- a/docs/self-host/options.md +++ b/docs/self-host/options.md @@ -40,10 +40,14 @@ One list of everything you can set up, and where. Required items are steps in th *Launch Stack:* `EmailFrom`\ *Config:* `email.from`, `email.identity`\ *Checked by:* `email`, `email_identity` -- **Who else may sign up**\ +- **Let people from your company join** (default: only people you invite)\ *Install guide:* More options\ *Launch Stack:* `SignupDomain`\ *Config:* `signup.domains`, `signup.emails` +- **Require two-factor sign-in**\ + *Install guide:* More options\ + *Launch Stack:* `RequireTwoFactor`\ + *Config:* `signup.requireTwoFactor` - **Automatic updates and the window**\ *Install guide:* More options\ *Launch Stack:* `AutoUpdate`, `UpdateWindow`, `UpdateTimezone`\ diff --git a/docs/self-host/quick-start.md b/docs/self-host/quick-start.md index 7405cbb54..83ab3e307 100644 --- a/docs/self-host/quick-start.md +++ b/docs/self-host/quick-start.md @@ -102,10 +102,10 @@ Your email: you@example.com Emails come from [coderhelm@example.com]: example.com is your Route 53 zone: the deploy adds its DKIM records and SES verifies it in minutes. This account is in the SES sandbox: email only reaches verified addresses, 200 a day. ... -Let anyone with this email domain sign up (empty: only you) [example.com]: +This install is for one organization. Let people from your company join: an email domain such as example.com (empty: only people you invite) []: ``` -You become the first admin. It checks the sender's SES identity (verified, with DKIM; when not, it prints the three DNS records to add) and whether the account is still in the SES sandbox (a warning, with the link to request production access). See [Email](./email.md). +You become the first admin. Nobody else can sign up unless you invite them or allow their email domain (change it later in **Settings, Sign-in**; see [Sign-in and people](./sign-in.md)). It checks the sender's SES identity (verified, with DKIM; when not, it prints the three DNS records to add) and whether the account is still in the SES sandbox (a warning, with the link to request production access). See [Email](./email.md). ## Step 6: optional extras @@ -196,7 +196,7 @@ The [install guide](https://docs.coderhelm.com/self-host/install/) builds this l - Quick-create link (replace both regions with yours): `https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/create/review?stackName=coderhelm-prod&templateURL=https://coderhelm-public.s3.amazonaws.com/launch/v0.7.0/coderhelm-launch.yaml¶m_AdminEmail=you@example.com` -Only your email is required. The optional parameters: `Hostname` (your own domain: a Route 53 zone in the account is found and set up for you, any other DNS provider gets two records to add, see [Domains](./domains.md)), `EmailFrom`, `SignupDomain`, `AutoUpdate` with `UpdateWindow` and `UpdateTimezone`, `BedrockInferencePrefix` and `Telemetry`. [Everything you can set up](./options.md) lists each with its config setting. Tick the box that lets the stack create IAM roles and press **Create stack**. A CodeBuild project in your account downloads the release, checks its signature and checksums, deploys every CoderHelm stack (about 20 minutes) and finishes with your URL in the stack's **Outputs**. Its log stays in CloudWatch under `/aws/codebuild/-installer`, also if the stack is rolled back. +Only your email is required. The optional parameters: `Hostname` (your own domain: a Route 53 zone in the account is found and set up for you, any other DNS provider gets two records to add, see [Domains](./domains.md)), `EmailFrom`, `SignupDomain` (empty: only people you invite) and `RequireTwoFactor`, `AutoUpdate` with `UpdateWindow` and `UpdateTimezone`, `BedrockInferencePrefix` and `Telemetry`. [Everything you can set up](./options.md) lists each with its config setting. Tick the box that lets the stack create IAM roles and press **Create stack**. A CodeBuild project in your account downloads the release, checks its signature and checksums, deploys every CoderHelm stack (about 20 minutes) and finishes with your URL in the stack's **Outputs**. Its log stays in CloudWatch under `/aws/codebuild/-installer`, also if the stack is rolled back. Without the guide's setup key, create the GitHub App from your computer with the two commands in the **GitHubAppWithoutTheGuide** output (`pull`, then `github-app`). diff --git a/docs/self-host/sign-in.md b/docs/self-host/sign-in.md index 0f079bfd4..89db67b8f 100644 --- a/docs/self-host/sign-in.md +++ b/docs/self-host/sign-in.md @@ -1,29 +1,58 @@ --- title: Sign-in and people -description: Who may sign up, email and password with passkeys and two-factor codes, Google sign-in, GitHub accounts, install admins and team roles. +description: One organization per install, who may join (invites and allowed email domains), required two-factor sign-in, Google sign-in, GitHub accounts, install admins and team roles. order: 6.5 --- -Accounts live in a Cognito user pool in your AWS account. Nobody can sign up unless the config lets them. +Accounts live in a Cognito user pool in your AWS account. A self-hosted install is for **one organization**: one team, owned by the first admin. Nobody can make another team, and nobody can sign up on their own. -## Who may sign up +## Who may join -| Setting | Who | Where | +People join in one of two ways: + +- **An invite.** An admin invites them by email in **Settings, Team**. The invite works for 30 days; resend it from **Pending invites**. +- **An allowed email domain.** Admins can let anyone with an email at a domain join, such as `example.com`, in **Settings, Sign-in**. They join as members. Public email services (Gmail, Outlook and the like) can't be allowed: that would let anyone in. + +Everyone else is refused, on every way in: email sign-up, Google, GitHub, and the Cognito API itself. A pre-sign-up trigger in the user pool checks the same rules as CoderHelm, so even a direct Cognito `SignUp` call with the app's client id is refused. + +The first admin is the address you gave the install (the Launch Stack's **Your email**, or `admins` in the config). Their first sign-in makes the organization; until then, only they can sign up. + +### At install time + +The install guide's **Let people from your company join** starts as **Only people I invite**. Pick **Anyone with an email at** and type your company's domain to allow it from the start. The config's `signup.domains` and `signup.emails` do the same: on first boot the domains become the allowed domains and the addresses become invites. After that, admins change both in **Settings** (the config is not read again). + +| Setting | First boot | After | |---|---|---| -| `admins` | The install's admins: they may always sign up, and see the admin pages (teams, failed events, support, Settings, then Setup and System) | The Launch Stack's **Your email**, or the config | -| `signup.domains` | Anyone with an email at these domains | The Launch Stack's **Who else may sign up** (one domain), or the config | -| `signup.emails` | These addresses | The config | -| Invites | Anyone a team admin invites | **Settings, People, Invite** (no config) | +| `admins` | The first admin (the first one to sign in makes the organization); the others are invited as admins | Install admins (see below) | +| `signup.domains` | Allowed email domains | **Settings, Sign-in** | +| `signup.emails` | Invited as members | **Settings, Team** | +| `signup.requireTwoFactor` | Two-factor sign-in required | **Settings, Sign-in** | + +An install from before this change keeps working: its oldest team becomes the organization at the next sign-in, its config list is carried over as above, and people on other teams need an invite. + +## Two-factor sign-in + +Anyone can turn on two-factor sign-in for themselves in **Settings, Security**. Admins can require it for everyone: **Settings, Sign-in, Require two-factor sign-in**. Turn it on for yourself first; the switch asks for that, so you can't lock yourself out. + +With it on: + +- **Everyone** must set up an authenticator app (any TOTP app: 1Password, Google Authenticator, Authy and so on) before they can use CoderHelm. At their next sign-in they see a setup screen with a code to scan, and nothing else works until they enter a code from the app. +- **People who sign in with a password** use Cognito's own two-factor codes: Cognito asks for the code at every sign-in. +- **People who sign in with Google or GitHub** don't pass through Cognito's two-factor step, so CoderHelm asks for its own authenticator-app code right after Google or GitHub. Their secret is sealed with the install's KMS key. No sign-in path skips the code. +- **Sessions from before the switch** are checked at their next request: someone already signed in without a code is sent to the setup screen, or asked to sign in again with their code. +- **API keys** are not people and keep working. **Settings, Sign-in** lists them, so you can revoke any you don't want. + +**Settings, Sign-in** shows who has set it up. If someone loses their phone, an admin can reset their two-factor sign-in after checking it's really them (a video call, say). The admin writes how they checked; the reset and the reason go in the log under **Settings, Roles**. The person sets it up again at their next sign-in. Only an owner can reset an admin's or another owner's. Nobody can reset their own. -Sign-up is closed to everyone else. Change `signup` in the config and deploy, or invite people from the dashboard. The install guide's **Optional setup** list links to the invite page. +Why an authenticator app and not passkeys: Cognito's passkeys need its paid Essentials tier, a fixed sign-in domain (passkeys break when the CloudFront address changes to your own domain) and Cognito's hosted sign-in pages. Authenticator apps work on every install, including one on its free CloudFront address. -## Email and password, passkeys and two-factor codes +## Email and password -Always on. People confirm their email with a code, then can add a passkey or an authenticator app code in their own settings. Sign-up and password emails come from Amazon Cognito until `email.cognitoUsesSes` is on (see [Email](./email.md#sign-up-and-password-emails)); Cognito's own address is limited to 50 emails a day. +Always on. People confirm their email with a code. Sign-up and password emails come from Amazon Cognito until `email.cognitoUsesSes` is on (see [Email](./email.md#sign-up-and-password-emails)); Cognito's own address is limited to 50 emails a day. ## Sign in with Google -Optional, and it needs your own domain (Google requires a fixed sign-in address; see [Domains](./domains.md)). +Optional, and it needs your own domain (Google requires a fixed sign-in address; see [Domains](./domains.md)). It follows the same rules: only invited people and allowed domains. 1. In Google Cloud, **APIs and services, Credentials, Create credentials, OAuth client ID**, type **Web application**. 2. Add the authorized redirect URI `https:///oauth2/idpresponse` (the deploy's `SignInDomain` output shows the domain). @@ -34,14 +63,14 @@ Settings, then Setup checks it (`google_sign_in`): off, on with its keys, or on ## GitHub accounts -People connect their GitHub account in their own settings, so pull requests and reviews are credited to them. It uses the GitHub App's own OAuth client, which the GitHub App step stores; nothing to set up. +People connect their GitHub account in their own settings, so pull requests and reviews are credited to them. Signing in with GitHub follows the same rules as everything else: it lands on the organization only for someone already in it, invited, or at an allowed domain (by the email on their GitHub account). It uses the GitHub App's own OAuth client, which the GitHub App step stores; nothing to set up. ## Single sign-on (SAML, OIDC) -Not available yet: CoderHelm's sign-in page offers email and password and Google. The Cognito user pool is in your account, so an identity provider added there by hand is not shown on the sign-in page and isn't supported. +Not available yet: CoderHelm's sign-in page offers email and password, Google and GitHub. The Cognito user pool is in your account, so an identity provider added there by hand is not shown on the sign-in page and isn't supported. ## Install admins and team roles -- **Install admins** (`admins`) see the whole install: every team, the failed events queue, support tickets, and the Setup and System pages. They must have an email CoderHelm verified itself. -- **Team roles** (viewer, member, admin, owner, and custom roles) are set per team in **Settings, People** and **Settings, Roles**. +- **Install admins** (`admins`) see the whole install: the failed events queue, support tickets, and the Setup and System pages. They must have an email CoderHelm verified itself. +- **Team roles** (viewer, member, admin, owner, and custom roles) are set in **Settings, Team** and **Settings, Roles**. Sign-in rules stay with built-in admins and owners; a custom role can't hold them. - **Support access:** a team admin can let the install admins see the team's workspace read-only for a fixed time, with every read in the team's audit log (**Settings, Support access**). diff --git a/infra/cfn/coderhelm-selfhost-launch.yaml b/infra/cfn/coderhelm-selfhost-launch.yaml index 2a9d19df1..6e473c91c 100644 --- a/infra/cfn/coderhelm-selfhost-launch.yaml +++ b/infra/cfn/coderhelm-selfhost-launch.yaml @@ -21,8 +21,10 @@ Metadata: Parameters: [Stage, ModelProvider, Version] - Label: { default: "Optional: your own domain (leave empty to use a free CloudFront address)" } Parameters: [Hostname, HostedZone] + - Label: { default: "Who may join (this install is for one organization; change these later in Settings, Sign-in)" } + Parameters: [SignupDomain, RequireTwoFactor] - Label: { default: "Optional" } - Parameters: [EmailFrom, SignupDomain, BedrockInferencePrefix, Telemetry] + Parameters: [EmailFrom, BedrockInferencePrefix, Telemetry] - Label: { default: "Optional: updates (you can change these later in Settings, System)" } Parameters: [AutoUpdate, UpdateWindow, UpdateTimezone] - Label: { default: "Filled in by the install guide (leave as they are)" } @@ -35,7 +37,8 @@ Metadata: Hostname: { default: "Hostname" } HostedZone: { default: "Route 53 hosted zone" } EmailFrom: { default: "Send email from" } - SignupDomain: { default: "Who else may sign up" } + SignupDomain: { default: "Let people from your company join" } + RequireTwoFactor: { default: "Require two-factor sign-in" } BedrockInferencePrefix: { default: "Bedrock inference profile" } Telemetry: { default: "Anonymous install pings" } AutoUpdate: { default: "Install new releases by themselves" } @@ -89,8 +92,15 @@ Parameters: SignupDomain: Type: String Default: "" - Description: Let anyone with an email at this domain sign up, e.g. example.com. Empty for only you (you can invite people later). + Description: > + Empty (the default) means only people you invite. Or an email domain, e.g. example.com: anyone with an email + there may join. This install is for one organization only; nobody else can sign up. AllowedPattern: "^$|^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$" + RequireTwoFactor: + Type: String + Default: "off" + AllowedValues: ["off", "on"] + Description: on makes everyone set up an authenticator app before they can use CoderHelm, you included. BedrockInferencePrefix: Type: String Default: auto @@ -205,6 +215,7 @@ Resources: - { Name: MODEL_PROVIDER, Value: !Ref ModelProvider } - { Name: BEDROCK_PREFIX, Value: !Ref BedrockInferencePrefix } - { Name: SIGNUP_DOMAIN, Value: !Ref SignupDomain } + - { Name: REQUIRE_TWO_FACTOR, Value: !Ref RequireTwoFactor } - { Name: TELEMETRY, Value: !Ref Telemetry } - { Name: AUTO_UPDATE, Value: !Ref AutoUpdate } - { Name: UPDATE_WINDOW, Value: !Ref UpdateWindow } diff --git a/infra/lib/api-stack.ts b/infra/lib/api-stack.ts index 40010a292..51e928765 100644 --- a/infra/lib/api-stack.ts +++ b/infra/lib/api-stack.ts @@ -129,6 +129,32 @@ export class ApiStack extends cdk.Stack { customMessageFn ); + // A self-hosted install is one organization: every account the user pool + // makes (sign-up with the app client, Google, AdminCreateUser) is checked + // against its rules first, so even a direct Cognito SignUp call is + // refused unless the person is invited, at an allowed domain, or the + // first admin. The gateway checks the same rules (routes/sign_in.rs). + if (cfg.layout === "single-origin") { + const preSignUpFn = new lambda.Function(this, "PreSignUpFn", { + functionName: `${prefix}-pre-signup`, + runtime: lambda.Runtime.NODEJS_22_X, + handler: "handler.handler", + code: lambda.Code.fromAsset(repoPath("lambda/pre-signup"), { + exclude: ["*.test.js", "cases.json"], + }), + timeout: cdk.Duration.seconds(5), + memorySize: 128, + environment: { + SETTINGS_TABLE_NAME: props.settingsTable.tableName, + USERS_TABLE_NAME: props.usersTable.tableName, + }, + logRetention: logs.RetentionDays.ONE_MONTH, + }); + props.settingsTable.grantReadData(preSignUpFn); + props.usersTable.grantReadData(preSignUpFn); + userPool.addTrigger(cognito.UserPoolOperation.PRE_SIGN_UP, preSignUpFn); + } + // Google identity provider (optional: integrations.googleSignIn). // google_client_id and google_client_secret live in the deployment's // secret (cfg.secretName). Callback URL: diff --git a/infra/lib/config.ts b/infra/lib/config.ts index 43d33604c..22fa30d3d 100644 --- a/infra/lib/config.ts +++ b/infra/lib/config.ts @@ -150,12 +150,20 @@ export interface CoderhelmConfig { }; /** People with admin rights over the whole deployment (the first one is you). */ admins?: string[]; - /** Who may create an account (admins always may). */ + /** + * Who may create an account (admins always may). On a self-hosted install + * this is the first boot's list: the addresses become invites and the + * domains the allowed domains of the one organization, which admins change + * after that in Settings, Sign-in. Empty means only people the admins + * invite. + */ signup?: { /** Exact addresses. */ emails?: string[]; /** Whole email domains, e.g. `example.com`. */ domains?: string[]; + /** Start with two-factor sign-in required for everyone. Default false. */ + requireTwoFactor?: boolean; }; integrations?: { /** "Sign in with Google" (needs google_client_id/secret in the secret and a domain). Default false. */ @@ -265,7 +273,7 @@ export interface ResolvedConfig { privacyUrl: string | null; }; admins: string[]; - signup: { emails: string[]; domains: string[] }; + signup: { emails: string[]; domains: string[]; requireTwoFactor: boolean }; integrations: Required>; dashboardAssetDir: string | null; updates: { @@ -478,6 +486,9 @@ export function validateConfig(c: unknown): string[] { if (s.domains !== undefined && (!Array.isArray(s.domains) || s.domains.some((x) => !HOST_RE.test(String(x).toLowerCase())))) { p.push("signup.domains: a list of email domains such as example.com"); } + if (s.requireTwoFactor !== undefined && typeof s.requireTwoFactor !== "boolean") { + p.push("signup.requireTwoFactor: true or false"); + } } const i = cfg.integrations ?? {}; for (const [k, v] of Object.entries(i)) { @@ -605,6 +616,7 @@ export function resolveConfig(cfg: CoderhelmConfig, opts: { skipValidation?: boo signup: { emails: [...new Set([...admins, ...(cfg.signup?.emails ?? [])].map((x) => x.toLowerCase()))], domains: [...new Set((cfg.signup?.domains ?? []).map((x) => x.toLowerCase()))], + requireTwoFactor: cfg.signup?.requireTwoFactor === true, }, integrations: { googleSignIn: i.googleSignIn ?? false, diff --git a/infra/lib/database-stack.ts b/infra/lib/database-stack.ts index 9c4c11d4e..c784b6b28 100644 --- a/infra/lib/database-stack.ts +++ b/infra/lib/database-stack.ts @@ -615,9 +615,15 @@ export class DatabaseStack extends cdk.Stack { // Who may sign up: the config's admins, addresses and domains go on the // allowlist the sign-up check reads (settings table, pk ALLOWLIST). // Entries are only ever added here; remove one from the dashboard. - const allow = [ - ...props.cfg.signup.emails.map((e) => `EMAIL#${e}`), - ...props.cfg.signup.domains.map((d) => `EMAIL#*@${d}`), + // On a self-hosted install this is the first boot's list: the first admin + // comes from it, and when the organization is made its other addresses + // become invites and its domains the allowed domains (changed after that + // in Settings, Sign-in). `kind` tells an admin from an invite. + const admins = new Set(props.cfg.admins.map((a) => a.toLowerCase())); + const allow: { sk: string; kind: string }[] = [ + ...props.cfg.signup.emails.map((e) => ({ sk: `EMAIL#${e}`, kind: admins.has(e) ? "admin" : "invite" })), + ...props.cfg.signup.domains.map((d) => ({ sk: `EMAIL#*@${d}`, kind: "domain" })), + ...(props.cfg.signup.requireTwoFactor ? [{ sk: "TWO_FACTOR", kind: "rule" }] : []), ]; for (let i = 0; i < allow.length; i += 25) { const chunk = allow.slice(i, i + 25); @@ -626,18 +632,20 @@ export class DatabaseStack extends cdk.Stack { action: "batchWriteItem", parameters: { RequestItems: { - [this.settingsTable.tableName]: chunk.map((sk) => ({ + [this.settingsTable.tableName]: chunk.map(({ sk, kind }) => ({ PutRequest: { Item: { pk: { S: "ALLOWLIST" }, sk: { S: sk }, + kind: { S: kind }, added_by: { S: "config" }, + ...(sk === "TWO_FACTOR" ? { require: { BOOL: true } } : {}), }, }, })), }, }, - physicalResourceId: cr.PhysicalResourceId.of(`allowlist-${chunk.join(",")}`.slice(0, 1000)), + physicalResourceId: cr.PhysicalResourceId.of(`allowlist-${chunk.map((c) => c.sk).join(",")}`.slice(0, 1000)), }; const seed = new cr.AwsCustomResource(this, `SignupAllowlist${i / 25}`, { onCreate: call, diff --git a/infra/test/config.test.ts b/infra/test/config.test.ts index 1bfc82179..c81af5f46 100644 --- a/infra/test/config.test.ts +++ b/infra/test/config.test.ts @@ -251,3 +251,11 @@ test("updates settings", () => { assert.equal(r.updates.enabled, true); assert.deepEqual(r.updates.defaults, { auto: false, channel: "stable", day: "sun", hour: 3, timezone: "UTC", majors: "ask" }); }); + +test("signup.requireTwoFactor: off unless set, and only a boolean", () => { + const base = (over: Record = {}) => + resolveConfig({ account: "111122223333", region: "us-west-2", stage: "prod", email: { from: "a@example.org" }, admins: ["a@example.org"], ...over } as any); + assert.equal(base().signup.requireTwoFactor, false); + assert.equal(base({ signup: { requireTwoFactor: true } }).signup.requireTwoFactor, true); + assert.throws(() => base({ signup: { requireTwoFactor: "yes" } }), /requireTwoFactor/); +}); diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 170ed579d..073ad3f65 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -576,4 +576,47 @@ test("the release check reads models.json only after the signature check, and ca assert.ok(actions.every((a) => a === "lambda:InvokeFunction" || a.startsWith("logs:") || /^codebuild:(Create|Update|BatchPut)/.test(a)), JSON.stringify(actions)); assert.ok(!actions.some((a) => /sts:|secretsmanager:|ssm:|cloudformation:|bedrock:/.test(a))); assert.equal(envOf(u, "coderhelm-prod-updater").RELEASE_CHECK_PROJECT_NAME, "coderhelm-prod-release-check"); + +test("sign-in: self-host checks every new account in Cognito (pre-sign-up trigger); MFA stays optional with authenticator apps", () => { + const t = synth(selfHost({ signup: { domains: ["Example.org"], emails: ["b@example.org"], requireTwoFactor: true } })); + const api = t["coderhelm-prod-api"]; + // Optional in Cognito: the "required" switch is CoderHelm's (an admin turns + // it on at runtime), and Google sign-ins never pass Cognito MFA anyway. + api.hasResourceProperties("AWS::Cognito::UserPool", { + MfaConfiguration: "OPTIONAL", + EnabledMfas: ["SOFTWARE_TOKEN_MFA"], + }); + const pool = Object.values(api.findResources("AWS::Cognito::UserPool"))[0] as any; + const pre = pool.Properties.LambdaConfig.PreSignUp; + assert.ok(pre, "a pre-sign-up trigger"); + const fns = api.findResources("AWS::Lambda::Function"); + const [fnId, fn] = Object.entries(fns).find(([, r]) => (r as any).Properties.FunctionName === "coderhelm-prod-pre-signup") as [string, any]; + assert.deepEqual(pre, { "Fn::GetAtt": [fnId, "Arn"] }); + const env = fn.Properties.Environment.Variables; + assert.ok(env.SETTINGS_TABLE_NAME && env.USERS_TABLE_NAME); + // Cognito may call it; it only reads. + api.hasResourceProperties("AWS::Lambda::Permission", { Principal: "cognito-idp.amazonaws.com", FunctionName: { "Fn::GetAtt": [fnId, "Arn"] } }); + const policies = JSON.stringify(api.findResources("AWS::IAM::Policy")); + const preRolePolicy = Object.values(api.findResources("AWS::IAM::Policy")).find((p: any) => + JSON.stringify(p.Properties.Roles).includes(fn.Properties.Role["Fn::GetAtt"][0]), + ) as any; + const actions = JSON.stringify(preRolePolicy.Properties.PolicyDocument.Statement.map((s: any) => s.Action)); + assert.ok(actions.includes("dynamodb:GetItem") && actions.includes("dynamodb:Query"), actions); + assert.ok(!/PutItem|UpdateItem|DeleteItem|BatchWrite/.test(actions), `pre-sign-up may only read: ${actions}`); + assert.ok(policies.length > 0); + + // The first boot's list: the admin, an invite, a domain and the rule. + const db = json(t["coderhelm-prod-database"]); + for (const want of ['"EMAIL#owner@example.org"},"kind":{"S":"admin"}', '"EMAIL#b@example.org"},"kind":{"S":"invite"}', '"EMAIL#*@example.org"},"kind":{"S":"domain"}', '"TWO_FACTOR"},"kind":{"S":"rule"}', '"require":{"BOOL":true}']) { + assert.ok(db.replace(/\\/g, "").includes(want), want); + } +}); + +test("sign-in: hosted keeps its open pool (no pre-sign-up trigger) and optional MFA", () => { + const cfg = loadConfigFile(path.join(INFRA, "config", "hosted.prod.json"), { CDK_DEFAULT_ACCOUNT: "654654210434" }); + const api = synth(cfg, zoneContext("654654210434", "us-east-1", "coderhelm.com"))["coderhelm-prod-api"]; + const pool = Object.values(api.findResources("AWS::Cognito::UserPool"))[0] as any; + assert.equal(pool.Properties.MfaConfiguration, "OPTIONAL"); + assert.equal(pool.Properties.LambdaConfig.PreSignUp, undefined); + assert.ok(pool.Properties.LambdaConfig.CustomMessage); }); diff --git a/installer/lib/wizard.mjs b/installer/lib/wizard.mjs index ed760d6f7..7f4e35f10 100644 --- a/installer/lib/wizard.mjs +++ b/installer/lib/wizard.mjs @@ -256,7 +256,7 @@ async function stepEmail(ctx, answers) { }, { heading: "Checking Amazon SES" }); if (checked === BACK) return BACK; const acct = runner.dryRun ? null : { ProductionAccessEnabled: !sandbox }; - const signupDomain = await answer(ctx, pick(flags, answers, "signupDomain"), "Let anyone with this email domain sign up (empty: only you)", admin.split("@")[1], (v) => (!v || HOST_RE.test(v) ? null : "A domain such as example.com, or empty.")); + const signupDomain = await answer(ctx, pick(flags, answers, "signupDomain"), "This install is for one organization. Let people from your company join: an email domain such as example.com (empty: only people you invite)", "", (v) => (!v || HOST_RE.test(v) ? null : "A domain such as example.com, or empty.")); if (signupDomain === BACK) return BACK; return { ...answers, admin, emailFrom, signupDomain, sesSandbox: acct ? !acct.ProductionAccessEnabled : undefined }; } @@ -342,7 +342,7 @@ async function stepSummary(ctx, answers) { log(` Address ${cfg.domain ? `https://${cfg.domain.hostname}` : "CloudFront's own address"}`); log(` Claude ${cfg.models.provider === "bedrock" ? `Amazon Bedrock (${cfg.models.bedrockInferencePrefix || "in-region"})` : "Anthropic API, each team's key"}`); log(` Admin / sender ${cfg.admins[0]} / ${cfg.email.from}`); - log(` Sign-up ${cfg.signup.domains?.length ? `anyone at ${cfg.signup.domains[0]}` : "only you (invite others later)"}`); + log(` Who may join ${cfg.signup.domains?.length ? `people you invite, and anyone at ${cfg.signup.domains[0]}` : "only people you invite"} (change it later in Settings, Sign-in)`); log(` Google sign-in ${cfg.integrations.googleSignIn ? "on" : "off"}`); log(` Auto-update ${cfg.updates.auto ? `on, ${cfg.updates.window} ${cfg.updates.timezone}, majors: ${cfg.updates.majors}` : "off (you're emailed about new releases)"}`); const c = estimateMonthlyCost(answers); diff --git a/installer/test/installer.test.mjs b/installer/test/installer.test.mjs index dec68a164..fbc5f2c7d 100644 --- a/installer/test/installer.test.mjs +++ b/installer/test/installer.test.mjs @@ -108,7 +108,8 @@ test("init writes a config from flags (non-interactive)", async () => { assert.equal(cfg.models.provider, "bedrock"); assert.equal(cfg.email.from, "coderhelm@example.org"); assert.deepEqual(cfg.admins, ["me@example.org"]); - assert.deepEqual(cfg.signup, { domains: ["example.org"] }); + // One organization, closed by default: only people the admins invite. + assert.deepEqual(cfg.signup, {}); assert.equal(cfg.telemetry.enabled, false, "telemetry is off unless asked for"); // Running it again does not overwrite. await assert.rejects(() => main(["init", "--config", file], { runner, log: () => {}, interactive: false, ask: quietAsk() }), /already exists/); diff --git a/lambda/pre-signup/cases.json b/lambda/pre-signup/cases.json new file mode 100644 index 000000000..964fcf222 --- /dev/null +++ b/lambda/pre-signup/cases.json @@ -0,0 +1,19 @@ +[ + { "name": "first admin, nobody signed up yet", "email": "admin@example.com", "org": null, "admin_listed": true, "listed": true, "anyone": false, "now": "2026-10-26T12:00:00Z", "want": "first_admin" }, + { "name": "not listed, nobody signed up yet", "email": "stranger@example.com", "org": null, "anyone": false, "now": "2026-10-26T12:00:00Z", "want": "refused" }, + { "name": "on the config list as an invite, before the first admin", "email": "b@example.com", "org": null, "admin_listed": false, "listed": true, "anyone": false, "now": "2026-10-26T12:00:00Z", "want": "refused" }, + { "name": "a listed admin once the organization exists (no second organization)", "email": "admin2@example.com", "org": { "team_id": "TEAM#org", "domains": [] }, "admin_listed": true, "listed": true, "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "refused" }, + { "name": "a stranger once the organization exists", "email": "x@elsewhere.io", "org": { "team_id": "TEAM#org", "domains": ["example.com"] }, "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "refused" }, + { "name": "an allowed domain", "email": "Ann@Example.com", "org": { "team_id": "TEAM#org", "domains": ["example.com"] }, "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "domain" }, + { "name": "a subdomain of an allowed domain is not that domain", "email": "ann@eu.example.com", "org": { "team_id": "TEAM#org", "domains": ["example.com"] }, "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "refused" }, + { "name": "a lookalike domain", "email": "ann@example.com.evil.io", "org": { "team_id": "TEAM#org", "domains": ["example.com"] }, "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "refused" }, + { "name": "a live invite", "email": "bo@other.io", "org": { "team_id": "TEAM#org", "domains": [] }, "records": [{ "pk": "TEAM#org", "sk": "USER#invite_01", "status": "invited", "invited_at": "2026-10-20T00:00:00Z" }], "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "invite" }, + { "name": "an expired invite", "email": "bo@other.io", "org": { "team_id": "TEAM#org", "domains": [] }, "records": [{ "pk": "TEAM#org", "sk": "USER#invite_01", "status": "invited", "invited_at": "2026-09-01T00:00:00Z" }], "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "refused" }, + { "name": "an invite to some other team", "email": "bo@other.io", "org": { "team_id": "TEAM#org", "domains": [] }, "records": [{ "pk": "TEAM#old", "sk": "USER#invite_01", "status": "invited", "invited_at": "2026-10-20T00:00:00Z" }], "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "refused" }, + { "name": "already a member (signing up again after their account was removed from Cognito)", "email": "m@other.io", "org": { "team_id": "TEAM#org", "domains": [] }, "records": [{ "pk": "TEAM#org", "sk": "USER#abc" }], "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "existing" }, + { "name": "a member of some other team only", "email": "m@other.io", "org": { "team_id": "TEAM#org", "domains": [] }, "records": [{ "pk": "TEAM#old", "sk": "USER#abc" }], "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "refused" }, + { "name": "an older install without the organization yet: a member", "email": "m@other.io", "org": null, "records": [{ "pk": "TEAM#old", "sk": "USER#abc" }], "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "existing" }, + { "name": "an older install without the organization yet: on the config list", "email": "n@example.com", "org": null, "listed": true, "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "listed" }, + { "name": "an older install without the organization yet: a stranger", "email": "n@elsewhere.io", "org": null, "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "refused" }, + { "name": "no email at all", "email": "", "org": { "team_id": "TEAM#org", "domains": ["example.com"] }, "anyone": true, "now": "2026-10-26T12:00:00Z", "want": "refused" } +] diff --git a/lambda/pre-signup/handler.js b/lambda/pre-signup/handler.js new file mode 100644 index 000000000..9376f2c66 --- /dev/null +++ b/lambda/pre-signup/handler.js @@ -0,0 +1,123 @@ +// Cognito pre-sign-up trigger for a self-hosted install: one organization, +// joined only by an admin's invite or an email at a domain the admins allow. +// The first admin from the install config starts it. Runs for every way an +// account is made in the user pool (SignUp with the app client, Google, and +// AdminCreateUser), so a direct Cognito SignUp call is refused too. +// +// The rules are the gateway's (services/gateway/src/routes/sign_in.rs, +// decide_join); both are tested against cases.json. + +const SETTINGS = process.env.SETTINGS_TABLE_NAME; +const USERS = process.env.USERS_TABLE_NAME; +const INVITE_VALID_DAYS = 30; +const REFUSED = + "This CoderHelm is private to one organization. Ask one of its admins to invite you."; + +/** lowercase, and user+tag@x.io is user@x.io (as the gateway stores it). */ +function normalizeEmail(email) { + const e = String(email || "").trim().toLowerCase(); + const at = e.indexOf("@"); + if (at < 0) return e; + return `${e.slice(0, at).split("+")[0]}${e.slice(at)}`; +} + +function emailDomain(email) { + const e = String(email || "").trim(); + const at = e.lastIndexOf("@"); + if (at <= 0) return null; + const d = e.slice(at + 1).toLowerCase(); + return d && d.includes(".") ? d : null; +} + +function inviteExpired(r, now) { + const sent = Date.parse(r.invited_at || r.updated_at || ""); + if (Number.isNaN(sent)) return false; + return sent + INVITE_VALID_DAYS * 86400 * 1000 <= now.getTime(); +} + +/** + * The decision, from the facts: existing, invite, domain, first_admin, + * listed or refused. + */ +function decide(f, now) { + const isUser = (r) => String(r.sk || "").startsWith("USER#"); + const invited = (r) => r.status === "invited"; + const records = f.records || []; + if (f.org) { + const mine = records.filter((r) => isUser(r) && r.pk === f.org.team_id); + if (mine.some((r) => !invited(r))) return "existing"; + if (mine.some((r) => invited(r) && !inviteExpired(r, now))) return "invite"; + const d = emailDomain(f.email); + return d && (f.org.domains || []).includes(d) ? "domain" : "refused"; + } + if (!f.anyone) return f.admin_listed ? "first_admin" : "refused"; + if (records.some((r) => isUser(r) && !invited(r))) return "existing"; + return f.listed ? "listed" : "refused"; +} + +const s = (v) => (v && typeof v.S === "string" ? v.S : undefined); + +function orgFrom(item) { + if (!item || !s(item.team_id)) return null; + return { + team_id: s(item.team_id), + domains: ((item.domains && item.domains.L) || []).map((d) => String(s(d) || "").toLowerCase()), + }; +} + +function recordFrom(item) { + return { pk: s(item.pk), sk: s(item.sk), status: s(item.status), invited_at: s(item.invited_at), updated_at: s(item.updated_at) }; +} + +/** Everything the decision needs, read from the tables. */ +async function gather(db, email) { + const norm = normalizeEmail(email); + const domain = emailDomain(norm); + const get = (pk, sk, consistent) => + db.send("GetItemCommand", { TableName: SETTINGS, Key: { pk: { S: pk }, sk: { S: sk } }, ConsistentRead: !!consistent }); + const [org, anyone, exact, wild, recs] = await Promise.all([ + get("ORG", "META", true), + db.send("ScanCommand", { TableName: USERS, Limit: 1, ProjectionExpression: "pk" }), + norm ? get("ALLOWLIST", `EMAIL#${norm}`) : Promise.resolve({}), + domain ? get("ALLOWLIST", `EMAIL#*@${domain}`) : Promise.resolve({}), + norm + ? db.send("QueryCommand", { + TableName: USERS, + IndexName: "gsi2", + KeyConditionExpression: "gsi2pk = :pk", + ExpressionAttributeValues: { ":pk": { S: `EMAIL#${norm}` } }, + }) + : Promise.resolve({ Items: [] }), + ]); + return { + email: String(email || "").trim(), + org: orgFrom(org.Item), + anyone: (anyone.Count || 0) > 0, + admin_listed: !!exact.Item && s(exact.Item.kind) !== "invite", + listed: !!exact.Item || !!wild.Item, + records: (recs.Items || []).map(recordFrom), + }; +} + +let real; + +/** DynamoDB, by command name (the Lambda runtime's SDK). */ +function dynamo() { + if (!real) { + const sdk = require("@aws-sdk/client-dynamodb"); + const c = new sdk.DynamoDBClient({}); + real = { send: (name, input) => c.send(new sdk[name](input)) }; + } + return real; +} + +async function handler(event, _context, db = dynamo()) { + const email = (event.request && event.request.userAttributes && event.request.userAttributes.email) || ""; + const facts = await gather(db, email); + const outcome = decide(facts, new Date()); + console.log(JSON.stringify({ trigger: event.triggerSource, outcome })); + if (outcome === "refused") throw new Error(REFUSED); + return event; +} + +module.exports = { handler, decide, gather, normalizeEmail, emailDomain }; diff --git a/lambda/pre-signup/handler.test.js b/lambda/pre-signup/handler.test.js new file mode 100644 index 000000000..766a4ecd6 --- /dev/null +++ b/lambda/pre-signup/handler.test.js @@ -0,0 +1,69 @@ +// node --test lambda/pre-signup/handler.test.js +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { decide, handler, normalizeEmail } = require("./handler.js"); +const cases = require("./cases.json"); + +test("every shared join case decides as the gateway does", () => { + assert.ok(cases.length >= 12); + for (const c of cases) { + const facts = { ...c, records: c.records || [] }; + assert.equal(decide(facts, new Date(c.now)), c.want, c.name); + } +}); + +test("emails are matched the way the gateway stores them", () => { + assert.equal(normalizeEmail(" Ann+tag@Example.COM "), "ann@example.com"); +}); + +/** A fake DynamoDB: answers by command name and key. */ +function fakeDb({ org = null, anyone = false, allow = {}, records = [] } = {}) { + const seen = []; + return { + seen, + async send(name, i) { + seen.push(name); + if (name === "GetItemCommand" && i.Key.pk.S === "ORG") return { Item: org || undefined }; + if (name === "GetItemCommand") return { Item: allow[i.Key.sk.S] }; + if (name === "ScanCommand") return { Count: anyone ? 1 : 0 }; + if (name === "QueryCommand") return { Items: records }; + throw new Error(`unexpected ${name}`); + }, + }; +} + +const event = (email, triggerSource = "PreSignUp_SignUp") => ({ + triggerSource, + request: { userAttributes: { email } }, + response: {}, +}); + +test("a direct Cognito sign-up from a stranger is refused", async () => { + const db = fakeDb({ org: { team_id: { S: "TEAM#org" }, domains: { L: [{ S: "example.com" }] } }, anyone: true }); + await assert.rejects(handler(event("x@elsewhere.io"), {}, db), /private to one organization/); +}); + +test("Google sign-ups are held to the same rules", async () => { + const db = fakeDb({ org: { team_id: { S: "TEAM#org" }, domains: { L: [{ S: "example.com" }] } }, anyone: true }); + await assert.rejects(handler(event("x@gmail.com", "PreSignUp_ExternalProvider"), {}, db)); + const ok = await handler(event("ann@example.com", "PreSignUp_ExternalProvider"), {}, db); + assert.equal(ok.triggerSource, "PreSignUp_ExternalProvider"); +}); + +test("an invited person and the first admin get through", async () => { + const invited = fakeDb({ + org: { team_id: { S: "TEAM#org" }, domains: { L: [] } }, + anyone: true, + records: [{ pk: { S: "TEAM#org" }, sk: { S: "USER#invite_1" }, status: { S: "invited" }, invited_at: { S: new Date().toISOString() } }], + }); + await handler(event("bo@other.io"), {}, invited); + const first = fakeDb({ allow: { "EMAIL#admin@example.com": { pk: { S: "ALLOWLIST" } } } }); + await handler(event("admin@example.com"), {}, first); + const asInvite = fakeDb({ allow: { "EMAIL#b@example.com": { kind: { S: "invite" } } } }); + await assert.rejects(handler(event("b@example.com"), {}, asInvite)); +}); + +test("a table it can't read refuses (fails closed)", async () => { + const broken = { async send() { throw new Error("throttled"); } }; + await assert.rejects(handler(event("admin@example.com"), {}, broken), /throttled/); +}); diff --git a/selfhost/launch/bootstrap.mjs b/selfhost/launch/bootstrap.mjs index 5100d879d..f9a97fe77 100644 --- a/selfhost/launch/bootstrap.mjs +++ b/selfhost/launch/bootstrap.mjs @@ -34,7 +34,9 @@ // or another DNS provider) // MODEL_PROVIDER bedrock | anthropic // BEDROCK_PREFIX auto | us. | eu. | apac. | global. | "" (in-region ids) -// SIGNUP_DOMAIN optional email domain anyone may sign up from +// SIGNUP_DOMAIN optional: people with an email at this domain may join +// the organization (empty: only people the admins invite) +// REQUIRE_TWO_FACTOR on | off: start with two-factor sign-in required // TELEMETRY on | off // AUTO_UPDATE on | off; UPDATE_WINDOW ("Sun 03:00", "daily 02:00") and // UPDATE_TIMEZONE (IANA) set its window (admins change them later in Settings) @@ -159,6 +161,7 @@ export function configFromEnv(env, { account, found = null }) { }; const signup = (env.SIGNUP_DOMAIN || "").trim().toLowerCase(); if (signup) cfg.signup = { domains: [signup] }; + if (env.REQUIRE_TWO_FACTOR === "on") cfg.signup = { ...(cfg.signup ?? {}), requireTwoFactor: true }; const updates = updatesFromEnv(env); if (updates) cfg.updates = updates; return cfg; diff --git a/selfhost/launch/bootstrap.test.mjs b/selfhost/launch/bootstrap.test.mjs index 33c65ffe0..bdf81e34f 100644 --- a/selfhost/launch/bootstrap.test.mjs +++ b/selfhost/launch/bootstrap.test.mjs @@ -35,6 +35,10 @@ test("config: a domain in a hosted zone gets a domain identity", () => { assert.deepEqual(cfg.domain, { hostname: "ch.example.com", hostedZone: "example.com" }); assert.equal(cfg.email.identity, "example.com"); assert.deepEqual(cfg.signup, { domains: ["example.com"] }); + // Two-factor sign-in required from the start. + const tf = configFromEnv({ ...ENV, REQUIRE_TWO_FACTOR: "on" }, { account: "123456789012" }); + assert.deepEqual(tf.signup, { requireTwoFactor: true }); + assert.equal(configFromEnv({ ...ENV, REQUIRE_TWO_FACTOR: "off" }, { account: "123456789012" }).signup, undefined); }); test("config: anthropic has no Bedrock prefix; explicit prefixes are kept", () => { diff --git a/services/gateway/src/auth/jwt.rs b/services/gateway/src/auth/jwt.rs index aa0d13715..181866c38 100644 --- a/services/gateway/src/auth/jwt.rs +++ b/services/gateway/src/auth/jwt.rs @@ -1,5 +1,36 @@ use crate::models::Claims; use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; +use serde::{Deserialize, Serialize}; + +/// How a session signed in, carried in the session token beside its claims: +/// whether the sign-in passed a second factor, and the way in (`password`, +/// `google` or `github`). A token from before this existed reads as no second +/// factor, so a required second factor reaches old sessions too. +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] +pub struct SignInProof { + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub mfa: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub via: Option, +} + +impl SignInProof { + pub fn new(mfa: bool, via: &str) -> Self { + Self { + mfa, + via: Some(via.to_string()), + } + } +} + +/// A session token: the claims and the sign-in proof, flattened into one. +#[derive(Serialize)] +struct SessionToken<'a> { + #[serde(flatten)] + claims: &'a Claims, + #[serde(flatten)] + proof: &'a SignInProof, +} pub fn create_token( user_id: &str, @@ -9,6 +40,30 @@ pub fn create_token( github_login: Option<&str>, secret: &str, ttl_secs: u64, +) -> Result { + create_session_token( + user_id, + team_id, + email, + role, + github_login, + &SignInProof::default(), + secret, + ttl_secs, + ) +} + +/// A session token that records how the person signed in. +#[allow(clippy::too_many_arguments)] +pub fn create_session_token( + user_id: &str, + team_id: &str, + email: &str, + role: &str, + github_login: Option<&str>, + proof: &SignInProof, + secret: &str, + ttl_secs: u64, ) -> Result { let now = chrono::Utc::now().timestamp() as u64; let claims = Claims { @@ -26,11 +81,80 @@ pub fn create_token( }; encode( &Header::default(), - &claims, + &SessionToken { + claims: &claims, + proof, + }, &EncodingKey::from_secret(secret.as_bytes()), ) } +/// The sign-in proof of a session token. Call it only on a token +/// [`validate_token`] accepted; anything unreadable is no proof. +pub fn read_proof(token: &str, secret: &str) -> SignInProof { + let mut validation = Validation::default(); + validation.set_audience(&["coderhelm-dashboard"]); + decode::( + token, + &DecodingKey::from_secret(secret.as_bytes()), + &validation, + ) + .map(|t| t.claims) + .unwrap_or_default() +} + +/// Audience of the short token between a Google or GitHub sign-in and its +/// second step: accepted only by `POST /auth/2fa/verify`. +pub const SECOND_STEP_AUDIENCE: &str = "coderhelm-2fa"; + +/// Who is between a federated sign-in and their two-factor code. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] +pub struct SecondStep { + pub sub: String, + pub team_id: String, + pub email: String, + pub role: String, + #[serde(default)] + pub github_login: Option, + pub via: String, + pub aud: String, + pub iat: u64, + pub exp: u64, +} + +pub fn create_second_step( + step: &SecondStep, + secret: &str, + ttl_secs: u64, +) -> Result { + let now = chrono::Utc::now().timestamp() as u64; + let s = SecondStep { + aud: SECOND_STEP_AUDIENCE.to_string(), + iat: now, + exp: now + ttl_secs, + ..step.clone() + }; + encode( + &Header::default(), + &s, + &EncodingKey::from_secret(secret.as_bytes()), + ) +} + +pub fn validate_second_step( + token: &str, + secret: &str, +) -> Result { + let mut validation = Validation::default(); + validation.set_audience(&[SECOND_STEP_AUDIENCE]); + Ok(decode::( + token, + &DecodingKey::from_secret(secret.as_bytes()), + &validation, + )? + .claims) +} + /// Audience of the brain chat's short-lived stream token: accepted only by /// `/api/brain/stream`, never as a session or a plan chat token. pub const BRAIN_AUDIENCE: &str = "coderhelm-brain"; @@ -129,6 +253,41 @@ mod tests { assert_eq!((back.sub.as_str(), back.role.as_str()), ("u", "member")); } + #[test] + fn a_session_carries_its_sign_in_proof_and_old_tokens_have_none() { + let secret = "test-jwt-secret-at-least-32-chars!"; + let proof = SignInProof::new(true, "google"); + let t = + create_session_token("u", "t", "e@x.com", "member", None, &proof, secret, 300).unwrap(); + assert_eq!(validate_token(&t, secret).unwrap().sub, "u"); + assert_eq!(read_proof(&t, secret), proof); + let old = create_token("u", "t", "e@x.com", "member", None, secret, 300).unwrap(); + assert!(!read_proof(&old, secret).mfa); + // A proof is read only from a token signed with the secret. + assert!(!read_proof(&t, "another-secret-of-at-least-32-chars").mfa); + } + + #[test] + fn a_second_step_token_is_not_a_session_and_a_session_is_not_one() { + let secret = "test-jwt-secret-at-least-32-chars!"; + let step = SecondStep { + sub: "USER#1".into(), + team_id: "TEAM#a".into(), + email: "a@x.com".into(), + role: "member".into(), + github_login: None, + via: "github".into(), + aud: String::new(), + iat: 0, + exp: 0, + }; + let t = create_second_step(&step, secret, 300).unwrap(); + assert!(validate_token(&t, secret).is_err()); + assert_eq!(validate_second_step(&t, secret).unwrap().sub, "USER#1"); + let session = create_token("u", "t", "e@x.com", "member", None, secret, 300).unwrap(); + assert!(validate_second_step(&session, secret).is_err()); + } + #[test] fn test_invalid_token_rejected() { let result = validate_token("not.a.valid.token", "secret"); diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 11b9efbc2..f80c60fb4 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -526,6 +526,18 @@ async fn main() -> Result<(), Error> { .route("/users/mfa/setup", post(routes::users::mfa_setup)) .route("/users/mfa/verify", post(routes::users::mfa_verify_setup)) .route("/users/mfa", delete(routes::users::mfa_disable)) + .route("/users/2fa", get(routes::sign_in::my_status)) + .route("/users/2fa/app/setup", post(routes::sign_in::app_setup)) + .route("/users/2fa/app/verify", post(routes::sign_in::app_verify)) + .route("/users/2fa/app", delete(routes::sign_in::app_disable)) + .route( + "/users/:user_id/2fa/reset", + post(routes::sign_in::reset_two_factor), + ) + .route( + "/sign-in", + get(routes::sign_in::get_settings).put(routes::sign_in::update_settings), + ) // Plan endpoints .route( "/plans", @@ -1193,6 +1205,7 @@ async fn main() -> Result<(), Error> { .route("/forgot-password", post(routes::auth::forgot_password)) .route("/confirm-reset", post(routes::auth::confirm_reset)) .route("/mfa/verify", post(routes::auth::mfa_verify)) + .route("/2fa/verify", post(routes::sign_in::verify_second_step)) .route("/google", get(routes::auth::google_login)) .route("/google/callback", get(routes::auth::google_callback)) .route("/github", get(routes::auth::github_login)) diff --git a/services/gateway/src/middleware/auth.rs b/services/gateway/src/middleware/auth.rs index 9cac3197b..cffc3eec8 100644 --- a/services/gateway/src/middleware/auth.rs +++ b/services/gateway/src/middleware/auth.rs @@ -13,7 +13,7 @@ use crate::auth::jwt; use crate::models::{ApiKeyRef, Claims}; use crate::openapi; use crate::permissions::{self, Access, Capability}; -use crate::routes::{roles, support_access}; +use crate::routes::{roles, sign_in, support_access}; use crate::AppState; /// Session TTL: 7 days. Used by both token creation and cookie Max-Age. @@ -114,6 +114,17 @@ pub async fn require_auth( .extensions() .get::() .and_then(|m| permissions::routed_handler(req.method().as_str(), m.as_str())); + // How this session signed in. On a self-hosted install that requires + // two-factor sign-in, a session without a second factor reaches only the + // screens that set one up; the rule is read on every request, so sessions + // from before it was turned on are held at their next request. + let proof = jwt::read_proof(token, &state.secrets.jwt_secret); + if sign_in::applies() { + if let Err(held) = sign_in::check_session(&state, &proof, handler).await { + return Ok(held); + } + } + let holder = roles::holder_for(&state, &claims).await; match permissions::resolve_access(&holder, handler) { Access::Deny { capability } => return Ok(refused_for(capability)), @@ -127,6 +138,7 @@ pub async fn require_auth( note_activity(&state, &claims.team_id, &claims.sub).await; req.extensions_mut().insert(claims.clone()); + req.extensions_mut().insert(proof.clone()); let mut response = next.run(req).await; // The refreshed token carries the member's CURRENT role, and a removed @@ -139,12 +151,14 @@ pub async fn require_auth( }; if let Some(role) = current_role { - if let Ok(new_token) = jwt::create_token( + // The refreshed session keeps how it signed in. + if let Ok(new_token) = jwt::create_session_token( &claims.sub, &claims.team_id, &claims.email, &role, claims.github_login.as_deref(), + &proof, &state.secrets.jwt_secret, SESSION_TTL_SECS, ) { diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 82e8ec32c..4feba3744 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -144,6 +144,10 @@ pub const CAPABILITIES: &[Capability] = &[ "users::mfa_setup", "users::mfa_verify_setup", "users::mfa_disable", + "sign_in::my_status", + "sign_in::app_setup", + "sign_in::app_verify", + "sign_in::app_disable", "api::update_notification_prefs", ], }, @@ -334,6 +338,18 @@ pub const CAPABILITIES: &[Capability] = &[ "users::link_github", ], }, + Capability { + key: "sign_in", + label: "Change who may join (allowed email domains) and whether two-factor sign-in is required, see who has it, and reset a person's two-factor sign-in (self-hosted installs)", + min_role: "admin", + // Sign-in rules stay with built-in admins and owners + // (`NEVER_IN_CUSTOM_ROLES`). + handlers: &[ + "sign_in::get_settings", + "sign_in::update_settings", + "sign_in::reset_two_factor", + ], + }, Capability { key: "roles", label: "Create, edit and delete custom roles, give people a custom role, and see the log of role changes", @@ -732,7 +748,7 @@ pub const CUSTOM_PREFIX: &str = "custom:"; /// Capabilities a custom role can never hold, whatever the table says about /// them: managing roles, and support (checked by built-in role inside the /// support handlers), stay with built-in admins and owners. -pub const NEVER_IN_CUSTOM_ROLES: &[&str] = &["roles", "support", "system", "system.models"]; +pub const NEVER_IN_CUSTOM_ROLES: &[&str] = &["roles", "sign_in", "support", "system", "system.models"]; /// The id in a `custom:` role, or `None` for a built-in role. pub fn custom_role_id(role: &str) -> Option<&str> { diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index a324b97fc..4a64d915b 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -440,6 +440,7 @@ pub async fn list_teams( pub async fn switch_team( State(state): State>, Extension(claims): Extension, + proof: Option>, Json(body): Json, ) -> Result { let target_team = body["team_id"].as_str().ok_or(StatusCode::BAD_REQUEST)?; @@ -462,13 +463,15 @@ pub async fn switch_team( .and_then(|v| v.as_s().ok()) .map_or("member", |v| v); - // Re-issue JWT with new team_id and correct role - let token = jwt::create_token( + // Re-issue JWT with new team_id and correct role, keeping how the + // session signed in. + let token = jwt::create_session_token( &claims.sub, target_team, &claims.email, target_role, claims.github_login.as_deref(), + &proof.map(|p| p.0).unwrap_or_default(), &state.secrets.jwt_secret, SESSION_TTL_SECS, ) diff --git a/services/gateway/src/routes/auth.rs b/services/gateway/src/routes/auth.rs index 3b032bb4d..1adb7638b 100644 --- a/services/gateway/src/routes/auth.rs +++ b/services/gateway/src/routes/auth.rs @@ -12,7 +12,8 @@ use std::sync::Arc; use tracing::{error, info, warn}; use super::oauth_signin::{self, CallbackQuery, Provider, Reason, SignInFailure}; -use crate::auth::jwt; +use super::sign_in::{self, Join}; +use crate::auth::jwt::{self, SecondStep, SignInProof}; use crate::middleware::auth::SESSION_TTL_SECS; use crate::AppState; @@ -175,8 +176,22 @@ pub async fn signup( )); } - // Closed beta: check allowlist - if !is_email_allowed(&state, &email).await { + // A self-hosted install: one organization, joined only by invite or an + // allowed email domain (the first admin starts it). + if sign_in::applies() { + let join = sign_in::may_sign_up(&state, &email).await.map_err(|e| { + error!("Sign-up check failed: {e}"); + ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({ "error": "Sign-up is unavailable just now. Try again shortly." })), + ) + })?; + if !join.allowed() { + info!(outcome = join.key(), "Self-hosted sign-up refused"); + return Err(not_invited_json()); + } + } else if !is_email_allowed(&state, &email).await { + // Closed beta: check allowlist return Err(( StatusCode::FORBIDDEN, Json(serde_json::json!({ @@ -217,7 +232,11 @@ pub async fn signup( } let result = req.send().await.map_err(|e| { - let msg = format!("{e}"); + let msg = format!("{e:?}"); + // The pre-sign-up trigger said no (a self-hosted install's rules). + if msg.contains("UserLambdaValidationException") { + return not_invited_json(); + } if msg.contains("UsernameExistsException") { return ( StatusCode::CONFLICT, @@ -296,6 +315,15 @@ pub async fn verify_email( let cognito_sub = user_result.username(); + // A self-hosted install makes no team here: the person's place in the + // organization is settled at their first sign-in. + if sign_in::applies() { + return Ok(Json(serde_json::json!({ + "status": "verified", + "message": "Email verified. You can now log in." + }))); + } + // Someone invited (or already on a team) lands there at first sign-in: // no personal team for them. A failed lookup falls back to making one, as // before. @@ -438,7 +466,13 @@ pub async fn login_email( .access_token() .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?; - issue_session_from_cognito(&state, &email, access_token).await + issue_session_from_cognito( + &state, + &email, + access_token, + &SignInProof::new(false, "password"), + ) + .await } // ── MFA verify ─────────────────────────────────────────────────────── @@ -498,7 +532,136 @@ pub async fn mfa_verify( .and_then(|a| a.value().map(|v| v.to_string())) .unwrap_or_default(); - issue_session_from_cognito(&state, &email, access_token).await + let resp = issue_session_from_cognito( + &state, + &email, + access_token, + &SignInProof::new(true, "password"), + ) + .await?; + if sign_in::applies() && resp.status().is_success() { + let sub = format!("USER#{}", user.username()); + if let Some(team) = cognito_member_team(&state, &email, &sub).await { + sign_in::note_factor(&state, &team, &sub, Some("cognito")).await; + } + } + Ok(resp) +} + +/// The organization team a Cognito user's own record is in, if any. +async fn cognito_member_team(state: &AppState, email: &str, sub: &str) -> Option { + let org = sign_in::load_org(state).await.ok()??; + state + .dynamo + .get_item() + .table_name(&state.config.users_table_name) + .key("pk", attr_s(&org.team_id)) + .key("sk", attr_s(sub)) + .send() + .await + .ok()? + .item + .filter(|i| { + i.get("email") + .and_then(|v| v.as_s().ok()) + .map(|e| normalize_email(e)) + == Some(normalize_email(email)) + }) + .map(|_| org.team_id) +} + +/// The answer to someone a self-hosted install won't let in. +fn not_invited_json() -> (StatusCode, Json) { + ( + StatusCode::FORBIDDEN, + Json(serde_json::json!({ "error": sign_in::NOT_INVITED, "code": "not_invited" })), + ) +} + +/// Where a refused Google or GitHub sign-in lands. +fn not_invited_url(dash: &str) -> String { + format!("{dash}?error=not_invited") +} + +/// A self-hosted install: the organization record this person signs in to, +/// made when the rules let them in (the first admin, an invite, an allowed +/// domain). `None` when they may not join. +async fn selfhost_landing( + state: &AppState, + email: &str, + user_id: &str, + name: &str, + avatar: &str, +) -> Result>, String> { + let facts = sign_in::facts_for(state, email).await?; + let join = sign_in::decide_join(&facts, chrono::Utc::now()); + info!(outcome = join.key(), "Self-hosted sign-in"); + match join { + Join::Member { team_id, user_id } => Ok(facts + .records + .iter() + .find(|i| { + i.get("pk").and_then(|v| v.as_s().ok()) == Some(&team_id) + && i.get("sk").and_then(|v| v.as_s().ok()) == Some(&user_id) + }) + .cloned()), + Join::Invite => { + let Some(org) = facts.org.as_ref() else { + return Ok(None); + }; + let mine: Vec<_> = facts + .records + .iter() + .filter(|i| i.get("pk").and_then(|v| v.as_s().ok()) == Some(&org.team_id)) + .cloned() + .collect(); + Ok(accept_pending_invites(state, &mine, user_id, email) + .await + .into_iter() + .next()) + } + Join::Domain => { + let Some(org) = facts.org.as_ref() else { + return Ok(None); + }; + sign_in::join_by_domain(state, org, user_id, email, name, avatar) + .await + .map(Some) + } + Join::FirstAdmin => { + let Some(team_id) = sign_in::create_org(state, user_id, email, name, avatar).await? + else { + return Ok(None); + }; + Ok(state + .dynamo + .get_item() + .table_name(&state.config.users_table_name) + .key("pk", attr_s(&team_id)) + .key("sk", attr_s(user_id)) + .consistent_read(true) + .send() + .await + .map_err(|e| format!("{e}"))? + .item) + } + Join::Listed | Join::Refused => Ok(None), + } +} + +/// The landing record's team, user id, role and GitHub login. +fn landing_parts( + item: &HashMap, +) -> (String, String, String, Option) { + let g = |k: &str| item.get(k).and_then(|v| v.as_s().ok()).cloned(); + ( + g("pk").unwrap_or_default(), + g("sk").unwrap_or_default(), + g("role") + .filter(|r| !r.is_empty()) + .unwrap_or_else(|| "member".to_string()), + g("github_login").filter(|l| !l.is_empty()), + ) } // ── Forgot password ────────────────────────────────────────────────── @@ -762,6 +925,53 @@ async fn google_callback_inner( .and_then(|r| r.items) .unwrap_or_default(); + if sign_in::applies() { + let dash = common::public_urls::app_url(&state.config.stage); + let landed = selfhost_landing( + state, + &email, + &format!("USER#{cognito_sub}"), + name.as_deref().unwrap_or(""), + picture.as_deref().unwrap_or(""), + ) + .await + .map_err(|e| SignInFailure::new(P, Reason::Server, "join", e))?; + let Some(record) = landed else { + return Ok(Redirect::temporary(¬_invited_url(dash)).into_response()); + }; + let (team_id, user_id, role, github_login) = landing_parts(&record); + touch_last_login(state, &team_id, &user_id).await; + let step = SecondStep { + sub: user_id.clone(), + team_id: team_id.clone(), + email: email.clone(), + role: role.clone(), + github_login: github_login.clone(), + via: "google".into(), + aud: String::new(), + iat: 0, + exp: 0, + }; + if let Some(resp) = sign_in::second_step(state, step, dash) + .await + .map_err(|e| SignInFailure::new(P, Reason::Server, "second_step", e))? + { + return Ok(resp); + } + let token = jwt::create_session_token( + &user_id, + &team_id, + &email, + &role, + github_login.as_deref(), + &SignInProof::new(false, "google"), + &state.secrets.jwt_secret, + SESSION_TTL_SECS, + ) + .map_err(|e| SignInFailure::new(P, Reason::Server, "session_token", e))?; + return Ok(session_redirect(P, &token, dash)); + } + // Closed beta: only allow new users on the allowlist (existing users can always log in) if existing.is_empty() && !is_email_allowed(state, &email).await { let dash = common::public_urls::app_url(&state.config.stage); @@ -965,8 +1175,12 @@ async fn github_callback_inner( .map_err(|e| SignInFailure::new(P, Reason::Provider, "installations", e))?; // Check if user already has a session (connecting GitHub to existing account) - let existing_claims = extract_cookie(cookie_header(headers), "__Host-coderhelm_session") - .and_then(|token| jwt::validate_token(token, &state.secrets.jwt_secret).ok()); + let session_token = extract_cookie(cookie_header(headers), "__Host-coderhelm_session"); + let existing_claims = + session_token.and_then(|token| jwt::validate_token(token, &state.secrets.jwt_secret).ok()); + let existing_proof = session_token + .map(|t| jwt::read_proof(t, &state.secrets.jwt_secret)) + .unwrap_or_default(); let now = chrono::Utc::now().to_rfc3339(); @@ -1095,13 +1309,15 @@ async fn github_callback_inner( ); } - // Re-issue JWT with github_login (keep the user's existing team) - let token = jwt::create_token( + // Re-issue JWT with github_login (keep the user's existing team and + // how they signed in) + let token = jwt::create_session_token( &claims.sub, &claims.team_id, &claims.email, &claims.role, Some(github_login), + &existing_proof, &state.secrets.jwt_secret, SESSION_TTL_SECS, ) @@ -1156,6 +1372,38 @@ async fn github_callback_inner( let existing_user = existing_by_github.or(existing_by_email); + // A self-hosted install: only the organization's own records, or a join + // its rules allow; never a new team. + let existing_user = if sign_in::applies() { + let org_team = sign_in::ensure_org(state) + .await + .map_err(|e| SignInFailure::new(P, Reason::Server, "join", e))? + .map(|o| o.team_id); + let in_org = existing_user.filter(|i| { + org_team.is_some() && i.get("pk").and_then(|v| v.as_s().ok()) == org_team.as_ref() + }); + let landed = match in_org { + Some(rec) => Some(rec), + None if !email.is_empty() => selfhost_landing( + state, + email, + &github_user_id, + user["name"].as_str().unwrap_or(""), + user["avatar_url"].as_str().unwrap_or(""), + ) + .await + .map_err(|e| SignInFailure::new(P, Reason::Server, "join", e))?, + None => None, + }; + let Some(rec) = landed else { + let dash = common::public_urls::app_url(&state.config.stage); + return Ok(Redirect::temporary(¬_invited_url(dash)).into_response()); + }; + Some(rec) + } else { + existing_user + }; + let has_existing_record = existing_user.is_some(); // Closed beta: check allowlist for new GitHub users @@ -1381,12 +1629,35 @@ async fn github_callback_inner( "User authenticated via GitHub" ); - let token = jwt::create_token( + if sign_in::applies() { + touch_last_login(state, &team_id, &user_id).await; + let step = SecondStep { + sub: user_id.clone(), + team_id: team_id.clone(), + email: email.to_string(), + role: role.clone(), + github_login: Some(github_login.to_string()), + via: "github".into(), + aud: String::new(), + iat: 0, + exp: 0, + }; + let dash = common::public_urls::app_url(&state.config.stage); + if let Some(resp) = sign_in::second_step(state, step, dash) + .await + .map_err(|e| SignInFailure::new(P, Reason::Server, "second_step", e))? + { + return Ok(resp); + } + } + + let token = jwt::create_session_token( &user_id, &team_id, email, &role, Some(github_login), + &SignInProof::new(false, "github"), &state.secrets.jwt_secret, SESSION_TTL_SECS, ) @@ -1568,6 +1839,7 @@ async fn issue_session_from_cognito( state: &Arc, email: &str, access_token: &str, + proof: &SignInProof, ) -> Result { // Get Cognito user info let user = state @@ -1583,6 +1855,29 @@ async fn issue_session_from_cognito( let cognito_sub = user.username(); + if sign_in::applies() { + let landed = selfhost_landing(state, email, &format!("USER#{cognito_sub}"), "", "") + .await + .map_err(|e| { + error!("Self-hosted sign-in check failed: {e}"); + StatusCode::SERVICE_UNAVAILABLE + })?; + let Some(record) = landed else { + return Ok(not_invited_json().into_response()); + }; + let (team_id, user_id, role, github_login) = landing_parts(&record); + touch_last_login(state, &team_id, &user_id).await; + return session_json( + state, + &team_id, + &user_id, + email, + &role, + github_login.as_deref(), + proof, + ); + } + // Look up user by email (GSI2) — includes personal team + any pending invites let existing = state .dynamo @@ -1686,13 +1981,34 @@ async fn issue_session_from_cognito( }; touch_last_login(state, &team_id, &user_id).await; - - let token = jwt::create_token( - &user_id, + session_json( + state, &team_id, + &user_id, email, &role, github_login.as_deref(), + proof, + ) +} + +/// The JSON answer to an email sign-in, with its session cookie. +fn session_json( + state: &AppState, + team_id: &str, + user_id: &str, + email: &str, + role: &str, + github_login: Option<&str>, + proof: &SignInProof, +) -> Result { + let token = jwt::create_session_token( + user_id, + team_id, + email, + role, + github_login, + proof, &state.secrets.jwt_secret, SESSION_TTL_SECS, ) diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index eb7bed098..0c7b4241c 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -49,6 +49,7 @@ pub mod run_search; pub mod search; pub mod setup; pub mod setup_checks; +pub mod sign_in; pub mod skills; pub mod sns; pub mod support; diff --git a/services/gateway/src/routes/sign_in.rs b/services/gateway/src/routes/sign_in.rs new file mode 100644 index 000000000..de5901348 --- /dev/null +++ b/services/gateway/src/routes/sign_in.rs @@ -0,0 +1,2044 @@ +//! Who may join a self-hosted install, and the two-factor rule. +//! +//! A self-hosted install has exactly one organization: one team, owned by the +//! first admin from setup. Nobody can make another one, and nobody signs up +//! on their own. A person joins only with an admin's invite, or with an email +//! at a domain the admins allow. Every way in goes through [`decide_join`]: +//! email sign-up, the email sign-in that makes a person's first record, +//! Google, GitHub, and the Cognito pre-sign-up trigger +//! (`lambda/pre-signup`, which reads the same cases from +//! `lambda/pre-signup/cases.json`). +//! +//! Storage, in the settings table: +//! - `pk = ORG`, `sk = META`: the organization (its team, the allowed +//! domains, whether two-factor sign-in is required and since when). +//! - `pk = ALLOWLIST`, `sk = EMAIL#...`: the install config's first-boot +//! list. The first admin comes from it; when the organization is made, its +//! other addresses become invites and its domains the allowed domains. +//! After that, admins change both in Settings, Sign-in. +//! +//! Two-factor: password accounts use Cognito's authenticator-app (TOTP) MFA. +//! Google and GitHub sign-ins never pass through Cognito MFA, so CoderHelm +//! asks for its own authenticator-app code after them (secret sealed with +//! the install's KMS key on the member record). The session token records +//! whether its sign-in passed a second factor ([`SignInProof`]); with the +//! rule on, the auth middleware lets a session without one reach only the +//! screens that set it up ([`gate`]). The rule is read on every request, so +//! sessions from before it was turned on are held at their next request. API +//! keys are not people and are not affected. +//! +//! The hosted deployment keeps its behavior: none of this applies there. + +use aws_sdk_dynamodb::types::AttributeValue; +use axum::{ + extract::{Extension, Path, State}, + http::{header, HeaderMap, HeaderValue, StatusCode}, + response::{IntoResponse, Response}, + Json, +}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::sync::Arc; +use tracing::{error, info, warn}; + +use crate::auth::jwt::{self, SecondStep, SignInProof}; +use crate::middleware::auth::SESSION_TTL_SECS; +use crate::models::Claims; +use crate::routes::auth::normalize_email; +use crate::AppState; + +type Item = HashMap; +type ApiError = (StatusCode, Json); + +pub const ORG_PK: &str = "ORG"; +pub const ORG_SK: &str = "META"; +/// Most domains an organization may allow. +pub const MAX_DOMAINS: usize = 20; +/// The pending second step after a Google or GitHub sign-in. +pub const SECOND_STEP_COOKIE: &str = "__Host-coderhelm_2fa"; +const SECOND_STEP_SECS: u64 = 300; + +/// The words a refused person reads. +pub const NOT_INVITED: &str = + "This CoderHelm is private to one organization. Ask one of its admins to invite you."; + +fn fail(code: StatusCode, msg: &str) -> ApiError { + (code, Json(json!({ "error": msg }))) +} + +fn fail_code(code: StatusCode, msg: &str, key: &str) -> ApiError { + (code, Json(json!({ "error": msg, "code": key }))) +} + +fn internal(context: &str, e: impl std::fmt::Display) -> ApiError { + error!("{context}: {e}"); + fail( + StatusCode::INTERNAL_SERVER_ERROR, + "Something went wrong on our side. Try again.", + ) +} + +fn attr_s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +fn s<'a>(item: &'a Item, key: &str) -> &'a str { + item.get(key) + .and_then(|v| v.as_s().ok()) + .map_or("", String::as_str) +} + +/// Admins and owners only. +fn admin(claims: &Claims) -> Result<(), ApiError> { + claims + .require_role(3) + .map_err(|_| fail(StatusCode::FORBIDDEN, "Only admins and owners can do that.")) +} + +/// Only on a self-hosted install. +pub fn applies() -> bool { + super::setup_checks::self_hosted() +} + +// ── The organization ──────────────────────────────────────────────── + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Org { + pub team_id: String, + /// Email domains whose people may join, lowercase. + pub domains: Vec, + pub require_2fa: bool, + /// When the rule was last turned on. + pub require_2fa_since: Option, +} + +impl Org { + pub fn from_item(item: &Item) -> Option { + let team_id = s(item, "team_id"); + if team_id.is_empty() { + return None; + } + let domains = item + .get("domains") + .and_then(|v| v.as_l().ok()) + .map(|l| { + l.iter() + .filter_map(|d| d.as_s().ok()) + .map(|d| d.to_lowercase()) + .collect() + }) + .unwrap_or_default(); + Some(Org { + team_id: team_id.to_string(), + domains, + require_2fa: item + .get("require_2fa") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false), + require_2fa_since: Some(s(item, "require_2fa_since")) + .filter(|v| !v.is_empty()) + .map(str::to_string), + }) + } +} + +/// The organization record, if there is one. +pub async fn load_org(state: &AppState) -> Result, String> { + let out = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(ORG_PK)) + .key("sk", attr_s(ORG_SK)) + .consistent_read(true) + .send() + .await + .map_err(|e| format!("{e}"))?; + Ok(out.item().and_then(Org::from_item)) +} + +// ── Who may join ──────────────────────────────────────────────────── + +/// What a person's join is decided from. +#[derive(Debug, Clone, Default)] +pub struct JoinFacts { + pub email: String, + pub org: Option, + /// Their records by email (users table, GSI2). + pub records: Vec, + /// On the config list as an admin (an exact address not marked as an + /// invite): may become the first admin while nobody has signed up. + pub admin_listed: bool, + /// On the config list at all (address or domain). + pub listed: bool, + /// Someone already has an account on this install. + pub anyone: bool, +} + +/// The decision. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Join { + /// Already in the organization: this record. + Member { + team_id: String, + user_id: String, + }, + /// A live invite to the organization. + Invite, + /// Their email domain is allowed. + Domain, + /// The first admin: makes the organization. + FirstAdmin, + /// An install from before the organization existed: on the config list. + /// The organization is made at their first sign-in. + Listed, + Refused, +} + +impl Join { + pub fn allowed(&self) -> bool { + *self != Join::Refused + } + pub fn key(&self) -> &'static str { + match self { + Join::Member { .. } => "existing", + Join::Invite => "invite", + Join::Domain => "domain", + Join::FirstAdmin => "first_admin", + Join::Listed => "listed", + Join::Refused => "refused", + } + } +} + +/// The part of an email after the `@`, lowercase. +pub fn email_domain(email: &str) -> Option { + let (local, domain) = email.trim().rsplit_once('@')?; + if local.is_empty() || domain.is_empty() || !domain.contains('.') { + return None; + } + Some(domain.to_lowercase()) +} + +fn is_invite(item: &Item) -> bool { + s(item, "status") == "invited" +} + +fn is_user(item: &Item) -> bool { + s(item, "sk").starts_with("USER#") +} + +/// The one place a join is decided. Pure: the caller gathers the facts. +pub fn decide_join(f: &JoinFacts, now: chrono::DateTime) -> Join { + match &f.org { + Some(org) => { + let in_org = |i: &&Item| is_user(i) && s(i, "pk") == org.team_id; + if let Some(m) = f.records.iter().filter(in_org).find(|i| !is_invite(i)) { + return Join::Member { + team_id: org.team_id.clone(), + user_id: s(m, "sk").to_string(), + }; + } + if f.records + .iter() + .filter(in_org) + .any(|i| is_invite(i) && !super::users::invite_expired(i, now)) + { + return Join::Invite; + } + match email_domain(&f.email) { + Some(d) if org.domains.contains(&d) => Join::Domain, + _ => Join::Refused, + } + } + None if !f.anyone => { + if f.admin_listed { + Join::FirstAdmin + } else { + Join::Refused + } + } + None => { + if let Some(m) = f.records.iter().find(|i| is_user(i) && !is_invite(i)) { + Join::Member { + team_id: s(m, "pk").to_string(), + user_id: s(m, "sk").to_string(), + } + } else if f.listed { + Join::Listed + } else { + Join::Refused + } + } + } +} + +/// The config list's word on an email: (admin_listed, listed). +async fn config_listing(state: &AppState, email: &str) -> (bool, bool) { + let get = |sk: String| async move { + state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s("ALLOWLIST")) + .key("sk", attr_s(&sk)) + .send() + .await + .ok() + .and_then(|r| r.item) + }; + let email = normalize_email(email); + let exact = get(format!("EMAIL#{email}")).await; + let admin = exact.as_ref().is_some_and(|i| s(i, "kind") != "invite"); + let domain = match email_domain(&email) { + Some(d) => get(format!("EMAIL#*@{d}")).await.is_some(), + None => false, + }; + (admin, exact.is_some() || domain) +} + +async fn records_by_email(state: &AppState, email: &str) -> Result, String> { + state + .dynamo + .query() + .table_name(&state.config.users_table_name) + .index_name("gsi2") + .key_condition_expression("gsi2pk = :pk") + .expression_attribute_values(":pk", attr_s(&format!("EMAIL#{}", normalize_email(email)))) + .send() + .await + .map(|r| r.items().to_vec()) + .map_err(|e| format!("{e}")) +} + +async fn anyone_signed_up(state: &AppState) -> bool { + !super::setup_checks::setup_open(state).await +} + +/// The facts for `email`, with the organization made first on an install +/// from before it existed (see [`ensure_org`]). +pub async fn facts_for(state: &AppState, email: &str) -> Result { + let anyone = anyone_signed_up(state).await; + let org = if anyone { + ensure_org(state).await? + } else { + load_org(state).await? + }; + let (admin_listed, listed) = config_listing(state, email).await; + Ok(JoinFacts { + email: email.to_string(), + org, + records: if email.is_empty() { + Vec::new() + } else { + records_by_email(state, email).await? + }, + admin_listed, + listed, + anyone, + }) +} + +/// Whether `email` may make an account (`POST /auth/signup`). +pub async fn may_sign_up(state: &AppState, email: &str) -> Result { + let facts = facts_for(state, email).await?; + Ok(decide_join(&facts, chrono::Utc::now())) +} + +/// The organization, made from the oldest team on an install that has people +/// but no organization record yet (an install from before this existed). +pub async fn ensure_org(state: &AppState) -> Result, String> { + if let Some(org) = load_org(state).await? { + return Ok(Some(org)); + } + let mut oldest: Option<(String, String)> = None; + let mut start: Option = None; + loop { + let out = state + .dynamo + .scan() + .table_name(&state.config.teams_table_name) + .filter_expression("sk = :m") + .expression_attribute_values(":m", attr_s("META")) + .set_exclusive_start_key(start) + .send() + .await + .map_err(|e| format!("{e}"))?; + for i in out.items() { + let key = (s(i, "created_at").to_string(), s(i, "team_id").to_string()); + if key.1.is_empty() { + continue; + } + if oldest.as_ref().is_none_or(|o| key < *o) { + oldest = Some(key); + } + } + match out.last_evaluated_key() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => break, + } + } + let Some((_, team_id)) = oldest else { + return Ok(None); + }; + info!(%team_id, "Making the organization from the oldest team"); + claim_org(state, &team_id, "adopted", "").await +} + +/// Writes the organization record once; whoever comes second reads the +/// first one's. The config's domains, invite list and two-factor default +/// come along (first boot only). +async fn claim_org( + state: &AppState, + team_id: &str, + how: &str, + creator_email: &str, +) -> Result, String> { + let seed = config_seed(state).await; + let now = chrono::Utc::now().to_rfc3339(); + let mut put = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", attr_s(ORG_PK)) + .item("sk", attr_s(ORG_SK)) + .item("team_id", attr_s(team_id)) + .item( + "domains", + AttributeValue::L(seed.domains.iter().map(|d| attr_s(d)).collect()), + ) + .item("require_2fa", AttributeValue::Bool(seed.require_2fa)) + .item("created_at", attr_s(&now)) + .item("created_how", attr_s(how)) + .condition_expression("attribute_not_exists(pk)"); + if seed.require_2fa { + put = put.item("require_2fa_since", attr_s(&now)); + } + match put.send().await { + Ok(_) => { + seed_invites(state, team_id, &seed, creator_email).await; + load_org(state).await + } + Err(e) + if e.as_service_error() + .is_some_and(|se| se.is_conditional_check_failed_exception()) => + { + load_org(state).await + } + Err(e) => Err(format!("{e}")), + } +} + +/// The install config's first-boot list. +#[derive(Debug, Default)] +struct Seed { + domains: Vec, + /// (email, role) + invites: Vec<(String, String)>, + require_2fa: bool, +} + +async fn config_seed(state: &AppState) -> Seed { + let items = state + .dynamo + .query() + .table_name(&state.config.settings_table_name) + .key_condition_expression("pk = :pk") + .expression_attribute_values(":pk", attr_s("ALLOWLIST")) + .send() + .await + .map(|r| r.items().to_vec()) + .unwrap_or_default(); + seed_from(&items) +} + +fn seed_from(items: &[Item]) -> Seed { + let mut seed = Seed::default(); + for i in items { + let sk = s(i, "sk"); + if sk == "TWO_FACTOR" { + seed.require_2fa = i + .get("require") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false); + } else if let Some(d) = sk.strip_prefix("EMAIL#*@") { + if valid_domain(d) { + seed.domains.push(d.to_lowercase()); + } + } else if let Some(e) = sk.strip_prefix("EMAIL#") { + let role = if s(i, "kind") == "invite" { + "member" + } else { + "admin" + }; + seed.invites.push((e.to_lowercase(), role.to_string())); + } + } + seed.domains.sort(); + seed.domains.dedup(); + seed +} + +/// The config's other addresses as invites (no email is sent; an admin can +/// resend from the team page). +async fn seed_invites(state: &AppState, team_id: &str, seed: &Seed, creator_email: &str) { + let now = chrono::Utc::now().to_rfc3339(); + let creator = normalize_email(creator_email); + for (email, role) in &seed.invites { + if normalize_email(email) == creator { + continue; + } + let gsi2pk = format!("EMAIL#{}", normalize_email(email)); + // Someone with a record in the organization already needs no invite. + let has = state + .dynamo + .query() + .table_name(&state.config.users_table_name) + .index_name("gsi2") + .key_condition_expression("gsi2pk = :pk AND gsi2sk = :t") + .expression_attribute_values(":pk", attr_s(&gsi2pk)) + .expression_attribute_values(":t", attr_s(team_id)) + .send() + .await + .map(|r| r.count() > 0) + .unwrap_or(true); + if has { + continue; + } + let _ = state + .dynamo + .put_item() + .table_name(&state.config.users_table_name) + .item("pk", attr_s(team_id)) + .item("sk", attr_s(&format!("USER#invite_{}", ulid::Ulid::new()))) + .item("email", attr_s(email)) + .item("role", attr_s(role)) + .item("status", attr_s("invited")) + .item("avatar_url", attr_s("")) + .item("updated_at", attr_s(&now)) + .item("invited_at", attr_s(&now)) + .item("invited_by", attr_s("config")) + .item("gsi2pk", attr_s(&gsi2pk)) + .item("gsi2sk", attr_s(team_id)) + .condition_expression("attribute_not_exists(pk)") + .send() + .await; + } +} + +/// The first admin's sign-in: the organization's team, its META records and +/// their owner record. Returns the team and the user id. +pub async fn create_org( + state: &AppState, + user_id: &str, + email: &str, + name: &str, + avatar: &str, +) -> Result, String> { + let team_id = format!("TEAM#{}", ulid::Ulid::new().to_string().to_lowercase()); + let Some(org) = claim_org(state, &team_id, "first_admin", email).await? else { + return Ok(None); + }; + if org.team_id != team_id { + // Someone else made it first. + return Ok(None); + } + let now = chrono::Utc::now().to_rfc3339(); + let _ = state + .dynamo + .put_item() + .table_name(&state.config.table_name) + .item("pk", attr_s(&team_id)) + .item("sk", attr_s("META")) + .item("status", attr_s("active")) + .item("created_at", attr_s(&now)) + .condition_expression("attribute_not_exists(pk)") + .send() + .await; + let _ = state + .dynamo + .put_item() + .table_name(&state.config.teams_table_name) + .item("team_id", attr_s(&team_id)) + .item("sk", attr_s("META")) + .item("created_at", attr_s(&now)) + .condition_expression("attribute_not_exists(team_id)") + .send() + .await; + state + .dynamo + .put_item() + .table_name(&state.config.users_table_name) + .item("pk", attr_s(&team_id)) + .item("sk", attr_s(user_id)) + .item("email", attr_s(email)) + .item("role", attr_s("owner")) + .item("status", attr_s("active")) + .item("name", attr_s(name)) + .item("avatar_url", attr_s(avatar)) + .item("updated_at", attr_s(&now)) + .item("created_at", attr_s(&now)) + .item( + "gsi2pk", + attr_s(&format!("EMAIL#{}", normalize_email(email))), + ) + .item("gsi2sk", attr_s(&team_id)) + .send() + .await + .map_err(|e| format!("{e}"))?; + info!(%team_id, "First admin made the organization"); + Ok(Some(team_id)) +} + +/// Someone whose email domain is allowed: a member record in the +/// organization. Returns their record. +pub async fn join_by_domain( + state: &AppState, + org: &Org, + user_id: &str, + email: &str, + name: &str, + avatar: &str, +) -> Result { + let now = chrono::Utc::now().to_rfc3339(); + let record = HashMap::from([ + ("pk".to_string(), attr_s(&org.team_id)), + ("sk".to_string(), attr_s(user_id)), + ("email".to_string(), attr_s(email)), + ("role".to_string(), attr_s("member")), + ("status".to_string(), attr_s("active")), + ("name".to_string(), attr_s(name)), + ("avatar_url".to_string(), attr_s(avatar)), + ("updated_at".to_string(), attr_s(&now)), + ("created_at".to_string(), attr_s(&now)), + ("invited_by".to_string(), attr_s("domain")), + ( + "gsi2pk".to_string(), + attr_s(&format!("EMAIL#{}", normalize_email(email))), + ), + ("gsi2sk".to_string(), attr_s(&org.team_id)), + ]); + let put = state + .dynamo + .put_item() + .table_name(&state.config.users_table_name) + .set_item(Some(record.clone())) + .condition_expression("attribute_not_exists(pk)") + .send() + .await; + match put { + Ok(_) => { + info!(team_id = %org.team_id, "Joined the organization by email domain"); + Ok(record) + } + Err(e) + if e.as_service_error() + .is_some_and(|se| se.is_conditional_check_failed_exception()) => + { + Ok(record) + } + Err(e) => Err(format!("{e}")), + } +} + +// ── Domains ───────────────────────────────────────────────────────── + +/// Email services anyone can sign up for: allowing one would let anyone in. +const PUBLIC_MAIL: &[&str] = &[ + "gmail.com", + "googlemail.com", + "outlook.com", + "hotmail.com", + "live.com", + "msn.com", + "yahoo.com", + "icloud.com", + "me.com", + "aol.com", + "proton.me", + "protonmail.com", + "gmx.com", + "mail.com", + "yandex.com", + "zoho.com", +]; + +pub fn valid_domain(d: &str) -> bool { + let d = d.trim(); + if d.len() > 253 || !d.contains('.') { + return false; + } + d.split('.').all(|label| { + !label.is_empty() + && label.len() <= 63 + && !label.starts_with('-') + && !label.ends_with('-') + && label + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') + }) && d + .rsplit('.') + .next() + .is_some_and(|tld| tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_lowercase())) +} + +/// The domains an admin typed, cleaned and checked. +pub fn clean_domains(input: &[String]) -> Result, String> { + let mut out = Vec::new(); + for raw in input { + let d = raw.trim().trim_start_matches('@').to_lowercase(); + if d.is_empty() { + continue; + } + if !valid_domain(&d) { + return Err(format!( + "\"{raw}\" isn't an email domain such as example.com." + )); + } + if PUBLIC_MAIL.contains(&d.as_str()) { + return Err(format!( + "{d} is a public email service: allowing it would let anyone join. Invite those people instead." + )); + } + if !out.contains(&d) { + out.push(d); + } + } + if out.len() > MAX_DOMAINS { + return Err(format!("Allow at most {MAX_DOMAINS} domains.")); + } + out.sort(); + Ok(out) +} + +// ── Two-factor: the request gate ──────────────────────────────────── + +/// What a session without a second factor may still reach while the rule is +/// on: who they are, and the screens that set up a second factor. +pub const SETUP_HANDLERS: &[&str] = &[ + "api::me", + "sign_in::my_status", + "users::mfa_setup", + "users::mfa_verify_setup", + "sign_in::app_setup", + "sign_in::app_verify", +]; + +/// May this session make this request? +pub fn gate(require_2fa: bool, proof: &SignInProof, handler: Option<&str>) -> bool { + !require_2fa || proof.mfa || handler.is_some_and(|h| SETUP_HANDLERS.contains(&h)) +} + +/// The answer to a held session. +pub fn two_factor_required() -> Response { + ( + StatusCode::FORBIDDEN, + Json(json!({ + "error": "Your organization requires two-factor sign-in. Set it up to continue.", + "code": "two_factor_required", + })), + ) + .into_response() +} + +/// The middleware's check for one session request on a self-hosted install. +/// The rule is read fresh each time; when it can't be read the request is +/// refused (the safe answer). +pub async fn check_session( + state: &AppState, + proof: &SignInProof, + handler: Option<&str>, +) -> Result<(), Response> { + if proof.mfa { + return Ok(()); + } + let require = match load_org(state).await { + Ok(org) => org.is_some_and(|o| o.require_2fa), + Err(e) => { + error!(error = %e, "Two-factor rule not read; request refused"); + return Err(StatusCode::SERVICE_UNAVAILABLE.into_response()); + } + }; + if gate(require, proof, handler) { + Ok(()) + } else { + Err(two_factor_required()) + } +} + +/// GET /api/users/2fa — this person's two-factor sign-in: whether the +/// organization requires it, whether this session is held until it is set +/// up, which kind they set up (`app`, `cognito` or none), and which kind fits +/// how they signed in (`cognito` after a password, `app` after Google or +/// GitHub). +pub async fn my_status( + State(state): State>, + Extension(claims): Extension, + proof: Option>, +) -> Result, ApiError> { + if !applies() { + return Ok(Json( + json!({ "self_hosted": false, "required": false, "held": false }), + )); + } + let required = load_org(&state) + .await + .map_err(|e| internal("Organization not read", e))? + .is_some_and(|o| o.require_2fa); + let passed = proof.as_ref().is_some_and(|p| p.mfa); + let via = via_of(proof.as_ref()); + let item = member(&state, &claims.team_id, &claims.sub) + .await + .map_err(|e| internal("Member not read", e))?; + let factor = match &item { + Some(i) => factor_of(&state, i).await, + None => None, + }; + Ok(Json(json!({ + "self_hosted": true, + "required": required, + "held": required && !passed, + "session_has_2fa": passed, + "signed_in_with": via, + "set_up": factor, + "fits": if via == "password" { "cognito" } else { "app" }, + }))) +} + +// ── Two-factor: authenticator-app codes (RFC 6238) ────────────────── + +const B32: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + +pub fn base32(bytes: &[u8]) -> String { + let mut out = String::new(); + let (mut buf, mut bits) = (0u32, 0u32); + for &b in bytes { + buf = (buf << 8) | u32::from(b); + bits += 8; + while bits >= 5 { + out.push(B32[((buf >> (bits - 5)) & 31) as usize] as char); + bits -= 5; + } + } + if bits > 0 { + out.push(B32[((buf << (5 - bits)) & 31) as usize] as char); + } + out +} + +/// The six-digit code for a 30-second time step. +pub fn totp_at(secret: &[u8], step: u64) -> String { + use hmac::{Hmac, Mac}; + let mut mac = Hmac::::new_from_slice(secret).expect("HMAC key length"); + mac.update(&step.to_be_bytes()); + let h = mac.finalize().into_bytes(); + let off = (h[19] & 0x0f) as usize; + let bin = (u32::from(h[off] & 0x7f) << 24) + | (u32::from(h[off + 1]) << 16) + | (u32::from(h[off + 2]) << 8) + | u32::from(h[off + 3]); + format!("{:06}", bin % 1_000_000) +} + +/// The time step a code matches (this step or one either side), newer than +/// `last_used` so a code works once. `None` when it doesn't match. +pub fn totp_check(secret: &[u8], code: &str, unix: u64, last_used: u64) -> Option { + let code: String = code.chars().filter(|c| !c.is_whitespace()).collect(); + if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) { + return None; + } + let now = unix / 30; + [now.saturating_sub(1), now, now + 1] + .into_iter() + .filter(|st| *st > last_used) + .find(|st| { + use subtle::ConstantTimeEq; + totp_at(secret, *st) + .as_bytes() + .ct_eq(code.as_bytes()) + .into() + }) +} + +fn otpauth_uri(email: &str, secret_b32: &str) -> String { + format!( + "otpauth://totp/CoderHelm:{}?secret={secret_b32}&issuer=CoderHelm", + urlencoding::encode(email) + ) +} + +fn cipher(state: &AppState) -> common::mcp_credentials::Kms<'_> { + common::mcp_credentials::Kms { + client: &state.kms, + key_id: &state.config.secrets_key_id, + } +} + +fn seal_context(team_id: &str, user_id: &str) -> HashMap { + HashMap::from([ + ("team".to_string(), team_id.to_string()), + ("user".to_string(), user_id.to_string()), + ("purpose".to_string(), "two_factor".to_string()), + ]) +} + +async fn seal(state: &AppState, team: &str, user: &str, secret: &[u8]) -> Result { + use base64::Engine; + use common::mcp_credentials::Cipher; + let blob = cipher(state) + .encrypt(seal_context(team, user), secret) + .await?; + Ok(base64::engine::general_purpose::STANDARD.encode(blob)) +} + +async fn unseal(state: &AppState, team: &str, user: &str, sealed: &str) -> Result, String> { + use base64::Engine; + use common::mcp_credentials::Cipher; + let blob = base64::engine::general_purpose::STANDARD + .decode(sealed) + .map_err(|e| e.to_string())?; + cipher(state).decrypt(seal_context(team, user), &blob).await +} + +async fn member(state: &AppState, team_id: &str, user_id: &str) -> Result, String> { + state + .dynamo + .get_item() + .table_name(&state.config.users_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(user_id)) + .consistent_read(true) + .send() + .await + .map(|r| r.item) + .map_err(|e| format!("{e}")) +} + +fn app_enabled(item: &Item) -> bool { + item.get("totp_enabled") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false) + && !s(item, "totp_sealed").is_empty() +} + +fn last_step(item: &Item) -> u64 { + item.get("totp_last_step") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0) +} + +/// Checks an authenticator-app code against the member's own secret and uses +/// it up (a code works once). +async fn use_app_code(state: &AppState, item: &Item, code: &str) -> Result { + let (team, user) = (s(item, "pk"), s(item, "sk")); + let secret = unseal(state, team, user, s(item, "totp_sealed")).await?; + let unix = chrono::Utc::now().timestamp().max(0) as u64; + let Some(step) = totp_check(&secret, code, unix, last_step(item)) else { + return Ok(false); + }; + let used = state + .dynamo + .update_item() + .table_name(&state.config.users_table_name) + .key("pk", attr_s(team)) + .key("sk", attr_s(user)) + .update_expression("SET totp_last_step = :st") + .condition_expression("attribute_not_exists(totp_last_step) OR totp_last_step < :st") + .expression_attribute_values(":st", AttributeValue::N(step.to_string())) + .send() + .await; + Ok(used.is_ok()) +} + +/// Records which second factor a member has (shown to admins). +pub async fn note_factor(state: &AppState, team_id: &str, user_id: &str, factor: Option<&str>) { + let mut up = state + .dynamo + .update_item() + .table_name(&state.config.users_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(user_id)) + .condition_expression("attribute_exists(pk)"); + up = match factor { + Some(f) => up + .update_expression("SET two_factor = :f") + .expression_attribute_values(":f", attr_s(f)), + None => up.update_expression("REMOVE two_factor"), + }; + let _ = up.send().await; +} + +fn session_cookie(token: &str) -> String { + format!( + "__Host-coderhelm_session={token}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age={SESSION_TTL_SECS}" + ) +} + +/// A fresh session for `claims` that passed a second factor just now. +pub fn session_with_second_factor( + state: &AppState, + claims: &Claims, + via: &str, +) -> Result { + let token = jwt::create_session_token( + &claims.sub, + &claims.team_id, + &claims.email, + claims.session_role(), + claims.github_login.as_deref(), + &SignInProof::new(true, via), + &state.secrets.jwt_secret, + SESSION_TTL_SECS, + ) + .map_err(|e| internal("Session not made", e))?; + Ok(session_cookie(&token)) +} + +fn with_cookie(body: Value, cookie: &str) -> Response { + let mut resp = Json(body).into_response(); + if let Ok(v) = HeaderValue::from_str(cookie) { + resp.headers_mut().append(header::SET_COOKIE, v); + } + resp +} + +fn via_of(proof: Option<&Extension>) -> String { + proof + .and_then(|p| p.via.clone()) + .unwrap_or_else(|| "password".to_string()) +} + +#[derive(Deserialize)] +pub struct CodeBody { + pub code: String, +} + +/// POST /api/users/2fa/app/setup — start the authenticator-app second factor +/// for a Google or GitHub sign-in: a new secret, kept pending until a code +/// from it is entered. +pub async fn app_setup( + State(state): State>, + Extension(claims): Extension, +) -> Result, ApiError> { + if !applies() { + return Err(fail(StatusCode::NOT_FOUND, "Not available here.")); + } + let item = member(&state, &claims.team_id, &claims.sub) + .await + .map_err(|e| internal("Member not read", e))? + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "You aren't on this team."))?; + if app_enabled(&item) { + return Err(fail( + StatusCode::CONFLICT, + "Two-factor sign-in is already on for you.", + )); + } + let mut secret = [0u8; 20]; + rand::RngCore::fill_bytes(&mut rand::rng(), &mut secret); + let sealed = seal(&state, &claims.team_id, &claims.sub, &secret) + .await + .map_err(|e| internal("Two-factor secret not sealed", e))?; + state + .dynamo + .update_item() + .table_name(&state.config.users_table_name) + .key("pk", attr_s(&claims.team_id)) + .key("sk", attr_s(&claims.sub)) + .update_expression("SET totp_pending = :p") + .condition_expression("attribute_exists(pk)") + .expression_attribute_values(":p", attr_s(&sealed)) + .send() + .await + .map_err(|e| internal("Two-factor setup not saved", e))?; + let b32 = base32(&secret); + let label = if claims.email.is_empty() { + claims.github_login.clone().unwrap_or_default() + } else { + claims.email.clone() + }; + Ok(Json(json!({ + "secret": b32, + "qr_uri": otpauth_uri(&label, &b32), + }))) +} + +/// POST /api/users/2fa/app/verify — finish the setup with a code from the +/// app. The session then counts as signed in with a second factor. +pub async fn app_verify( + State(state): State>, + Extension(claims): Extension, + proof: Option>, + Json(body): Json, +) -> Result { + if !applies() { + return Err(fail(StatusCode::NOT_FOUND, "Not available here.")); + } + let item = member(&state, &claims.team_id, &claims.sub) + .await + .map_err(|e| internal("Member not read", e))? + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "You aren't on this team."))?; + let pending = s(&item, "totp_pending"); + if pending.is_empty() { + return Err(fail( + StatusCode::BAD_REQUEST, + "Start the setup first: it shows the code to scan.", + )); + } + let secret = unseal(&state, &claims.team_id, &claims.sub, pending) + .await + .map_err(|e| internal("Two-factor secret not read", e))?; + let unix = chrono::Utc::now().timestamp().max(0) as u64; + let Some(step) = totp_check(&secret, &body.code, unix, 0) else { + return Err(fail_code( + StatusCode::BAD_REQUEST, + "That code didn't match. Enter the current 6-digit code from the app.", + "wrong_code", + )); + }; + state + .dynamo + .update_item() + .table_name(&state.config.users_table_name) + .key("pk", attr_s(&claims.team_id)) + .key("sk", attr_s(&claims.sub)) + .update_expression( + "SET totp_sealed = :s, totp_enabled = :t, totp_last_step = :st, two_factor = :f, \ + totp_enabled_at = :now REMOVE totp_pending", + ) + .condition_expression("totp_pending = :p") + .expression_attribute_values(":s", attr_s(pending)) + .expression_attribute_values(":p", attr_s(pending)) + .expression_attribute_values(":t", AttributeValue::Bool(true)) + .expression_attribute_values(":st", AttributeValue::N(step.to_string())) + .expression_attribute_values(":f", attr_s("app")) + .expression_attribute_values(":now", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await + .map_err(|e| internal("Two-factor not turned on", e))?; + info!(team_id = %claims.team_id, "Authenticator-app two-factor turned on"); + let via = via_of(proof.as_ref()); + let cookie = session_with_second_factor(&state, &claims, &via)?; + Ok(with_cookie(json!({ "status": "enabled" }), &cookie)) +} + +/// DELETE /api/users/2fa/app — turn the authenticator-app second factor off +/// (with a current code). Refused while the organization requires it. +pub async fn app_disable( + State(state): State>, + Extension(claims): Extension, + Json(body): Json, +) -> Result, ApiError> { + if !applies() { + return Err(fail(StatusCode::NOT_FOUND, "Not available here.")); + } + if load_org(&state) + .await + .map_err(|e| internal("Organization not read", e))? + .is_some_and(|o| o.require_2fa) + { + return Err(fail( + StatusCode::CONFLICT, + "Your organization requires two-factor sign-in, so it stays on.", + )); + } + let item = member(&state, &claims.team_id, &claims.sub) + .await + .map_err(|e| internal("Member not read", e))? + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "You aren't on this team."))?; + if !app_enabled(&item) { + return Err(fail( + StatusCode::CONFLICT, + "Two-factor sign-in is already off.", + )); + } + if !use_app_code(&state, &item, &body.code) + .await + .map_err(|e| internal("Code not checked", e))? + { + return Err(fail_code( + StatusCode::BAD_REQUEST, + "That code didn't match. Enter the current 6-digit code from the app.", + "wrong_code", + )); + } + clear_app_factor(&state, &claims.team_id, &claims.sub) + .await + .map_err(|e| internal("Two-factor not turned off", e))?; + Ok(Json(json!({ "status": "disabled" }))) +} + +async fn clear_app_factor(state: &AppState, team: &str, user: &str) -> Result<(), String> { + state + .dynamo + .update_item() + .table_name(&state.config.users_table_name) + .key("pk", attr_s(team)) + .key("sk", attr_s(user)) + .update_expression( + "REMOVE totp_sealed, totp_enabled, totp_last_step, totp_pending, totp_enabled_at, two_factor", + ) + .condition_expression("attribute_exists(pk)") + .send() + .await + .map(|_| ()) + .map_err(|e| format!("{e}")) +} + +// ── Two-factor: the step after Google or GitHub ───────────────────── + +/// After a Google or GitHub sign-in: when the person has the +/// authenticator-app factor, the session waits for their code. Returns the +/// redirect to the code screen, or `None` to sign them straight in (no +/// factor yet: with the rule on, the session can then only set one up). +pub async fn second_step( + state: &AppState, + step: SecondStep, + app_url: &str, +) -> Result, String> { + let Some(item) = member(state, &step.team_id, &step.sub).await? else { + return Ok(None); + }; + if !app_enabled(&item) { + return Ok(None); + } + let token = jwt::create_second_step(&step, &state.secrets.jwt_secret, SECOND_STEP_SECS) + .map_err(|e| e.to_string())?; + let mut resp = ( + StatusCode::FOUND, + [(header::LOCATION, format!("{app_url}/?two_factor=1"))], + ) + .into_response(); + let cookie = format!( + "{SECOND_STEP_COOKIE}={token}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age={SECOND_STEP_SECS}" + ); + if let Ok(v) = HeaderValue::from_str(&cookie) { + resp.headers_mut().append(header::SET_COOKIE, v); + } + Ok(Some(resp)) +} + +fn cookie_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { + headers + .get(header::COOKIE) + .and_then(|v| v.to_str().ok())? + .split(';') + .map(str::trim) + .find_map(|c| c.strip_prefix(name).and_then(|r| r.strip_prefix('='))) +} + +/// POST /auth/2fa/verify — the code after a Google or GitHub sign-in. On a +/// match: the session, with its second factor recorded. +pub async fn verify_second_step( + State(state): State>, + headers: HeaderMap, + Json(body): Json, +) -> Result { + let token = cookie_value(&headers, SECOND_STEP_COOKIE).ok_or_else(|| { + fail_code( + StatusCode::UNAUTHORIZED, + "The sign-in took too long. Sign in again.", + "second_step_expired", + ) + })?; + let step = jwt::validate_second_step(token, &state.secrets.jwt_secret).map_err(|_| { + fail_code( + StatusCode::UNAUTHORIZED, + "The sign-in took too long. Sign in again.", + "second_step_expired", + ) + })?; + let item = member(&state, &step.team_id, &step.sub) + .await + .map_err(|e| internal("Member not read", e))? + .ok_or_else(|| fail(StatusCode::UNAUTHORIZED, NOT_INVITED))?; + if !app_enabled(&item) + || !use_app_code(&state, &item, &body.code) + .await + .map_err(|e| internal("Code not checked", e))? + { + warn!(team_id = %step.team_id, "Second-step code refused"); + return Err(fail_code( + StatusCode::UNAUTHORIZED, + "That code didn't work. Open your authenticator app and enter the current 6-digit code.", + "wrong_code", + )); + } + let session = jwt::create_session_token( + &step.sub, + &step.team_id, + &step.email, + match s(&item, "role") { + "" => "member", + r => r, + }, + step.github_login.as_deref(), + &SignInProof::new(true, &step.via), + &state.secrets.jwt_secret, + SESSION_TTL_SECS, + ) + .map_err(|e| internal("Session not made", e))?; + let mut resp = Json(json!({ "status": "ok", "team_id": step.team_id })).into_response(); + for c in [ + session_cookie(&session), + format!("{SECOND_STEP_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0"), + ] { + if let Ok(v) = HeaderValue::from_str(&c) { + resp.headers_mut().append(header::SET_COOKIE, v); + } + } + Ok(resp) +} + +// ── Settings, Sign-in ─────────────────────────────────────────────── + +/// Whether a member has a second factor: `app`, `cognito` or none. A record +/// from before `two_factor` was written is checked in Cognito. +async fn factor_of(state: &AppState, item: &Item) -> Option { + match s(item, "two_factor") { + "" => {} + f => return Some(f.to_string()), + } + if app_enabled(item) { + return Some("app".into()); + } + let email = s(item, "email"); + if email.is_empty() { + return None; + } + let on = state + .cognito + .admin_get_user() + .user_pool_id(&state.config.cognito_user_pool_id) + .username(email) + .send() + .await + .ok() + .and_then(|u| u.user_mfa_setting_list) + .is_some_and(|l| l.iter().any(|m| m == "SOFTWARE_TOKEN_MFA")); + on.then(|| "cognito".to_string()) +} + +async fn team_members(state: &AppState, team_id: &str) -> Result, String> { + let mut items = Vec::new(); + let mut start: Option = None; + loop { + let out = state + .dynamo + .query() + .table_name(&state.config.users_table_name) + .key_condition_expression("pk = :pk AND begins_with(sk, :u)") + .expression_attribute_values(":pk", attr_s(team_id)) + .expression_attribute_values(":u", attr_s("USER#")) + .set_exclusive_start_key(start) + .send() + .await + .map_err(|e| format!("{e}"))?; + items.extend(out.items().iter().cloned()); + match out.last_evaluated_key() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => break, + } + } + Ok(items) +} + +/// GET /api/sign-in — the organization's sign-in rules, who has two-factor +/// sign-in, and the API keys (which the rule doesn't affect). +pub async fn get_settings( + State(state): State>, + Extension(claims): Extension, + proof: Option>, +) -> Result, ApiError> { + admin(&claims)?; + if !applies() { + return Ok(Json(json!({ "self_hosted": false }))); + } + let org = ensure_org(&state) + .await + .map_err(|e| internal("Organization not read", e))?; + let items = team_members(&state, &claims.team_id) + .await + .map_err(|e| internal("Members not read", e))?; + let active: Vec<&Item> = items.iter().filter(|i| !is_invite(i)).collect(); + let factors = futures::future::join_all(active.iter().map(|i| factor_of(&state, i))).await; + let people: Vec = active + .iter() + .zip(factors) + .map(|(i, f)| { + json!({ + "user_id": s(i, "sk").trim_start_matches("USER#"), + "email": s(i, "email"), + "name": s(i, "name"), + "github_login": s(i, "github_login"), + "role": s(i, "role"), + "two_factor": f, + "is_self": s(i, "sk") == claims.sub, + }) + }) + .collect(); + let invites = items.iter().filter(|i| is_invite(i)).count(); + let now = chrono::Utc::now(); + let keys: Vec = { + use crate::api_keys::KeyStore; + crate::api_keys::store(&state) + .list(&claims.team_id) + .await + .unwrap_or_default() + .iter() + .filter(|k| k.is_live(now)) + .map(|k| json!({ "id": k.id, "name": k.name, "created_by": k.created_by_name })) + .collect() + }; + Ok(Json(json!({ + "self_hosted": true, + "is_org": org.as_ref().is_some_and(|o| o.team_id == claims.team_id), + "domains": org.as_ref().map(|o| o.domains.clone()).unwrap_or_default(), + "require_2fa": org.as_ref().is_some_and(|o| o.require_2fa), + "require_2fa_since": org.as_ref().and_then(|o| o.require_2fa_since.clone()), + "pending_invites": invites, + "people": people, + "api_keys": keys, + "your_session_has_2fa": proof.is_some_and(|p| p.mfa), + }))) +} + +#[derive(Deserialize)] +pub struct SettingsBody { + pub domains: Option>, + pub require_2fa: Option, +} + +/// PUT /api/sign-in — change the allowed domains or the two-factor rule. +pub async fn update_settings( + State(state): State>, + Extension(claims): Extension, + proof: Option>, + Json(body): Json, +) -> Result, ApiError> { + admin(&claims)?; + if !applies() { + return Err(fail(StatusCode::NOT_FOUND, "Not available here.")); + } + let org = ensure_org(&state) + .await + .map_err(|e| internal("Organization not read", e))? + .filter(|o| o.team_id == claims.team_id) + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "This team isn't the organization."))?; + let domains = match &body.domains { + Some(d) => Some(clean_domains(d).map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?), + None => None, + }; + let turning_on = body.require_2fa == Some(true) && !org.require_2fa; + if turning_on && !proof.as_ref().is_some_and(|p| p.mfa) { + return Err(fail_code( + StatusCode::CONFLICT, + "Set up two-factor sign-in for yourself first, then sign in again with it. Then you can require it for everyone.", + "set_up_yours_first", + )); + } + let mut changes = Vec::new(); + let mut sets = vec!["updated_at = :now", "updated_by = :by"]; + let now = chrono::Utc::now().to_rfc3339(); + let mut values = HashMap::from([ + (":now".to_string(), attr_s(&now)), + (":by".to_string(), attr_s(&claims.display_name())), + ]); + if let Some(d) = &domains { + if *d != org.domains { + changes.push(if d.is_empty() { + "Allowed domains: none (invites only)".to_string() + } else { + format!("Allowed domains: {}", d.join(", ")) + }); + } + sets.push("domains = :d"); + values.insert( + ":d".into(), + AttributeValue::L(d.iter().map(|x| attr_s(x)).collect()), + ); + } + if let Some(r) = body.require_2fa { + if r != org.require_2fa { + changes.push(if r { + "Two-factor sign-in required for everyone".to_string() + } else { + "Two-factor sign-in no longer required".to_string() + }); + } + sets.push("require_2fa = :r"); + values.insert(":r".into(), AttributeValue::Bool(r)); + if turning_on { + sets.push("require_2fa_since = :now"); + } + } + if !changes.is_empty() { + // Nothing changes without its line in the log. + super::roles::record( + &state, + &claims, + super::roles::AuditEntry { + action: "sign_in_rules", + role_id: "", + role_name: "", + detail: changes.join(". "), + }, + ) + .await?; + } + state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(ORG_PK)) + .key("sk", attr_s(ORG_SK)) + .update_expression(format!("SET {}", sets.join(", "))) + .set_expression_attribute_values(Some(values)) + .condition_expression("attribute_exists(pk)") + .send() + .await + .map_err(|e| internal("Sign-in rules not saved", e))?; + info!(changes = ?changes, "Sign-in rules changed"); + let org = load_org(&state) + .await + .map_err(|e| internal("Organization not read", e))? + .unwrap_or(org); + Ok(Json(json!({ + "domains": org.domains, + "require_2fa": org.require_2fa, + "require_2fa_since": org.require_2fa_since, + }))) +} + +#[derive(Deserialize)] +pub struct ResetBody { + /// How the admin made sure it is really them (logged). + pub verified_how: String, +} + +/// What an admin must say before resetting someone's second factor. +pub fn reset_reason(how: &str) -> Result { + let how = how.trim(); + if how.chars().count() < 10 { + return Err("Say how you checked it's really them (at least 10 characters), for the log."); + } + Ok(how.chars().take(300).collect()) +} + +/// POST /api/users/:user_id/2fa/reset — turn a member's second factor off +/// after the admin checked who is asking (a lost phone). Logged first; the +/// member sets it up again at their next sign-in when the rule is on. +pub async fn reset_two_factor( + State(state): State>, + Extension(claims): Extension, + Path(user_id): Path, + Json(body): Json, +) -> Result, ApiError> { + admin(&claims)?; + if !applies() { + return Err(fail(StatusCode::NOT_FOUND, "Not available here.")); + } + let how = reset_reason(&body.verified_how).map_err(|m| fail(StatusCode::BAD_REQUEST, m))?; + let sk = format!("USER#{}", user_id.trim_start_matches("USER#")); + if sk == claims.sub { + return Err(fail( + StatusCode::BAD_REQUEST, + "You can't reset your own. Ask another admin.", + )); + } + let item = member(&state, &claims.team_id, &sk) + .await + .map_err(|e| internal("Member not read", e))? + .filter(|i| !is_invite(i)) + .ok_or_else(|| fail(StatusCode::NOT_FOUND, "That person isn't on this team."))?; + let target_role = match s(&item, "role") { + "" => "member", + r => r, + }; + if !crate::permissions::can_manage(&claims.role, target_role) { + return Err(fail( + StatusCode::FORBIDDEN, + "Only an owner can reset an admin's or owner's two-factor sign-in.", + )); + } + let who = [ + s(&item, "email"), + s(&item, "github_login"), + s(&item, "name"), + ] + .into_iter() + .find(|v| !v.is_empty()) + .unwrap_or("a member") + .to_string(); + super::roles::record( + &state, + &claims, + super::roles::AuditEntry { + action: "two_factor_reset", + role_id: "", + role_name: "", + detail: format!("Reset two-factor sign-in for {who}. How it was checked: {how}"), + }, + ) + .await?; + let email = s(&item, "email"); + if !email.is_empty() { + if let Err(e) = state + .cognito + .admin_set_user_mfa_preference() + .user_pool_id(&state.config.cognito_user_pool_id) + .username(email) + .software_token_mfa_settings( + aws_sdk_cognitoidentityprovider::types::SoftwareTokenMfaSettingsType::builder() + .enabled(false) + .preferred_mfa(false) + .build(), + ) + .send() + .await + { + let msg = format!("{e:?}"); + if !msg.contains("UserNotFound") { + return Err(internal("Cognito two-factor not reset", msg)); + } + } + } + clear_app_factor(&state, &claims.team_id, &sk) + .await + .map_err(|e| internal("Two-factor not reset", e))?; + info!(team_id = %claims.team_id, "Two-factor sign-in reset by an admin"); + Ok(Json(json!({ "status": "reset" }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn rec(pk: &str, sk: &str, status: Option<&str>, invited_at: Option<&str>) -> Item { + let mut m = HashMap::from([ + ("pk".to_string(), attr_s(pk)), + ("sk".to_string(), attr_s(sk)), + ]); + if let Some(st) = status { + m.insert("status".into(), attr_s(st)); + } + if let Some(t) = invited_at { + m.insert("invited_at".into(), attr_s(t)); + } + m + } + + /// The cases the Cognito pre-sign-up trigger is tested with too. + #[derive(Deserialize)] + struct Case { + name: String, + email: String, + org: Option, + #[serde(default)] + records: Vec, + #[serde(default)] + admin_listed: bool, + #[serde(default)] + listed: bool, + #[serde(default)] + anyone: bool, + now: String, + want: String, + } + #[derive(Deserialize)] + struct CaseOrg { + team_id: String, + #[serde(default)] + domains: Vec, + } + #[derive(Deserialize)] + struct CaseRecord { + pk: String, + sk: String, + status: Option, + invited_at: Option, + } + + #[test] + fn every_shared_join_case_decides_as_written() { + let cases: Vec = + serde_json::from_str(include_str!("../../../../lambda/pre-signup/cases.json")).unwrap(); + assert!(cases.len() >= 12); + for c in cases { + let facts = JoinFacts { + email: c.email.clone(), + org: c.org.map(|o| Org { + team_id: o.team_id, + domains: o.domains, + ..Org::default() + }), + records: c + .records + .iter() + .map(|r| rec(&r.pk, &r.sk, r.status.as_deref(), r.invited_at.as_deref())) + .collect(), + admin_listed: c.admin_listed, + listed: c.listed, + anyone: c.anyone, + }; + let now = chrono::DateTime::parse_from_rfc3339(&c.now) + .unwrap() + .with_timezone(&chrono::Utc); + assert_eq!(decide_join(&facts, now).key(), c.want, "{}", c.name); + } + } + + fn org(domains: &[&str]) -> Org { + Org { + team_id: "TEAM#org".into(), + domains: domains.iter().map(|d| d.to_string()).collect(), + ..Org::default() + } + } + + fn now() -> chrono::DateTime { + chrono::DateTime::parse_from_rfc3339("2026-10-26T12:00:00Z") + .unwrap() + .with_timezone(&chrono::Utc) + } + + #[test] + fn a_stranger_is_refused_once_the_organization_exists() { + let f = JoinFacts { + email: "someone@elsewhere.io".into(), + org: Some(org(&["example.com"])), + anyone: true, + // The config list no longer lets anyone in after first boot. + listed: true, + admin_listed: true, + ..JoinFacts::default() + }; + assert_eq!(decide_join(&f, now()), Join::Refused); + } + + #[test] + fn an_allowed_domain_joins_and_a_lookalike_does_not() { + let mut f = JoinFacts { + email: "Ann@Example.com".into(), + org: Some(org(&["example.com"])), + anyone: true, + ..JoinFacts::default() + }; + assert_eq!(decide_join(&f, now()), Join::Domain); + for e in [ + "ann@notexample.com", + "ann@example.com.evil.io", + "ann@sub.example.com", + "example.com", + "@example.com", + ] { + f.email = e.into(); + assert_eq!(decide_join(&f, now()), Join::Refused, "{e}"); + } + } + + #[test] + fn an_invite_to_another_team_does_not_let_anyone_into_the_organization() { + let f = JoinFacts { + email: "b@x.io".into(), + org: Some(org(&[])), + anyone: true, + records: vec![ + rec( + "TEAM#other", + "USER#invite_1", + Some("invited"), + Some("2026-10-20T00:00:00Z"), + ), + rec("TEAM#other", "USER#2", None, None), + ], + ..JoinFacts::default() + }; + assert_eq!(decide_join(&f, now()), Join::Refused); + } + + #[test] + fn no_second_organization_after_the_first_admin() { + // Before anyone signs up, only a listed admin may start it... + let mut f = JoinFacts { + email: "admin@x.io".into(), + admin_listed: true, + listed: true, + ..JoinFacts::default() + }; + assert_eq!(decide_join(&f, now()), Join::FirstAdmin); + f.admin_listed = false; + assert_eq!(decide_join(&f, now()), Join::Refused); + // ...and once it exists, the same person can't start another one. + f.admin_listed = true; + f.anyone = true; + f.org = Some(org(&[])); + assert_eq!(decide_join(&f, now()), Join::Refused); + } + + #[test] + fn domains_are_checked_and_public_mail_refused() { + assert_eq!( + clean_domains(&[ + " Example.COM ".into(), + "@corp.example.org".into(), + "example.com".into() + ]) + .unwrap(), + vec!["corp.example.org".to_string(), "example.com".to_string()] + ); + assert!(clean_domains(&["gmail.com".into()]) + .unwrap_err() + .contains("public email")); + for bad in [ + "example", + "exa mple.com", + "-x.com", + "x..com", + "x.c0m", + "*.example.com", + ] { + assert!(clean_domains(&[bad.into()]).is_err(), "{bad}"); + } + let many: Vec = (0..21).map(|i| format!("d{i}.example.com")).collect(); + assert!(clean_domains(&many).is_err()); + assert_eq!(clean_domains(&[]).unwrap(), Vec::::new()); + } + + #[test] + fn the_config_seed_splits_admins_invites_domains_and_the_rule() { + let items = vec![ + HashMap::from([("sk".to_string(), attr_s("EMAIL#admin@x.io"))]), + HashMap::from([ + ("sk".to_string(), attr_s("EMAIL#b@x.io")), + ("kind".to_string(), attr_s("invite")), + ]), + HashMap::from([("sk".to_string(), attr_s("EMAIL#*@x.io"))]), + HashMap::from([ + ("sk".to_string(), attr_s("TWO_FACTOR")), + ("require".to_string(), AttributeValue::Bool(true)), + ]), + ]; + let seed = seed_from(&items); + assert_eq!(seed.domains, vec!["x.io".to_string()]); + assert_eq!( + seed.invites, + vec![ + ("admin@x.io".to_string(), "admin".to_string()), + ("b@x.io".to_string(), "member".to_string()) + ] + ); + assert!(seed.require_2fa); + } + + #[test] + fn the_rule_holds_a_session_without_a_second_factor_on_every_route_but_setup() { + let none = SignInProof::default(); + let google = SignInProof { + mfa: false, + via: Some("google".into()), + }; + let passed = SignInProof::new(true, "github"); + // Off: everyone goes on. + assert!(gate(false, &none, Some("api::list_runs"))); + // On: only the setup screens, for password and federated sessions alike. + for p in [&none, &google] { + assert!(!gate(true, p, Some("api::list_runs"))); + assert!(!gate(true, p, Some("users::invite_user"))); + assert!(!gate(true, p, Some("sign_in::update_settings"))); + assert!(!gate(true, p, Some("users::mfa_disable"))); + assert!(!gate(true, p, None)); + for h in SETUP_HANDLERS { + assert!(gate(true, p, Some(h)), "{h}"); + } + } + assert!(gate(true, &passed, Some("api::list_runs"))); + } + + #[test] + fn every_setup_route_is_routed() { + let routed: Vec<&String> = crate::permissions::api_route_handlers().values().collect(); + for h in SETUP_HANDLERS { + assert!(routed.iter().any(|r| r == h), "{h} isn't routed under /api"); + } + } + + #[test] + fn totp_matches_rfc_6238_and_a_code_works_once() { + // RFC 6238 appendix B, SHA-1, the last 6 of each 8-digit value. + let key = b"12345678901234567890"; + for (t, want) in [ + (59u64, "287082"), + (1_111_111_109, "081804"), + (1_234_567_890, "005924"), + (2_000_000_000, "279037"), + ] { + assert_eq!(totp_at(key, t / 30), want, "t={t}"); + } + let t = 1_234_567_890; + let step = totp_check(key, "005 924", t, 0).unwrap(); + assert_eq!(step, t / 30); + // The same code again is refused; so is one from far away, or junk. + assert_eq!(totp_check(key, "005924", t, step), None); + assert_eq!(totp_check(key, "005924", t + 120, 0), None); + assert_eq!(totp_check(key, "12345", t, 0), None); + assert_eq!(totp_check(key, "abcdef", t, 0), None); + // One step of clock drift either side is fine. + assert!(totp_check(key, &totp_at(key, t / 30 + 1), t, 0).is_some()); + } + + #[test] + fn base32_and_the_app_link() { + assert_eq!( + base32(b"12345678901234567890"), + "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" + ); + assert_eq!(base32(b"f"), "MY"); + let uri = otpauth_uri("a+b@x.io", "ABC"); + assert!(uri.starts_with("otpauth://totp/CoderHelm:a%2Bb%40x.io?secret=ABC")); + } + + #[test] + fn a_reset_needs_a_reason_for_the_log() { + assert!(reset_reason("ok").is_err()); + assert!(reset_reason(" ").is_err()); + assert_eq!( + reset_reason(" Video call, saw their badge ").unwrap(), + "Video call, saw their badge" + ); + assert_eq!(reset_reason(&"x".repeat(500)).unwrap().len(), 300); + } + + #[test] + fn the_org_record_reads_back() { + let item = HashMap::from([ + ("team_id".to_string(), attr_s("TEAM#a")), + ( + "domains".to_string(), + AttributeValue::L(vec![attr_s("Example.com")]), + ), + ("require_2fa".to_string(), AttributeValue::Bool(true)), + ( + "require_2fa_since".to_string(), + attr_s("2026-10-26T00:00:00Z"), + ), + ]); + let o = Org::from_item(&item).unwrap(); + assert_eq!(o.domains, vec!["example.com".to_string()]); + assert!(o.require_2fa); + assert!(Org::from_item(&HashMap::new()).is_none()); + } + + /// The body of `fn name` in `src`. + fn body<'a>(src: &'a str, name: &str) -> &'a str { + let start = src + .find(&format!("fn {name}(")) + .unwrap_or_else(|| panic!("no fn {name}")); + let end = src[start..].find("\n}\n").map_or(src.len(), |e| start + e); + &src[start..end] + } + + fn before(hay: &str, first: &str, then: &str) -> bool { + match (hay.find(first), hay.find(then)) { + (Some(a), Some(b)) => a < b, + _ => false, + } + } + + /// Every way to make an account or a session on a self-hosted install + /// goes through the join rules before anything is written or a session + /// is made, and no path makes a team of its own there. + #[test] + fn every_sign_up_and_sign_in_path_checks_the_rules_first() { + let auth = include_str!("auth.rs"); + // Email sign-up: refused before Cognito is asked. + let signup = body(auth, "signup"); + assert!(before(signup, "sign_in::may_sign_up", ".sign_up()")); + assert!(signup.contains("UserLambdaValidationException")); + // Email confirmation makes no personal team. + let verify = body(auth, "verify_email"); + assert!(before(verify, "sign_in::applies()", "needs_personal_team")); + // Email sign-in (with or without the Cognito code): the landing. + let issue = body(auth, "issue_session_from_cognito"); + assert!(before( + issue, + "selfhost_landing", + "Created new user + team on first login" + )); + assert!(before(issue, "sign_in::applies()", "TEAM#{cognito_sub}")); + // Google. + let google = body(auth, "google_callback_inner"); + assert!(before(google, "selfhost_landing", "Google user created")); + assert!(before( + google, + "sign_in::second_step", + "Google user created" + )); + // GitHub: the organization's records or the landing, never a new team. + let github = body(auth, "github_callback_inner"); + assert!(before(github, "selfhost_landing", "Brand new user")); + assert!(before( + github, + "sign_in::second_step", + "SignInProof::new(false, \"github\")" + )); + // The landing makes teams only through the organization's own rules. + let landing = body(auth, "selfhost_landing"); + for word in [ + "decide_join", + "create_org", + "join_by_domain", + "accept_pending_invites", + ] { + assert!(landing.contains(word), "{word}"); + } + assert!(!landing.contains("Ulid::new")); + } + + /// The middleware reads the rule on every session request, before the + /// role check and before the handler runs; API keys take their own path. + #[test] + fn the_middleware_holds_sessions_on_every_request() { + let mw = include_str!("../middleware/auth.rs"); + let f = body(mw, "require_auth"); + assert!(before(f, "api_key_request", "sign_in::check_session")); + assert!(before( + f, + "sign_in::check_session", + "match permissions::resolve_access" + )); + assert!(before(f, "sign_in::check_session", "note_activity")); + // The refreshed session keeps its proof. + assert!(f.contains("create_session_token") && f.contains("&proof")); + // Read fresh each time: no cache in front of the rule. + let check = body(include_str!("sign_in.rs"), "check_session"); + assert!(check.contains("load_org(state)")); + assert!(!check.to_lowercase().contains("cache")); + } + + /// A reset is logged before anything changes, and only by an admin. + #[test] + fn a_reset_is_logged_first() { + let f = body(include_str!("sign_in.rs"), "reset_two_factor"); + assert!(before(f, "admin(&claims)?", "roles::record")); + assert!(before(f, "reset_reason", "roles::record")); + assert!(before(f, "roles::record", "admin_set_user_mfa_preference")); + assert!(before(f, "roles::record", "clear_app_factor")); + assert!(f.contains("can_manage")); + let u = body(include_str!("sign_in.rs"), "update_settings"); + assert!(before(u, "set_up_yours_first", "roles::record")); + assert!(before(u, "roles::record", ".update_item()")); + } + + #[test] + fn email_domains() { + assert_eq!(email_domain("a@B.io").as_deref(), Some("b.io")); + assert_eq!(email_domain("a@b"), None); + assert_eq!(email_domain("@b.io"), None); + assert_eq!(email_domain("nope"), None); + } +} diff --git a/services/gateway/src/routes/users.rs b/services/gateway/src/routes/users.rs index bd31b5f0c..2017b093e 100644 --- a/services/gateway/src/routes/users.rs +++ b/services/gateway/src/routes/users.rs @@ -2,6 +2,7 @@ use aws_sdk_dynamodb::types::{AttributeValue, Delete, TransactWriteItem, Update} use axum::{ extract::{Extension, Path, State}, http::StatusCode, + response::IntoResponse, Json, }; use serde::Deserialize; @@ -1169,7 +1170,7 @@ pub async fn mfa_verify_setup( State(state): State>, Extension(claims): Extension, Json(body): Json, -) -> Result, StatusCode> { +) -> Result { // Authenticate to get a Cognito access token let hash = cognito_secret_hash( &state.cognito_client_secret, @@ -1246,7 +1247,23 @@ pub async fn mfa_verify_setup( info!(email = %claims.email, "MFA enabled"); - Ok(Json(json!({ "status": "enabled" }))) + // A self-hosted install: the factor is recorded for admins, and this + // session, which just proved the password and a code, counts as signed + // in with two factors. + if crate::routes::sign_in::applies() { + crate::routes::sign_in::note_factor(&state, &claims.team_id, &claims.sub, Some("cognito")) + .await; + let cookie = + crate::routes::sign_in::session_with_second_factor(&state, &claims, "password") + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let mut resp = Json(json!({ "status": "enabled" })).into_response(); + if let Ok(v) = axum::http::HeaderValue::from_str(&cookie) { + resp.headers_mut().append(axum::http::header::SET_COOKIE, v); + } + return Ok(resp); + } + + Ok(Json(json!({ "status": "enabled" })).into_response()) } /// DELETE /api/users/mfa — Disable TOTP MFA. @@ -1257,6 +1274,15 @@ pub async fn mfa_disable( if role_level(&claims.role) < 3 && claims.email.is_empty() { return Err(StatusCode::FORBIDDEN); } + // A self-hosted install that requires two-factor sign-in keeps it on. + if crate::routes::sign_in::applies() + && crate::routes::sign_in::load_org(&state) + .await + .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)? + .is_some_and(|o| o.require_2fa) + { + return Err(StatusCode::CONFLICT); + } state .cognito @@ -1277,6 +1303,9 @@ pub async fn mfa_disable( })?; info!(email = %claims.email, "MFA disabled"); + if crate::routes::sign_in::applies() { + crate::routes::sign_in::note_factor(&state, &claims.team_id, &claims.sub, None).await; + } Ok(Json(json!({ "status": "disabled" }))) } From daafb88473da9bf439022c4ec3a0a785ea4d8727 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 26 Oct 2026 16:07:58 -0400 Subject: [PATCH 2/2] Two-factor: pause sign-in after repeated wrong codes, and end sessions on reset, removal, role change or turning it off --- docs/self-host/sign-in.md | 22 + infra/test/synth.test.ts | 1 + services/gateway/src/auth/jwt.rs | 17 +- services/gateway/src/middleware/auth.rs | 6 + services/gateway/src/permissions.rs | 3 +- services/gateway/src/routes/auth.rs | 28 +- services/gateway/src/routes/sign_in.rs | 720 +++++++++++++++++++++++- services/gateway/src/routes/users.rs | 23 +- 8 files changed, 807 insertions(+), 13 deletions(-) diff --git a/docs/self-host/sign-in.md b/docs/self-host/sign-in.md index 89db67b8f..075b71d36 100644 --- a/docs/self-host/sign-in.md +++ b/docs/self-host/sign-in.md @@ -44,6 +44,28 @@ With it on: **Settings, Sign-in** shows who has set it up. If someone loses their phone, an admin can reset their two-factor sign-in after checking it's really them (a video call, say). The admin writes how they checked; the reset and the reason go in the log under **Settings, Roles**. The person sets it up again at their next sign-in. Only an owner can reset an admin's or another owner's. Nobody can reset their own. +### Wrong codes + +Every place CoderHelm checks a code counts wrong ones against the person, by email, across every way in: the code after Google or GitHub, the code after a password, and turning the app code off. + +- **Ten wrong codes in 15 minutes** pause that person's sign-in with a code for 15 minutes. Each pause after that is twice as long, up to a day. After a quiet day the count starts over. A right code clears the wrong ones so far. +- **One sign-in through Google or GitHub** allows five wrong codes; after that the person starts again from the sign-in screen. +- **The person** sees a plain sentence saying how long the pause lasts. +- **Admins** get an email, and a line in the log under **Settings, Roles**. If they lost their phone, check it's them and reset; if it wasn't them, someone may know their password or have their Google or GitHub account. + +Cognito also limits wrong passwords on its own. + +### Sessions that end + +A person's existing sessions end, everywhere, when: + +- an admin resets their two-factor sign-in; +- an admin removes them from the team; +- their role changes; +- they turn their own two-factor sign-in off (the session they did it from keeps working). + +Every request checks the person's record, so the next request from an ended session goes back to the sign-in screen. + Why an authenticator app and not passkeys: Cognito's passkeys need its paid Essentials tier, a fixed sign-in domain (passkeys break when the CloudFront address changes to your own domain) and Cognito's hosted sign-in pages. Authenticator apps work on every install, including one on its free CloudFront address. ## Email and password diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index 073ad3f65..139afa5f4 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -576,6 +576,7 @@ test("the release check reads models.json only after the signature check, and ca assert.ok(actions.every((a) => a === "lambda:InvokeFunction" || a.startsWith("logs:") || /^codebuild:(Create|Update|BatchPut)/.test(a)), JSON.stringify(actions)); assert.ok(!actions.some((a) => /sts:|secretsmanager:|ssm:|cloudformation:|bedrock:/.test(a))); assert.equal(envOf(u, "coderhelm-prod-updater").RELEASE_CHECK_PROJECT_NAME, "coderhelm-prod-release-check"); +}); test("sign-in: self-host checks every new account in Cognito (pre-sign-up trigger); MFA stays optional with authenticator apps", () => { const t = synth(selfHost({ signup: { domains: ["Example.org"], emails: ["b@example.org"], requireTwoFactor: true } })); diff --git a/services/gateway/src/auth/jwt.rs b/services/gateway/src/auth/jwt.rs index 181866c38..c725cec43 100644 --- a/services/gateway/src/auth/jwt.rs +++ b/services/gateway/src/auth/jwt.rs @@ -117,6 +117,9 @@ pub struct SecondStep { #[serde(default)] pub github_login: Option, pub via: String, + /// This token's id: its wrong codes are counted, and it dies after five. + #[serde(default)] + pub jti: String, pub aud: String, pub iat: u64, pub exp: u64, @@ -129,6 +132,11 @@ pub fn create_second_step( ) -> Result { let now = chrono::Utc::now().timestamp() as u64; let s = SecondStep { + jti: if step.jti.is_empty() { + ulid::Ulid::new().to_string() + } else { + step.jti.clone() + }, aud: SECOND_STEP_AUDIENCE.to_string(), iat: now, exp: now + ttl_secs, @@ -277,13 +285,20 @@ mod tests { role: "member".into(), github_login: None, via: "github".into(), + jti: String::new(), aud: String::new(), iat: 0, exp: 0, }; let t = create_second_step(&step, secret, 300).unwrap(); assert!(validate_token(&t, secret).is_err()); - assert_eq!(validate_second_step(&t, secret).unwrap().sub, "USER#1"); + let back = validate_second_step(&t, secret).unwrap(); + assert_eq!(back.sub, "USER#1"); + // Each token gets its own id (wrong codes are counted against it). + assert_eq!(back.jti.len(), 26); + let other = + validate_second_step(&create_second_step(&step, secret, 300).unwrap(), secret).unwrap(); + assert_ne!(back.jti, other.jti); let session = create_token("u", "t", "e@x.com", "member", None, secret, 300).unwrap(); assert!(validate_second_step(&session, secret).is_err()); } diff --git a/services/gateway/src/middleware/auth.rs b/services/gateway/src/middleware/auth.rs index cffc3eec8..4a6af96d3 100644 --- a/services/gateway/src/middleware/auth.rs +++ b/services/gateway/src/middleware/auth.rs @@ -119,6 +119,12 @@ pub async fn require_auth( // screens that set one up; the rule is read on every request, so sessions // from before it was turned on are held at their next request. let proof = jwt::read_proof(token, &state.secrets.jwt_secret); + // The session against the member's record, read on every request: a + // removal, a role change, a two-factor reset or turning two-factor off + // ends every session issued before it. + if let Err(ended) = sign_in::check_member_session(&state, &claims).await { + return Ok(ended); + } if sign_in::applies() { if let Err(held) = sign_in::check_session(&state, &proof, handler).await { return Ok(held); diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 4feba3744..67bb1bbb6 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -748,7 +748,8 @@ pub const CUSTOM_PREFIX: &str = "custom:"; /// Capabilities a custom role can never hold, whatever the table says about /// them: managing roles, and support (checked by built-in role inside the /// support handlers), stay with built-in admins and owners. -pub const NEVER_IN_CUSTOM_ROLES: &[&str] = &["roles", "sign_in", "support", "system", "system.models"]; +pub const NEVER_IN_CUSTOM_ROLES: &[&str] = + &["roles", "sign_in", "support", "system", "system.models"]; /// The id in a `custom:` role, or `None` for a built-in role. pub fn custom_role_id(role: &str) -> Option<&str> { diff --git a/services/gateway/src/routes/auth.rs b/services/gateway/src/routes/auth.rs index 1adb7638b..f31e169ed 100644 --- a/services/gateway/src/routes/auth.rs +++ b/services/gateway/src/routes/auth.rs @@ -483,13 +483,18 @@ pub async fn mfa_verify( Json(body): Json, ) -> Result { let email = body.email.trim().to_lowercase(); + // A paused person gets no more tries; a wrong code counts against them. + let key = sign_in::person_key(&email, "", ""); + if let Some(left) = sign_in::lockout_left(&state, &key).await { + return Ok(sign_in::locked_response(left)); + } let hash = cognito_secret_hash( &state.cognito_client_secret, &email, &state.config.cognito_client_id, ); - let result = state + let challenge = state .cognito .respond_to_auth_challenge() .client_id(&state.config.cognito_client_id) @@ -499,11 +504,22 @@ pub async fn mfa_verify( .challenge_responses("USERNAME", &email) .challenge_responses("SECRET_HASH", &hash) .send() - .await - .map_err(|e| { + .await; + let result = match challenge { + Ok(r) => r, + Err(e) => { error!("MFA verification failed: {e}"); - StatusCode::UNAUTHORIZED - })?; + // Only a wrong code counts (not an expired Cognito session). + if format!("{e:?}").contains("CodeMismatch") { + if let Some(left) = sign_in::record_failure(&state, &key).await { + sign_in::notify_lockout(&state, &email, left).await; + return Ok(sign_in::locked_response(left)); + } + } + return Err(StatusCode::UNAUTHORIZED); + } + }; + sign_in::record_success(&state, &key).await; let auth_result = result .authentication_result() @@ -948,6 +964,7 @@ async fn google_callback_inner( role: role.clone(), github_login: github_login.clone(), via: "google".into(), + jti: String::new(), aud: String::new(), iat: 0, exp: 0, @@ -1638,6 +1655,7 @@ async fn github_callback_inner( role: role.clone(), github_login: Some(github_login.to_string()), via: "github".into(), + jti: String::new(), aud: String::new(), iat: 0, exp: 0, diff --git a/services/gateway/src/routes/sign_in.rs b/services/gateway/src/routes/sign_in.rs index de5901348..c6475fa2b 100644 --- a/services/gateway/src/routes/sign_in.rs +++ b/services/gateway/src/routes/sign_in.rs @@ -1131,8 +1131,9 @@ pub async fn app_verify( pub async fn app_disable( State(state): State>, Extension(claims): Extension, + proof: Option>, Json(body): Json, -) -> Result, ApiError> { +) -> Result { if !applies() { return Err(fail(StatusCode::NOT_FOUND, "Not available here.")); } @@ -1156,20 +1157,32 @@ pub async fn app_disable( "Two-factor sign-in is already off.", )); } + let key = person_key(&claims.email, &claims.team_id, &claims.sub); + if let Some(left) = lockout_left(&state, &key).await { + return Ok(locked_response(left)); + } if !use_app_code(&state, &item, &body.code) .await .map_err(|e| internal("Code not checked", e))? { + if let Some(left) = record_failure(&state, &key).await { + notify_lockout(&state, &claims.display_name(), left).await; + return Ok(locked_response(left)); + } return Err(fail_code( StatusCode::BAD_REQUEST, "That code didn't match. Enter the current 6-digit code from the app.", "wrong_code", )); } + record_success(&state, &key).await; clear_app_factor(&state, &claims.team_id, &claims.sub) .await .map_err(|e| internal("Two-factor not turned off", e))?; - Ok(Json(json!({ "status": "disabled" }))) + // Every other session of theirs ends; this one carries on. + let proof = proof.map(|p| p.0).unwrap_or_default(); + let cookie = end_other_sessions(&state, &claims, &proof).await?; + Ok(with_cookie(json!({ "status": "disabled" }), &cookie)) } async fn clear_app_factor(state: &AppState, team: &str, user: &str) -> Result<(), String> { @@ -1189,6 +1202,489 @@ async fn clear_app_factor(state: &AppState, team: &str, user: &str) -> Result<() .map_err(|e| format!("{e}")) } +// ── Wrong codes: per-person lockout ───────────────────────────────── +// +// Every place CoderHelm checks a two-factor code counts a wrong one against +// the person (by email, or their record when there is none): the code after +// Google or GitHub, Cognito's code after a password, and turning the app +// code off. Ten wrong codes in 15 minutes pause that person's code sign-in; +// each pause is twice as long as the last (15 minutes up to a day), and the +// count starts over after a quiet day. A pending second-step token also dies +// after five wrong codes. Admins of the organization are told. + +/// Wrong codes in this window count toward a pause. +pub const WINDOW_SECS: i64 = 900; +/// Wrong codes in a window that pause sign-in. +pub const MAX_FAILS: u32 = 10; +/// Wrong codes one pending second-step token survives. +pub const STEP_MAX_FAILS: i64 = 5; +const LOCK_PK: &str = "SIGNIN_LOCK"; +const STEP_PK: &str = "SIGNIN_STEP"; + +/// How long the `n`th pause in a row lasts: 15 minutes, doubling, at most a day. +pub fn cooldown_secs(n: u32) -> i64 { + (900i64 << n.saturating_sub(1).min(7)).min(86_400) +} + +/// One person's wrong codes. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Attempts { + pub window_start: i64, + pub fails: u32, + pub locked_until: i64, + /// Pauses so far (the next one is longer). + pub lockouts: u32, + pub last_lockout: i64, +} + +impl Attempts { + /// Seconds left in a pause, if paused. + pub fn locked_for(&self, now: i64) -> Option { + (self.locked_until > now).then(|| self.locked_until - now) + } + + /// One more wrong code. `true` when it starts a pause. + pub fn fail(mut self, now: i64) -> (Self, bool) { + if self.last_lockout > 0 && now - self.last_lockout > 86_400 { + self.lockouts = 0; + } + if now - self.window_start >= WINDOW_SECS { + self.window_start = now; + self.fails = 0; + } + self.fails += 1; + if self.fails >= MAX_FAILS { + self.lockouts += 1; + self.last_lockout = now; + self.locked_until = now + cooldown_secs(self.lockouts); + self.fails = 0; + self.window_start = now; + return (self, true); + } + (self, false) + } + + /// A right code: the count starts over (earlier pauses still lengthen the next). + pub fn success(mut self) -> Self { + self.fails = 0; + self.window_start = 0; + self + } + + fn from_item(i: &Item) -> Self { + let n = |k: &str| { + i.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse::().ok()) + .unwrap_or(0) + }; + Attempts { + window_start: n("window_start"), + fails: n("fails").max(0) as u32, + locked_until: n("locked_until"), + lockouts: n("lockouts").max(0) as u32, + last_lockout: n("last_lockout"), + } + } +} + +/// Who wrong codes count against: the email (the same person through every +/// way in), else their record. +pub fn person_key(email: &str, team_id: &str, user_id: &str) -> String { + let e = normalize_email(email); + if e.contains('@') { + format!("EMAIL#{e}") + } else { + format!("USER#{team_id}#{user_id}") + } +} + +/// The plain sentence for someone paused. +pub fn locked_message(secs: i64) -> String { + let mins = ((secs + 59) / 60).max(1); + let when = if mins >= 120 { + format!("{} hours", (mins + 59) / 60) + } else if mins == 1 { + "a minute".to_string() + } else { + format!("{mins} minutes") + }; + format!( + "Too many wrong codes. To keep your account safe, sign-in with a code is paused for {when}. If this wasn't you, tell an admin." + ) +} + +pub fn locked_response(secs: i64) -> Response { + let mut resp = ( + StatusCode::TOO_MANY_REQUESTS, + Json(json!({ "error": locked_message(secs), "code": "locked_out", "retry_after": secs })), + ) + .into_response(); + if let Ok(v) = HeaderValue::from_str(&secs.to_string()) { + resp.headers_mut().insert(header::RETRY_AFTER, v); + } + resp +} + +async fn load_attempts(state: &AppState, key: &str) -> Result<(Attempts, i64), String> { + let out = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(LOCK_PK)) + .key("sk", attr_s(key)) + .consistent_read(true) + .send() + .await + .map_err(|e| format!("{e}"))?; + Ok(match out.item() { + Some(i) => ( + Attempts::from_item(i), + i.get("ver") + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse().ok()) + .unwrap_or(0), + ), + None => (Attempts::default(), 0), + }) +} + +/// Seconds left in this person's pause, if any. A read that fails counts as +/// paused for a minute (the safe answer). +pub async fn lockout_left(state: &AppState, key: &str) -> Option { + match load_attempts(state, key).await { + Ok((a, _)) => a.locked_for(chrono::Utc::now().timestamp()), + Err(e) => { + error!(error = %e, "Wrong-code count not read; treated as paused"); + Some(60) + } + } +} + +async fn save_attempts(state: &AppState, key: &str, a: &Attempts, ver: i64) -> bool { + let n = |v: i64| AttributeValue::N(v.to_string()); + let ttl = chrono::Utc::now().timestamp() + 3 * 86_400; + state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", attr_s(LOCK_PK)) + .item("sk", attr_s(key)) + .item("window_start", n(a.window_start)) + .item("fails", n(i64::from(a.fails))) + .item("locked_until", n(a.locked_until)) + .item("lockouts", n(i64::from(a.lockouts))) + .item("last_lockout", n(a.last_lockout)) + .item("ver", n(ver + 1)) + .item("ttl", n(ttl.max(a.locked_until + 86_400))) + .condition_expression("attribute_not_exists(pk) OR ver = :v") + .expression_attribute_values(":v", n(ver)) + .send() + .await + .is_ok() +} + +/// Counts one wrong code. Returns the pause it starts, in seconds, if any. +pub async fn record_failure(state: &AppState, key: &str) -> Option { + for _ in 0..5 { + let Ok((a, ver)) = load_attempts(state, key).await else { + break; + }; + let now = chrono::Utc::now().timestamp(); + let (next, locked) = a.fail(now); + if save_attempts(state, key, &next, ver).await { + return locked.then(|| next.locked_until - now); + } + } + error!("Wrong code not counted after retries"); + None +} + +/// A right code: the count starts over. +pub async fn record_success(state: &AppState, key: &str) { + if let Ok((a, ver)) = load_attempts(state, key).await { + if a.fails > 0 { + save_attempts(state, key, &a.success(), ver).await; + } + } +} + +/// One more wrong code on a pending second-step token; its new count. +async fn step_failure(state: &AppState, jti: &str) -> i64 { + let ttl = chrono::Utc::now().timestamp() + 900; + state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(STEP_PK)) + .key("sk", attr_s(jti)) + .update_expression("ADD fails :one SET #t = :ttl") + .expression_attribute_names("#t", "ttl") + .expression_attribute_values(":one", AttributeValue::N("1".into())) + .expression_attribute_values(":ttl", AttributeValue::N(ttl.to_string())) + .return_values(aws_sdk_dynamodb::types::ReturnValue::UpdatedNew) + .send() + .await + .ok() + .and_then(|o| o.attributes) + .and_then(|a| { + a.get("fails") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + }) + // Not counted: treat the token as spent (the safe answer). + .unwrap_or(STEP_MAX_FAILS) +} + +async fn step_failures(state: &AppState, jti: &str) -> i64 { + state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(STEP_PK)) + .key("sk", attr_s(jti)) + .consistent_read(true) + .send() + .await + .ok() + .and_then(|o| o.item) + .and_then(|i| { + i.get("fails") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + }) + .unwrap_or(0) +} + +/// A pending token is dead after this many wrong codes. +pub fn step_spent(fails: i64) -> bool { + fails >= STEP_MAX_FAILS +} + +/// Tells the organization's admins that someone's code sign-in is paused: +/// a line in the log under Settings, Roles and an email to each admin and +/// owner. Self-hosted installs only (the hosted side has no organization). +pub async fn notify_lockout(state: &AppState, who: &str, secs: i64) { + if !applies() { + return; + } + let Ok(Some(org)) = load_org(state).await else { + return; + }; + let mins = (secs + 59) / 60; + let detail = format!( + "Two-factor sign-in paused for {mins} minutes for {who} after too many wrong codes." + ); + warn!(team_id = %org.team_id, "Two-factor sign-in paused after wrong codes"); + let now = chrono::Utc::now(); + let at = now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true); + let _ = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", attr_s(&org.team_id)) + .item( + "sk", + attr_s(&format!( + "{}{at}#{}", + super::roles::AUDIT_PREFIX, + ulid::Ulid::new() + )), + ) + .item("record_type", attr_s("role_audit")) + .item("at", attr_s(&at)) + .item("actor", attr_s("Coderhelm")) + .item("actor_id", attr_s("SYSTEM")) + .item("action", attr_s("two_factor_lockout")) + .item("role_id", attr_s("")) + .item("role_name", attr_s("")) + .item("detail", attr_s(&detail)) + .item( + "ttl", + AttributeValue::N((now + chrono::Duration::days(365)).timestamp().to_string()), + ) + .send() + .await; + let admins: Vec = team_members(state, &org.team_id) + .await + .unwrap_or_default() + .iter() + .filter(|i| !is_invite(i) && matches!(s(i, "role"), "owner" | "admin")) + .map(|i| s(i, "email").to_string()) + .filter(|e| e.contains('@')) + .collect(); + let body = format!( + "{detail}\n\nIf they lost their phone, check it's really them, then reset their two-factor sign-in in Settings, Sign-in. If it wasn't them, someone may know their password or have their Google or GitHub account: ask them to change it.\n" + ); + for to in admins { + let content = aws_sdk_sesv2::types::EmailContent::builder() + .simple( + aws_sdk_sesv2::types::Message::builder() + .subject( + aws_sdk_sesv2::types::Content::builder() + .data("Two-factor sign-in paused after wrong codes") + .build() + .expect("subject"), + ) + .body( + aws_sdk_sesv2::types::Body::builder() + .text( + aws_sdk_sesv2::types::Content::builder() + .data(&body) + .build() + .expect("body"), + ) + .build(), + ) + .build(), + ) + .build(); + if let Err(e) = state + .ses + .send_email() + .from_email_address(&state.config.ses_from_address) + .destination( + aws_sdk_sesv2::types::Destination::builder() + .to_addresses(&to) + .build(), + ) + .content(content) + .send() + .await + { + warn!(error = %e, "Lockout email not sent"); + } + } +} + +// ── Sessions: ended by a reset, a removal or a role change ────────── + +/// The member record field: sessions issued before this time (unix seconds) +/// are refused. +pub const VALID_AFTER: &str = "sessions_valid_after"; + +/// Why a session no longer counts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Ended { + /// No longer on the team. + Removed, + /// Ended by a reset, a role change or turning two-factor off. + Revoked, +} + +/// Whether a session issued at `iat` still counts against the member's +/// record now. Pure. +pub fn session_state(item: Option<&Item>, iat: u64) -> Result<(), Ended> { + let Some(i) = item else { + return Err(Ended::Removed); + }; + if is_invite(i) { + return Err(Ended::Removed); + } + let after = i + .get(VALID_AFTER) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + if iat < after { + return Err(Ended::Revoked); + } + Ok(()) +} + +pub fn session_ended(why: Ended) -> Response { + let msg = match why { + Ended::Removed => "You're no longer on this team. Sign in again, or ask an admin.", + Ended::Revoked => { + "Your session ended because your access or two-factor sign-in changed. Sign in again." + } + }; + let mut resp = ( + StatusCode::UNAUTHORIZED, + Json(json!({ "error": msg, "code": "session_ended" })), + ) + .into_response(); + if let Ok(v) = HeaderValue::from_str( + "__Host-coderhelm_session=; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=0", + ) { + resp.headers_mut().append(header::SET_COOKIE, v); + } + resp +} + +/// The middleware's check of one session against the member's record, read +/// fresh on every request. A read that fails refuses the request. +pub async fn check_member_session(state: &AppState, claims: &Claims) -> Result<(), Response> { + let item = match state + .dynamo + .get_item() + .table_name(&state.config.users_table_name) + .key("pk", attr_s(&claims.team_id)) + .key("sk", attr_s(&claims.sub)) + .projection_expression("pk, #st, #va") + .expression_attribute_names("#st", "status") + .expression_attribute_names("#va", VALID_AFTER) + .send() + .await + { + Ok(o) => o.item, + Err(e) => { + error!(error = %e, "Member record not read; request refused"); + return Err(StatusCode::SERVICE_UNAVAILABLE.into_response()); + } + }; + session_state(item.as_ref(), claims.iat).map_err(session_ended) +} + +/// Ends every session of a member issued before now. `include_now` also ends +/// one issued this very second (someone else's action); without it, a session +/// re-issued right after for the person acting keeps working. +pub async fn end_sessions( + state: &AppState, + team_id: &str, + user_id: &str, + include_now: bool, +) -> Result<(), String> { + let at = chrono::Utc::now().timestamp() + i64::from(include_now); + state + .dynamo + .update_item() + .table_name(&state.config.users_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(user_id)) + .update_expression("SET #va = :at") + .condition_expression("attribute_exists(pk)") + .expression_attribute_names("#va", VALID_AFTER) + .expression_attribute_values(":at", AttributeValue::N(at.to_string())) + .send() + .await + .map(|_| ()) + .map_err(|e| format!("{e}")) +} + +/// The caller's other sessions end; this one gets a fresh cookie. +pub async fn end_other_sessions( + state: &AppState, + claims: &Claims, + proof: &SignInProof, +) -> Result { + end_sessions(state, &claims.team_id, &claims.sub, false) + .await + .map_err(|e| internal("Sessions not ended", e))?; + let token = jwt::create_session_token( + &claims.sub, + &claims.team_id, + &claims.email, + claims.session_role(), + claims.github_login.as_deref(), + proof, + &state.secrets.jwt_secret, + SESSION_TTL_SECS, + ) + .map_err(|e| internal("Session not made", e))?; + Ok(session_cookie(&token)) +} + // ── Two-factor: the step after Google or GitHub ───────────────────── /// After a Google or GitHub sign-in: when the person has the @@ -1252,6 +1748,36 @@ pub async fn verify_second_step( "second_step_expired", ) })?; + let clear_step = || { + HeaderValue::from_str(&format!( + "{SECOND_STEP_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0" + )) + .ok() + }; + let with_cleared = |mut r: Response| { + if let Some(v) = clear_step() { + r.headers_mut().append(header::SET_COOKIE, v); + } + r + }; + let spent = || { + with_cleared( + fail_code( + StatusCode::UNAUTHORIZED, + "Too many wrong codes for this sign-in. Sign in again.", + "second_step_expired", + ) + .into_response(), + ) + }; + // A paused person, or a token with five wrong codes, gets no more tries. + let key = person_key(&step.email, &step.team_id, &step.sub); + if let Some(left) = lockout_left(&state, &key).await { + return Ok(with_cleared(locked_response(left))); + } + if step_spent(step_failures(&state, &step.jti).await) { + return Ok(spent()); + } let item = member(&state, &step.team_id, &step.sub) .await .map_err(|e| internal("Member not read", e))? @@ -1262,12 +1788,29 @@ pub async fn verify_second_step( .map_err(|e| internal("Code not checked", e))? { warn!(team_id = %step.team_id, "Second-step code refused"); + let token_fails = step_failure(&state, &step.jti).await; + if let Some(left) = record_failure(&state, &key).await { + let who = [ + step.email.as_str(), + step.github_login.as_deref().unwrap_or(""), + ] + .into_iter() + .find(|v| !v.is_empty()) + .unwrap_or("a member") + .to_string(); + notify_lockout(&state, &who, left).await; + return Ok(with_cleared(locked_response(left))); + } + if step_spent(token_fails) { + return Ok(spent()); + } return Err(fail_code( StatusCode::UNAUTHORIZED, "That code didn't work. Open your authenticator app and enter the current 6-digit code.", "wrong_code", )); } + record_success(&state, &key).await; let session = jwt::create_session_token( &step.sub, &step.team_id, @@ -1610,6 +2153,10 @@ pub async fn reset_two_factor( clear_app_factor(&state, &claims.team_id, &sk) .await .map_err(|e| internal("Two-factor not reset", e))?; + // Their sessions end: whoever holds one signs in again and sets it up. + end_sessions(&state, &claims.team_id, &sk, true) + .await + .map_err(|e| internal("Sessions not ended", e))?; info!(team_id = %claims.team_id, "Two-factor sign-in reset by an admin"); Ok(Json(json!({ "status": "reset" }))) } @@ -2034,6 +2581,175 @@ mod tests { assert!(before(u, "roles::record", ".update_item()")); } + #[test] + fn ten_wrong_codes_in_15_minutes_pause_and_each_pause_is_longer() { + let t0 = 1_800_000_000i64; + let mut a = Attempts::default(); + for i in 0..9 { + let (next, locked) = a.fail(t0 + i * 60); + assert!(!locked, "wrong code {}", i + 1); + a = next; + } + assert_eq!(a.locked_for(t0 + 600), None); + let (a, locked) = a.fail(t0 + 600); + assert!(locked, "the 10th wrong code pauses"); + assert_eq!(a.locked_for(t0 + 600), Some(900)); + assert_eq!(a.locked_for(t0 + 600 + 900), None); + // The next pause is twice as long, then doubles up to a day. + let mut b = a; + for _ in 0..10 { + b = b.fail(t0 + 2000).0; + } + assert_eq!(b.locked_for(t0 + 2000), Some(1800)); + assert_eq!( + (1..=10).map(cooldown_secs).collect::>(), + vec![900, 1800, 3600, 7200, 14_400, 28_800, 57_600, 86_400, 86_400, 86_400] + ); + // After a quiet day, pauses start short again. + let mut c = b; + for _ in 0..10 { + c = c.fail(t0 + 2000 + 2 * 86_400).0; + } + assert_eq!(c.lockouts, 1); + assert_eq!(c.locked_for(t0 + 2000 + 2 * 86_400), Some(900)); + } + + #[test] + fn wrong_codes_spread_out_or_followed_by_a_right_one_do_not_pause() { + let t0 = 1_800_000_000i64; + // Nine wrong codes every 15 minutes: never ten in one window. + let mut a = Attempts::default(); + for i in 0..36 { + let (next, locked) = a.fail(t0 + (i / 9) * WINDOW_SECS + i % 9); + assert!(!locked, "{i}"); + a = next; + } + let mut b = Attempts::default(); + for i in 0..9 { + b = b.fail(t0 + i).0; + } + b = b.success(); + assert!(!b.fail(t0 + 10).1, "a right code starts the count over"); + let mut w = Attempts::default(); + for i in 0..9 { + w = w.fail(t0 + i).0; + } + assert!(!w.fail(t0 + WINDOW_SECS + 1).1, "the window moved on"); + } + + #[test] + fn a_pending_token_dies_after_five_wrong_codes() { + assert!(!step_spent(4)); + assert!(step_spent(5)); + assert!(step_spent(6)); + } + + #[test] + fn wrong_codes_count_against_the_person_through_every_way_in() { + // The same email through Google, GitHub and a password: one count. + assert_eq!( + person_key("Ann+x@Example.com", "TEAM#a", "USER#Google_1"), + "EMAIL#ann@example.com" + ); + assert_eq!( + person_key("ann@example.com", "", ""), + "EMAIL#ann@example.com" + ); + // No email (GitHub without one): their record. + assert_eq!(person_key("", "TEAM#a", "USER#9"), "USER#TEAM#a#USER#9"); + assert!(locked_message(900).contains("15 minutes")); + assert!(locked_message(30).contains("a minute")); + assert!(locked_message(86_400).contains("24 hours")); + let r = locked_response(900); + assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS); + assert_eq!(r.headers()[header::RETRY_AFTER], "900"); + } + + #[test] + fn a_session_ends_with_a_removal_a_role_change_or_a_reset() { + let rec = |after: Option, status: Option<&str>| { + let mut m: Item = HashMap::from([("pk".to_string(), attr_s("TEAM#a"))]); + if let Some(a) = after { + m.insert(VALID_AFTER.into(), AttributeValue::N(a.to_string())); + } + if let Some(st) = status { + m.insert("status".into(), attr_s(st)); + } + m + }; + assert_eq!(session_state(Some(&rec(None, None)), 100), Ok(())); + assert_eq!(session_state(None, 100), Err(Ended::Removed)); + assert_eq!( + session_state(Some(&rec(None, Some("invited"))), 100), + Err(Ended::Removed) + ); + assert_eq!( + session_state(Some(&rec(Some(200), None)), 100), + Err(Ended::Revoked) + ); + assert_eq!( + session_state(Some(&rec(Some(200), None)), 200), + Ok(()), + "issued at the cut" + ); + assert_eq!( + session_state(Some(&rec(Some(200), None)), 300), + Ok(()), + "a later sign-in" + ); + let r = session_ended(Ended::Revoked); + assert_eq!(r.status(), StatusCode::UNAUTHORIZED); + assert!(r.headers()[header::SET_COOKIE] + .to_str() + .unwrap() + .contains("Max-Age=0")); + } + + /// Every code check counts wrong codes and refuses a paused person first; + /// every change that must end sessions ends them. + #[test] + fn every_code_check_is_capped_and_every_change_ends_sessions() { + let me = include_str!("sign_in.rs"); + let auth = include_str!("auth.rs"); + let users = include_str!("users.rs"); + let step = body(me, "verify_second_step"); + assert!(before(step, "lockout_left", "use_app_code")); + assert!(before(step, "step_spent(step_failures", "use_app_code")); + assert!(before(step, "step_failure(&state", "record_success")); + assert!(step.contains("record_failure") && step.contains("notify_lockout")); + let mfa = body(auth, "mfa_verify"); + assert!(before( + mfa, + "sign_in::lockout_left", + ".respond_to_auth_challenge()" + )); + assert!(mfa.contains("sign_in::record_failure") && mfa.contains("sign_in::notify_lockout")); + let off = body(me, "app_disable"); + assert!(before(off, "lockout_left", "use_app_code")); + assert!(before(off, "clear_app_factor", "end_other_sessions")); + let reset = body(me, "reset_two_factor"); + assert!(before( + reset, + "clear_app_factor", + "end_sessions(&state, &claims.team_id, &sk, true)" + )); + assert!(body(users, "update_role").contains("sign_in::VALID_AFTER")); + assert!(body(users, "mfa_disable").contains("end_other_sessions")); + // A removal deletes the record, and the middleware refuses a session + // with no record. + assert!(body(users, "remove_user").contains(".delete_item()")); + let mw = body(include_str!("../middleware/auth.rs"), "require_auth"); + assert!(before(mw, "api_key_request", "check_member_session")); + assert!(before( + mw, + "check_member_session", + "match permissions::resolve_access" + )); + assert!(!body(me, "check_member_session") + .to_lowercase() + .contains("cache")); + } + #[test] fn email_domains() { assert_eq!(email_domain("a@B.io").as_deref(), Some("b.io")); diff --git a/services/gateway/src/routes/users.rs b/services/gateway/src/routes/users.rs index 2017b093e..6d8d3f5f0 100644 --- a/services/gateway/src/routes/users.rs +++ b/services/gateway/src/routes/users.rs @@ -881,8 +881,14 @@ pub async fn update_role( .table_name(&state.config.users_table_name) .key("pk", attr_s(&claims.team_id)) .key("sk", attr_s(&sk)) - .update_expression("SET #r = :role, updated_at = :now") + // Their sessions end with the change: they sign in again with the new role. + .update_expression("SET #r = :role, updated_at = :now, #va = :va") .expression_attribute_names("#r", "role") + .expression_attribute_names("#va", crate::routes::sign_in::VALID_AFTER) + .expression_attribute_values( + ":va", + AttributeValue::N((chrono::Utc::now().timestamp() + 1).to_string()), + ) .expression_attribute_values(":role", attr_s(&body.role)) .expression_attribute_values(":now", attr_s(&chrono::Utc::now().to_rfc3339())) .condition_expression(condition); @@ -1270,7 +1276,8 @@ pub async fn mfa_verify_setup( pub async fn mfa_disable( State(state): State>, Extension(claims): Extension, -) -> Result, StatusCode> { + proof: Option>, +) -> Result { if role_level(&claims.role) < 3 && claims.email.is_empty() { return Err(StatusCode::FORBIDDEN); } @@ -1306,8 +1313,16 @@ pub async fn mfa_disable( if crate::routes::sign_in::applies() { crate::routes::sign_in::note_factor(&state, &claims.team_id, &claims.sub, None).await; } - - Ok(Json(json!({ "status": "disabled" }))) + // Every other session of theirs ends; this one carries on. + let proof = proof.map(|p| p.0).unwrap_or_default(); + let cookie = crate::routes::sign_in::end_other_sessions(&state, &claims, &proof) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let mut resp = Json(json!({ "status": "disabled" })).into_response(); + if let Ok(v) = axum::http::HeaderValue::from_str(&cookie) { + resp.headers_mut().append(axum::http::header::SET_COOKIE, v); + } + Ok(resp) } // ── Helpers ──────────────────────────────────────────────────────────