diff --git a/README.md b/README.md index a102e51..bc6ec43 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ A key lifts those limits and unlocks every option, `request` and `sitemap`. Ther export STRING_API_KEY="your-api-key" ``` -`string whoami` shows which key commands use, and `string logout` deletes the saved one. +`string whoami` shows which key commands use, the account it was saved for and the key's first characters, and checks it with String in one request that spends no credit. It exits 3 when String refuses the key, and 6 when it couldn't ask. `string whoami --offline` only says where the key comes from, as `whoami` did before. `string logout` deletes the saved key. An agent working with nobody present can register for a trial key instead, where the server offers it. `string trial` solves a few seconds' proof of work and saves a key with a small balance in the same file. The key doesn't expire; it works until its credit runs out. Beside it, in `trial.json`, it keeps a claim token, which a person can use for 7 days to adopt the agent onto their String account. Neither is printed. Where trial keys are switched off, `string trial` exits 3. diff --git a/cmd/string/help.go b/cmd/string/help.go index 237cdf5..285c301 100644 --- a/cmd/string/help.go +++ b/cmd/string/help.go @@ -367,16 +367,19 @@ var commandDocs = map[string]commandDoc{ more: keysDocs, }, "whoami": { - summary: "say which key string uses", - usage: []string{"string whoami"}, - examples: []string{"string whoami"}, + summary: "say which key string uses, and check it with String", + usage: []string{"string whoami [--offline]"}, + examples: []string{"string whoami", "string whoami --offline"}, returns: []string{ - "stdout where the key comes from, STRING_API_KEY or the saved file, and the", - " account it was saved for", - "exit 0 a key is set · 3 none is", + "stdout where the key comes from, STRING_API_KEY or the saved file, the", + " account it was saved for, the key's start, and whether String", + " accepts it. --json gives one object", + "exit 0 String accepts the key · 3 no key, or String refused it · 6 string", + " couldn't ask String", }, - cost: "Free, and it sends no request.", - more: keysDocs, + cost: "Free: one request that spends no credit, or none with --offline.", + flags: " --offline say where the key comes from, without asking String\n", + more: keysDocs, }, "trial": { summary: "get a trial key for an agent, with no account", diff --git a/cmd/string/login.go b/cmd/string/login.go index 89408a6..7fb3067 100644 --- a/cmd/string/login.go +++ b/cmd/string/login.go @@ -814,33 +814,77 @@ func logoutCommand(list []string, rt runtime) error { } func whoamiCommand(list []string, rt runtime) error { - if done, err := noOptions(list, "whoami", rt); done { - return err + parsed, err := parse(list, spec{switches: []string{"offline"}}) + if err != nil { + return usage(err) } - path, ok := credentialsPath(rt.env) - if key, _ := rt.env("STRING_API_KEY"); key != "" { - if saved, err := loadCredentials(path); ok && err == nil && saved.APIKey != "" { - return write(rt.stdout, []byte(fmt.Sprintf("Using STRING_API_KEY from the environment. It wins over the key saved in %s.\n", path))) - } - return write(rt.stdout, []byte("Using STRING_API_KEY from the environment.\n")) + if parsed.help { + return write(rt.stdout, []byte(helpFor("whoami"))) } + if err := expectPositionals(parsed.positionals, 0, "string whoami [--offline]"); err != nil { + return usage(err) + } + if _, ok := parsed.value("input"); ok { + return usage(errors.New("--input does not apply to whoami")) + } + path, ok := credentialsPath(rt.env) + var saved credentials if ok { - saved, err := loadCredentials(path) - if err != nil { + if saved, err = loadCredentials(path); err != nil { return err } - if saved.APIKey != "" && saved.Email != "" { - return write(rt.stdout, []byte(fmt.Sprintf("Logged in as %s, with the key saved in %s.\n", saved.Email, path))) + } + env, _ := rt.env("STRING_API_KEY") + key, from := saved.APIKey, "the key saved in "+path + said := fmt.Sprintf("Using the key saved in %s", path) + switch { + case env != "" && saved.APIKey != "": + key, from, said = env, "the key in STRING_API_KEY", fmt.Sprintf("Using STRING_API_KEY from the environment. It wins over the key saved in %s", path) + case env != "": + key, from, said = env, "the key in STRING_API_KEY", "Using STRING_API_KEY from the environment" + case saved.APIKey != "" && saved.Email != "": + said = fmt.Sprintf("Logged in as %s, with the key saved in %s", saved.Email, path) + case saved.APIKey == "": + return &failure{ + exit: exitAuth, + code: "not_logged_in", + message: "Not logged in. string fetch and string search run keyless, within a daily allowance.", + nextStep: needsKey, + helpURL: helpURL, } - if saved.APIKey != "" { - return write(rt.stdout, []byte(fmt.Sprintf("Using the key saved in %s.\n", path))) + } + if parsed.switches["offline"] { + return write(rt.stdout, []byte(said+".\n")) + } + // One request, which spends no credit, says whether String takes the key. + base, err := apiBaseURL(rt.env) + if err != nil { + return usage(err) + } + if _, err := (apiClient{rt: rt, base: base, key: key}).call(&operation{method: "GET", path: "/account/balance"}); err != nil { + if refused := asFailure(err); refused.exit == exitAuth { + next := "run `string login` to save a new key" + if from == "the key in STRING_API_KEY" { + next = "check STRING_API_KEY, or unset it and run `string login`" + } + return &failure{exit: exitAuth, code: "key_refused", status: refused.status, requestID: refused.requestID, message: "String refused " + from + " (" + keyPrefix(key) + ").", nextStep: next} } + yes := true + return &failure{exit: exitUpstream, code: "unverified", retryable: &yes, message: said + " (" + keyPrefix(key) + "), but string couldn't check it with String.", notes: []string{strings.TrimPrefix(asFailure(err).Error(), "error: ")}, nextStep: "run it again, or `string whoami --offline` to see the key without checking it"} } - return &failure{ - exit: exitAuth, - code: "not_logged_in", - message: "Not logged in. string fetch and string search run keyless, within a daily allowance.", - nextStep: needsKey, - helpURL: helpURL, + if rt.json { + source := "saved" + if key == env { + source = "STRING_API_KEY" + } + shown, _ := json.Marshal(map[string]any{"source": source, "credentials": path, "email": saved.Email, "key_prefix": keyPrefix(key), "accepted": true}) + return write(rt.stdout, append(shown, '\n')) } + return write(rt.stdout, []byte(said+" ("+keyPrefix(key)+"). String accepts it.\n")) +} + +// keyPrefix is the start of key, enough to tell keys apart and never more +// than a third of it. +func keyPrefix(key string) string { + return key[:min(8, len(key)/3)] + "…" } diff --git a/cmd/string/run.go b/cmd/string/run.go index 3df55ad..920e62f 100644 --- a/cmd/string/run.go +++ b/cmd/string/run.go @@ -201,7 +201,8 @@ and the first part of its hostname, as in Mac · work-laptop. String puts it in the new key's name, which your organization sees on its API keys page. --device-name NAME sends NAME instead, and init takes it too. --browser and --with-token send no name. -STRING_API_KEY wins over a saved key; whoami says which one is in use. +STRING_API_KEY wins over a saved key. whoami says which one is in use and +checks it with String, which costs nothing; whoami --offline doesn't check. trial registers an agent for a trial key with no account: after a few seconds' proof of work, it saves a key with a small balance that doesn't expire, and a claim token a person can use to adopt the agent onto their account. diff --git a/cmd/string/run_test.go b/cmd/string/run_test.go index ace514d..1bb4e80 100644 --- a/cmd/string/run_test.go +++ b/cmd/string/run_test.go @@ -635,7 +635,7 @@ func TestLoginSavesTheReleasedKeyForLaterCommands(t *testing.T) { t.Errorf("fetch status %d, authorization %q: %s", status, fetchAuthorization, stderr.String()) } stdout.Reset() - if status := run([]string{"whoami"}, rt); status != 0 || !strings.Contains(stdout.String(), path) { + if status := run([]string{"whoami", "--offline"}, rt); status != 0 || !strings.Contains(stdout.String(), path) { t.Errorf("whoami status %d: %s", status, stdout.String()) } if status := run([]string{"logout"}, rt); status != 0 { diff --git a/cmd/string/whoami_test.go b/cmd/string/whoami_test.go new file mode 100644 index 0000000..5e7c428 --- /dev/null +++ b/cmd/string/whoami_test.go @@ -0,0 +1,81 @@ +package main + +import ( + "bytes" + "errors" + "io" + "net/http" + "path/filepath" + "strings" + "testing" +) + +// whoami checks the key with one request that spends no credit: it says +// whether String takes it, exits 3 when String refuses it, and 6 when it +// couldn't ask. --offline says where the key comes from without asking. +func TestWhoamiChecksTheKeyWithString(t *testing.T) { + const savedKey, envKey = "saved-key-0123456789abcdef", "env-key-fedcba9876543210" + answer, sent := http.StatusOK, "" + base := api(t, func(w http.ResponseWriter, r *http.Request) { + sent = r.Method + " " + r.URL.Path + " " + r.Header.Get("Authorization") + w.WriteHeader(answer) + io.WriteString(w, `{"error":"Invalid API key"}`) + }) + whoami := func(client *http.Client, env string, saved bool, list ...string) result { + home := t.TempDir() + vars := map[string]string{"HOME": home, "STRING_API_BASE_URL": base} + if env != "" { + vars["STRING_API_KEY"] = env + } + if saved { + if err := saveCredentials(filepath.Join(home, ".config", "string", "credentials.json"), credentials{APIKey: savedKey, Email: "dev@localhost"}); err != nil { + t.Fatal(err) + } + } + var stdout, stderr bytes.Buffer + status := run(append([]string{"whoami"}, list...), runtime{env: envOf(vars), client: client, stdout: &stdout, stderr: &stderr}) + return result{status, stdout.String(), strings.ReplaceAll(stderr.String(), home, "HOME")} + } + path := filepath.Join("HOME", ".config", "string", "credentials.json") + + got := whoami(http.DefaultClient, "", true) + if !strings.HasSuffix(got.output, "/.config/string/credentials.json (saved-ke…). String accepts it.\n") || !strings.HasPrefix(got.output, "Logged in as dev@localhost, with the key saved in ") || got.status != 0 || sent != "GET /v1/account/balance Bearer "+savedKey { + t.Errorf("a saved key: %+v, sent %q", got, sent) + } + if got := whoami(http.DefaultClient, envKey, false); got.status != 0 || got.output != "Using STRING_API_KEY from the environment (env-key-…). String accepts it.\n" || sent != "GET /v1/account/balance Bearer "+envKey { + t.Errorf("STRING_API_KEY: %+v, sent %q", got, sent) + } + if got := whoami(http.DefaultClient, envKey, true); got.status != 0 || !strings.HasPrefix(got.output, "Using STRING_API_KEY from the environment. It wins over the key saved in ") || !strings.HasSuffix(got.output, " (env-key-…). String accepts it.\n") { + t.Errorf("both: %+v", got) + } + if got := whoami(http.DefaultClient, "", true, "--json"); got.status != 0 || !strings.Contains(got.output, `"accepted":true`) || !strings.Contains(got.output, `"key_prefix":"saved-ke…"`) || !strings.Contains(got.output, `"source":"saved"`) || !strings.Contains(got.output, `"email":"dev@localhost"`) { + t.Errorf("--json: %+v", got) + } + + answer = http.StatusUnauthorized + if got := whoami(http.DefaultClient, "", true); got.status != exitAuth || got.errors != "error: String refused the key saved in "+path+" (saved-ke…).\n\nnext: run `string login` to save a new key\n" { + t.Errorf("a refused saved key: %+v", got) + } + if got := whoami(http.DefaultClient, envKey, false); got.status != exitAuth || got.errors != "error: String refused the key in STRING_API_KEY (env-key-…).\n\nnext: check STRING_API_KEY, or unset it and run `string login`\n" { + t.Errorf("a refused STRING_API_KEY: %+v", got) + } + answer = http.StatusServiceUnavailable + if got := whoami(http.DefaultClient, envKey, false); got.status != exitUpstream || !strings.HasPrefix(got.errors, "error: Using STRING_API_KEY from the environment (env-key-…), but string couldn't check it with String.\n ") { + t.Errorf("String failing: %+v", got) + } + unreachable := &http.Client{Transport: failingTransport{errors.New("no route")}} + if got := whoami(unreachable, envKey, false); got.status != exitUpstream || !strings.Contains(got.errors, "but string couldn't check it with String.\n string lost the connection to ") { + t.Errorf("no network: %+v", got) + } + + offline := &http.Client{Transport: noNetwork{t}} + if got := whoami(offline, "", true, "--offline"); got.status != 0 || !strings.HasPrefix(got.output, "Logged in as dev@localhost, with the key saved in ") || !strings.HasSuffix(got.output, "credentials.json.\n") { + t.Errorf("--offline: %+v", got) + } + if got := whoami(offline, "", false); got.status != exitAuth || !strings.HasPrefix(got.errors, "error: Not logged in.") { + t.Errorf("no key: %+v", got) + } + if keyPrefix("abcdef") != "ab…" || keyPrefix("0123456789abcdefghijklmnop") != "01234567…" { + t.Errorf("keyPrefix: %q, %q", keyPrefix("abcdef"), keyPrefix("0123456789abcdefghijklmnop")) + } +}