diff --git a/DESIGN.md b/DESIGN.md index f004c69..8df8aa5 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -510,6 +510,85 @@ The list has limits: sees. It does not stop a hostile agent (THREAT-MODEL.md section 5, item 1). +### TOTP codes + +Issue #212 (owner, 2026-11-19). Some CLI tools need a 2FA code for a +write, for example `npm publish` of a new package and `npm trust`: they +fail with `EOTP` without one. nodkey hands such a tool one TOTP code, as +a `run` secret: + +```sh +nodkey run --totp NPM_OTP=npm-otp \ + -- sh -c 'npm publish pkg.tgz --otp "$NPM_OTP"' +``` + +- **The config allows it** (closed by default). A `[secret.*]` section + with `totp = true` is the TOTP code of a Bitwarden login item, not its + password: + + ```toml + [secret.npm-otp] + store = "vault" # a store of type bw + id = "11111111-1111-1111-1111-111111111111" # the login item + totp = true + clients = ["laptop"] + ask = "always" + preapprove = true # optional; a batch with one tap + ``` + + `totp` is allowed only with a store of type `bw`. A secret with + `totp = true` needs `ask = "always"` and no `standing = true`: one tap + gives one code, and a window grant or a standing grant would hand out + codes without one. `preapprove = true` is allowed (see below). An item + in a `[logins.*]` collection is not a CLI code for that: only a + `[secret.*]` section with `totp = true` makes one. A change of `totp` + in a reload ends the grants of the secret, and `config-diff` marks it + as a change that widens. +- **The client asks for a code with `--totp VAR=NAME`.** NAME is a + `[secret.*]` section, never `PROJECT/KEY`. The request carries the + variable with `"kind": "totp"` (`api.KindTOTP`); a `--secret` has no + `kind` field, as before. At most one `--totp` in a request; it counts + as one of the 32 secrets. An older broker refuses the field: its + decoding is strict, so it fails closed. +- **The broker checks the kind against the config** in step 3, as for + any other check: a secret with `totp = true` only with `--totp`, and + `--totp` only for such a secret, at most once. A request that fails + gets 403 with no message, and the entries `request` and `denied` with + cause `not_allowed`. +- **The message is the message of a run secret** (section 7): it names + the secret, as in `✅ secrets: npm-otp`, and shows the variable, the + command line, the directory and the reason as claimed text. Give the + section a name that says what the code is for, such as `npm-otp`. +- **After the tap, the broker makes the code.** It runs + `bw sync --force` and `bw get item ID`, as for a password (section + 21.9), and checks that the item is the item of `id`, a login item, not + in the trash and not archived. It reads `login.totp` and clears the + password at once; a login with no password is fine. It reads the seed + with `internal/totp` (section 21.5), makes the code of the broker's + clock of now, and clears the seed and the key. **The seed never leaves + the broker**; the client gets only the code, as the value of VAR. An + item with no seed, a seed in a form that nodkey does not read, or a + store failure denies the request with `error` code `store_failed` + (status 503). The journal says what is wrong and how to fix it, with + no seed and no code. +- **The code is fresh at each use.** The broker fetches the item and + makes the code for each approved request; it keeps no code and no + seed. Two uses in the same time step (30 s for most sites) get the + same code. Some sites take a code only once; then wait for the next + step between two uses. +- **A batch with one tap** is a scheduled grant: `nodkey preapprove + --secret npm-otp --until TIME --uses N` (section 8). As for any + scheduled grant, it must name every secret of the command, for example + `--secret npm-token` too. Each `nodkey run + --totp` in its time span takes one use and gets its own code of that + moment, with a silent notice, up to N uses. The grant ends at its last + use; the next request asks for a tap again. +- **Audit**: one `secret_sent` entry per code, as for any run secret + (section 9). It names the secret, never the code or the seed. +- **The risks** are in THREAT-MODEL.md, T54: a code works for any write + of that account in its time step (about 30 s), not only for the + command in the message, and the command line is claimed by the client. + ## 6. Flow: an SSH login ``` @@ -2954,6 +3033,14 @@ name = "CI_TOKEN" # the name of the secret clients = ["laptop"] ask = "always" +[secret.npm-otp] # the TOTP code of a bw login item (section 5, "TOTP codes") +store = "vault" +id = "11111111-1111-1111-1111-111111111111" +totp = true # optional; default false; only for a store of type bw +clients = ["laptop"] +ask = "always" # needed with totp = true +preapprove = true + [key.deploy] file = "${CREDENTIALS_DIRECTORY}/ssh-deploy" clients = ["laptop"] @@ -3338,7 +3425,7 @@ nodkey broker [--config FILE] nodkey broker reload [--config FILE] [--timeout DURATION] nodkey broker check [--config FILE] [--files DIR] [--credentials DIR] nodkey broker config-diff [--short] [--max-chars N] OLD NEW -nodkey run [--secret VAR=NAME]... [--grant-token FILE] [--reason TEXT] [--mask | --no-mask] -- COMMAND [ARGS...] +nodkey run [--secret VAR=NAME]... [--totp VAR=NAME] [--grant-token FILE] [--reason TEXT] [--mask | --no-mask] -- COMMAND [ARGS...] nodkey ssh-agent [--socket PATH] nodkey ssh-grant --key NAME --user USER --host NAME... --for DURATION [--reason TEXT] nodkey preapprove (--secret NAME... | --key NAME --user USER --host NAME...) --until TIME --uses N [--from TIME] [--reason TEXT] @@ -4953,7 +5040,9 @@ broker cannot check that the browser is on that page. 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 + current code itself (*built*: `internal/totp`). This code is only for + the login on the page; a code for a CLI tool is a `run` secret with + `totp = true` (section 5, "TOTP codes"). 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. diff --git a/README.md b/README.md index ae9ee69..d0bcb88 100644 --- a/README.md +++ b/README.md @@ -283,6 +283,24 @@ root on the broker host on the agent machine `GH_TOKEN`, and prints only its length, so the agent's screen shows only that length. +**A 2FA code for a CLI tool.** Some tools need a one-time code for a +write, such as `npm publish` and `npm trust` (they fail with `EOTP`). +nodkey can make the code from the TOTP seed of a Bitwarden login item, +on the broker, after a tap. The seed never leaves the broker; the +command gets only the code: + +```sh +nodkey run --secret NPM_TOKEN=npm-token --totp NPM_OTP=npm-otp -- \ + sh -c 'npm publish pkg.tgz --otp "$NPM_OTP"' +``` + +The broker hands out a code only for a `[secret.*]` section with +`totp = true`. For many packages with one tap, use +`nodkey preapprove --secret npm-token --secret npm-otp --uses 8 ...` +(both secrets need `preapprove = true`): each run gets its own fresh +code. See +[docs/setup.md](docs/setup.md#a-2fa-code-for-a-cli-tool-nodkey-run---totp). + Before real use, read [docs/setup.md](docs/setup.md): above all the safety of your Telegram and Bitwarden accounts and of the broker host diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md index 1118737..f8ea21d 100644 --- a/THREAT-MODEL.md +++ b/THREAT-MODEL.md @@ -1911,6 +1911,41 @@ What nodkey does not do: makes that run restart it. Risk that remains: low, when the role comes from a checked release file. +**T54. A TOTP code for a CLI command is used for another write.** +`nodkey run --totp` (DESIGN.md section 5, "TOTP codes") hands the +current TOTP code of a Bitwarden login item to one command, for example +`npm publish --otp`. A code is a second factor for **any** write of that +account, not only for the command in the message, for as long as the +site takes it: its time step (about 30 s), often one step more. The +command line in the message is claimed by the client: an agent can show +`npm publish pkg.tgz` and run something else with the code, or read it +from the command's environment, and the agent's session with the site +then has both factors (section 5, item 1). +What nodkey does: +- **Closed by default.** Only a `[secret.*]` section with `totp = true` + hands out a code, for the clients in its list. An item that is allowed + for website logins (`[logins.*]`) is not allowed for CLI codes. +- **One tap per code.** Such a secret needs `ask = "always"`: no window + grant and no standing grant. A scheduled grant (`nodkey preapprove`) + has a time span and a number of uses that the owner approved with one + tap, and each use has a silent notice. +- **The seed never leaves the broker.** The broker makes the code and + clears the seed; the client gets the code only, so a leak of it ends + with its time step. A leaked seed would give codes for ever. +- **The kind is checked.** The broker refuses `--totp` for a secret that + is not a TOTP code, and `--secret` for one that is, before any + message. At most one code per request. +- **One `secret_sent` entry per code**, with no code and no seed. +What nodkey does not do: +- It cannot bind a code to the command in the message, or to one write. + The approver reads the command as a claim and taps only when the agent + should have one write with that account in the next 30 s. +- The password or the token of the account is a separate matter: a code + alone does not log in. Keep the token (such as `NPM_TOKEN`) as its own + `[secret.*]`, with its own rule. +Risk that remains: medium for one approved code (any write of that +account for about 30 s), and the number of uses for a scheduled grant. + ## 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 869d4b3..4833cdb 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -2361,6 +2361,69 @@ check that fails before a message, such as a host that is not in sent`. Plain `denied` comes after the `waiting for approval` line: the person denied it, or nobody answered in time. +### A 2FA code for a CLI tool: nodkey run --totp + +Some CLI tools ask for a 2FA code on a write. For example `npm publish` +of a new package and `npm trust` fail with `EOTP` without `--otp CODE`. +nodkey can hand one code to such a command, after a tap. The broker +makes the code from the TOTP seed of a Bitwarden login item. The seed +never leaves the broker: the command gets only the code. + +1. **Put the seed into the item.** In Bitwarden, the login item of the + account has the TOTP seed in its "Authenticator key" field + (`login.totp`): a base32 secret or an `otpauth://totp/` URI. The item + must be in a collection that the `bw` store can read (see "bw: a + separate Bitwarden account" in section 5). +2. **Allow it in `broker.toml`.** It is off by default. A `[logins.*]` + collection does not allow it. + + ```toml + [secret.npm-otp] + store = "vault" # a store of type bw + id = "11111111-1111-1111-1111-111111111111" # the ID of the login item + totp = true + clients = ["laptop"] + ask = "always" # needed: one tap per code + preapprove = true # optional: a batch with one tap + ``` + + `totp = true` works only with a `bw` store, and needs + `ask = "always"` and no `standing = true`. Name the section after what + the code is for: the message shows the name. +3. **Use it**, on the agent machine: + + ```sh + nodkey run --secret NPM_TOKEN=npm-token --totp NPM_OTP=npm-otp -- \ + sh -c 'npm publish pkg.tgz --otp "$NPM_OTP"' + ``` + + The message shows `npm-otp` and the command. After **Approve once**, + the broker runs `bw sync --force` and `bw get item`, makes the code + of now, and the command gets it in `NPM_OTP`. At most one `--totp` in + one command. +4. **Many packages with one tap:** a scheduled grant with one use per + package. Each `nodkey run` in its time takes one use and gets its own + fresh code. The grant must name every secret of the command, so here + `npm-token` too, and both need `preapprove = true` (see "A job that + runs later" below): + + ```sh + nodkey preapprove --secret npm-token --secret npm-otp \ + --until 2026-11-19T18:00 --uses 8 \ + --reason "publish the 8 new packages" + ``` + +Things to know: + +- A code works for **any** write of that account, for its time step + (about 30 s), not only for the command in the message. The command + line is what the agent claims (THREAT-MODEL.md T54). Tap only when the + agent should make a write with that account now. +- Two runs in the same 30 s get the same code. Some sites take a code + only once: then wait 30 s between two runs. +- An item with no seed, or a seed in a form that nodkey does not read, + denies the request. The journal says which secret and what to fix. + ### A job that runs later: nodkey preapprove New in 0.3.0: nodkey 0.2.0 does not have it. diff --git a/internal/api/api_test.go b/internal/api/api_test.go index ad85a80..9eb7c4b 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -945,3 +945,30 @@ func TestKeyWindow(t *testing.T) { } } } + +// TestSecretRefKind: "kind" is optional. "totp" is the only kind; any +// other value, a null, a number and two kinds are refused. A SecretRef +// with no kind is written with no "kind" field, as before. +func TestSecretRefKind(t *testing.T) { + var r SecretRef + if err := json.Unmarshal([]byte(`{"var":"A","name":"a","kind":"totp"}`), &r); err != nil || r.Kind != KindTOTP { + t.Errorf("kind totp: %+v, %v", r, err) + } + for _, bad := range []string{ + `{"var":"A","name":"a","kind":"TOTP"}`, + `{"var":"A","name":"a","kind":""}`, + `{"var":"A","name":"a","kind":"password"}`, + `{"var":"A","name":"a","kind":null}`, + `{"var":"A","name":"a","kind":1}`, + `{"var":"A","name":"a","kind":"totp","kind":"totp"}`, + } { + var r SecretRef + if err := json.Unmarshal([]byte(bad), &r); err == nil { + t.Errorf("%s was accepted", bad) + } + } + b, err := json.Marshal(SecretRef{Var: "A", Name: "a"}) + if err != nil || string(b) != `{"var":"A","name":"a"}` { + t.Errorf("a plain secret is written as %s, %v", b, err) + } +} diff --git a/internal/api/decode.go b/internal/api/decode.go index 70d94dd..3f88b16 100644 --- a/internal/api/decode.go +++ b/internal/api/decode.go @@ -10,20 +10,21 @@ import ( // Errors of the strict decoding and of the caps. They never hold text from // the data, so they are safe to log. var ( - errNotObject = errors.New("api: the value is not a JSON object") - errSyntax = errors.New("api: the data is not valid JSON") - errUnknown = errors.New("api: an object has an unknown field") - errDuplicate = errors.New("api: a field appears twice in one object") - errMissing = errors.New("api: an object misses a field") - errNull = errors.New("api: a field or a list item is null") - errType = errors.New("api: a value has the wrong type") - errTrailing = errors.New("api: more data after the JSON value") - errTooMany = errors.New("api: a list has more items than its cap") - errTooLong = errors.New("api: a value is longer than its cap") - errBadWindow = errors.New("api: a window is not valid") - errBadVar = errors.New("api: a variable name is not valid") - errRead = errors.New("api: the answer could not be read") - errTooLarge = errors.New("api: the answer is larger than api.MaxAnswer") + errNotObject = errors.New("api: the value is not a JSON object") + errSyntax = errors.New("api: the data is not valid JSON") + errUnknown = errors.New("api: an object has an unknown field") + errDuplicate = errors.New("api: a field appears twice in one object") + errMissing = errors.New("api: an object misses a field") + errNull = errors.New("api: a field or a list item is null") + errType = errors.New("api: a value has the wrong type") + errTrailing = errors.New("api: more data after the JSON value") + errTooMany = errors.New("api: a list has more items than its cap") + errTooLong = errors.New("api: a value is longer than its cap") + errBadWindow = errors.New("api: a window is not valid") + errBadVar = errors.New("api: a variable name is not valid") + errUnknownKind = errors.New("api: a secret has an unknown kind") + errRead = errors.New("api: the answer could not be read") + errTooLarge = errors.New("api: the answer is larger than api.MaxAnswer") ) // field decodes the value of one field of an object. The value is not diff --git a/internal/api/types.go b/internal/api/types.go index 37f3e89..331f2dd 100644 --- a/internal/api/types.go +++ b/internal/api/types.go @@ -142,15 +142,46 @@ type SecretRef struct { Var string `json:"var"` // Name is the name of a [secret.*] section, such as "github-token". Name string `json:"name"` + // Kind is "" for a secret value (--secret), or KindTOTP for a TOTP + // code (--totp). The broker checks it against the config: a secret + // with totp = true is handed out only as KindTOTP, and KindTOTP only + // for such a secret (DESIGN.md section 5, "TOTP codes"). A request + // with no TOTP code has no "kind" field, as before. + Kind string `json:"kind"` } -// UnmarshalJSON decodes strictly. +// MarshalJSON writes no field "kind" for a secret value, so such a +// request is the same as before TOTP codes. +func (s SecretRef) MarshalJSON() ([]byte, error) { + type plain SecretRef + if s.Kind == "" { + return json.Marshal(struct { + plain + Kind *struct{} `json:"kind,omitempty"` + }{plain: plain(s)}) + } + return json.Marshal(plain(s)) +} + +// KindTOTP is the Kind of a SecretRef that asks for a TOTP code. +const KindTOTP = "totp" + +// UnmarshalJSON decodes strictly. "kind" is optional; when it is there, +// it must be KindTOTP. func (s *SecretRef) UnmarshalJSON(data []byte) error { var v SecretRef - err := decodeObject(data, map[string]field{ + hasKind := false + err := decodeObjectOptional(data, map[string]field{ "var": text(&v.Var), "name": text(&v.Name), - }) + "kind": func(raw json.RawMessage) error { + hasKind = true + return decodeText(raw, &v.Kind) + }, + }, map[string]bool{"kind": true}) + if err == nil && hasKind && v.Kind != KindTOTP { + err = errUnknownKind + } if err != nil { return err } diff --git a/internal/broker/secrets.go b/internal/broker/secrets.go index c78bbc5..1b2943f 100644 --- a/internal/broker/secrets.go +++ b/internal/broker/secrets.go @@ -3,6 +3,7 @@ package broker import ( "context" "errors" + "fmt" "log/slog" "net/http" @@ -13,6 +14,7 @@ import ( "github.com/code6x/nodkey/internal/config" "github.com/code6x/nodkey/internal/grantkey" "github.com/code6x/nodkey/internal/store" + "github.com/code6x/nodkey/internal/totp" "github.com/code6x/nodkey/internal/transport" ) @@ -121,20 +123,34 @@ func (rq *request) secrets(ctx context.Context, r *http.Request) { // checkSecrets checks the variables and the secret names of req: 1 to // api.MaxSecrets variables, each with a valid name that is not on the // deny list (api.DeniedVar), none twice, and each secret in the config and -// allowed for client. It returns the secret names in the order of the +// allowed for client. The kind of each variable must match the config: a +// secret with totp = true only as api.KindTOTP, and api.KindTOTP only for +// such a secret, at most once in a request (DESIGN.md section 5, "TOTP +// codes"). It returns the secret names in the order of the // request, for the core, and the names that passed, once each, for the // audit log. func (s *Service) checkSecrets(client string, req *api.SecretsRequest) (names, passed []string, ok bool) { ok = len(req.Secrets) > 0 && len(req.Secrets) <= api.MaxSecrets vars := make(map[string]bool, len(req.Secrets)) seen := make(map[string]bool, len(req.Secrets)) + cfg := s.view().cfg + codes := 0 for _, ref := range req.Secrets { _, denied := api.DeniedVar(ref.Var) if !api.ValidVar(ref.Var) || denied || vars[ref.Var] { ok = false } vars[ref.Var] = true - if !secretAllowed(s.view().cfg, client, ref.Name) { + if !secretAllowed(cfg, client, ref.Name) { + ok = false + continue + } + if ref.Kind == api.KindTOTP { + codes++ + } + // A project secret is never a TOTP code: its Secrets entry is + // missing, so its TOTP is false. + if wantTOTP := ref.Kind == api.KindTOTP; wantTOTP != cfg.Secrets[ref.Name].TOTP || codes > 1 { ok = false continue } @@ -244,6 +260,9 @@ func (rq *request) fetcher(name string) (string, func(context.Context) (store.Va } } sec := rq.v.cfg.Secrets[name] + if sec.TOTP { + return sec.Store, func(ctx context.Context) (store.Value, error) { return rq.totpCode(ctx, name, sec) } + } ref := sec.ID switch { case sec.Field != "": @@ -290,3 +309,51 @@ func (rq *request) decideStanding(ctx context.Context, names []string, cl approv } return res, rc, true } + +// errBadTOTPSeed is the error of a login.totp field that internal/totp +// does not read. It never holds the field. +var errBadTOTPSeed = errors.New("the TOTP seed in the item's login.totp field is not in a form nodkey reads; " + + "see DESIGN.md section 21.5") + +// totpCode makes the current TOTP code of the secret sec, a secret with +// totp = true (DESIGN.md section 5, "TOTP codes"). The store hands the +// seed only to the broker; the broker makes the code and clears the seed +// and the key at once. Each call fetches the item again, so each use of a +// grant gets the code of its own moment. Any error means deny. The error +// names the store and the secret and says how to fix it; it never holds +// the seed or the code. +func (rq *request) totpCode(ctx context.Context, name string, sec config.Secret) (store.Value, error) { + ts, ok := rq.s.stores[sec.Store].(store.TOTPStore) + if !ok { + return store.Value{}, fmt.Errorf("store %q: secret %q: the store cannot hand out TOTP codes; "+ + `totp = true needs a store of type = "bw"`, sec.Store, name) + } + seed, err := ts.FetchTOTP(ctx, sec.ID) + defer seed.Clear() + switch { + case errors.Is(err, store.ErrNoTOTP): + return store.Value{}, fmt.Errorf("%w; put the seed into the item in Bitwarden, or remove "+ + "totp = true from [secret.%s]", err, name) + case err != nil: + return store.Value{}, err + } + key, err := totp.Parse(seed.Bytes()) + if err != nil { + // The errors of totp.Parse are fixed texts that say what to fix; + // they never hold the field. Any other error gets errBadTOTPSeed. + known := errBadTOTPSeed + for _, e := range []error{totp.ErrEmpty, totp.ErrForm, totp.ErrBase32, totp.ErrAlgorithm, totp.ErrDigits, + totp.ErrPeriod} { + if errors.Is(err, e) { + known = e + } + } + return store.Value{}, fmt.Errorf("store %q: secret %q: %w", sec.Store, name, known) + } + defer key.Clear() + code, err := key.Code(rq.s.nowTime()) + if err != nil { + return store.Value{}, fmt.Errorf("store %q: secret %q: %w", sec.Store, name, err) + } + return store.NewValue([]byte(code)), nil +} diff --git a/internal/broker/totp_test.go b/internal/broker/totp_test.go new file mode 100644 index 0000000..7ab9d93 --- /dev/null +++ b/internal/broker/totp_test.go @@ -0,0 +1,332 @@ +package broker + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "maps" + "net/http" + "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" + "github.com/code6x/nodkey/internal/totp" +) + +// The TOTP item of the tests, and its seed: the base32 form of the SHA1 +// seed of RFC 6238, appendix B. +const ( + idOTP = "00000000-0000-0000-0000-000000000005" + otpSeed = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" +) + +// fakeTOTPStore is a bw-like store that hands out the TOTP seed of its +// items (store.TOTPStore). It keeps each seed it hands out, so a test can +// check that the broker cleared it. +type fakeTOTPStore struct { + *fakeStore + tmu sync.Mutex + seeds map[string]string // by item ID; "" is an item with no seed + seedErr error + tgiven [][]byte + tcount int +} + +func newFakeTOTPStore() *fakeTOTPStore { + return &fakeTOTPStore{fakeStore: newFakeStore(), seeds: map[string]string{idOTP: otpSeed}} +} + +func (f *fakeTOTPStore) FetchTOTP(_ context.Context, id string) (store.Value, error) { + f.tmu.Lock() + defer f.tmu.Unlock() + f.tcount++ + seed, ok := f.seeds[id] + switch { + case f.seedErr != nil: + return store.Value{}, f.seedErr + case !ok: + return store.Value{}, store.ErrBadID + case seed == "": + return store.Value{}, store.ErrNoTOTP + } + b := []byte(seed) + f.tgiven = append(f.tgiven, b) + return store.NewValue(b), nil +} + +func (f *fakeTOTPStore) checkSeedsCleared(t testing.TB) { + t.Helper() + f.tmu.Lock() + defer f.tmu.Unlock() + for _, b := range f.tgiven { + if !bytes.Equal(b, make([]byte, len(b))) { + t.Error("a TOTP seed was not cleared") + } + } +} + +// totpOn adds the store otp (type bw) and the secret npm-otp: the TOTP +// code of the item idOTP, ask always, for laptop, with preapprove. +func totpOn(cfg *config.Broker) { + cfg.Stores["otp"] = config.Store{Name: "otp", Type: config.StoreBW} + cfg.Secrets["npm-otp"] = config.Secret{Name: "npm-otp", Store: "otp", ID: idOTP, TOTP: true, + Clients: []string{"laptop"}, Rule: config.Rule{Ask: config.AskAlways, Preapprove: true}} +} + +// totpEnv starts a broker with totpOn and a fake TOTP store. The broker's +// clock for the codes is now. +func totpEnv(t *testing.T, more func(*config.Broker), now func() time.Time) (*env, *fakeTOTPStore) { + t.Helper() + ts := newFakeTOTPStore() + e := newEnv(t, envOptions{ + config: func(cfg *config.Broker) { + totpOn(cfg) + if more != nil { + more(cfg) + } + }, + stores: map[string]store.Store{"otp": ts}, + }) + e.svc.setNow(now) + return e, ts +} + +// wantCode is the code of otpSeed at t. +func wantCode(t testing.TB, at time.Time) string { + t.Helper() + k, err := totp.Parse([]byte(otpSeed)) + if err != nil { + t.Fatal(err) + } + c, err := k.Code(at) + if err != nil { + t.Fatal(err) + } + return c +} + +func totpRequest(variable, name string) api.SecretsRequest { + r := secretsRequest(variable, name) + r.Secrets[0].Kind = api.KindTOTP + r.Command = []string{"/usr/bin/npm", "publish", "pkg.tgz", "--otp"} + return r +} + +// TestTOTPCode: a --totp request asks for a tap; after it, the client gets +// the code of the broker's clock, and the seed is cleared. The message +// names the secret and the command; the entries hold no code and no seed. +func TestTOTPCode(t *testing.T) { + at := time.Unix(1111111109, 0) + e, ts := totpEnv(t, nil, func() time.Time { return at }) + c := e.httpClient("laptop") + p := e.start(c, api.PathSecrets, totpRequest("NPM_OTP", "npm-otp")) + pr := e.waitAsked(1)[0].Prompt + if strings.Join(pr.Secrets, ",") != "npm-otp" || !strings.Contains(pr.Claim.Command, "npm publish pkg.tgz --otp") || + pr.WindowMinutes != 0 { + t.Errorf("the message shows %+v", pr) + } + e.tap(pr.RequestID, audit.AnswerApproveOnce) + got := secretsOf(t, p.wait(t)) + if got["NPM_OTP"] != wantCode(t, at) || got["NPM_OTP"] != "081804" { + t.Errorf("the code is not the RFC 6238 code of the time (%d bytes)", len(got["NPM_OTP"])) + } + events := e.audit.waitFor(t, 3) + mustEvents(t, requestEvents(events, pr.RequestID), "request decision:approve_once secret_sent") + text := encodeEvents(t, events) + e.logs.String() + e.approverTexts() + if strings.Contains(text, otpSeed[:8]) || strings.Contains(text, "081804") { + t.Error("an entry, the log or the message holds the seed or the code") + } + ts.checkSeedsCleared(t) +} + +// TestTOTPRefused: closed by default. Each request is refused before a +// message: a secret with totp = true asked for with --secret, --totp for a +// secret that is not a TOTP code, two codes in one request, a client that +// is not in the list, and a name that is not in the config. +func TestTOTPRefused(t *testing.T) { + e, ts := totpEnv(t, func(cfg *config.Broker) { + s := cfg.Secrets["npm-otp"] + s.Clients = []string{"laptop", "ci"} + cfg.Secrets["npm-otp"] = s + cfg.Secrets["other-otp"] = config.Secret{Name: "other-otp", Store: "otp", ID: idOTP, TOTP: true, + Clients: []string{"laptop"}, Rule: config.Rule{Ask: config.AskAlways}} + cfg.Secrets["only-laptop"] = config.Secret{Name: "only-laptop", Store: "otp", ID: idOTP, TOTP: true, + Clients: []string{"laptop"}, Rule: config.Rule{Ask: config.AskAlways}} + }, time.Now) + two := totpRequest("A", "npm-otp") + two.Secrets = append(two.Secrets, api.SecretRef{Var: "B", Name: "other-otp", Kind: api.KindTOTP}) + cases := []struct { + name string + client string + req api.SecretsRequest + }{ + {"totp secret as a plain secret", "laptop", secretsRequest("NPM_OTP", "npm-otp")}, + {"a plain secret as totp", "laptop", totpRequest("DB", "db-password")}, + {"two codes", "laptop", two}, + {"another client", "ci", totpRequest("NPM_OTP", "only-laptop")}, + {"not in the config", "laptop", totpRequest("NPM_OTP", "no-such-otp")}, + } + for i, tc := range cases { + res := e.post(t.Context(), e.httpClient(tc.client), api.PathSecrets, tc.req) + if res.err != nil || res.status != http.StatusForbidden { + t.Errorf("%s: status %d, %v; want 403", tc.name, res.status, res.err) + } + events := e.audit.waitFor(t, 2*(i+1)) + mustEvents(t, events[2*i:], "request denied:not_allowed") + } + if n := len(e.approver.Asked()); n != 0 { + t.Errorf("%d messages for refused requests", n) + } + if ts.tcount != 0 || e.vault.fetched() != 0 { + t.Error("a refused request read a store") + } +} + +// TestTOTPNoSeed: an item with no seed, a seed that internal/totp does not +// read, and a store failure each deny the request after the tap, with a +// log line that says how to fix it and no code in the answer. +func TestTOTPNoSeed(t *testing.T) { + cases := []struct { + name, seed, log string + err error + }{ + {"no seed", "", "put the seed into the item in Bitwarden, or remove totp = true from [secret.npm-otp]", nil}, + {"steam seed", "steam://ABCDEFGH", "the TOTP field is not a base32 secret", nil}, + {"bad base32", "!!!!", "the TOTP secret is not valid base32; copy the secret again", nil}, + {"store failure", otpSeed, "bw sync: the program failed", + errors.New(`store "otp": bw sync: the program failed (exit code 1)`)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + e, ts := totpEnv(t, nil, time.Now) + ts.seeds[idOTP] = tc.seed + ts.seedErr = tc.err + e.approver.Auto(audit.AnswerApproveOnce) + res := e.post(t.Context(), e.httpClient("laptop"), api.PathSecrets, totpRequest("NPM_OTP", "npm-otp")) + mustStatus(t, res, http.StatusServiceUnavailable) + events := e.audit.all() + mustEvents(t, requestEvents(events, lastRequestID(t, events)), + "request decision:approve_once error:store_failed denied:error") + if !strings.Contains(e.logs.String(), tc.log) { + t.Errorf("the log does not say how to fix it:\n%s", e.logs.String()) + } + if tc.seed != "" && (strings.Contains(e.logs.String(), tc.seed) || strings.Contains(e.logs.String(), otpSeed[:8])) { + t.Error("the log holds the seed") + } + ts.checkSeedsCleared(t) + }) + } +} + +// TestTOTPPreapprove: a scheduled grant with 2 uses gives 2 codes without +// a tap, each the code of the moment of its use; the third request asks +// again. +func TestTOTPPreapprove(t *testing.T) { + var mu sync.Mutex + at := noon + now := func() time.Time { + mu.Lock() + defer mu.Unlock() + return at + } + e, ts := totpEnv(t, func(cfg *config.Broker) { cfg.Preapprove = config.DefaultPreapprove() }, now) + c := e.httpClient("laptop") + e.preapprove(c, preReq(2, "npm-otp"), 1) + e.clock.Advance(time.Hour) + var codes []string + for i := range 2 { + mu.Lock() + at = noon.Add(time.Hour + time.Duration(i)*30*time.Second) + mu.Unlock() + got := secretsOf(t, e.post(t.Context(), c, api.PathSecrets, totpRequest("NPM_OTP", "npm-otp"))) + if got["NPM_OTP"] != wantCode(t, now()) { + t.Errorf("use %d: not the code of the moment of the use", i+1) + } + codes = append(codes, got["NPM_OTP"]) + } + if codes[0] == codes[1] { + t.Error("two uses in two time steps got the same code") + } + events := e.audit.waitFor(t, 8)[2:] + mustEvents(t, events, "request grant_used:scheduled secret_sent "+ + "request grant_used:scheduled grant_ended:used_up secret_sent") + if n := len(e.approver.Asked()); n != 1 { + t.Errorf("%d messages, want 1", n) + } + // Used up: the next code needs a tap. + again := e.start(c, api.PathSecrets, totpRequest("NPM_OTP", "npm-otp")) + e.waitAsked(2) + again.cancel() + again.wait(t) + ts.checkSeedsCleared(t) +} + +// TestTOTPGrantToken: a request for a code with the header of a standing +// grant token is refused: a TOTP secret has no standing grants. Nobody is +// asked and no seed is read. +func TestTOTPGrantToken(t *testing.T) { + e, ts := totpEnv(t, nil, time.Now) + c := e.httpClient("laptop") + data, err := json.Marshal(totpRequest("NPM_OTP", "npm-otp")) + if err != nil { + t.Fatal(err) + } + req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "https://"+e.addr+api.PathSecrets, bytes.NewReader(data)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set(api.GrantTokenHeader, "nodkey-grant-v1-"+strings.Repeat("A", 43)) + res, err := c.Do(req) + if err != nil { + t.Fatal(err) + } + _ = res.Body.Close() + if res.StatusCode != http.StatusForbidden { + t.Errorf("status %d, want 403", res.StatusCode) + } + if n := len(e.approver.Asked()); n != 0 { + t.Errorf("%d messages", n) + } + ts.tmu.Lock() + defer ts.tmu.Unlock() + if ts.tcount != 0 { + t.Error("a seed was read") + } +} + +// TestTOTPReloadEndsGrant: a reload that turns a secret with an open +// window grant into a TOTP code (ask = "always") ends the grant: the next +// code needs a tap. +func TestTOTPReloadEndsGrant(t *testing.T) { + e, ts := totpEnv(t, func(cfg *config.Broker) { + s := cfg.Secrets["npm-otp"] + s.TOTP, s.Rule = false, config.Rule{Ask: config.AskWindow, Window: 15 * time.Minute} + cfg.Secrets["npm-otp"] = s + }, time.Now) + ts.set(func(f *fakeStore) { f.items[idOTP] = madeUp("password") }) + c := e.httpClient("laptop") + p := e.start(c, api.PathSecrets, secretsRequest("PW", "npm-otp")) + e.tap(e.waitAsked(1)[0].Prompt.RequestID, audit.AnswerApproveWindow) + secretsOf(t, p.wait(t)) + next := *e.svc.view().cfg + next.Secrets = maps.Clone(next.Secrets) + s := next.Secrets["npm-otp"] + s.TOTP, s.Rule = true, config.Rule{Ask: config.AskAlways} + next.Secrets["npm-otp"] = s + if ended, err := e.svc.Reload(&next, e.svc.view().keys, strings.Repeat("a", 64)); err != nil || ended != 1 { + t.Fatalf("Reload = %d, %v; want 1 grant ended", ended, err) + } + // The old kind is refused now, and a code needs a tap. + mustStatus(t, e.post(t.Context(), c, api.PathSecrets, secretsRequest("PW", "npm-otp")), http.StatusForbidden) + p = e.start(c, api.PathSecrets, totpRequest("NPM_OTP", "npm-otp")) + e.waitAsked(2) + p.cancel() + p.wait(t) +} diff --git a/internal/client/request_test.go b/internal/client/request_test.go index 7ee56d8..ed5b0cc 100644 --- a/internal/client/request_test.go +++ b/internal/client/request_test.go @@ -1,6 +1,7 @@ package client import ( + "errors" "net/http" "os" "os/exec" @@ -48,7 +49,13 @@ func TestRunUsage(t *testing.T) { {"two slashes", []string{"--secret", "GH_TOKEN=a/b/c", "--", "gh"}, "the secret name must be NAME or PROJECT/KEY"}, {"a variable twice", []string{"--secret", "GH_TOKEN=a", "--secret", "GH_TOKEN=b", "--", "gh"}, "the variable GH_TOKEN is given twice"}, - {"too many", append(thirtyThree, "--", "gh"), "at most 32 --secret options"}, + {"too many", append(thirtyThree, "--", "gh"), "at most 32 --secret and --totp options"}, + {"totp no =", []string{"--totp", "NPM_OTP", "--", "npm"}, "--totp needs VAR=NAME"}, + {"two totps", []string{"--totp", "A=x", "--totp", "B=y", "--", "npm"}, "--totp is given twice"}, + {"totp project name", []string{"--totp", "A=p/k", "--", "npm"}, "--totp A=...: the secret name must be NAME"}, + {"totp denied var", []string{"--totp", "PATH=x", "--", "npm"}, "--totp PATH=...: nodkey refuses the variable PATH"}, + {"totp and secret one var", []string{"--secret", "A=x", "--totp", "A=y", "--", "npm"}, + "--totp: the variable A is given twice"}, {"two reasons", []string{"--reason", "a", "--reason=b", "--secret", "A=b", "--", "gh"}, "--reason is given twice"}, {"a value for --mask", []string{"--secret", "A=b", "--mask=yes", "--", "gh"}, "--mask takes no value"}, {"two masks", []string{"--mask", "--secret", "A=b", "-mask", "--", "gh"}, "--mask is given twice"}, @@ -174,6 +181,51 @@ func TestParseArgs(t *testing.T) { } } +// TestTOTPHint: a 400 answer to a request with --totp says that the broker +// may be older; other answers and requests keep their text. +func TestTOTPHint(t *testing.T) { + t.Parallel() + code := []api.SecretRef{{Var: "A", Name: "a", Kind: api.KindTOTP}} + plain := []api.SecretRef{{Var: "A", Name: "a"}} + bad := statusError(http.StatusBadRequest) + if got := totpHint(bad, code).Error(); !strings.Contains(got, "400") || !strings.Contains(got, "update it") { + t.Errorf("400 with --totp: %q", got) + } + for _, tc := range []struct { + err error + refs []api.SecretRef + }{{bad, plain}, {statusError(http.StatusForbidden), code}, {errors.New("x"), code}} { + if got := totpHint(tc.err, tc.refs); got.Error() != tc.err.Error() { + t.Errorf("%v: changed to %v", tc.err, got) + } + } +} + +// TestParseArgsTOTP: --totp VAR=NAME asks for a TOTP code. It is sent +// with the kind "totp"; a --secret is sent with no kind field, as before. +func TestParseArgsTOTP(t *testing.T) { + t.Parallel() + o, err := parseArgs([]string{"--secret", "A=a", "--totp=NPM_OTP=npm-otp", "--", "npm", "publish", "--otp"}) + if err != nil { + t.Fatal(err) + } + want := []api.SecretRef{{Var: "A", Name: "a"}, {Var: "NPM_OTP", Name: "npm-otp", Kind: api.KindTOTP}} + if !slices.Equal(o.secrets, want) { + t.Fatalf("secrets = %+v, want %+v", o.secrets, want) + } + if _, err := parseArgs([]string{"-totp", "NPM_OTP=npm-otp", "--", "npm"}); err != nil { + t.Errorf("--totp alone: %v", err) + } + body, err := encodeRequest(newRequest(o.secrets, []string{"npm"}, "/", "")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), `{"var":"A","name":"a"}`) || + !strings.Contains(string(body), `{"var":"NPM_OTP","name":"npm-otp","kind":"totp"}`) { + t.Errorf("the request is %s", body) + } +} + // TestNewRequest: a claimed field over 64 KiB, and a command line with // more than 4096 arguments or more than 64 KiB in all, become "[hidden: // too long]" (DESIGN.md section 10). Fields at the limit stay. @@ -226,6 +278,7 @@ func TestLargestRequestFits(t *testing.T) { v := strings.Repeat("V", api.MaxName-2) + string(rune('A'+i/26)) + string(rune('A'+i%26)) secrets = append(secrets, api.SecretRef{Var: v, Name: strings.Repeat("\x01", api.MaxName)}) } + secrets[0].Kind = api.KindTOTP // one --totp at most command := make([]string, api.MaxArgs) for i := range command { command[i] = strings.Repeat("\x01", api.MaxText/api.MaxArgs) diff --git a/internal/client/run.go b/internal/client/run.go index b91ba63..4674f18 100644 --- a/internal/client/run.go +++ b/internal/client/run.go @@ -13,6 +13,7 @@ import ( "os/exec" "os/signal" "path/filepath" + "slices" "strconv" "strings" "sync" @@ -38,7 +39,7 @@ const ( ) // runUsage is the help of nodkey run. -const runUsage = `Usage: nodkey run [--secret VAR=NAME]... [--grant-token FILE] [--reason TEXT] [--mask | --no-mask] -- COMMAND [ARGS...] +const runUsage = `Usage: nodkey run [--secret VAR=NAME]... [--totp VAR=NAME] [--grant-token FILE] [--reason TEXT] [--mask | --no-mask] -- COMMAND [ARGS...] Ask the broker for secrets, and wait until a person approves the request on the phone. Then run COMMAND, with the value of the secret NAME in the @@ -50,6 +51,11 @@ environment variable VAR. nodkey never prints a value. LD_PRELOAD or GIT_SSH_COMMAND, in any case. NAME is a secret of the broker, or PROJECT/KEY for the secret KEY of a project of the broker. + --totp VAR=NAME the current TOTP code of the secret NAME, a secret of + the broker with totp = true, such as a code for + "npm publish --otp". The broker makes the code; the + TOTP seed never leaves it. At most one --totp; it + counts as one of the 32 secrets. --grant-token FILE the token file of a standing grant (nodkey preapprove). With it, no tap is needed inside a window of the grant. nodkey replaces the token in FILE with a new one before @@ -226,6 +232,9 @@ func (r runner) run(ctx context.Context, args []string, w io.Writer, beforeExec _, _ = fmt.Fprintf(stderr, "nodkey: waiting for approval (request %s)\n", code) }, hdr) if err != nil { + if ctx.Err() == nil { + err = totpHint(err, o.secrets) + } return requestFailed(ctx, stderr, err) } // The new token is saved before the values are used (DESIGN.md section @@ -401,6 +410,7 @@ type runOptions struct { func parseArgs(args []string) (*runOptions, error) { o := &runOptions{} vars := make(map[string]bool) + hasTOTP := false for rest := args; len(rest) > 0; { arg := rest[0] rest = rest[1:] @@ -410,13 +420,13 @@ func parseArgs(args []string) (*runOptions, error) { case len(o.command) == 0: return nil, errors.New(`no command after "--"`) case len(o.secrets) == 0: - return nil, errors.New("give at least one --secret VAR=NAME") + return nil, errors.New("give at least one --secret VAR=NAME or --totp VAR=NAME") } return o, nil } name, value, hasValue := splitOption(arg) switch name { - case "secret", "reason", "grant-token": + case "secret", "totp", "reason", "grant-token": case "mask": switch { case hasValue: @@ -473,15 +483,22 @@ func parseArgs(args []string) (*runOptions, error) { o.reason, o.reasonSet = value, true continue } - ref, err := parseSecret(value) + ref, err := parseSecret(name, value) if err != nil { return nil, err } + if name == "totp" { + if hasTOTP { + return nil, errors.New("--totp is given twice; one command gets at most one TOTP code") + } + hasTOTP = true + ref.Kind = api.KindTOTP + } switch { case vars[ref.Var]: - return nil, fmt.Errorf("--secret: the variable %s is given twice", ref.Var) + return nil, fmt.Errorf("--%s: the variable %s is given twice", name, ref.Var) case len(o.secrets) == api.MaxSecrets: - return nil, fmt.Errorf("at most %d --secret options", api.MaxSecrets) + return nil, fmt.Errorf("at most %d --secret and --totp options", api.MaxSecrets) } vars[ref.Var] = true o.secrets = append(o.secrets, ref) @@ -490,6 +507,21 @@ func parseArgs(args []string) (*runOptions, error) { `nodkey run --secret GH_TOKEN=github-token -- gh release create v1.2.0`) } +// totpHint adds a hint to the 400 answer of a request with --totp: a +// broker older than --totp refuses the field "kind" (DESIGN.md section 5, +// "TOTP codes"). Any other error is returned as it is. +func totpHint(err error, refs []api.SecretRef) error { + var e *Error + if !errors.As(err, &e) || e.Status != http.StatusBadRequest || + !slices.ContainsFunc(refs, func(r api.SecretRef) bool { return r.Kind == api.KindTOTP }) { + return err + } + c := *e + c.text += "; --totp needs a broker that hands out TOTP codes: " + + "if the broker is older than this client, update it (docs/setup.md, section 2)" + return &c +} + // splitOption splits an option such as --secret=VALUE or -reason into its // name and value. name is "" for an argument that is not an option. func splitOption(arg string) (name, value string, hasValue bool) { @@ -503,21 +535,26 @@ func splitOption(arg string) (name, value string, hasValue bool) { return strings.Cut(s, "=") } -// parseSecret reads the value of --secret: VAR=NAME. -func parseSecret(value string) (api.SecretRef, error) { +// parseSecret reads the value of --secret or --totp (opt): VAR=NAME. A +// TOTP code is never a project secret, so --totp takes only NAME. +func parseSecret(opt, value string) (api.SecretRef, error) { v, name, ok := strings.Cut(value, "=") prefix, denied := api.DeniedVar(v) switch { + case !ok && opt == "totp": + return api.SecretRef{}, errors.New("--totp needs VAR=NAME, such as NPM_OTP=npm-otp") case !ok: return api.SecretRef{}, errors.New("--secret needs VAR=NAME, such as GH_TOKEN=github-token") case !api.ValidVar(v): - return api.SecretRef{}, fmt.Errorf("--secret: the variable name %.64q must match [A-Za-z_][A-Za-z0-9_]{0,63}", v) + return api.SecretRef{}, fmt.Errorf("--%s: the variable name %.64q must match [A-Za-z_][A-Za-z0-9_]{0,63}", opt, v) case denied && prefix != "": - return api.SecretRef{}, fmt.Errorf("--secret %s=...: nodkey refuses variables that start with %s, "+ - "because programs show or run their values", v, prefix) + return api.SecretRef{}, fmt.Errorf("--%s %s=...: nodkey refuses variables that start with %s, "+ + "because programs show or run their values", opt, v, prefix) case denied: - return api.SecretRef{}, fmt.Errorf("--secret %s=...: nodkey refuses the variable %s, "+ - "because programs show or run its value", v, v) + return api.SecretRef{}, fmt.Errorf("--%s %s=...: nodkey refuses the variable %s, "+ + "because programs show or run its value", opt, v, v) + case opt == "totp" && !grantNamePattern.MatchString(name): + return api.SecretRef{}, fmt.Errorf("--totp %s=...: the secret name must be NAME, %s", v, grantNameRule) case len(name) > api.MaxSecretName || !validSecretName(name): return api.SecretRef{}, fmt.Errorf("--secret %s=...: the secret name must be NAME or PROJECT/KEY, "+ "each part %s", v, grantNameRule) diff --git a/internal/config/broker.go b/internal/config/broker.go index af4afd5..8e65890 100644 --- a/internal/config/broker.go +++ b/internal/config/broker.go @@ -255,6 +255,10 @@ type Secret struct { Store string // a name in Broker.Stores ID string // the item's ID in the store: a UUID, or for 1password a 1Password ID Field string // 1password only: the field's ID or title; "password" when the config has none + // TOTP is true when the secret is the current TOTP code of a bw login + // item, made on the broker from its login.totp field, not the + // item's password (key "totp"; DESIGN.md section 5, "TOTP codes"). + TOTP bool // The secret in Infisical: infisical only. ID is empty then. Project string // the project's ID Environment string // the environment's slug, such as "prod" @@ -345,6 +349,7 @@ type ( Store string `toml:"store"` ID string `toml:"id"` Field *string `toml:"field"` + TOTP *bool `toml:"totp"` // The keys of a secret of an infisical store. Project *string `toml:"project"` Environment *string `toml:"environment"` @@ -1077,6 +1082,9 @@ func (b *Broker) addSecrets(m map[string]secretSection) error { if _, ok := b.Stores[s.Store]; !ok { return fmt.Errorf("%s: no [store.*] section has this name", place(sec, "store")) } + if s.TOTP != nil && b.Stores[s.Store].Type != StoreBW { + return fmt.Errorf(`%s: is allowed only with a store of type = "bw"`, place(sec, "totp")) + } if b.Stores[s.Store].Type == StoreInfisical { inf, err := infisicalSecret(sec, s) if err != nil { @@ -1120,7 +1128,7 @@ func (b *Broker) addSecrets(m map[string]secretSection) error { place(sec, "id")) } } - secret := Secret{ID: s.ID, Field: field} + secret := Secret{ID: s.ID, Field: field, TOTP: s.TOTP != nil && *s.TOTP} if err := b.addSecret(name, sec, s, secret, never, strings.ToLower(s.ID)); err != nil { return err } @@ -1140,6 +1148,17 @@ func (b *Broker) addSecret(name, sec string, s secretSection, secret Secret, nev if err != nil { return err } + if secret.TOTP && (rule.Ask != AskAlways || rule.Standing) { + // One tap per code: a code works for any write of its account + // (DESIGN.md section 5, "TOTP codes"). A scheduled grant is a tap + // with a number of uses, so preapprove = true is allowed. + key := "ask" + if rule.Standing { + key = "standing" + } + return fmt.Errorf(`%s: a secret with totp = true needs ask = "always" and no standing grants; `+ + `use "nodkey preapprove" for a batch (DESIGN.md section 5, "TOTP codes")`, place(sec, key)) + } if rule.Ask == AskNever { if len(clients) != 1 { return fmt.Errorf(`%s: ask = "never" needs exactly one client`, place(sec, "clients")) diff --git a/internal/config/diff.go b/internal/config/diff.go index 25450c2..6c11772 100644 --- a/internal/config/diff.go +++ b/internal/config/diff.go @@ -283,6 +283,10 @@ func (d *differ) secrets(old, next *Broker) { q(p.old), q(p.new), secretRef(n)) } } + if o.TOTP != n.TOTP { + d.add("secret", name, true, "%s: now another value: totp changed from %t to %t, %s", what, + o.TOTP, n.TOTP, secretRef(n)) + } d.clientList("secret", name, what, "ask for it", o.Clients, n.Clients) d.rule("secret", name, what, o.Rule, n.Rule) } @@ -473,6 +477,9 @@ func secretRef(s Secret) string { if s.Field != "" && s.Field != "password" { ref += ", field " + q(s.Field) } + if s.TOTP { + ref += ", its TOTP code" + } return ref } @@ -709,7 +716,7 @@ var compared = map[reflect.Type][]string{ reflect.TypeFor[Client](): {"Name", "Pin"}, reflect.TypeFor[Store](): {"Name", "Type", "Program", "TokenFile", "PasswordFile", "Vault", "Server", "ClientID", "ClientSecretFile"}, - reflect.TypeFor[Secret](): {"Name", "Store", "ID", "Field", "Project", "Environment", "Path", "SecretName", + reflect.TypeFor[Secret](): {"Name", "Store", "ID", "Field", "TOTP", "Project", "Environment", "Path", "SecretName", "Clients"}, reflect.TypeFor[Key](): {"Name", "File", "Clients", "Hosts"}, reflect.TypeFor[Logins](): {"Name", "Store", "Collection", "Clients"}, diff --git a/internal/config/totp_test.go b/internal/config/totp_test.go new file mode 100644 index 0000000..4b2a1d0 --- /dev/null +++ b/internal/config/totp_test.go @@ -0,0 +1,80 @@ +package config + +import ( + "strings" + "testing" +) + +// dbAlways is the start of the [secret.db-password] section of the valid +// config, a secret of the bw store vault with ask = "always". +const dbAlways = "id = \"00000000-0000-0000-0000-00000000000A\"\nclients = [\"laptop\", \"backup-box\"]\nask = \"always\"\n" + +// TestLoadBrokerTOTP: totp = true makes a secret of a bw store a TOTP +// code. It is off by default, and allowed only for a bw store with +// ask = "always" and no standing grants; preapprove = true is fine. +func TestLoadBrokerTOTP(t *testing.T) { + e := newBrokerEnv(t) + b, err := LoadBroker(e.write(t)) + if err != nil { + t.Fatal(err) + } + for name, s := range b.Secrets { + if s.TOTP { + t.Errorf("secret %s: TOTP is on by default", name) + } + } + b, err = LoadBroker(e.write(t, edit{dbAlways, dbAlways + "totp = true\npreapprove = true\n"})) + if err != nil { + t.Fatal(err) + } + if s := b.Secrets["db-password"]; !s.TOTP || !s.Rule.Preapprove { + t.Errorf("totp = true: TOTP = %v, Preapprove = %v", s.TOTP, s.Rule.Preapprove) + } + b, err = LoadBroker(e.write(t, edit{dbAlways, dbAlways + "totp = false\n"})) + if err != nil || b.Secrets["db-password"].TOTP { + t.Errorf("totp = false: %v", err) + } + cases := []struct { + name string + ed edit + want string + }{ + {"bws store", edit{"ask = \"window\"\nwindow = \"15m\"\n", "ask = \"always\"\ntotp = true\n"}, + `[secret.github-token] totp: is allowed only with a store of type = "bw"`}, + {"window", edit{dbAlways, strings.Replace(dbAlways, `"always"`, `"window"`, 1) + "window = \"5m\"\ntotp = true\n"}, + `[secret.db-password] ask: a secret with totp = true needs ask = "always" and no standing grants`}, + {"never", edit{dbAlways, "id = \"00000000-0000-0000-0000-00000000000A\"\nclients = [\"laptop\"]\nask = \"never\"\ntotp = true\n"}, + `[secret.db-password] ask: a secret with totp = true needs ask = "always"`}, + {"standing", edit{dbAlways, dbAlways + "standing = true\ntotp = true\n"}, + `[secret.db-password] standing: a secret with totp = true needs ask = "always" and no standing grants`}, + {"not a bool", edit{dbAlways, dbAlways + "totp = \"yes\"\n"}, "destination has type boolean"}, + } + for _, tc := range cases { + _, err := LoadBroker(e.write(t, tc.ed)) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("%s: error %v, want %q", tc.name, err, tc.want) + } + } +} + +// TestDiffTOTP: config-diff shows a new TOTP secret, and a change of +// totp, as a change that widens. +func TestDiffTOTP(t *testing.T) { + old := &Broker{Secrets: map[string]Secret{"otp": {Name: "otp", Store: "vault", ID: "00000000-0000-0000-0000-00000000000a"}}} + next := &Broker{Secrets: map[string]Secret{"otp": {Name: "otp", Store: "vault", ID: "00000000-0000-0000-0000-00000000000a", TOTP: true}}} + if old.SameSecret(next, "otp", "laptop") { + t.Error("SameSecret ignores totp") + } + var found bool + for _, c := range Diff(old, next) { + if strings.Contains(c.Text, "totp changed from false to true") && strings.Contains(c.Text, "its TOTP code") { + found = true + if !c.Widens { + t.Errorf("not marked as one that widens: %+v", c) + } + } + } + if !found { + t.Errorf("the diff does not show the change of totp: %+v", Diff(old, next)) + } +} diff --git a/internal/store/bwlogin.go b/internal/store/bwlogin.go index 069f40a..b92387d 100644 --- a/internal/store/bwlogin.go +++ b/internal/store/bwlogin.go @@ -44,6 +44,37 @@ type LoginStore interface { FetchLoginNoSync(ctx context.Context, id string) (Login, error) } +// ErrNoTOTP is returned for a login item with no TOTP seed (login.totp). +var ErrNoTOTP = errors.New("the item has no TOTP seed in its login.totp field") + +// TOTPStore is a store that hands the TOTP seed of a login item to the +// broker, which makes the code (DESIGN.md section 5, "TOTP codes"). Only +// the bw store is one. +type TOTPStore interface { + // FetchTOTP runs "bw sync --force" and "bw get item ID" and returns + // the seed of login.totp. An item in the trash is ErrTrashed, an + // archived item ErrArchived, an item that is not a login ErrNotLogin, + // and an item with no seed ErrNoTOTP. The caller must Clear the seed. + FetchTOTP(ctx context.Context, id string) (Value, error) +} + +// FetchTOTP implements TOTPStore. +func (s *bwStore) FetchTOTP(ctx context.Context, id string) (Value, error) { + if !isUUID(id) { + return Value{}, stepError(s.run.store, stepGetItem, ErrBadID) + } + out, err := s.synced(ctx, true, stepGetItem, "get", "item", id) + if err != nil { + return Value{}, err + } + defer clear(out) + v, err := parseBWTOTP(out, id) + if err != nil { + return Value{}, stepError(s.run.store, stepGetItem, err) + } + return v, nil +} + // LoginURI is one URI of a login item: login.uris[].uri, and // login.uris[].match (nil when the item has none). type LoginURI struct { @@ -347,6 +378,49 @@ func parseBWLoginList(data []byte, collection string) ([]LoginItem, error) { // 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, err := parseBWLoginFields(data, id) + if err != nil { + 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 +} + +// parseBWTOTP reads the answer of "bw get item ID" for a TOTP code +// (DESIGN.md section 5, "TOTP codes"): the item id, a login item that is +// not in the trash and not archived. It returns the seed of login.totp +// and clears the password at once. An item with no seed is ErrNoTOTP. A +// login with no password is fine: the code needs only the seed. +func parseBWTOTP(data []byte, id string) (Value, error) { + f, err := parseBWLoginFields(data, id) + if err != nil { + return Value{}, err + } + clear(f.password) + f.password = nil + if len(f.totp) == 0 { + return Value{}, ErrNoTOTP + } + totp := f.totp + f.totp = nil + return newValue(totp), nil +} + +// parseBWLoginFields reads one login item with its secrets and checks +// that it is the item id, a login, and not in the trash or archived. On +// an error, the secrets are cleared. +func parseBWLoginFields(data []byte, id string) (loginFields, error) { f := loginFields{wantSecrets: true} r := &jsonReader{data: data} r.space() @@ -370,21 +444,9 @@ func parseBWLogin(data []byte, id string) (Login, error) { } if err != nil { f.clearSecrets() - return Login{}, err + return loginFields{}, 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 + return f, nil } // hasID reports whether ids holds id, in upper or lower case. diff --git a/internal/store/bwtotp_test.go b/internal/store/bwtotp_test.go new file mode 100644 index 0000000..96fa6d3 --- /dev/null +++ b/internal/store/bwtotp_test.go @@ -0,0 +1,95 @@ +package store + +import ( + "fmt" + "slices" + "testing" + + "github.com/code6x/nodkey/internal/config" +) + +// TestBWFetchTOTP: FetchTOTP runs the fake bw with "bw sync --force" and +// "bw get item", and returns only the seed of login.totp. A login with no +// password is fine. The seed is hidden in every format. +func TestBWFetchTOTP(t *testing.T) { + t.Parallel() + for name, pw := range map[string]string{"with a password": madeUp("password"), "no password": ""} { + t.Run(name, func(t *testing.T) { + t.Parallel() + seed, other := madeUp("totp"), madeUp("other") + sc := bwScenario(madeUp("password"), "", madeUp("value"), other) + sc.Items[testItemID] = loginJSON(testItemID, 1, []string{testCollection}, pw, seed, other, nil) + f := newTestFake(t, config.StoreBW, sc, testDeps()) + v, err := f.store.(TOTPStore).FetchTOTP(t.Context(), testItemID) + if err != nil { + t.Fatalf("FetchTOTP: %v", err) + } + checkValue(t, v, seed) + noCanary(t, "the seed's format", fmt.Sprintf("%v %+v %#v %s %q", v, v, v, v, v), seed) + if got, want := f.steps(), []string{"unlock", "sync", "get item"}; !slices.Equal(got, want) { + t.Errorf("steps = %q, want %q", got, want) + } + buf := v.Bytes() + v.Clear() + for _, c := range buf { + if c != 0 { + t.Fatal("Clear left the seed") + } + } + }) + } +} + +// TestBWFetchTOTPRefused: no seed, an item in the trash, an archived item, +// an item that is not a login, another item and a bad ID are refused, and +// the error holds no secret of the item. +func TestBWFetchTOTPRefused(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 + }{ + "no seed": {loginJSON(testItemID, 1, cols, pw, "", other, nil), ErrNoTOTP}, + "null seed": {`{"id":"` + testItemID + `","type":1,"login":{"password":"` + pw + `","totp":null}}`, ErrNoTOTP}, + "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}, + "other item": {loginJSON(testItemID2, 1, cols, pw, seed, other, nil), errOtherItem}, + "a list": {"[" + loginJSON(testItemID, 1, cols, pw, seed, other, nil) + "]", 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()) + v, err := f.store.(TOTPStore).FetchTOTP(t.Context(), testItemID) + checkErr(t, err, tc.want) + if v.Bytes() != nil { + t.Error("FetchTOTP returned a seed with its error") + } + if err != nil { + for _, s := range []string{pw, seed, other} { + noCanary(t, "the error", err.Error(), s) + } + } + }) + } + sc := bwScenario(madeUp("password"), "", madeUp("value"), other) + f := newTestFake(t, config.StoreBW, sc, testDeps()) + if _, err := f.store.(TOTPStore).FetchTOTP(t.Context(), "not-a-uuid"); err == nil { + t.Error("a bad ID was accepted") + } +} + +// TestOnlyBWHandsOutTOTP: no other store type is a TOTPStore. +func TestOnlyBWHandsOutTOTP(t *testing.T) { + t.Parallel() + for _, s := range []Store{&bwsStore{}, &opStore{}, &infStore{}} { + if _, ok := s.(TOTPStore); ok { + t.Errorf("%T is a TOTPStore", s) + } + } +}