Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <origin> 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 <origin> auth login`.

| Option | Effect |
|--|--|
Expand Down Expand Up @@ -484,7 +484,7 @@ It runs the local `ssh` with your own SSH key; `mysqldump --single-transaction -

The default output is `<environment>.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 <https://dash.fortrabbit.com/new/ssh-key>. 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.<region>.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.

Expand All @@ -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 <target> 'set -o pipefail; gunzip -c /data/home/frbit-backup-<UTC time>.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 <https://dash.fortrabbit.com/new/ssh-key>.
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 <target> 'set -o pipefail; gunzip -c /data/home/frbit-backup-<UTC time>.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

Expand All @@ -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 <https://dash.fortrabbit.com/new/ssh-key>. |
| `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 <https://status.fortrabbit.com>. |
| `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
Expand All @@ -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 <id>` 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 <https://dash.fortrabbit.com/new/ssh-key>; 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

Expand Down Expand Up @@ -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.
62 changes: 57 additions & 5 deletions internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
32 changes: 30 additions & 2 deletions internal/api/client_refresh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -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)
}
}
Expand All @@ -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) {
Expand Down
20 changes: 20 additions & 0 deletions internal/api/you.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"context"
"encoding/json"
"fmt"
"strings"
"unicode"
)

type Step struct {
Expand Down Expand Up @@ -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
}
12 changes: 12 additions & 0 deletions internal/api/you_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
10 changes: 9 additions & 1 deletion internal/cmd/auth/login/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
53 changes: 53 additions & 0 deletions internal/cmd/auth/login/login_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/db/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading