diff --git a/docs/cli.md b/docs/cli.md index 7c9bef0..87ccade 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -61,7 +61,7 @@ Sign in through the browser: frbit auth login ``` -The command prints the sign-in URL and a code first, opens the URL in your default browser, and waits up to 15 minutes. Type the code on the consent page: it shows that the sign-in in the browser belongs to this terminal. Without an account, the same page signs you up. It stores the credential in your operating system's credential store and saves the API host for subsequent commands. The credential refreshes itself before it expires and is only sent to the API host it signed in to; for another host, run `frbit --host auth login`. +The command prints the sign-in URL and a code first, opens the URL in your default browser, and waits up to 15 minutes. Type the code on the consent page: it shows that the sign-in in the browser belongs to this terminal. Without an account, the same page signs you up. It stores the credential in your operating system's credential store and saves the API host for subsequent commands. It then prints the next setup step and, while your account has no SSH key, the optional step to add one. The credential refreshes itself before it expires and is only sent to the API host it signed in to; for another host, run `frbit --host auth login`. | Option | Effect | |--|--| @@ -484,7 +484,7 @@ It runs the local `ssh` with your own SSH key; `mysqldump --single-transaction - The default output is `.sql.gz` in the current folder; `--output` is a file or a folder. The file has mode 0600 and appears only once the dump is complete. An existing file is not overwritten unless you pass `--force`. `--output -` is refused: `db pull` writes a file. -A rejected SSH key or a failed connection (ssh exit 255) points to . A missing `ssh` client fails before any request. +A failed SSH connection is explained as under [SSH](#ssh). A missing `ssh` client fails before any request. The host key of fortrabbit's production SSH endpoints (`ssh..frbit.app`) ships with frbit: `ssh-ed25519`, fingerprint `SHA256:UB3p/YgtQSuK3WESB/0ra5dTDWkggrCOz0WkWe4Tvvg`. frbit writes it to `known_hosts` in its config folder (mode 0600, rewritten when it differs) and checks these hosts against that file alone, with `StrictHostKeyChecking=yes`. The first connection from an agent or CI needs no prompt and no entry in `~/.ssh/known_hosts`. Entries for these hosts in your own `known_hosts` files are not used, because ssh accepts a key found in any listed file. If the server shows another key, the command stops: do not accept the key by hand; update frbit, and contact fortrabbit support if it persists. @@ -509,7 +509,7 @@ Each step is its own SSH call with your own SSH key: 4. Import: `gunzip -c | mysql "$FORTRABBIT_DB_NAME"`. 5. Removal of the upload. -A failure or Ctrl-C after the backup says whether the database changed and prints the backup path and the command to restore it, `ssh 'set -o pipefail; gunzip -c /data/home/frbit-backup-.sql.gz | mysql "$FORTRABBIT_DB_NAME"'`. Ctrl-C during the import leaves the database partly imported. The backup stays on the environment; remove it once you no longer need it. A rejected SSH key (ssh exit 255) points to . +A failure or Ctrl-C after the backup says whether the database changed and prints the backup path and the command to restore it, `ssh 'set -o pipefail; gunzip -c /data/home/frbit-backup-.sql.gz | mysql "$FORTRABBIT_DB_NAME"'`. Ctrl-C during the import leaves the database partly imported. The backup stays on the environment; remove it once you no longer need it. A failed SSH connection is explained as under [SSH](#ssh). ## SSH @@ -525,6 +525,18 @@ Several arguments after `--` are quoted one by one, so a space or `;` inside one The connection uses your own SSH key and the same settings as `db` and `files`: no agent or X11 forwarding and the pinned host key of fortrabbit's SSH endpoints. With a terminal, ssh gets one too; without one, as in scripts, it runs in batch mode and never prompts. +When ssh itself fails (exit 255), frbit reads its message and names the missing step: + +| ssh says | frbit says | +|--|--| +| `Permission denied (publickey)` | Whether your account has no SSH key, ssh has none to offer here, or the key here is not on your account or needs `ssh-add` for its passphrase. Without a key here: create one with `ssh-keygen -t ed25519`. Then add the public key at . | +| `Too many authentication failures` | ssh offered too many keys: set `IdentitiesOnly yes` and the `IdentityFile` for the host in `~/.ssh/config`. | +| `Could not resolve hostname`, `Connection refused`, a timeout | The connection failed: check the network, a firewall or VPN, and . | +| `Host key verification failed` | The host key is unknown, changed, or not fortrabbit's. | +| anything else | All of the above as possible causes. | + +frbit learns whether your account has a key from the "Add an SSH key" setup step, and whether this machine has one from `ssh -G` and the SSH agent. + ## Files ```sh @@ -545,7 +557,7 @@ A sync without a path, and any sync with `--delete`, refuses to run from `/`, yo `files push`, `files pull` without a path, and `files pull --delete` need the environment ID typed on a terminal, or `--confirm ` without one; a dry run needs neither. The check runs before rsync starts; with a label or the environment of the checkout, the environment may already have been read from the API to resolve it. When the environment deploys from a Git branch, the warning says that the next deployment overwrites code pushed this way. -On a terminal rsync shows per-file progress (`--progress`). Missing `rsync` or `ssh` fails with how to install it. A rejected SSH key (exit 255) points to ; any other rsync failure names rsync's exit code. Ctrl-C stops rsync and says the sync stopped partway. +On a terminal rsync shows per-file progress (`--progress`). Missing `rsync` or `ssh` fails with how to install it. A failed SSH connection is explained as under [SSH](#ssh); any other rsync failure names rsync's exit code. Ctrl-C stops rsync and says the sync stopped partway. ## People @@ -926,4 +938,6 @@ Global options: If a command reports that no API token is available, set `FRBIT_TOKEN` for that command or run `frbit auth login`. +An expired or revoked sign-in fails with "the sign-in expired or was revoked" and the `frbit auth login` command for the profile and host in use. A refused `FRBIT_TOKEN` names that variable. + If authentication fails, confirm that the token is active and has access to the expected apps, then run `frbit auth status` to test the exact profile and host in use. diff --git a/internal/api/client.go b/internal/api/client.go index 901288f..a8e91c6 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -32,6 +32,8 @@ type Client struct { tokens TokenSource http *http.Client userAgent string + // SignIn names the fix when the API or the sign-in server refuses the credential. + SignIn SignInHint // Warnings receives the API's Warning, Deprecation and Sunset headers; nil discards them. Warnings io.Writer warned *sync.Map @@ -114,11 +116,15 @@ func (s *OAuthTokens) refreshLocked(ctx context.Context, stale string) (string, return stored.AccessToken, nil } if stored.Kind != credentials.KindOAuth || stored.RefreshToken == "" { - return "", fmt.Errorf("the sign-in for profile %q has expired; run `frbit auth login` again", s.profile) + return "", &SignInError{Err: fmt.Errorf("the sign-in for profile %q has expired", s.profile)} } refreshed, err := s.refresh(ctx, stored.RefreshToken) + var refused interface{ Refused() bool } + if errors.As(err, &refused) && refused.Refused() { + return "", &SignInError{Err: err} + } if err != nil { - return "", fmt.Errorf("refresh the sign-in for profile %q: %w; run `frbit auth login` again", s.profile, err) + return "", fmt.Errorf("refresh the sign-in for profile %q: %w", s.profile, err) } if err := s.store.Set(s.profile, refreshed); err != nil { return "", fmt.Errorf("save refreshed credential: %w", err) @@ -127,6 +133,37 @@ func (s *OAuthTokens) refreshLocked(ctx context.Context, stale string) (string, return refreshed.AccessToken, nil } +// SignInHint says where the credential came from, so a refusal names the right fix. +type SignInHint struct { + // FromEnv marks a token from FRBIT_TOKEN. + FromEnv bool + // Login is the sign-in command for this profile and host; empty means `frbit auth login`. + Login string +} + +// SignInError is a credential the API or the sign-in server refused: expired, revoked or invalid. +type SignInError struct { + Hint SignInHint + Err error +} + +func (e *SignInError) Error() string { + login := e.Hint.Login + if login == "" { + login = "frbit auth login" + } + message := fmt.Sprintf("the sign-in expired or was revoked; run `%s`", login) + if e.Hint.FromEnv { + message = fmt.Sprintf("the API token in FRBIT_TOKEN is invalid, expired or revoked; set a valid token, or unset FRBIT_TOKEN and run `%s`", login) + } + if e.Err != nil { + message += " (" + e.Err.Error() + ")" + } + return message +} + +func (e *SignInError) Unwrap() error { return e.Err } + type HTTPError struct { Status int Message string @@ -348,15 +385,25 @@ type rawResponse struct { header http.Header } -// do sends the call and repeats it once with a refreshed token after a 401. +// do sends the call and repeats it once with a refreshed token after a 401; a refused credential becomes a SignInError. func (c Client) do(ctx context.Context, request call) (rawResponse, error) { + response, err := c.doOnce(ctx, request) + var signIn *SignInError + if errors.As(err, &signIn) { + signIn.Hint = c.SignIn + } else if unauthorized(err) { + err = &SignInError{Hint: c.SignIn, Err: err} + } + return response, err +} + +func (c Client) doOnce(ctx context.Context, request call) (rawResponse, error) { token, err := c.tokens.Token(ctx) if err != nil { return rawResponse{}, err } response, err := c.send(ctx, request, token) - var httpErr *HTTPError - if !errors.As(err, &httpErr) || httpErr.Status != http.StatusUnauthorized { + if !unauthorized(err) { return response, err } refreshed, refreshErr := c.tokens.Refresh(ctx, token) @@ -369,6 +416,11 @@ func (c Client) do(ctx context.Context, request call) (rawResponse, error) { return c.send(ctx, request, refreshed) } +func unauthorized(err error) bool { + var httpErr *HTTPError + return errors.As(err, &httpErr) && httpErr.Status == http.StatusUnauthorized +} + func (c Client) send(ctx context.Context, call call, token string) (rawResponse, error) { if err := checkPath(call.path); err != nil { return rawResponse{}, err diff --git a/internal/api/client_refresh_test.go b/internal/api/client_refresh_test.go index bee6b34..a06dd6e 100644 --- a/internal/api/client_refresh_test.go +++ b/internal/api/client_refresh_test.go @@ -3,6 +3,7 @@ package api import ( "context" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" @@ -208,8 +209,29 @@ func TestRevokedGrantAsksToSignInAgain(t *testing.T) { }} client := newOAuthClient(t, server, store, filepath.Join(t.TempDir(), "credentials.lock")) + client.SignIn = SignInHint{Login: "frbit auth login --profile work"} _, err := client.Apps(context.Background(), 1) - if err == nil || !strings.Contains(err.Error(), "frbit auth login") { + var signIn *SignInError + if !errors.As(err, &signIn) || err.Error() != "the sign-in expired or was revoked; run `frbit auth login --profile work` (token request failed with HTTP 400: invalid_grant)" { + t.Fatalf("Apps() error = %v", err) + } +} + +func TestAFailedRefreshRequestIsNoSignInError(t *testing.T) { + store := &memoryStore{credentials: map[string]credentials.Credential{ + "default": {Kind: credentials.KindOAuth, AccessToken: "access-1", RefreshToken: "refresh-1", ExpiresAt: time.Now().Add(-time.Minute), Issuer: "https://api.example"}, + }} + refresh := func(context.Context, string) (credentials.Credential, error) { + return credentials.Credential{}, errors.New("dial tcp: timeout") + } + tokens := NewOAuthTokens("https://api.example", store, "default", filepath.Join(t.TempDir(), "credentials.lock"), store.credentials["default"], refresh) + client, err := NewClientWithTokens("https://api.example", tokens, nil, "frbit/test") + if err != nil { + t.Fatal(err) + } + _, err = client.Apps(context.Background(), 1) + var signIn *SignInError + if err == nil || errors.As(err, &signIn) || !strings.Contains(err.Error(), "dial tcp: timeout") { t.Fatalf("Apps() error = %v", err) } } @@ -226,10 +248,16 @@ func TestStaticTokenIsNotRetriedAfterUnauthorized(t *testing.T) { t.Fatal(err) } + client.SignIn = SignInHint{FromEnv: true} _, err = client.Apps(context.Background(), 1) - if httpErr, ok := err.(*HTTPError); !ok || httpErr.Status != http.StatusUnauthorized || calls != 1 { + var httpErr *HTTPError + var signIn *SignInError + if !errors.As(err, &signIn) || !errors.As(err, &httpErr) || httpErr.Status != http.StatusUnauthorized || calls != 1 { t.Fatalf("Apps() error = %v, calls = %d", err, calls) } + if !strings.Contains(err.Error(), "FRBIT_TOKEN") || !strings.Contains(err.Error(), "frbit auth login") { + t.Fatalf("Apps() error = %v", err) + } } func TestRefreshRefusesACredentialFromAnotherIssuer(t *testing.T) { diff --git a/internal/api/you.go b/internal/api/you.go index cd5bcb0..94f69d3 100644 --- a/internal/api/you.go +++ b/internal/api/you.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "fmt" + "strings" + "unicode" ) type Step struct { @@ -61,3 +63,21 @@ func (c Client) You(ctx context.Context) (YouResponse, error) { } return YouResponse{You: you, Next: next, Raw: body}, nil } + +// Link is the URL of the step when it is an https URL, else "". +func (s OptionalStep) Link() string { + if s.URL == nil || !strings.HasPrefix(*s.URL, "https://") || strings.IndexFunc(*s.URL, unicode.IsControl) >= 0 { + return "" + } + return *s.URL +} + +// OptionalStep returns the optional step named name, or nil when the server lists none. +func (y You) OptionalStep(name string) *OptionalStep { + for index := range y.Optional { + if y.Optional[index].Step == name { + return &y.Optional[index] + } + } + return nil +} diff --git a/internal/api/you_test.go b/internal/api/you_test.go index c799268..00c9a79 100644 --- a/internal/api/you_test.go +++ b/internal/api/you_test.go @@ -42,3 +42,15 @@ func TestYouDecodesBareObjectAndDataEnvelope(t *testing.T) { }) } } + +func TestOptionalStepLinkIsHTTPSOnly(t *testing.T) { + for raw, want := range map[string]string{"https://dash.example/ssh": "https://dash.example/ssh", "http://dash.example/ssh": "", "/ssh": "", "javascript:x": "", "https://dash.example/\x1b]8;;x\x07": ""} { + url := raw + if got := (OptionalStep{URL: &url}).Link(); got != want { + t.Errorf("Link(%q) = %q, want %q", raw, got, want) + } + } + if (OptionalStep{}).Link() != "" { + t.Error("Link without URL") + } +} diff --git a/internal/cmd/auth/login/login.go b/internal/cmd/auth/login/login.go index c1279b8..9b31e4e 100644 --- a/internal/cmd/auth/login/login.go +++ b/internal/cmd/auth/login/login.go @@ -9,12 +9,14 @@ import ( "strings" "time" + "github.com/fortrabbit/frbit-cli/internal/api" "github.com/fortrabbit/frbit-cli/internal/app" "github.com/fortrabbit/frbit-cli/internal/cmdutil" "github.com/fortrabbit/frbit-cli/internal/config" "github.com/fortrabbit/frbit-cli/internal/credentials" "github.com/fortrabbit/frbit-cli/internal/filelock" "github.com/fortrabbit/frbit-cli/internal/oauth" + "github.com/fortrabbit/frbit-cli/internal/sshexec" "github.com/spf13/cobra" ) @@ -182,7 +184,10 @@ func runBrowser(options *Options) error { if _, err := fmt.Fprintf(out, "Signed in as %s. Profile %q is authenticated against %s.\n", you.You.Email, profile, host); err != nil { return err } - return cmdutil.WriteNext(out, you.You.Next) + if err := cmdutil.WriteNext(out, you.You.Next); err != nil { + return err + } + return cmdutil.WriteOpenStep(out, you.You, sshexec.SSHKeyStep, sshexec.SSHKeyInstruction) } // storeCredential takes the refresh lock so a concurrent refresh cannot overwrite the new sign-in. @@ -223,6 +228,9 @@ func runToken(options *Options) error { return err } if err := client.CheckToken(options.Command.Context()); err != nil { + if signIn := (*api.SignInError)(nil); errors.As(err, &signIn) { + return fmt.Errorf("validate token: the API refused it as invalid, expired or revoked: %w", signIn.Err) + } return fmt.Errorf("validate token: %w", err) } if err := options.Factory.CredentialStore.Set(profile, credentials.APIToken(token)); err != nil { diff --git a/internal/cmd/auth/login/login_test.go b/internal/cmd/auth/login/login_test.go index 9075f4f..7b32235 100644 --- a/internal/cmd/auth/login/login_test.go +++ b/internal/cmd/auth/login/login_test.go @@ -58,6 +58,9 @@ type fakeAPI struct { authorize url.Values discoveries int bearerTokens []string + // you replaces the /v1/you body; appsStatus answers /v1/apps with that status. + you string + appsStatus int } func newFakeAPI(t *testing.T) *fakeAPI { @@ -86,9 +89,17 @@ func newFakeAPI(t *testing.T) *fakeAPI { _, _ = writer.Write([]byte(`{"access_token":"frbit-mcp-at-1","token_type":"Bearer","expires_in":3600,"refresh_token":"frbit-mcp-rt-1"}`)) case "/v1/you": fake.bearerTokens = append(fake.bearerTokens, request.Header.Get("Authorization")) + if fake.you != "" { + _, _ = writer.Write([]byte(fake.you)) + return + } _, _ = writer.Write([]byte(`{"publicId":"pe-abc123","email":"ada@example.com","name":"Ada","next":{"step":"connect_git","instruction":"Connect GitHub to deploy from a repository.","url":"https:\/\/dash.example\/git?a=1&b=2"},"optional":[]}`)) case "/v1/apps": fake.bearerTokens = append(fake.bearerTokens, request.Header.Get("Authorization")) + if fake.appsStatus != 0 { + writer.WriteHeader(fake.appsStatus) + return + } _, _ = writer.Write([]byte(`[]`)) default: http.NotFound(writer, request) @@ -261,6 +272,48 @@ func TestLoginTokenStdinKeepsTheTokenPath(t *testing.T) { } } +func TestLoginShowsAnOpenSSHKeyStep(t *testing.T) { + fake := newFakeAPI(t) + factory, _, _ := loginFactory(t, fake) + fake.you = `{"email":"ada@example.com","next":{"step":"connect_git","instruction":"Connect GitHub","url":"https://dash.example/git"},"optional":[{"step":"ssh_key","done":false,"instruction":"Add an SSH key","url":"https://dash.example/ssh"}]}` + + output, err := executeLogin(t, factory, fake.URL) + if err != nil { + t.Fatalf("login error = %v", err) + } + if !strings.Contains(output, "Next: Connect GitHub\n https://dash.example/git\nOptional: Add an SSH key\n https://dash.example/ssh\n") { + t.Fatalf("output = %q", output) + } + + for _, you := range []string{ + `{"email":"ada@example.com","next":null,"optional":[{"step":"ssh_key","done":true,"instruction":"Add an SSH key","url":"https://dash.example/ssh"}]}`, + `{"email":"ada@example.com","next":{"step":"ssh_key","instruction":"Add an SSH key","url":"https://dash.example/ssh"},"optional":[{"step":"ssh_key","done":false,"instruction":"Add an SSH key","url":"https://dash.example/ssh"}]}`, + } { + fake.mu.Lock() + fake.you = you + fake.mu.Unlock() + output, err := executeLogin(t, factory, fake.URL) + if err != nil || strings.Contains(output, "Optional:") { + t.Fatalf("output = %q, %v", output, err) + } + } +} + +func TestLoginTokenStdinNamesARefusedToken(t *testing.T) { + fake := newFakeAPI(t) + factory, store, _ := loginFactory(t, fake) + factory.IOStreams.In = strings.NewReader("frbit-at-revoked\n") + fake.appsStatus = http.StatusUnauthorized + + _, err := executeLogin(t, factory, fake.URL, "--token-stdin") + if err == nil || !strings.HasPrefix(err.Error(), "validate token: the API refused it as invalid, expired or revoked: public API request failed with HTTP 401") { + t.Fatalf("login error = %v", err) + } + if _, ok := store.credentials["default"]; ok { + t.Fatal("a refused token was stored") + } +} + func TestLoginRefusesWhileFRBITTokenIsSet(t *testing.T) { fake := newFakeAPI(t) factory, _, _ := loginFactory(t, fake) diff --git a/internal/cmd/db/pull.go b/internal/cmd/db/pull.go index 470dd8b..59fdccf 100644 --- a/internal/cmd/db/pull.go +++ b/internal/cmd/db/pull.go @@ -73,7 +73,7 @@ The environment is an ID, a label from .fortrabbit/environments.yml, or app/envi } p := puller{id: id, target: target, interactive: factory.IOStreams.IsTTY, stderr: cmd.ErrOrStderr()} if err := cmdutil.WriteFileAtomic(path, 0o600, func(out io.Writer) error { return p.run(ctx, out) }); err != nil { - return err + return sshexec.Explain(ctx, err, client) } _, err = fmt.Fprintf(cmd.ErrOrStderr(), "Saved %s\n", path) return err diff --git a/internal/cmd/db/push.go b/internal/cmd/db/push.go index 96f1344..2e325c3 100644 --- a/internal/cmd/db/push.go +++ b/internal/cmd/db/push.go @@ -96,7 +96,7 @@ The environment is an ID, a label from .fortrabbit/environments.yml, or app/envi interactive: factory.IOStreams.IsTTY, stderr: stderr, } - return p.push(ctx, input) + return sshexec.Explain(ctx, p.push(ctx, input), client) }, } command.Flags().StringVar(&confirmation, "confirm", "", "Confirm by repeating the environment ID") diff --git a/internal/cmd/doctor/doctor.go b/internal/cmd/doctor/doctor.go index 8747255..c9c7cbf 100644 --- a/internal/cmd/doctor/doctor.go +++ b/internal/cmd/doctor/doctor.go @@ -17,6 +17,7 @@ import ( "github.com/fortrabbit/frbit-cli/internal/app" "github.com/fortrabbit/frbit-cli/internal/cmdutil" "github.com/fortrabbit/frbit-cli/internal/credentials" + "github.com/fortrabbit/frbit-cli/internal/iostreams" "github.com/fortrabbit/frbit-cli/internal/link" "github.com/fortrabbit/frbit-cli/internal/sshexec" "github.com/fortrabbit/frbit-cli/internal/update" @@ -49,7 +50,7 @@ type Environment struct { // Probes are the side effects the checks need; tests replace them. type Probes struct { Latest func(ctx context.Context, current string) (string, error) - SignIn func(ctx context.Context) (email string, err error) + SignIn func(ctx context.Context) (api.You, error) LookPath func(name string) (string, error) ToolVersion func(ctx context.Context, name string) string Linked func(ctx context.Context) (labels []string, inCheckout bool, err error) @@ -116,12 +117,12 @@ Exits 1 when a check fails; warnings and skipped checks exit 0. --json prints th // Run runs every check in order; a check that depends on an earlier one is skipped when that one fails. func Run(ctx context.Context, version string, p *Probes) []Check { checks := []Check{versionCheck(ctx, version, p)} - signIn := signInCheck(ctx, p) + signIn, you := signInCheck(ctx, p) checks = append(checks, signIn) checks = append(checks, toolChecks(ctx, p)...) project := projectCheck(ctx, p) checks = append(checks, project) - checks = append(checks, sshCheck(ctx, p, signIn, project)) + checks = append(checks, sshCheck(ctx, p, signIn, project, keyStep(you))) checks = append(checks, agentChecks(ctx, p)...) return checks } @@ -148,26 +149,44 @@ func versionCheck(ctx context.Context, version string, p *Probes) Check { } } -func signInCheck(ctx context.Context, p *Probes) Check { +// signInCheck also returns the account, for the setup steps later checks name as their fix. +func signInCheck(ctx context.Context, p *Probes) (Check, api.You) { ctx, cancel := bounded(ctx) defer cancel() login := p.Login if login == "" { login = "frbit auth login" } - email, err := p.SignIn(ctx) + you, err := p.SignIn(ctx) switch { case errors.Is(err, credentials.ErrNotFound): - return Check{Name: "Sign-in", Status: StatusWarn, Detail: "not signed in", Fix: login} + return Check{Name: "Sign-in", Status: StatusWarn, Detail: "not signed in", Fix: login}, api.You{} case errors.Is(err, ErrRefused): - return Check{Name: "Sign-in", Status: StatusFail, Detail: err.Error(), Fix: login + ", or check FRBIT_TOKEN"} + return Check{Name: "Sign-in", Status: StatusFail, Detail: err.Error(), Fix: login + ", or check FRBIT_TOKEN"}, api.You{} case err != nil: - return Check{Name: "Sign-in", Status: StatusWarn, Detail: "the API did not answer: " + err.Error(), Fix: "check the network and https://status.fortrabbit.com"} + return Check{Name: "Sign-in", Status: StatusWarn, Detail: "the API did not answer: " + err.Error(), Fix: "check the network and https://status.fortrabbit.com"}, api.You{} default: - return Check{Name: "Sign-in", Status: StatusOK, Detail: email} + return Check{Name: "Sign-in", Status: StatusOK, Detail: you.Email}, you } } +// keyStep is the open "add an SSH key" step of the account as a fix, or "" when the account has a key or the API lists no such step. +func keyStep(you api.You) string { + step := you.OptionalStep(sshexec.SSHKeyStep) + if step == nil || step.Done { + return "" + } + instruction := iostreams.StripControl(step.Instruction) + if instruction == "" { + instruction = sshexec.SSHKeyInstruction + } + link := step.Link() + if link == "" { + link = sshexec.KeyURL + } + return instruction + ": " + link +} + func toolChecks(ctx context.Context, p *Probes) []Check { tools := []struct { name, use, missing string @@ -203,7 +222,8 @@ func projectCheck(ctx context.Context, p *Probes) Check { } } -func sshCheck(ctx context.Context, p *Probes, signIn, project Check) Check { +// sshCheck names an open SSH key step of the account as the fix when there is no environment to try; a rejected key carries its own fix. +func sshCheck(ctx context.Context, p *Probes, signIn, project Check, keyFix string) Check { if signIn.Status != StatusOK { return Check{Name: "SSH", Status: StatusSkip, Detail: "needs a sign-in"} } @@ -214,7 +234,11 @@ func sshCheck(ctx context.Context, p *Probes, signIn, project Check) Check { env, err := p.Environment(envCtx) cancel() if errors.Is(err, link.ErrNoEnvironment) { - return Check{Name: "SSH", Status: StatusSkip, Detail: "no environment for this checkout", Fix: "frbit link "} + fix := "frbit link " + if keyFix != "" { + fix = keyFix + "; then " + fix + } + return Check{Name: "SSH", Status: StatusSkip, Detail: "no environment for this checkout", Fix: fix} } if err != nil { return Check{Name: "SSH", Status: StatusFail, Detail: err.Error()} @@ -222,6 +246,9 @@ func sshCheck(ctx context.Context, p *Probes, signIn, project Check) Check { sshCtx, cancelSSH := context.WithTimeout(ctx, sshTimeout) defer cancelSSH() if err := p.SSH(sshCtx, env.Target); err != nil { + if keyErr := (*sshexec.KeyError)(nil); errors.As(err, &keyErr) { + return Check{Name: "SSH", Status: StatusFail, Detail: fmt.Sprintf("%s (%s): %s", env.ID, env.From, keyErr.Reason()), Fix: keyErr.Fix()} + } return Check{Name: "SSH", Status: StatusFail, Detail: fmt.Sprintf("%s (%s): %v", env.ID, env.From, err)} } return Check{Name: "SSH", Status: StatusOK, Detail: fmt.Sprintf("%s (%s) answers", env.ID, env.From)} @@ -335,9 +362,9 @@ func defaultProbes(cmd *cobra.Command, factory *app.Factory) *Probes { } login := "frbit auth login" - for _, flag := range []string{"profile", "host"} { - if f := cmd.Flags().Lookup(flag); f != nil && f.Changed { - login += fmt.Sprintf(" --%s %s", flag, f.Value.String()) + if profile, err := cmdutil.Profile(cmd); err == nil { + if host, err := cmdutil.Host(cmd, factory); err == nil { + login = cmdutil.LoginCommand(host, profile) } } hostWarned := false @@ -351,21 +378,22 @@ func defaultProbes(cmd *cobra.Command, factory *app.Factory) *Probes { return &Probes{ Login: login, Latest: checker.Latest, - SignIn: func(ctx context.Context) (string, error) { + SignIn: func(ctx context.Context) (api.You, error) { warnHost() c, err := client() if err != nil { - return "", err + return api.You{}, err } you, err := c.You(ctx) var httpErr *api.HTTPError - if errors.As(err, &httpErr) && (httpErr.Status == 401 || httpErr.Status == 403) { - return "", fmt.Errorf("%w: %w", ErrRefused, err) + var signIn *api.SignInError + if errors.As(err, &signIn) || (errors.As(err, &httpErr) && httpErr.Status == 403) { + return api.You{}, fmt.Errorf("%w: %w", ErrRefused, err) } if err != nil { - return "", err + return api.You{}, err } - return you.You.Email, nil + return you.You, nil }, LookPath: exec.LookPath, ToolVersion: func(ctx context.Context, name string) string { @@ -423,7 +451,15 @@ func defaultProbes(cmd *cobra.Command, factory *app.Factory) *Probes { return Environment{ID: resolution.ID, From: from, Target: target}, nil }, SSH: func(ctx context.Context, target string) error { - return sshexec.Run(ctx, sshexec.System{}, target, "true", false, nil, io.Discard, io.Discard) + err := sshexec.Run(ctx, sshexec.System{}, target, "true", false, nil, io.Discard, io.Discard) + if err == nil { + return nil + } + c, clientErr := client() + if clientErr != nil { + return sshexec.Explain(ctx, err, nil) + } + return sshexec.Explain(ctx, err, c) }, MCP: func(ctx context.Context) ([]agentmcp.Registration, bool, error) { agents, err := mcp.ResolveAgents(nil) diff --git a/internal/cmd/doctor/doctor_test.go b/internal/cmd/doctor/doctor_test.go index ae470fe..daa8945 100644 --- a/internal/cmd/doctor/doctor_test.go +++ b/internal/cmd/doctor/doctor_test.go @@ -11,16 +11,18 @@ import ( "github.com/fortrabbit/frbit-cli/internal/agentmcp" "github.com/fortrabbit/frbit-cli/internal/agentskills" + "github.com/fortrabbit/frbit-cli/internal/api" "github.com/fortrabbit/frbit-cli/internal/app" "github.com/fortrabbit/frbit-cli/internal/cmdutil" "github.com/fortrabbit/frbit-cli/internal/credentials" "github.com/fortrabbit/frbit-cli/internal/link" + "github.com/fortrabbit/frbit-cli/internal/sshexec" ) func healthy() *Probes { return &Probes{ Latest: func(context.Context, string) (string, error) { return "", nil }, - SignIn: func(context.Context) (string, error) { return "dev@example.com", nil }, + SignIn: func(context.Context) (api.You, error) { return api.You{Email: "dev@example.com"}, nil }, LookPath: func(name string) (string, error) { return "/usr/bin/" + name, nil }, ToolVersion: func(_ context.Context, name string) string { return name + " 1.0" }, Linked: func(context.Context) ([]string, bool, error) { return []string{"main"}, true, nil }, @@ -69,7 +71,7 @@ func TestAnOutdatedVersionWarnsWithTheFix(t *testing.T) { func TestSignedOutWarnsAndSkipsSSH(t *testing.T) { probes := healthy() - probes.SignIn = func(context.Context) (string, error) { return "", credentials.ErrNotFound } + probes.SignIn = func(context.Context) (api.You, error) { return api.You{}, credentials.ErrNotFound } sshRan := false probes.SSH = func(context.Context, string) error { sshRan = true; return nil } checks := Run(context.Background(), "1.15.0", probes) @@ -125,11 +127,11 @@ func TestOutsideACheckoutSkipsProjectButStillTriesSSH(t *testing.T) { func TestARefusedCredentialFailsAndAnUnreachableAPIWarns(t *testing.T) { probes := healthy() probes.Login = "frbit auth login --profile work" - probes.SignIn = func(context.Context) (string, error) { return "", fmt.Errorf("%w: HTTP 401", ErrRefused) } + probes.SignIn = func(context.Context) (api.You, error) { return api.You{}, fmt.Errorf("%w: HTTP 401", ErrRefused) } if check := byName(Run(context.Background(), "1.15.0", probes), "Sign-in"); check.Status != StatusFail || !strings.HasPrefix(check.Fix, "frbit auth login --profile work") { t.Fatalf("refused sign-in check = %+v", check) } - probes.SignIn = func(context.Context) (string, error) { return "", errors.New("dial tcp: timeout") } + probes.SignIn = func(context.Context) (api.You, error) { return api.You{}, errors.New("dial tcp: timeout") } if check := byName(Run(context.Background(), "1.15.0", probes), "Sign-in"); check.Status != StatusWarn { t.Fatalf("unreachable sign-in check = %+v", check) } @@ -144,11 +146,11 @@ func TestProbesGetADeadline(t *testing.T) { } return nil, false, nil } - probes.SignIn = func(ctx context.Context) (string, error) { + probes.SignIn = func(ctx context.Context) (api.You, error) { if _, ok := ctx.Deadline(); ok { deadlines++ } - return "dev@example.com", nil + return api.You{Email: "dev@example.com"}, nil } Run(context.Background(), "1.15.0", probes) if deadlines != 2 { @@ -165,6 +167,48 @@ func TestNoEnvironmentForTheCheckoutSkipsSSHWithTheFix(t *testing.T) { } } +func withoutSSHKey() func(context.Context) (api.You, error) { + url := "https://dash.example/ssh" + return func(context.Context) (api.You, error) { + return api.You{Email: "dev@example.com", Optional: []api.OptionalStep{{Step: sshexec.SSHKeyStep, Instruction: "Add an SSH key", URL: &url}}}, nil + } +} + +func TestAnOpenSSHKeyStepIsTheFixOfTheSSHCheck(t *testing.T) { + probes := healthy() + probes.SignIn = withoutSSHKey() + probes.Environment = func(context.Context) (Environment, error) { return Environment{}, link.ErrNoEnvironment } + if check := byName(Run(context.Background(), "1.15.0", probes), "SSH"); check.Status != StatusSkip || check.Fix != "Add an SSH key: https://dash.example/ssh; then frbit link " { + t.Fatalf("no environment: %+v", check) + } + + probes = healthy() + probes.SignIn = withoutSSHKey() + probes.SSH = func(context.Context, string) error { return errors.New("ssh to x failed") } + // A failure that is not a rejected key gets no key fix: the network may be the cause. + if check := byName(Run(context.Background(), "1.15.0", probes), "SSH"); check.Status != StatusFail || check.Fix != "" { + t.Fatalf("failed connection: %+v", check) + } + + // A passing connection wins over the step, which may lag behind. + probes = healthy() + probes.SignIn = withoutSSHKey() + if check := byName(Run(context.Background(), "1.15.0", probes), "SSH"); check.Status != StatusOK || check.Fix != "" { + t.Fatalf("connected: %+v", check) + } +} + +func TestARejectedKeySplitsReasonAndFix(t *testing.T) { + probes := healthy() + probes.SSH = func(context.Context, string) error { + return &sshexec.KeyError{Target: "en-a1b2c3@ssh.eu-n1a.frbit.app", Account: sshexec.KeyPresent, Local: sshexec.KeyMissing} + } + check := byName(Run(context.Background(), "1.15.0", probes), "SSH") + if check.Status != StatusFail || check.Detail != "en-a1b2c3 (label main): ssh has no key to offer on this machine" || !strings.HasPrefix(check.Fix, "create one with `ssh-keygen -t ed25519`") { + t.Fatalf("ssh check = %+v", check) + } +} + func TestMissingAgentSetupWarns(t *testing.T) { probes := healthy() probes.MCP = func(context.Context) ([]agentmcp.Registration, bool, error) { @@ -255,7 +299,7 @@ func TestCommandPrintsJSONAndExitsNonZeroOnFailure(t *testing.T) { func TestCommandPrintsTheFixUnderAProblem(t *testing.T) { probes := healthy() - probes.SignIn = func(context.Context) (string, error) { return "", credentials.ErrNotFound } + probes.SignIn = func(context.Context) (api.You, error) { return api.You{}, credentials.ErrNotFound } command := NewCmdDoctor(&app.Factory{Version: "1.15.0"}, probes) command.SilenceErrors, command.SilenceUsage = true, true var out bytes.Buffer diff --git a/internal/cmd/files/files.go b/internal/cmd/files/files.go index f11e111..8b3ae43 100644 --- a/internal/cmd/files/files.go +++ b/internal/cmd/files/files.go @@ -292,7 +292,7 @@ func run(cmd *cobra.Command, factory *app.Factory, push bool, args []string, opt return ctx.Err() } if mapped := sshexec.MapOutput(target, err, tail.String()); mapped != err { - return mapped + return sshexec.Explain(ctx, mapped, client) } if code := sshexec.ExitCode(err); err != nil && code > 0 { return fmt.Errorf("rsync failed with exit code %d; see the message above", code) diff --git a/internal/cmd/ssh/ssh.go b/internal/cmd/ssh/ssh.go index 5a00b53..c7430a0 100644 --- a/internal/cmd/ssh/ssh.go +++ b/internal/cmd/ssh/ssh.go @@ -91,7 +91,7 @@ The connection uses your own SSH key and the same SSH settings as frbit db and f code := sshexec.ExitCode(err) // A remote PHP fatal exits 255 as well, so only ssh's own message makes it a connection problem. if code < 0 || (code == 255 && sshFailed(tail.String())) { - return sshexec.MapOutput(target, err, tail.String()) + return sshexec.Explain(cmd.Context(), sshexec.MapOutput(target, err, tail.String()), client) } return &cmdutil.ExitError{Code: code} }, @@ -136,7 +136,7 @@ func arguments(target string, remote []string, terminal bool) ([]string, error) // sshFailed tells ssh's own failure messages from a remote command that exited 255. func sshFailed(stderr string) bool { - for _, marker := range []string{"Permission denied", "Host key verification failed", "Could not resolve hostname", "Connection refused", "Connection timed out", "Connection closed", "ssh: "} { + for _, marker := range []string{"Permission denied", "Too many authentication failures", "Host key verification failed", "Could not resolve hostname", "Connection refused", "Connection timed out", "Connection closed", "Connection reset", "kex_exchange_identification", "ssh: "} { if strings.Contains(stderr, marker) { return true } diff --git a/internal/cmdutil/next.go b/internal/cmdutil/next.go index f94d786..2c3c0b5 100644 --- a/internal/cmdutil/next.go +++ b/internal/cmdutil/next.go @@ -5,6 +5,7 @@ import ( "io" "github.com/fortrabbit/frbit-cli/internal/api" + "github.com/fortrabbit/frbit-cli/internal/iostreams" ) // WriteNext prints the server's hint for the next setup step, if there is one. @@ -12,11 +13,31 @@ func WriteNext(writer io.Writer, next *api.Step) error { if next == nil || next.Instruction == "" { return nil } - if _, err := fmt.Fprintf(writer, "Next: %s\n", next.Instruction); err != nil { + if _, err := fmt.Fprintf(writer, "Next: %s\n", iostreams.StripControl(next.Instruction)); err != nil { return err } if next.URL != nil && *next.URL != "" { - _, err := fmt.Fprintf(writer, " %s\n", *next.URL) + _, err := fmt.Fprintf(writer, " %s\n", iostreams.StripControl(*next.URL)) + return err + } + return nil +} + +// WriteOpenStep prints the optional step named name while it is open and not already the next step; fallback stands in for a missing instruction. +func WriteOpenStep(writer io.Writer, you api.You, name string, fallback string) error { + step := you.OptionalStep(name) + if step == nil || step.Done || (you.Next != nil && you.Next.Step == name) { + return nil + } + instruction := iostreams.StripControl(step.Instruction) + if instruction == "" { + instruction = fallback + } + if _, err := fmt.Fprintf(writer, "Optional: %s\n", instruction); err != nil { + return err + } + if link := step.Link(); link != "" { + _, err := fmt.Fprintf(writer, " %s\n", link) return err } return nil diff --git a/internal/cmdutil/next_test.go b/internal/cmdutil/next_test.go new file mode 100644 index 0000000..95bd423 --- /dev/null +++ b/internal/cmdutil/next_test.go @@ -0,0 +1,23 @@ +package cmdutil + +import ( + "bytes" + "testing" + + "github.com/fortrabbit/frbit-cli/internal/api" +) + +func TestWriteOpenStepFallsBackAndStripsControl(t *testing.T) { + url := "https://dash.example/ssh" + cases := map[string]string{ + "": "Optional: Add an SSH key\n https://dash.example/ssh\n", + "Add a key\x1b[2J": "Optional: Add a key[2J\n https://dash.example/ssh\n", + } + for instruction, want := range cases { + var out bytes.Buffer + you := api.You{Optional: []api.OptionalStep{{Step: "ssh_key", Instruction: instruction, URL: &url}}} + if err := WriteOpenStep(&out, you, "ssh_key", "Add an SSH key"); err != nil || out.String() != want { + t.Errorf("WriteOpenStep(%q) = %q, %v; want %q", instruction, out.String(), err, want) + } + } +} diff --git a/internal/cmdutil/runtime.go b/internal/cmdutil/runtime.go index 84118a0..58e04fa 100644 --- a/internal/cmdutil/runtime.go +++ b/internal/cmdutil/runtime.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "net/url" + "os" "strings" "github.com/fortrabbit/frbit-cli/internal/api" @@ -41,6 +42,38 @@ func Client(factory *app.Factory, host string, token string) (*api.Client, error // CredentialClient builds a client that refreshes an OAuth credential of profile as needed. func CredentialClient(factory *app.Factory, host string, profile string, credential credentials.Credential) (*api.Client, error) { + client, err := credentialClient(factory, host, profile, credential) + if err != nil { + return nil, err + } + client.SignIn = api.SignInHint{ + FromEnv: credential.Kind == credentials.KindAPIToken && strings.TrimSpace(os.Getenv("FRBIT_TOKEN")) == credential.AccessToken, + Login: LoginCommand(host, profile), + } + return client, nil +} + +// LoginCommand is the sign-in command for profile and host, with the flags only when they differ from the defaults. +func LoginCommand(host string, profile string) string { + command := "frbit auth login" + if profile != "" && profile != app.DefaultProfile { + command += " --profile " + shellWord(profile) + } + if !IsDefaultHost(host) { + command += " --host " + shellWord(host) + } + return command +} + +// shellWord single-quotes value unless it is safe to paste into a shell as is. +func shellWord(value string) string { + if value != "" && strings.Trim(value, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@%+=:,./_-") == "" { + return value + } + return "'" + strings.ReplaceAll(value, "'", `'\''`) + "'" +} + +func credentialClient(factory *app.Factory, host string, profile string, credential credentials.Credential) (*api.Client, error) { if credential.Kind != credentials.KindOAuth { return Client(factory, host, credential.AccessToken) } diff --git a/internal/cmdutil/runtime_test.go b/internal/cmdutil/runtime_test.go new file mode 100644 index 0000000..8dff6ac --- /dev/null +++ b/internal/cmdutil/runtime_test.go @@ -0,0 +1,49 @@ +package cmdutil + +import ( + "errors" + "testing" + + "github.com/fortrabbit/frbit-cli/internal/api" + "github.com/fortrabbit/frbit-cli/internal/app" + "github.com/fortrabbit/frbit-cli/internal/credentials" +) + +func TestLoginCommandAddsOnlyNonDefaultFlags(t *testing.T) { + cases := map[[2]string]string{ + {"https://api.fortrabbit.com", "default"}: "frbit auth login", + {"https://api.fortrabbit.com", ""}: "frbit auth login", + {"https://api.fortrabbit.com", "work"}: "frbit auth login --profile work", + {"http://localhost:8080", "default"}: "frbit auth login --host http://localhost:8080", + {"https://api.fortrabbit.com", "my work"}: "frbit auth login --profile 'my work'", + {"https://api.fortrabbit.com", "it's"}: `frbit auth login --profile 'it'\''s'`, + } + for input, want := range cases { + if got := LoginCommand(input[0], input[1]); got != want { + t.Errorf("LoginCommand(%q, %q) = %q, want %q", input[0], input[1], got, want) + } + } +} + +func TestCredentialClientKnowsAnEnvironmentToken(t *testing.T) { + factory := &app.Factory{} + t.Setenv("FRBIT_TOKEN", " frbit-at-env ") + client, err := CredentialClient(factory, "https://api.fortrabbit.com", "work", credentials.APIToken("frbit-at-env")) + if err != nil { + t.Fatal(err) + } + if !client.SignIn.FromEnv || client.SignIn.Login != "frbit auth login --profile work" { + t.Fatalf("SignIn = %+v", client.SignIn) + } + stored, err := CredentialClient(factory, "https://api.fortrabbit.com", "work", credentials.APIToken("frbit-at-stored")) + if err != nil { + t.Fatal(err) + } + if stored.SignIn.FromEnv { + t.Fatal("a stored token counted as FRBIT_TOKEN") + } + signIn := &api.SignInError{Hint: client.SignIn, Err: errors.New("HTTP 401")} + if want := "the API token in FRBIT_TOKEN is invalid, expired or revoked; set a valid token, or unset FRBIT_TOKEN and run `frbit auth login --profile work` (HTTP 401)"; signIn.Error() != want { + t.Fatalf("SignInError = %q", signIn.Error()) + } +} diff --git a/internal/oauth/flow.go b/internal/oauth/flow.go index 040bbaf..7efc340 100644 --- a/internal/oauth/flow.go +++ b/internal/oauth/flow.go @@ -102,6 +102,11 @@ func (e *TokenError) Error() string { return message } +// Refused reports a refresh token the server no longer accepts (invalid_grant) or a 401 from the token endpoint. +func (e *TokenError) Refused() bool { + return e.Code == "invalid_grant" || e.Status == http.StatusUnauthorized +} + type serverMetadata struct { Issuer string `json:"issuer"` AuthorizationEndpoint string `json:"authorization_endpoint"` diff --git a/internal/sshexec/diagnose.go b/internal/sshexec/diagnose.go new file mode 100644 index 0000000..7e87eca --- /dev/null +++ b/internal/sshexec/diagnose.go @@ -0,0 +1,285 @@ +package sshexec + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "time" + + "github.com/fortrabbit/frbit-cli/internal/api" + "github.com/fortrabbit/frbit-cli/internal/iostreams" +) + +// KeyState is what frbit found out about an SSH key. +type KeyState int + +const ( + KeyUnknown KeyState = iota + KeyMissing + KeyPresent +) + +// SSHKeyStep is the optional /v1/you step that is done once the account has an SSH key. +const SSHKeyStep = "ssh_key" + +// SSHKeyInstruction stands in when the API gives the ssh_key step no instruction. +const SSHKeyInstruction = "Add an SSH key" + +// keygen is the command that creates a key the dashboard accepts. +const keygen = "ssh-keygen -t ed25519" + +// KeyError is ssh's "Permission denied": the server took none of the keys ssh offered. +type KeyError struct { + Target string + // TooMany is ssh offering so many keys that the server disconnected before the right one. + TooMany bool + // Account is whether the fortrabbit account has an SSH key, Local whether ssh has one to offer on this machine. + Account KeyState + Local KeyState + // URL is where to add the key; empty means KeyURL. + URL string + Err error +} + +func (e *KeyError) Error() string { + return fmt.Sprintf("ssh to %s failed: %s; %s", e.Target, e.Reason(), e.Fix()) +} + +func (e *KeyError) Unwrap() error { return e.Err } + +// Reason says which key is missing, as far as Explain found out. +func (e *KeyError) Reason() string { + switch { + case e.TooMany: + return "ssh offered too many keys and the server disconnected before the right one" + case e.Account == KeyMissing && e.Local == KeyMissing: + return "your fortrabbit account has no SSH key, and ssh has no key to offer on this machine" + case e.Account == KeyMissing: + return "your fortrabbit account has no SSH key" + case e.Local == KeyMissing: + return "ssh has no key to offer on this machine" + case e.Account == KeyPresent && e.Local == KeyPresent: + return "the server took none of the keys ssh offered: the key on this machine is not on your fortrabbit account, or it has a passphrase and is not in the SSH agent" + } + return "the server rejected the SSH key" +} + +// Fix names the next step: create a key when this machine has none, then add its public key to the account. +func (e *KeyError) Fix() string { + url := e.URL + if url == "" { + url = KeyURL + } + switch { + case e.TooMany: + return "set `IdentitiesOnly yes` and the `IdentityFile` of your fortrabbit key for this host in ~/.ssh/config" + case e.Local == KeyMissing: + return fmt.Sprintf("create one with `%s`, then add the public key (~/.ssh/id_ed25519.pub) at %s", keygen, url) + case e.Account == KeyPresent && e.Local == KeyPresent: + return "load it with `ssh-add`, or add the public key of this machine at " + url + } + return "add the public key of this machine at " + url +} + +// connectionError is ssh losing the connection: DNS, a refused or timed-out connection, a network that dropped before or during the session. +type connectionError struct { + target string + line string + err error +} + +func (e *connectionError) Error() string { + return fmt.Sprintf("ssh to %s failed: the connection to %s failed (%s); check the network, whether a firewall or VPN blocks outgoing SSH, and https://status.fortrabbit.com", e.target, host(e.target), e.line) +} + +func (e *connectionError) Unwrap() error { return e.err } + +// connectionPrefixes start ssh's own lines for a failed or dropped connection; a remote program printing "Connection refused" does not match. +var connectionPrefixes = []string{ + "ssh: ", + "kex_exchange_identification: ", + "Connection closed by ", + "Connection reset by ", + "Connection timed out during banner exchange", +} + +// rejected reports ssh's "Permission denied (publickey…)": the server answered and took none of the offered keys. +func rejected(stderr string) bool { + return strings.Contains(stderr, "Permission denied (publickey") +} + +// tooManyKeys reports the server disconnecting after ssh offered more keys than it allows. +func tooManyKeys(stderr string) bool { + return strings.Contains(stderr, "Too many authentication failures") +} + +// connectionLine returns ssh's first connection failure line in stderr, cleaned for printing. +func connectionLine(stderr string) string { + for _, line := range strings.Split(stderr, "\n") { + line = strings.TrimSpace(iostreams.StripControl(line)) + for _, prefix := range connectionPrefixes { + if strings.HasPrefix(line, prefix) { + return strings.TrimPrefix(line, "ssh: ") + } + } + } + return "" +} + +// Account reads the setup steps of the signed-in account; *api.Client is one. +type Account interface { + You(ctx context.Context) (api.YouResponse, error) +} + +// explainTimeout bounds the extra API call and local probes after a failed connection. +const explainTimeout = 10 * time.Second + +// Explain fills in a KeyError inside err with the account's SSH key step and the keys on this machine, so its message names what is missing. Other errors pass through. +func Explain(ctx context.Context, err error, account Account) error { + var keyErr *KeyError + if !errors.As(err, &keyErr) || ctx.Err() != nil { + return err + } + ctx, cancel := context.WithTimeout(ctx, explainTimeout) + defer cancel() + if account != nil { + keyErr.Account, keyErr.URL = AccountKey(ctx, account) + } + keyErr.Local = LocalKey(ctx, keyErr.Target) + return err +} + +// AccountKey reads the ssh_key step from /v1/you: KeyMissing while it is open, with the URL of the step. +func AccountKey(ctx context.Context, account Account) (KeyState, string) { + you, err := account.You(ctx) + if err != nil { + return KeyUnknown, "" + } + step := you.You.OptionalStep(SSHKeyStep) + switch { + case step == nil: + return KeyUnknown, "" + case step.Done: + return KeyPresent, "" + } + return KeyMissing, step.Link() +} + +// LocalKey reports whether ssh has a key to offer for target; tests replace it. +var LocalKey = localKey + +// localKey asks ssh -G which identity files and agent apply to target: KeyPresent when one file exists or the agent holds a key, KeyMissing when neither, KeyUnknown when ssh's configuration cannot be read with certainty. +func localKey(ctx context.Context, target string) KeyState { + options, err := Options(target, false) + if err != nil { + return KeyUnknown + } + // ssh -G evaluates Match exec of the user's own config again, as the failed ssh just did; it opens no connection. + args := append([]string{"-G"}, options...) + output, err := exec.CommandContext(ctx, "ssh", append(args, "--", target)...).Output() + if err != nil { + return KeyUnknown + } + config := parseConfig(output) + home, _ := os.UserHomeDir() + for _, file := range config.identityFiles { + path, ok := expand(file, home) + if !ok { + return KeyUnknown + } + if _, err := os.Stat(path); err == nil { + return KeyPresent + } + } + // With IdentitiesOnly, agent keys count only when they match a listed file, which this check cannot see. + if config.pkcs11 || config.identitiesOnly { + return KeyUnknown + } + return agentKey(ctx, config.agent, home) +} + +type sshConfig struct { + identityFiles []string + agent string + pkcs11 bool + identitiesOnly bool +} + +// parseConfig reads the keywords of ssh -G output that decide which keys ssh offers. +func parseConfig(output []byte) sshConfig { + var config sshConfig + scanner := bufio.NewScanner(bytes.NewReader(output)) + for scanner.Scan() { + keyword, value, _ := strings.Cut(strings.TrimSpace(scanner.Text()), " ") + value = strings.TrimSpace(value) + switch strings.ToLower(keyword) { + case "identityfile": + config.identityFiles = append(config.identityFiles, value) + case "identitiesonly": + config.identitiesOnly = strings.EqualFold(value, "yes") + case "identityagent": + config.agent = value + case "pkcs11provider": + config.pkcs11 = value != "" && !strings.EqualFold(value, "none") + } + } + return config +} + +// expand resolves ~ in an ssh path; ok is false for %-tokens and other variables ssh would expand on its own. +func expand(path, home string) (string, bool) { + if strings.ContainsAny(path, "%$") { + return "", false + } + if path == "~" || strings.HasPrefix(path, "~/") { + if home == "" { + return "", false + } + return filepath.Join(home, strings.TrimPrefix(path, "~")), true + } + if strings.HasPrefix(path, "~") { + return "", false + } + return path, true +} + +// agentKey asks the agent ssh would use whether it holds a key. +func agentKey(ctx context.Context, agent, home string) KeyState { + socket := os.Getenv("SSH_AUTH_SOCK") + switch { + case strings.EqualFold(agent, "none"): + return KeyMissing + case agent == "" || agent == "SSH_AUTH_SOCK" || agent == "$SSH_AUTH_SOCK": + default: + path, ok := expand(agent, home) + if !ok { + return KeyUnknown + } + socket = path + } + if socket == "" { + // Windows OpenSSH reaches its agent through a named pipe without SSH_AUTH_SOCK. + if runtime.GOOS == "windows" { + return KeyUnknown + } + return KeyMissing + } + command := exec.CommandContext(ctx, "ssh-add", "-L") + command.Env = append(os.Environ(), "SSH_AUTH_SOCK="+socket) + err := command.Run() + switch ExitCode(err) { + case 0: + return KeyPresent + // 1 is an agent without keys; 2, an agent ssh-add cannot reach, may only be locked or stale, so it proves nothing. + case 1: + return KeyMissing + } + return KeyUnknown +} diff --git a/internal/sshexec/diagnose_test.go b/internal/sshexec/diagnose_test.go new file mode 100644 index 0000000..cf4c33e --- /dev/null +++ b/internal/sshexec/diagnose_test.go @@ -0,0 +1,225 @@ +package sshexec + +import ( + "context" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/fortrabbit/frbit-cli/internal/api" +) + +const rejectedStderr = "en-abc123@ssh.eu-w1a.frbit.app: Permission denied (publickey).\r\n" + +type fakeAccount struct { + you api.You + err error +} + +func (f fakeAccount) You(context.Context) (api.YouResponse, error) { + return api.YouResponse{You: f.you}, f.err +} + +func withSSHKeyStep(done bool, url string) api.You { + return api.You{Optional: []api.OptionalStep{{Step: SSHKeyStep, Done: done, Instruction: "Add an SSH key", URL: &url}}} +} + +func useLocalKey(t *testing.T, state KeyState) { + t.Helper() + previous := LocalKey + LocalKey = func(context.Context, string) KeyState { return state } + t.Cleanup(func() { LocalKey = previous }) +} + +func TestMapOutputSplitsKeyAndConnectionFailures(t *testing.T) { + const target = "en-abc123@ssh.eu-w1a.frbit.app" + var keyErr *KeyError + if err := MapOutput(target, exitError(255), rejectedStderr); !errors.As(err, &keyErr) || ExitCode(err) != 255 { + t.Fatalf("rejected key: %v", err) + } + for _, stderr := range []string{ + "ssh: Could not resolve hostname ssh.eu-w1a.frbit.app: nodename nor servname provided\r\n", + "ssh: connect to host ssh.eu-w1a.frbit.app port 22: Connection refused\r\n", + "ssh: connect to host ssh.eu-w1a.frbit.app port 22: Operation timed out\r\n", + "kex_exchange_identification: Connection closed by remote host\r\nConnection closed by 1.2.3.4 port 22\r\n", + } { + err := MapOutput(target, exitError(255), stderr) + if err == nil || !strings.Contains(err.Error(), "the connection to ssh.eu-w1a.frbit.app failed") || strings.Contains(err.Error(), KeyURL) || ExitCode(err) != 255 { + t.Fatalf("%q: %v", stderr, err) + } + } + tooMany := "Received disconnect from 1.2.3.4 port 22:2: Too many authentication failures\r\nDisconnected from 1.2.3.4 port 22\r\n" + if err := MapOutput(target, exitError(255), tooMany); !errors.As(err, &keyErr) || !keyErr.TooMany || !strings.Contains(err.Error(), "IdentitiesOnly yes") { + t.Fatalf("too many keys: %v", err) + } + // A remote PHP fatal exits 255 too; its "Connection refused" is not ssh's. + if err := MapOutput(target, exitError(255), "SQLSTATE[HY000] [2002] Connection refused\n"); errors.As(err, &keyErr) || strings.Contains(err.Error(), "connection to") || !strings.Contains(err.Error(), KeyURL) { + t.Fatalf("remote failure: %v", err) + } + // Only ssh's own exit code makes the words ssh's. + if err := MapOutput(target, exitError(2), rejectedStderr); err.Error() != "exit status" { + t.Fatalf("exit 2: %v", err) + } + if err := MapOutput(target, exitError(255), "ssh: connect to host x port 22: Connection refused\x1b[2J\r\n"); strings.Contains(err.Error(), "\x1b") { + t.Fatalf("control characters kept: %q", err) + } +} + +func TestExplainNamesTheMissingKey(t *testing.T) { + const target = "en-abc123@ssh.eu-w1a.frbit.app" + cases := []struct { + name string + account fakeAccount + local KeyState + want string + }{ + {"neither", fakeAccount{you: withSSHKeyStep(false, "https://dash.example/ssh")}, KeyMissing, + "ssh to " + target + " failed: your fortrabbit account has no SSH key, and ssh has no key to offer on this machine; create one with `ssh-keygen -t ed25519`, then add the public key (~/.ssh/id_ed25519.pub) at https://dash.example/ssh"}, + {"account", fakeAccount{you: withSSHKeyStep(false, "https://dash.example/ssh")}, KeyPresent, + "ssh to " + target + " failed: your fortrabbit account has no SSH key; add the public key of this machine at https://dash.example/ssh"}, + {"machine", fakeAccount{you: withSSHKeyStep(true, "")}, KeyMissing, + "ssh to " + target + " failed: ssh has no key to offer on this machine; create one with `ssh-keygen -t ed25519`, then add the public key (~/.ssh/id_ed25519.pub) at " + KeyURL}, + {"mismatch", fakeAccount{you: withSSHKeyStep(true, "")}, KeyPresent, + "ssh to " + target + " failed: the server took none of the keys ssh offered: the key on this machine is not on your fortrabbit account, or it has a passphrase and is not in the SSH agent; load it with `ssh-add`, or add the public key of this machine at " + KeyURL}, + {"api down", fakeAccount{err: errors.New("dial tcp: timeout")}, KeyUnknown, + "ssh to " + target + " failed: the server rejected the SSH key; add the public key of this machine at " + KeyURL}, + {"no step", fakeAccount{}, KeyPresent, + "ssh to " + target + " failed: the server rejected the SSH key; add the public key of this machine at " + KeyURL}, + {"step url not https", fakeAccount{you: withSSHKeyStep(false, "javascript:x")}, KeyPresent, + "ssh to " + target + " failed: your fortrabbit account has no SSH key; add the public key of this machine at " + KeyURL}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + useLocalKey(t, c.local) + err := Explain(context.Background(), MapOutput(target, exitError(255), rejectedStderr), c.account) + if err == nil || err.Error() != c.want || ExitCode(err) != 255 { + t.Fatalf("Explain:\n got %v\nwant %s", err, c.want) + } + }) + } +} + +func TestExplainLeavesOtherErrorsAlone(t *testing.T) { + called := false + previous := LocalKey + LocalKey = func(context.Context, string) KeyState { called = true; return KeyMissing } + t.Cleanup(func() { LocalKey = previous }) + other := errors.New("other") + if err := Explain(context.Background(), other, fakeAccount{}); err != other || called { + t.Fatalf("Explain = %v, probed = %v", err, called) + } + if err := Explain(context.Background(), nil, fakeAccount{}); err != nil { + t.Fatalf("Explain(nil) = %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + keyErr := &KeyError{Target: "t"} + if Explain(ctx, keyErr, fakeAccount{}); called || keyErr.Local != KeyUnknown { + t.Fatal("probed after cancel") + } +} + +func TestParseConfigAndExpand(t *testing.T) { + config := parseConfig([]byte("user x\nidentityfile ~/.ssh/id_rsa\nidentityfile /keys/work key\nidentityagent /Users/a/Library/Group Containers/agent.sock\npkcs11provider none\n")) + if len(config.identityFiles) != 2 || config.identityFiles[1] != "/keys/work key" || config.agent != "/Users/a/Library/Group Containers/agent.sock" || config.pkcs11 { + t.Fatalf("parseConfig = %+v", config) + } + if got, ok := expand("~/.ssh/id_rsa", "/home/a"); !ok || got != filepath.Join("/home/a", ".ssh/id_rsa") { + t.Fatalf("expand ~ = %q, %v", got, ok) + } + for _, path := range []string{"~/.ssh/%h", "$HOME/.ssh/id", "~other/.ssh/id"} { + if _, ok := expand(path, "/home/a"); ok { + t.Fatalf("expand(%q) claimed to know the path", path) + } + } +} + +// fakeTools puts ssh and ssh-add scripts first on PATH; ssh -G prints config, ssh-add exits with agentExit. +func fakeTools(t *testing.T, config string, agentExit string) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("shell scripts") + } + useKnownHosts(t) + dir := t.TempDir() + write := func(name, body string) { + if err := os.WriteFile(filepath.Join(dir, name), []byte("#!/bin/sh\n"+body), 0o755); err != nil { + t.Fatal(err) + } + } + write("ssh", "/bin/cat <<'EOF'\n"+config+"EOF\n") + write("ssh-add", "exit "+agentExit+"\n") + t.Setenv("PATH", dir) +} + +func TestLocalKeyReadsSSHConfiguration(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("SSH_AUTH_SOCK", "") + const target = "en-abc123@ssh.eu-w1a.frbit.app" + + fakeTools(t, "identityfile ~/.ssh/id_ed25519\n", "0") + if got := localKey(context.Background(), target); got != KeyMissing { + t.Fatalf("no file, no agent = %v", got) + } + + t.Setenv("SSH_AUTH_SOCK", "/tmp/agent") + if got := localKey(context.Background(), target); got != KeyPresent { + t.Fatalf("agent with a key = %v", got) + } + fakeTools(t, "identityfile ~/.ssh/id_ed25519\n", "1") + if got := localKey(context.Background(), target); got != KeyMissing { + t.Fatalf("empty agent = %v", got) + } + fakeTools(t, "identityfile ~/.ssh/id_ed25519\nidentityagent none\n", "0") + if got := localKey(context.Background(), target); got != KeyMissing { + t.Fatalf("IdentityAgent none = %v", got) + } + fakeTools(t, "identityfile ~/.ssh/id_ed25519\n", "2") + if got := localKey(context.Background(), target); got != KeyUnknown { + t.Fatalf("unreachable agent = %v", got) + } + fakeTools(t, "identityfile ~/.ssh/id_ed25519\nidentitiesonly yes\n", "0") + if got := localKey(context.Background(), target); got != KeyUnknown { + t.Fatalf("IdentitiesOnly = %v", got) + } + fakeTools(t, "identityfile ~/.ssh/id_ed25519\n", "127") + if got := localKey(context.Background(), target); got != KeyUnknown { + t.Fatalf("broken ssh-add = %v", got) + } + fakeTools(t, "identityfile ~/.ssh/%h\n", "1") + if got := localKey(context.Background(), target); got != KeyUnknown { + t.Fatalf("token in path = %v", got) + } + fakeTools(t, "identityfile ~/.ssh/id_ed25519\npkcs11provider /usr/lib/opensc.so\n", "1") + if got := localKey(context.Background(), target); got != KeyUnknown { + t.Fatalf("PKCS#11 = %v", got) + } + + if err := os.MkdirAll(filepath.Join(home, ".ssh"), 0o700); err != nil { + t.Fatal(err) + } + // A certificate without its private key offers nothing. + if err := os.WriteFile(filepath.Join(home, ".ssh", "id_ed25519-cert.pub"), []byte("cert"), 0o600); err != nil { + t.Fatal(err) + } + fakeTools(t, "identityfile ~/.ssh/id_ed25519\ncertificatefile ~/.ssh/id_ed25519-cert.pub\n", "1") + if got := localKey(context.Background(), target); got != KeyMissing { + t.Fatalf("certificate only = %v", got) + } + if err := os.WriteFile(filepath.Join(home, ".ssh", "id_ed25519"), []byte("key"), 0o600); err != nil { + t.Fatal(err) + } + fakeTools(t, "identityfile ~/.ssh/id_ed25519\n", "1") + if got := localKey(context.Background(), target); got != KeyPresent { + t.Fatalf("key file = %v", got) + } + + t.Setenv("PATH", t.TempDir()) + if got := localKey(context.Background(), target); got != KeyUnknown { + t.Fatalf("no ssh = %v", got) + } +} diff --git a/internal/sshexec/sshexec.go b/internal/sshexec/sshexec.go index 1c5c25a..7c6c138 100644 --- a/internal/sshexec/sshexec.go +++ b/internal/sshexec/sshexec.go @@ -131,28 +131,36 @@ func Run(ctx context.Context, runner Runner, target, remote string, interactive return MapOutput(target, err, tail.String()) } -// MapOutput turns ssh's own exit code 255 into an error pointing at the SSH key page, and reads what ssh printed to name the fix for a host key it could not verify; other errors pass through. +// MapOutput turns ssh's own exit code 255 into an error that reads what ssh printed: a host key it could not verify, a key the server rejected, or a connection that failed. Other errors pass through. func MapOutput(target string, err error, stderr string) error { // rsync may report a failed ssh with its own exit code, so the ssh message counts on any failure. if err != nil && strings.Contains(stderr, "Host key verification failed") { return &hostKeyError{target: target, pinned: Pinned(target), changed: strings.Contains(stderr, "IDENTIFICATION HAS CHANGED"), err: err} } + // A remote program may print the same words, so the rest needs ssh's own exit code; rsync passes it on. if ExitCode(err) != 255 { return err } - return &keyError{target: target, err: err} + if rejected(stderr) || tooManyKeys(stderr) { + return &KeyError{Target: target, TooMany: tooManyKeys(stderr), Err: err} + } + if line := connectionLine(stderr); line != "" { + return &connectionError{target: target, line: line, err: err} + } + return &unknownError{target: target, err: err} } -type keyError struct { +// unknownError is ssh's exit 255 without a message frbit recognizes. +type unknownError struct { target string err error } -func (e *keyError) Error() string { +func (e *unknownError) Error() string { return fmt.Sprintf("ssh to %s failed: the SSH key was rejected, the connection failed, or the host key is unknown or changed; add your public key at %s, or check the network and ~/.ssh/known_hosts", e.target, KeyURL) } -func (e *keyError) Unwrap() error { return e.err } +func (e *unknownError) Unwrap() error { return e.err } type hostKeyError struct { target string