diff --git a/AGENTS.md b/AGENTS.md index 5b838cf..65b0791 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,6 +40,10 @@ Planned. Each v1 issue adds its part. section 10). - `internal/grantkey/` - the token of a standing grant: make, parse, hash, and hide it in every format (DESIGN.md section 8). + - `internal/totp/` - TOTP codes made on the broker (RFC 6238) from the + `login.totp` field of a Bitwarden item (DESIGN.md section 21). + - `internal/loginmatch/` - the page URL of a website login and + Bitwarden's URI match types (DESIGN.md section 21). - `internal/doctor/` - the checks of `nodkey doctor` (client) and `nodkey doctor broker`: read only, with the text and JSON form of the result (DESIGN.md section 15). @@ -116,7 +120,8 @@ that it makes. request. If it changes the config, the example unit, a command, or a line that `docs/setup.md` or a `docs/manual-*-test.md` guide shows, update these guides too. -- **Dependencies:** the standard library, `golang.org/x/crypto` and +- **Dependencies:** the standard library, `golang.org/x/crypto`, + `golang.org/x/net` (only `publicsuffix`, for website logins) and `github.com/BurntSushi/toml`. Anything else needs a reason in the pull request. The `1password` and `infisical` stores also link the official 1Password and Infisical Go SDKs (DESIGN.md section 4). diff --git a/DESIGN.md b/DESIGN.md index e102b7d..e9ad746 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1971,9 +1971,11 @@ The fields of each event, after `seq`, `time`, `event` and `prev`: | `log_recovered` | `torn_length` and `torn_sha256`: the length and the SHA-256 of the torn line | The request fields are `request_id`, `client`, `kind` (`secrets`, -`ssh_login`, `ssh_grant`, `preapprove` or `standing`), `secrets`, `key`, `hosts`, +`ssh_login`, `ssh_grant`, `preapprove`, `standing` or `web_login`), `secrets`, `key`, `hosts`, `host_key` (a SHA256 fingerprint), `remote_user`, and the claimed -`command` and `reason`. A `preapprove` request that was approved also has +`command` and `reason`. A website login (section 21.8) has `logins` (the +`[logins.NAME]` section), `item` (the item ID) and the claimed `origin`, +never a username. `login_list` and `login_totp` are its other entries. A `preapprove` request that was approved also has `grant_id`, `uses`, `not_before` and `not_after` (UTC, RFC 3339). A `standing` request that was approved also has `windows` (such as `daily 03:00-05:00`), and its `uses` are the uses in each window; the @@ -4099,6 +4101,7 @@ bws 2.1.0 and bw 2026.9.1 on 2026-10-14 | a `bw` unlock | `bw unlock --passwordfile FILE --raw --nointeraction` | stdout: only the session key, in base64. | | a `bw` fetch, first | `bw sync --force --nointeraction` | only the exit code. | | a `bw` fetch, then | `bw get item ID --nointeraction` | stdout: one JSON object, the item. The broker reads only `id`, `login.password`, `deletedDate` and `archivedDate`. | +| a website login (section 21) | `bw list items --collectionid ID --nointeraction`, and `bw get item ID --nointeraction` | see section 21.9. | | after a `bw` step failed | `bw status --nointeraction` | stdout: one JSON object. The broker reads only `status`: `unauthenticated` (logged out), `locked` (the session key does not work) or `unlocked`. | - Both programs write errors to stderr and exit with 1; `bws` exits with @@ -4522,3 +4525,268 @@ Standards we use or borrow names from: (a request ID, a short code shown on both sides, an expiry), and [RFC 4252](https://www.rfc-editor.org/rfc/rfc4252) (the SSH authentication request). + +## 21. Website logins + +Issue #103. An agent logs in to a website with a browser that it drives. +nodkey hands it one login (a username and a password, and later one TOTP +code) after a tap, from a shared collection of the owner's Bitwarden +vault. The only browser that nodkey supports is agent-browser, through +its credential plugin (#104). nodkey has no Chrome DevTools Protocol +command of its own. + +**What is built.** The broker part of #103 is built: the config, the +three requests, the URI match, TOTP codes, the messages, the grants, the +one-use pre-approval and the audit events. Not built yet: standing +grants for logins (a request with a grant token is refused), a reload +that changes `[logins.*]`, and the browser plugin (#104). + +### 21.1 The owner's setup + +No nodkey code. The owner's main Bitwarden account makes an organization +with one collection, for example `agents`. The separate account of the +broker's `bw` store (T24) is the second member. It has access to that +collection only, with "Can view": it cannot change items. The owner +moves the logins that agents may use into the collection. The owner still +sees, fills and changes them in the normal vault. The Free plan allows 2 +users and 2 collections +([organizations](https://bitwarden.com/help/what-is-an-organization/), +seen 2026-10-21). `docs/setup.md` shows the steps. + +The master password on the broker still opens only what the separate +account can see (section 11): the collection, not the owner's vault. +Putting an item into the collection is the "allow" step: no config edit, +no restart. + +### 21.2 Config *(built: `internal/config/logins.go`)* + +```toml +[logins.web] # any name +store = "vault" # a store of type bw +collection = "00000000-0000-0000-0000-000000000000" +clients = ["laptop"] +ask = "window" # always or window +window = "15m" +preapprove = true # optional; `nodkey preapprove --login` may ask for it +standing = false # optional; standing grants of one item + +[[logins.web.items]] # optional; the rule of one item +id = "11111111-1111-1111-1111-111111111111" +clients = ["laptop"] # this item's rule replaces the collection's rule +ask = "always" +``` + +- `store` must be a `bw` store. `collection` and `id` are UUIDs, in + upper or lower case. +- `ask = "never"` is refused, for the collection and for an item: a + website login always needs a tap, or a grant that came from a tap. +- **The item's rule wins, completely** (owner, 2026-11-11). Its + `clients`, `ask`, `window`, `preapprove` and `standing` replace the + collection's rule. Nothing is merged. A client that is in the + collection's `clients` but not in the item's `clients` is refused. The + item's rule may be looser than the collection's: the owner wrote it for + that one item. Two rules for one item, in one section or in two, are + an error at start and at reload. +- The broker applies the rule on each request, after it has found the + item, not only at start. +- The same collection in two `[logins.*]` sections is an error at start + and at reload. +- An item that leaves the collection is no longer served, even if it has + its own rule. +- For now, a change of `[logins.*]` needs a restart: a reload refuses + it and names `[logins.*]` (section 14, "Reload"). This ends when the + broker keeps login grants per item (21.7). +- `nodkey broker config-diff` lists the changes of `[logins.*]`. A new + or a removed item rule is marked as one that widens: either rule can + be the looser one. + +### 21.3 Requests *(built: `internal/broker/logins.go`)* + +The paths are `/v1/logins/list`, `/v1/logins/login` and +`/v1/logins/totp` (`internal/api/logins.go`). The client names the item +by its ID only. The broker looks for it in the stores of the +`[logins.*]` sections that may allow the client, and finds the section +from the item's `collectionIds`. + +The client sends a page URL. **The page URL is claimed** (T43): the +broker cannot check that the browser is on that page. + +1. **List** (no tap). The client sends a page URL. The broker runs + `bw sync --force` and `bw list items --collectionid ID`, and returns + the items that have a URI that matches the page (21.4): the item ID, + the item name and the username. Never a password or a TOTP seed. A + tap only to see a list would teach the approver to tap without + reading, so a list needs none. It has a rate limit per client of + `LoginListRate` (10 lists a minute). Every list has an audit entry: + one for each section of the client, with a count of 0 when nothing + matches. A refused list (rate limit, bad URL, store failure) has one + entry with a `cause`, at most `refusedEntriesPerMinute` a minute. +2. **Login** (a tap, a grant, or a pre-approval). The client sends a + page URL and one item ID from the list. The broker runs + `bw sync --force` and `bw get item ID` (at most `LoginRequestRate`, + 10 a minute per client, for logins and pre-approvals together; more + get 429 before the store runs), and checks that the item: + is a login item; is not in the trash; is not archived; has + `collectionIds` that hold the configured collection and no other + configured collection; has no item rule in another section; and has a URI that matches the page. Each + check that fails means deny, with an audit entry. Then it applies the + item's rule (21.2). The broker clears the password and the TOTP seed + at once: they are not kept while the request waits for the tap. On + approval it runs `bw sync --force` and `bw get item ID` again, runs + every check again, and the username, the item name and the rule + must be the same as in the message. Then it returns the username and the password. + A request with the header of a standing grant token is refused: + standing grants for logins are not built yet. + An item with Bitwarden's "Master password re-prompt" (`reprompt` is + 1) needs a tap for each login, whatever its rule: no `window` grant + and no standing grant hands it out. A pre-approval is a tap for that + one login, so it works. +3. **TOTP code.** When the item has `login.totp`, the broker makes the + current code itself (*built*: `internal/totp`). The seed never leaves + the broker. The client asks for the code after the password step, + when the site shows its code page. It sends the same page origin and + item ID. + - An approved login (a tap, a window grant or a pre-approval) leaves a + ticket for (client, item ID, page origin). It covers **one** code, + for `LoginTOTPTime` (2 minutes) after the login. The second ask for + a code needs a new login. The broker keeps at most 1024 tickets. + - A `window` grant covers codes during its window, like logins. + - A request with no ticket and no grant is answered with 403 and an + entry, at most `LoginTOTPNoTicketRate` (10) a minute per client; + more get 429 and no entry. A store failure is `store`, status 503. + - Standing grants for logins are not built yet (21.7). + +Several logins for one site: the list shows them all, and the client +names one item ID. The page must match that item. + +### 21.4 URI match *(built: `internal/loginmatch`)* + +The broker follows the match type of each URI of the item, as Bitwarden +does: + +| match | Bitwarden name | the page matches when | +|---|---|---| +| `null` or `0` | base domain | the base domains are the same: the public suffix and one label more (`shop.example.co.uk` โ†’ `example.co.uk`) | +| `1` | host | the host and the port are the same | +| `2` | starts with | the URI is `https`, its host and port are the page's, and the page URL, with no fragment, starts with the URI, as plain text | +| `3` | exact | the URI is `https`, its host and port are the page's, and the page URL, with no fragment, is the URI | +| `4`, `5`, other | regular expression, never | never | + +- A URI with no match type uses the base domain (#103 open question 5). + The real default is a setting of each Bitwarden app, which the CLI + cannot read. Base domain is the loosest type: an item with the URI + `https://app.example.com` and no match type also serves + `https://other.example.com`. Set the match type of each URI to "Host" + when other hosts of the same domain are run by other people (T43). +- The public suffix list comes from `golang.org/x/net/publicsuffix` + (BSD-3-Clause, the same authors and licence as `golang.org/x/crypto`). + It holds the private suffixes too, so `alice.github.io` and + `bob.github.io` do not match. A host that is itself a public suffix + matches nothing. An IP address and a name with no dot are their own + base domain. +- Bitwarden's equivalent domains are not used. +- A URI with no scheme is read as `http://`, as Bitwarden does. A URI of + another scheme, such as `androidapp://`, matches no page. +- **The page URL must be `https`** (owner, 2026-11-11). An `http` page, + such as a router on the local network, is refused for now. +- The page URL must be at most 2048 bytes, in plain ASCII, with a host + name in plain ASCII (punycode for other letters), no user name or + password, no trailing dot, and a port from 1 to 65535. Port 443 is + dropped. Anything else is refused, and the error never holds the URL. +- "Starts with" and "exact" are stricter than in Bitwarden. In + Bitwarden, the URI `https://example.com` with "starts with" also + matches `https://example.com.example.net/`. In nodkey the host and the + port must be the same as the page's first. +- A host whose last label is all digits, or starts with `0x`, is refused + unless it is an IP address: a browser reads `https://192.0.2.01/` as + an IP address. +- The public suffix list is the one in the `golang.org/x/net` version in + `go.mod`. It changes only when that dependency is updated. + +### 21.5 TOTP forms *(built: `internal/totp`)* + +- A plain base32 secret: SHA1, 6 digits, 30 seconds. Spaces, dashes, + lower case and missing padding are accepted. +- An `otpauth://totp/...?secret=...` URI with `algorithm` SHA1, SHA256 or + SHA512, `digits` from 6 to 8, and `period` from 1 to 3600 seconds. +- Everything else is refused with an error that says what to fix: + `steam://`, `otpauth://hotp`, another algorithm, other digits, two + values of one parameter. The error never holds the field. +- The tests use the test vectors of RFC 6238, appendix B. + +### 21.6 Messages *(built)* + +The message shows the item name and the username as read from Bitwarden +(verified), and the page origin as sent by the client (claimed): + +> log in to https://example.com as alice@example.com (Example shop), from laptop + +The pre-approval message says what the tap allows, and for how long +after the tap: + +> approve one login to https://example.com as alice@example.com (Example shop), from laptop, in the next 60 s + +The message never names a time limit for the tap itself. + +The item name and the username come from the owner's vault, but they can +hold any text, for example from an import. They get the same treatment +as claimed text (section 7): one line, no control characters and no +characters that change the direction of the text, a length limit, and +escaped HTML. The claimed origin comes after the verified lines. + +### 21.7 Grants and the one-use pre-approval *(built)* + +Grants are kept per (client, item ID), and the one-use pre-approval per +(client, item ID, page origin). They are not kept per config section +name: a grant must not move to another item through a rename. A grant +for one login does not hand out another login of the same site. On +reload, a grant stays only if the new config still gives the same rule +to that item (`RuleFor` gives the same clients and rule). + +**The pre-approval** (step 9 of #103, owner 2026-10-27) is +`nodkey preapprove --login ITEM --url URL`, on the grant core of +`nodkey preapprove` (section 8). It asks for a tap and hands out nothing. + +- It waits for the tap as long as any other request: the broker's + `timeout` setting. No extra limit for logins (owner, 2026-11-11). +- After the tap, the broker keeps a one-use approval for (client, item + ID, origin) for `LoginPreapproveTime` = **60 seconds**. +- The next login request with the same client, item and origin gets the + login without a tap, and uses the approval up, in one atomic step. A + request from another client, for another item or another origin does + not use it. +- It works for items with `ask = "always"` too, when the rule has + `preapprove = true`. +- Why: agent-browser waits only 15 seconds for a credential plugin, and + a tap often takes longer. So the wait runs in a nodkey command. + +### 21.8 Audit events + +*(Built.)* New events: `login_list` (client, collection section, page +origin, the number of items; or the `cause` of a refused list), `login_totp` (client, section, item ID, +page origin, the decision and why), the request events of section 9 with +the kind `web_login` and the subject fields `logins`, `item` and +`origin`, and the `preapprove` events of section 9 with these subject +fields. No event holds a +password, a TOTP seed, a TOTP code or a username. + +### 21.9 What the broker reads from bw *(built)* + +| when | command | what the broker reads | +|---|---|---| +| a list | `bw sync --force`, then `bw list items --collectionid ID --nointeraction` | stdout: one JSON array of items. Of each item: `id`, `type`, `name`, `reprompt`, `deletedDate`, `archivedDate`, `collectionIds`, `login.username`, and `uri` and `match` of each `login.uris`. It checks `login.password` and `login.totp` (a string or `null`) and keeps neither. | +| a login | `bw sync --force`, then `bw get item ID --nointeraction` | the same fields, and `login.password` and `login.totp`, each into its own buffer that is cleared after use. | + +- `bw list items` returns whole items, with every password of the + collection. The broker skips every other field without keeping it, and + clears the whole answer at once. +- Items that are not logins (`type` is not 1), in the trash, archived, + or whose `collectionIds` do not hold the collection are left out of a + list. +- A login with no password, or a password with a NUL byte, is refused. +- Limits: 500 items in a collection, and 1 MiB for the whole answer, as + for every store program; 100 URIs and 100 collections of an item, 1024 + bytes of a name or a username, 2048 bytes of a URI. An answer over a + limit is refused: the broker never cuts a field. One bad item refuses + the whole list, so the list fails closed. +- `reprompt` is read too (21.3). diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md index 9eb0532..2b35a2c 100644 --- a/THREAT-MODEL.md +++ b/THREAT-MODEL.md @@ -1008,6 +1008,22 @@ What to do: a security key. A code by email does not help if you read that email on an agent machine. +**Website logins (DESIGN.md section 21, owner 2026-11-11).** The logins +that agents may use are in a collection of an organization that the +owner's main account owns. So the main account can read them, and the +rule above needs other words for it. These are the owner's own logins, +and the owner uses them every day. The rule is: +- The separate account of the `bw` store stays off agent machines, in + every app, as above. +- The owner's main vault is never unlocked in a browser or an app that + an agent can drive: not in agent-browser, not in a browser that the + agent reaches over the Chrome DevTools Protocol, and not in a browser + profile that such a browser uses. An agent that drives a browser with + the unlocked extension can open the extension's own page in a tab and + read every item (T46). +- The owner may keep the main vault unlocked in a browser that only the + owner uses, on a machine with no agent. + Risk that remains: real. nodkey cannot see a read in Bitwarden's own apps, and it cannot check where an account is logged in. @@ -1507,6 +1523,90 @@ is in neither list. The short form never drops a line that widens: when they do not all fit, it says how many there are. It reads no credential. It is no control of the broker: it only helps a person to decide. +**T43. A website login goes to a page that the client claims.** +The client sends the page URL of a login (DESIGN.md section 21). The +broker cannot check that the browser is on that page: the agent can +claim `https://example.com` and paste the password into another site. +What nodkey does: +- The message shows the page origin as claimed, and the item name and + the username as read from Bitwarden. The tap is for that login, from + that client. +- The page must be `https`, and it must match a URI of the item, by + Bitwarden's match type of that URI. So a login for one site is never + handed out for a page of another site, by mistake or by a prompt + injection that names a wrong site. +- "Starts with" and "exact" also need the same host and port as the + page, which is stricter than in Bitwarden. +- A URI with no match type uses the base domain, the loosest type + (DESIGN.md section 21.4). Where other people run other hosts of the + same domain, set the URI's match type to "Host". +- The page URL is checked strictly and is never in an error. +What nodkey does not do: it cannot stop an agent that has the password +from using it anywhere. This is the same as for every secret (section 5). +Risk that remains: real, and the same as for a secret. + +**T44. A list of logins shows item names and usernames on the agent +machine.** +A list needs no tap (DESIGN.md section 21.3). It shows the item ID, the +item name and the username of each item of the collection that matches +the page. These are not secrets, but they tell the agent which accounts +the owner has on a site. +What nodkey does: a list shows only items that match an `https` page, +never a password or a TOTP seed. Each list is in the audit log, even an +empty or refused one, and lists have a rate limit per client. The owner puts into the collection only +the logins that agents may use. +Risk that remains: low. + +**T45. The broker reads TOTP seeds.** +The broker makes TOTP codes itself, so it reads the seed of each login +it hands out. Anyone who controls the broker can make codes. And a login +with its seed in the same item is one factor, not two, for anyone who +can read the item. +What nodkey does: +- The seed never leaves the broker: not in an answer, an error, a log or + the audit log. Its type hides it in every format, and its buffer is + cleared after use. +- A code is handed out only after an approved login, for one code within + 2 minutes, or during a `window` grant. +- `bw list items` returns every seed of the collection: the broker checks + the field and keeps none of it, and clears the whole answer. +- Only base32 secrets and `otpauth://totp` are read; `steam://` and other + forms are refused. +Risk that remains: the broker host is trusted (section 3). Put a login +whose second factor matters more into the collection with no seed, and +type the code yourself. + +**T46. The owner's vault is open in a browser that an agent drives.** +An agent that drives a browser with an unlocked Bitwarden extension can +open the extension's own page in a tab and read every item. Then nodkey +gives no protection. See the rule for website logins in T32. +What nodkey does: the setup guide says it, and the agent-browser how-to +(#104) uses a separate browser profile with no password manager. +Risk that remains: real; it depends on the owner. + +**T47. A login grant or a pre-approval hands out another login.** +A `window` grant or a one-use pre-approval (DESIGN.md section 21.7) +lets a login go out without a new tap. An agent could try to use it for +another item of the same site, from another client, for another page, or +later than the person meant. +What nodkey does: +- A `window` grant covers (client, item ID), never a config section or a + site. A pre-approval covers (client, item ID, page origin). +- A pre-approval is used at most once, in one atomic step, and ends + `LoginPreapproveTime` (60 seconds) after the tap. The message says + this. It names no time limit for the tap itself. +- An item with "Master password re-prompt" needs a tap for each login; + no `window` grant hands it out. +- The broker does not keep the password while the request waits for the + tap. After the tap it reads the item again and runs every check again; + the username, the item name, the rule and the re-prompt flag must be + unchanged. +- Logins and pre-approvals have a rate limit per client, before the + store runs. +- A reload keeps a login grant only when the item has the same rule. +Risk that remains: low. In its 60 seconds, a pre-approval can be used by +any process of that client that asks for that item and origin (as T35). + ## 7. Assumptions - The broker host is patched, has no agent on it, and only the owner has diff --git a/docs/setup.md b/docs/setup.md index bea76c7..e3b7102 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -940,6 +940,102 @@ access to it: such an account could read them too. not start, and the error has `bw unlock` and `took too long`, the unlock took more than 30 seconds: lower the KDF settings (step 3). +### Website logins: a shared collection + +> **The browser part is not ready yet.** The broker hands out logins +> (issue #103). The plugin for agent-browser is issue #104. Until then, +> only `nodkey preapprove --login` uses logins from the command line. + +Agents can log in to websites with logins from your own Bitwarden vault. +You choose the logins: you put them into one shared collection. The +separate account of the `bw` store (above) can read only that +collection. You still see, fill and change these logins in your normal +vault. A password that you change there is used on the next request. + +The Free plan of Bitwarden allows an organization with 2 users and 2 +collections ([organizations](https://bitwarden.com/help/what-is-an-organization/), +seen 2026-10-21). That is enough: your main account and the separate +account. + +1. **Make the organization.** Log in to the web app with your main + account. Choose **New organization**, give it a name, and choose the + Free plan. +2. **Make the collection.** In the organization, open **Collections** + and make one named, for example, `agents`. +3. **Invite the separate account.** In **Members**, invite the email + address of the separate account of the `bw` store, with the role + **User**. Give it access to the `agents` collection only, with the + permission **Can view**. It must not be able to change items. Do not + give it "Can view, except passwords": then the broker cannot read the + password. Accept the invitation as the separate account, and confirm + the member with your main account. +4. **Move the logins.** In your main vault, open each login that agents + may use, and choose **Assign to collections** (or **Move to + organization**) and `agents`. Only these logins. Check the URIs of + each item: the broker hands out a login only for an `https` page that + matches a URI of the item, with Bitwarden's match type of that URI. + A URI with no match type is read as **Base domain**, the loosest + type. When other people run other hosts of the same domain, set the + match type to **Host**. Regular expressions never match. +5. **The TOTP seed, if any.** When a login has an "Authenticator key", + the broker makes the codes itself. It reads a base32 secret, or an + `otpauth://totp` URI with SHA1, SHA256 or SHA512, 6 to 8 digits and + any period. It refuses `steam://` and other forms. For a site whose + second factor matters more, leave the key out of the item and type + the code yourself. +6. **Find the ID of the collection.** On the broker host, as the user of + the store, after a sync: + + ```sh + bw list collections --nointeraction + ``` + + The config names the collection by its `id`, never by its name. +7. **Add the collection to `broker.toml`** (DESIGN.md section 21.2): + + ```toml + [logins.web] + store = "vault" + collection = "00000000-0000-0000-0000-000000000000" + clients = ["laptop"] + ask = "window" + window = "15m" + preapprove = true + + [[logins.web.items]] + id = "11111111-1111-1111-1111-111111111111" + clients = ["laptop"] + ask = "always" + preapprove = true + ``` + + `store` is a store of type `bw`. `ask = "never"` is refused for + logins. An item's own rule replaces the rule of the collection + completely. A change of `[logins.*]` needs a restart of the broker: + a reload refuses it. Putting an item into the collection needs no + change of the config. + +8. **One login after one tap, for a browser that waits only a short + time.** On the client: + + ```sh + nodkey preapprove --login 11111111-1111-1111-1111-111111111111 --url https://example.com/sign-in + ``` + + It waits for your tap as long as any other request (the `timeout` + of the broker). After the tap, the next login to that item, from that + machine, for that origin, gets the login without a new tap. It works + once, and only in the 60 seconds after the tap. The rule of the item + needs `preapprove = true`. + +**Never unlock your main vault in a browser or an app that an agent can +drive**: not in agent-browser, not in a browser that an agent reaches +over the Chrome DevTools Protocol, and not in a browser profile that +such a browser uses. With the unlocked extension, the agent can open the +extension's own page in a tab and read every item +(THREAT-MODEL.md T32 and T46). Keep the separate account off agent +machines, as above. + ## 6. SSH keys and the broker's known_hosts Skip this section if you use nodkey only for secrets. The broker still diff --git a/go.mod b/go.mod index 8dfda01..28ebfbd 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/go-resty/resty/v2 v2.17.2 github.com/infisical/go-sdk v0.9.1 golang.org/x/crypto v0.58.0 + golang.org/x/net v0.60.0 ) require ( @@ -50,7 +51,6 @@ require ( go.opentelemetry.io/otel/metric v1.44.0 // indirect go.opentelemetry.io/otel/trace v1.44.0 // indirect go.opentelemetry.io/proto/otlp v1.9.0 // indirect - golang.org/x/net v0.60.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sync v0.24.0 // indirect golang.org/x/sys v0.49.0 // indirect diff --git a/internal/api/logins.go b/internal/api/logins.go new file mode 100644 index 0000000..7a89d3c --- /dev/null +++ b/internal/api/logins.go @@ -0,0 +1,288 @@ +package api + +import ( + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" +) + +// The paths of website logins (DESIGN.md section 21). Each takes POST only. +const ( + // PathLoginList lists the logins that match a page (ListLoginsRequest, + // ListLoginsAnswer). There is no tap. nodkey asks it for the browser + // plugin of #104. + PathLoginList = "/v1/logins/list" + // PathLogin asks for the username and the password of one login + // (LoginRequest, LoginAnswer). It needs a tap, a grant or a + // pre-approval. + PathLogin = "/v1/logins/login" + // PathLoginTOTP asks for the current TOTP code of a login + // (TOTPRequest, TOTPAnswer). + PathLoginTOTP = "/v1/logins/totp" +) + +// Caps of the website login requests and answers. +const ( + // MaxURL is the most bytes of a page URL (loginmatch.MaxURL). + MaxURL = 2048 + // MaxLoginText is the most bytes of an item name or a user name in an + // answer (the limit of the bw store). + MaxLoginText = 1024 + // MaxLoginEntries is the most items of a ListLoginsAnswer (the limit + // of the bw store). + MaxLoginEntries = 500 + // MaxItemID is the most bytes of an item ID. + MaxItemID = 36 + // MaxTOTPCode is the most bytes of a TOTP code. + MaxTOTPCode = 8 +) + +// ListLoginsRequest asks which logins match a page. +type ListLoginsRequest struct { + // URL is the page URL. It is claimed (THREAT-MODEL.md T43). + URL string `json:"url"` +} + +// Check checks the caps of the request. +func (r *ListLoginsRequest) Check() error { + if len(r.URL) > MaxURL { + return errTooLong + } + return nil +} + +// UnmarshalJSON decodes strictly, and checks the caps. +func (r *ListLoginsRequest) UnmarshalJSON(data []byte) error { + var v ListLoginsRequest + if err := decodeObject(data, map[string]field{"url": text(&v.URL)}); err != nil { + return err + } + if err := v.Check(); err != nil { + return err + } + *r = v + return nil +} + +// LoginEntry is one login in a ListLoginsAnswer. It holds no password and +// no TOTP seed. +type LoginEntry struct { + // Logins is the name of the [logins.*] section. + Logins string `json:"logins"` + // ID is the item ID. + ID string `json:"id"` + // Name and Username are from the vault. + Name string `json:"name"` + Username string `json:"username"` +} + +// UnmarshalJSON decodes strictly, and checks the caps. +func (e *LoginEntry) UnmarshalJSON(data []byte) error { + var v LoginEntry + err := decodeObject(data, map[string]field{ + "logins": text(&v.Logins), "id": text(&v.ID), "name": text(&v.Name), "username": text(&v.Username), + }) + if err != nil { + return err + } + if len(v.Logins) > MaxName || len(v.ID) > MaxItemID || len(v.Name) > MaxLoginText || len(v.Username) > MaxLoginText { + return errTooLong + } + *e = v + return nil +} + +// ListLoginsAnswer lists the logins that match the page. +type ListLoginsAnswer struct { + Logins []LoginEntry `json:"logins"` +} + +// MarshalJSON writes a nil list as []. +func (a ListLoginsAnswer) MarshalJSON() ([]byte, error) { + type plain ListLoginsAnswer + p := plain{Logins: orEmpty(a.Logins)} + if len(p.Logins) > MaxLoginEntries { + return nil, errTooMany + } + return json.Marshal(p) +} + +// UnmarshalJSON decodes strictly, and checks the caps. +func (a *ListLoginsAnswer) UnmarshalJSON(data []byte) error { + var v ListLoginsAnswer + if err := decodeObject(data, map[string]field{ + "logins": list(&v.Logins, MaxLoginEntries, object[LoginEntry]()), + }); err != nil { + return err + } + *a = v + return nil +} + +// LoginRequest asks for one login. +type LoginRequest struct { + // URL is the page URL. It is claimed. + URL string `json:"url"` + // Item is an item ID from the list. + Item string `json:"item"` +} + +// Check checks the caps of the request. +func (r *LoginRequest) Check() error { + if len(r.URL) > MaxURL || len(r.Item) > MaxItemID { + return errTooLong + } + return nil +} + +// UnmarshalJSON decodes strictly, and checks the caps. +func (r *LoginRequest) UnmarshalJSON(data []byte) error { + var v LoginRequest + if err := decodeObject(data, map[string]field{"url": text(&v.URL), "item": text(&v.Item)}); err != nil { + return err + } + if err := v.Check(); err != nil { + return err + } + *r = v + return nil +} + +// TOTPRequest asks for the current TOTP code of a login. +type TOTPRequest struct { + URL string `json:"url"` + Item string `json:"item"` +} + +// Check checks the caps of the request. +func (r *TOTPRequest) Check() error { return (&LoginRequest{URL: r.URL, Item: r.Item}).Check() } + +// UnmarshalJSON decodes strictly, and checks the caps. +func (r *TOTPRequest) UnmarshalJSON(data []byte) error { + var v LoginRequest + if err := v.UnmarshalJSON(data); err != nil { + return err + } + *r = TOTPRequest(v) + return nil +} + +// LoginAnswer holds the username and the password of a login. The broker +// writes it with Encode, not with encoding/json, as for SecretsAnswer. The +// password is a secret: fmt and slog never show it. +type LoginAnswer struct { + Username string `json:"username"` + Password []byte `json:"password"` +} + +// Check checks the caps of the answer. +func (a *LoginAnswer) Check() error { + if len(a.Username) > MaxLoginText || len(a.Password) > MaxValue { + return errTooLong + } + return nil +} + +// Encode writes the answer as JSON into a new buffer of exactly its size. +// The buffer holds the password in base64: the caller must clear it once +// the answer is written. +func (a *LoginAnswer) Encode() ([]byte, error) { + if err := a.Check(); err != nil { + return nil, err + } + user, err := json.Marshal(a.Username) + if err != nil { + return nil, err + } + const ( + head = `{"username":` + mid = `,"password":"` + tail = `"}` + ) + n := len(head) + len(user) + len(mid) + base64.StdEncoding.EncodedLen(len(a.Password)) + len(tail) + // The exact size, so that append never moves the bytes and leaves a + // copy behind. + b := make([]byte, 0, n) + b = append(b, head...) + b = append(b, user...) + b = append(b, mid...) + b = base64.StdEncoding.AppendEncode(b, a.Password) + return append(b, tail...), nil +} + +// UnmarshalJSON decodes strictly, and checks the caps. +func (a *LoginAnswer) UnmarshalJSON(data []byte) error { + var v LoginAnswer + err := decodeObject(data, map[string]field{"username": text(&v.Username), "password": binary(&v.Password)}) + if err != nil { + clear(v.Password) + return err + } + if err := v.Check(); err != nil { + clear(v.Password) + return err + } + *a = v + return nil +} + +// Clear overwrites the password with zeros, as best effort. +func (a *LoginAnswer) Clear() { clear(a.Password) } + +// String returns a text without the password. +func (a LoginAnswer) String() string { return "api.LoginAnswer{password hidden}" } + +// GoString returns a text without the password. +func (a LoginAnswer) GoString() string { return a.String() } + +// Format writes a text without the password, for every verb. +func (a LoginAnswer) Format(f fmt.State, _ rune) { _, _ = io.WriteString(f, a.String()) } + +// LogValue returns a text without the password, so slog never logs it. +func (a LoginAnswer) LogValue() slog.Value { return slog.StringValue(a.String()) } + +// MarshalJSON refuses: the password must not go through encoding/json, +// which leaves a copy in a buffer that nobody clears. Use Encode. +func (a LoginAnswer) MarshalJSON() ([]byte, error) { + return nil, errors.New("api: a LoginAnswer is written with Encode, not with encoding/json") +} + +// TOTPAnswer holds one TOTP code. A code is good for a short time only, +// and fmt and slog do not show it. +type TOTPAnswer struct { + Code string `json:"code"` +} + +// UnmarshalJSON decodes strictly, and checks that the code is 6 to +// MaxTOTPCode digits. +func (a *TOTPAnswer) UnmarshalJSON(data []byte) error { + var v TOTPAnswer + if err := decodeObject(data, map[string]field{"code": text(&v.Code)}); err != nil { + return err + } + if len(v.Code) < 6 || len(v.Code) > MaxTOTPCode { + return errTooLong + } + for _, c := range []byte(v.Code) { + if c < '0' || c > '9' { + return errType + } + } + *a = v + return nil +} + +// String returns a text without the code. +func (a TOTPAnswer) String() string { return "api.TOTPAnswer{code hidden}" } + +// GoString returns a text without the code. +func (a TOTPAnswer) GoString() string { return a.String() } + +// Format writes a text without the code, for every verb. +func (a TOTPAnswer) Format(f fmt.State, _ rune) { _, _ = io.WriteString(f, a.String()) } + +// LogValue returns a text without the code, so slog never logs it. +func (a TOTPAnswer) LogValue() slog.Value { return slog.StringValue(a.String()) } diff --git a/internal/api/logins_test.go b/internal/api/logins_test.go new file mode 100644 index 0000000..dadbbc7 --- /dev/null +++ b/internal/api/logins_test.go @@ -0,0 +1,137 @@ +package api + +import ( + "bytes" + "encoding/json" + "fmt" + "log/slog" + "strings" + "testing" +) + +func TestLoginRequestsAreStrict(t *testing.T) { + good := `{"url":"https://example.com/","item":"11111111-1111-1111-1111-111111111111"}` + var r LoginRequest + if err := json.Unmarshal([]byte(good), &r); err != nil || r.Item == "" { + t.Fatalf("good request: %v", err) + } + bad := []string{ + `{"url":"https://example.com/"}`, + `{"url":"https://example.com/","item":null}`, + `{"url":"https://example.com/","item":"x","other":"y"}`, + `{"URL":"https://example.com/","item":"x"}`, + `{"url":"` + strings.Repeat("a", MaxURL+1) + `","item":"x"}`, + `{"url":"u","item":"` + strings.Repeat("a", MaxItemID+1) + `"}`, + `[]`, + } + for _, b := range bad { + if err := json.Unmarshal([]byte(b), &LoginRequest{}); err == nil { + t.Errorf("accepted %.60s", b) + } + if err := json.Unmarshal([]byte(b), &TOTPRequest{}); err == nil { + t.Errorf("TOTPRequest accepted %.60s", b) + } + } + for _, b := range []string{`{}`, `{"url":1}`, `{"url":null}`, `{"url":"` + strings.Repeat("a", MaxURL+1) + `"}`} { + if err := json.Unmarshal([]byte(b), &ListLoginsRequest{}); err == nil { + t.Errorf("ListLoginsRequest accepted %.60s", b) + } + } +} + +func TestListLoginsAnswer(t *testing.T) { + data, err := json.Marshal(ListLoginsAnswer{}) + if err != nil || string(data) != `{"logins":[]}` { + t.Fatalf("empty answer %s, %v", data, err) + } + a := ListLoginsAnswer{Logins: []LoginEntry{{Logins: "web", ID: "i", Name: "n", Username: "u"}}} + data, _ = json.Marshal(a) + got, err := ReadAnswer[ListLoginsAnswer](bytes.NewReader(data)) + if err != nil || len(got.Logins) != 1 || got.Logins[0] != a.Logins[0] { + t.Fatalf("round trip: %v %+v", err, got) + } + for _, b := range []string{ + `{"logins":[{"logins":"w","id":"i","name":"n","username":"u","password":"p"}]}`, + `{"logins":[{"logins":"w","id":"i","name":"n"}]}`, + `{"logins":null}`, + } { + if _, err := ReadAnswer[ListLoginsAnswer](strings.NewReader(b)); err == nil { + t.Errorf("accepted %s", b) + } + } +} + +func TestLoginAnswerEncodeAndHide(t *testing.T) { + pw := []byte("made-up-password-" + t.Name()) + a := LoginAnswer{Username: "alice@example.com \"q\"", Password: bytes.Clone(pw)} + body, err := a.Encode() + if err != nil { + t.Fatal(err) + } + if cap(body) != len(body) { + t.Errorf("the buffer is not exact: len %d cap %d", len(body), cap(body)) + } + got, err := ReadAnswer[LoginAnswer](bytes.NewReader(body)) + if err != nil || got.Username != a.Username || !bytes.Equal(got.Password, pw) { + t.Fatalf("round trip: %v", err) + } + got.Clear() + if !bytes.Equal(got.Password, make([]byte, len(pw))) { + t.Error("Clear left the password") + } + for _, s := range []string{fmt.Sprint(a), fmt.Sprintf("%v %+v %#v %s", a, a, a, a), slog.Any("a", a).Value.String()} { + if strings.Contains(s, string(pw)) { + t.Errorf("the password shows: %s", s) + } + } + if _, err := json.Marshal(a); err == nil { + t.Error("json.Marshal wrote the answer") + } + for _, b := range []string{ + `{"username":"u"}`, `{"username":"u","password":null}`, `{"username":"u","password":"!!"}`, + `{"username":"u","password":"AA==","x":1}`, + `{"username":"` + strings.Repeat("a", MaxLoginText+1) + `","password":"AA=="}`, + } { + if _, err := ReadAnswer[LoginAnswer](strings.NewReader(b)); err == nil { + t.Errorf("accepted %.60s", b) + } + } + big := LoginAnswer{Password: make([]byte, MaxValue+1)} + if _, err := big.Encode(); err == nil { + t.Error("Encode took a password over the cap") + } +} + +func TestTOTPAnswer(t *testing.T) { + a, err := ReadAnswer[TOTPAnswer](strings.NewReader(`{"code":"287082"}`)) + if err != nil || a.Code != "287082" { + t.Fatalf("good answer: %v", err) + } + if s := fmt.Sprintf("%v %+v %#v", *a, *a, *a); strings.Contains(s, "287082") { + t.Errorf("the code shows: %s", s) + } + for _, b := range []string{`{"code":"12345"}`, `{"code":"123456789"}`, `{"code":"12a456"}`, `{"code":null}`, `{}`, `{"code":"123456","x":1}`} { + if _, err := ReadAnswer[TOTPAnswer](strings.NewReader(b)); err == nil { + t.Errorf("accepted %s", b) + } + } +} + +func TestPreapproveRequestLoginFields(t *testing.T) { + r := PreapproveRequest{Login: "11111111-1111-1111-1111-111111111111", URL: "https://example.com/", Uses: 1} + data, err := json.Marshal(r) + if err != nil { + t.Fatal(err) + } + var back PreapproveRequest + if err := json.Unmarshal(data, &back); err != nil || back.Login != r.Login || back.URL != r.URL { + t.Fatalf("round trip: %v %s", err, data) + } + plain, _ := json.Marshal(PreapproveRequest{Uses: 1}) + if strings.Contains(string(plain), "login") || strings.Contains(string(plain), "url") || strings.Contains(string(plain), "windows") { + t.Errorf("a request with no login writes its fields: %s", plain) + } + if err := json.Unmarshal(plain, &PreapproveRequest{}); err != nil { + t.Errorf("a request with no login field: %v", err) + } +} diff --git a/internal/api/types.go b/internal/api/types.go index 6e180e4..1cb1d92 100644 --- a/internal/api/types.go +++ b/internal/api/types.go @@ -558,6 +558,12 @@ type PreapproveRequest struct { // section 8): 1 to MaxWindows windows. Nil for a scheduled grant; then // MarshalJSON does not write the field. Windows []Window `json:"windows"` + // Login and URL make the request one for a login pre-approval (DESIGN.md + // section 21): Login is the item ID, URL the page URL (claimed). Then + // Uses is 1, and the other fields are empty. Both are "" for the + // other kinds; then MarshalJSON does not write them. + Login string `json:"login"` + URL string `json:"url"` } // Check checks the caps of the request. @@ -570,6 +576,9 @@ func (r *PreapproveRequest) Check() error { return err } } + if len(r.Login) > MaxItemID || len(r.URL) > MaxURL { + return errTooLong + } if len(r.Key) > MaxName || len(r.User) > MaxName || len(r.From) > MaxTime || len(r.Until) > MaxTime { return errTooLong } @@ -587,14 +596,21 @@ func (r PreapproveRequest) MarshalJSON() ([]byte, error) { type plain PreapproveRequest p := plain(r) p.Secrets, p.Hosts = orEmpty(p.Secrets), orEmpty(p.Hosts) - if r.Windows == nil { - // The shallower field wins over the one in plain. - return json.Marshal(struct { - plain - Windows *struct{} `json:"windows,omitempty"` - }{plain: p}) + // The shallower fields win over the ones in plain. A nil pointer is + // not written. + out := struct { + plain + Windows *[]Window `json:"windows,omitempty"` + Login *string `json:"login,omitempty"` + URL *string `json:"url,omitempty"` + }{plain: p} + if r.Windows != nil { + out.Windows = &r.Windows } - return json.Marshal(p) + if r.Login != "" || r.URL != "" { + out.Login, out.URL = &r.Login, &r.URL + } + return json.Marshal(out) } // UnmarshalJSON decodes strictly, and checks the caps. @@ -610,7 +626,9 @@ func (r *PreapproveRequest) UnmarshalJSON(data []byte) error { "uses": integer(&v.Uses), "reason": text(&v.Reason), "windows": list(&v.Windows, MaxWindows, object[Window]()), - }, map[string]bool{"windows": true}) + "login": text(&v.Login), + "url": text(&v.URL), + }, map[string]bool{"windows": true, "login": true, "url": true}) if err != nil { return err } diff --git a/internal/approval/approver.go b/internal/approval/approver.go index 6b0c57d..9a8786f 100644 --- a/internal/approval/approver.go +++ b/internal/approval/approver.go @@ -154,6 +154,10 @@ type Prompt struct { // (audit.ViaScheduled). It is empty in a notice of a "never ask" use. Via audit.Via + // Login is set for a KindWebLogin request and for a pre-approval of + // one login. + Login *LoginPrompt + // Claim is the claimed part. Claim Claim @@ -174,6 +178,18 @@ type Prompt struct { WindowMinutes int } +// LoginPrompt is the part of a Prompt about a website login. Name and +// Username come from the vault: they are verified, but the core has +// cleaned them, because the vault may hold text that fakes the look of a +// message. Origin is claimed by the client (THREAT-MODEL.md T43). +type LoginPrompt struct { + Name, Username, Origin string + // For is how long after the tap a pre-approval allows its one login: + // LoginPreapproveTime. It is zero for a login request, and the + // message of a pre-approval shows no time limit for the tap. + For time.Duration +} + // Ending says how a request with a message ended, so the approver can // update the message (DESIGN.md section 7). type Ending struct { diff --git a/internal/approval/check.go b/internal/approval/check.go index 242e59a..30720be 100644 --- a/internal/approval/check.go +++ b/internal/approval/check.go @@ -43,13 +43,16 @@ func (c *Core) check(r *Request, p *pending) bool { ok = false } switch r.Kind { - case audit.KindSecrets, audit.KindSSHLogin, audit.KindSSHGrant, audit.KindPreapprove, audit.KindStanding: + case audit.KindSecrets, audit.KindSSHLogin, audit.KindSSHGrant, audit.KindPreapprove, audit.KindStanding, audit.KindWebLogin: p.kind = r.Kind p.subject.Kind = r.Kind default: return false } ok = c.checkClaim(r.Claim, p) && ok + if r.Login != nil && r.Kind != audit.KindWebLogin && r.Kind != audit.KindPreapprove { + ok = false // a login belongs to a website login only + } switch r.Kind { case audit.KindSecrets: ok = c.checkSecrets(r, p) && ok @@ -57,8 +60,14 @@ func (c *Core) check(r *Request, p *pending) bool { ok = c.checkLogin(r, p) && ok case audit.KindSSHGrant: ok = c.checkGrant(r, p) && ok + case audit.KindWebLogin: + ok = c.checkWebLogin(r, p) && ok case audit.KindPreapprove: - ok = c.checkPreapprove(r, p) && ok + if r.Login != nil { + ok = c.checkLoginPreapprove(r, p) && ok + } else { + ok = c.checkPreapprove(r, p) && ok + } case audit.KindStanding: ok = c.checkStanding(r, p) && ok } @@ -224,7 +233,7 @@ func (c *Core) addGrantHosts(names []string, k config.Key, keyOK bool, p *pendin // limits of [preapprove]; a limit that is not set (0) allows nothing. func (c *Core) checkPreapprove(r *Request, p *pending) bool { lim := p.cfg.Preapprove - ok := r.HostKey == nil && r.For == 0 + ok := r.Login == nil && r.HostKey == nil && r.For == 0 allowed := func(rule config.Rule, clients []string) bool { return rule.Preapprove && rule.Ask != config.AskNever && validRule(rule, clients) } diff --git a/internal/approval/decide.go b/internal/approval/decide.go index aa1ab8b..6ee5bea 100644 --- a/internal/approval/decide.go +++ b/internal/approval/decide.go @@ -49,6 +49,8 @@ type pending struct { grantHostKeys []string // KindSSHGrant: the host keys of the hosts, in SSH wire form grantEnds moment // KindSSHGrant: when its grants end plan *grant // KindPreapprove: the grant that an approval starts + origin string // KindWebLogin, and a login pre-approval: the claimed https origin + login *LoginPrompt start, deadline moment once bool // the message has "Approve once" @@ -119,7 +121,14 @@ func (p *pending) prompt(now moment) Prompt { if p.kind == audit.KindSSHGrant { pr.GrantEnds = p.grantEnds.wall } - if p.kind.IsPreapprove() { + if p.login != nil { + l := *p.login + pr.Login = &l + } + if p.kind.IsPreapprove() && p.login != nil { + // A login pre-approval has no span: its end comes from the tap. + pr.Uses = p.plan.uses + } else if p.kind.IsPreapprove() { loc := now.wall.Location() pr.Uses, pr.From, pr.Until = p.plan.uses, p.plan.start.In(loc), p.plan.end.wall.In(loc) if p.kind == audit.KindStanding { @@ -168,9 +177,12 @@ func (c *Core) Decide(ctx context.Context, r *Request) *Result { } if p.kind.IsPreapprove() { // Its grant ends at a fixed time, as an SSH grant's do: after it, - // an approval would grant nothing. - end := p.plan.end.wall - p.deadline = earlier(p.deadline, moment{mono: p.start.mono.Add(end.Sub(p.start.wall)), wall: end}) + // an approval would grant nothing. A login pre-approval has no + // fixed end: its time starts at the tap. + if p.login == nil { + end := p.plan.end.wall + p.deadline = earlier(p.deadline, moment{mono: p.start.mono.Add(end.Sub(p.start.wall)), wall: end}) + } if err := c.makeGrantID(p); err != nil { res := c.denied(p, audit.CauseError) res.Err = err @@ -676,6 +688,9 @@ func (c *Core) approvePlan(p *pending, res *Result) { res.plan = &g res.GrantID = g.id loc := c.clock.Wall().Location() + if g.loginOrigin != "" { + return // the end comes at the tap (startScheduled) + } res.GrantFrom, res.GrantUntil = g.start.In(loc), g.end.wall.In(loc) } diff --git a/internal/approval/grants.go b/internal/approval/grants.go index dba4080..b4f123e 100644 --- a/internal/approval/grants.go +++ b/internal/approval/grants.go @@ -46,6 +46,11 @@ type grant struct { // origin is the subject of the request that made a scheduled grant, // for its audit entries. origin audit.Subject + // loginOrigin is the https origin of a pre-approval of one login + // (DESIGN.md section 21). The grant covers only a request for the + // same origin. It is "" for every other grant. The end of such a grant + // is set at the tap (LoginPreapproveTime), not when it is asked for. + loginOrigin string // reqID is the ID of the request that made a scheduled grant. The // Revoke button carries it. reqID string @@ -666,7 +671,7 @@ func (c *Core) standingCount(client string) int { // are not mixed with each other or with other rules (DESIGN.md section 8). // Of several, the one that ends first. Core.mu must be held. func (c *Core) findScheduled(p *pending, now moment) *grant { - if p.kind != audit.KindSecrets && p.kind != audit.KindSSHLogin || len(p.items) == 0 { + if p.kind != audit.KindSecrets && p.kind != audit.KindSSHLogin && p.kind != audit.KindWebLogin || len(p.items) == 0 { return nil } var best *grant @@ -674,6 +679,11 @@ func (c *Core) findScheduled(p *pending, now moment) *grant { if !g.scheduled() || g.uses < 1 || !g.live(now) { continue } + // A login pre-approval covers the same origin only, and a login + // request is covered by nothing else. + if g.loginOrigin != p.origin || (p.kind == audit.KindWebLogin) != (g.loginOrigin != "") { + continue + } all := true for _, it := range p.items { if !g.covers(p.client, it.ref, p.hostKey, p.user) { @@ -711,6 +721,12 @@ func (c *Core) settle(p *pending, res *Result) { // grants were dropped already). Core.mu must be held. func (c *Core) startScheduled(r *Result, now moment) { g := r.plan + if g.loginOrigin != "" { + // The time of a login pre-approval starts at the tap, not when + // it was asked for: the person may take long to tap. + g.end.wall = now.wall.Add(LoginPreapproveTime) + r.GrantFrom, r.GrantUntil = now.wall, g.end.wall + } // The end is an absolute time. Its monotonic reading is counted from // now, so a wall clock that is set back later cannot make it later. g.end.mono = now.mono.Add(g.end.wall.Sub(now.wall)) diff --git a/internal/approval/login.go b/internal/approval/login.go new file mode 100644 index 0000000..14086f6 --- /dev/null +++ b/internal/approval/login.go @@ -0,0 +1,154 @@ +package approval + +import ( + "reflect" + "regexp" + "slices" + "strings" + "time" + + "github.com/code6x/nodkey/internal/claim" + "github.com/code6x/nodkey/internal/config" +) + +// LoginPreapproveTime is how long a pre-approval of one login lasts after +// the tap (DESIGN.md section 21). The time starts at the tap, not when +// the request was made: the person may take long to tap. +const LoginPreapproveTime = 60 * time.Second + +// maxLoginText is the most runes of an item name or a user name in a +// message. A longer text is cut. +const maxLoginText = 128 + +// noLoginName stands for an item name that is empty after cleaning. +const noLoginName = "(no name)" + +var ( + // loginOriginPattern is the form of an origin that the broker made + // from a checked page URL: https, a host name or an IP address, and + // perhaps a port. It is also the form that the audit log takes. + loginOriginPattern = regexp.MustCompile(`^https://([a-z0-9][a-z0-9.-]{0,252}|\[[0-9a-f:]{2,45}\])(:[0-9]{1,5})?$`) + // loginItemPattern is a Bitwarden item ID in lower case. + loginItemPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) +) + +// loginRef returns the ref of the login item with the ID item. +func loginRef(item string) ref { return ref{login: true, name: strings.ToLower(item)} } + +// checkLoginScope checks the login of r against the config of p, and +// fills what both kinds of login request share: the item, the subject, +// the origin and the text of the message. It does not look at the kind. +func (c *Core) checkLoginScope(r *Request, p *pending) (rule config.Rule, ok bool) { + l := r.Login + if l == nil || p.client == "" { + return config.Rule{}, false + } + if !slices.Contains(l.Clients, p.client) || !validRule(l.Rule, l.Clients) || l.Rule.Ask == config.AskNever { + return config.Rule{}, false + } + if !loginOriginPattern.MatchString(l.Origin) || !loginItemPattern.MatchString(l.Item) { + return config.Rule{}, false + } + // The config of the checks must still have the section, and give the + // rule that the broker used: else a reload came in between. + sec, found := p.cfg.Logins[l.Section] + if !found { + return config.Rule{}, false + } + clients, cfgRule, known := sec.RuleFor(l.Item) + if !known || !slices.Equal(clients, l.Clients) || !sameLoginRule(cfgRule, l.Rule) { + return config.Rule{}, false + } + p.items = []item{{ref: loginRef(l.Item), rule: l.Rule}} + p.origin = l.Origin + p.subject.Logins, p.subject.Item, p.subject.Origin = l.Section, l.Item, l.Origin + p.login = &LoginPrompt{Name: loginText(l.Name, noLoginName), Username: loginText(l.Username, ""), Origin: l.Origin} + return l.Rule, true +} + +// sameLoginRule reports whether got is the configured rule cfg, or cfg +// made stricter for an item with a re-prompt: the broker then asks every +// time, which is "always". +func sameLoginRule(cfg, got config.Rule) bool { + if got.Ask == config.AskAlways && cfg.Ask != config.AskAlways { + cfg.Ask, cfg.Window = config.AskAlways, got.Window + } + return reflect.DeepEqual(cfg, got) +} + +// loginText cleans text from the vault for a message: one line, no +// control or direction characters, at most maxLoginText runes. +func loginText(s, empty string) string { + if t := claim.Line(s, maxLoginText); t != "" { + return t + } + return empty +} + +// checkWebLogin checks a KindWebLogin request (DESIGN.md section 21). +func (c *Core) checkWebLogin(r *Request, p *pending) bool { + ok := r.Key == "" && r.HostKey == nil && r.RemoteUser == "" && len(r.Hosts) == 0 && len(r.Secrets) == 0 && + r.For == 0 && r.Uses == 0 && r.NotBefore.IsZero() && r.NotAfter.IsZero() && len(r.Windows) == 0 + if _, good := c.checkLoginScope(r, p); !good || !ok { + p.items = nil + return false + } + p.once = true + p.windowMinutes = windowMinutes(p.items) + return true +} + +// checkLoginPreapprove checks a KindPreapprove request for one login: one +// use, no times, and a rule with preapprove = true. +func (c *Core) checkLoginPreapprove(r *Request, p *pending) bool { + ok := r.Key == "" && r.HostKey == nil && r.RemoteUser == "" && len(r.Hosts) == 0 && len(r.Secrets) == 0 && + r.For == 0 && r.Uses == 1 && r.NotBefore.IsZero() && r.NotAfter.IsZero() + rule, good := c.checkLoginScope(r, p) + if !good || !ok || !rule.Preapprove || rule.Ask == config.AskNever { + p.items, p.login = nil, nil + return false + } + p.login.For = LoginPreapproveTime + p.once = true // the one "Approve" button + p.subject.Uses = 1 + p.plan = &grant{ + kind: kindScheduled, client: p.client, refs: []ref{p.items[0].ref}, uses: 1, + loginOrigin: r.Login.Origin, + } + return true +} + +// LoginGranted reports whether a live "Approve N min" grant covers the +// login item for client now (DESIGN.md section 21). The broker uses it +// for TOTP codes, after it has checked the rule of the item. A +// pre-approval does not count: it covers one login. +func (c *Core) LoginGranted(client, item string) bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.granted(grantKey{client: client, ref: loginRef(item)}, c.now()) +} + +// keepsLogin reports whether the login grant g of the config old is +// allowed in the same way by the config next: the same sections, each +// with the same store and collection, and for the item the same clients +// and the same rule. +func keepsLogin(old, next *config.Broker, item, client string) bool { + if len(old.Logins) != len(next.Logins) { + return false + } + for name, o := range old.Logins { + n, ok := next.Logins[name] + if !ok || o.Store != n.Store || o.Collection != n.Collection { + return false + } + oc, or, ok1 := o.RuleFor(item) + nc, nr, ok2 := n.RuleFor(item) + if !ok1 || !ok2 || !slices.Equal(oc, nc) || !reflect.DeepEqual(or, nr) { + return false + } + if slices.Contains(oc, client) != slices.Contains(nc, client) { + return false + } + } + return true +} diff --git a/internal/approval/login_test.go b/internal/approval/login_test.go new file mode 100644 index 0000000..c809e70 --- /dev/null +++ b/internal/approval/login_test.go @@ -0,0 +1,414 @@ +package approval_test + +// Tests of website logins (DESIGN.md section 21) in the approval core. + +import ( + "maps" + "strings" + "testing" + "testing/synctest" + "time" + + "github.com/code6x/nodkey/internal/approval" + "github.com/code6x/nodkey/internal/audit" + "github.com/code6x/nodkey/internal/config" +) + +const ( + itemA = "11111111-1111-1111-1111-111111111111" + itemB = "22222222-2222-2222-2222-222222222222" + loginsColl = "00000000-0000-0000-0000-000000000000" + pageOrigin = "https://example.com" +) + +// loginEnv starts a core with one [logins.web] section: laptop and build +// may ask, with a window rule that allows preapprove. +func loginEnv(t *testing.T, edit ...func(*config.Broker)) *env { + t.Helper() + return newEnv(t, func(cfg *config.Broker) { + cfg.Preapprove = config.DefaultPreapprove() + cfg.Logins = map[string]config.Logins{"web": { + Name: "web", Store: "vault", Collection: loginsColl, Clients: []string{"laptop", "build"}, + Rule: config.Rule{Ask: config.AskWindow, Window: 15 * time.Minute, Preapprove: true}, + }} + for _, f := range edit { + f(cfg) + } + }) +} + +// webLogin asks for a login of the item for client at the page. +func webLogin(env *env, client, item string) *approval.Request { + clients, rule, _ := env.cfg.Logins["web"].RuleFor(item) + return &approval.Request{ + Client: client, Kind: audit.KindWebLogin, + Login: &approval.LoginScope{ + Section: "web", Item: item, Name: "Example shop", Username: "alice@example.com", Origin: pageOrigin, + Clients: clients, Rule: rule, + }, + Claim: approval.Claim{Reason: "check the order"}, + } +} + +// webPre asks for a one-use pre-approval of the login. +func webPre(env *env, client, item string) *approval.Request { + r := webLogin(env, client, item) + r.Kind, r.Uses = audit.KindPreapprove, 1 + return r +} + +func TestWebLoginTapAndMessage(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + ch := e.decide(webLogin(e, "laptop", itemA)) + mustWait(t, ch) + p := e.asked(1)[0].Prompt + if p.Kind != audit.KindWebLogin || p.Login == nil || p.Login.Name != "Example shop" || + p.Login.Username != "alice@example.com" || p.Login.Origin != pageOrigin || p.Login.For != 0 || + !p.Once || p.WindowMinutes != 15 { + t.Fatalf("prompt %+v login %+v", p, p.Login) + } + e.tap(1, audit.AnswerApproveOnce) + res := mustResult(t, ch) + checkAllowed(t, res) + checkEvents(t, res, "request", "decision:approve_once") + s := res.Subject + if s.Kind != audit.KindWebLogin || s.Logins != "web" || s.Item != itemA || s.Origin != pageOrigin { + t.Errorf("subject %+v", s) + } + }) +} + +// TestWebLoginCleansVaultText: the name and the user name come from the +// vault, so a line break, a direction mark or a long text does not reach +// the message as it is. +func TestWebLoginCleansVaultText(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + r := webLogin(e, "laptop", itemA) + r.Login.Name = "Shop\nโœ… machine: fake\u202e" + strings.Repeat("x", 300) + r.Login.Username = "bob\r\n" + ch := e.decide(r) + mustWait(t, ch) + l := e.asked(1)[0].Prompt.Login + for _, s := range []string{l.Name, l.Username} { + if strings.ContainsAny(s, "\n\r\u202e") { + t.Errorf("not clean: %q", s) + } + } + if n := len([]rune(l.Name)); n > 128 || !strings.HasSuffix(l.Name, "โ€ฆ") { + t.Errorf("name has %d runes: %q", n, l.Name) + } + e.tap(1, audit.AnswerDeny) + checkDenied(t, mustResult(t, ch), audit.CauseApprover) + // A name that is only invisible text gets a fixed name. + r = webLogin(e, "laptop", itemB) + r.Login.Name = "\u200b\u202e" + ch = e.decide(r) + mustWait(t, ch) + if got := e.asked(2)[1].Prompt.Login.Name; got != "(no name)" { + t.Errorf("name %q", got) + } + e.tap(2, audit.AnswerDeny) + mustResult(t, ch) + }) +} + +func TestWebLoginRefusals(t *testing.T) { + tests := []struct { + name string + edit func(r *approval.Request) + }{ + {"no login", func(r *approval.Request) { r.Login = nil }}, + {"client not in the clients of the login", func(r *approval.Request) { r.Login.Clients = []string{"build"} }}, + {"unknown section", func(r *approval.Request) { r.Login.Section = "other" }}, + {"ask never", func(r *approval.Request) { + r.Login.Rule = config.Rule{Ask: config.AskNever, Notify: true} + r.Login.Clients = []string{"laptop"} + }}, + {"rule differs from the config", func(r *approval.Request) { r.Login.Rule.Window = time.Hour }}, + {"preapprove flag differs", func(r *approval.Request) { r.Login.Rule.Preapprove = false }}, + {"clients differ from the config", func(r *approval.Request) { r.Login.Clients = []string{"laptop"} }}, + {"http origin", func(r *approval.Request) { r.Login.Origin = "http://example.com" }}, + {"origin with a path", func(r *approval.Request) { r.Login.Origin = "https://example.com/x" }}, + {"origin with a user name", func(r *approval.Request) { r.Login.Origin = "https://u@example.com" }}, + {"item in capitals", func(r *approval.Request) { r.Login.Item = "AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA" }}, + {"item that is not a UUID", func(r *approval.Request) { r.Login.Item = "x" }}, + {"stray secrets", func(r *approval.Request) { r.Secrets = []string{"github-token"} }}, + {"stray key", func(r *approval.Request) { r.Key = "deploy" }}, + {"stray remote user", func(r *approval.Request) { r.RemoteUser = "root" }}, + {"stray hosts", func(r *approval.Request) { r.Hosts = []string{"web-1"} }}, + {"stray for", func(r *approval.Request) { r.For = time.Minute }}, + {"stray uses", func(r *approval.Request) { r.Uses = 1 }}, + {"stray times", func(r *approval.Request) { r.NotAfter = noon.Add(time.Hour) }}, + {"login in a secrets request", func(r *approval.Request) { r.Kind = audit.KindSecrets; r.Secrets = []string{"github-token"} }}, + {"login in an SSH login", func(r *approval.Request) { r.Kind = audit.KindSSHLogin }}, + {"login in a standing request", func(r *approval.Request) { r.Kind = audit.KindStanding }}, + {"unknown client", func(r *approval.Request) { r.Client = "nobody" }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + r := webLogin(e, "laptop", itemA) + tt.edit(r) + e.refuses(r, audit.CauseNotAllowed) + }) + }) + } + t.Run("rule of the item in the config is stricter than the request", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t, func(cfg *config.Broker) { + l := cfg.Logins["web"] + l.Items = map[string]config.LoginItemRule{itemA: {ID: itemA, Clients: []string{"build"}, Rule: config.Rule{Ask: config.AskAlways}}} + cfg.Logins["web"] = l + }) + defer e.stop() + r := webLogin(e, "laptop", itemA) + r.Login.Clients = []string{"laptop", "build"} + r.Login.Rule = config.Rule{Ask: config.AskWindow, Window: 15 * time.Minute, Preapprove: true} + e.refuses(r, audit.CauseNotAllowed) + // The rule that the config gives for the item is the one that counts. + r = webLogin(e, "build", itemA) + ch := e.decide(r) + mustWait(t, ch) + if p := e.asked(1)[0].Prompt; p.WindowMinutes != 0 { + t.Errorf("prompt %+v: an always rule has no window button", p) + } + e.tap(1, audit.AnswerDeny) + mustResult(t, ch) + }) + }) + t.Run("reprompt makes the rule always", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + r := webLogin(e, "laptop", itemA) + r.Login.Rule.Ask = config.AskAlways + ch := e.decide(r) + mustWait(t, ch) + if p := e.asked(1)[0].Prompt; p.WindowMinutes != 0 || !p.Once { + t.Errorf("prompt %+v", p) + } + e.tap(1, audit.AnswerApproveOnce) + checkAllowed(t, mustResult(t, ch)) + }) + }) +} + +// TestWebLoginWindowGrant: a window grant covers the same client and item +// again, and no other item and no other client. +func TestWebLoginWindowGrant(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + if e.core.LoginGranted("laptop", itemA) { + t.Fatal("granted before a tap") + } + ch := e.decide(webLogin(e, "laptop", itemA)) + mustWait(t, ch) + e.asked(1) + e.tap(1, audit.AnswerApproveWindow) + res := mustResult(t, ch) + checkAllowed(t, res) + res.StartGrants() + if !e.core.LoginGranted("laptop", itemA) || !e.core.LoginGranted("laptop", strings.ToUpper(itemA)) { + t.Error("the grant does not cover the item") + } + if e.core.LoginGranted("laptop", itemB) || e.core.LoginGranted("build", itemA) { + t.Error("the grant covers another item or client") + } + again := e.now(webLogin(e, "laptop", itemA)) + checkAllowed(t, again) + checkEvents(t, again, "request", "grant_used:grant") + e.needsMessageLogin(webLogin(e, "laptop", itemB), 2) + e.needsMessageLogin(webLogin(e, "build", itemA), 3) + // A window grant for a secret does not cover a login and back. + e.clock.Advance(15*time.Minute - time.Nanosecond) + if !e.core.LoginGranted("laptop", itemA) { + t.Error("the grant ended early") + } + e.clock.Advance(time.Nanosecond) + if e.core.LoginGranted("laptop", itemA) { + t.Error("the grant did not end") + } + }) +} + +func (e *env) needsMessageLogin(r *approval.Request, n int) { + e.t.Helper() + e.needsMessage(r, n) +} + +func TestLoginPreapprove(t *testing.T) { + t.Run("message and one use", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + res := e.grant(webPre(e, "laptop", itemA), 1) + p := e.fake.Asked()[0].Prompt + if p.Kind != audit.KindPreapprove || p.Login == nil || p.Login.For != approval.LoginPreapproveTime || p.Uses != 1 || + !p.Once || !p.From.IsZero() || !p.Until.IsZero() { + t.Errorf("prompt %+v login %+v", p, p.Login) + } + checkEvents(t, res, "request", "decision:approve_once") + if res.Subject.Uses != 1 || res.Subject.Origin != pageOrigin || res.Subject.NotBefore != "" { + t.Errorf("subject %+v", res.Subject) + } + if !res.GrantUntil.Equal(noon.Add(approval.LoginPreapproveTime)) { + t.Errorf("grant until %v", res.GrantUntil) + } + use := e.uses(webLogin(e, "laptop", itemA), res.GrantID) + if !strings.Contains(strings.Join(eventNames(use), " "), "GrantEnded") { + t.Errorf("events %v: the one use must end the grant", eventNames(use)) + } + e.needsMessage(webLogin(e, "laptop", itemA), 2) // used up + }) + }) + t.Run("same client item and origin only", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + g := e.grant(webPre(e, "laptop", itemA), 1) + other := webLogin(e, "laptop", itemA) + other.Login.Origin = "https://other.example.com" + e.needsMessage(other, 2) + e.needsMessage(webLogin(e, "build", itemA), 3) + e.needsMessage(webLogin(e, "laptop", itemB), 4) + // Not a secret, not by a login of a window. + e.needsMessage(secretsReq("laptop", "github-token"), 5) + e.uses(webLogin(e, "laptop", itemA), g.GrantID) + }) + }) + t.Run("ends 60 s after the tap", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + g := e.grant(webPre(e, "laptop", itemA), 1) + e.clock.Advance(approval.LoginPreapproveTime - time.Nanosecond) + e.uses(webLogin(e, "laptop", itemA), g.GrantID) + }) + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + e.grant(webPre(e, "laptop", itemA), 1) + e.clock.Advance(approval.LoginPreapproveTime) + e.needsMessage(webLogin(e, "laptop", itemA), 2) + }) + }) + t.Run("a slow tap still gives 60 s", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + ch := e.decide(webPre(e, "laptop", itemA)) + mustWait(t, ch) + e.asked(1) + e.clock.Advance(100 * time.Second) // longer than the pre-approval itself + e.tap(1, audit.AnswerApproveOnce) + res := mustResult(t, ch) + checkAllowed(t, res) + res.StartGrants() + if !res.GrantStarted() { + t.Fatal("the grant did not start") + } + synctest.Wait() + e.clock.Advance(30 * time.Second) + e.uses(webLogin(e, "laptop", itemA), res.GrantID) + }) + }) + t.Run("works with ask always", func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t, func(cfg *config.Broker) { + l := cfg.Logins["web"] + l.Rule = config.Rule{Ask: config.AskAlways, Preapprove: true} + cfg.Logins["web"] = l + }) + defer e.stop() + g := e.grant(webPre(e, "laptop", itemA), 1) + e.uses(webLogin(e, "laptop", itemA), g.GrantID) + }) + }) + t.Run("refusals", func(t *testing.T) { + tests := []struct { + name string + edit func(cfg *config.Broker, r *approval.Request) + }{ + {"preapprove is false", func(cfg *config.Broker, r *approval.Request) { + l := cfg.Logins["web"] + l.Rule.Preapprove = false + cfg.Logins["web"] = l + r.Login.Rule.Preapprove = false + }}, + {"two uses", func(_ *config.Broker, r *approval.Request) { r.Uses = 2 }}, + {"no uses", func(_ *config.Broker, r *approval.Request) { r.Uses = 0 }}, + {"not before", func(_ *config.Broker, r *approval.Request) { r.NotBefore = noon }}, + {"not after", func(_ *config.Broker, r *approval.Request) { r.NotAfter = noon.Add(time.Hour) }}, + {"secrets", func(_ *config.Broker, r *approval.Request) { r.Secrets = []string{"github-token"} }}, + {"key", func(_ *config.Broker, r *approval.Request) { r.Key = "deploy" }}, + {"ask never", func(_ *config.Broker, r *approval.Request) { + r.Login.Rule = config.Rule{Ask: config.AskNever, Preapprove: true} + r.Login.Clients = []string{"laptop"} + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + cfgEdit := func(cfg *config.Broker) {} + var r *approval.Request + e := loginEnv(t, func(cfg *config.Broker) { cfgEdit(cfg) }) + defer e.stop() + r = webPre(e, "laptop", itemA) + tt.edit(e.cfg, r) + e.refuses(r, audit.CauseNotAllowed) + }) + }) + } + }) +} + +// TestLoginReload: a login grant stays when the new config gives the same +// clients and rule for the item, and ends when it does not. +func TestLoginReload(t *testing.T) { + cloneLogins := func(cfg *config.Broker) *config.Broker { + next := copyConfig(cfg) + next.Logins = maps.Clone(cfg.Logins) + return next + } + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + g := e.grant(webPre(e, "laptop", itemA), 1) + same := cloneLogins(e.cfg) + if n := e.core.Reload(same, sameKeys); n != 0 { + t.Fatalf("a reload with the same logins ended %d grants", n) + } + e.uses(webLogin(e, "laptop", itemA), g.GrantID) + }) + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + e.grant(webPre(e, "laptop", itemA), 1) + next := cloneLogins(e.cfg) + l := next.Logins["web"] + l.Rule.Window = time.Hour + next.Logins["web"] = l + if n := e.core.Reload(next, sameKeys); n != 1 { + t.Fatalf("a reload with another rule ended %d grants, want 1", n) + } + }) + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + e.grant(webPre(e, "laptop", itemA), 1) + next := cloneLogins(e.cfg) + l := next.Logins["web"] + l.Items = map[string]config.LoginItemRule{itemA: {ID: itemA, Clients: []string{"build"}, Rule: l.Rule}} + next.Logins["web"] = l + if n := e.core.Reload(next, sameKeys); n != 1 { + t.Fatalf("a reload that took the client from the item ended %d grants, want 1", n) + } + }) +} diff --git a/internal/approval/reload.go b/internal/approval/reload.go index 11ad55f..9782131 100644 --- a/internal/approval/reload.go +++ b/internal/approval/reload.go @@ -68,6 +68,12 @@ func keeps(old, next *config.Broker, sameKey func(string) bool, g *grant) bool { return false } for _, r := range g.refs { + if r.login { + if !keepsLogin(old, next, r.name, g.client) { + return false + } + continue + } if !r.key { if !old.SameSecret(next, r.name, g.client) { return false diff --git a/internal/approval/request.go b/internal/approval/request.go index 89a14b0..6e4aaa0 100644 --- a/internal/approval/request.go +++ b/internal/approval/request.go @@ -53,6 +53,10 @@ type Request struct { Windows []WindowSpec TokenHash [32]byte + // Login is the website login of a KindWebLogin request, and of a + // KindPreapprove request for one login (Uses 1, no times). + Login *LoginScope + // Claim is the claimed text, made safe by the caller (see Claim). Claim Claim @@ -63,6 +67,26 @@ type Request struct { OnWait func(shortCode string) } +// LoginScope describes one website login (DESIGN.md section 21). The +// broker fills it from the Bitwarden item it read, after its own checks. +// The core checks it against the config again. +type LoginScope struct { + // Section is the [logins.NAME] section that holds the item. + Section string + // Item is the item ID in lower case. + Item string + // Name and Username are text from the vault. The core cleans them + // before they reach a message, and they never go into the audit log. + Name, Username string + // Origin is the https origin of the page, as the client claimed it. + Origin string + // Clients and Rule are what config.Logins.RuleFor gave for the item. + // For an item with "master password re-prompt", the broker sets + // Rule.Ask to config.AskAlways. + Clients []string + Rule config.Rule +} + // WindowSpec is one daily or weekly window of a KindStanding request, in // the broker's local time. It does not pass midnight: From is before To, // and To is at most 24 hours. diff --git a/internal/approval/state.go b/internal/approval/state.go index 64f1b01..c11e8c9 100644 --- a/internal/approval/state.go +++ b/internal/approval/state.go @@ -12,10 +12,15 @@ import ( // MaxNoticesPerMinute count. const rateWindow = time.Minute -// ref names a secret or a key of the broker config. +// ref names a secret or a key of the broker config, or a website login. type ref struct { - key bool // a [key.*] section; else a [secret.*] section - name string + key bool // a [key.*] section; else a [secret.*] section + // login says that name is the ID of a Bitwarden login item, in lower + // case (DESIGN.md section 21). It is never set together with key. A + // login ref is never equal to a secret or key ref, so a grant for one + // never covers the other. + login bool + name string } // grantKey is the scope of a grant (DESIGN.md section 8): a client and a diff --git a/internal/audit/event.go b/internal/audit/event.go index 4f88396..d62394b 100644 --- a/internal/audit/event.go +++ b/internal/audit/event.go @@ -7,6 +7,7 @@ import ( "fmt" "reflect" "regexp" + "strings" "time" "github.com/code6x/nodkey/internal/version" @@ -41,6 +42,9 @@ const ( // KindStanding is nodkey preapprove with daily or weekly windows: a // standing grant (DESIGN.md section 8). KindStanding Kind = "standing" + // KindWebLogin is a website login: a username and a password from a + // Bitwarden collection (DESIGN.md section 21). + KindWebLogin Kind = "web_login" ) // Answer is the button the approver pressed. @@ -187,6 +191,16 @@ type Subject struct { // "daily 03:00-05:00" or "mon,thu 03:00-05:00", in the broker's local // time. Uses is then the number of uses in each window. Windows []string `json:"windows,omitempty"` + // Logins is the [logins.NAME] section of a website login, a login + // pre-approval, or the list of logins. + Logins string `json:"logins,omitempty"` + // Item is the Bitwarden item ID (a UUID) of a website login. The + // broker read it from its own store. + Item string `json:"item,omitempty"` + // Origin is the https origin of the page, as the client claimed it + // (THREAT-MODEL.md T43). It holds no path, no user name and no + // password. + Origin string `json:"origin,omitempty"` } // IsPreapprove reports whether k is a request for a grant that nodkey @@ -342,6 +356,58 @@ type Failure struct { Code Code `json:"code"` } +// LoginList records a list of website logins for a page (DESIGN.md +// section 21.3). There is no tap. It holds no item names and no user +// names. +type LoginList struct { + // Client is the client that asked. + Client string `json:"client"` + // Logins is the [logins.NAME] section that was listed. + Logins string `json:"logins"` + // Origin is the claimed origin of the page. + Origin string `json:"origin"` + // Count is how many items matched. + Count int `json:"count"` + // Cause is set when the list was refused; then Logins and Origin may + // be empty and Count is 0. + Cause ListCause `json:"cause,omitempty"` +} + +// ListCause says why a list of logins was refused. +type ListCause string + +const ( + ListLimited ListCause = "limit" // the client asked too often + ListBadURL ListCause = "bad_url" // the page URL is not valid + ListCancelled ListCause = "cancelled" // the client went away while the store ran + ListStore ListCause = "store" // a store failed +) + +// LoginTOTP records a request for a TOTP code of a website login. It +// never holds the code or the seed. +type LoginTOTP struct { + Client string `json:"client"` + Logins string `json:"logins,omitempty"` + Item string `json:"item,omitempty"` + Origin string `json:"origin,omitempty"` + // Allowed says whether the broker made a code. + Allowed bool `json:"allowed"` + // Cause says why not, when it is not allowed: a fixed word. + Cause TOTPCause `json:"cause,omitempty"` +} + +// TOTPCause says why a TOTP code was refused. +type TOTPCause string + +// The causes of a refused code. +const ( + TOTPNoGrant TOTPCause = "no_login" // no approved login, ticket or window grant covers it + TOTPNoSeed TOTPCause = "no_totp" // the item has no TOTP seed + TOTPBadSeed TOTPCause = "bad_totp" // the seed is not in a form nodkey knows + TOTPBadItem TOTPCause = "bad_item" // the item failed a check + TOTPStoreFail TOTPCause = "store" // the store failed +) + // logRecovered records a torn last line that Open found. Only Open writes // it, because only Open knows the torn bytes; so it is not exported. type logRecovered struct { @@ -367,8 +433,12 @@ const ( eventForeignTap = "foreign_tap" eventError = "error" eventLogRecovered = "log_recovered" + eventLoginList = "login_list" + eventLoginTOTP = "login_totp" ) +func (LoginList) eventName() string { return eventLoginList } +func (LoginTOTP) eventName() string { return eventLoginTOTP } func (BrokerStarted) eventName() string { return eventBrokerStarted } func (BrokerStopped) eventName() string { return eventBrokerStopped } func (ConfigReloaded) eventName() string { return eventConfigReload } @@ -435,10 +505,29 @@ func (s *Subject) validate(needRequest bool) error { if len(s.Secrets) > 0 || s.HostKey != "" { return errors.New("an SSH grant has no secret names and no single host key") } + case KindWebLogin: + // A request that a check denied before the item was known has none + // of the three; else it has all. + set := 0 + for _, f := range []string{s.Logins, s.Item, s.Origin} { + if f != "" { + set++ + } + } + if (set != 0 && set != 3) || (set == 3 && !strings.HasPrefix(s.Origin, "https://")) || + len(s.Secrets) > 0 || s.Key != "" || len(s.Hosts) > 0 || s.HostKey != "" || s.RemoteUser != "" { + return errors.New("a website login has logins, item and an https origin, or none of them, and no secrets, key, host or remote user") + } case KindPreapprove: if s.HostKey != "" || (len(s.Secrets) > 0 && s.Key != "") { return errors.New("a preapprove request names secrets or one key, not both, and has no single host key") } + if s.Logins != "" || s.Item != "" || s.Origin != "" { + if s.Logins == "" || s.Item == "" || !strings.HasPrefix(s.Origin, "https://") || + len(s.Secrets) > 0 || s.Key != "" || len(s.Hosts) > 0 || s.RemoteUser != "" { + return errors.New("a login pre-approval needs logins, item and an https origin, and has no secrets, key or hosts") + } + } case KindStanding: if s.HostKey != "" || s.Key != "" || len(s.Hosts) > 0 || s.RemoteUser != "" { return errors.New("a standing request names secrets only") @@ -449,6 +538,12 @@ func (s *Subject) validate(needRequest bool) error { if !s.Kind.IsPreapprove() && (s.Uses != 0 || s.NotBefore != "" || s.NotAfter != "") { return errors.New("only a preapprove request has uses and a time span") } + if s.Kind != KindWebLogin && s.Kind != KindPreapprove && (s.Logins != "" || s.Item != "" || s.Origin != "") { + return errors.New("only a website login and a login pre-approval have logins, item and origin") + } + if err := s.validateLogin(); err != nil { + return err + } if s.Kind != KindStanding && len(s.Windows) > 0 { return errors.New("only a standing request has windows") } @@ -496,6 +591,25 @@ func (s *Subject) validate(needRequest bool) error { return nil } +// validateLogin checks the form of logins, item and origin. +func (s *Subject) validateLogin() error { + if s.Logins != "" && !namePattern.MatchString(s.Logins) { + return errors.New("logins must be a section name from the config") + } + if s.Item != "" && !uuidLower.MatchString(s.Item) { + return errors.New("item must be an item ID in lower case") + } + if s.Origin != "" && !originPattern.MatchString(s.Origin) { + return errors.New("origin must be an https origin: a host name and perhaps a port, no path") + } + return nil +} + +var ( + uuidLower = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) + originPattern = regexp.MustCompile(`^https://[a-z0-9][a-z0-9.-]{0,252}(:[0-9]{1,5})?$|^https://\[[0-9a-f:]{2,45}\](:[0-9]{1,5})?$`) +) + func (e BrokerStarted) validate() error { if !version.Valid(e.Version) { return errors.New("version must be a version such as 1.2.0 or dev") @@ -515,6 +629,44 @@ func (e ConfigReloaded) validate() error { // sha256Hex is a SHA-256 in lower-case hex. var sha256Hex = regexp.MustCompile(`^[0-9a-f]{64}$`) +func (e LoginList) validate() error { + if !namePattern.MatchString(e.Client) { + return errors.New("client must be a name from the config") + } + switch e.Cause { + case "": + if !namePattern.MatchString(e.Logins) || !originPattern.MatchString(e.Origin) || e.Count < 0 { + return errors.New("it needs a logins section, an https origin and a count that is not negative") + } + case ListLimited, ListBadURL, ListStore, ListCancelled: + if e.Count != 0 || (e.Logins != "" && !namePattern.MatchString(e.Logins)) || + (e.Origin != "" && !originPattern.MatchString(e.Origin)) { + return errors.New("a refused list has a count of 0, and a section name and an https origin only if it has them") + } + default: + return errors.New("cause must be limit, bad_url, cancelled or store") + } + return nil +} + +func (e LoginTOTP) validate() error { + s := Subject{Client: e.Client, Logins: e.Logins, Item: e.Item, Origin: e.Origin} + if !namePattern.MatchString(e.Client) { + return errors.New("client must be a name from the config") + } + if err := s.validateLogin(); err != nil { + return err + } + if e.Allowed != (e.Cause == "") { + return errors.New("a refused code needs a cause, and an allowed one has none") + } + switch e.Cause { + case "", TOTPNoGrant, TOTPNoSeed, TOTPBadSeed, TOTPBadItem, TOTPStoreFail: + return nil + } + return errors.New("cause is not known") +} + func (e Request) validate() error { return e.Subject.validate(true) } func (e SecretSent) validate() error { return e.Subject.validate(true) } func (e Signed) validate() error { return e.Subject.validate(true) } @@ -663,7 +815,7 @@ func encodeEvent(ev Event) (string, []byte, error) { // them. switch ev.(type) { case BrokerStarted, BrokerStopped, ConfigReloaded, Request, Decision, GrantUsed, GrantEnded, GrantAlarm, SecretSent, Signed, Denied, ForeignTap, Failure, - logRecovered: + logRecovered, LoginList, LoginTOTP: default: return "", nil, errors.New("not an event of the audit package; pass an event such as audit.Signed{...} as a value") } diff --git a/internal/audit/weblogin_test.go b/internal/audit/weblogin_test.go new file mode 100644 index 0000000..b25910e --- /dev/null +++ b/internal/audit/weblogin_test.go @@ -0,0 +1,85 @@ +package audit + +import ( + "strings" + "testing" +) + +const testItem = "11111111-1111-1111-1111-111111111111" + +func webLoginSubject() Subject { + return Subject{ + RequestID: testRequestID(1), Client: "laptop", Kind: KindWebLogin, + Logins: "web", Item: testItem, Origin: "https://example.com", + } +} + +func TestWebLoginSubjectValidate(t *testing.T) { + pre := webLoginSubject() + pre.Kind, pre.Uses = KindPreapprove, 1 + good := []Subject{webLoginSubject(), pre} + for i, s := range good { + if _, _, err := encodeEvent(Request{Subject: s}); err != nil { + t.Errorf("good subject %d: %v", i, err) + } + } + edit := func(base Subject, f func(s *Subject)) Subject { f(&base); return base } + bad := map[string]Subject{ + "no logins": edit(webLoginSubject(), func(s *Subject) { s.Logins = "" }), + "no item": edit(webLoginSubject(), func(s *Subject) { s.Item = "" }), + "no origin": edit(webLoginSubject(), func(s *Subject) { s.Origin = "" }), + "http origin": edit(webLoginSubject(), func(s *Subject) { s.Origin = "http://example.com" }), + "origin with path": edit(webLoginSubject(), func(s *Subject) { s.Origin = "https://example.com/a" }), + "origin with user": edit(webLoginSubject(), func(s *Subject) { s.Origin = "https://u:p@example.com" }), + "item not a UUID": edit(webLoginSubject(), func(s *Subject) { s.Item = "CANARY" }), + "secrets": edit(webLoginSubject(), func(s *Subject) { s.Secrets = []string{"a"} }), + "key": edit(webLoginSubject(), func(s *Subject) { s.Key = "k" }), + "hosts": edit(webLoginSubject(), func(s *Subject) { s.Hosts = []string{"h"} }), + "host key": edit(webLoginSubject(), func(s *Subject) { s.HostKey = testHostKey() }), + "remote user": edit(webLoginSubject(), func(s *Subject) { s.RemoteUser = "root" }), + "login in secrets": edit(secretsSubject(), func(s *Subject) { s.Origin = "https://example.com" }), + "item in ssh login": edit(loginSubject(), func(s *Subject) { s.Item = testItem }), + "preapprove with secrets": edit(pre, func(s *Subject) { s.Secrets = []string{"a"} }), + "preapprove with key": edit(pre, func(s *Subject) { s.Key = "k" }), + "preapprove no origin": edit(pre, func(s *Subject) { s.Origin = "" }), + } + for name, s := range bad { + t.Run(name, func(t *testing.T) { + _, _, err := encodeEvent(Request{Subject: s}) + if err == nil { + t.Fatal("no error") + } + if strings.Contains(err.Error(), "CANARY") { + t.Errorf("the error shows the value: %v", err) + } + }) + } +} + +func TestLoginEventsValidate(t *testing.T) { + good := []Event{ + LoginList{Client: "laptop", Logins: "web", Origin: "https://example.com:8443", Count: 2}, + LoginTOTP{Client: "laptop", Logins: "web", Item: testItem, Origin: "https://example.com", Allowed: true}, + LoginTOTP{Client: "laptop", Logins: "web", Item: testItem, Origin: "https://example.com", Cause: TOTPNoGrant}, + LoginTOTP{Client: "laptop", Cause: TOTPBadItem}, + } + for i, ev := range good { + if _, _, err := encodeEvent(ev); err != nil { + t.Errorf("good event %d: %v", i, err) + } + } + bad := []Event{ + LoginList{Client: "laptop", Logins: "web", Origin: "http://example.com"}, + LoginList{Client: "", Logins: "web", Origin: "https://example.com"}, + LoginList{Client: "laptop", Logins: "web", Origin: "https://example.com", Count: -1}, + LoginTOTP{Client: "laptop", Allowed: true, Cause: TOTPNoSeed}, + LoginTOTP{Client: "laptop"}, + LoginTOTP{Client: "laptop", Cause: "CANARY"}, + LoginTOTP{Client: "laptop", Item: "CANARY", Cause: TOTPNoSeed}, + } + for i, ev := range bad { + if _, _, err := encodeEvent(ev); err == nil { + t.Errorf("bad event %d: no error", i) + } + } +} diff --git a/internal/broker/broker.go b/internal/broker/broker.go index ec897e5..b5f2a76 100644 --- a/internal/broker/broker.go +++ b/internal/broker/broker.go @@ -242,6 +242,9 @@ type Service struct { // nil for none (SetSecurity). The handler reads it without mu. security atomic.Pointer[securityInfo] + // logins holds the lists and the TOTP tickets of website logins. + logins loginState + coreStopped atomic.Bool // the approval core's Run returned broken atomic.Bool // an audit write failed diff --git a/internal/broker/handler.go b/internal/broker/handler.go index af0796e..c3188ed 100644 --- a/internal/broker/handler.go +++ b/internal/broker/handler.go @@ -31,6 +31,9 @@ var endpoints = []endpoint{ {api.PathSSHGrant, audit.KindSSHGrant}, {api.PathPreapprove, audit.KindPreapprove}, {api.PathPreapproveCancel, ""}, + {api.PathLoginList, ""}, + {api.PathLogin, audit.KindWebLogin}, + {api.PathLoginTOTP, ""}, } // route returns the endpoint of r, or the status of the answer: 404 for a @@ -111,6 +114,12 @@ func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) { rq.preapprove(ctx, r) case api.PathPreapproveCancel: rq.cancelGrant(r) + case api.PathLoginList: + rq.listLogins(ctx, r) + case api.PathLogin: + rq.logins(ctx, r) + case api.PathLoginTOTP: + rq.loginTOTP(ctx, r) } } diff --git a/internal/broker/helpers_test.go b/internal/broker/helpers_test.go index b730c12..b05bc59 100644 --- a/internal/broker/helpers_test.go +++ b/internal/broker/helpers_test.go @@ -248,6 +248,10 @@ func eventName(ev audit.Event) string { return "denied:" + string(e.Cause) case audit.Failure: return "error:" + string(e.Code) + case audit.LoginList: + return "login_list" + case audit.LoginTOTP: + return fmt.Sprintf("login_totp:%v:%s", e.Allowed, e.Cause) case audit.ForeignTap: return "foreign_tap:" + string(e.Cause) } @@ -408,6 +412,8 @@ type envOptions struct { // clients are more clients, each with its own key, and no secret or // key of their own. clients []string + // vault, if set, is the store "vault" instead of the fake one. + vault store.Store } // newEnv starts a broker with this config: @@ -521,10 +527,14 @@ func newEnv(t *testing.T, opts envOptions) *env { t.Fatal(err) } e.core = core + var vaultStore store.Store = e.vault + if opts.vault != nil { + vaultStore = opts.vault + } svc, err := New(Parts{ Config: e.cfg, Audit: e.audit, - Stores: map[string]store.Store{"main": e.main, "vault": e.vault}, + Stores: map[string]store.Store{"main": e.main, "vault": vaultStore}, Keys: keys, Logger: NewLogger(e.logs), Version: opts.version, diff --git a/internal/broker/logins.go b/internal/broker/logins.go new file mode 100644 index 0000000..0523d78 --- /dev/null +++ b/internal/broker/logins.go @@ -0,0 +1,762 @@ +package broker + +import ( + "context" + "errors" + "log/slog" + "maps" + "net/http" + "reflect" + "regexp" + "slices" + "sort" + "strings" + "sync" + "time" + + "github.com/code6x/nodkey/internal/api" + "github.com/code6x/nodkey/internal/approval" + "github.com/code6x/nodkey/internal/audit" + "github.com/code6x/nodkey/internal/config" + "github.com/code6x/nodkey/internal/grantkey" + "github.com/code6x/nodkey/internal/loginmatch" + "github.com/code6x/nodkey/internal/store" + "github.com/code6x/nodkey/internal/totp" + "github.com/code6x/nodkey/internal/transport" +) + +// Website logins (DESIGN.md section 21). + +const ( + // LoginListRate is the most lists of logins that one client may ask for + // in a minute. There is no tap for a list, so the rate is limited. + LoginListRate = 10 + // LoginRequestRate is the most requests for a login, or for a login + // pre-approval, that one client may make in a minute. Each one runs the + // store (bw sync and get) before any tap. + LoginRequestRate = 10 + // LoginTOTPNoTicketRate is the most TOTP requests without a ticket or + // a window grant that one client may have answered with an audit entry + // in a minute. + LoginTOTPNoTicketRate = 10 + // LoginTOTPTime is how long a TOTP code may be asked for after an + // approved login of the same client, item and origin. One code only. + LoginTOTPTime = 2 * time.Minute + + // maxLoginTickets is the most tickets the broker keeps. + maxLoginTickets = 1024 +) + +// itemIDPattern is a Bitwarden item ID. +var itemIDPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) + +// loginTicket names the one TOTP code that an approved login allows. +type loginTicket struct { + client, item, origin string +} + +// loginState holds what the broker keeps for website logins in memory. +type loginState struct { + mu sync.Mutex + lists map[string][]time.Time // when each client asked for a list + reqs map[string][]time.Time // when each client asked for a login + noTotp map[string][]time.Time // TOTP requests without a ticket + tickets map[loginTicket]time.Time +} + +// nowTime returns the time of the Service. +func (s *Service) nowTime() time.Time { + s.mu.Lock() + defer s.mu.Unlock() + return s.now() +} + +// allowIn reports whether client may do one more thing now, with at most +// limit in a minute, and counts it. The caller holds s.logins.mu. +func allowIn(m *map[string][]time.Time, now time.Time, client string, limit int) bool { + if *m == nil { + *m = make(map[string][]time.Time) + } + recent := slices.DeleteFunc((*m)[client], func(t time.Time) bool { return now.Sub(t) >= time.Minute }) + if len(recent) >= limit { + (*m)[client] = recent + return false + } + (*m)[client] = append(recent, now) + return true +} + +// allowList reports whether client may ask for one more list now, and +// counts it. +func (s *Service) allowList(client string) bool { + now := s.nowTime() + s.logins.mu.Lock() + defer s.logins.mu.Unlock() + return allowIn(&s.logins.lists, now, client, LoginListRate) +} + +// allowLoginRequest is allowList for a login or a login pre-approval. +func (s *Service) allowLoginRequest(client string) bool { + now := s.nowTime() + s.logins.mu.Lock() + defer s.logins.mu.Unlock() + return allowIn(&s.logins.reqs, now, client, LoginRequestRate) +} + +// allowNoTicket is allowList for a TOTP request that has no ticket. +func (s *Service) allowNoTicket(client string) bool { + now := s.nowTime() + s.logins.mu.Lock() + defer s.logins.mu.Unlock() + return allowIn(&s.logins.noTotp, now, client, LoginTOTPNoTicketRate) +} + +// addTicket lets the client take one TOTP code for the login. +func (s *Service) addTicket(t loginTicket) { + now := s.nowTime() + s.logins.mu.Lock() + defer s.logins.mu.Unlock() + if s.logins.tickets == nil { + s.logins.tickets = make(map[loginTicket]time.Time) + } + for k, end := range s.logins.tickets { + if !now.Before(end) { + delete(s.logins.tickets, k) + } + } + if len(s.logins.tickets) >= maxLoginTickets { + return // fail closed: the code is not available + } + s.logins.tickets[t] = now.Add(LoginTOTPTime) +} + +// hasTicket reports whether a ticket for t is valid now, without using it. +func (s *Service) hasTicket(t loginTicket) bool { + now := s.nowTime() + s.logins.mu.Lock() + defer s.logins.mu.Unlock() + end, ok := s.logins.tickets[t] + return ok && now.Before(end) +} + +// takeTicket uses the ticket for t, if it is valid: it is gone after. +func (s *Service) takeTicket(t loginTicket) bool { + now := s.nowTime() + s.logins.mu.Lock() + defer s.logins.mu.Unlock() + end, ok := s.logins.tickets[t] + delete(s.logins.tickets, t) + return ok && now.Before(end) +} + +// candidateSections returns the names of the [logins.*] sections that +// name client, in the collection's clients or in the clients of an item +// rule, in name order. +func candidateSections(cfg *config.Broker, client string) []string { + var names []string + for name, l := range cfg.Logins { + if slices.Contains(l.Clients, client) { + names = append(names, name) + continue + } + for _, it := range l.Items { + if slices.Contains(it.Clients, client) { + names = append(names, name) + break + } + } + } + sort.Strings(names) + return names +} + +// holds reports whether the collection IDs include collection. +func holds(collections []string, collection string) bool { + return slices.ContainsFunc(collections, func(c string) bool { return strings.EqualFold(c, collection) }) +} + +// loginSel is an item that passed the checks of 21.3. +type loginSel struct { + section string + clients []string + rule config.Rule // with ask = always for an item with a re-prompt + meta store.LoginItem +} + +// checkLoginItem checks the item meta, which came from the store named +// from, for client and page against cfg (DESIGN.md section 21.3): exactly +// one configured collection, a section whose store is from, the rule of +// the item, and a URI that matches the page. It returns a fixed reason +// text for the journal when a check fails. +func checkLoginItem(cfg *config.Broker, client string, page loginmatch.Page, meta store.LoginItem, from string) (loginSel, string) { + var sections []string + for name, l := range cfg.Logins { + if holds(meta.Collections, l.Collection) { + sections = append(sections, name) + } + } + switch { + case len(sections) == 0: + return loginSel{}, "the item is in no collection of a [logins.*] section" + case len(sections) > 1: + return loginSel{}, "the item is in two configured collections" + } + for name, other := range cfg.Logins { + if _, has := other.Items[strings.ToLower(meta.ID)]; has && name != sections[0] { + return loginSel{}, "another [logins.*] section has an item rule for the item" + } + } + l := cfg.Logins[sections[0]] + if l.Store != from { + return loginSel{}, "the item came from another store than its section's" + } + clients, rule, ok := l.RuleFor(strings.ToLower(meta.ID)) + if !ok || !slices.Contains(clients, client) { + return loginSel{}, "the rule of the item does not name the client" + } + if rule.Ask != config.AskAlways && rule.Ask != config.AskWindow { + return loginSel{}, "the rule of the item is not always or window" + } + if !slices.ContainsFunc(meta.URIs, func(u store.LoginURI) bool { return loginmatch.Match(page, u.URI, u.Match) }) { + return loginSel{}, "no URI of the item matches the page" + } + if meta.Reprompt { + rule.Ask = config.AskAlways + } + return loginSel{section: sections[0], clients: clients, rule: rule, meta: meta}, "" +} + +// loginStores returns the names of the stores of the sections, once each, +// in the order of the sections. +func loginStores(cfg *config.Broker, sections []string) []string { + var names []string + for _, s := range sections { + if n := cfg.Logins[s].Store; !slices.Contains(names, n) { + names = append(names, n) + } + } + return names +} + +// fetchLogin gets the login item from the stores of the sections. Its +// password and seed are in rq.values, so they are cleared on every path; +// the caller clears the returned login as soon as it can. On a failure it +// has answered the request, and ok is false. +// +// A store that cannot find the item (bw exits with an error) is skipped +// for the next store; any other error ends the request. +func (rq *request) fetchLogin(ctx context.Context, cfg *config.Broker, sections []string, item string, sub audit.Subject) (store.Login, string, bool) { + var lastErr error + for _, name := range loginStores(cfg, sections) { + ls, isLS := rq.s.stores[name].(store.LoginStore) + if !isLS { + continue + } + if ctx.Err() != nil { + rq.recordDenied(sub, audit.CauseCancelled, "", false) + rq.answer(http.StatusForbidden) + return store.Login{}, "", false + } + fctx, cancel := context.WithTimeout(ctx, fetchTimeout) + l, err := ls.FetchLogin(fctx, item) + cancel() + if err == nil { + rq.values = append(rq.values, l.Password, l.TOTP) + return l, name, true + } + l.Clear() + switch { + case ctx.Err() != nil: + rq.recordDenied(sub, audit.CauseCancelled, "", false) + rq.answer(http.StatusForbidden) + return store.Login{}, "", false + case errors.Is(err, store.ErrFailed) && !errors.Is(err, store.ErrLoggedOut) && !errors.Is(err, store.ErrLocked): + lastErr = err + continue + case errors.Is(err, store.ErrTrashed), errors.Is(err, store.ErrArchived), errors.Is(err, store.ErrNotLogin), + errors.Is(err, store.ErrNoValue): + rq.refuseLogin(sub, "the item is in the trash, archived, not a login, or has no password") + return store.Login{}, "", false + } + rq.s.log.Warn("broker: a store failed; the request is denied", + slog.String("client", rq.client), slog.String("store", name), slog.String("error", errorText(err))) + if errors.Is(err, store.ErrRateLimited) { + rq.s.rateLimited(name) + } + rq.recordDenied(sub, audit.CauseError, audit.CodeStoreFailed, false) + rq.answer(http.StatusServiceUnavailable) + return store.Login{}, "", false + } + if lastErr != nil { + rq.s.log.Warn("broker: no store has the login item, or it failed; the request is denied", + slog.String("client", rq.client), slog.String("error", errorText(lastErr))) + } + rq.refuseLogin(sub, "no store has the item") + return store.Login{}, "", false +} + +// refuseLogin denies a request for a login that a check refused. The +// journal gets a fixed reason, never the URL or the item name. +func (rq *request) refuseLogin(sub audit.Subject, reason string) { + rq.s.log.Info("broker: a request for a website login is denied: "+reason, + slog.String("client", rq.client)) + rq.deny(sub, audit.CauseNotAllowed, "", http.StatusForbidden) +} + +// loginInput reads the page and the item of a request: the URL must be an +// https page that loginmatch accepts, and the item an item ID in lower +// case. On a failure the request is denied. +func (rq *request) loginInput(url, item string) (loginmatch.Page, string, bool) { + page, err := loginmatch.ParsePage(url) + if err != nil || !itemIDPattern.MatchString(item) { + rq.releaseBody() + rq.s.log.Info("broker: a request for a website login is denied: the page URL or the item ID is not valid", + slog.String("client", rq.client)) + rq.deny(audit.Subject{}, audit.CauseNotAllowed, "", http.StatusForbidden) + return loginmatch.Page{}, "", false + } + return page, strings.ToLower(item), true +} + +// loginScope returns the request of the core for a login. +func loginScope(sel loginSel, origin string) *approval.LoginScope { + return &approval.LoginScope{ + Section: sel.section, Item: strings.ToLower(sel.meta.ID), Name: sel.meta.Name, Username: sel.meta.Username, + Origin: origin, Clients: sel.clients, Rule: sel.rule, + } +} + +// checkedLogin fetches the item, checks it, and clears its secrets at +// once: the secrets must not sit in memory while the person decides. It +// returns only what the item says about itself. On a failure the request +// is answered. +func (rq *request) checkedLogin(ctx context.Context, page loginmatch.Page, item string) (loginSel, bool) { + if !rq.s.allowLoginRequest(rq.client) { + rq.s.log.Info("broker: a request for a website login is denied: the client asks too often; wait a minute", + slog.String("client", rq.client)) + rq.recordDenied(audit.Subject{}, audit.CauseLimit, "", true) + rq.answer(http.StatusTooManyRequests) + return loginSel{}, false + } + cfg := rq.v.cfg + sections := candidateSections(cfg, rq.client) + rq.failCode = audit.CodeStoreFailed + l, from, ok := rq.fetchLogin(ctx, cfg, sections, item, audit.Subject{}) + if !ok { + return loginSel{}, false + } + meta := l.LoginItem + l.Clear() + if !strings.EqualFold(meta.ID, item) { + rq.refuseLogin(audit.Subject{}, "the store answered with another item") + return loginSel{}, false + } + sel, reason := checkLoginItem(cfg, rq.client, page, meta, from) + if reason != "" { + rq.refuseLogin(audit.Subject{}, reason) + return loginSel{}, false + } + if !slices.Contains(sections, sel.section) { + rq.refuseLogin(audit.Subject{}, "the section is not one of the client's") + return loginSel{}, false + } + return sel, true +} + +// logins answers a request for a login: username and password (DESIGN.md +// section 21.3). +func (rq *request) logins(ctx context.Context, r *http.Request) { + req, err := transport.ReadJSON[api.LoginRequest](rq.w, r) + if err != nil { + rq.deniedBody() + return + } + if len(r.Header.Values(api.GrantTokenHeader)) > 0 { + // Standing grants for logins are not built (DESIGN.md section 21.7). + rq.releaseBody() + rq.refuseLogin(audit.Subject{}, "a grant token is not used for logins") + return + } + page, item, ok := rq.loginInput(req.URL, req.Item) + if !ok { + return + } + rq.releaseBody() + sel, ok := rq.checkedLogin(ctx, page, item) + if !ok { + return + } + origin := page.Origin() + rq.pre = audit.Subject{Logins: sel.section, Item: item, Origin: origin} + res, rc, ok := rq.decide(ctx, &approval.Request{ + Client: rq.client, Kind: audit.KindWebLogin, Login: loginScope(sel, origin), + }) + if !ok { + return + } + res.StartGrants() + rq.decided = res.Config() + // The password is fetched again after the tap: it was cleared during + // the wait, and the item may have changed. + if !rc.valid() { + rq.fail(audit.CodeStoreFailed) + return + } + if ctx.Err() != nil { + rq.cancelled() + return + } + rq.failCode = audit.CodeStoreFailed + l, from, ok := rq.fetchApproved(ctx, item) + if !ok { + return + } + defer l.Clear() + again, reason := checkLoginItem(rq.s.view().cfg, rq.client, page, l.LoginItem, from) + if reason != "" || again.section != sel.section || l.Username != sel.meta.Username || + l.Name != sel.meta.Name || l.Reprompt != sel.meta.Reprompt || !reflect.DeepEqual(again.rule, sel.rule) || + !strings.EqualFold(l.ID, item) || !rq.stillAllowedLogin(sel, item) { + rq.s.log.Warn("broker: the login item changed while the request waited; the request is denied", + slog.String("request_id", rq.sub.RequestID), slog.String("client", rq.client)) + rq.ended = true + _, _ = rq.s.append(audit.Denied{Subject: rq.sub, Cause: audit.CauseNotAllowed}) + rq.answer(http.StatusForbidden) + return + } + ans := api.LoginAnswer{Username: l.Username, Password: l.Password.Bytes()} + body, err := ans.Encode() + defer clear(body) + if err != nil { + rq.s.log.Warn("broker: a login value is longer than the broker hands out; the request is denied", + slog.String("request_id", rq.sub.RequestID)) + rq.fail(audit.CodeStoreFailed) + return + } + if ctx.Err() != nil { + rq.cancelled() + return + } + if !rq.handOut(rc, audit.SecretSent{Subject: rq.sub}) { + return + } + rq.answered = true + // One TOTP code may follow this login. + rq.s.addTicket(loginTicket{client: rq.client, item: item, origin: origin}) + if err := transport.WriteJSONBody(rq.w, http.StatusOK, body); err != nil { + rq.s.log.Warn("broker: cannot write the answer; the client may not have it", + slog.String("request_id", rq.sub.RequestID), slog.String("client", rq.client)) + } +} + +// fetchApproved gets the item of an approved request again. The stores +// are those of the current config's sections. On a failure the request +// has its end entries and its answer. +func (rq *request) fetchApproved(ctx context.Context, item string) (store.Login, string, bool) { + cfg := rq.s.view().cfg + for _, name := range loginStores(cfg, candidateSections(cfg, rq.client)) { + ls, isLS := rq.s.stores[name].(store.LoginStore) + if !isLS { + continue + } + fctx, cancel := context.WithTimeout(ctx, fetchTimeout) + l, err := ls.FetchLogin(fctx, item) + cancel() + if err == nil { + rq.values = append(rq.values, l.Password, l.TOTP) + return l, name, true + } + l.Clear() + if ctx.Err() != nil { + rq.cancelled() + return store.Login{}, "", false + } + if errors.Is(err, store.ErrFailed) && !errors.Is(err, store.ErrLoggedOut) && !errors.Is(err, store.ErrLocked) { + continue // not in this store + } + rq.s.log.Warn("broker: a store failed; the request is denied", + slog.String("request_id", rq.sub.RequestID), slog.String("store", name), slog.String("error", errorText(err))) + if errors.Is(err, store.ErrRateLimited) { + rq.s.rateLimited(name) + } + rq.fail(audit.CodeStoreFailed) + return store.Login{}, "", false + } + rq.fail(audit.CodeStoreFailed) + return store.Login{}, "", false +} + +// stillAllowedLogin checks, after the tap, that a reload did not take away +// what the request uses: the client and its pin, and the rule of the item. +func (rq *request) stillAllowedLogin(sel loginSel, item string) bool { + if !rq.stillAllowed(rq.decided, nil, "", nil) { + return false // it has answered + } + l, ok := rq.s.view().cfg.Logins[sel.section] + if !ok { + return false + } + clients, rule, ok := l.RuleFor(item) + if sel.meta.Reprompt { + rule.Ask = config.AskAlways // as in checkLoginItem + } + return ok && slices.Equal(clients, sel.clients) && slices.Contains(clients, rq.client) && + reflect.DeepEqual(rule, sel.rule) +} + +// listLogins answers a request for the list of logins of a page. It needs +// no tap, so it never holds a password, and it is limited per client. +func (rq *request) listLogins(ctx context.Context, r *http.Request) { + req, err := transport.ReadJSON[api.ListLoginsRequest](rq.w, r) + if err != nil { + return // ReadJSON has answered + } + rq.releaseBody() + // refuse writes the one entry of a refused list, limited per minute so + // that a client cannot fill the disk with them, then answers. + refuse := func(cause audit.ListCause, origin string, status int) { + if rq.s.refusedAllowed(rq.client) { + if _, err := rq.s.append(audit.LoginList{Client: rq.client, Origin: origin, Cause: cause}); err != nil { + status = http.StatusServiceUnavailable + } + } + rq.answer(status) + } + page, err := loginmatch.ParsePage(req.URL) + if err != nil { + rq.s.log.Info("broker: a request for a list of logins is denied: the page URL is not valid", + slog.String("client", rq.client)) + refuse(audit.ListBadURL, "", http.StatusForbidden) + return + } + if !rq.s.allowList(rq.client) { + rq.s.log.Info("broker: a request for a list of logins is denied: the client asks too often; wait a minute", + slog.String("client", rq.client)) + refuse(audit.ListLimited, page.Origin(), http.StatusTooManyRequests) + return + } + cfg := rq.v.cfg + var entries []api.LoginEntry + counts := make(map[string]int) + for _, name := range candidateSections(cfg, rq.client) { + l := cfg.Logins[name] + ls, isLS := rq.s.stores[l.Store].(store.LoginStore) + if !isLS { + continue + } + fctx, cancel := context.WithTimeout(ctx, fetchTimeout) + items, err := ls.ListLogins(fctx, l.Collection) + cancel() + if err != nil { + if ctx.Err() != nil { + refuse(audit.ListCancelled, page.Origin(), http.StatusForbidden) + return + } + rq.s.log.Warn("broker: a store failed; the list of logins is denied", + slog.String("client", rq.client), slog.String("store", l.Store), slog.String("error", errorText(err))) + if errors.Is(err, store.ErrRateLimited) { + rq.s.rateLimited(l.Store) + } + refuse(audit.ListStore, page.Origin(), http.StatusServiceUnavailable) + return + } + counts[name] = 0 + for _, it := range items { + sel, reason := checkLoginItem(cfg, rq.client, page, it, l.Store) + if reason != "" || sel.section != name { + continue + } + entries = append(entries, api.LoginEntry{Logins: name, ID: strings.ToLower(it.ID), Name: it.Name, Username: it.Username}) + counts[name]++ + } + } + if len(entries) > api.MaxLoginEntries { + refuse(audit.ListStore, page.Origin(), http.StatusServiceUnavailable) + return + } + // The entries come before the answer; no entry, no list. A section + // with no match gets an entry with a count of 0. + for _, name := range slices.Sorted(maps.Keys(counts)) { + if _, err := rq.s.append(audit.LoginList{Client: rq.client, Logins: name, Origin: page.Origin(), Count: counts[name]}); err != nil { + rq.answer(http.StatusServiceUnavailable) + return + } + } + rq.answerJSON(api.ListLoginsAnswer{Logins: entries}) +} + +// loginTOTP answers a request for the current TOTP code of a login. The +// seed never leaves the broker (DESIGN.md section 21.3). +func (rq *request) loginTOTP(ctx context.Context, r *http.Request) { + req, err := transport.ReadJSON[api.TOTPRequest](rq.w, r) + if err != nil { + return + } + rq.releaseBody() + deny := func(cause audit.TOTPCause, status int, sub audit.Subject) { + ev := audit.LoginTOTP{Client: rq.client, Logins: sub.Logins, Item: sub.Item, Origin: sub.Origin, Cause: cause} + if _, err := rq.s.append(ev); err != nil { + status = http.StatusServiceUnavailable + } + rq.answer(status) + } + page, item, ok := func() (loginmatch.Page, string, bool) { + p, err := loginmatch.ParsePage(req.URL) + if err != nil || !itemIDPattern.MatchString(req.Item) { + return p, "", false + } + return p, strings.ToLower(req.Item), true + }() + if !ok { + // A bad request needs no ticket: it shares the cap of the requests + // with no ticket, so a loop cannot fill the audit log. + if !rq.s.allowNoTicket(rq.client) { + rq.answer(http.StatusTooManyRequests) + return + } + deny(audit.TOTPBadItem, http.StatusForbidden, audit.Subject{}) + return + } + origin := page.Origin() + ticket := loginTicket{client: rq.client, item: item, origin: origin} + // Cheap check first: no ticket and no window grant, no fetch. + if !rq.s.hasTicket(ticket) && !rq.core.LoginGranted(rq.client, item) { + if !rq.s.allowNoTicket(rq.client) { + // Limited: no entry, as for other refused requests over the cap. + rq.s.log.Info("broker: a request for a TOTP code is denied: the client asks too often without a login; wait a minute", + slog.String("client", rq.client)) + rq.answer(http.StatusTooManyRequests) + return + } + deny(audit.TOTPNoGrant, http.StatusForbidden, audit.Subject{Logins: "", Item: item, Origin: origin}) + return + } + cfg := rq.v.cfg + sections := candidateSections(cfg, rq.client) + rq.failCode = "" + l, from, kind := rq.fetchLoginForTOTP(ctx, cfg, sections, item) + switch kind { + case totpFetchStore: + deny(audit.TOTPStoreFail, http.StatusServiceUnavailable, audit.Subject{}) + return + case totpFetchRefused: + deny(audit.TOTPBadItem, http.StatusForbidden, audit.Subject{}) + return + } + defer l.Clear() + sel, reason := checkLoginItem(cfg, rq.client, page, l.LoginItem, from) + sub := audit.Subject{Logins: sel.section, Item: item, Origin: origin} + if reason != "" || !strings.EqualFold(l.ID, item) { + rq.s.log.Info("broker: a request for a TOTP code is denied: "+reason, slog.String("client", rq.client)) + deny(audit.TOTPBadItem, http.StatusForbidden, audit.Subject{}) + return + } + if len(l.TOTP.Bytes()) == 0 { + rq.s.log.Info("broker: the login item has no TOTP seed; ask for a code only for an item that has one", + slog.String("client", rq.client)) + deny(audit.TOTPNoSeed, http.StatusForbidden, sub) + return + } + key, err := totp.Parse(l.TOTP.Bytes()) + if err != nil { + rq.s.log.Warn("broker: the TOTP seed of a login item is not in a form nodkey knows; see DESIGN.md section 21.5", + slog.String("client", rq.client)) + deny(audit.TOTPBadSeed, http.StatusForbidden, sub) + return + } + defer key.Clear() + // A window grant covers codes while the rule is a window rule and the + // item has no re-prompt; else a ticket of an approved login is needed. + byGrant := sel.rule.Ask == config.AskWindow && !sel.meta.Reprompt && rq.core.LoginGranted(rq.client, item) + if !byGrant && !rq.s.takeTicket(ticket) { + deny(audit.TOTPNoGrant, http.StatusForbidden, sub) + return + } + code, err := key.Code(rq.s.nowTime()) + if err != nil { + deny(audit.TOTPBadSeed, http.StatusForbidden, sub) + return + } + ev := audit.LoginTOTP{Client: rq.client, Logins: sub.Logins, Item: item, Origin: origin, Allowed: true} + if _, err := rq.s.append(ev); err != nil { + rq.answer(http.StatusServiceUnavailable) + return + } + rq.answerJSON(struct { + Code string `json:"code"` + }{Code: code}) +} + +// totpFetch says how fetchLoginForTOTP ended. +type totpFetch int + +const ( + totpFetched totpFetch = iota // the login is returned + totpFetchRefused // no store has the item, or it was cancelled + totpFetchStore // a store failed +) + +// fetchLoginForTOTP is fetchLogin for a request that has no audit subject +// of the core: it does not answer; it says how the fetch ended. +func (rq *request) fetchLoginForTOTP(ctx context.Context, cfg *config.Broker, sections []string, item string) (store.Login, string, totpFetch) { + for _, name := range loginStores(cfg, sections) { + ls, isLS := rq.s.stores[name].(store.LoginStore) + if !isLS { + continue + } + fctx, cancel := context.WithTimeout(ctx, fetchTimeout) + l, err := ls.FetchLogin(fctx, item) + cancel() + if err == nil { + rq.values = append(rq.values, l.Password, l.TOTP) + return l, name, totpFetched + } + l.Clear() + if ctx.Err() == nil && errors.Is(err, store.ErrFailed) && !errors.Is(err, store.ErrLoggedOut) && !errors.Is(err, store.ErrLocked) { + continue + } + rq.s.log.Warn("broker: a store failed or refused the item; the request for a TOTP code is denied", + slog.String("client", rq.client), slog.String("store", name), slog.String("error", errorText(err))) + if errors.Is(err, store.ErrRateLimited) { + rq.s.rateLimited(name) + } + if ctx.Err() != nil || errors.Is(err, store.ErrTrashed) || errors.Is(err, store.ErrArchived) || + errors.Is(err, store.ErrNotLogin) || errors.Is(err, store.ErrNoValue) { + return store.Login{}, "", totpFetchRefused + } + return store.Login{}, "", totpFetchStore + } + return store.Login{}, "", totpFetchRefused +} + +// preapproveLogin answers a request for a one-use pre-approval of a login +// (DESIGN.md section 21.3): one login, in the 60 s after the tap. The +// item is checked as for a login, and its secrets are cleared at once. +func (rq *request) preapproveLogin(ctx context.Context, req *api.PreapproveRequest) { + if req.Login == "" || req.URL == "" || len(req.Secrets) > 0 || req.Key != "" || req.User != "" || + len(req.Hosts) > 0 || req.From != "" || req.Until != "" || req.Uses != 1 || req.Windows != nil { + rq.releaseBody() + rq.s.log.Info("broker: a request for a login pre-approval is denied: it must give a login, a URL and one use, and nothing else", + slog.String("client", rq.client)) + rq.deny(audit.Subject{}, audit.CauseNotAllowed, "", http.StatusForbidden) + return + } + cl := approval.Claim{Reason: freeText(req.Reason, maxReasonRunes)} + page, item, ok := rq.loginInput(req.URL, req.Login) + if !ok { + return + } + rq.releaseBody() + sel, ok := rq.checkedLogin(ctx, page, item) + if !ok { + return + } + origin := page.Origin() + rq.pre = audit.Subject{Logins: sel.section, Item: item, Origin: origin, Reason: cl.Reason} + res, _, ok := rq.decide(ctx, &approval.Request{ + Client: rq.client, Kind: audit.KindPreapprove, Uses: 1, Login: loginScope(sel, origin), Claim: cl, + }) + if !ok { + return + } + rq.startedGrant(ctx, res, false, grantkey.Token{}) +} diff --git a/internal/broker/logins_test.go b/internal/broker/logins_test.go new file mode 100644 index 0000000..a276211 --- /dev/null +++ b/internal/broker/logins_test.go @@ -0,0 +1,883 @@ +package broker + +// Tests of website logins (DESIGN.md section 21) through the broker. + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/code6x/nodkey/internal/api" + "github.com/code6x/nodkey/internal/audit" + "github.com/code6x/nodkey/internal/config" + "github.com/code6x/nodkey/internal/store" +) + +const ( + collWeb = "aaaaaaaa-0000-0000-0000-000000000001" // the collection of [logins.web] + collOther = "aaaaaaaa-0000-0000-0000-000000000002" // the collection of [logins.other] + collNone = "aaaaaaaa-0000-0000-0000-000000000003" // a collection no section names + itemShop = "bbbbbbbb-0000-0000-0000-000000000001" + itemMail = "bbbbbbbb-0000-0000-0000-000000000002" + pageShop = "https://example.com/sign-in" + // totpSeed is the base32 form of "12345678901234567890", the seed of + // RFC 6238 appendix B. At 59 s after the epoch, the SHA1 code with 6 + // digits is 287082. + totpSeed = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" +) + +// fakeLogin is an item of the fake login store. +type fakeLogin struct { + store.LoginItem + password, totp string + fetchErr error // FetchLogin returns it + hidden bool // ListLogins leaves it out +} + +// fakeLoginStore is the store "vault" for the tests of logins. +type fakeLoginStore struct { + *fakeStore + lmu sync.Mutex + logins map[string]*fakeLogin + listErr error + listed int + fetchedIDs []string + given [][]byte +} + +func newFakeLoginStore() *fakeLoginStore { + return &fakeLoginStore{fakeStore: newFakeStore(), logins: make(map[string]*fakeLogin)} +} + +func (f *fakeLoginStore) add(l *fakeLogin) { + f.lmu.Lock() + defer f.lmu.Unlock() + f.logins[l.ID] = l +} + +func (f *fakeLoginStore) ListLogins(_ context.Context, collection string) ([]store.LoginItem, error) { + f.lmu.Lock() + defer f.lmu.Unlock() + f.listed++ + if f.listErr != nil { + return nil, f.listErr + } + var out []store.LoginItem + for _, id := range slices.Sorted(mapKeys(f.logins)) { + l := f.logins[id] + if !l.hidden && slices.Contains(l.Collections, collection) { + out = append(out, l.LoginItem) + } + } + return out, nil +} + +func mapKeys[V any](m map[string]V) func(func(string) bool) { + return func(yield func(string) bool) { + for k := range m { + if !yield(k) { + return + } + } + } +} + +func (f *fakeLoginStore) FetchLogin(_ context.Context, id string) (store.Login, error) { + f.lmu.Lock() + defer f.lmu.Unlock() + f.fetchedIDs = append(f.fetchedIDs, id) + l, ok := f.logins[id] + if !ok { + return store.Login{}, fmt.Errorf("fake bw: not found: %w", store.ErrFailed) + } + if l.fetchErr != nil { + return store.Login{}, l.fetchErr + } + pw, seed := []byte(l.password), []byte(l.totp) + f.given = append(f.given, pw, seed) + out := store.Login{LoginItem: l.LoginItem, Password: store.NewValue(pw)} + if l.totp != "" { + out.TOTP = store.NewValue(seed) + } + return out, nil +} + +// checkCleared fails unless every password and seed that the store gave +// out is cleared. +func (f *fakeLoginStore) checkCleared(t testing.TB) { + t.Helper() + f.lmu.Lock() + defer f.lmu.Unlock() + for i, b := range f.given { + if len(b) > 0 && !bytes.Equal(b, make([]byte, len(b))) { + t.Errorf("value %d that the store gave out is not cleared", i) + } + } +} + +func (f *fakeLoginStore) fetches() int { + f.lmu.Lock() + defer f.lmu.Unlock() + return len(f.fetchedIDs) +} + +// loginEnv starts a broker with [logins.web] (laptop; window 15m; +// preapprove) for the collection collWeb on the store "vault", and +// [logins.other] for collOther. The store holds the shop login and a mail +// login, both at example.com. +type loginTest struct { + *env + vs *fakeLoginStore + pw string + seed string + shop *fakeLogin + laptp *http.Client +} + +func newLoginEnv(t *testing.T, edit func(*config.Broker)) *loginTest { + t.Helper() + vs := newFakeLoginStore() + pw := madeUp("shop-password") + shop := &fakeLogin{ + LoginItem: store.LoginItem{ + ID: itemShop, Name: "Example shop", Username: "alice@example.com", + URIs: []store.LoginURI{{URI: "https://example.com"}}, Collections: []string{collWeb}, + }, + password: pw, totp: totpSeed, + } + vs.add(shop) + vs.add(&fakeLogin{ + LoginItem: store.LoginItem{ + ID: itemMail, Name: "Example mail", Username: "bob@example.com", + URIs: []store.LoginURI{{URI: "https://example.com"}}, Collections: []string{collWeb}, + }, + password: madeUp("mail-password"), + }) + e := newEnv(t, envOptions{vault: vs, config: func(cfg *config.Broker) { + cfg.Preapprove = config.DefaultPreapprove() + cfg.Logins = map[string]config.Logins{ + "web": {Name: "web", Store: "vault", Collection: collWeb, Clients: []string{"laptop"}, + Rule: config.Rule{Ask: config.AskWindow, Window: 15 * time.Minute, Preapprove: true}}, + "other": {Name: "other", Store: "vault", Collection: collOther, Clients: []string{"laptop"}, + Rule: config.Rule{Ask: config.AskAlways}}, + } + if edit != nil { + edit(cfg) + } + }}) + return &loginTest{env: e, vs: vs, pw: pw, seed: totpSeed, shop: shop, laptp: e.httpClient("laptop")} +} + +func (l *loginTest) loginReq(item, url string) api.LoginRequest { + return api.LoginRequest{URL: url, Item: item} +} + +// approveLogin asks for the login and approves it with action. +func (l *loginTest) approveLogin(item, url string, action audit.Answer) *result { + l.t.Helper() + n := len(l.approver.Asked()) + 1 + p := l.start(l.laptp, api.PathLogin, l.loginReq(item, url)) + pr := l.waitAsked(n)[n-1].Prompt + l.tap(pr.RequestID, action) + return p.wait(l.t) +} + +func (l *loginTest) noMessage(res *result, status int) { + l.t.Helper() + mustStatus(l.t, res, status) + if n := len(l.approver.Asked()); n != 0 { + l.t.Errorf("the approver was asked %d times; want 0", n) + } +} + +func TestLoginByTap(t *testing.T) { + l := newLoginEnv(t, nil) + res := l.approveLogin(itemShop, pageShop, audit.AnswerApproveOnce) + mustStatus(t, res, http.StatusOK) + ans, err := api.ReadAnswer[api.LoginAnswer](bytes.NewReader(res.body)) + if err != nil || ans.Username != "alice@example.com" || string(ans.Password) != l.pw { + t.Fatalf("answer: %v", err) + } + pr := l.approver.Asked()[0].Prompt + if pr.Kind != audit.KindWebLogin || pr.Login == nil || pr.Login.Name != "Example shop" || + pr.Login.Username != "alice@example.com" || pr.Login.Origin != "https://example.com" { + t.Errorf("prompt %+v", pr) + } + events := l.audit.all() + mustEvents(t, events, "request decision:approve_once secret_sent") + s := subjectOf(events[0]) + if s.Kind != audit.KindWebLogin || s.Logins != "web" || s.Item != itemShop || s.Origin != "https://example.com" { + t.Errorf("subject %+v", s) + } + // The password was fetched twice: it is not held while the person decides. + if n := l.vs.fetches(); n != 2 { + t.Errorf("%d fetches, want 2", n) + } + l.vs.checkCleared(t) + if all := encodeEvents(t, events); strings.Contains(all, l.pw) || strings.Contains(all, "alice@") || + strings.Contains(all, "Example shop") || strings.Contains(all, l.seed) { + t.Errorf("the audit log holds vault text or a secret:\n%s", all) + } + if strings.Contains(l.logs.String(), l.pw) || strings.Contains(l.approverTexts(), l.pw) { + t.Error("the password is in the log or in a message") + } +} + +func TestLoginDeny(t *testing.T) { + tests := []struct { + name string + edit func(l *loginTest) + url string + item string + header string + }{ + {name: "item outside the collection", edit: func(l *loginTest) { l.shop.Collections = []string{collNone} }}, + {name: "item in two configured collections", edit: func(l *loginTest) { l.shop.Collections = []string{collWeb, collOther} }}, + {name: "not a login", edit: func(l *loginTest) { l.shop.fetchErr = store.ErrNotLogin }}, + {name: "in the trash", edit: func(l *loginTest) { l.shop.fetchErr = store.ErrTrashed }}, + {name: "archived", edit: func(l *loginTest) { l.shop.fetchErr = store.ErrArchived }}, + {name: "no password", edit: func(l *loginTest) { l.shop.fetchErr = store.ErrNoValue }}, + {name: "origin matches no URI", url: "https://evil.test/sign-in"}, + {name: "sibling host with host match", edit: func(l *loginTest) { + host := 1 + l.shop.URIs = []store.LoginURI{{URI: "https://example.com", Match: &host}} + }, url: "https://www.example.com/"}, + {name: "http page", url: "http://example.com/sign-in"}, + {name: "page URL that is not a URL", url: "example"}, + {name: "page with a user name", url: "https://" + "u:p" + "@example.com/"}, + {name: "unknown item", item: "bbbbbbbb-0000-0000-0000-0000000000ff"}, + {name: "item that is not a UUID", item: "../etc"}, + {name: "grant token header", header: "tokentokentoken"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + l := newLoginEnv(t, nil) + if tt.edit != nil { + tt.edit(l) + } + item, url := cmp(tt.item, itemShop), cmp(tt.url, pageShop) + body := l.loginReq(item, url) + var res *result + if tt.header != "" { + res = l.postHeader(api.PathLogin, body, api.GrantTokenHeader, tt.header) + } else { + res = l.post(t.Context(), l.laptp, api.PathLogin, body) + } + l.noMessage(res, http.StatusForbidden) + if bytes.Contains(res.body, []byte(l.pw)) { + t.Error("the answer holds the password") + } + events := l.audit.all() + if got := eventNames(events); got != "request denied:not_allowed" { + t.Errorf("entries %s", got) + } + l.vs.checkCleared(t) + }) + } +} + +func cmp(a, b string) string { + if a != "" { + return a + } + return b +} + +// postHeader sends body with one header. +func (l *loginTest) postHeader(path string, body any, name, value string) *result { + l.t.Helper() + data, err := json.Marshal(body) + if err != nil { + l.t.Fatal(err) + } + req, err := http.NewRequestWithContext(l.t.Context(), http.MethodPost, "https://"+l.addr+path, bytes.NewReader(data)) + if err != nil { + l.t.Fatal(err) + } + req.Header.Set("Content-Type", api.ContentType) + req.Header.Set(name, value) + resp, err := l.laptp.Do(req) + if err != nil { + return &result{err: err} + } + defer func() { _ = resp.Body.Close() }() + b, err := io.ReadAll(io.LimitReader(resp.Body, api.MaxAnswer+1)) + return &result{status: resp.StatusCode, body: b, err: err} +} + +func TestLoginItemRuleDecidesTheClient(t *testing.T) { + // A stricter item rule: the collection names laptop, the item names ci. + l := newLoginEnv(t, func(cfg *config.Broker) { + s := cfg.Logins["web"] + s.Items = map[string]config.LoginItemRule{itemShop: {ID: itemShop, Clients: []string{"ci"}, Rule: config.Rule{Ask: config.AskAlways}}} + cfg.Logins["web"] = s + }) + l.noMessage(l.post(t.Context(), l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)), http.StatusForbidden) + // The mail item still follows the collection's rule. + res := l.approveLogin(itemMail, pageShop, audit.AnswerApproveOnce) + mustStatus(t, res, http.StatusOK) +} + +func TestLoginItemRuleLooser(t *testing.T) { + // A looser item rule: ci is not in the collection's clients, but the + // item's rule names it. + l := newLoginEnv(t, func(cfg *config.Broker) { + s := cfg.Logins["web"] + s.Items = map[string]config.LoginItemRule{itemShop: {ID: itemShop, Clients: []string{"laptop", "ci"}, Rule: config.Rule{Ask: config.AskAlways}}} + cfg.Logins["web"] = s + }) + ci := l.httpClient("ci") + p := l.start(ci, api.PathLogin, l.loginReq(itemShop, pageShop)) + pr := l.waitAsked(1)[0].Prompt + if pr.WindowMinutes != 0 { + t.Errorf("the item rule is always, but the message offers a window: %+v", pr) + } + l.tap(pr.RequestID, audit.AnswerApproveOnce) + mustStatus(t, p.wait(t), http.StatusOK) + // ci may not use the mail item: the collection does not name it. + res := l.post(t.Context(), ci, api.PathLogin, l.loginReq(itemMail, pageShop)) + mustStatus(t, res, http.StatusForbidden) +} + +func TestLoginReprompt(t *testing.T) { + l := newLoginEnv(t, nil) + l.shop.Reprompt = true + n := 1 + p := l.start(l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)) + pr := l.waitAsked(n)[0].Prompt + if pr.WindowMinutes != 0 { + t.Errorf("an item with a re-prompt must offer no window: %+v", pr) + } + l.tap(pr.RequestID, audit.AnswerApproveOnce) + mustStatus(t, p.wait(t), http.StatusOK) +} + +func TestLoginWindowGrant(t *testing.T) { + l := newLoginEnv(t, nil) + mustStatus(t, l.approveLogin(itemShop, pageShop, audit.AnswerApproveWindow), http.StatusOK) + // The same item again: no message. + res := l.post(t.Context(), l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)) + mustStatus(t, res, http.StatusOK) + if n := len(l.approver.Asked()); n != 1 { + t.Errorf("%d messages, want 1", n) + } + // Another item needs a tap. + p := l.start(l.laptp, api.PathLogin, l.loginReq(itemMail, pageShop)) + pr := l.waitAsked(2)[1].Prompt + l.tap(pr.RequestID, audit.AnswerDeny) + mustStatus(t, p.wait(t), http.StatusForbidden) +} + +func (l *loginTest) listReq(url string) *result { + return l.post(l.t.Context(), l.laptp, api.PathLoginList, api.ListLoginsRequest{URL: url}) +} + +func TestLoginList(t *testing.T) { + l := newLoginEnv(t, nil) + l.vs.add(&fakeLogin{LoginItem: store.LoginItem{ID: "bbbbbbbb-0000-0000-0000-000000000003", Name: "Other site", + Username: "x", URIs: []store.LoginURI{{URI: "https://other.test"}}, Collections: []string{collWeb}}}) + l.vs.add(&fakeLogin{LoginItem: store.LoginItem{ID: "bbbbbbbb-0000-0000-0000-000000000004", Name: "In two", + Username: "y", URIs: []store.LoginURI{{URI: "https://example.com"}}, Collections: []string{collWeb, collOther}}}) + l.vs.add(&fakeLogin{LoginItem: store.LoginItem{ID: "bbbbbbbb-0000-0000-0000-000000000005", Name: "Hidden", + Username: "z", URIs: []store.LoginURI{{URI: "https://example.com"}}, Collections: []string{collWeb}}, hidden: true}) + res := l.listReq(pageShop) + mustStatus(t, res, http.StatusOK) + ans, err := api.ReadAnswer[api.ListLoginsAnswer](bytes.NewReader(res.body)) + if err != nil || len(ans.Logins) != 2 || ans.Logins[0].ID != itemShop || ans.Logins[1].ID != itemMail || + ans.Logins[0].Logins != "web" || ans.Logins[0].Username != "alice@example.com" || ans.Logins[0].Name != "Example shop" { + t.Fatalf("answer %+v, %v", ans, err) + } + for _, secret := range []string{l.pw, l.seed, "password", "totp"} { + if bytes.Contains(res.body, []byte(secret)) { + t.Errorf("the raw answer holds %q:\n%s", secret, res.body) + } + } + events := l.audit.all() + mustEvents(t, events, "login_list login_list") // other: 0 matches, web: 2 + if got := encodeEvents(t, events); !strings.Contains(got, `"count":2`) || strings.Contains(got, "alice") || + strings.Contains(got, "Example") { + t.Errorf("entry %s", got) + } + if n := len(l.approver.Asked()); n != 0 { + t.Errorf("a list asked the person %d times", n) + } + // Other pages: no match is an empty list; a bad page is refused. + res = l.listReq("https://nothing.test/") + ans, err = api.ReadAnswer[api.ListLoginsAnswer](bytes.NewReader(res.body)) + if err != nil || len(ans.Logins) != 0 { + t.Errorf("answer %s, %v", res.body, err) + } + mustStatus(t, l.listReq("http://example.com/"), http.StatusForbidden) + // A store that fails makes a 503, not a list. + l.vs.lmu.Lock() + l.vs.listErr = errors.New("fake bw: down") + l.vs.lmu.Unlock() + mustStatus(t, l.listReq(pageShop), http.StatusServiceUnavailable) +} + +func TestLoginListRate(t *testing.T) { + l := newLoginEnv(t, nil) + now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) + l.svc.setNow(func() time.Time { return now }) + for i := range LoginListRate { + if res := l.listReq(pageShop); res.status != http.StatusOK { + t.Fatalf("list %d: status %d", i, res.status) + } + } + mustStatus(t, l.listReq(pageShop), http.StatusTooManyRequests) + now = now.Add(time.Minute) + mustStatus(t, l.listReq(pageShop), http.StatusOK) +} + +func (l *loginTest) totp(item, url string) *result { + return l.post(l.t.Context(), l.laptp, api.PathLoginTOTP, api.TOTPRequest{URL: url, Item: item}) +} + +func codeOf(t *testing.T, res *result) string { + t.Helper() + mustStatus(t, res, http.StatusOK) + a, err := api.ReadAnswer[api.TOTPAnswer](bytes.NewReader(res.body)) + if err != nil { + t.Fatal(err) + } + return a.Code +} + +func TestLoginTOTPTicket(t *testing.T) { + l := newLoginEnv(t, nil) + now := time.Unix(59, 0) + l.svc.setNow(func() time.Time { return now }) + // No login first: no code, and the seed is not even read. + mustStatus(t, l.totp(itemShop, pageShop), http.StatusForbidden) + if n := l.vs.fetches(); n != 0 { + t.Errorf("%d fetches without a ticket", n) + } + mustStatus(t, l.approveLogin(itemShop, pageShop, audit.AnswerApproveOnce), http.StatusOK) + // Another origin, another item: no code. + mustStatus(t, l.totp(itemShop, "https://shop.example.com/"), http.StatusForbidden) + mustStatus(t, l.totp(itemMail, pageShop), http.StatusForbidden) + // The RFC 6238 code for T = 59 s with SHA1 and 6 digits. + res := l.totp(itemShop, pageShop+"?step=2") + if code := codeOf(t, res); code != "287082" { + t.Errorf("code %q, want 287082", code) + } + // One code only. + mustStatus(t, l.totp(itemShop, pageShop), http.StatusForbidden) + events := l.audit.all() + var got []string + for _, ev := range events { + if _, ok := ev.(audit.LoginTOTP); ok { + got = append(got, eventName(ev)) + } + } + want := "login_totp:false:no_login login_totp:false:no_login login_totp:false:no_login login_totp:true: login_totp:false:no_login" + if strings.Join(got, " ") != want { + t.Errorf("totp entries %v\nwant %s", got, want) + } + all := encodeEvents(t, events) + for _, secret := range []string{l.seed, "287082", l.pw} { + if strings.Contains(all, secret) || strings.Contains(l.logs.String(), secret) || strings.Contains(l.approverTexts(), secret) { + t.Errorf("%q is in the audit log, the journal or a message", secret) + } + } + l.vs.checkCleared(t) +} + +func TestLoginTOTPTicketExpires(t *testing.T) { + l := newLoginEnv(t, nil) + now := time.Unix(59, 0) + l.svc.setNow(func() time.Time { return now }) + mustStatus(t, l.approveLogin(itemShop, pageShop, audit.AnswerApproveOnce), http.StatusOK) + now = now.Add(LoginTOTPTime) + mustStatus(t, l.totp(itemShop, pageShop), http.StatusForbidden) +} + +func TestLoginTOTPWithWindowGrant(t *testing.T) { + l := newLoginEnv(t, nil) + now := time.Unix(59, 0) + l.svc.setNow(func() time.Time { return now }) + mustStatus(t, l.approveLogin(itemShop, pageShop, audit.AnswerApproveWindow), http.StatusOK) + for i := range 3 { + if code := codeOf(t, l.totp(itemShop, pageShop)); code != "287082" { + t.Errorf("code %d: %q", i, code) + } + } + // The window grant is for the shop item only. + mustStatus(t, l.totp(itemMail, pageShop), http.StatusForbidden) +} + +func TestLoginTOTPNoSeedAndReprompt(t *testing.T) { + l := newLoginEnv(t, nil) + mustStatus(t, l.approveLogin(itemMail, pageShop, audit.AnswerApproveOnce), http.StatusOK) + res := l.totp(itemMail, pageShop) // the mail item has no seed + mustStatus(t, res, http.StatusForbidden) + // A window grant does not cover a code of an item with a re-prompt. + l.shop.Reprompt = true + mustStatus(t, l.approveLogin(itemShop, pageShop, audit.AnswerApproveOnce), http.StatusOK) // gives a ticket + l.shop.Reprompt = false +} + +func TestLoginTOTPBadSeed(t *testing.T) { + l := newLoginEnv(t, nil) + l.shop.totp = "steam://" + madeUp("seed") + mustStatus(t, l.approveLogin(itemShop, pageShop, audit.AnswerApproveOnce), http.StatusOK) + res := l.totp(itemShop, pageShop) + mustStatus(t, res, http.StatusForbidden) + if strings.Contains(string(res.body), "steam") || strings.Contains(l.logs.String(), "steam://") { + t.Error("the seed shows in an answer or the journal") + } + l.vs.checkCleared(t) +} + +// loginPre asks for the pre-approval and approves it. +func (l *loginTest) loginPre(item, url string) *result { + l.t.Helper() + n := len(l.approver.Asked()) + 1 + p := l.start(l.laptp, api.PathPreapprove, api.PreapproveRequest{Login: item, URL: url, Uses: 1, Reason: "log in for the test"}) + pr := l.waitAsked(n)[n-1].Prompt + if pr.Kind != audit.KindPreapprove || pr.Login == nil || pr.Login.For != 60*time.Second || pr.Uses != 1 { + l.t.Errorf("prompt %+v", pr) + } + l.tap(pr.RequestID, audit.AnswerApproveOnce) + return p.wait(l.t) +} + +func TestLoginPreapprove(t *testing.T) { + l := newLoginEnv(t, nil) + res := l.loginPre(itemShop, pageShop) + mustStatus(t, res, http.StatusOK) + if got := l.approver.Asked(); len(got) != 1 { + t.Fatalf("%d messages", len(got)) + } + // Another item or origin does not use it: the person is asked. The + // client hangs up, so nothing is denied. + for i, tt := range []struct{ item, url string }{{itemMail, pageShop}, {itemShop, "https://shop.example.com/"}} { + p := l.start(l.laptp, api.PathLogin, l.loginReq(tt.item, tt.url)) + l.waitAsked(i + 2) + p.cancel() + } + // The pre-approval of the shop item on example.com is used once, with + // no new message. + before := len(l.approver.Asked()) + res = l.post(t.Context(), l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)) + mustStatus(t, res, http.StatusOK) + if n := len(l.approver.Asked()); n != before { + t.Errorf("the use asked the person") + } + if code := codeOf(t, l.totp(itemShop, pageShop)); len(code) != 6 { + t.Errorf("code %q: a login by pre-approval gives one code", code) + } + // Used up: the next login needs a tap. + p := l.start(l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)) + pr := l.waitAsked(before + 1)[before].Prompt + l.tap(pr.RequestID, audit.AnswerDeny) + mustStatus(t, p.wait(t), http.StatusForbidden) + l.vs.checkCleared(t) +} + +func TestLoginPreapproveOtherClient(t *testing.T) { + l := newLoginEnv(t, func(cfg *config.Broker) { + s := cfg.Logins["web"] + s.Clients = []string{"laptop", "ci"} + cfg.Logins["web"] = s + }) + mustStatus(t, l.loginPre(itemShop, pageShop), http.StatusOK) + ci := l.httpClient("ci") + p := l.start(ci, api.PathLogin, l.loginReq(itemShop, pageShop)) + pr := l.waitAsked(2)[1].Prompt + l.tap(pr.RequestID, audit.AnswerDeny) + mustStatus(t, p.wait(t), http.StatusForbidden) +} + +func TestLoginPreapproveEndsAfterSixtySeconds(t *testing.T) { + l := newLoginEnv(t, nil) + mustStatus(t, l.loginPre(itemShop, pageShop), http.StatusOK) + l.clock.Advance(60 * time.Second) + p := l.start(l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)) + pr := l.waitAsked(2)[1].Prompt + l.tap(pr.RequestID, audit.AnswerDeny) + mustStatus(t, p.wait(t), http.StatusForbidden) +} + +// TestLoginPreapproveSlowTap: the 60 s start at the tap, not at the +// request. A tap after 100 s still gives a pre-approval. +func TestLoginPreapproveSlowTap(t *testing.T) { + l := newLoginEnv(t, nil) + p := l.start(l.laptp, api.PathPreapprove, api.PreapproveRequest{Login: itemShop, URL: pageShop, Uses: 1}) + pr := l.waitAsked(1)[0].Prompt + l.clock.Advance(100 * time.Second) + l.tap(pr.RequestID, audit.AnswerApproveOnce) + mustStatus(t, p.wait(t), http.StatusOK) + l.clock.Advance(30 * time.Second) + res := l.post(t.Context(), l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)) + mustStatus(t, res, http.StatusOK) + if n := len(l.approver.Asked()); n != 1 { + t.Errorf("%d messages, want 1", n) + } +} + +func TestLoginPreapproveDeny(t *testing.T) { + bad := map[string]api.PreapproveRequest{ + "two uses": {Login: itemShop, URL: pageShop, Uses: 2}, + "no uses": {Login: itemShop, URL: pageShop}, + "with times": {Login: itemShop, URL: pageShop, Uses: 1, From: "2026-10-14T13:00:00Z", Until: "2026-10-14T14:00:00Z"}, + "with secrets": {Login: itemShop, URL: pageShop, Uses: 1, Secrets: []string{"github-token"}}, + "with a key": {Login: itemShop, URL: pageShop, Uses: 1, Key: "deploy"}, + "no URL": {Login: itemShop, Uses: 1}, + "no login": {URL: pageShop, Uses: 1}, + "http page": {Login: itemShop, URL: "http://example.com/", Uses: 1}, + "other page": {Login: itemShop, URL: "https://evil.test/", Uses: 1}, + "windows": {Login: itemShop, URL: pageShop, Uses: 1, Windows: []api.Window{{Kind: api.WindowDaily, From: "03:00", To: "04:00"}}}, + } + for name, body := range bad { + t.Run(name, func(t *testing.T) { + l := newLoginEnv(t, nil) + l.noMessage(l.post(t.Context(), l.laptp, api.PathPreapprove, body), http.StatusForbidden) + }) + } + t.Run("rule without preapprove", func(t *testing.T) { + l := newLoginEnv(t, func(cfg *config.Broker) { + s := cfg.Logins["web"] + s.Rule.Preapprove = false + cfg.Logins["web"] = s + }) + l.noMessage(l.post(t.Context(), l.laptp, api.PathPreapprove, api.PreapproveRequest{Login: itemShop, URL: pageShop, Uses: 1}), + http.StatusForbidden) + }) +} + +// changeAfterAsk starts a login, changes the shop item when the person is +// asked, taps, and returns the answer. +func (l *loginTest) changeAfterAsk(change func()) *result { + l.t.Helper() + p := l.start(l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)) + pr := l.waitAsked(1)[0].Prompt + change() + l.tap(pr.RequestID, audit.AnswerApproveOnce) + return p.wait(l.t) +} + +func TestLoginItemChangesAfterTheTap(t *testing.T) { + changes := map[string]func(l *loginTest){ + "username": func(l *loginTest) { l.shop.Username = "mallory@example.com" }, + "name": func(l *loginTest) { l.shop.Name = "Another name" }, + "collection": func(l *loginTest) { l.shop.Collections = []string{collNone} }, + "uri": func(l *loginTest) { l.shop.URIs = []store.LoginURI{{URI: "https://evil.test"}} }, + "reprompt": func(l *loginTest) { l.shop.Reprompt = true }, + "second collection": func(l *loginTest) { + l.shop.Collections = []string{collWeb, collOther} + }, + } + for name, change := range changes { + t.Run(name, func(t *testing.T) { + l := newLoginEnv(t, nil) + res := l.changeAfterAsk(func() { change(l) }) + mustStatus(t, res, http.StatusForbidden) + if bytes.Contains(res.body, []byte(l.pw)) { + t.Error("the password is in the answer") + } + if strings.Contains(eventNames(l.audit.all()), "secret_sent") { + t.Error("a password was sent") + } + l.vs.checkCleared(t) + }) + } +} + +func TestLoginRuleChangesAfterTheTap(t *testing.T) { + l := newLoginEnv(t, nil) + p := l.start(l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)) + pr := l.waitAsked(1)[0].Prompt + // A reload gives the section a longer window: the decided rule differs. + cfg := *l.svc.view().cfg + cfg.Logins = map[string]config.Logins{} + for k, v := range l.svc.view().cfg.Logins { + cfg.Logins[k] = v + } + w := cfg.Logins["web"] + w.Rule.Window = 4 * time.Hour + cfg.Logins["web"] = w + v := *l.svc.view() + v.cfg = &cfg + l.svc.cur.Store(&v) + l.tap(pr.RequestID, audit.AnswerApproveOnce) + mustStatus(t, p.wait(t), http.StatusForbidden) +} + +func TestLoginItemRuleInAnotherSection(t *testing.T) { + l := newLoginEnv(t, func(cfg *config.Broker) { + o := cfg.Logins["other"] + o.Items = map[string]config.LoginItemRule{ + itemShop: {Clients: []string{"laptop"}, Rule: config.Rule{Ask: config.AskAlways}}, + } + cfg.Logins["other"] = o + }) + l.noMessage(l.post(t.Context(), l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)), http.StatusForbidden) + res := l.listReq(pageShop) + ans, err := api.ReadAnswer[api.ListLoginsAnswer](bytes.NewReader(res.body)) + if err != nil { + t.Fatal(err) + } + for _, e := range ans.Logins { + if e.ID == itemShop { + t.Errorf("the list holds an item that another section has a rule for") + } + } +} + +func TestLoginTOTPStoreFailure(t *testing.T) { + l := newLoginEnv(t, nil) + mustStatus(t, l.approveLogin(itemShop, pageShop, audit.AnswerApproveOnce), http.StatusOK) + l.shop.fetchErr = errors.New("fake bw: down") + mustStatus(t, l.totp(itemShop, pageShop), http.StatusServiceUnavailable) + events := l.audit.all() + if got := encodeEvents(t, events[len(events)-1:]); !strings.Contains(got, `"cause":"store"`) { + t.Errorf("last entry %s", got) + } +} + +func TestLoginTOTPNoTicketIsLimited(t *testing.T) { + l := newLoginEnv(t, nil) + now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) + l.svc.setNow(func() time.Time { return now }) + for i := range LoginTOTPNoTicketRate { + if res := l.totp(itemShop, pageShop); res.status != http.StatusForbidden { + t.Fatalf("request %d: status %d", i, res.status) + } + } + n := len(l.audit.all()) + mustStatus(t, l.totp(itemShop, pageShop), http.StatusTooManyRequests) + if got := len(l.audit.all()); got != n { + t.Errorf("a limited request wrote an entry") + } + if l.vs.fetches() != 0 { + t.Error("a request with no ticket fetched from the store") + } +} + +// A bad TOTP request shares the cap of the requests with no ticket, so a +// loop cannot fill the audit log. +func TestLoginTOTPBadRequestIsLimited(t *testing.T) { + l := newLoginEnv(t, nil) + now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) + l.svc.setNow(func() time.Time { return now }) + for i := range LoginTOTPNoTicketRate { + if res := l.totp("not-an-id", pageShop); res.status != http.StatusForbidden { + t.Fatalf("request %d: status %d", i, res.status) + } + } + n := len(l.audit.all()) + if n != LoginTOTPNoTicketRate { + t.Errorf("got %d entries, want %d", n, LoginTOTPNoTicketRate) + } + mustStatus(t, l.totp("not-an-id", pageShop), http.StatusTooManyRequests) + mustStatus(t, l.totp(itemShop, "http://example.com/"), http.StatusTooManyRequests) + if got := len(l.audit.all()); got != n { + t.Errorf("a limited request wrote an entry") + } +} + +func TestLoginListAudited(t *testing.T) { + l := newLoginEnv(t, nil) + // No match: one entry with a count of 0 for each section of the client. + mustStatus(t, l.listReq("https://nothing.test/"), http.StatusOK) + mustEvents(t, l.audit.all(), "login_list login_list") + if got := encodeEvents(t, l.audit.all()); strings.Contains(got, `"count":1`) || strings.Contains(got, `"count":2`) { + t.Errorf("entries %s", got) + } + // A bad URL. + mustStatus(t, l.listReq("http://example.com/"), http.StatusForbidden) + events := l.audit.all() + mustEvents(t, events, "login_list login_list login_list") + if got := encodeEvents(t, events[2:]); !strings.Contains(got, `"cause":"bad_url"`) { + t.Errorf("entry %s", got) + } + // A store failure. + l.vs.lmu.Lock() + l.vs.listErr = errors.New("fake bw: down") + l.vs.lmu.Unlock() + mustStatus(t, l.listReq(pageShop), http.StatusServiceUnavailable) + events = l.audit.all() + if got := encodeEvents(t, events[len(events)-1:]); !strings.Contains(got, `"cause":"store"`) { + t.Errorf("entry %s", got) + } +} + +func TestLoginListRateIsAudited(t *testing.T) { + l := newLoginEnv(t, nil) + now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) + l.svc.setNow(func() time.Time { return now }) + for range LoginListRate { + mustStatus(t, l.listReq(pageShop), http.StatusOK) + } + n := len(l.audit.all()) + mustStatus(t, l.listReq(pageShop), http.StatusTooManyRequests) + events := l.audit.all() + if len(events) != n+1 || !strings.Contains(encodeEvents(t, events[n:]), `"cause":"limit"`) { + t.Errorf("entries %s", eventNames(events[n:])) + } +} + +func TestLoginRequestRate(t *testing.T) { + l := newLoginEnv(t, nil) + now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) + l.svc.setNow(func() time.Time { return now }) + for i := range LoginRequestRate { + if res := l.post(t.Context(), l.laptp, api.PathLogin, l.loginReq(itemShop, "https://nothing.test/")); res.status != http.StatusForbidden { + t.Fatalf("request %d: status %d", i, res.status) + } + } + // The cap counts requests, so the next one is refused before the store. + // (A bad page is refused before the cap, so use a good page.) + for range LoginRequestRate { + l.post(t.Context(), l.laptp, api.PathLogin, l.loginReq("cccccccc-0000-0000-0000-000000000009", pageShop)) + } + before := l.vs.fetches() + mustStatus(t, l.post(t.Context(), l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)), http.StatusTooManyRequests) + mustStatus(t, l.post(t.Context(), l.laptp, api.PathPreapprove, + api.PreapproveRequest{Login: itemShop, URL: pageShop, Uses: 1}), http.StatusTooManyRequests) + if l.vs.fetches() != before { + t.Error("a limited request ran the store") + } + if n := len(l.approver.Asked()); n != 0 { + t.Errorf("the approver was asked %d times", n) + } + now = now.Add(time.Minute) + p := l.start(l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)) + l.waitAsked(1) + p.cancel() +} + +func TestLoginPreapproveUsedOnce(t *testing.T) { + l := newLoginEnv(t, nil) + mustStatus(t, l.loginPre(itemShop, pageShop), http.StatusOK) + p1 := l.start(l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)) + p2 := l.start(l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)) + var won, other *pendingResult + select { + case r := <-p1.done: + p1.done <- r + won, other = p1, p2 + case r := <-p2.done: + p2.done <- r + won, other = p2, p1 + case <-time.After(waitLimit): + t.Fatal("no request got the login") + } + mustStatus(t, won.wait(t), http.StatusOK) + // The other one needs a tap of its own. + l.waitAsked(2) + other.cancel() + if n := len(l.approver.Asked()); n != 2 { + t.Errorf("%d messages, want 2", n) + } +} diff --git a/internal/broker/preapprove.go b/internal/broker/preapprove.go index 00d262b..fbee09d 100644 --- a/internal/broker/preapprove.go +++ b/internal/broker/preapprove.go @@ -32,6 +32,10 @@ func (rq *request) preapprove(ctx context.Context, r *http.Request) { rq.deniedBody() return } + if req.Login != "" || req.URL != "" { + rq.preapproveLogin(ctx, req) + return + } cl := approval.Claim{Reason: freeText(req.Reason, maxReasonRunes)} standing := len(req.Windows) > 0 var sub audit.Subject @@ -72,6 +76,12 @@ func (rq *request) preapprove(ctx context.Context, r *http.Request) { if !ok { return } + rq.startedGrant(ctx, res, standing, token) +} + +// startedGrant starts the grant of an approved request for a scheduled or +// standing grant, and answers it. +func (rq *request) startedGrant(ctx context.Context, res *approval.Result, standing bool, token grantkey.Token) { // The grant is all that an approval gives. When the client has hung // up, no grant starts. if ctx.Err() != nil { @@ -114,7 +124,7 @@ func (rq *request) preapprove(ctx context.Context, r *http.Request) { if standing { ans.GrantToken = token.Reveal() } - err = transport.WriteJSON(rq.w, http.StatusOK, ans) + err := transport.WriteJSON(rq.w, http.StatusOK, ans) if err == nil { // writeBody does not flush; a hang-up shows here, not at Write. if err = http.NewResponseController(rq.w).Flush(); errors.Is(err, http.ErrNotSupported) { diff --git a/internal/client/logins.go b/internal/client/logins.go new file mode 100644 index 0000000..1fcfdef --- /dev/null +++ b/internal/client/logins.go @@ -0,0 +1,64 @@ +package client + +import ( + "context" + "encoding/json" + "errors" + + "github.com/code6x/nodkey/internal/api" +) + +// The requests for website logins (DESIGN.md section 21), for the browser +// plugin of #104. They never print anything: the caller gets the answer +// and decides what to do with it. A LoginAnswer holds a password; the +// caller must call its Clear as soon as it has used it. + +// errLoginRequest is the error for a request that is over a cap of the +// broker. +var errLoginRequest = errors.New("the request is over a cap of the broker: the page URL is at most 2048 bytes and the item ID a UUID") + +// ListLogins asks the broker for the logins that match the page pageURL. +// There is no tap. The answer holds the item IDs, names and user names, +// never a password. +func ListLogins(ctx context.Context, b *Broker, pageURL string) (*api.ListLoginsAnswer, error) { + req := api.ListLoginsRequest{URL: pageURL} + if req.Check() != nil { + return nil, errLoginRequest + } + body, err := json.Marshal(req) + if err != nil { + return nil, errLoginRequest + } + return Post[api.ListLoginsAnswer](ctx, b, api.PathLoginList, body, nil) +} + +// Login asks the broker for the username and the password of the item at +// the page pageURL. It waits for the person's tap, as nodkey run does; +// onCode, if not nil, gets the short code when the request starts to wait. +// The caller must Clear the answer. +func Login(ctx context.Context, b *Broker, pageURL, item string, onCode func(code string)) (*api.LoginAnswer, error) { + req := api.LoginRequest{URL: pageURL, Item: item} + if req.Check() != nil { + return nil, errLoginRequest + } + body, err := json.Marshal(req) + if err != nil { + return nil, errLoginRequest + } + return Post[api.LoginAnswer](ctx, b, api.PathLogin, body, onCode) +} + +// LoginTOTP asks the broker for the current TOTP code of the item at the +// page pageURL. The broker allows it after an approved login (DESIGN.md +// section 21.3). +func LoginTOTP(ctx context.Context, b *Broker, pageURL, item string) (*api.TOTPAnswer, error) { + req := api.TOTPRequest{URL: pageURL, Item: item} + if req.Check() != nil { + return nil, errLoginRequest + } + body, err := json.Marshal(req) + if err != nil { + return nil, errLoginRequest + } + return Post[api.TOTPAnswer](ctx, b, api.PathLoginTOTP, body, nil) +} diff --git a/internal/client/logins_test.go b/internal/client/logins_test.go new file mode 100644 index 0000000..c476826 --- /dev/null +++ b/internal/client/logins_test.go @@ -0,0 +1,202 @@ +package client + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "strings" + "testing" + + "github.com/code6x/nodkey/internal/api" +) + +const ( + testItem = "11111111-1111-1111-1111-111111111111" + testPage = "https://example.com/sign-in" +) + +// loginHandler answers the paths of website logins and keeps the bodies. +func loginHandler(t *testing.T, password string, bodies *[]string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + data, _ := io.ReadAll(r.Body) + *bodies = append(*bodies, r.URL.Path+" "+string(data)) + switch r.URL.Path { + case api.PathLoginList: + _, _ = io.WriteString(w, `{"logins":[{"logins":"web","id":"`+testItem+`","name":"Example shop","username":"alice@example.com"}]}`) + case api.PathLogin: + ans := api.LoginAnswer{Username: "alice@example.com", Password: []byte(password)} + body, err := ans.Encode() + if err != nil { + t.Error(err) + } + w.Header().Set("Content-Type", api.ContentType) + _, _ = w.Write(body) + case api.PathLoginTOTP: + _, _ = io.WriteString(w, `{"code":"287082"}`) + case api.PathPreapprove: + _, _ = io.WriteString(w, `{"id":"abcdefghijklmnopqrstuv","from":"2026-10-15T12:00:00Z","until":"2026-10-15T12:01:00Z"}`) + default: + w.WriteHeader(http.StatusNotFound) + } + } +} + +func TestListLoginsLoginAndTOTP(t *testing.T) { + t.Parallel() + pw := madeUp("shop-password") + var bodies []string + fb := newFakeBroker(t, loginHandler(t, pw, &bodies)) + list, err := ListLogins(t.Context(), fb.b, testPage) + if err != nil || len(list.Logins) != 1 || list.Logins[0].ID != testItem || list.Logins[0].Logins != "web" { + t.Fatalf("list: %v %+v", err, list) + } + ans, err := Login(t.Context(), fb.b, testPage, testItem, nil) + if err != nil || ans.Username != "alice@example.com" || string(ans.Password) != pw { + t.Fatalf("login: %v", err) + } + // Nothing prints the password, and Clear wipes it. + for _, s := range []string{fmt.Sprint(ans), fmt.Sprintf("%+v %#v %v", ans, *ans, *ans), slog.Any("a", ans).Value.String()} { + if strings.Contains(s, pw) { + t.Errorf("the password shows: %s", s) + } + } + ans.Clear() + if !bytes.Equal(ans.Password, make([]byte, len(pw))) { + t.Error("Clear left the password") + } + code, err := LoginTOTP(t.Context(), fb.b, testPage, testItem) + if err != nil || code.Code != "287082" { + t.Fatalf("totp: %v", err) + } + if len(bodies) != 3 || !strings.Contains(bodies[1], `"item":"`+testItem+`"`) || !strings.Contains(bodies[1], `"url":"`+testPage+`"`) { + t.Errorf("bodies %q", bodies) + } +} + +func TestLoginErrors(t *testing.T) { + t.Parallel() + status := http.StatusForbidden + fb := newFakeBroker(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(status) }) + for name, call := range map[string]func() error{ + "list": func() error { _, err := ListLogins(t.Context(), fb.b, testPage); return err }, + "login": func() error { _, err := Login(t.Context(), fb.b, testPage, testItem, nil); return err }, + "totp": func() error { _, err := LoginTOTP(t.Context(), fb.b, testPage, testItem); return err }, + } { + err := call() + var e *Error + if err == nil || !asError(err, &e) || e.Status != http.StatusForbidden { + t.Errorf("%s: %v, want a 403 error", name, err) + } + } + // A request over a cap never reaches the broker. + before := fb.requests.Load() + long := "https://example.com/" + strings.Repeat("a", api.MaxURL) + if _, err := ListLogins(t.Context(), fb.b, long); err == nil { + t.Error("a long URL was sent") + } + if _, err := Login(t.Context(), fb.b, testPage, strings.Repeat("a", api.MaxItemID+1), nil); err == nil { + t.Error("a long item was sent") + } + if fb.requests.Load() != before { + t.Error("a request over a cap reached the broker") + } + // A bad answer is an error, and a password in a list is refused. + fb2 := newFakeBroker(t, func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, `{"logins":[{"logins":"w","id":"i","name":"n","username":"u","password":"p"}]}`) + }) + if _, err := ListLogins(t.Context(), fb2.b, testPage); err == nil { + t.Error("a list with a password field was taken") + } +} + +func asError(err error, target **Error) bool { return errors.As(err, target) } + +func TestPreapproveLoginUsage(t *testing.T) { + t.Parallel() + g := testGranter(nil, nil) + bad := map[string][]string{ + "login without url": {"--login", testItem}, + "url without login": {"--url", testPage}, + "login with secret": {"--login", testItem, "--url", testPage, "--secret", "a"}, + "login with key": {"--login", testItem, "--url", testPage, "--key", "deploy"}, + "login with uses": {"--login", testItem, "--url", testPage, "--uses", "1"}, + "login with until": {"--login", testItem, "--url", testPage, "--until", "2026-10-28T04:00"}, + "login with from": {"--login", testItem, "--url", testPage, "--from", "2026-10-28T04:00"}, + "login with host": {"--login", testItem, "--url", testPage, "--host", "web-1"}, + "login with daily": {"--login", testItem, "--url", testPage, "--daily", "03:00-05:00"}, + "login with cancel": {"--login", testItem, "--cancel", "abcdefghijklmnopqrstuv"}, + "login with token": {"--login", testItem, "--url", testPage, "--grant-token", "/tmp/x"}, + "item not a UUID": {"--login", "shop", "--url", testPage}, + "http page": {"--login", testItem, "--url", "http://example.com/"}, + "page that is no URL": {"--login", testItem, "--url", "example"}, + "login twice": {"--login", testItem, "--login", testItem, "--url", testPage}, + "url twice": {"--login", testItem, "--url", testPage, "--url", testPage}, + "login without value": {"--login"}, + "secret with a url": {"--secret", "a", "--url", testPage, "--until", "2026-10-28T04:00", "--uses", "1"}, + "login and secret url": {"--login", testItem, "--url", testPage, "--secret", "a", "--uses", "1"}, + } + for name, args := range bad { + t.Run(name, func(t *testing.T) { + code, stdout, stderr := preIn(t.Context(), g, args...) + lines := strings.Split(strings.TrimSuffix(stderr, "\n"), "\n") + if code != exitUsage || stdout != "" || len(lines) != 1 || !strings.HasPrefix(lines[0], "nodkey preapprove: ") || + !strings.HasSuffix(lines[0], "(exit 64)") { + t.Errorf("exit %d, stdout %q, stderr %q; want one usage line", code, stdout, stderr) + } + }) + } +} + +func TestPreapproveLoginApproves(t *testing.T) { + t.Parallel() + var bodies []string + fb := newFakeBroker(t, loginHandler(t, "x", &bodies)) + code, stdout, stderr := preIn(t.Context(), testGranter(fb.b, nil), + "--login", strings.ToUpper(testItem[:1])+testItem[1:], "--url", testPage, "--reason", "check the order") + if code != exitOK || stdout != "abcdefghijklmnopqrstuv\n" || + !strings.Contains(stderr, "one login for this page, until 2026-10-15T12:01:00Z (exit 0)") { + t.Fatalf("exit %d, stdout %q, stderr %q", code, stdout, stderr) + } + var req map[string]any + if err := json.Unmarshal([]byte(strings.TrimPrefix(bodies[0], api.PathPreapprove+" ")), &req); err != nil { + t.Fatal(err) + } + if req["login"] == "" || req["url"] != testPage || req["uses"] != float64(1) || req["from"] != "" || req["until"] != "" || + req["reason"] != "check the order" { + t.Errorf("request %v", req) + } + if _, ok := req["windows"]; ok { + t.Error("the request has windows") + } +} + +func TestPreapproveLoginWaitsAsLongAsOthers(t *testing.T) { + t.Parallel() + // The request has no limit of its own: it ends with the context. + started := make(chan struct{}) + fb := newFakeBroker(t, func(w http.ResponseWriter, r *http.Request) { + close(started) + <-r.Context().Done() + }) + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan int, 1) + go func() { + code, _, _ := preIn(ctx, testGranter(fb.b, nil), "--login", testItem, "--url", testPage) + done <- code + }() + <-started + select { + case code := <-done: + t.Fatalf("it ended before the tap, with %d", code) + default: + } + cancel() + if code := <-done; code == exitOK { + t.Error("a cancelled request succeeded") + } +} diff --git a/internal/client/preapprove.go b/internal/client/preapprove.go index af9555e..60bbeab 100644 --- a/internal/client/preapprove.go +++ b/internal/client/preapprove.go @@ -8,6 +8,7 @@ import ( "io" "net/http" "os" + "regexp" "slices" "strconv" "strings" @@ -16,6 +17,7 @@ import ( "github.com/code6x/nodkey/internal/api" "github.com/code6x/nodkey/internal/grantkey" + "github.com/code6x/nodkey/internal/loginmatch" "github.com/code6x/nodkey/internal/sshauth" "github.com/code6x/nodkey/internal/transport" ) @@ -27,6 +29,7 @@ const preapproveUsage = `Usage: nodkey preapprove (--secret NAME... | --key NAME (--daily HH:MM-HH:MM | --weekly DAYS HH:MM-HH:MM) --until TIME [--from TIME] [--uses N] --grant-token FILE [--reason TEXT] + nodkey preapprove --login ITEM --url URL [--reason TEXT] nodkey preapprove --cancel ID Ask the broker now for a grant that you use later, and wait until a person @@ -60,6 +63,12 @@ planned. for a standing grant: the file where the token is written. The token is never printed. It must be a new file, or your own file with mode 0600. + --login ITEM a website login: the ID of a Bitwarden item of the broker. + Needs --url. The tap allows one login, for the page + --url, in the 60 s after the tap. It excludes --secret, + --key, --user, --host, --from, --until, --uses, --daily, + --weekly and --grant-token. + --url URL the https page of the login, with --login --reason TEXT why the grant is needed. Without it, the reason is the environment variable NODKEY_REASON. --cancel ID end a grant of this machine now, without a tap; ID is @@ -119,6 +128,9 @@ type preapproveOptions struct { windows []api.Window // grantToken is the file of --grant-token, for a standing grant. grantToken string + // login and url are the item ID of --login and the page of --url, for + // a pre-approval of one login. + login, url string } // runPreapprove runs nodkey preapprove, and returns the exit code. @@ -142,7 +154,7 @@ func (g granter) runPreapprove(ctx context.Context, args []string, stdout, w io. return fail(stderr, exitUsage, err.Error()) } } - if o.cancel == "" && o.from == "" { + if o.cancel == "" && o.from == "" && o.login == "" { o.from = g.now().Format(time.RFC3339) } path, body, err := newPreapprove(o, reason) @@ -219,6 +231,10 @@ func (g granter) runPreapprove(ctx context.Context, args []string, stdout, w io. } // The grant is made. The ID goes to stdout for a script that cancels. _, _ = fmt.Fprintln(stdout, ans.ID) + if o.login != "" { + _, _ = fmt.Fprintf(stderr, "nodkey: grant %s: one login for this page, until %s (exit %d)\n", ans.ID, ans.Until, exitOK) + return exitOK + } if o.windows != nil { _, _ = fmt.Fprintf(stderr, "nodkey: standing grant %s: %s in each window, %s (broker time), from %s until %s (exit %d)\n", ans.ID, usesText(o.uses), windowText(o.windows[0]), ans.From, ans.Until, exitOK) @@ -336,7 +352,7 @@ func parsePreapproveArgs(args []string) (*preapproveOptions, error) { name, value, hasValue := splitOption(arg) switch name { case "secret", "key", "user", "host", "from", "until", "uses", "reason", "cancel", - "daily", "weekly", "grant-token": + "daily", "weekly", "grant-token", "login", "url": case "h", "help": return nil, errors.New("--help must be the only argument") default: @@ -373,6 +389,16 @@ func parsePreapproveArgs(args []string) (*preapproveOptions, error) { err = errors.New("--grant-token: give the path of a file") } o.grantToken = value + case "login": + if !itemIDPattern.MatchString(value) { + err = fmt.Errorf("--login: %.64q is not an item ID: give the UUID that the broker lists for the page", value) + } + o.login = value + case "url": + if _, perr := loginmatch.ParsePage(value); perr != nil { + err = fmt.Errorf("--url: %w", perr) + } + o.url = value case "secret": err = addSecret(o, seen, value) case "key": @@ -423,6 +449,18 @@ func checkPreapproveGiven(o *preapproveOptions, given map[string]bool) error { } return nil } + if given["url"] && !given["login"] { + return errors.New("--url is for a website login: give --login ITEM too") + } + if given["login"] { + if len(given) > 1+btoi(given["url"])+btoi(given["reason"]) || len(o.secrets) > 0 || len(o.hosts) > 0 { + return errors.New("--login excludes --secret, --key, --user, --host, --from, --until, --uses, --daily, --weekly and --grant-token; give only --login, --url and --reason") + } + if !given["url"] { + return errors.New("give the page of the login with --url URL, such as --url https://example.com/sign-in") + } + return nil + } if o.windows != nil { return checkStandingGiven(o, given) } @@ -484,10 +522,14 @@ func newPreapprove(o *preapproveOptions, reason string) (string, []byte, error) path, v = api.PathPreapproveCancel, api.PreapproveCancelRequest{ID: o.cancel} } else { req := api.PreapproveRequest{ + Login: o.login, URL: o.url, Secrets: o.secrets, Key: o.key, User: o.user, Hosts: o.hosts, From: o.from, Until: o.until, Uses: int64(o.uses), Reason: claimedText(reason), Windows: o.windows, } + if o.login != "" { + req.Uses = 1 + } if err := req.Check(); err != nil { return "", nil, errors.New("the request is over a cap of the broker") } @@ -567,3 +609,14 @@ func parseDays(s string) ([]string, error) { }) return days, nil } + +// itemIDPattern is a Bitwarden item ID. +var itemIDPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) + +// btoi returns 1 for true and 0 for false. +func btoi(b bool) int { + if b { + return 1 + } + return 0 +} diff --git a/internal/config/broker.go b/internal/config/broker.go index 57f2547..d12821a 100644 --- a/internal/config/broker.go +++ b/internal/config/broker.go @@ -68,6 +68,7 @@ type Broker struct { Stores map[string]Store // by name Secrets map[string]Secret // by name Keys map[string]Key // by name + Logins map[string]Logins // by name: the [logins.*] sections (DESIGN.md section 21) } // Telegram is the [telegram] section. @@ -289,6 +290,7 @@ type ( Store map[string]storeSection `toml:"store"` Secret map[string]secretSection `toml:"secret"` Key map[string]keySection `toml:"key"` + Logins map[string]loginsSection `toml:"logins"` } telegramSection struct { TokenFile string `toml:"token_file"` @@ -419,7 +421,7 @@ func loadBroker(path, filesDir string) (*Broker, error) { return nil, fmt.Errorf("config %s: %w", path, err) } var f brokerFile - if err := decode(data, &f, "client", "store", "secret", "key"); err != nil { + if err := decode(data, &f, "client", "store", "secret", "key", "logins"); err != nil { return nil, fmt.Errorf("config %s: %w", path, err) } b, err := newBroker(&f, filesDir) @@ -437,6 +439,7 @@ func newBroker(f *brokerFile, filesDir string) (*Broker, error) { Clients: make(map[string]Client), Stores: make(map[string]Store), Secrets: make(map[string]Secret), + Logins: make(map[string]Logins), Keys: make(map[string]Key), } var err error @@ -492,6 +495,9 @@ func newBroker(f *brokerFile, filesDir string) (*Broker, error) { if err := b.addSecrets(f.Secret); err != nil { return nil, err } + if err := b.addLogins(f.Logins); err != nil { + return nil, err + } knownHosts := b.KnownHostsFile if filesDir != "" { knownHosts = filepath.Join(filesDir, filepath.Base(knownHosts)) diff --git a/internal/config/diff.go b/internal/config/diff.go index eccc1a8..ca5fe84 100644 --- a/internal/config/diff.go +++ b/internal/config/diff.go @@ -43,7 +43,7 @@ func (c Change) String() string { } // groups is the order of the groups in the output. -var groups = []string{"broker", "client", "store", "secret", "key", "known_hosts"} +var groups = []string{"broker", "client", "store", "secret", "logins", "key", "known_hosts"} // Diff returns the changes from old to next, by group and then by name, // in a fixed order. No change means the two configs mean the same. @@ -53,6 +53,7 @@ func Diff(old, next *Broker) []Change { d.clients(old, next) d.stores(old, next) d.secrets(old, next) + d.logins(old, next) d.keys(old, next) d.knownHosts(old.KnownHosts, next.KnownHosts) d.unknown(old, next) @@ -275,6 +276,60 @@ func (d *differ) secrets(old, next *Broker) { } } +// logins compares the [logins.*] sections. A new or removed rule of an +// item is marked as widening: the item's rule replaces the collection's, +// and either one can be the looser (DESIGN.md section 21.2). +func (d *differ) logins(old, next *Broker) { + for _, name := range sortedUnion(old.Logins, next.Logins) { + o, inOld := old.Logins[name] + n, inNew := next.Logins[name] + what := "logins " + q(name) + switch { + case !inOld: + d.add("logins", name, true, "%s: new website logins of collection %s in store %s, %s", + what, q(n.Collection), q(n.Store), ruleText(n.Rule)) + for _, c := range n.Clients { + d.add("logins", name, true, "%s: client %s may now ask for a login", what, q(c)) + } + for _, id := range slices.Sorted(maps.Keys(n.Items)) { + d.add("logins", name, true, "%s: item %s has its own rule: %s", what, q(id), ruleText(n.Items[id].Rule)) + } + continue + case !inNew: + d.add("logins", name, false, "%s: removed", what) + continue + } + for _, p := range []struct{ key, old, new string }{ + {"store", o.Store, n.Store}, + {"collection", o.Collection, n.Collection}, + } { + if p.old != p.new { + d.add("logins", name, true, "%s: now other logins: %s changed from %s to %s", what, p.key, q(p.old), q(p.new)) + } + } + d.clientList("logins", name, what, "ask for a login", o.Clients, n.Clients) + d.rule("logins", name, what, o.Rule, n.Rule) + for _, id := range sortedUnion(o.Items, n.Items) { + oi, inO := o.Items[id] + ni, inN := n.Items[id] + iw := what + " item " + q(id) + switch { + case !inO: + d.add("logins", name, true, "%s: has its own rule now, in place of the collection's: %s", iw, ruleText(ni.Rule)) + for _, c := range ni.Clients { + d.add("logins", name, !slices.Contains(o.Clients, c), "%s: client %s may ask for it", iw, q(c)) + } + case !inN: + d.add("logins", name, true, "%s: its own rule is removed; the collection's rule applies now: %s", + iw, ruleText(n.Rule)) + default: + d.clientList("logins", name, iw, "ask for it", oi.Clients, ni.Clients) + d.rule("logins", name, iw, oi.Rule, ni.Rule) + } + } + } +} + func (d *differ) keys(old, next *Broker) { for _, name := range sortedUnion(old.Keys, next.Keys) { o, inOld := old.Keys[name] @@ -517,6 +572,13 @@ func (d *differ) unknown(old, next *Broker) { x.Stores, y.Stores = common(old.Stores, next.Stores) x.Secrets, y.Secrets = common(old.Secrets, next.Secrets) x.Keys, y.Keys = common(old.Keys, next.Keys) + x.Logins, y.Logins = common(old.Logins, next.Logins) + for name, l := range x.Logins { + // Item rules that only one side has are compared in logins. + m := y.Logins[name] + l.Items, m.Items = common(l.Items, m.Items) + x.Logins[name], y.Logins[name] = l, m + } if (x.Ntfy == nil) != (y.Ntfy == nil) { x.Ntfy, y.Ntfy = nil, nil // a change of the channel is compared above } @@ -543,8 +605,10 @@ var compared = map[reflect.Type][]string{ "ClientSecretFile"}, reflect.TypeFor[Secret](): {"Name", "Store", "ID", "Field", "Project", "Environment", "Path", "SecretName", "Clients"}, - reflect.TypeFor[Key](): {"Name", "File", "Clients", "Hosts"}, - reflect.TypeFor[Rule](): {"Ask", "Window", "Preapprove", "Standing", "Notify", "MaxPerDay", "Hours"}, + reflect.TypeFor[Key](): {"Name", "File", "Clients", "Hosts"}, + reflect.TypeFor[Logins](): {"Name", "Store", "Collection", "Clients"}, + reflect.TypeFor[LoginItemRule](): {"ID", "Clients"}, + reflect.TypeFor[Rule](): {"Ask", "Window", "Preapprove", "Standing", "Notify", "MaxPerDay", "Hours"}, } // zeroCompared zeros the fields in compared, in v and in each struct, diff --git a/internal/config/logins.go b/internal/config/logins.go new file mode 100644 index 0000000..695c18a --- /dev/null +++ b/internal/config/logins.go @@ -0,0 +1,138 @@ +package config + +import ( + "fmt" + "maps" + "slices" + "strings" +) + +// Logins is a [logins.NAME] section: the website logins of one Bitwarden +// collection (DESIGN.md section 21). +type Logins struct { + Name string + Store string // a name in Broker.Stores, of type bw + Collection string // the collection's ID, a UUID in lower case + Clients []string // the names in Broker.Clients that may ask for a login + Rule Rule + // Items are the rules of single items, by item ID in lower case. The + // rule of an item replaces the collection's rule completely. + Items map[string]LoginItemRule +} + +// LoginItemRule is a [[logins.NAME.items]] table: the rule of one item. +type LoginItemRule struct { + ID string // the item's ID, a UUID in lower case + Clients []string + Rule Rule +} + +// RuleFor returns the clients and the rule for the item id: the item's +// own rule when it has one, and else the collection's. Nothing is merged +// (owner, 2026-11-11). The broker calls it on each request, after it has +// found the item. An id that is not a UUID gets ok = false: the request +// must be denied, so that an ID in another form never falls back to the +// collection's rule. +func (l Logins) RuleFor(id string) (clients []string, rule Rule, ok bool) { + if !uuidPattern.MatchString(id) { + return nil, Rule{}, false + } + if r, found := l.Items[strings.ToLower(id)]; found { + return r.Clients, r.Rule, true + } + return l.Clients, l.Rule, true +} + +type ( + loginsSection struct { + Store string `toml:"store"` + Collection string `toml:"collection"` + Clients []string `toml:"clients"` + Items []loginItemSection `toml:"items"` + ruleKeys + } + loginItemSection struct { + ID string `toml:"id"` + Clients []string `toml:"clients"` + ruleKeys + } +) + +// addLogins checks the [logins.*] sections and adds them to b.Logins. +func (b *Broker) addLogins(m map[string]loginsSection) error { + collections := make(map[string]string) // collection ID -> section name + items := make(map[string]string) // item ID -> section name + for _, name := range slices.Sorted(maps.Keys(m)) { + if err := checkName("logins", name); err != nil { + return err + } + sec := sectionName("logins", name) + s := m[name] + if s.Store == "" { + return fmt.Errorf("%s: is missing; name a [store.*] section of type = \"bw\"", place(sec, "store")) + } + st, ok := b.Stores[s.Store] + if !ok { + return fmt.Errorf("%s: no [store.*] section has this name", place(sec, "store")) + } + if st.Type != StoreBW { + return fmt.Errorf(`%s: must name a store of type = "bw"; website logins come only from the Bitwarden `+ + `Password Manager (DESIGN.md section 21)`, place(sec, "store")) + } + if !uuidPattern.MatchString(s.Collection) { + return fmt.Errorf(`%s: must be the ID of the collection, a UUID such as "00000000-0000-0000-0000-000000000000"; `+ + `"bw list collections" shows it`, place(sec, "collection")) + } + col := strings.ToLower(s.Collection) + if other, ok := collections[col]; ok { + return fmt.Errorf("%s: %s has the same collection; one collection may be in one [logins.*] section only", + place(sec, "collection"), sectionName("logins", other)) + } + collections[col] = name + clients, rule, err := b.loginRule(sec, s.Clients, s.ruleKeys) + if err != nil { + return err + } + l := Logins{Name: name, Store: s.Store, Collection: col, Clients: clients, Rule: rule, + Items: make(map[string]LoginItemRule)} + for i, it := range s.Items { + isec := fmt.Sprintf("[[%s.items]] number %d", strings.Trim(sec, "[]"), i+1) + if !uuidPattern.MatchString(it.ID) { + return fmt.Errorf(`%s: must be the item's ID, a UUID such as "00000000-0000-0000-0000-000000000000"`, + place(isec, "id")) + } + id := strings.ToLower(it.ID) + if other, ok := items[id]; ok { + return fmt.Errorf("%s: %s has a rule for the same item; one item may have one rule", + place(isec, "id"), sectionName("logins", other)) + } + items[id] = name + c, r, err := b.loginRule(isec, it.Clients, it.ruleKeys) + if err != nil { + return err + } + l.Items[id] = LoginItemRule{ID: id, Clients: c, Rule: r} + } + b.Logins[name] = l + } + return nil +} + +// loginRule checks the clients and the rule of a [logins.*] section or of +// one of its items. ask = "never" is refused: a website login always +// needs a tap or a grant that came from one. +func (b *Broker) loginRule(sec string, names []string, k ruleKeys) ([]string, Rule, error) { + clients, err := b.clientList(sec, names) + if err != nil { + return nil, Rule{}, err + } + if k.Ask == string(AskNever) { + return nil, Rule{}, fmt.Errorf(`%s: "never" is not allowed for website logins; use "always" or "window"`, + place(sec, "ask")) + } + rule, err := parseRule(sec, k) + if err != nil { + return nil, Rule{}, err + } + return clients, rule, nil +} diff --git a/internal/config/logins_test.go b/internal/config/logins_test.go new file mode 100644 index 0000000..32b51f9 --- /dev/null +++ b/internal/config/logins_test.go @@ -0,0 +1,183 @@ +package config + +import ( + "slices" + "strings" + "testing" +) + +const ( + testCol = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d" + testCol2 = "1b2c3d4e-5f6a-4b7c-8d9e-0f1a2b3c4d5e" + testItem = "6F1E2D3C-4B5A-4987-8A6B-5C4D3E2F1A0B" + testItem2 = "7a2e3d4c-5b6a-4f98-9b7c-6d5e4f3a2b1c" +) + +// loginsTOML is a [logins.web] section with a looser rule for testItem +// (another client, a window) and a stricter one for testItem2. +const loginsTOML = `[logins.web] +store = "vault" +collection = "` + testCol + `" +clients = ["laptop"] +ask = "window" +window = "15m" +preapprove = true + +[[logins.web.items]] +id = "` + testItem + `" +clients = ["laptop", "backup-box"] +ask = "window" +window = "30m" + +[[logins.web.items]] +id = "` + testItem2 + `" +clients = ["backup-box"] +ask = "always" + +[key.deploy]` + +// loginsNoItems is loginsTOML with no item rules. +const loginsNoItems = `[logins.web] +store = "vault" +collection = "` + testCol + `" +clients = ["laptop"] +ask = "window" +window = "15m" +preapprove = true + +[key.deploy]` + +func addLoginsEdit(section string) edit { return edit{"[key.deploy]", section} } + +func TestLoginsConfig(t *testing.T) { + e := newBrokerEnv(t) + b, err := loadBroker(e.write(t, addLoginsEdit(loginsTOML)), "") + if err != nil { + t.Fatalf("loadBroker: %v", err) + } + l, ok := b.Logins["web"] + if !ok || l.Store != "vault" || l.Collection != testCol || !slices.Equal(l.Clients, []string{"laptop"}) || + l.Rule.Ask != AskWindow || !l.Rule.Preapprove || len(l.Items) != 2 { + t.Fatalf("logins = %+v", l) + } + // The collection's rule. + clients, rule, ok := l.RuleFor("8b3f4e5d-6c7b-4a09-8c8d-7e6f5a4b3c2d") + if !ok || !slices.Equal(clients, []string{"laptop"}) || rule.Ask != AskWindow || !rule.Preapprove { + t.Errorf("collection rule = %v %+v", clients, rule) + } + // A looser item rule wins completely: another client, a longer window, + // and no preapprove, because nothing is merged. + clients, rule, _ = l.RuleFor(strings.ToLower(testItem)) + if !slices.Equal(clients, []string{"laptop", "backup-box"}) || rule.Ask != AskWindow || rule.Preapprove || + rule.Window.Minutes() != 30 { + t.Errorf("looser item rule = %v %+v", clients, rule) + } + // A stricter item rule wins completely: laptop, in the collection's + // clients, is refused for it. + clients, rule, _ = l.RuleFor(strings.ToUpper(testItem2)) + if slices.Contains(clients, "laptop") || rule.Ask != AskAlways { + t.Errorf("stricter item rule = %v %+v", clients, rule) + } + // An ID in another form never falls back to the collection's rule. + for _, id := range []string{" " + testItem2, "{" + testItem2 + "}", "Example shop", ""} { + if c, _, ok := l.RuleFor(id); ok || c != nil { + t.Errorf("RuleFor(%q) = %v, %v", id, c, ok) + } + } +} + +func TestLoginsConfigRefused(t *testing.T) { + base := strings.TrimSuffix(loginsTOML, "[key.deploy]") + other := "\n[logins.other]\nstore = \"vault\"\ncollection = \"" + testCol2 + "\"\nclients = [\"laptop\"]\nask = \"always\"\n\n" + for _, c := range []struct { + name string + cfg string + want string + }{ + {"no store", strings.Replace(base, "store = \"vault\"\n", "", 1), "store: is missing"}, + {"unknown store", strings.Replace(base, "store = \"vault\"", "store = \"nope\"", 1), "no [store.*] section"}, + {"not a bw store", strings.Replace(base, "store = \"vault\"", "store = \"main\"", 1), `type = "bw"`}, + {"bad collection", strings.Replace(base, testCol, "agents", 1), "collection: must be the ID"}, + {"same collection twice", base + strings.Replace(other, testCol2, strings.ToUpper(testCol), 1), "same collection"}, + {"no clients", strings.Replace(base, "clients = [\"laptop\"]\nask = \"window\"\nwindow = \"15m\"", "ask = \"window\"\nwindow = \"15m\"", 1), "clients: is missing"}, + {"unknown client", strings.Replace(base, "clients = [\"laptop\"]", "clients = [\"phone\"]", 1), "clients"}, + {"never", strings.Replace(base, "ask = \"window\"\nwindow = \"15m\"\npreapprove = true", "ask = \"never\"", 1), `"never" is not allowed`}, + {"never for an item", strings.Replace(base, "ask = \"always\"", "ask = \"never\"", 1), `"never" is not allowed`}, + {"no ask", strings.Replace(base, "ask = \"window\"\nwindow = \"15m\"\npreapprove = true\n", "", 1), "ask: is missing"}, + {"bad item id", strings.Replace(base, testItem, "Example shop", 1), "[[logins.web.items]] number 1 id: must be the item's ID"}, + {"item twice", base + "[[logins.web.items]]\nid = \"" + strings.ToLower(testItem) + "\"\nclients = [\"laptop\"]\nask = \"always\"\n\n", "one item may have one rule"}, + {"item in two sections", base + other + "[[logins.other.items]]\nid = \"" + testItem2 + "\"\nclients = [\"laptop\"]\nask = \"always\"\n\n", "one item may have one rule"}, + {"unknown key", strings.Replace(base, "preapprove = true", "preapprove = true\nmatch = \"host\"", 1), "match"}, + {"unknown item key", strings.Replace(base, "ask = \"always\"", "ask = \"always\"\nurl = \"https://example.com\"", 1), "url"}, + } { + t.Run(c.name, func(t *testing.T) { + e := newBrokerEnv(t) + _, err := loadBroker(e.write(t, addLoginsEdit(c.cfg+"[key.deploy]")), "") + if err == nil || !strings.Contains(err.Error(), c.want) { + t.Fatalf("error = %v, want one with %q", err, c.want) + } + }) + } +} + +func TestDiffLogins(t *testing.T) { + added := addLoginsEdit(loginsTOML) + for _, c := range []struct { + diffCase + widens bool + }{ + {diffCase{name: "new logins", new: []edit{added}, want: `logins "web": client "laptop" may now ask for a login`}, true}, + {diffCase{name: "another collection", old: []edit{added}, new: []edit{{testCol, testCol2}}, + want: `logins "web": now other logins: collection changed`}, true}, + {diffCase{name: "an item rule removed", old: []edit{added}, + new: []edit{{"[[logins.web.items]]\nid = \"" + testItem2 + "\"\nclients = [\"backup-box\"]\nask = \"always\"\n", ""}}, + want: "its own rule is removed"}, true}, + {diffCase{name: "an item rule added", old: []edit{addLoginsEdit(loginsNoItems)}, + new: []edit{{"preapprove = true\n", "preapprove = true\n\n[[logins.web.items]]\nid = \"" + testItem + "\"\nclients = [\"laptop\"]\nask = \"always\"\n"}}, + want: "has its own rule now"}, true}, + {diffCase{name: "an item gets another client", old: []edit{added}, new: []edit{{"clients = [\"backup-box\"]\nask = \"always\"", "clients = [\"backup-box\", \"laptop\"]\nask = \"always\""}}, + want: `item "` + testItem2 + `": client "laptop" may now ask for it`}, true}, + {diffCase{name: "logins removed", old: []edit{added}, new: []edit{{loginsTOML, "[key.deploy]"}}, + want: `logins "web": removed`}, false}, + {diffCase{name: "an item's window", old: []edit{added}, new: []edit{{"window = \"30m\"", "window = \"1h\""}}, + want: `item "` + strings.ToLower(testItem) + `": window changed from 30m to 1h`}, true}, + } { + t.Run(c.name, func(t *testing.T) { + changes := c.run(t) + ch, ok := findChange(changes, c.want) + if !ok { + t.Fatalf("no change with %q in %v", c.want, changes) + } + if ch.Widens != c.widens { + t.Errorf("%q: widens = %v, want %v", ch.Text, ch.Widens, c.widens) + } + if _, ok := findChange(changes, "does not know"); ok { + t.Errorf("a logins change is not known to config-diff: %v", changes) + } + }) + } +} + +// TestReloadRefusesLoginsChange: until the broker keeps login grants per +// item, a change of [logins.*] needs a restart. +func TestReloadRefusesLoginsChange(t *testing.T) { + e := newBrokerEnv(t) + old, err := loadBroker(e.write(t, addLoginsEdit(loginsTOML)), "") + if err != nil { + t.Fatal(err) + } + next, err := loadBroker(e.write(t, addLoginsEdit(strings.Replace(loginsTOML, `window = "30m"`, `window = "1h"`, 1))), "") + if err != nil { + t.Fatal(err) + } + if err := old.ReloadFixed(next); err == nil || !strings.Contains(err.Error(), "[logins.*]") { + t.Fatalf("ReloadFixed = %v", err) + } + same, err := loadBroker(e.write(t, addLoginsEdit(loginsTOML)), "") + if err != nil { + t.Fatal(err) + } + if err := old.ReloadFixed(same); err != nil { + t.Fatalf("ReloadFixed of the same logins = %v", err) + } +} diff --git a/internal/config/reload.go b/internal/config/reload.go index d1e6bd9..dc95e30 100644 --- a/internal/config/reload.go +++ b/internal/config/reload.go @@ -39,6 +39,9 @@ func (b *Broker) ReloadFixed(next *Broker) error { {"[preapprove]", b.Preapprove, next.Preapprove}, {"[standing]", b.Standing, next.Standing}, {"[store.*]", b.Stores, next.Stores}, + // Until the broker serves logins and keeps their grants per item + // (DESIGN.md section 21.7), a change of them needs a restart. + {"[logins.*]", b.Logins, next.Logins}, } parts = append(parts, part{"the config", x, y}) // a part that is not named above for _, p := range parts { diff --git a/internal/loginmatch/loginmatch.go b/internal/loginmatch/loginmatch.go new file mode 100644 index 0000000..453ad54 --- /dev/null +++ b/internal/loginmatch/loginmatch.go @@ -0,0 +1,240 @@ +// Package loginmatch decides if a page URL that a client sends matches a +// URI of a Bitwarden login item (DESIGN.md section 21). +// +// It follows the match type of each URI, as Bitwarden does: base domain +// (also when the URI has no match type), host, starts with, and exact. A +// regular expression and "never" do not match. Equivalent domains of +// Bitwarden are not used. The page URL must be https. +// +// "Starts with" and "exact" are stricter than in Bitwarden: the URI must +// be https and have the same host and port as the page. +// +// The page URL is claimed by the client: the broker cannot check that the +// browser is on that page (THREAT-MODEL.md T43). +package loginmatch + +import ( + "errors" + "net" + "net/url" + "strconv" + "strings" + + "golang.org/x/net/publicsuffix" +) + +// MaxURL is the longest page URL that a client may send. +const MaxURL = 2048 + +// Type is the match type of a URI, as the bw CLI writes it in +// login.uris[].match. +type Type int + +// The match types of Bitwarden. +const ( + Domain Type = 0 + Host Type = 1 + StartsWith Type = 2 + Exact Type = 3 + Regex Type = 4 + Never Type = 5 +) + +// The errors of ParsePage. They never hold the URL: it is text the client chose. +var ( + ErrPageURL = errors.New("the page URL is not a valid absolute URL; give the full URL of the login page, for example https://example.com/sign-in") + ErrHTTPS = errors.New("the page URL is not https; nodkey hands out logins only for https pages (DESIGN.md section 21)") + ErrHost = errors.New("the page URL has no valid host name; give the host as plain ASCII (punycode for other letters), with no user name, password or trailing dot") + ErrTooLong = errors.New("the page URL is longer than 2048 bytes; give the URL of the login page only") + ErrNoSuffix = errors.New("the host of the page URL is a public suffix; give the URL of the site itself") +) + +// Page is a page URL that a client sent, after its checks. +type Page struct { + full string // the URL with no fragment + origin string // https://host[:port] + host string // lower case, no port + port string // "" for 443 + base string // the base domain of host +} + +// Origin returns "https://host" or "https://host:port". +func (p Page) Origin() string { return p.origin } + +// URL returns the page URL with no fragment. +func (p Page) URL() string { return p.full } + +// ParsePage checks a page URL that a client sent. +func ParsePage(s string) (Page, error) { + if len(s) > MaxURL { + return Page{}, ErrTooLong + } + for i := 0; i < len(s); i++ { + if s[i] <= 0x20 || s[i] >= 0x7f { + return Page{}, ErrPageURL + } + } + u, err := url.Parse(s) + if err != nil || u.Opaque != "" || u.Scheme == "" { + return Page{}, ErrPageURL + } + if u.Scheme != "https" { + return Page{}, ErrHTTPS + } + if u.User != nil { + return Page{}, ErrHost + } + host, port, ok := hostPort(u) + if !ok { + return Page{}, ErrHost + } + if port == "443" { + port = "" + } + base, ok := baseDomain(host) + if !ok { + return Page{}, ErrNoSuffix + } + u.Fragment, u.RawFragment = "", "" + u.Host = host + if strings.Contains(host, ":") { + u.Host = "[" + host + "]" + } + if port != "" { + u.Host = net.JoinHostPort(host, port) + } + origin := "https://" + u.Host + return Page{full: u.String(), origin: origin, host: host, port: port, base: base}, nil +} + +// hostPort returns the lower case host and the port of u. It refuses an +// empty host, a trailing dot, a host that is not plain ASCII letters, +// digits, dots and dashes (or an IP address), and a bad port. +func hostPort(u *url.URL) (string, string, bool) { + host := strings.ToLower(u.Hostname()) + port := u.Port() + if strings.HasSuffix(u.Host, ":") { + return "", "", false + } + if port != "" { + n, err := strconv.Atoi(port) + if err != nil || n < 1 || n > 65535 || strconv.Itoa(n) != port { + return "", "", false + } + } + if host == "" || len(host) > 253 { + return "", "", false + } + if ip := net.ParseIP(host); ip != nil { + if strings.Contains(host, "%") { + return "", "", false + } + return ip.String(), port, true + } + if strings.HasSuffix(host, ".") || strings.HasPrefix(host, ".") || strings.Contains(host, "..") { + return "", "", false + } + labels := strings.Split(host, ".") + // A last label of digits, or of 0x and hex digits, is an IPv4 address + // for a browser (https://192.0.2.01/, https://3221225985/), but not + // for net.ParseIP. Refuse it: the origin would not be where the + // browser connects. + if last := labels[len(labels)-1]; strings.HasPrefix(last, "0x") || strings.Trim(last, "0123456789") == "" { + return "", "", false + } + for _, label := range labels { + if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' { + return "", "", false + } + for i := 0; i < len(label); i++ { + c := label[i] + if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '-' { + return "", "", false + } + } + } + return host, port, true +} + +// baseDomain returns the registrable domain of host: the public suffix and +// one label more. An IP address and a name with no dot are their own base +// domain. A host that is itself a public suffix has none. +func baseDomain(host string) (string, bool) { + if net.ParseIP(host) != nil || !strings.Contains(host, ".") { + return host, true + } + d, err := publicsuffix.EffectiveTLDPlusOne(host) + if err != nil || d == "" { + return "", false + } + return d, true +} + +// Match reports if the page matches one URI of an item. uri is +// login.uris[].uri and match is login.uris[].match (nil when Bitwarden +// has none: then the base domain is used). +func Match(p Page, uri string, match *int) bool { + if p.origin == "" || uri == "" || len(uri) > MaxURL { + return false + } + t := Domain + if match != nil { + t = Type(*match) + } + switch t { + case Domain, Host: + host, port, ok := itemHost(uri) + if !ok { + return false + } + if t == Host { + return host == p.host && port == p.port + } + base, ok := baseDomain(host) + return ok && base == p.base + case StartsWith, Exact: + // Stricter than Bitwarden: the URI must be https, with the same + // host and port as the page, so that "https://example.com" does + // not match "https://example.com.example.net/" (T43). + if !strings.HasPrefix(strings.ToLower(uri), "https://") { + return false + } + host, port, ok := itemHost(uri) + if !ok || host != p.host || port != p.port { + return false + } + if t == Exact { + return p.full == uri + } + return strings.HasPrefix(p.full, uri) + default: + // Regex, Never and any unknown type do not match. + return false + } +} + +// itemHost reads the host and port of a URI of an item. A URI with no +// scheme is read as http://, as Bitwarden does. Only http and https URIs +// have a host here; androidapp:// and others do not match a page. +func itemHost(uri string) (string, string, bool) { + s := strings.TrimSpace(uri) + if !strings.Contains(s, "://") { + s = "http://" + s + } + u, err := url.Parse(s) + if err != nil || u.Opaque != "" { + return "", "", false + } + scheme := strings.ToLower(u.Scheme) + if scheme != "http" && scheme != "https" { + return "", "", false + } + host, port, ok := hostPort(u) + if !ok { + return "", "", false + } + if (scheme == "https" && port == "443") || (scheme == "http" && port == "80") { + port = "" + } + return host, port, true +} diff --git a/internal/loginmatch/loginmatch_test.go b/internal/loginmatch/loginmatch_test.go new file mode 100644 index 0000000..7e64b53 --- /dev/null +++ b/internal/loginmatch/loginmatch_test.go @@ -0,0 +1,164 @@ +package loginmatch + +import ( + "errors" + "strconv" + "strings" + "testing" +) + +func ip(n int) *int { return &n } + +func mustPage(t *testing.T, s string) Page { + t.Helper() + p, err := ParsePage(s) + if err != nil { + t.Fatalf("ParsePage(%q): %v", s, err) + } + return p +} + +func TestParsePage(t *testing.T) { + cases := []struct{ in, origin, full string }{ + {"https://example.com/login", "https://example.com", "https://example.com/login"}, + {"https://Example.COM:443/a?b=c#frag", "https://example.com", "https://example.com/a?b=c"}, + {"https://shop.example.co.uk:8443/", "https://shop.example.co.uk:8443", "https://shop.example.co.uk:8443/"}, + {"https://192.0.2.10/", "https://192.0.2.10", "https://192.0.2.10/"}, + {"https://[2001:db8::1]:8443/x", "https://[2001:db8::1]:8443", "https://[2001:db8::1]:8443/x"}, + {"https://xn--bcher-kva.example/", "https://xn--bcher-kva.example", "https://xn--bcher-kva.example/"}, + } + for _, c := range cases { + p := mustPage(t, c.in) + if p.Origin() != c.origin || p.URL() != c.full { + t.Errorf("%s: got %s %s", c.in, p.Origin(), p.URL()) + } + } +} + +func TestParsePageRefused(t *testing.T) { + cases := []struct { + in string + want error + }{ + {"http://example.com/", ErrHTTPS}, + {"HTTP://example.com/", ErrHTTPS}, + {"ftp://example.com/", ErrHTTPS}, + {"javascript:alert(1)", ErrPageURL}, + {"example.com/login", ErrPageURL}, + {"/login", ErrPageURL}, + {"", ErrPageURL}, + {"https://example.com/a b", ErrPageURL}, + {"https://bรผcher.example/", ErrPageURL}, + {"https://example.com/\x00", ErrPageURL}, + {"https://alice:pw@example.com/", ErrHost}, + {"https://example.com./", ErrHost}, + {"https://.example.com/", ErrHost}, + {"https:///path", ErrHost}, + {"https://exa_mple.com/", ErrHost}, + {"https://-example.com/", ErrHost}, + {"https://example.com:0/", ErrHost}, + {"https://example.com:65536/", ErrHost}, + {"https://example.com:/", ErrHost}, + {"https://example.com:0443/", ErrHost}, + {"https://co.uk/", ErrNoSuffix}, + {"https://192.0.2.01/", ErrHost}, + {"https://0300.0.2.1/", ErrHost}, + {"https://3221225985/", ErrHost}, + {"https://example.0x1f/", ErrHost}, + {"https://github.io/", ErrNoSuffix}, + {"https://example.com/" + strings.Repeat("a", MaxURL), ErrTooLong}, + } + for _, c := range cases { + _, err := ParsePage(c.in) + if !errors.Is(err, c.want) { + t.Errorf("ParsePage(%.40q): got %v, want %v", c.in, err, c.want) + } + if err != nil && c.in != "" && strings.Contains(err.Error(), c.in) { + t.Errorf("error holds the URL: %v", err) + } + } +} + +func TestMatch(t *testing.T) { + cases := []struct { + page, uri string + match *int + want bool + }{ + // Base domain, also with no match type. + {"https://login.example.com/", "https://example.com", nil, true}, + {"https://example.com/", "https://www.example.com/x", nil, true}, + {"https://example.com/", "example.com", nil, true}, + {"https://example.com:8443/", "https://example.com", ip(0), true}, + {"https://example.org/", "https://example.com", nil, false}, + {"https://example.com.evil.example/", "https://example.com", nil, false}, + {"https://a.example.co.uk/", "https://b.example.co.uk", nil, true}, + {"https://example.co.uk/", "https://other.co.uk", nil, false}, + {"https://alice.github.io/", "https://bob.github.io", nil, false}, + {"https://192.0.2.10/", "https://192.0.2.10:8443/", nil, true}, + {"https://192.0.2.10/", "https://198.51.100.10/", nil, false}, + {"https://192.0.2.10/", "https://10.0.2.10/", nil, false}, + {"https://example.com/", "androidapp://com.example", nil, false}, + {"https://example.com/", "", nil, false}, + {"https://example.com/", "https://co.uk", nil, false}, + // Host: host and port. + {"https://example.com/", "https://example.com/login", ip(1), true}, + {"https://example.com/", "example.com", ip(1), true}, + {"https://login.example.com/", "https://example.com", ip(1), false}, + {"https://example.com:8443/", "https://example.com", ip(1), false}, + {"https://example.com:8443/", "https://example.com:8443", ip(1), true}, + // Starts with and exact. + {"https://example.com/login?x=1", "https://example.com/login", ip(2), true}, + {"https://example.com/logout", "https://example.com/login", ip(2), false}, + {"https://example.com.evil.example/", "https://example.com", ip(2), false}, + {"https://example.com:8443/", "https://example.com", ip(2), false}, + {"https://example.com/", "http://example.com/", ip(2), false}, + {"https://example.com/", "example.com/", ip(2), false}, + {"https://example.com/", "HTTPS://example.com/", ip(2), false}, + {"https://example.com/x", "https://example.com", ip(2), true}, + {"https://example.com:8443/x", "https://example.com:8443/", ip(2), true}, + {"https://example.com/", "http://example.com/", ip(3), false}, + {"https://example.com/login", "https://example.com/login", ip(3), true}, + {"https://example.com/login?x=1", "https://example.com/login", ip(3), false}, + {"https://example.com/login#a", "https://example.com/login", ip(3), true}, + // Regex, never and unknown types never match. + {"https://example.com/", ".*", ip(4), false}, + {"https://example.com/", "https://example.com", ip(4), false}, + {"https://example.com/", "https://example.com", ip(5), false}, + {"https://example.com/", "https://example.com", ip(6), false}, + {"https://example.com/", "https://example.com", ip(-1), false}, + } + for _, c := range cases { + p := mustPage(t, c.page) + if got := Match(p, c.uri, c.match); got != c.want { + m := "nil" + if c.match != nil { + m = strconv.Itoa(*c.match) + } + t.Errorf("Match(%s, %s, %s) = %v, want %v", c.page, c.uri, m, got, c.want) + } + } +} + +func TestZeroPageMatchesNothing(t *testing.T) { + if Match(Page{}, "https://example.com", nil) { + t.Fatal("zero page matched") + } +} + +func FuzzParsePage(f *testing.F) { + f.Add("https://example.com/login", "example.com") + f.Fuzz(func(t *testing.T, page, uri string) { + p, err := ParsePage(page) + if err != nil { + return + } + if !strings.HasPrefix(p.Origin(), "https://") || !strings.HasPrefix(p.URL(), p.Origin()) { + t.Fatalf("bad page %q -> %q %q", page, p.Origin(), p.URL()) + } + for m := -1; m < 7; m++ { + _ = Match(p, uri, &m) + } + _ = Match(p, uri, nil) + }) +} diff --git a/internal/ntfy/ntfy.go b/internal/ntfy/ntfy.go index b8e348d..287d96f 100644 --- a/internal/ntfy/ntfy.go +++ b/internal/ntfy/ntfy.go @@ -213,13 +213,13 @@ func (a *Approver) Ask(ctx context.Context, p approval.Prompt) (approval.Shown, } // The text, and the whole publish body with the buttons, must fit. b, err := fitBodyWith(p, false, limit, func(b string) bool { - pm.Message = b + "\n" + expiryLine(p) + pm.Message = withExpiry(b, p) return fitsPublish(pm) }) if err != nil { return approval.Shown{}, err } - msg := b + "\n" + expiryLine(p) + msg := withExpiry(b, p) pm.Message = msg if err := a.add(p.RequestID, e); err != nil { return approval.Shown{}, err diff --git a/internal/ntfy/text.go b/internal/ntfy/text.go index 6ba3091..e66911c 100644 --- a/internal/ntfy/text.go +++ b/internal/ntfy/text.go @@ -96,7 +96,15 @@ func checkPrompt(p approval.Prompt, notice bool) error { case p.WindowMinutes < 0 || p.Uses < 0 || p.UsesLeft < 0: return bad("a number") } + if err := checkLoginPrompt(p, notice); err != nil { + return err + } switch p.Kind { + case audit.KindWebLogin: + if p.Login == nil || p.Login.For != 0 || len(p.Secrets) != 0 || p.Key != "" || len(p.Hosts) != 0 || + p.HostKey != "" || p.RemoteUser != "" || !p.GrantEnds.IsZero() { + return bad("the fields of a website login") + } case audit.KindSecrets: if len(p.Secrets) == 0 { return bad("no secrets") @@ -110,6 +118,15 @@ func checkPrompt(p approval.Prompt, notice bool) error { return bad("the fields of an SSH grant") } case audit.KindPreapprove, audit.KindStanding: + if p.Kind == audit.KindPreapprove && p.Login != nil { + if p.Uses != 1 || !p.From.IsZero() || !p.Until.IsZero() || p.Login.For != approval.LoginPreapproveTime || + len(p.Secrets) != 0 || p.Key != "" || len(p.Hosts) != 0 || p.RemoteUser != "" || p.HostKey != "" || + p.Via != "" || p.WindowMinutes != 0 || !p.GrantEnds.IsZero() || + (notice != (p.GrantID != "")) || (notice && p.UsesLeft != 1) || (!notice && (p.UsesLeft != 0 || !p.Once)) { + return bad("the fields of a login pre-approval") + } + break + } if p.Uses < 1 || p.From.IsZero() || !p.From.Before(p.Until) { return bad("the fields of a scheduled grant") } @@ -131,6 +148,38 @@ func checkPrompt(p approval.Prompt, notice bool) error { return nil } +// loginOriginPattern is an https origin: a host name or an IP address, +// and perhaps a port. The core made it from a checked page URL. +var loginOriginPattern = regexp.MustCompile(`^https://([a-z0-9][a-z0-9.-]{0,252}|\[[0-9a-f:]{2,45}\])(:[0-9]{1,5})?$`) + +// maxLoginText is the most runes of an item name or a user name. +const maxLoginText = 128 + +// checkLoginPrompt checks the login part of p. The item name and the user +// name come from the vault: the core cleaned them, and this checks that +// they are clean, so a message never shows a line break or a direction +// mark from the vault. +func checkLoginPrompt(p approval.Prompt, notice bool) error { + bad := func(what string) error { return errors.New("ntfy: the prompt is not valid: " + what) } + l := p.Login + if l == nil { + if p.Kind == audit.KindWebLogin { + return bad("a website login without its login") + } + return nil + } + if p.Kind != audit.KindWebLogin && p.Kind != audit.KindPreapprove { + return bad("a login outside a website login") + } + clean := func(s string) bool { + return utf8.RuneCountInString(s) <= maxLoginText && claim.Line(s, maxLoginText+1) == s + } + if l.Name == "" || !clean(l.Name) || !clean(l.Username) || !loginOriginPattern.MatchString(l.Origin) || l.For < 0 { + return bad("the login") + } + return nil +} + // title returns the first line of a message or a notice of p. func title(p approval.Prompt, notice bool) string { icon, name := "๐Ÿ”‘", "Secrets" @@ -143,6 +192,8 @@ func title(p approval.Prompt, notice bool) string { icon, name = "๐Ÿ—“", "Pre-approval" case audit.KindStanding: icon, name = "๐Ÿ—“", "Standing grant" + case audit.KindWebLogin: + icon, name = "๐ŸŒ", "Website login" } if notice { icon = "๐Ÿ””" @@ -208,9 +259,18 @@ func body(p approval.Prompt, notice bool, c caps) string { verified("remote user", p.RemoteUser) } switch p.Kind { + case audit.KindWebLogin: + verified("login", p.Login.Name) + verified("username", p.Login.Username) case audit.KindSSHGrant: verified("grants end", p.GrantEnds.Format(clockFormat)+" ("+strconv.Itoa(p.WindowMinutes)+" min)") case audit.KindPreapprove: + if p.Login != nil { + verified("login", p.Login.Name) + verified("username", p.Login.Username) + line("allows: one login in the next " + strconv.Itoa(int(p.Login.For/time.Second)) + " s after the tap") + break + } verified("uses", strconv.Itoa(p.Uses)) verified("from", p.From.Format(dateTimeFormat)) verified("until", p.Until.Format(dateTimeFormat)) @@ -227,6 +287,7 @@ func body(p approval.Prompt, notice bool, c caps) string { label, value string limit int }{ + {"page", loginPage(p), c.dir}, {"as", p.Claim.Vars, c.vars}, {"command", p.Claim.Command, c.command}, {"in", p.Claim.Dir, c.dir}, @@ -247,6 +308,14 @@ func body(p approval.Prompt, notice bool, c caps) string { return b.String() } +// loginPage returns the claimed origin of a website login, or "". +func loginPage(p approval.Prompt) string { + if p.Login == nil { + return "" + } + return p.Login.Origin +} + // fitBodyWith returns the body of p in at most limit bytes, and, if fits is // not nil, so that fits says yes (it checks the whole publish body). It cuts the // claimed fields shorter as needed, never the verified ones: the person @@ -260,6 +329,17 @@ func fitBodyWith(p approval.Prompt, notice bool, limit int, fits func(string) bo return "", errTooLong } +// withExpiry adds the expiry line to the text b of a message that waits +// for an answer. The message of a login pre-approval has none: its time +// starts at the tap, and a limit for the tap would read as the time of +// the login. +func withExpiry(b string, p approval.Prompt) string { + if p.Login != nil && p.Login.For != 0 { + return b + } + return b + "\n" + expiryLine(p) +} + // expiryLine is the last line of a message that waits for an answer. func expiryLine(p approval.Prompt) string { secs := int64(p.TimeLeft.Round(time.Second) / time.Second) @@ -327,6 +407,9 @@ func resultLine(p approval.Prompt, e approval.Ending) string { return "๐Ÿ‘ approved at " + at + ", for " + strconv.Itoa(p.Uses) + " use(s) in each window until " + p.Until.Format(dateTimeFormat) case audit.KindPreapprove: + if p.Login != nil { + return "๐Ÿ‘ approved at " + at + ": one login in the next " + strconv.Itoa(int(p.Login.For/time.Second)) + " s" + } return "๐Ÿ‘ approved at " + at + ", for " + strconv.Itoa(p.Uses) + " use(s) until " + p.Until.Format(dateTimeFormat) } diff --git a/internal/ntfy/weblogin_test.go b/internal/ntfy/weblogin_test.go new file mode 100644 index 0000000..a53f20e --- /dev/null +++ b/internal/ntfy/weblogin_test.go @@ -0,0 +1,121 @@ +package ntfy + +import ( + "strings" + "testing" + "time" + + "github.com/code6x/nodkey/internal/approval" + "github.com/code6x/nodkey/internal/audit" +) + +func webLoginPrompt(t *testing.T) approval.Prompt { + return approval.Prompt{ + RequestID: newRequestID(t), ShortCode: "w4x8", Kind: audit.KindWebLogin, Client: "laptop", + Login: &approval.LoginPrompt{Name: "Example shop", Username: "alice@example.com", Origin: "https://example.com"}, + Claim: approval.Claim{Reason: "check the order"}, + Expires: time.Date(2026, 10, 14, 14, 5, 40, 0, time.UTC), + TimeLeft: 120 * time.Second, Once: true, WindowMinutes: 15, + } +} + +func webPreapprovePrompt(t *testing.T) approval.Prompt { + p := webLoginPrompt(t) + p.Kind, p.Uses, p.WindowMinutes = audit.KindPreapprove, 1, 0 + p.Login.For = approval.LoginPreapproveTime + return p +} + +func TestWebLoginText(t *testing.T) { + p := webLoginPrompt(t) + if err := checkPrompt(p, false); err != nil { + t.Fatal(err) + } + if got := title(p, false); got != "๐ŸŒ Website login ยท request w4x8" { + t.Errorf("title %q", got) + } + want := "โœ… machine: laptop\nโœ… login: Example shop\nโœ… username: alice@example.com\n" + + claimedHead + "\npage: https://example.com\nreason: check the order" + if got := body(p, false, fullCaps); got != want { + t.Errorf("body:\n%s\nwant:\n%s", got, want) + } + if got := withExpiry(want, p); !strings.HasSuffix(got, "expires 14:05:40 (120 s)") { + t.Errorf("message:\n%s", got) + } +} + +func TestWebLoginPreapproveText(t *testing.T) { + p := webPreapprovePrompt(t) + if err := checkPrompt(p, false); err != nil { + t.Fatal(err) + } + if got := title(p, false); got != "๐Ÿ—“ Pre-approval ยท request w4x8" { + t.Errorf("title %q", got) + } + b := body(p, false, fullCaps) + want := "โœ… machine: laptop\nโœ… login: Example shop\nโœ… username: alice@example.com\n" + + "allows: one login in the next 60 s after the tap\n" + + claimedHead + "\npage: https://example.com\nreason: check the order" + if b != want { + t.Errorf("body:\n%s\nwant:\n%s", b, want) + } + if got := withExpiry(b, p); got != b || strings.Contains(got, "expire") { + t.Errorf("the message shows a time limit for the tap:\n%s", got) + } + // The other kinds keep theirs. + s := approval.Prompt{Expires: p.Expires, TimeLeft: p.TimeLeft} + if got := withExpiry("x", s); !strings.Contains(got, "expires ") { + t.Errorf("a message lost its expiry: %q", got) + } + if got := resultLine(p, approval.Ending{Answer: audit.AnswerApproveOnce, At: p.Expires}); !strings.Contains(got, "one login in the next 60 s") { + t.Errorf("result line %q", got) + } +} + +func TestWebLoginBadPrompts(t *testing.T) { + edits := map[string]func(p *approval.Prompt){ + "no login": func(p *approval.Prompt) { p.Login = nil }, + "no name": func(p *approval.Prompt) { p.Login.Name = "" }, + "RTL in the name": func(p *approval.Prompt) { p.Login.Name = "a\u202eb" }, + "newline in the name": func(p *approval.Prompt) { p.Login.Name = "a\nโœ… machine: x" }, + "newline in the user": func(p *approval.Prompt) { p.Login.Username = "a\nb" }, + "long name": func(p *approval.Prompt) { p.Login.Name = strings.Repeat("x", 129) }, + "http origin": func(p *approval.Prompt) { p.Login.Origin = "http://example.com" }, + "origin with a path": func(p *approval.Prompt) { p.Login.Origin = "https://example.com/a" }, + "secrets": func(p *approval.Prompt) { p.Secrets = []string{"a"} }, + "for in a login": func(p *approval.Prompt) { p.Login.For = time.Minute }, + } + for name, ed := range edits { + t.Run(name, func(t *testing.T) { + p := webLoginPrompt(t) + ed(&p) + if checkPrompt(p, false) == nil { + t.Error("the prompt was taken") + } + }) + } + pre := map[string]func(p *approval.Prompt){ + "two uses": func(p *approval.Prompt) { p.Uses = 2 }, + "a span": func(p *approval.Prompt) { p.Until = time.Now() }, + "another time": func(p *approval.Prompt) { p.Login.For = time.Hour }, + "no time": func(p *approval.Prompt) { p.Login.For = 0 }, + "secrets": func(p *approval.Prompt) { p.Secrets = []string{"a"} }, + "a window": func(p *approval.Prompt) { p.WindowMinutes = 15 }, + } + for name, ed := range pre { + t.Run("pre-approval "+name, func(t *testing.T) { + p := webPreapprovePrompt(t) + ed(&p) + if checkPrompt(p, false) == nil { + t.Error("the prompt was taken") + } + }) + } + p := approval.Prompt{ + RequestID: newRequestID(t), ShortCode: "k3f9", Kind: audit.KindSecrets, Client: "laptop", + Secrets: []string{"a"}, Login: webLoginPrompt(t).Login, Expires: time.Now(), TimeLeft: time.Second, + } + if checkPrompt(p, false) == nil { + t.Error("a login in a secrets prompt was taken") + } +} diff --git a/internal/store/bwlogin.go b/internal/store/bwlogin.go new file mode 100644 index 0000000..766374e --- /dev/null +++ b/internal/store/bwlogin.go @@ -0,0 +1,380 @@ +package store + +import ( + "context" + "errors" + "fmt" + "io" +) + +// Limits of the login fields that nodkey reads from bw (DESIGN.md +// section 21). An answer over a limit is ErrBadAnswer: nodkey never cuts +// a field. +const ( + maxLoginName = 1024 // bytes of an item name or a username + maxLoginURI = 2048 // bytes of one URI + maxLoginURIs = 100 // URIs of one item + maxLoginItems = 500 // items in one collection; the answer must also fit in maxStdout + maxCollectionIDs = 100 // collections of one item + bwTypeLogin = 1 // "type" of a login item + stepListItems = "bw list items" +) + +// ErrNotLogin is returned for an item that is not a login item. +var ErrNotLogin = errors.New("the item is not a login item") + +// LoginStore is a store that hands out website logins from a collection +// (DESIGN.md section 21). Only the bw store is one. +type LoginStore interface { + // ListLogins runs "bw sync --force" and returns the login items of + // the collection, with no password and no TOTP seed. Items in the + // trash, archived items, items that are not logins and items whose + // collectionIds do not hold the collection are left out. + ListLogins(ctx context.Context, collection string) ([]LoginItem, error) + // FetchLogin runs "bw sync --force" and returns the login item id, + // with its password and its TOTP seed. An item in the trash is + // ErrTrashed, an archived item ErrArchived, an item that is not a + // login ErrNotLogin, and an item with no password ErrNoValue. The + // caller must Clear the login. + FetchLogin(ctx context.Context, id string) (Login, error) +} + +// LoginURI is one URI of a login item: login.uris[].uri, and +// login.uris[].match (nil when the item has none). +type LoginURI struct { + URI string + Match *int +} + +// LoginItem is what nodkey reads from a login item, without its secrets. +type LoginItem struct { + ID string + Name string + Username string + URIs []LoginURI + Collections []string // collectionIds + // Reprompt is true when the item asks for the master password again + // in Bitwarden's apps ("reprompt": 1). The broker then asks for a tap + // for each login (DESIGN.md section 21.3). + Reprompt bool +} + +// Login is a login item with its password and its TOTP seed. TOTP is +// empty when the item has none. Login hides both in every format. +type Login struct { + LoginItem + Password Value + TOTP Value +} + +// Clear overwrites the password and the TOTP seed. +func (l *Login) Clear() { + l.Password.Clear() + l.TOTP.Clear() + l.Password, l.TOTP = Value{}, Value{} +} + +// String names the item, without its secrets. +func (l Login) String() string { return fmt.Sprintf("login %s %s", l.ID, hidden) } + +// GoString names the item, without its secrets. +func (l Login) GoString() string { return l.String() } + +// Format writes String for every verb. +func (l Login) Format(f fmt.State, _ rune) { _, _ = io.WriteString(f, l.String()) } + +// ListLogins implements LoginStore. +func (s *bwStore) ListLogins(ctx context.Context, collection string) ([]LoginItem, error) { + if !isUUID(collection) { + return nil, stepError(s.run.store, stepListItems, ErrBadID) + } + out, err := s.synced(ctx, stepListItems, "list", "items", "--collectionid", collection) + if err != nil { + return nil, err + } + defer clear(out) // it holds every password and TOTP seed of the collection + items, err := parseBWLoginList(out, collection) + if err != nil { + return nil, stepError(s.run.store, stepListItems, err) + } + return items, nil +} + +// FetchLogin implements LoginStore. +func (s *bwStore) FetchLogin(ctx context.Context, id string) (Login, error) { + if !isUUID(id) { + return Login{}, stepError(s.run.store, stepGetItem, ErrBadID) + } + out, err := s.synced(ctx, stepGetItem, "get", "item", id) + if err != nil { + return Login{}, err + } + defer clear(out) + l, err := parseBWLogin(out, id) + if err != nil { + return Login{}, stepError(s.run.store, stepGetItem, err) + } + return l, nil +} + +// synced takes the store's turn, unlocks if needed, runs +// "bw sync --force" and then bw with args, as Fetch does. The caller must +// clear the answer. +func (s *bwStore) synced(ctx context.Context, step string, args ...string) ([]byte, error) { + if err := acquire(ctx, s.lock); err != nil { + return nil, stepError(s.run.store, step, err) + } + defer s.release() + if s.closed { + return nil, stepError(s.run.store, step, ErrClosed) + } + if s.session.Bytes() == nil { + if err := s.unlock(ctx); err != nil { + return nil, err + } + } + out, err := s.runWithSession(ctx, stepSync, "sync", "--force") + if err != nil { + return nil, err + } + clear(out) + return s.runWithSession(ctx, step, args...) +} + +// loginFields is what parseBWLoginItem read from one item. +type loginFields struct { + item LoginItem + typ int + typeSet bool + trashed, archived bool + password, totp []byte + wantSecrets bool +} + +func (f *loginFields) clearSecrets() { + clear(f.password) + clear(f.totp) + f.password, f.totp = nil, nil +} + +// readLoginItem reads one item object. It keeps "id", "type", "name", +// "reprompt", "deletedDate", "archivedDate", "collectionIds", "login.username" and +// "login.uris[].uri" and ".match". It keeps "login.password" and +// "login.totp" only when f.wantSecrets; else it checks and drops them. It +// skips every other field without keeping it: "notes", "fields" and +// "passwordHistory" can hold secrets too. +func readLoginItem(r *jsonReader, f *loginFields) error { + return r.object(func(r *jsonReader, key string) error { + switch key { + case "id": + id, err := r.text(maxIDLen) + f.item.ID = id + return err + case "type": + n, err := readSmallInt(r) + f.typ, f.typeSet = n, err == nil + return err + case "name": + return readOptText(r, maxLoginName, &f.item.Name) + case "reprompt": + if r.peek() == 'n' { + return r.null() + } + n, err := readSmallInt(r) + f.item.Reprompt = n != 0 + return err + case "deletedDate": + return readDate(r, &f.trashed) + case "archivedDate": + return readDate(r, &f.archived) + case "collectionIds": + if r.peek() == 'n' { + return r.null() + } + return r.arrayEach(func(r *jsonReader) error { + if len(f.item.Collections) >= maxCollectionIDs { + return ErrBadAnswer + } + id, err := r.text(maxIDLen) + f.item.Collections = append(f.item.Collections, id) + return err + }) + case "login": + if r.peek() == 'n' { + return r.null() + } + return r.object(func(r *jsonReader, key string) error { return readLoginField(r, key, f) }) + } + return r.skip() + }) +} + +func readLoginField(r *jsonReader, key string, f *loginFields) error { + switch key { + case "username": + return readOptText(r, maxLoginName, &f.item.Username) + case "uris": + if r.peek() == 'n' { + return r.null() + } + return r.arrayEach(func(r *jsonReader) error { + if len(f.item.URIs) >= maxLoginURIs { + return ErrBadAnswer + } + var u LoginURI + err := r.object(func(r *jsonReader, key string) error { + switch key { + case "uri": + return readOptText(r, maxLoginURI, &u.URI) + case "match": + if r.peek() == 'n' { + return r.null() + } + n, err := readSmallInt(r) + u.Match = &n + return err + } + return r.skip() + }) + f.item.URIs = append(f.item.URIs, u) + return err + }) + case "password", "totp": + switch r.peek() { + case 'n': + return r.null() + case '"': + if !f.wantSecrets { + _, err := r.str(nil) // checks it, keeps nothing + return err + } + b, err := r.secret() + if key == "password" { + f.password = b + } else { + f.totp = b + } + return err + } + return ErrBadAnswer + } + return r.skip() +} + +// readOptText reads a string of at most limit bytes, or null. +func readOptText(r *jsonReader, limit int, out *string) error { + if r.peek() == 'n' { + return r.null() + } + s, err := r.text(limit) + *out = s + return err +} + +// readSmallInt reads a whole number from 0 to 99. +func readSmallInt(r *jsonReader) (int, error) { + start := r.pos + if err := r.number(); err != nil { + return 0, err + } + b := r.data[start:r.pos] + if len(b) == 0 || len(b) > 2 { + return 0, ErrBadAnswer + } + n := 0 + for _, c := range b { + if c < '0' || c > '9' { + return 0, ErrBadAnswer + } + n = n*10 + int(c-'0') + } + return n, nil +} + +// parseBWLoginList reads the answer of "bw list items --collectionid C": +// one JSON array of items. It never keeps a password or a TOTP seed. +func parseBWLoginList(data []byte, collection string) ([]LoginItem, error) { + r := &jsonReader{data: data} + r.space() + var items []LoginItem + err := r.arrayEach(func(r *jsonReader) error { + var f loginFields + if err := readLoginItem(r, &f); err != nil { + return err + } + if !isUUID(f.item.ID) { + return ErrBadAnswer + } + if !f.typeSet || f.typ != bwTypeLogin || f.trashed || f.archived || !hasID(f.item.Collections, collection) { + return nil + } + if len(items) >= maxLoginItems { + return ErrBadAnswer + } + items = append(items, f.item) + return nil + }) + if err == nil { + r.space() + if r.pos != len(r.data) { + err = ErrBadAnswer + } + } + if err != nil { + return nil, err + } + return items, nil +} + +// parseBWLogin reads the answer of "bw get item ID" for a login. "id" must +// be id. It keeps the password and the TOTP seed. +func parseBWLogin(data []byte, id string) (Login, error) { + f := loginFields{wantSecrets: true} + r := &jsonReader{data: data} + r.space() + err := readLoginItem(r, &f) + if err == nil { + r.space() + if r.pos != len(r.data) { + err = ErrBadAnswer + } + } + switch { + case err != nil: + case !sameUUID(f.item.ID, id): + err = errOtherItem + case f.trashed: + err = ErrTrashed + case f.archived: + err = ErrArchived + case !f.typeSet || f.typ != bwTypeLogin: + err = ErrNotLogin + } + if err != nil { + f.clearSecrets() + return Login{}, err + } + totp := f.totp + f.totp = nil + password, err := keepValue(f.password, nil) + f.password = nil + if err != nil { + clear(totp) + return Login{}, err + } + l := Login{LoginItem: f.item, Password: password} + if len(totp) > 0 { + l.TOTP = newValue(totp) + } + return l, nil +} + +// hasID reports whether ids holds id, in upper or lower case. +func hasID(ids []string, id string) bool { + for _, x := range ids { + if sameUUID(x, id) { + return true + } + } + return false +} diff --git a/internal/store/bwlogin_test.go b/internal/store/bwlogin_test.go new file mode 100644 index 0000000..b616895 --- /dev/null +++ b/internal/store/bwlogin_test.go @@ -0,0 +1,219 @@ +package store + +import ( + "encoding/json" + "fmt" + "slices" + "strings" + "testing" + + "github.com/code6x/nodkey/internal/config" +) + +const ( + testCollection = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d" + otherCollection = "1b2c3d4e-5f6a-4b7c-8d9e-0f1a2b3c4d5e" + testItemID2 = "7a2e3d4c-5b6a-4f98-9b7c-6d5e4f3a2b1c" +) + +// loginJSON returns a login item as bw writes it. password, totp and +// other are made-up secrets; other goes in the notes, a custom field and +// the password history. +func loginJSON(id string, typ int, collections []string, password, totp, other string, extra map[string]any) string { + item := map[string]any{ + "object": "item", "id": id, "organizationId": "2c3d4e5f-6a7b-4c8d-9e0f-1a2b3c4d5e6f", + "folderId": nil, "type": typ, "reprompt": 0, "name": "Example shop", "notes": other, + "favorite": false, "collectionIds": collections, + "fields": []any{map[string]any{"name": "pin", "value": other, "type": 1}}, + "passwordHistory": []any{map[string]any{"lastUsedDate": "2026-10-01T12:00:00.000Z", "password": other}}, + "login": map[string]any{ + "uris": []any{ + map[string]any{"match": nil, "uri": "https://example.com/login"}, + map[string]any{"match": 1, "uri": "https://shop.example.org"}, + }, + "username": "alice@example.com", "password": password, "totp": totp, + "passwordRevisionDate": nil, "fido2Credentials": []any{}, + }, + "revisionDate": "2026-10-01T12:00:00.000Z", "creationDate": "2026-10-01T12:00:00.000Z", + "deletedDate": nil, "archivedDate": nil, + } + for k, v := range extra { + item[k] = v + } + b, _ := json.Marshal(item) + return string(b) +} + +func TestBWListLogins(t *testing.T) { + t.Parallel() + pw, seed, other := madeUp("password"), madeUp("totp"), madeUp("other") + cols := []string{testCollection} + list := "[" + strings.Join([]string{ + loginJSON(testItemID, 1, cols, pw, seed, other, nil), + loginJSON(testItemID2, 1, []string{testCollection, otherCollection}, pw, seed, other, nil), + loginJSON("8b3f4e5d-6c7b-4a09-8c8d-7e6f5a4b3c2d", 2, cols, pw, seed, other, nil), // a note + loginJSON("9c4a5f6e-7d8c-4b1a-9d9e-8f7a6b5c4d3e", 1, cols, pw, seed, other, map[string]any{"deletedDate": "2026-10-02T00:00:00Z"}), // trash + loginJSON("ad5b6a7f-8e9d-4c2b-8eaf-9a8b7c6d5e4f", 1, cols, pw, seed, other, map[string]any{"archivedDate": "2026-10-02T00:00:00Z"}), // archived + loginJSON("be6c7b8a-9f0e-4d3c-9fba-ab9c8d7e6f5a", 1, []string{otherCollection}, pw, seed, other, nil), // not in it + }, ",") + "]" + sc := bwScenario(madeUp("password"), "", madeUp("value"), other) + sc.Lists = map[string]string{testCollection: list} + f := newTestFake(t, config.StoreBW, sc, testDeps()) + ls := f.store.(LoginStore) + items, err := ls.ListLogins(t.Context(), testCollection) + if err != nil { + t.Fatalf("ListLogins: %v", err) + } + if len(items) != 2 || items[0].ID != testItemID || items[1].ID != testItemID2 { + t.Fatalf("items = %+v", items) + } + it := items[0] + if it.Name != "Example shop" || it.Username != "alice@example.com" || len(it.URIs) != 2 || + it.URIs[0].URI != "https://example.com/login" || it.URIs[0].Match != nil || + it.URIs[1].Match == nil || *it.URIs[1].Match != 1 { + t.Fatalf("item = %+v", it) + } + if it.Reprompt { + t.Fatal("reprompt 0 read as true") + } + if !slices.Equal(items[1].Collections, []string{testCollection, otherCollection}) { + t.Fatalf("collections = %q", items[1].Collections) + } + dump := fmt.Sprintf("%+v %#v", items, items) + for _, s := range []string{pw, seed, other} { + noCanary(t, "the list", dump, s) + } + if got, want := f.steps(), []string{"unlock", "sync", "list items"}; !slices.Equal(got, want) { + t.Errorf("steps = %q, want %q", got, want) + } + if want := []string{"list", "items", "--collectionid", testCollection, "--nointeraction"}; !slices.Equal(f.calls()[2].Args, want) { + t.Errorf("arguments = %q, want %q", f.calls()[2].Args, want) + } +} + +func TestBWListLoginsRefused(t *testing.T) { + t.Parallel() + pw, other := madeUp("password"), madeUp("other") + tests := map[string]struct { + list string + want error + }{ + "an object": {loginJSON(testItemID, 1, []string{testCollection}, pw, "", other, nil), ErrBadAnswer}, + "bad item id": {`[{"id":"x","type":1,"collectionIds":["` + testCollection + `"]}]`, ErrBadAnswer}, + "cut short": {`[{"id":"` + testItemID + `"}`, ErrBadAnswer}, + "type text": {`[{"id":"` + testItemID + `","type":"1"}]`, ErrBadAnswer}, + "type negative": {`[{"id":"` + testItemID + `","type":-1}]`, ErrBadAnswer}, + "match fraction": {`[{"id":"` + testItemID + `","type":1,"login":{"uris":[{"uri":"https://example.com","match":0.5}]}}]`, ErrBadAnswer}, + "long name": {`[{"id":"` + testItemID + `","type":1,"name":"` + strings.Repeat("a", maxLoginName+1) + `"}]`, ErrBadAnswer}, + "password number": {`[{"id":"` + testItemID + `","type":1,"login":{"password":7}}]`, ErrBadAnswer}, + "trailing": {`[] []`, ErrBadAnswer}, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + sc := bwScenario(madeUp("password"), "", madeUp("value"), other) + sc.Lists = map[string]string{testCollection: tc.list} + f := newTestFake(t, config.StoreBW, sc, testDeps()) + items, err := f.store.(LoginStore).ListLogins(t.Context(), testCollection) + checkErr(t, err, tc.want) + if items != nil { + t.Error("items with an error") + } + if err != nil { + noCanary(t, "the error", err.Error(), pw) + noCanary(t, "the error", err.Error(), other) + } + }) + } + f := newTestFake(t, config.StoreBW, bwScenario(madeUp("password"), "", madeUp("value"), other), testDeps()) + _, err := f.store.(LoginStore).ListLogins(t.Context(), "not-a-uuid") + checkErr(t, err, ErrBadID) + if len(f.steps()) != 0 { + t.Error("bw ran for a bad collection ID") + } +} + +func TestBWFetchLogin(t *testing.T) { + t.Parallel() + pw, seed, other := madeUp("password"), madeUp("totp"), madeUp("other") + sc := bwScenario(madeUp("password"), "", madeUp("value"), other) + sc.Items[testItemID] = loginJSON(strings.ToUpper(testItemID), 1, []string{testCollection}, pw, seed, other, + map[string]any{"reprompt": 1}) + f := newTestFake(t, config.StoreBW, sc, testDeps()) + l, err := f.store.(LoginStore).FetchLogin(t.Context(), testItemID) + if err != nil { + t.Fatalf("FetchLogin: %v", err) + } + defer l.Clear() + checkValue(t, l.Password, pw) + checkValue(t, l.TOTP, seed) + if !l.Reprompt { + t.Error("reprompt 1 read as false") + } + if l.Username != "alice@example.com" || len(l.URIs) != 2 || !slices.Equal(l.Collections, []string{testCollection}) { + t.Fatalf("login = %+v", l.LoginItem) + } + for _, s := range []string{fmt.Sprint(l), fmt.Sprintf("%+v %#v %s %q", l, l, l, l)} { + noCanary(t, "the login's format", s, pw) + noCanary(t, "the login's format", s, seed) + } + if got, want := f.steps(), []string{"unlock", "sync", "get item"}; !slices.Equal(got, want) { + t.Errorf("steps = %q, want %q", got, want) + } + pwBuf := l.Password.Bytes() + l.Clear() + for _, c := range pwBuf { + if c != 0 { + t.Fatal("Clear left the password") + } + } +} + +func TestBWFetchLoginRefused(t *testing.T) { + t.Parallel() + pw, seed, other := madeUp("password"), madeUp("totp"), madeUp("other") + cols := []string{testCollection} + tests := map[string]struct { + item string + want error + }{ + "in the trash": {loginJSON(testItemID, 1, cols, pw, seed, other, map[string]any{"deletedDate": "2026-10-02T00:00:00Z"}), ErrTrashed}, + "archived": {loginJSON(testItemID, 1, cols, pw, seed, other, map[string]any{"archivedDate": "2026-10-02T00:00:00Z"}), ErrArchived}, + "a note": {loginJSON(testItemID, 2, cols, pw, seed, other, nil), ErrNotLogin}, + "no type": {`{"id":"` + testItemID + `","login":{"password":"` + pw + `"}}`, ErrNotLogin}, + "other item": {loginJSON(testItemID2, 1, cols, pw, seed, other, nil), errOtherItem}, + "no password": {loginJSON(testItemID, 1, cols, "", seed, other, nil), ErrNoValue}, + "NUL password": {loginJSON(testItemID, 1, cols, "a\x00b", seed, other, nil), ErrBadValue}, + "a list": {"[" + loginJSON(testItemID, 1, cols, pw, seed, other, nil) + "]", ErrBadAnswer}, + "two totps": {`{"id":"` + testItemID + `","type":1,"login":{"totp":"a","totp":"b"}}`, ErrBadAnswer}, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + sc := bwScenario(madeUp("password"), "", madeUp("value"), other) + sc.Items[testItemID] = tc.item + f := newTestFake(t, config.StoreBW, sc, testDeps()) + l, err := f.store.(LoginStore).FetchLogin(t.Context(), testItemID) + checkErr(t, err, tc.want) + if l.Password.Bytes() != nil || l.TOTP.Bytes() != nil || l.ID != "" { + t.Error("FetchLogin returned a login with its error") + } + for _, s := range []string{pw, seed, other} { + if err != nil { + noCanary(t, "the error", err.Error(), s) + } + } + }) + } +} + +func FuzzParseBWLogin(f *testing.F) { + f.Add(loginJSON(testItemID, 1, []string{testCollection}, "pw", "seed", "other", nil)) + f.Fuzz(func(t *testing.T, data string) { + l, err := parseBWLogin([]byte(data), testItemID) + if err == nil { + l.Clear() + } + _, _ = parseBWLoginList([]byte("["+data+"]"), testCollection) + }) +} diff --git a/internal/store/fake_test.go b/internal/store/fake_test.go index 38cddab..87a2e96 100644 --- a/internal/store/fake_test.go +++ b/internal/store/fake_test.go @@ -76,6 +76,7 @@ type fakeScenario struct { Password string `json:"password"` // bw: the master password, the first line of the password file Session string `json:"session"` // bw: the session key that unlock makes; random if empty Items map[string]string `json:"items"` // the answer for each item ID, in lower case + Lists map[string]string `json:"lists"` // bw: the answer of "list items" for each collection ID, in lower case Steps map[string]fakeStep `json:"steps"` // what a step does instead of its usual work Pause time.Duration `json:"pause"` // each run waits this long first } @@ -189,6 +190,8 @@ func fakeBW(home string, sc *fakeScenario) int { step = args[0] case len(args) > 2 && args[0] == "get" && args[1] == "item": step = "get item" + case len(args) > 3 && args[0] == "list" && args[1] == "items" && args[2] == "--collectionid": + step = "list items" default: return fakeFail("Invalid command: "+strings.Join(args, " "), 1) } @@ -250,13 +253,21 @@ func fakeBW(home string, sc *fakeScenario) int { _, _ = fakeStdout.WriteString("Syncing complete.") return 0 } - // get item + // get item, list items switch { case st.LoggedOut: return fakeFail("You are not logged in.", 1) case !unlocked: return fakeFail("Vault is locked.", 1) } + if step == "list items" { + list, ok := sc.Lists[strings.ToLower(args[3])] + if !ok { + list = "[]" + } + _, _ = fakeStdout.WriteString(list) + return 0 + } item, ok := sc.Items[strings.ToLower(args[2])] if !ok { return fakeFail("Not found.", 1) diff --git a/internal/store/helpers_test.go b/internal/store/helpers_test.go index 461d53d..9c7b81c 100644 --- a/internal/store/helpers_test.go +++ b/internal/store/helpers_test.go @@ -184,7 +184,7 @@ func (f *testFake) steps() []string { var steps []string for _, c := range f.calls() { switch { - case len(c.Args) >= 2 && (c.Args[0] == "secret" || c.Args[0] == "get"): + case len(c.Args) >= 2 && (c.Args[0] == "secret" || c.Args[0] == "get" || c.Args[0] == "list"): steps = append(steps, c.Args[0]+" "+c.Args[1]) case len(c.Args) >= 1: steps = append(steps, c.Args[0]) diff --git a/internal/store/json.go b/internal/store/json.go index e90d5d0..49790ca 100644 --- a/internal/store/json.go +++ b/internal/store/json.go @@ -129,6 +129,12 @@ func (r *jsonReader) object(member func(r *jsonReader, key string) error) error // array reads an array and skips its values. func (r *jsonReader) array() error { + return r.arrayEach(func(r *jsonReader) error { return r.skip() }) +} + +// arrayEach reads an array and calls each for each value, with the reader +// at the value: each must read the value. +func (r *jsonReader) arrayEach(each func(r *jsonReader) error) error { if r.peek() != '[' { return ErrBadAnswer } @@ -141,7 +147,7 @@ func (r *jsonReader) array() error { return nil } for { - if err := r.skip(); err != nil { + if err := each(r); err != nil { return err } r.space() diff --git a/internal/telegram/text.go b/internal/telegram/text.go index 8c3a9cc..5b844b6 100644 --- a/internal/telegram/text.go +++ b/internal/telegram/text.go @@ -266,7 +266,15 @@ func checkPrompt(p approval.Prompt, notice bool) error { if p.Via == audit.ViaStanding && p.Kind != audit.KindSecrets { return bad("a standing use outside a secrets request") } + if err := checkLoginPrompt(p, notice); err != nil { + return err + } switch p.Kind { + case audit.KindWebLogin: + if len(p.Secrets) != 0 || p.Key != "" || len(p.Hosts) != 0 || p.HostKey != "" || p.RemoteUser != "" || + !p.GrantEnds.IsZero() || p.Login == nil || p.Login.For != 0 { + return bad("the fields of a website login") + } case audit.KindSecrets: if len(p.Secrets) == 0 || !allNames(p.Secrets) || p.Key != "" || len(p.Hosts) != 0 || p.HostKey != "" || p.RemoteUser != "" || !p.GrantEnds.IsZero() { @@ -284,6 +292,18 @@ func checkPrompt(p approval.Prompt, notice bool) error { return bad("the fields of an SSH grant") } case audit.KindPreapprove: + if p.Login != nil { + if len(p.Secrets) != 0 || p.Key != "" || len(p.Hosts) != 0 || p.HostKey != "" || p.RemoteUser != "" || + !p.GrantEnds.IsZero() || p.WindowMinutes != 0 || p.Uses != 1 || !p.From.IsZero() || !p.Until.IsZero() || + p.Via != "" || p.Login.For != approval.LoginPreapproveTime { + return bad("the fields of a login pre-approval") + } + if notice != validRequestID(p.GrantID) || (notice && p.UsesLeft != 1) || + (!notice && (p.GrantID != "" || p.UsesLeft != 0 || !p.Once)) { + return bad("the fields of a login pre-approval") + } + break + } named := len(p.Secrets) > 0 && allNames(p.Secrets) && p.Key == "" && len(p.Hosts) == 0 && p.RemoteUser == "" keyed := len(p.Secrets) == 0 && namePattern.MatchString(p.Key) && len(p.Hosts) > 0 && len(p.Hosts) <= approval.MaxGrantHosts && allNames(p.Hosts) && remoteUserPattern.MatchString(p.RemoteUser) @@ -328,6 +348,38 @@ func checkPrompt(p approval.Prompt, notice bool) error { return nil } +// loginOriginPattern is an https origin: a host name or an IP address, +// and perhaps a port. The core made it from a checked page URL. +var loginOriginPattern = regexp.MustCompile(`^https://([a-z0-9][a-z0-9.-]{0,252}|\[[0-9a-f:]{2,45}\])(:[0-9]{1,5})?$`) + +// maxLoginText is the most runes of an item name or a user name. +const maxLoginText = 128 + +// checkLoginPrompt checks the login part of p. The item name and the user +// name come from the vault: the core cleaned them, and this checks that +// they are clean, so a message never shows a line break or a direction +// mark from the vault. +func checkLoginPrompt(p approval.Prompt, notice bool) error { + bad := func(what string) error { return errors.New("telegram: the prompt is not valid: " + what) } + l := p.Login + if l == nil { + if p.Kind == audit.KindWebLogin { + return bad("a website login without its login") + } + return nil + } + if p.Kind != audit.KindWebLogin && p.Kind != audit.KindPreapprove { + return bad("a login outside a website login") + } + clean := func(s string) bool { + return utf8.RuneCountInString(s) <= maxLoginText && claim.Line(s, maxLoginText+1) == s + } + if l.Name == "" || !clean(l.Name) || !clean(l.Username) || !loginOriginPattern.MatchString(l.Origin) || l.For < 0 { + return bad("the login") + } + return nil +} + func allNames(names []string) bool { for _, n := range names { if !namePattern.MatchString(n) { @@ -349,6 +401,8 @@ func title(p approval.Prompt, notice bool) string { icon, name = "๐Ÿ—“", "Pre-approval" case audit.KindStanding: icon, name = "๐Ÿ—“", "Standing grant" + case audit.KindWebLogin: + icon, name = "๐ŸŒ", "Website login" } if notice { icon = "๐Ÿ””" @@ -376,12 +430,20 @@ func claimedValue(s string) string { // claimedValues are the claimed fields of a prompt, made with // claimedValue: Vars, Command, Dir and Reason. -type claimedValues [4]string +type claimedValues [5]string + +// loginPage returns the claimed origin of a website login, or "". +func loginPage(p approval.Prompt) string { + if p.Login == nil { + return "" + } + return p.Login.Origin +} func claimedOf(p approval.Prompt) claimedValues { return claimedValues{ claimedValue(p.Claim.Vars), claimedValue(p.Claim.Command), - claimedValue(p.Claim.Dir), claimedValue(p.Claim.Reason), + claimedValue(p.Claim.Dir), claimedValue(p.Claim.Reason), claimedValue(loginPage(p)), } } @@ -404,6 +466,12 @@ func body(p approval.Prompt, notice bool, cv claimedValues, c caps) *text { } } verified := func(label, value string) { t.write("\nโœ… " + label + ": " + value) } + // The name and the user name of an item come from the vault, so they + // are set apart as code. + verifiedCode := func(label, value string) { + t.write("\nโœ… " + label + ": ") + t.code(value) + } verified("machine", p.Client) switch p.Kind { case audit.KindSecrets: @@ -417,7 +485,16 @@ func body(p approval.Prompt, notice bool, cv claimedValues, c caps) *text { verified("hosts", strings.Join(p.Hosts, ", ")) verified("remote user", p.RemoteUser) verified("grants end", p.GrantEnds.Format(clockFormat)+" ("+strconv.Itoa(p.WindowMinutes)+" min)") + case audit.KindWebLogin: + verifiedCode("login", p.Login.Name) + verifiedCode("username", p.Login.Username) case audit.KindPreapprove: + if p.Login != nil { + verifiedCode("login", p.Login.Name) + verifiedCode("username", p.Login.Username) + t.write("\nallows: one login in the next " + strconv.Itoa(int(p.Login.For/time.Second)) + " s after the tap") + break + } if len(p.Secrets) > 0 { verified("secrets", strings.Join(p.Secrets, ", ")) } else { @@ -442,6 +519,7 @@ func body(p approval.Prompt, notice bool, cv claimedValues, c caps) *text { label, value string limit int }{ + {"page", cv[4], c.dir}, {"as", cv[0], c.vars}, {"command", cv[1], c.command}, {"in", cv[2], c.dir}, @@ -548,7 +626,12 @@ func promptMessage(p approval.Prompt) (*text, inlineKeyboard, error) { if err != nil { return nil, inlineKeyboard{}, err } - t.write("\n" + expiryLine(p)) + if p.Login == nil || p.Login.For == 0 { + // The message of a login pre-approval shows no time limit for the + // tap: its time starts at the tap, and a limit here would read as + // the time of the login. + t.write("\n" + expiryLine(p)) + } return t, keyboard(p), nil } @@ -580,6 +663,10 @@ func resultLine(p approval.Prompt, e approval.Ending) string { return "๐Ÿ‘ approved by you at " + at + ", for " + strconv.Itoa(p.Uses) + " use(s) in each window until " + p.Until.Format(dateTimeFormat) } + if p.Kind == audit.KindPreapprove && p.Login != nil { + return "๐Ÿ‘ approved by you at " + at + ": one login in the next " + + strconv.Itoa(int(p.Login.For/time.Second)) + " s" + } if p.Kind == audit.KindPreapprove { return "๐Ÿ‘ approved by you at " + at + ", for " + strconv.Itoa(p.Uses) + " use(s) until " + p.Until.Format(dateTimeFormat) diff --git a/internal/telegram/weblogin_test.go b/internal/telegram/weblogin_test.go new file mode 100644 index 0000000..7e12072 --- /dev/null +++ b/internal/telegram/weblogin_test.go @@ -0,0 +1,159 @@ +package telegram + +import ( + "strings" + "testing" + "time" + + "github.com/code6x/nodkey/internal/approval" + "github.com/code6x/nodkey/internal/audit" +) + +func webLoginPrompt() approval.Prompt { + return approval.Prompt{ + RequestID: testID(3), ShortCode: "w4x8", Kind: audit.KindWebLogin, Client: "laptop", + Login: &approval.LoginPrompt{Name: "Example shop", Username: "alice@example.com", Origin: "https://example.com"}, + Claim: approval.Claim{Reason: "check the order"}, + Expires: time.Date(2026, 10, 14, 14, 5, 40, 0, time.UTC), + TimeLeft: 120 * time.Second, + Once: true, + WindowMinutes: 15, + } +} + +func webPreapprovePrompt() approval.Prompt { + p := webLoginPrompt() + p.Kind, p.Uses, p.WindowMinutes = audit.KindPreapprove, 1, 0 + p.Login.For = approval.LoginPreapproveTime + return p +} + +func TestWebLoginMessage(t *testing.T) { + tx, kb, err := promptMessage(webLoginPrompt()) + if err != nil { + t.Fatal(err) + } + want := "๐ŸŒ Website login ยท request w4x8\n" + + "โœ… machine: laptop\nโœ… login: Example shop\nโœ… username: alice@example.com\n" + + claimedHead + "\npage: https://example.com\nreason: check the order\n" + + "expires 14:05:40 (120 s)" + if got := tx.plain.String(); got != want { + t.Errorf("text:\n%s\nwant:\n%s", got, want) + } + if len(kb.InlineKeyboard) != 1 || len(kb.InlineKeyboard[0]) != 3 { + t.Errorf("buttons %+v, want once, window and deny", kb) + } +} + +// TestWebLoginPreapproveMessage: the message says what the tap allows, +// and shows no time limit for the tap itself. +func TestWebLoginPreapproveMessage(t *testing.T) { + tx, kb, err := promptMessage(webPreapprovePrompt()) + if err != nil { + t.Fatal(err) + } + got := tx.plain.String() + want := "๐Ÿ—“ Pre-approval ยท request w4x8\n" + + "โœ… machine: laptop\nโœ… login: Example shop\nโœ… username: alice@example.com\n" + + "allows: one login in the next 60 s after the tap\n" + + claimedHead + "\npage: https://example.com\nreason: check the order" + if got != want { + t.Errorf("text:\n%s\nwant:\n%s", got, want) + } + if strings.Contains(got, "expire") || strings.Contains(got, "14:05") { + t.Errorf("the message shows a time limit for the tap:\n%s", got) + } + if kb.InlineKeyboard[0][0].Text != "Approve" { + t.Errorf("buttons %+v", kb) + } + // The pre-approval of a secret keeps its expiry line. + tx, _, err = promptMessage(secretsPrompt()) + if err != nil || !strings.Contains(tx.plain.String(), "expires ") { + t.Errorf("a secrets message lost its expiry: %v", err) + } + // The line after the tap. + end := resultLine(webPreapprovePrompt(), approval.Ending{Answer: audit.AnswerApproveOnce, At: time.Date(2026, 10, 14, 14, 4, 0, 0, time.UTC)}) + if !strings.Contains(end, "one login in the next 60 s") { + t.Errorf("result line %q", end) + } +} + +func TestWebLoginHostileText(t *testing.T) { + p := webLoginPrompt() + p.Login.Name = "Shop\nโœ… machine: fake\u202e&" + if _, _, err := promptMessage(p); err == nil { + t.Error("the prompt with a line break in the item name was taken") + } + // The HTML of a clean but hostile name is escaped. + p = webLoginPrompt() + p.Login.Name = "Shop & Co" + p.Login.Username = "a@example.com" + tx, _, err := promptMessage(p) + if err != nil { + t.Fatal(err) + } + h := tx.html.String() + if strings.Contains(h, "Shop") || strings.Contains(h, "") || !strings.Contains(h, "<b>Shop</b> & Co") { + t.Errorf("html not escaped:\n%s", h) + } +} + +func TestWebLoginBadPrompts(t *testing.T) { + edits := map[string]func(p *approval.Prompt){ + "no login": func(p *approval.Prompt) { p.Login = nil }, + "no name": func(p *approval.Prompt) { p.Login.Name = "" }, + "RTL in the name": func(p *approval.Prompt) { p.Login.Name = "a\u202eb" }, + "newline in the user": func(p *approval.Prompt) { p.Login.Username = "a\nb" }, + "long name": func(p *approval.Prompt) { p.Login.Name = strings.Repeat("x", 129) }, + "http origin": func(p *approval.Prompt) { p.Login.Origin = "http://example.com" }, + "origin with a path": func(p *approval.Prompt) { p.Login.Origin = "https://example.com/a" }, + "secrets": func(p *approval.Prompt) { p.Secrets = []string{"a"} }, + "key": func(p *approval.Prompt) { p.Key = "deploy" }, + "for in a login": func(p *approval.Prompt) { p.Login.For = time.Minute }, + } + for name, ed := range edits { + t.Run(name, func(t *testing.T) { + p := webLoginPrompt() + ed(&p) + if _, _, err := promptMessage(p); err == nil { + t.Error("the prompt was taken") + } + }) + } + pre := map[string]func(p *approval.Prompt){ + "two uses": func(p *approval.Prompt) { p.Uses = 2 }, + "a span": func(p *approval.Prompt) { p.Until = time.Now() }, + "another time": func(p *approval.Prompt) { p.Login.For = time.Hour }, + "no time": func(p *approval.Prompt) { p.Login.For = 0 }, + "secrets": func(p *approval.Prompt) { p.Secrets = []string{"a"} }, + "a window": func(p *approval.Prompt) { p.WindowMinutes = 15 }, + } + for name, ed := range pre { + t.Run("pre-approval "+name, func(t *testing.T) { + p := webPreapprovePrompt() + ed(&p) + if _, _, err := promptMessage(p); err == nil { + t.Error("the prompt was taken") + } + }) + } + t.Run("a login in a secrets prompt", func(t *testing.T) { + p := secretsPrompt() + p.Login = webLoginPrompt().Login + if _, _, err := promptMessage(p); err == nil { + t.Error("the prompt was taken") + } + }) +} + +func TestWebLoginNotice(t *testing.T) { + p := webLoginPrompt() + p.Via, p.Expires, p.TimeLeft, p.Once, p.WindowMinutes = audit.ViaScheduled, time.Time{}, 0, false, 0 + tx, err := noticeText(p) + if err != nil { + t.Fatal(err) + } + if got := tx.plain.String(); !strings.Contains(got, "๐Ÿ”” Website login") || !strings.Contains(got, "login: Example shop") { + t.Errorf("notice:\n%s", got) + } +} diff --git a/internal/totp/totp.go b/internal/totp/totp.go new file mode 100644 index 0000000..7c4b5b8 --- /dev/null +++ b/internal/totp/totp.go @@ -0,0 +1,293 @@ +// Package totp makes TOTP codes (RFC 6238) on the broker, from the +// login.totp field of a Bitwarden item (DESIGN.md section 21). +// +// The seed never leaves the broker: Key hides it in every format, and +// only Code reads it. Two forms are accepted: a plain base32 secret, and +// an otpauth://totp URI with SHA1, SHA256 or SHA512, 6 to 8 digits and +// any period from 1 to 3600 seconds. Every other form (steam://, +// otpauth://hotp, an unknown algorithm) is refused. +// +// No error of this package holds the seed or the field it came from. +package totp + +import ( + "bytes" + "crypto/hmac" + "crypto/sha1" // #nosec G505 -- RFC 6238 uses HMAC-SHA1 by default; HMAC-SHA1 is not broken. + "crypto/sha256" + "crypto/sha512" + "encoding/base32" + "encoding/binary" + "errors" + "fmt" + "hash" + "io" + "log/slog" + "strconv" + "strings" + "time" +) + +// Limits of the accepted forms. +const ( + MinDigits = 6 + MaxDigits = 8 + MaxPeriod = 3600 + maxSeedLen = 1024 // bytes of the decoded seed + maxField = 4096 // bytes of the login.totp field +) + +const hidden = "[totp seed hidden]" + +// Algorithm is the HMAC hash of a key. +type Algorithm string + +// The accepted algorithms. +const ( + SHA1 Algorithm = "SHA1" + SHA256 Algorithm = "SHA256" + SHA512 Algorithm = "SHA512" +) + +// The errors of Parse. They never hold the field. +var ( + ErrEmpty = errors.New("the item has no TOTP seed; add one in the item's \"Authenticator key\" field in Bitwarden") + ErrForm = errors.New("the TOTP field is not a base32 secret or an otpauth://totp URI; nodkey makes no codes for steam:// or other forms (DESIGN.md section 21); put a base32 secret or an otpauth://totp URI in the item's \"Authenticator key\" field") + ErrBase32 = errors.New("the TOTP secret is not valid base32; copy the secret again from the site into the item's \"Authenticator key\" field") + ErrAlgorithm = errors.New("the otpauth URI names an algorithm other than SHA1, SHA256 or SHA512; nodkey does not make codes for it (DESIGN.md section 21)") + ErrDigits = errors.New("the otpauth URI asks for fewer than 6 or more than 8 digits; nodkey does not make codes for it (DESIGN.md section 21)") + ErrPeriod = errors.New("the otpauth URI has a period that is not a whole number of seconds from 1 to 3600; fix the period in the item's \"Authenticator key\" field") +) + +// Key is a parsed TOTP key. It hides the seed in every format. +type Key struct { + seed []byte + alg Algorithm + digits int + period time.Duration +} + +// String returns a redacted form. +func (Key) String() string { return hidden } + +// GoString returns a redacted form. +func (Key) GoString() string { return "totp.Key{" + hidden + "}" } + +// Format prints a redacted form for every verb. +func (Key) Format(f fmt.State, _ rune) { _, _ = io.WriteString(f, hidden) } + +// LogValue returns a redacted form. +func (Key) LogValue() slog.Value { return slog.StringValue(hidden) } + +// MarshalJSON refuses to encode the key. +func (Key) MarshalJSON() ([]byte, error) { return nil, errors.New("totp: a key is never encoded") } + +// MarshalText refuses to encode the key. +func (Key) MarshalText() ([]byte, error) { return nil, errors.New("totp: a key is never encoded") } + +// Digits returns the number of digits of a code. +func (k Key) Digits() int { return k.digits } + +// Period returns the time step. +func (k Key) Period() time.Duration { return k.period } + +// Algorithm returns the HMAC hash. +func (k Key) Algorithm() Algorithm { return k.alg } + +// Clear overwrites the seed. The key makes no codes after it. +func (k *Key) Clear() { + for i := range k.seed { + k.seed[i] = 0 + } + k.seed = nil +} + +// Parse reads the login.totp field of an item. It does not change or +// keep field: the caller clears it. Every copy of the seed that Parse +// makes is cleared, except the one in the Key, which Clear clears. +func Parse(field []byte) (Key, error) { + s := bytes.TrimSpace(field) + if len(s) == 0 { + return Key{}, ErrEmpty + } + if len(s) > maxField { + return Key{}, ErrForm + } + if i := bytes.IndexByte(s, ':'); i >= 0 { + if !bytes.EqualFold(s[:i], []byte("otpauth")) { + return Key{}, ErrForm + } + return parseURI(s) + } + seed, err := decodeBase32(s) + if err != nil { + return Key{}, err + } + return Key{seed: seed, alg: SHA1, digits: 6, period: 30 * time.Second}, nil +} + +// parseURI reads otpauth://totp/LABEL?PARAMS. It reads the parameters on +// the bytes of s, with no copy of the secret. A secret with a percent +// escape is refused: a base32 secret needs none. +func parseURI(s []byte) (Key, error) { + const prefix = "otpauth://totp/" + if len(s) < len(prefix) || !bytes.EqualFold(s[:len(prefix)], []byte(prefix)) { + return Key{}, ErrForm + } + q := bytes.IndexByte(s, '?') + if q < 0 { + return Key{}, ErrEmpty + } + rest := s[q+1:] + if i := bytes.IndexByte(rest, '#'); i >= 0 { + rest = rest[:i] + } + k := Key{alg: SHA1, digits: 6, period: 30 * time.Second} + var secret []byte + seen := map[string]bool{} + for _, part := range bytes.Split(rest, []byte("&")) { + if len(part) == 0 { + continue + } + name, val, ok := bytes.Cut(part, []byte("=")) + if !ok { + return Key{}, ErrForm + } + // Make a string only of a known name: an unknown name could be + // a pasted seed, and a string cannot be cleared. + key := "" + for _, known := range []string{"secret", "algorithm", "digits", "period"} { + if bytes.EqualFold(name, []byte(known)) { + key = known + } + } + if key == "" { + continue + } + if seen[key] { + return Key{}, ErrForm + } + seen[key] = true + switch key { + case "secret": + if bytes.IndexByte(val, '%') >= 0 || bytes.IndexByte(val, '+') >= 0 { + return Key{}, ErrBase32 + } + secret = val + case "algorithm": + switch Algorithm(strings.ToUpper(string(val))) { + case SHA1: + k.alg = SHA1 + case SHA256: + k.alg = SHA256 + case SHA512: + k.alg = SHA512 + default: + return Key{}, ErrAlgorithm + } + case "digits": + n, err := strconv.Atoi(string(val)) + if err != nil || n < MinDigits || n > MaxDigits { + return Key{}, ErrDigits + } + k.digits = n + case "period": + n, err := strconv.Atoi(string(val)) + if err != nil || n < 1 || n > MaxPeriod { + return Key{}, ErrPeriod + } + k.period = time.Duration(n) * time.Second + } + } + if len(secret) == 0 { + return Key{}, ErrEmpty + } + seed, err := decodeBase32(secret) + if err != nil { + return Key{}, err + } + k.seed = seed + return k, nil +} + +// decodeBase32 reads a base32 secret. Spaces and dashes are dropped, +// case does not matter, and padding is optional. It works in buffers of +// a fixed size, and clears the cleaned copy, and the seed on an error. +func decodeBase32(s []byte) ([]byte, error) { + clean := make([]byte, 0, len(s)) + defer func() { clear(clean[:cap(clean)]) }() + for _, c := range s { + switch { + case c == ' ' || c == '-' || c == '\t' || c == '=': + case c >= 'a' && c <= 'z': + clean = append(clean, c-'a'+'A') + case (c >= 'A' && c <= 'Z') || (c >= '2' && c <= '7'): + clean = append(clean, c) + default: + return nil, ErrBase32 + } + } + if len(clean) == 0 { + return nil, ErrEmpty + } + enc := base32.StdEncoding.WithPadding(base32.NoPadding) + seed := make([]byte, enc.DecodedLen(len(clean))) + n, err := enc.Decode(seed, clean) + if err != nil || n == 0 || n > maxSeedLen { + clear(seed) + return nil, ErrBase32 + } + if n < len(seed) { + clear(seed[n:]) + } + return seed[:n], nil +} + +// ErrCleared is returned by Code for a key that was cleared or never parsed. +var ErrCleared = errors.New("totp: the key has no seed") + +// Code returns the code for the time t. +func (k Key) Code(t time.Time) (string, error) { + if len(k.seed) == 0 || k.period <= 0 || k.digits < MinDigits || k.digits > MaxDigits { + return "", ErrCleared + } + unix := t.Unix() + if unix < 0 { + return "", errors.New("totp: the time is before 1970; check the broker's clock") + } + step := uint64(unix) / uint64(k.period/time.Second) + return hotp(k.seed, k.alg, k.digits, step), nil +} + +// Step returns the number of the time step that holds t. Two codes of +// one key with the same step are the same code. +func (k Key) Step(t time.Time) int64 { + if k.period <= 0 || t.Unix() < 0 { + return -1 + } + return t.Unix() / int64(k.period/time.Second) +} + +func hotp(seed []byte, alg Algorithm, digits int, counter uint64) string { + var h func() hash.Hash + switch alg { + case SHA256: + h = sha256.New + case SHA512: + h = sha512.New + default: + h = sha1.New + } + mac := hmac.New(h, seed) + var msg [8]byte + binary.BigEndian.PutUint64(msg[:], counter) + mac.Write(msg[:]) + sum := mac.Sum(nil) + off := sum[len(sum)-1] & 0x0f + bin := binary.BigEndian.Uint32(sum[off:off+4]) & 0x7fffffff + mod := uint32(1) + for range digits { + mod *= 10 + } + return fmt.Sprintf("%0*d", digits, bin%mod) +} diff --git a/internal/totp/totp_test.go b/internal/totp/totp_test.go new file mode 100644 index 0000000..c8eb496 --- /dev/null +++ b/internal/totp/totp_test.go @@ -0,0 +1,226 @@ +package totp + +import ( + "encoding/base32" + "encoding/json" + "errors" + "fmt" + "log/slog" + "strings" + "testing" + "time" +) + +func b32(s string) string { + return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString([]byte(s)) +} + +// The test vectors of RFC 6238, appendix B. +func TestRFC6238Vectors(t *testing.T) { + seeds := map[Algorithm]string{ + SHA1: "12345678901234567890", + SHA256: "12345678901234567890123456789012", + SHA512: "1234567890123456789012345678901234567890123456789012345678901234", + } + cases := []struct { + unix int64 + alg Algorithm + code string + }{ + {59, SHA1, "94287082"}, {59, SHA256, "46119246"}, {59, SHA512, "90693936"}, + {1111111109, SHA1, "07081804"}, {1111111109, SHA256, "68084774"}, {1111111109, SHA512, "25091201"}, + {1111111111, SHA1, "14050471"}, {1111111111, SHA256, "67062674"}, {1111111111, SHA512, "99943326"}, + {1234567890, SHA1, "89005924"}, {1234567890, SHA256, "91819424"}, {1234567890, SHA512, "93441116"}, + {2000000000, SHA1, "69279037"}, {2000000000, SHA256, "90698825"}, {2000000000, SHA512, "38618901"}, + {20000000000, SHA1, "65353130"}, {20000000000, SHA256, "77737706"}, {20000000000, SHA512, "47863826"}, + } + for _, c := range cases { + uri := fmt.Sprintf("otpauth://totp/Example:alice@example.com?secret=%s&algorithm=%s&digits=8&period=30&issuer=Example", b32(seeds[c.alg]), c.alg) + k, err := Parse([]byte(uri)) + if err != nil { + t.Fatalf("%s: Parse: %v", c.alg, err) + } + got, err := k.Code(time.Unix(c.unix, 0)) + if err != nil { + t.Fatalf("Code: %v", err) + } + if got != c.code { + t.Errorf("%d %s: got %s, want %s", c.unix, c.alg, got, c.code) + } + } +} + +func TestPlainBase32(t *testing.T) { + plain := strings.ToLower(b32("12345678901234567890")) + // Spaces and groups, as sites show them. + spaced := plain[:4] + " " + plain[4:8] + "-" + plain[8:] + for _, in := range []string{plain, spaced, " " + strings.ToUpper(plain) + " "} { + k, err := Parse([]byte(in)) + if err != nil { + t.Fatalf("Parse: %v", err) + } + if k.Digits() != 6 || k.Period() != 30*time.Second || k.Algorithm() != SHA1 { + t.Fatalf("defaults: %d %v %s", k.Digits(), k.Period(), k.Algorithm()) + } + got, _ := k.Code(time.Unix(59, 0)) + if got != "287082" { + t.Errorf("got %s, want 287082", got) + } + } +} + +func TestOtherDigitsAndPeriod(t *testing.T) { + k, err := Parse([]byte("otpauth://totp/x?secret=" + b32("12345678901234567890") + "&digits=7&period=60")) + if err != nil { + t.Fatal(err) + } + if k.Digits() != 7 || k.Period() != time.Minute { + t.Fatalf("got %d %v", k.Digits(), k.Period()) + } + a, _ := k.Code(time.Unix(60, 0)) + b, _ := k.Code(time.Unix(119, 0)) + c, _ := k.Code(time.Unix(120, 0)) + if len(a) != 7 || a != b || a == c { + t.Fatalf("codes %s %s %s", a, b, c) + } + if k.Step(time.Unix(119, 0)) != 1 || k.Step(time.Unix(120, 0)) != 2 { + t.Fatal("step") + } +} + +func TestRefused(t *testing.T) { + sec := b32("12345678901234567890") + cases := []struct { + in string + want error + }{ + {"", ErrEmpty}, + {" ", ErrEmpty}, + {"steam://" + sec, ErrForm}, + {"otpauth://hotp/x?secret=" + sec + "&counter=1", ErrForm}, + {"https://example.com/?secret=" + sec, ErrForm}, + {"otpauth://totp/x?secret=" + sec + "&algorithm=MD5", ErrAlgorithm}, + {"otpauth://totp/x?secret=" + sec + "&digits=5", ErrDigits}, + {"otpauth://totp/x?secret=" + sec + "&digits=9", ErrDigits}, + {"otpauth://totp/x?secret=" + sec + "&digits=six", ErrDigits}, + {"otpauth://totp/x?secret=" + sec + "&period=0", ErrPeriod}, + {"otpauth://totp/x?secret=" + sec + "&period=3601", ErrPeriod}, + {"otpauth://totp/x?secret=" + sec + "&period=-30", ErrPeriod}, + {"otpauth://totp/x?secret=" + sec + "&secret=" + sec, ErrForm}, + {"otpauth://totp/x?digits=6", ErrEmpty}, + {"otpauth://totp/x?secret=", ErrEmpty}, + {"otpauth://totp/x?secret=abc1", ErrBase32}, + {"otpauth://totp/x?secret=GEZD%47NBV", ErrBase32}, + {"otpauth://totp/x?secret=GEZD+GNBV", ErrBase32}, + {"otpauth://totp", ErrForm}, + {"otpauth://totp/x?" + sec, ErrForm}, + {"otpauth://totp/x?secret=" + sec + "&SECRET=" + sec, ErrForm}, + {"otpauth://totp/x", ErrEmpty}, + {"otpauth://totpx/x?secret=" + sec, ErrForm}, + {"not base32!", ErrBase32}, + {"A", ErrBase32}, + {strings.Repeat("A", maxField+1), ErrForm}, + } + for _, c := range cases { + _, err := Parse([]byte(c.in)) + if !errors.Is(err, c.want) { + t.Errorf("Parse(%.30q): got %v, want %v", c.in, err, c.want) + } + } +} + +func TestErrorsHoldNoSeed(t *testing.T) { + seed := "JBSWY3DPEHPK3PXP" + for _, in := range []string{ + "steam://" + seed, + "otpauth://totp/x?secret=" + seed + "&algorithm=MD5", + "otpauth://totp/x?secret=" + seed + "!", + seed + "1", + } { + _, err := Parse([]byte(in)) + if err == nil { + t.Fatalf("no error for %q", in) + } + if strings.Contains(err.Error(), seed) { + t.Fatal("an error holds the seed") + } + } +} + +func TestKeyHidesSeed(t *testing.T) { + seed := "12345678901234567890" + k, err := Parse([]byte(b32(seed))) + if err != nil { + t.Fatal(err) + } + enc := b32(seed) + for _, s := range []string{ + fmt.Sprint(k), fmt.Sprintf("%v %+v %#v %s %q %x", k, k, k, k, k, k), + fmt.Sprint(&k), fmt.Sprintf("%+v", struct{ K Key }{k}), + } { + if strings.Contains(s, seed) || strings.Contains(s, enc) || strings.Contains(s, "3132") { + t.Fatalf("format shows the seed: %s", s) + } + } + if _, err := json.Marshal(k); err == nil { + t.Fatal("JSON encoded the key") + } + var b strings.Builder + slog.New(slog.NewTextHandler(&b, nil)).Info("x", "key", k) + if strings.Contains(b.String(), enc) || strings.Contains(b.String(), seed) { + t.Fatal("log shows the seed") + } +} + +func TestClear(t *testing.T) { + k, _ := Parse([]byte(b32("12345678901234567890"))) + seed := k.seed + k.Clear() + for _, c := range seed { + if c != 0 { + t.Fatal("seed not cleared") + } + } + if _, err := k.Code(time.Unix(59, 0)); !errors.Is(err, ErrCleared) { + t.Fatalf("Code after Clear: %v", err) + } + var zero Key + if _, err := zero.Code(time.Unix(59, 0)); !errors.Is(err, ErrCleared) { + t.Fatalf("Code of zero key: %v", err) + } +} + +func TestInputNotKept(t *testing.T) { + in := []byte("otpauth://totp/x?secret=" + b32("12345678901234567890")) + k, err := Parse(in) + if err != nil { + t.Fatal(err) + } + clear(in) + if got, _ := k.Code(time.Unix(59, 0)); got != "287082" { + t.Fatalf("the key uses the caller's buffer: %s", got) + } +} + +func TestBeforeEpoch(t *testing.T) { + k, _ := Parse([]byte(b32("12345678901234567890"))) + if _, err := k.Code(time.Unix(-1, 0)); err == nil { + t.Fatal("no error before 1970") + } +} + +func FuzzParse(f *testing.F) { + f.Add("otpauth://totp/x?secret=JBSWY3DPEHPK3PXP&digits=8") + f.Add("JBSWY3DPEHPK3PXP") + f.Add("steam://JBSWY3DPEHPK3PXP") + f.Fuzz(func(t *testing.T, in string) { + k, err := Parse([]byte(in)) + if err != nil { + return + } + code, err := k.Code(time.Unix(1234567890, 0)) + if err != nil || len(code) != k.Digits() { + t.Fatalf("parsed key makes no code: %v", err) + } + }) +}