diff --git a/AGENTS.md b/AGENTS.md index 65b0791..1012e12 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,8 +21,8 @@ Planned. Each v1 issue adds its part. binary with `go:embed`, for `nodkey update`. The tests of the script are in `install_linux_test.go`. CI checks it with shellcheck. - `cmd/nodkey/` - the one binary. Subcommands: `broker`, `try`, `run`, - `ssh-agent`, `ssh-grant`, `preapprove`, `keygen`, `audit verify`, `update`, - `version`, `doctor`. + `ssh-agent`, `ssh-grant`, `preapprove`, `agent-browser-plugin`, `keygen`, + `audit verify`, `update`, `version`, `doctor`. `nodkey broker` starts the broker's parts in a fixed order, and stops them in a fixed order (DESIGN.md section 15). Its tests run it in a child process, with a fake Telegram server behind a fake HTTPS proxy. @@ -58,7 +58,9 @@ Planned. Each v1 issue adds its part. (config, TLS key, deadline, short code, strict answer), `nodkey run` (DESIGN.md sections 5 and 15), `nodkey ssh-agent` (sections 6 and 15), `nodkey ssh-grant` (sections 13 and 15) and - `nodkey preapprove` (sections 8 and 15). + `nodkey preapprove` (sections 8 and 15), and `nodkey agent-browser-plugin` + (section 21.10), with recorded requests of agent-browser in + `testdata/`. - `contrib/systemd/` - the example systemd unit of the broker, with encrypted credentials and a sandbox (DESIGN.md section 16). - `docs/` - the guides for people: @@ -72,6 +74,8 @@ Planned. Each v1 issue adds its part. server, on Android and on an iPhone (issue #24), with a table for the results. - `docs/releasing.md` - how releases are made and checked. + - `docs/agent-browser.md` - website logins with agent-browser: the + plugin entry, the login steps and the `agents` Chrome profile. - `docs_test.go` (at the root of the module) checks that no shell block in a Markdown file at the root or in `docs/` ends a command line with a `#` comment: zsh does not treat it as a comment (#92). diff --git a/DESIGN.md b/DESIGN.md index e9ad746..aa0a62b 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -104,6 +104,7 @@ One static Go binary holds all parts. The subcommand picks the role: | `nodkey update` | both, as root | Install a release in place of this binary, with the install script that is built into it (section 18). | | `nodkey doctor` | both | Check the setup, read only, and say how to fix what is wrong (section 15). | | `nodkey version` | both | Print the version. On a terminal, also say if a newer release is out. | +| `nodkey agent-browser-plugin` | agent machine | The credential plugin of agent-browser. agent-browser runs it; a person does not (section 21.10). | `nodkey try` runs the real broker parts on `127.0.0.1` of one machine, but with its own approver (the terminal) and its own store (three fake @@ -1965,7 +1966,7 @@ The fields of each event, after `seq`, `time`, `event` and `prev`: | `grant_ended` | the request fields of the `preapprove` request that made the grant, with its `grant_id`; `cause`: `used_up`, `ended`, `cancelled`, `denied`, `revoked`, `stopped`, `alarm`, `renewed` or `config_changed`; `uses_left` | | `grant_alarm` | the request fields; `grant_id` (none for an unknown token); `cause`: `old_token`, `over_uses`, `outside_window`, `unknown_token` or `missed_window` | | `secret_sent`, `signed` | the request fields | -| `denied` | the request fields; `cause`: `approver`, `expired`, `cancelled`, `not_allowed`, `limit` or `error` | +| `denied` | the request fields; `cause`: `approver`, `expired`, `cancelled`, `not_allowed`, `limit`, `error`, or `no_tap` (a website login with the no-tap header that nothing covered, section 21.10) | | `foreign_tap` | Telegram only. `user_id`, `chat_id`, `message_id`, `data`: the button data, at most 64 bytes, and `cause`: why it did not count (section 7). An entry with cause `edited_message` can belong to a Deny that counted: its `data` is `d:` and the request ID, and that request has a `decision` entry with `deny` | | `error` | the request fields, if the failure is about one request; `code`: `store_failed`, `sign_failed`, `approver_failed` or `poll_conflict` | | `log_recovered` | `torn_length` and `torn_sha256`: the length and the SHA-256 of the torn line | @@ -3192,6 +3193,8 @@ nodkey ssh-grant --key NAME --user USER --host NAME... --for DURATION [--reason nodkey preapprove (--secret NAME... | --key NAME --user USER --host NAME...) --until TIME --uses N [--from TIME] [--reason TEXT] nodkey preapprove --secret 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 --cancel ID +nodkey preapprove --login ITEM --url URL [--reason TEXT] +nodkey agent-browser-plugin nodkey try nodkey try run [--secret VAR=NAME]... [--reason TEXT] -- COMMAND [ARGS...] nodkey keygen --out FILE @@ -4537,9 +4540,10 @@ 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). +one-use pre-approval and the audit events. The agent-browser plugin of +#104 is built (21.10). Not built yet: standing grants for logins (a +request with a grant token is refused), and a reload that changes +`[logins.*]`. ### 21.1 The owner's setup @@ -4790,3 +4794,103 @@ password, a TOTP seed, a TOTP code or a username. 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). + +### 21.10 The agent-browser plugin *(built: `internal/client/abplugin.go`)* + +Issue #104. `nodkey agent-browser-plugin` is the credential plugin of +[agent-browser](https://github.com/vercel-labs/agent-browser). It is a +subcommand of `nodkey`, so it ships in the same signed release (#104 +open question 4). agent-browser runs it once for each request: it writes +one JSON request to the plugin's stdin and reads one JSON answer from +its stdout. This is the protocol `agent-browser.plugin.v1`. + +**Tested version: agent-browser 0.38.1** (`PluginVersion`). The tests +send requests that agent-browser 0.38.1 wrote to a recording plugin on +2026-11-13 (`internal/client/testdata/agent-browser-0.38.1/`). Another +version may change the protocol: test it before you use it. + +The config of agent-browser (`~/.agent-browser/config.json`) runs it: + +```json +{"plugins": [{"name": "nodkey", "command": "/usr/local/bin/nodkey", + "args": ["agent-browser-plugin"], + "capabilities": ["credential.read", "command.run"]}]} +``` + +agent-browser does not split `command` at spaces: the subcommand goes in +`args`. + +**The flow.** agent-browser waits only 15 seconds for +`credential.resolve` and 60 seconds for `plugin run`. A tap often takes +longer. So the tap comes first, in a nodkey command that waits as long +as any other request (21.7): + +1. `nodkey preapprove --login ITEM --url URL`. The person taps Approve. +2. Within `LoginPreapproveTime` (60 s) after the tap: + `agent-browser auth login NAME --credential-provider nodkey --item ITEM --url URL`. + The plugin asks the broker for the login with the no-tap header. The + pre-approval covers it, and is used up. +3. If the site asks for a code: + `agent-browser plugin run nodkey nodkey.totp --payload '{"itemRef":"ITEM","url":"URL"}'`, + within `LoginTOTPTime` (2 minutes) after the login (21.3). + +**The no-tap header.** The plugin's login request has the header +`Nodkey-No-Tap: 1` (`api.NoTapHeader`). The broker runs every check of +21.3 as for any login. Then, when no `window` grant and no pre-approval +covers the login, it answers 428 Precondition Required at once, with a +`denied` entry with the cause `no_tap`. It sends no message, so the +phone never shows a request that agent-browser has already given up on. +Another value of the header is refused (403, `not_allowed`). The header +only takes away the tap: it never allows what a tap would not. Other +paths ignore it. + +**Requests and answers.** Each answer has `"protocol": +"agent-browser.plugin.v1"` and `success`. + +| request `type` | capability | request fields | answer | +|---|---|---|---| +| `credential.resolve` | `credential.read` | `itemRef`: the item ID (a UUID); `url`: the page; `profileName` is not used | `credential`: `username`, `password`, and `url` (the page of the request, without its fragment) | +| `nodkey.list` | `command.run` | `url`: the page | `data.logins`: `id`, `name` and `username` of each item that matches the page (21.3 step 1); never a password | +| `nodkey.totp` | `command.run` | `itemRef`, `url` | `data.code`: one TOTP code (21.3 step 3) | +| `plugin.manifest` | any | none | `manifest`: the name `nodkey` and the two capabilities | + +- `itemRef` must be an item ID, not an item name: names can repeat + (#104 open question 2). `nodkey.list` shows the IDs. +- A request with no `url`, or `url` null, is refused (#104 open question + 3): the broker always needs a page to check and to show. agent-browser + sends null when the command has no `--url` and its auth profile has + none. +- The plugin checks the page as the broker does (21.4) before it loads + the config: an `http` page is refused at once. +- The plugin waits for the broker at most `PluginResolveTime` (12 s) for + `credential.resolve`, and `PluginCommandTime` (50 s) for the others, + so its answer comes before agent-browser stops it. +- **A refusal** is `"success": false` with an `error` that starts with + `nodkey: `, and one line on stderr. The error is a fixed text of + nodkey, or an error of the client config (with its path, or the + broker's address). It never holds a value, the item reference or the + page. The + exit code is 0 whenever an answer is written, because agent-browser + 0.38.1 drops the answer of a plugin that exits with another code. For + `credential.resolve`, agent-browser shows only "returned + success=false", not the error; `plugin run` shows the error. +- **The password** is written into one buffer of exactly the size of the + answer, which is cleared after the write. A password that is not UTF-8 + text is refused: a JSON string cannot hold it. +- The plugin reads at most 64 KiB from stdin. It ignores fields of the + request that it does not use, so a new optional field of agent-browser + does not break it. A field that it uses must have the right type. + +**Where the values go.** agent-browser's daemon reads the answer of +`credential.resolve` and fills the form. agent-browser's normal output +shows only "Logged in as NAME". The TOTP code of `nodkey.totp` is +printed by `plugin run`, for the agent to fill: it is good for one +period, and only one is given for each login. Neither the plugin nor the +broker writes a password, a seed or a code to a log or the audit log. +The agent can still read a filled field, and it has the session after +the login (THREAT-MODEL.md T48). + +**Chrome's "Save password?" prompt.** A Chrome that an agent drives +offers to save a filled password in Chrome's own password manager. +`docs/agent-browser.md` shows the `agents` Chrome profile that turns it +off. diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md index 2b35a2c..596b020 100644 --- a/THREAT-MODEL.md +++ b/THREAT-MODEL.md @@ -1607,6 +1607,48 @@ What nodkey does: 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). +**T48. The agent-browser plugin hands a login to the agent.** +The credential plugin (DESIGN.md section 21.10) answers agent-browser +with the username and the password, and `nodkey.totp` prints a TOTP +code. agent-browser fills the form. +What nodkey does: +- The plugin never asks for a tap: its login request has the no-tap + header. A login goes out only on a pre-approval that the person + tapped for that client, item and page (T47), or a `window` grant of + that item. Without one, the broker answers at once and sends no + message, so the phone never shows a request that nobody waits for. +- The header only takes away the tap. Every check of a login runs as + before: the client, the item, the collection, the page, the rule. +- The plugin sends the page of the request to the broker, which checks + it against the item's URIs (T43). It answers with that page, without its + fragment, as the credential's URL; agent-browser then opens it, or with `--no-navigate` + checks that the open page has its origin. This protects an agent that + is fooled by a wrong page. +- A request with no page, an `http` page, or an item name in place of an + item ID is refused. +- The plugin writes the password only into its answer on stdout, in one + buffer that it clears after. Its errors are texts of nodkey (with + at most the path of the client config or the broker's address), never + a value, the item reference or the page. The audit log has no password, username, + seed or code (DESIGN.md section 21.8). +What nodkey does not do: +- The agent can read a filled field, and it gets the session cookies + after the login. The tap is the guard; the password is not secret from + the agent. +- The page in the request is the agent's claim. An agent that attacks + can run the plugin, or call the broker, itself, and use the password + on another page (T43). +- A TOTP code passes through the agent's output. It is good for one + period, and the broker gives one code for each login. +- agent-browser's own code is not nodkey's: a bug in it could show the + password in its output. The tests pin version 0.38.1. +- Chrome offers to save the filled password. With a lasting profile, a + person who clicks Save leaves the password on the agent machine's + disk. The `agents` Chrome profile of docs/agent-browser.md turns the + offer off. +Risk that remains: medium, as for every value that an agent gets (section +5). + ## 7. Assumptions - The broker host is patched, has no agent on it, and only the owner has diff --git a/cmd/nodkey/abplugin.go b/cmd/nodkey/abplugin.go new file mode 100644 index 0000000..aa4a129 --- /dev/null +++ b/cmd/nodkey/abplugin.go @@ -0,0 +1,14 @@ +package main + +import ( + "io" + + "github.com/code6x/nodkey/internal/client" +) + +// runAgentBrowserPlugin runs nodkey agent-browser-plugin (package client): +// the credential plugin of agent-browser (DESIGN.md section 21.10). +func runAgentBrowserPlugin(args []string, stdin io.Reader, stdout, stderr io.Writer) int { + ignoreBrokenPipe() + return client.AgentBrowserPlugin(args, stdin, stdout, stderr, version) +} diff --git a/cmd/nodkey/main.go b/cmd/nodkey/main.go index bef6110..3d78a26 100644 --- a/cmd/nodkey/main.go +++ b/cmd/nodkey/main.go @@ -46,6 +46,8 @@ Commands: ssh-grant ask once for SSH logins to a list of hosts, for some minutes preapprove ask now for a grant to use later: secrets or SSH logins, in a time span, for a number of uses + agent-browser-plugin + the credential plugin of agent-browser; agent-browser runs it audit verify FILE [--anchor SEQ:HASH]... [--anchors FILE|-] check the hash chain of an audit log, and its anchors update [--version X.Y.Z] [--gh PATH] [--reinstall | --notes] @@ -112,6 +114,8 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { return runSSHGrant(rest, stderr) case "preapprove": return runPreapprove(rest, stdout, stderr) + case "agent-browser-plugin": + return runAgentBrowserPlugin(rest, stdin, stdout, stderr) case "update": return runUpdate(rest, stdout, stderr) case "changes": @@ -206,7 +210,7 @@ func runHelp(args []string, stdin io.Reader, stdout, stderr io.Writer) int { // commands are the commands of nodkey that "nodkey help COMMAND" knows. // Each must handle --help before it does any work. -var commands = []string{"broker", "try", "keygen", "audit", "run", "ssh-agent", "ssh-grant", "preapprove", "update", "changes", "doctor", "version"} +var commands = []string{"broker", "try", "keygen", "audit", "run", "ssh-agent", "ssh-grant", "preapprove", "agent-browser-plugin", "update", "changes", "doctor", "version"} // recordingWriter keeps the first write error, because the usage // functions of the commands ignore it. diff --git a/docs/agent-browser.md b/docs/agent-browser.md new file mode 100644 index 0000000..59cd53b --- /dev/null +++ b/docs/agent-browser.md @@ -0,0 +1,153 @@ +# Website logins with agent-browser + +An agent logs in to a website with +[agent-browser](https://github.com/vercel-labs/agent-browser). nodkey is +its credential plugin: after your tap on the phone, the plugin gives +agent-browser one login from the shared Bitwarden collection. +agent-browser fills the form. The password is not in the agent's +commands or in agent-browser's normal output. + +Tested with **agent-browser 0.38.1**, on 2026-11-13. Another version may +speak another protocol. Use 0.38.1, or test the new version first +(DESIGN.md section 21.10). + +What the agent can still see: a filled field, if it reads it; the +session after the login; and a TOTP code, which it fills itself +(THREAT-MODEL.md T48). + +## Before you start + +- The broker hands out website logins: [setup.md, "Website logins: a + shared collection"](setup.md#website-logins-a-shared-collection). The + rule of the items needs `preapprove = true`. +- nodkey is installed on the agent machine, and `nodkey doctor` shows no + problem. +- agent-browser 0.38.1 is installed on the agent machine. + +## 1. Add the plugin to agent-browser + +As the user of the agent, put this into `~/.agent-browser/config.json`. +If the file has other settings, add only the `plugins` entry. + +```json +{ + "plugins": [ + { + "name": "nodkey", + "command": "/usr/local/bin/nodkey", + "args": ["agent-browser-plugin"], + "capabilities": ["credential.read", "command.run"] + } + ] +} +``` + +Give the full path of `nodkey` (`command -v nodkey` shows it). Put +`agent-browser-plugin` into `args`: agent-browser does not split +`command` at spaces. Check it: + +```sh +agent-browser plugin show nodkey +``` + +## 2. Log in + +Each login takes three steps. Use the page of the login form for +`--url`, the same in each step. + +1. Find the item ID. The list needs no tap. + + ```sh + agent-browser plugin run nodkey nodkey.list --payload '{"url":"https://example.com/sign-in"}' + ``` + + It prints the ID, the name and the username of each login for the + page, and never a password. + +2. Ask for the tap. This waits until you tap Approve on the phone, as + long as any other nodkey request: + + ```sh + nodkey preapprove --login 11111111-1111-1111-1111-111111111111 --url https://example.com/sign-in + ``` + +3. Within 60 seconds after the tap, log in: + + ```sh + agent-browser auth login example --credential-provider nodkey --item 11111111-1111-1111-1111-111111111111 --url https://example.com/sign-in + ``` + + It prints `Logged in as 'example'`. The tap allows this one login; + the next login needs a new tap. + +Why the tap comes first: agent-browser waits only 15 seconds for a +plugin, and a tap often takes longer. The plugin itself never asks for a +tap. + +When the login form is already open, after some clicks, add +`--no-navigate`. agent-browser then checks that the open page has the +origin of `--url`. + +### A code from an authenticator app (TOTP) + +When the site asks for a code after the password, get it within 2 +minutes after the login: + +```sh +agent-browser plugin run nodkey nodkey.totp --payload '{"itemRef":"11111111-1111-1111-1111-111111111111","url":"https://example.com/sign-in"}' +``` + +It prints the code, and the agent fills it. The broker makes the code; +the seed never leaves it. You get one code for each login. + +## When it fails + +| what you see | why | what to do | +|---|---|---| +| `Plugin 'nodkey' returned success=false` after `auth login` | agent-browser does not show the reason. Most often: no tap first, or more than 60 seconds since the tap | Run `nodkey preapprove --login` again, then `auth login` at once. The broker's audit log has the cause; `no_tap` means no tap | +| `Failed to start plugin 'nodkey'` | the `command` is not a path to `nodkey`, or the subcommand is in `command` | Fix step 1 | +| `nodkey: the item is not an item ID` | `--item` is a name | Use the ID from `nodkey.list` | +| `nodkey: the request has no page URL` | no `--url` | Give `--url` with the page of the login | +| `nodkey: the page URL: ... not https` | the page is `http` | nodkey hands out logins only for `https` pages | +| `nodkey: totp: denied` | no login in the last 2 minutes, or the code was already given | Log in again, then ask for the code | + +## 3. Stop Chrome from saving passwords: the `agents` profile + +A Google Chrome that an agent drives offers to save a filled password in +Chrome's own password manager ("Save password?"). The offer is outside +the page, so the agent does not see it. But a person at the screen can +click Save, and with a lasting profile the password then stays on the +disk of the agent machine. The command line flag +`--disable-save-password-bubble` no longer works. + +Make one Chrome profile for agents, with saving turned off. +agent-browser copies a named profile to a new temporary folder for each +session, so every session starts from it. Make it in Chrome itself: +agent-browser finds profiles by their names in Chrome's `Local State` +file, and a folder made by hand is not found. + +**These steps are not yet tested from start to end.** A profile with the +two settings of step 7 is tested: Chrome 153 shows no prompt with it. + +Once, on the agent machine, as the user of the agent: + +1. In Chrome: the profile menu, then **Add**, then **Continue without an + account**. Name the profile `agents`. +2. In the window of that profile, open + `chrome://password-manager/settings`. Turn off **Offer to save + passwords** and **Sign in automatically**. +3. Open `chrome://settings/addresses`. Turn off saving and filling of + addresses. +4. Open `chrome://settings/payments`. Turn off saving and filling of + payment methods. +5. Close the window. Do not use this profile by hand, do not sign in to + Google in it, and do not add extensions to it: every agent session + gets a copy of it. +6. In `~/.agent-browser/config.json`, add `"profile": "agents"`. +7. Check: the `Preferences` file in the profile's folder has + `"credentials_enable_service": false` and + `"profile": {"password_manager_enabled": false}`. Then do a test login + (section 2): Chrome must show no "Save password?" prompt. + +**Never unlock your own vault in this browser**, or in any browser or app +that an agent can drive (THREAT-MODEL.md T32 and T46). diff --git a/docs/setup.md b/docs/setup.md index e3b7102..ed053cd 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -942,9 +942,8 @@ access to it: such an account could read them too. ### 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. +> The browser part is the agent-browser plugin: see +> [docs/agent-browser.md](agent-browser.md) after these steps. 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 @@ -1028,6 +1027,9 @@ account. once, and only in the 60 seconds after the tap. The rule of the item needs `preapprove = true`. +9. **Set up agent-browser** on the client, as + [docs/agent-browser.md](agent-browser.md) shows. + **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 diff --git a/internal/api/api.go b/internal/api/api.go index a86d0ed..4d2ac69 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -118,6 +118,18 @@ func KeyWindow(h http.Header) (window time.Duration, ok bool) { // value is a secret: never print or log it. const GrantTokenHeader = "Nodkey-Grant-Token" //nolint:gosec // G101: a header name, not a credential. +// NoTapHeader, with the value NoTapValue, asks the broker not to ask +// the person for a request for a website login (PathLogin). When no grant +// and no pre-approval covers the login, the broker answers 428 Precondition +// Required at once, and sends no message (DESIGN.md section 21.10). The +// agent-browser plugin sends it: agent-browser waits only 15 seconds, too +// short for a tap. The broker refuses another value; other paths ignore +// the header. +const NoTapHeader = "Nodkey-No-Tap" + +// NoTapValue is the only value of NoTapHeader. +const NoTapValue = "1" + // Version returns the version in the header VersionHeader of a request or // an answer. It returns "" when there is no such header, more than one, // or a value that version.Valid refuses. Such a value counts as no diff --git a/internal/approval/decide.go b/internal/approval/decide.go index 6ee5bea..8f8983c 100644 --- a/internal/approval/decide.go +++ b/internal/approval/decide.go @@ -56,6 +56,7 @@ type pending struct { once bool // the message has "Approve once" windowMinutes int // the message has "Approve N min" with this N; 0: no notify bool // a "never ask" rule with notify allowed it + noTap bool // Request.NoTap: deny when nothing covers the request // used is the scheduled grant that allowed p, and whose use p took. // preCounted says that p counts in clientState.preapproving. @@ -167,9 +168,10 @@ func (c *Core) Decide(ctx context.Context, r *Request) *Result { return c.denied(p, audit.CauseNotAllowed) } p.deadline = p.start.add(c.timeout(r.Kind)) - if !c.check(r, p) { + if !c.check(r, p) || (r.NoTap && p.kind != audit.KindWebLogin) { return c.denied(p, audit.CauseNotAllowed) } + p.noTap = r.NoTap if p.kind == audit.KindSSHGrant { // Its grants end at a fixed time. After it, an approval would // grant nothing, so the request ends then too. @@ -312,6 +314,10 @@ func (c *Core) begin(p *pending) *Result { } return res } + if p.noTap { + // Nothing covers it, and the client asked for no tap: no message. + return c.denied(p, audit.CauseNoTap) + } if c.stopped { return c.failed(p, ErrStopped) } diff --git a/internal/approval/login_test.go b/internal/approval/login_test.go index c809e70..eebf868 100644 --- a/internal/approval/login_test.go +++ b/internal/approval/login_test.go @@ -412,3 +412,43 @@ func TestLoginReload(t *testing.T) { } }) } + +// TestLoginNoTap: with NoTap, a login that nothing covers is denied with +// no_tap at once and asks nobody; a pre-approval still covers it. NoTap on +// a request of another kind, or on a login pre-approval, is not allowed. +func TestLoginNoTap(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := loginEnv(t) + defer e.stop() + noTap := func() *approval.Request { + r := webLogin(e, "laptop", itemA) + r.NoTap = true + return r + } + if res := e.now(noTap()); res.Allowed || res.Cause != audit.CauseNoTap { + t.Errorf("no grant: %+v", res) + } + if n := len(e.fake.Asked()); n != 0 { + t.Errorf("%d messages, want 0", n) + } + e.grant(webPre(e, "laptop", itemA), 1) + if res := e.now(noTap()); !res.Allowed { + t.Errorf("pre-approved: %+v", res) + } + if res := e.now(noTap()); res.Allowed || res.Cause != audit.CauseNoTap { + t.Errorf("used up: %+v", res) + } + sec := secretsReq("laptop", "github-token") + sec.NoTap = true + pre := webPre(e, "laptop", itemB) + pre.NoTap = true + for _, r := range []*approval.Request{sec, pre} { + if res := e.now(r); res.Allowed || res.Cause != audit.CauseNotAllowed { + t.Errorf("%s: %+v", r.Kind, res) + } + } + if n := len(e.fake.Asked()); n != 1 { + t.Errorf("%d messages, want 1", n) + } + }) +} diff --git a/internal/approval/request.go b/internal/approval/request.go index 6e4aaa0..f974f9d 100644 --- a/internal/approval/request.go +++ b/internal/approval/request.go @@ -60,6 +60,12 @@ type Request struct { // Claim is the claimed text, made safe by the caller (see Claim). Claim Claim + // NoTap is for a KindWebLogin request only: when no grant and no + // pre-approval covers it, it is denied with audit.CauseNoTap at once, + // and no message is sent (DESIGN.md section 21.10). The core denies a + // request of another kind with NoTap. + NoTap bool + // OnWait, if set, is called once, with the short code, when the // request starts to wait for the person: when it goes into the queue // or its message is about to be sent. The client prints the code. It diff --git a/internal/audit/event.go b/internal/audit/event.go index d62394b..590d9ff 100644 --- a/internal/audit/event.go +++ b/internal/audit/event.go @@ -87,6 +87,9 @@ const ( CauseNotAllowed Cause = "not_allowed" // a check failed: an unknown name, a name this client may not use, bad input CauseLimit Cause = "limit" // a limit per client, the queue, the pause after a Deny, or a limit of the approver itself (DESIGN.md section 8) CauseError Cause = "error" // a failure; an error entry says which + // CauseNoTap: the client asked for no tap (api.NoTapHeader), and no + // grant or pre-approval covered the request (DESIGN.md section 21.10). + CauseNoTap Cause = "no_tap" ) // EndCause says why a scheduled grant ended (DESIGN.md section 8). @@ -769,7 +772,7 @@ func (e Denied) validate() error { return err } switch e.Cause { - case CauseApprover, CauseExpired, CauseCancelled, CauseNotAllowed, CauseLimit, CauseError: + case CauseApprover, CauseExpired, CauseCancelled, CauseNotAllowed, CauseLimit, CauseError, CauseNoTap: return nil } return errors.New("cause is not known") diff --git a/internal/broker/handler.go b/internal/broker/handler.go index c3188ed..15f668d 100644 --- a/internal/broker/handler.go +++ b/internal/broker/handler.go @@ -182,6 +182,8 @@ func statusFor(cause audit.Cause) int { return http.StatusTooManyRequests case audit.CauseError: return http.StatusServiceUnavailable + case audit.CauseNoTap: + return http.StatusPreconditionRequired default: return http.StatusForbidden } diff --git a/internal/broker/logins.go b/internal/broker/logins.go index 0523d78..4a98880 100644 --- a/internal/broker/logins.go +++ b/internal/broker/logins.go @@ -377,6 +377,15 @@ func (rq *request) logins(ctx context.Context, r *http.Request) { rq.refuseLogin(audit.Subject{}, "a grant token is not used for logins") return } + noTap := false + if v := r.Header.Values(api.NoTapHeader); len(v) > 0 { + if len(v) != 1 || v[0] != api.NoTapValue { + rq.releaseBody() + rq.refuseLogin(audit.Subject{}, "the no-tap header is not valid") + return + } + noTap = true + } page, item, ok := rq.loginInput(req.URL, req.Item) if !ok { return @@ -389,7 +398,7 @@ func (rq *request) logins(ctx context.Context, r *http.Request) { 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), + Client: rq.client, Kind: audit.KindWebLogin, Login: loginScope(sel, origin), NoTap: noTap, }) if !ok { return diff --git a/internal/broker/logins_test.go b/internal/broker/logins_test.go index a276211..322d438 100644 --- a/internal/broker/logins_test.go +++ b/internal/broker/logins_test.go @@ -881,3 +881,92 @@ func TestLoginPreapproveUsedOnce(t *testing.T) { t.Errorf("%d messages, want 2", n) } } + +// TestLoginNoTap: with the no-tap header, a login that nothing covers is +// answered with 428 at once, with no message and an entry with the cause +// no_tap. A pre-approval or a window grant still covers it. +func TestLoginNoTap(t *testing.T) { + l := newLoginEnv(t, nil) + noTap := func() *result { + return l.postHeader(api.PathLogin, l.loginReq(itemShop, pageShop), api.NoTapHeader, api.NoTapValue) + } + l.noMessage(noTap(), http.StatusPreconditionRequired) + found := false + for _, ev := range l.audit.all() { + if d, ok := ev.(audit.Denied); ok && d.Cause == audit.CauseNoTap && d.Item == itemShop { + found = true + } + } + if !found { + t.Error("no denied entry with the cause no_tap") + } + // A value other than "1" is refused, and asks nobody either. + l.noMessage(l.postHeader(api.PathLogin, l.loginReq(itemShop, pageShop), api.NoTapHeader, "yes"), http.StatusForbidden) + + // The pre-approval covers it, once. + mustStatus(t, l.loginPre(itemShop, pageShop), http.StatusOK) + res := noTap() + mustStatus(t, res, http.StatusOK) + if !strings.Contains(string(res.body), `"username":"alice@example.com"`) { + t.Error("the answer has no username") + } + mustStatus(t, noTap(), http.StatusPreconditionRequired) + if n := len(l.approver.Asked()); n != 1 { + t.Errorf("%d messages, want 1 (the pre-approval)", n) + } + + // A window grant covers it too. + res = l.approveLogin(itemMail, pageShop, audit.AnswerApproveWindow) + mustStatus(t, res, http.StatusOK) + mustStatus(t, l.postHeader(api.PathLogin, l.loginReq(itemMail, pageShop), api.NoTapHeader, api.NoTapValue), http.StatusOK) + l.vs.checkCleared(t) +} + +// TestLoginNoTapReprompt: an item with a re-prompt needs a tap for each +// login; with the no-tap header it gets 428, also after a tap on the +// window button. +func TestLoginNoTapReprompt(t *testing.T) { + l := newLoginEnv(t, nil) + l.shop.Reprompt = true + l.noMessage(l.postHeader(api.PathLogin, l.loginReq(itemShop, pageShop), api.NoTapHeader, api.NoTapValue), + http.StatusPreconditionRequired) + n := len(l.approver.Asked()) + 1 + p := l.start(l.laptp, api.PathLogin, l.loginReq(itemShop, pageShop)) + pr := l.waitAsked(n)[n-1].Prompt + if err := l.approver.Tap(pr.RequestID, audit.AnswerApproveWindow); err == nil { + t.Fatal("the message of a re-prompt item offers the window button") + } + l.tap(pr.RequestID, audit.AnswerApproveOnce) + mustStatus(t, p.wait(t), http.StatusOK) + mustStatus(t, l.postHeader(api.PathLogin, l.loginReq(itemShop, pageShop), api.NoTapHeader, api.NoTapValue), + http.StatusPreconditionRequired) +} + +// TestLoginNoTapHeaderValues: the header twice, empty, or with another +// value is refused, and asks nobody. +func TestLoginNoTapHeaderValues(t *testing.T) { + l := newLoginEnv(t, nil) + for _, values := range [][]string{{"1", "1"}, {""}, {"0"}, {"true"}} { + data, err := json.Marshal(l.loginReq(itemShop, pageShop)) + if err != nil { + t.Fatal(err) + } + req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "https://"+l.addr+api.PathLogin, bytes.NewReader(data)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", api.ContentType) + req.Header[api.NoTapHeader] = values + resp, err := l.laptp.Do(req) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusForbidden { + t.Errorf("%q: status %d, want 403", values, resp.StatusCode) + } + } + if n := len(l.approver.Asked()); n != 0 { + t.Errorf("%d messages, want 0", n) + } +} diff --git a/internal/client/abplugin.go b/internal/client/abplugin.go new file mode 100644 index 0000000..20a22c0 --- /dev/null +++ b/internal/client/abplugin.go @@ -0,0 +1,435 @@ +package client + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "time" + "unicode/utf8" + + "github.com/code6x/nodkey/internal/loginmatch" +) + +// nodkey agent-browser-plugin: the credential plugin of agent-browser +// (DESIGN.md section 21.10, issue #104). agent-browser runs it once for +// each request: it writes one JSON request to its stdin, and reads one +// JSON answer from its stdout. The protocol is agent-browser.plugin.v1, as +// agent-browser PluginVersion speaks it; the test with recorded requests is +// abplugin_test.go. + +// PluginProtocol is the protocol of agent-browser's plugins. +const PluginProtocol = "agent-browser.plugin.v1" + +// PluginVersion is the version of agent-browser whose requests the tests +// recorded (docs/agent-browser.md). +const PluginVersion = "0.38.1" + +const ( + // maxPluginRequest is the most bytes of a request on stdin. + maxPluginRequest = 64 << 10 + // PluginResolveTime is how long credential.resolve waits for the + // broker. agent-browser stops the plugin after 15 seconds; the answer + // must come before that. + PluginResolveTime = 12 * time.Second + // PluginCommandTime is how long nodkey.list and nodkey.totp wait for + // the broker. agent-browser stops "plugin run" after 60 seconds. + PluginCommandTime = 50 * time.Second +) + +// The request types and the capabilities of the plugin. +const ( + pluginManifest = "plugin.manifest" + pluginResolve = "credential.resolve" + pluginList = "nodkey.list" + pluginTOTP = "nodkey.totp" + capCredential = "credential.read" //nolint:gosec // G101: a capability name of agent-browser, not a credential. + capCommand = "command.run" +) + +const pluginUsage = `Usage: nodkey agent-browser-plugin + +The credential plugin of agent-browser (` + PluginVersion + `). agent-browser runs +it: it reads one request on stdin and writes one answer on stdout. Do not +run it by hand. Set it up in ~/.agent-browser/config.json: + + {"plugins": [{"name": "nodkey", "command": "/usr/local/bin/nodkey", + "args": ["agent-browser-plugin"], + "capabilities": ["credential.read", "command.run"]}]} + +Give the full path of nodkey. agent-browser does not split "command" at +spaces: the subcommand goes in "args". + +First let the person approve the login on the phone, then log in at once: + + nodkey preapprove --login ITEM --url https://example.com/sign-in + agent-browser auth login example --credential-provider nodkey \ + --item ITEM --url https://example.com/sign-in + +Requests: + credential.resolve the username and the password of the item --item, for + the page --url. It never asks for a tap: run + nodkey preapprove --login first. + nodkey.list agent-browser plugin run nodkey nodkey.list + --payload '{"url":"https://example.com/"}' + the logins for the page: item IDs, names, usernames + nodkey.totp agent-browser plugin run nodkey nodkey.totp + --payload '{"itemRef":"ITEM","url":"https://example.com/"}' + the current TOTP code, once, after the login + +Guide: docs/agent-browser.md. +` + +// pluginRunner holds the parts of the plugin that the tests replace. +type pluginRunner struct { + load func(path string) (*Broker, error) + configPath func() (string, error) + version string +} + +// AgentBrowserPlugin runs nodkey agent-browser-plugin, and returns the +// exit code. +func AgentBrowserPlugin(args []string, stdin io.Reader, stdout, stderr io.Writer, version string) int { + r := pluginRunner{load: Load, configPath: ConfigPath, version: version} + return r.run(context.Background(), args, stdin, stdout, stderr) +} + +// pluginError is a refusal of the plugin: its text goes into the answer +// and to stderr. code says what kind of refusal it is (exitUsage, +// exitDenied, exitUnavailable); the process still exits with 0. The text +// is a fixed text, or an error of this package (such as the path of the +// client config or the broker's address). It never holds a value, the +// item reference or the page. +type pluginError struct { + code int + text string +} + +func (r pluginRunner) run(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) int { + if len(args) == 1 && isHelp(args[0]) { + _, _ = io.WriteString(stderr, pluginUsage) + return exitOK + } + if len(args) > 0 { + return UsageError(stderr, "agent-browser-plugin", "it takes no arguments: agent-browser runs it, with the request on stdin") + } + answer, perr := r.serve(ctx, stdin, stderr) + if perr != nil { + // The exit code is 0 when the answer is written: agent-browser + // drops the answer of a plugin that exits with another code, and + // the agent would not see why. + _, _ = fmt.Fprintf(stderr, "nodkey agent-browser-plugin: %s\n", oneLine(perr.text)) + if !writePluginError(stdout, perr.text) { + return exitUnavailable + } + return exitOK + } + defer clear(answer) + if _, err := stdout.Write(answer); err != nil { + return fail(stderr, exitUnavailable, "cannot write the answer to agent-browser") + } + return exitOK +} + +// pluginRequest is the envelope of a request. Other fields are ignored. +type pluginRequest struct { + Protocol string `json:"protocol"` + Type string `json:"type"` + Capability string `json:"capability"` + Request json.RawMessage `json:"request"` +} + +// loginRef is the request of credential.resolve and nodkey.totp. A field +// that is missing or null stays nil. +type loginRef struct { + ItemRef *string `json:"itemRef"` + URL *string `json:"url"` +} + +// serve reads the request and returns the answer. +func (r pluginRunner) serve(ctx context.Context, stdin io.Reader, stderr io.Writer) ([]byte, *pluginError) { + data, err := io.ReadAll(io.LimitReader(stdin, maxPluginRequest+1)) + if err != nil { + return nil, &pluginError{exitUsage, "cannot read the request from stdin"} + } + if len(data) > maxPluginRequest { + return nil, &pluginError{exitUsage, fmt.Sprintf("the request is longer than %d bytes", maxPluginRequest)} + } + var req pluginRequest + if err := json.Unmarshal(data, &req); err != nil { + return nil, &pluginError{exitUsage, "the request is not a JSON object of " + PluginProtocol} + } + if req.Protocol != PluginProtocol { + return nil, &pluginError{exitUsage, "the request is not of the protocol " + PluginProtocol + + "; use agent-browser " + PluginVersion + ", the version that nodkey is tested with (docs/agent-browser.md)"} + } + var want string + switch req.Type { + case pluginManifest: + return manifestAnswer(), nil + case pluginResolve: + want = capCredential + case pluginList, pluginTOTP: + want = capCommand + default: + return nil, &pluginError{exitUsage, "unknown request type: nodkey answers " + pluginResolve + ", " + + pluginList + " and " + pluginTOTP} + } + if req.Capability != want { + return nil, &pluginError{exitUsage, "a " + req.Type + " request must have the capability " + want} + } + if len(req.Request) == 0 || req.Request[0] != '{' { + return nil, &pluginError{exitUsage, "the request has no \"request\" object"} + } + switch req.Type { + case pluginResolve: + return r.resolve(ctx, req.Request, stderr) + case pluginList: + return r.list(ctx, req.Request, stderr) + default: + return r.totp(ctx, req.Request, stderr) + } +} + +// checkRef checks the item and the page of credential.resolve and +// nodkey.totp. +func checkRef(raw json.RawMessage) (item, page string, perr *pluginError) { + var ref loginRef + if err := json.Unmarshal(raw, &ref); err != nil { + return "", "", &pluginError{exitUsage, "the request has no valid itemRef and url"} + } + if ref.ItemRef == nil || !itemIDPattern.MatchString(*ref.ItemRef) { + return "", "", &pluginError{exitUsage, "the item is not an item ID: give --item with the UUID that " + + "\"agent-browser plugin run nodkey nodkey.list\" lists for the page"} + } + if ref.URL == nil || *ref.URL == "" { + return "", "", &pluginError{exitUsage, "the request has no page URL: give agent-browser --url with the https page of the login"} + } + p, err := checkPage(*ref.URL) + if err != nil { + return "", "", err + } + return *ref.ItemRef, p, nil +} + +// checkPage checks a page URL as the broker does, for a clear error +// before the request. It returns the page as the broker reads it (with no +// fragment): the plugin sends that to the broker, and gives it back to +// agent-browser, so both see the same page. +func checkPage(page string) (string, *pluginError) { + p, err := loginmatch.ParsePage(page) + if err != nil { + return "", &pluginError{exitUsage, "the page URL: " + err.Error()} + } + return p.URL(), nil +} + +// broker loads the client config. +func (r pluginRunner) broker(stderr io.Writer) (*Broker, *pluginError) { + path, err := r.configPath() + if err != nil { + return nil, &pluginError{exitUnavailable, err.Error()} + } + b, err := r.load(path) + if err != nil { + return nil, &pluginError{exitUnavailable, err.Error()} + } + b.warnVersions(r.version, func(text string) { warnLine(stderr, text) }) + return b, nil +} + +// requestError turns the error of a request into a refusal. +func requestError(err error, what string) *pluginError { + var e *Error + switch { + case errors.As(err, &e) && e.NeedsTap(): + return &pluginError{exitDenied, what + ": it needs a tap first: run \"nodkey preapprove --login ITEM --url URL\", " + + "wait for the tap, then run agent-browser auth login within 60 seconds"} + case errors.As(err, &e) && e.Denied(): + return &pluginError{exitDenied, what + ": " + e.Error()} + case errors.Is(err, context.DeadlineExceeded): + return &pluginError{exitUnavailable, what + ": no answer from the broker in time"} + } + return &pluginError{exitUnavailable, what + ": " + err.Error()} +} + +func (r pluginRunner) resolve(ctx context.Context, raw json.RawMessage, stderr io.Writer) ([]byte, *pluginError) { + item, page, perr := checkRef(raw) + if perr != nil { + return nil, perr + } + b, perr := r.broker(stderr) + if perr != nil { + return nil, perr + } + ctx, cancel := context.WithTimeout(ctx, PluginResolveTime) + defer cancel() + ans, err := LoginNoTap(ctx, b, page, item) + if err != nil { + return nil, requestError(err, "login") + } + defer ans.Clear() + out, err := credentialAnswer(ans.Username, ans.Password, page) + if err != nil { + return nil, &pluginError{exitUnavailable, err.Error()} + } + return out, nil +} + +func (r pluginRunner) list(ctx context.Context, raw json.RawMessage, stderr io.Writer) ([]byte, *pluginError) { + var req struct { + URL *string `json:"url"` + } + if err := json.Unmarshal(raw, &req); err != nil || req.URL == nil || *req.URL == "" { + return nil, &pluginError{exitUsage, "give the page in the payload: {\"url\":\"https://example.com/\"}"} + } + page, perr := checkPage(*req.URL) + if perr != nil { + return nil, perr + } + b, perr := r.broker(stderr) + if perr != nil { + return nil, perr + } + ctx, cancel := context.WithTimeout(ctx, PluginCommandTime) + defer cancel() + ans, err := ListLogins(ctx, b, page) + if err != nil { + return nil, requestError(err, "list") + } + type entry struct { + ID string `json:"id"` + Name string `json:"name"` + Username string `json:"username"` + } + data := struct { + Logins []entry `json:"logins"` + }{Logins: []entry{}} + for _, l := range ans.Logins { + data.Logins = append(data.Logins, entry{ID: l.ID, Name: l.Name, Username: l.Username}) + } + return dataAnswer(data) +} + +func (r pluginRunner) totp(ctx context.Context, raw json.RawMessage, stderr io.Writer) ([]byte, *pluginError) { + item, page, perr := checkRef(raw) + if perr != nil { + return nil, perr + } + b, perr := r.broker(stderr) + if perr != nil { + return nil, perr + } + ctx, cancel := context.WithTimeout(ctx, PluginCommandTime) + defer cancel() + ans, err := LoginTOTP(ctx, b, page, item) + if err != nil { + var e *Error + if errors.As(err, &e) && e.Status == http.StatusForbidden { + return nil, &pluginError{exitDenied, "totp: denied: there was no login through nodkey for this item " + + "and page in the last 2 minutes, the code of that login was already given, or this machine or " + + "page may not use the item; log in again with agent-browser auth login, then ask for the code"} + } + return nil, requestError(err, "totp") + } + return dataAnswer(struct { + Code string `json:"code"` + }{Code: ans.Code}) +} + +// manifestAnswer is the answer to plugin.manifest. +func manifestAnswer() []byte { + return []byte(`{"protocol":"` + PluginProtocol + `","success":true,"manifest":{"name":"nodkey",` + + `"capabilities":["` + capCredential + `","` + capCommand + `"]}}` + "\n") +} + +// dataAnswer is the answer of a plugin run command. +func dataAnswer(data any) ([]byte, *pluginError) { + d, err := json.Marshal(data) + if err != nil { + return nil, &pluginError{exitUnavailable, "cannot write the answer"} + } + out := []byte(`{"protocol":"` + PluginProtocol + `","success":true,"data":`) + out = append(out, d...) + return append(out, "}\n"...), nil +} + +// writePluginError writes the answer of a refusal, and reports whether +// it could. text is a fixed text. +func writePluginError(w io.Writer, text string) bool { + t, _ := json.Marshal("nodkey: " + oneLine(text)) + _, err := fmt.Fprintf(w, `{"protocol":"%s","success":false,"error":%s}`+"\n", PluginProtocol, t) + return err == nil +} + +// errPasswordText refuses a password that is not UTF-8 text: a JSON +// string cannot hold it as it is. +var errPasswordText = errors.New("the password of the item is not UTF-8 text, so agent-browser cannot fill it; change it in Bitwarden") + +// credentialAnswer writes the answer of credential.resolve into one +// buffer of exactly its size, so that no copy of the password is left +// behind by a growing buffer. The caller must clear it. +func credentialAnswer(username string, password []byte, page string) ([]byte, error) { + if !utf8.Valid(password) { + return nil, errPasswordText + } + user, err := json.Marshal(username) + if err != nil { + return nil, err + } + u, err := json.Marshal(page) + if err != nil { + return nil, err + } + head := `{"protocol":"` + PluginProtocol + `","success":true,"credential":{"username":` + const mid, mid2, tail = `,"password":"`, `","url":`, "}}\n" + n := len(head) + len(user) + len(mid) + jsonEscapedLen(password) + len(mid2) + len(u) + len(tail) + b := make([]byte, 0, n) + b = append(b, head...) + b = append(b, user...) + b = append(b, mid...) + b = appendJSONEscaped(b, password) + b = append(b, mid2...) + b = append(b, u...) + b = append(b, tail...) + if len(b) != n { + clear(b) + return nil, errors.New("cannot write the answer") + } + return b, nil +} + +// jsonEscapedLen is the length of s escaped for a JSON string. +func jsonEscapedLen(s []byte) int { + n := 0 + for _, c := range s { + switch { + case c == '"' || c == '\\': + n += 2 + case c < 0x20: + n += 6 + default: + n++ + } + } + return n +} + +// appendJSONEscaped appends s, which is valid UTF-8, escaped for a JSON +// string, with no quotes. dst must have room: it never grows. +func appendJSONEscaped(dst, s []byte) []byte { + const hex = "0123456789abcdef" + for _, c := range s { + switch { + case c == '"' || c == '\\': + dst = append(dst, '\\', c) + case c < 0x20: + dst = append(dst, '\\', 'u', '0', '0', hex[c>>4], hex[c&0xf]) + default: + dst = append(dst, c) + } + } + return dst +} diff --git a/internal/client/abplugin_test.go b/internal/client/abplugin_test.go new file mode 100644 index 0000000..e121d3e --- /dev/null +++ b/internal/client/abplugin_test.go @@ -0,0 +1,496 @@ +package client + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/code6x/nodkey/internal/audit" + "github.com/code6x/nodkey/internal/config" + "github.com/code6x/nodkey/internal/store" + "github.com/code6x/nodkey/internal/totp" +) + +// The item and the pages of the recorded requests in +// testdata/agent-browser-0.38.1. +const ( + recItem = "11111111-1111-1111-1111-111111111111" + recPage = "https://127.0.0.1:18766/login.html" + recListPage = "https://example.com/" + recColl = "00000000-0000-0000-0000-0000000000aa" + // recSeed is the base32 form of "12345678901234567890", the seed of + // RFC 6238 appendix B. + recSeed = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" +) + +// recorded returns a recorded request of agent-browser. +func recorded(t *testing.T, name string) []byte { + t.Helper() + data, err := os.ReadFile(filepath.Join("testdata", "agent-browser-"+PluginVersion, name)) //nolint:gosec // G304: a file of the test data. + if err != nil { + t.Fatal(err) + } + return data +} + +// pluginLoginStore is a bw store with one login item, recItem, in the +// collection recColl. +type pluginLoginStore struct { + memStore + mu sync.Mutex + password string + given [][]byte +} + +func (s *pluginLoginStore) item() store.LoginItem { + host := 1 + return store.LoginItem{ + ID: recItem, Name: "Example shop", Username: "alice@example.com", Collections: []string{recColl}, + URIs: []store.LoginURI{{URI: "https://127.0.0.1:18766", Match: &host}, {URI: "https://example.com"}}, + } +} + +func (s *pluginLoginStore) ListLogins(_ context.Context, collection string) ([]store.LoginItem, error) { + if collection != recColl { + return nil, nil + } + return []store.LoginItem{s.item()}, nil +} + +func (s *pluginLoginStore) FetchLogin(_ context.Context, id string) (store.Login, error) { + if id != recItem { + return store.Login{}, fmt.Errorf("fake bw: not found: %w", store.ErrFailed) + } + s.mu.Lock() + defer s.mu.Unlock() + pw, seed := []byte(s.password), []byte(recSeed) + s.given = append(s.given, pw, seed) + return store.Login{LoginItem: s.item(), Password: store.NewValue(pw), TOTP: store.NewValue(seed)}, nil +} + +// cleared reports whether every password and seed that the store gave out +// is cleared. +func (s *pluginLoginStore) cleared() bool { + s.mu.Lock() + defer s.mu.Unlock() + for _, b := range s.given { + if !bytes.Equal(b, make([]byte, len(b))) { + return false + } + } + return true +} + +// pluginEnv is a test broker with [logins.web] for laptop: ask always, +// preapprove allowed. +type pluginEnv struct { + tb *testBroker + vs *pluginLoginStore + pw string +} + +func newPluginEnv(t *testing.T) *pluginEnv { + t.Helper() + // The password has the characters that JSON must escape. + pw := madeUp(`shop"pass\word`) + "\té" + vs := &pluginLoginStore{password: pw} + tb := newTestBrokerFull(t, "", func(cfg *config.Broker) { + cfg.Stores["vault"] = config.Store{Name: "vault", Type: config.StoreBW} + cfg.Preapprove = config.DefaultPreapprove() + cfg.Logins = map[string]config.Logins{"web": {Name: "web", Store: "vault", Collection: recColl, + Clients: []string{"laptop"}, Rule: config.Rule{Ask: config.AskAlways, Preapprove: true}}} + }, map[string]store.Store{"vault": vs}) + return &pluginEnv{tb: tb, vs: vs, pw: pw} +} + +// plugin runs nodkey agent-browser-plugin with the request req, and +// returns the exit code, stdout and stderr. +func (e *pluginEnv) plugin(t *testing.T, req []byte) (int, string, string) { + t.Helper() + var b *Broker + if e != nil { + b = e.tb.client(t) + } + return runPlugin(t, b, req) +} + +func runPlugin(t *testing.T, b *Broker, req []byte) (int, string, string) { + t.Helper() + r := pluginRunner{ + load: func(string) (*Broker, error) { + if b == nil { + return nil, errors.New("this test must not connect to a broker") + } + return b, nil + }, + configPath: func() (string, error) { return "/nonexistent/client.toml", nil }, + } + var stdout, stderr bytes.Buffer + code := r.run(t.Context(), nil, bytes.NewReader(req), &stdout, &stderr) + return code, stdout.String(), stderr.String() +} + +// pluginAnswer is an answer of the plugin. +type pluginAnswer struct { + Protocol string `json:"protocol"` + Success bool `json:"success"` + Error string `json:"error"` + Credential *struct { + Username string `json:"username"` + Password string `json:"password"` + URL string `json:"url"` + } `json:"credential"` + Data json.RawMessage `json:"data"` + Manifest json.RawMessage `json:"manifest"` +} + +// readAnswer checks that out is one line with one JSON object of the +// protocol, and returns it. +func readAnswer(t *testing.T, out string) pluginAnswer { + t.Helper() + if strings.Count(out, "\n") != 1 || !strings.HasSuffix(out, "\n") { + t.Fatalf("stdout is not one line: %q", safe(out)) + } + var a pluginAnswer + dec := json.NewDecoder(strings.NewReader(out)) + dec.DisallowUnknownFields() + if err := dec.Decode(&a); err != nil || a.Protocol != PluginProtocol { + t.Fatalf("answer %q: %v", safe(out), err) + } + return a +} + +// noValue fails when s holds the password in any common form. +func (e *pluginEnv) noValue(t *testing.T, where, s string) { + t.Helper() + pwJSON, _ := json.Marshal(e.pw) + for _, v := range []string{e.pw, string(pwJSON[1 : len(pwJSON)-1]), base64.StdEncoding.EncodeToString([]byte(e.pw)), + madeUpCore(e.pw)} { + if v != "" && strings.Contains(s, v) { + t.Errorf("the password is in %s", where) + } + } +} + +// madeUpCore is the part of a madeUp value with no special characters. +func madeUpCore(v string) string { + i := strings.LastIndex(v, "-") + if i < 0 { + return v + } + return v[i+1 : min(len(v), i+20)] +} + +// auditText returns the audit log as text. +func (e *pluginEnv) auditText(t *testing.T) string { + t.Helper() + e.tb.audit.mu.Lock() + defer e.tb.audit.mu.Unlock() + data, err := json.Marshal(e.tb.audit.events) + if err != nil { + t.Fatal(err) + } + return string(data) +} + +// TestPluginContract: the recorded requests of agent-browser, against a +// test broker. nodkey preapprove waits more than 60 s for the tap; then +// auth login gets the login with no tap, and nodkey.totp one code. The +// password is nowhere but in the credential. +func TestPluginContract(t *testing.T) { + e := newPluginEnv(t) + tb := e.tb + + // nodkey preapprove --login: the tap comes after 100 s. + g := testGranter(tb.client(t), nil) + done := make(chan struct{}) + var preCode int + var preErr bytes.Buffer + go func() { + defer close(done) + preCode = g.runPreapprove(t.Context(), []string{"--login", recItem, "--url", recPage}, &bytes.Buffer{}, &preErr) + }() + asked := tb.waitAsked(t, 1) + pr := asked[0].Prompt + if pr.Kind != audit.KindPreapprove || pr.Login == nil || pr.Login.For != 60*time.Second { + t.Fatalf("prompt %+v %q", pr, asked[0].Text) + } + tb.clock.Advance(100 * time.Second) + if err := tb.approver.Tap(pr.RequestID, audit.AnswerApproveOnce); err != nil { + t.Fatal(err) + } + <-done + if preCode != exitOK { + t.Fatalf("preapprove: exit %d: %s", preCode, safe(preErr.String())) + } + + // agent-browser auth login: the recorded credential.resolve. + code, out, errText := e.plugin(t, recorded(t, "credential-resolve.json")) + if code != exitOK || errText != "" { + t.Fatalf("exit %d, stderr %q", code, safe(errText)) + } + a := readAnswer(t, out) + if !a.Success || a.Credential == nil || a.Credential.Username != "alice@example.com" || + a.Credential.Password != e.pw || a.Credential.URL != recPage { + t.Fatalf("answer %q", safe(out)) + } + if n := len(tb.approver.Asked()); n != 1 { + t.Errorf("%d messages, want 1: the login must not ask", n) + } + + // The credential's URL is the page as the broker read it. + if strings.Contains(a.Credential.URL, "#") { + t.Errorf("url %q", a.Credential.URL) + } + + // The second login has no pre-approval: it needs a tap, and the + // person is not asked. + code, out, errText = e.plugin(t, recorded(t, "credential-resolve.json")) + a = readAnswer(t, out) + if code != exitOK || a.Success || !strings.Contains(a.Error, "nodkey preapprove --login") || + !strings.Contains(errText, "needs a tap") { + t.Errorf("second login: exit %d, %q, stderr %q", code, safe(out), safe(errText)) + } + if n := len(tb.approver.Asked()); n != 1 { + t.Errorf("%d messages, want 1", n) + } + + // The recorded nodkey.totp: one code, the RFC 6238 code of now. + _, out, _ = e.plugin(t, recorded(t, "plugin-run-totp.json")) + a = readAnswer(t, out) + var data struct { + Code string `json:"code"` + } + if !a.Success || json.Unmarshal(a.Data, &data) != nil { + t.Fatalf("totp answer %q", safe(out)) + } + key, err := totp.Parse([]byte(recSeed)) + if err != nil { + t.Fatal(err) + } + // The broker's own clock is the real one; the code is of now, or of + // the step before when a step ended in between. + now := time.Now() + c1, _ := key.Code(now) + c0, _ := key.Code(now.Add(-key.Period())) + if data.Code != c1 && data.Code != c0 { + t.Errorf("code %q, want %q", data.Code, c1) + } + // A second code needs a new login. + _, out, _ = e.plugin(t, recorded(t, "plugin-run-totp.json")) + if a = readAnswer(t, out); a.Success || !strings.Contains(a.Error, "already given") { + t.Errorf("second code: %q", out) + } + + // The recorded nodkey.list: IDs, names and usernames only. + _, out, _ = e.plugin(t, recorded(t, "plugin-run-list.json")) + a = readAnswer(t, out) + if !a.Success || string(a.Data) != `{"logins":[{"id":"`+recItem+`","name":"Example shop","username":"alice@example.com"}]}` { + t.Errorf("list answer %q", safe(out)) + } + + e.noValue(t, "the audit log", e.auditText(t)) + e.noValue(t, "the messages", tb.approver.Asked()[0].Text) + if !e.vs.cleared() { + t.Error("a value that the store gave out is not cleared") + } +} + +// TestPluginValuesOnlyInTheCredential: in every answer and on stderr the +// password is only in the credential of credential.resolve. +func TestPluginValuesOnlyInTheCredential(t *testing.T) { + e := newPluginEnv(t) + e.tb.approver.Auto(audit.AnswerApproveOnce) + g := testGranter(e.tb.client(t), nil) + var stderr bytes.Buffer + if code := g.runPreapprove(t.Context(), []string{"--login", recItem, "--url", recPage}, &stderr, &stderr); code != exitOK { + t.Fatalf("preapprove: %s", safe(stderr.String())) + } + e.noValue(t, "the stderr of preapprove", stderr.String()) + code, out, errText := e.plugin(t, recorded(t, "credential-resolve.json")) + if code != exitOK || !readAnswer(t, out).Success { + t.Fatalf("login: %q", safe(out)) + } + e.noValue(t, "the plugin's stderr", errText) + for _, name := range []string{"plugin-run-list.json", "plugin-run-totp.json", "credential-resolve.json"} { + _, out, errText := e.plugin(t, recorded(t, name)) + e.noValue(t, name+" stdout", out) + e.noValue(t, name+" stderr", errText) + } + e.noValue(t, "the audit log", e.auditText(t)) +} + +// TestPluginRefusals: requests that the plugin refuses before it loads +// the config. Each gets one answer with success false, exit code 0 (else +// agent-browser drops the answer), and one line on stderr. +func TestPluginRefusals(t *testing.T) { + t.Parallel() + env := func(item, url string) string { + return `{"capability":"credential.read","protocol":"agent-browser.plugin.v1","request":{"itemRef":` + item + + `,"profileName":"p","url":` + url + `},"type":"credential.resolve"}` + } + tests := map[string]struct{ req, want string }{ + "no url (recorded)": {string(recorded(t, "credential-resolve-no-url.json")), "item ID"}, + "no url": {env(`"`+recItem+`"`, `null`), "no page URL"}, + "empty url": {env(`"`+recItem+`"`, `""`), "no page URL"}, + "http page": {env(`"`+recItem+`"`, `"http://example.com/"`), "https"}, + "user in url": {env(`"`+recItem+`"`, `"https://a:b@example.com/"`), "page URL"}, + "item name": {env(`"Example shop"`, `"https://example.com/"`), "item ID"}, + "no item": {env(`null`, `"https://example.com/"`), "item ID"}, + "item not a string": {env(`1`, `"https://example.com/"`), "itemRef"}, + "other protocol": {strings.Replace(env(`"`+recItem+`"`, `"https://example.com/"`), ".v1", ".v2", 1), "protocol"}, + "no protocol": {`{"type":"credential.resolve","capability":"credential.read","request":{}}`, "protocol"}, + "wrong capability": {strings.Replace(env(`"`+recItem+`"`, `"https://example.com/"`), "credential.read", "command.run", 1), "capability"}, + "unknown type": {`{"protocol":"agent-browser.plugin.v1","type":"browser.launch","capability":"browser.provider","request":{}}`, "unknown request type"}, + "no request": {`{"protocol":"agent-browser.plugin.v1","type":"credential.resolve","capability":"credential.read"}`, "request"}, + "request a list": {`{"protocol":"agent-browser.plugin.v1","type":"nodkey.list","capability":"command.run","request":[]}`, "request"}, + "list no url": {`{"protocol":"agent-browser.plugin.v1","type":"nodkey.list","capability":"command.run","request":{}}`, "payload"}, + "list http": {`{"protocol":"agent-browser.plugin.v1","type":"nodkey.list","capability":"command.run","request":{"url":"http://example.com/"}}`, "https"}, + "totp no item": {`{"protocol":"agent-browser.plugin.v1","type":"nodkey.totp","capability":"command.run","request":{"url":"https://example.com/"}}`, "item ID"}, + "not json": {`not json`, "JSON"}, + "empty": {``, "JSON"}, + "too long": {`{"protocol":"` + strings.Repeat("a", maxPluginRequest) + `"}`, "longer"}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + code, out, errText := runPlugin(t, nil, []byte(tt.req)) + a := readAnswer(t, out) + if code != exitOK || a.Success || !strings.HasPrefix(a.Error, "nodkey: ") || !strings.Contains(a.Error, tt.want) { + t.Errorf("exit %d, answer %q; want an error with %q", code, out, tt.want) + } + if strings.Count(errText, "\n") != 1 || !strings.HasPrefix(errText, "nodkey agent-browser-plugin: ") { + t.Errorf("stderr %q", errText) + } + if strings.Contains(out, "Example shop") || strings.Contains(out, "a:b") { + t.Errorf("the error repeats the request: %q", out) + } + }) + } +} + +// TestPluginBrokerRefusals: the broker refuses, or cannot be reached. +func TestPluginBrokerRefusals(t *testing.T) { + t.Parallel() + e := newPluginEnv(t) + other := `{"capability":"credential.read","protocol":"agent-browser.plugin.v1","request":{"itemRef":"` + + recItem + `","url":"https://other.example.net/"},"type":"credential.resolve"}` + // An origin that matches no URI of the item: denied, with no message. + _, out, _ := e.plugin(t, []byte(other)) + if a := readAnswer(t, out); a.Success || !strings.Contains(a.Error, "denied") { + t.Errorf("other origin: %q", out) + } + // Another item. + otherItem := strings.Replace(string(recorded(t, "credential-resolve.json")), recItem, "22222222-2222-2222-2222-222222222222", 1) + _, out, _ = e.plugin(t, []byte(otherItem)) + if a := readAnswer(t, out); a.Success { + t.Errorf("other item: %q", out) + } + // A code with no login before it. + _, out, _ = e.plugin(t, recorded(t, "plugin-run-totp.json")) + if a := readAnswer(t, out); a.Success || !strings.Contains(a.Error, "in the last 2 minutes") { + t.Errorf("totp: %q", out) + } + if n := len(e.tb.approver.Asked()); n != 0 { + t.Errorf("%d messages, want 0", n) + } + // The config cannot be loaded. + r := pluginRunner{load: func(string) (*Broker, error) { return nil, errors.New("config /x: broker: missing") }, + configPath: func() (string, error) { return "/x", nil }} + var stdout, stderr bytes.Buffer + if code := r.run(t.Context(), nil, bytes.NewReader(recorded(t, "credential-resolve.json")), &stdout, &stderr); code != exitOK { + t.Errorf("exit %d", code) + } + if a := readAnswer(t, stdout.String()); a.Success || !strings.Contains(a.Error, "config /x") { + t.Errorf("config: %q", stdout.String()) + } +} + +// TestPluginDeadline: a broker that does not answer in time. The plugin +// answers before agent-browser stops it. +func TestPluginDeadline(t *testing.T) { + t.Parallel() + if PluginResolveTime >= 15*time.Second || PluginCommandTime >= 60*time.Second { + t.Fatal("a wait is not shorter than agent-browser's limit") + } + fb := newFakeBroker(t, func(_ http.ResponseWriter, r *http.Request) { <-r.Context().Done() }) + ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond) + defer cancel() + r := pluginRunner{load: func(string) (*Broker, error) { return fb.b, nil }, + configPath: func() (string, error) { return "/x", nil }} + var stdout, stderr bytes.Buffer + _ = r.run(ctx, nil, bytes.NewReader(recorded(t, "credential-resolve.json")), &stdout, &stderr) + if a := readAnswer(t, stdout.String()); a.Success || !strings.Contains(a.Error, "in time") { + t.Errorf("answer %q", stdout.String()) + } +} + +func TestPluginManifestAndUsage(t *testing.T) { + t.Parallel() + code, out, _ := runPlugin(t, nil, []byte(`{"protocol":"agent-browser.plugin.v1","type":"plugin.manifest","capability":"","request":{}}`)) + if a := readAnswer(t, out); code != exitOK || !a.Success || + string(a.Manifest) != `{"name":"nodkey","capabilities":["credential.read","command.run"]}` { + t.Errorf("manifest %q", out) + } + var stdout, stderr bytes.Buffer + r := pluginRunner{} + if code := r.run(t.Context(), []string{"--help"}, strings.NewReader(""), &stdout, &stderr); code != exitOK || + !strings.Contains(stderr.String(), PluginVersion) || stdout.Len() != 0 { + t.Errorf("help: %d %q", code, stderr.String()) + } + stderr.Reset() + if code := r.run(t.Context(), []string{"extra"}, strings.NewReader(""), &stdout, &stderr); code != exitUsage || + strings.Count(stderr.String(), "\n") != 1 || stdout.Len() != 0 { + t.Errorf("usage: %d %q", code, stderr.String()) + } +} + +// TestCredentialAnswer: the password is escaped as encoding/json does, +// in a buffer of the exact size; a password that is not UTF-8 is refused. +func TestCredentialAnswer(t *testing.T) { + t.Parallel() + for _, pw := range []string{"plain", `q"uo\te`, "tab\tnl\n\x00\x1f", "é世\U0001F600", "<>&
", ""} { + b, err := credentialAnswer("alice@example.com", []byte(pw), recPage) + if err != nil { + t.Fatalf("%q: %v", pw, err) + } + if len(b) != cap(b) { + t.Errorf("%q: the buffer grew", pw) + } + a := readAnswer(t, string(b)) + if !a.Success || a.Credential == nil || a.Credential.Password != pw || a.Credential.URL != recPage { + t.Errorf("%q: %q", pw, b) + } + } + if _, err := credentialAnswer("u", []byte{0xff, 'a'}, recPage); !errors.Is(err, errPasswordText) { + t.Errorf("not UTF-8: %v", err) + } +} + +// TestPluginPageWithFragment: the page goes to the broker, and back to +// agent-browser, as the broker reads it: with no fragment. +func TestPluginPageWithFragment(t *testing.T) { + t.Parallel() + e := newPluginEnv(t) + e.tb.approver.Auto(audit.AnswerApproveOnce) + g := testGranter(e.tb.client(t), nil) + var stderr bytes.Buffer + if code := g.runPreapprove(t.Context(), []string{"--login", recItem, "--url", recPage}, &stderr, &stderr); code != exitOK { + t.Fatalf("preapprove: %s", safe(stderr.String())) + } + req := strings.Replace(string(recorded(t, "credential-resolve.json")), recPage, recPage+"#top", 1) + _, out, _ := e.plugin(t, []byte(req)) + if a := readAnswer(t, out); !a.Success || a.Credential.URL != recPage { + t.Errorf("answer %q", safe(out)) + } +} diff --git a/internal/client/client.go b/internal/client/client.go index c16e572..1115064 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -136,9 +136,15 @@ func (e *Error) Error() string { return e.text } // (by a limit). nodkey run exits with 77 then, and with 69 for every other // Error (DESIGN.md section 15). func (e *Error) Denied() bool { - return e.Status == http.StatusForbidden || e.Status == http.StatusTooManyRequests + return e.Status == http.StatusForbidden || e.Status == http.StatusTooManyRequests || + e.Status == http.StatusPreconditionRequired } +// NeedsTap reports whether the broker answered 428: a login request with +// api.NoTapHeader that no pre-approval or grant covers (DESIGN.md section +// 21.10). +func (e *Error) NeedsTap() bool { return e.Status == http.StatusPreconditionRequired } + // statusError returns the Error of a final answer with status, which is // not 200. func statusError(status int) *Error { @@ -147,6 +153,8 @@ func statusError(status int) *Error { return &Error{Status: status, text: "denied"} case http.StatusTooManyRequests: return &Error{Status: status, text: "denied by a limit of the broker"} + case http.StatusPreconditionRequired: + return &Error{Status: status, text: "this login needs a tap, and no pre-approval or grant covers it"} } text := fmt.Sprintf("the broker answered %d", status) if s := http.StatusText(status); s != "" { diff --git a/internal/client/helpers_test.go b/internal/client/helpers_test.go index d308d8c..d6d8668 100644 --- a/internal/client/helpers_test.go +++ b/internal/client/helpers_test.go @@ -331,6 +331,13 @@ func newTestBroker(t *testing.T) *testBroker { // newTestBrokerWith is newTestBroker for a broker whose version is // version ("" for none). func newTestBrokerWith(t *testing.T, version string) *testBroker { + t.Helper() + return newTestBrokerFull(t, version, nil, nil) +} + +// newTestBrokerFull is newTestBrokerWith with more: edit, if not nil, +// changes the config, and stores are more stores by name. +func newTestBrokerFull(t *testing.T, version string, edit func(*config.Broker), stores map[string]store.Store) *testBroker { t.Helper() tb := &testBroker{ key: newTLSKey(t), @@ -356,12 +363,19 @@ func newTestBrokerWith(t *testing.T, version string) *testBroker { "npm-token": {Name: "npm-token", Store: "main", ID: idNPM, Clients: []string{"laptop"}, Rule: always}, }, } + if edit != nil { + edit(cfg) + } + all := map[string]store.Store{"main": tb.store} + for name, st := range stores { + all[name] = st + } core, err := approval.New(cfg, tb.approver, approval.Options{Clock: tb.clock}) if err != nil { t.Fatal(err) } svc, err := broker.New(broker.Parts{Config: cfg, Audit: tb.audit, - Stores: map[string]store.Store{"main": tb.store}, Version: version}) + Stores: all, Version: version}) if err != nil { t.Fatal(err) } diff --git a/internal/client/logins.go b/internal/client/logins.go index 1fcfdef..bc4cf4b 100644 --- a/internal/client/logins.go +++ b/internal/client/logins.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "net/http" "github.com/code6x/nodkey/internal/api" ) @@ -48,6 +49,23 @@ func Login(ctx context.Context, b *Broker, pageURL, item string, onCode func(cod return Post[api.LoginAnswer](ctx, b, api.PathLogin, body, onCode) } +// LoginNoTap is Login with api.NoTapHeader: the broker never asks the +// person. When no pre-approval or grant covers the login, it answers at +// once, and the error is an *Error whose NeedsTap is true. The caller must +// Clear the answer. +func LoginNoTap(ctx context.Context, b *Broker, pageURL, item 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 + } + h := http.Header{api.NoTapHeader: []string{api.NoTapValue}} + return postWith[api.LoginAnswer](ctx, b, api.PathLogin, body, nil, h) +} + // 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). diff --git a/internal/client/testdata/agent-browser-0.38.1/README.md b/internal/client/testdata/agent-browser-0.38.1/README.md new file mode 100644 index 0000000..023343e --- /dev/null +++ b/internal/client/testdata/agent-browser-0.38.1/README.md @@ -0,0 +1,27 @@ +# Recorded requests of agent-browser 0.38.1 + +These are the exact requests that agent-browser 0.38.1 (npm package +`agent-browser@0.38.1`, binary `agent-browser-linux-x64`) wrote to the +stdin of a recording plugin, on 2026-11-13. The page was a local test +page on 127.0.0.1. `abplugin_test.go` sends them to +`nodkey agent-browser-plugin`. + +| file | command | +|---|---| +| `credential-resolve.json` | `agent-browser auth login shop --credential-provider nodkey --item 11111111-1111-1111-1111-111111111111 --url https://127.0.0.1:18766/login.html` | +| `credential-resolve-no-url.json` | `agent-browser auth login nourl --credential-provider nodkey --item abc` (no `--url`) | +| `plugin-run-list.json` | `agent-browser plugin run nodkey nodkey.list --payload '{"url":"https://example.com/"}'` | +| `plugin-run-totp.json` | `agent-browser plugin run nodkey nodkey.totp --payload '{"itemRef":"11111111-1111-1111-1111-111111111111","url":"https://127.0.0.1:18766/login.html"}'` | + +What agent-browser 0.38.1 does with the answer (seen the same day): + +- It reads one JSON object from stdout, and only when the plugin exits + with 0. It needs `"protocol":"agent-browser.plugin.v1"` in it. +- `credential.resolve`: on success, it reads the object `credential` + (`username`, `password`, `url`). On `"success":false` it prints only + "returned success=false", not the error text. +- `plugin run`: it prints the whole answer on success, and the `error` + text on `"success":false`. +- It does not show the plugin's stderr. +- The command in its config is not split at spaces: the argument goes in + `"args"`. diff --git a/internal/client/testdata/agent-browser-0.38.1/credential-resolve-no-url.json b/internal/client/testdata/agent-browser-0.38.1/credential-resolve-no-url.json new file mode 100644 index 0000000..2dd0724 --- /dev/null +++ b/internal/client/testdata/agent-browser-0.38.1/credential-resolve-no-url.json @@ -0,0 +1 @@ +{"capability":"credential.read","protocol":"agent-browser.plugin.v1","request":{"itemRef":"abc","profileName":"nourl","url":null},"type":"credential.resolve"} diff --git a/internal/client/testdata/agent-browser-0.38.1/credential-resolve.json b/internal/client/testdata/agent-browser-0.38.1/credential-resolve.json new file mode 100644 index 0000000..5c7bc59 --- /dev/null +++ b/internal/client/testdata/agent-browser-0.38.1/credential-resolve.json @@ -0,0 +1 @@ +{"capability":"credential.read","protocol":"agent-browser.plugin.v1","request":{"itemRef":"11111111-1111-1111-1111-111111111111","profileName":"shop","url":"https://127.0.0.1:18766/login.html"},"type":"credential.resolve"} diff --git a/internal/client/testdata/agent-browser-0.38.1/plugin-run-list.json b/internal/client/testdata/agent-browser-0.38.1/plugin-run-list.json new file mode 100644 index 0000000..8953534 --- /dev/null +++ b/internal/client/testdata/agent-browser-0.38.1/plugin-run-list.json @@ -0,0 +1 @@ +{"capability":"command.run","protocol":"agent-browser.plugin.v1","request":{"url":"https://example.com/"},"type":"nodkey.list"} diff --git a/internal/client/testdata/agent-browser-0.38.1/plugin-run-totp.json b/internal/client/testdata/agent-browser-0.38.1/plugin-run-totp.json new file mode 100644 index 0000000..018d837 --- /dev/null +++ b/internal/client/testdata/agent-browser-0.38.1/plugin-run-totp.json @@ -0,0 +1 @@ +{"capability":"command.run","protocol":"agent-browser.plugin.v1","request":{"itemRef":"11111111-1111-1111-1111-111111111111","url":"https://127.0.0.1:18766/login.html"},"type":"nodkey.totp"}