package main import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "sync/atomic" "testing" "time" ) // useTempCredentials points everything the CLI's console resolution reads — // the credentials file, $HOME, the working directory, CARLOS_CONSOLE — at // scratch space for the length of one test. Config resolution (config.go) // consults all four; a developer's real ~/.carlos/config must never change // a test's answer. The working directory is only scratch space because // TestMain (main_test.go isolateTempRoot) keeps every t.TempDir() clear of // a .carlos/config above it: discovery walks up from here. func useTempCredentials(t *testing.T) string { t.Helper() home := t.TempDir() t.Setenv("HOME", home) t.Setenv("CARLOS_CONSOLE", "") t.Chdir(t.TempDir()) path := filepath.Join(t.TempDir(), "carlos", "credentials") t.Setenv("CARLOS_CREDENTIALS", path) return path } func TestCredentialsRoundTripAndPermissions(t *testing.T) { path := useTempCredentials(t) f, err := loadCredentials() if err != nil { t.Fatalf("loading a missing credentials file must be empty, not an error: %v", err) } if len(f.Credentials) != 0 { t.Fatalf("fresh file = %v, want empty", f.Credentials) } now := time.Now().UTC().Truncate(time.Second) f.put(credential{Console: "https://platform.carlosframework.com", Address: "paul@keymail.dev", Token: "tok-flagship", CreatedAt: now, ExpiresAt: now.Add(time.Hour)}) f.put(credential{Console: "https://console.example.org", Address: "paul@self.host", Token: "tok-self", CreatedAt: now, ExpiresAt: now.Add(time.Hour)}) if err := f.save(); err != nil { t.Fatal(err) } // A bearer credential on disk is 0600, and the directory it lives in is // not readable by anyone else either. fi, err := os.Stat(path) if err != nil { t.Fatal(err) } if fi.Mode().Perm() != 0o600 { t.Fatalf("credentials mode = %v, want 0600", fi.Mode().Perm()) } di, err := os.Stat(filepath.Dir(path)) if err != nil { t.Fatal(err) } if di.Mode().Perm()&0o077 != 0 { t.Fatalf("credentials dir mode = %v, want no group/other bits", di.Mode().Perm()) } back, err := loadCredentials() if err != nil { t.Fatal(err) } if len(back.Credentials) != 2 { t.Fatalf("reloaded %d credentials, want 2", len(back.Credentials)) } // One entry per console origin: a laptop talks to the flagship AND a // self-hosted deployment, and re-logging in replaces only the one. back.put(credential{Console: "https://platform.carlosframework.com/", Address: "paul@keymail.dev", Token: "tok-flagship-2", CreatedAt: now, ExpiresAt: now.Add(time.Hour)}) if len(back.Credentials) != 2 { t.Fatalf("re-login added an entry: %d, want 2", len(back.Credentials)) } if c := back.find("https://platform.carlosframework.com"); c == nil || c.Token != "tok-flagship-2" { t.Fatalf("find after re-login = %+v, want the new token", c) } if c := back.find("https://console.example.org"); c == nil || c.Token != "tok-self" { t.Fatal("re-logging in to one console disturbed another") } if !back.remove("https://console.example.org") || len(back.Credentials) != 1 { t.Fatal("remove did not remove exactly one entry") } if back.remove("https://nobody.example") { t.Fatal("removing an absent console reported success") } } // With no -console flag the CLI picks the only credential it has, refuses to // guess between several, and says how to fix it when there are none. func TestCredentialSelection(t *testing.T) { useTempCredentials(t) f, _ := loadCredentials() if _, err := f.pick(""); err == nil { t.Fatal("picking from an empty credentials file must fail") } else if !strings.Contains(err.Error(), "carlos auth login") { t.Fatalf("empty-file error %q does not name the fix", err) } now := time.Now().UTC() f.put(credential{Console: "https://a.example", Address: "a@keymail.dev", Token: "t1", ExpiresAt: now.Add(time.Hour)}) c, err := f.pick("") if err != nil || c.Console != "https://a.example" { t.Fatalf("pick with one credential = %+v %v", c, err) } f.put(credential{Console: "https://b.example", Address: "b@keymail.dev", Token: "t2", ExpiresAt: now.Add(time.Hour)}) if _, err := f.pick(""); err == nil || !strings.Contains(err.Error(), "-console") { t.Fatalf("pick with two credentials = %v, want a refusal naming --console", err) } if c, err := f.pick("https://b.example/"); err != nil || c.Token != "t2" { t.Fatalf("explicit pick = %+v %v", c, err) } if _, err := f.pick("https://c.example"); err == nil { t.Fatal("picking a console we have no credential for must fail") } // An expired credential is not a credential. f.put(credential{Console: "https://old.example", Address: "o@keymail.dev", Token: "t3", ExpiresAt: now.Add(-time.Minute)}) if _, err := f.pick("https://old.example"); err == nil || !strings.Contains(err.Error(), "expired") { t.Fatalf("expired pick = %v, want an expiry refusal", err) } } func TestNormalizeConsole(t *testing.T) { for in, want := range map[string]string{ "https://platform.carlosframework.com/": "https://platform.carlosframework.com", "https://platform.carlosframework.com": "https://platform.carlosframework.com", "http://127.0.0.1:8090/": "http://127.0.0.1:8090", " https://platform.carlosframework.com ": "https://platform.carlosframework.com", } { got, err := normalizeConsole(in) if err != nil || got != want { t.Errorf("normalizeConsole(%q) = %q %v, want %q", in, got, err, want) } } for _, bad := range []string{"", "platform.carlosframework.com", "ftp://x", "https://"} { if got, err := normalizeConsole(bad); err == nil { t.Errorf("normalizeConsole(%q) = %q, want an error", bad, got) } } // http is for a console on this machine and nowhere else: over the network // it posts a 90-day bearer token in clear text. for _, bad := range []string{"http://platform.carlosframework.com", "http://192.168.1.4:8090"} { if got, err := normalizeConsole(bad); err == nil { t.Errorf("normalizeConsole(%q) = %q, want a refusal — http off-box", bad, got) } } for _, ok := range []string{"http://localhost:8090", "http://127.0.0.1:8090", "http://[::1]:8090"} { if _, err := normalizeConsole(ok); err != nil { t.Errorf("normalizeConsole(%q) = %v, want a local console to be allowed", ok, err) } } } // A console can ask a CLI to wait; it cannot talk it into a hot loop or an // endless one. func TestPollBoundsAreEnforced(t *testing.T) { if got := pollWait(0); got < time.Second { t.Fatalf("pollWait(0) = %v — interval 0 must not mean spin", got) } if got := pollWait(-5); got < time.Second { t.Fatalf("pollWait(-5) = %v, want the floor", got) } if got := pollWait(99999); got > 30*time.Second { t.Fatalf("pollWait(99999) = %v, want the cap", got) } now := time.Now() if got := loginDeadline(now, 99999999); got.After(now.Add(maxLoginWait)) { t.Fatalf("loginDeadline with an absurd expires_in = %v, want it capped", got.Sub(now)) } if got := loginDeadline(now, 0); !got.After(now) { t.Fatalf("loginDeadline with no expires_in = %v, want a sane default", got.Sub(now)) } } // fakeConsole answers the CLI endpoints the way the real console does, so the // login loop can be driven end to end without a browser. type fakeConsole struct { ts *httptest.Server polls atomic.Int32 approved atomic.Bool denied atomic.Bool revoked atomic.Bool noAccounts atomic.Bool // serve 404 on GET /api/cli/apps: a pre-5856dc5 console lastAuth atomic.Value // string: the bearer the last request carried label atomic.Value // string } func newFakeConsole(t *testing.T) *fakeConsole { t.Helper() fc := &fakeConsole{} mux := http.NewServeMux() mux.HandleFunc("POST /auth/cli/start", func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Content-Type") != "application/json" { w.WriteHeader(http.StatusUnsupportedMediaType) return } var req struct{ Label string } json.NewDecoder(r.Body).Decode(&req) fc.label.Store(req.Label) json.NewEncoder(w).Encode(map[string]any{ "user_code": "WXYZ-4823", "device_code": "device-secret", "verification_uri": fc.ts.URL + "/auth/cli", "verification_uri_complete": fc.ts.URL + "/auth/cli?code=WXYZ-4823", "interval": 0, "expires_in": 600, }) }) mux.HandleFunc("POST /auth/cli/poll", func(w http.ResponseWriter, r *http.Request) { n := fc.polls.Add(1) switch { case fc.denied.Load(): json.NewEncoder(w).Encode(map[string]any{"status": "denied", "interval": 0}) case fc.approved.Load() || n >= 2: json.NewEncoder(w).Encode(map[string]any{ "status": "approved", "token": "cli-token", "address": "paul@keymail.dev", "expires_at": time.Now().Add(90 * 24 * time.Hour).UTC().Format(time.RFC3339), "console": fc.ts.URL, }) default: json.NewEncoder(w).Encode(map[string]any{"status": "pending", "interval": 0}) } }) mux.HandleFunc("GET /auth/cli/whoami", func(w http.ResponseWriter, r *http.Request) { fc.lastAuth.Store(r.Header.Get("Authorization")) if r.Header.Get("Authorization") != "Bearer cli-token" || fc.revoked.Load() { w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(map[string]string{"error": "not signed in"}) return } json.NewEncoder(w).Encode(map[string]any{ "address": "paul@keymail.dev", "console": fc.ts.URL, "label": "paul@laptop", "expires_at": time.Now().Add(90 * 24 * time.Hour).UTC().Format(time.RFC3339), }) }) mux.HandleFunc("GET /api/cli/apps", func(w http.ResponseWriter, r *http.Request) { if fc.noAccounts.Load() { http.NotFound(w, r) return } if r.Header.Get("Authorization") != "Bearer cli-token" { w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(map[string]string{"error": "not signed in"}) return } json.NewEncoder(w).Encode(map[string]any{"accounts": []map[string]any{ {"sqid": "bab", "name": "paul@keymail.dev", "role": "owner", "apps": []string{}}, {"sqid": "bce", "name": "acme", "role": "member", "apps": []string{"shop"}}, }}) }) mux.HandleFunc("POST /auth/cli/revoke", func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "Bearer cli-token" { w.WriteHeader(http.StatusUnauthorized) return } fc.revoked.Store(true) json.NewEncoder(w).Encode(map[string]any{"revoked": true}) }) mux.HandleFunc("POST /auth/cli/accounts", func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "Bearer cli-token" { w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(map[string]string{"error": "not signed in"}) return } var req struct{ Name string } json.NewDecoder(r.Body).Decode(&req) json.NewEncoder(w).Encode(map[string]any{ "id": 7, "sqid": "bag", "name": req.Name, "owner": "paul@keymail.dev", "url": fc.ts.URL + "/a/bag/", }) }) fc.ts = httptest.NewServer(mux) t.Cleanup(fc.ts.Close) return fc } func TestAuthLoginStoresACredential(t *testing.T) { useTempCredentials(t) fc := newFakeConsole(t) var out bytes.Buffer if err := authLogin(&out, []string{"-console", fc.ts.URL, "-label", "paul@laptop"}); err != nil { t.Fatalf("authLogin: %v\n%s", err, out.String()) } // The human is told where to go and what to TYPE — that IS the flow. for _, want := range []string{fc.ts.URL + "/auth/cli", "type this code", "WXYZ-4823", "paul@keymail.dev"} { if !strings.Contains(out.String(), want) { t.Fatalf("login output missing %q:\n%s", want, out.String()) } } // And never the ready-made ?code= link. Printing that would teach people // that following a link somebody sent them is how this works, which is // precisely the habit device-code phishing needs. if strings.Contains(out.String(), "?code=") { t.Fatalf("login printed a one-click approval link:\n%s", out.String()) } if got, _ := fc.label.Load().(string); got != "paul@laptop" { t.Fatalf("label sent = %q, want paul@laptop", got) } f, err := loadCredentials() if err != nil { t.Fatal(err) } c := f.find(fc.ts.URL) if c == nil || c.Token != "cli-token" || c.Address != "paul@keymail.dev" { t.Fatalf("stored credential = %+v", c) } // The token is a secret: it must not be printed. if strings.Contains(out.String(), "cli-token") { t.Fatalf("login printed the token:\n%s", out.String()) } // whoami asks the console, and says who and where. out.Reset() if err := authWhoami(&out, []string{"-console", fc.ts.URL}); err != nil { t.Fatalf("authWhoami: %v", err) } if !strings.Contains(out.String(), "paul@keymail.dev") || !strings.Contains(out.String(), fc.ts.URL) { t.Fatalf("whoami output:\n%s", out.String()) } // logout revokes console-side and forgets locally. out.Reset() if err := authLogout(&out, []string{"-console", fc.ts.URL}); err != nil { t.Fatalf("authLogout: %v", err) } if !fc.revoked.Load() { t.Fatal("logout did not revoke the token at the console") } f, _ = loadCredentials() if f.find(fc.ts.URL) != nil { t.Fatal("logout left the credential on disk") } if err := authWhoami(&out, []string{"-console", fc.ts.URL}); err == nil { t.Fatal("whoami after logout must fail") } } // whoami closes the loop #157 opened: who am I, AND what can I act on. // Memberships come from GET /api/cli/apps; a console too old to answer // (bare 404) must not make whoami look broken — identity prints, the // bonus line is simply absent. func TestAuthWhoamiPrintsMemberships(t *testing.T) { useTempCredentials(t) fc := newFakeConsole(t) var out bytes.Buffer if err := authLogin(&out, []string{"-console", fc.ts.URL}); err != nil { t.Fatalf("authLogin: %v", err) } out.Reset() if err := authWhoami(&out, []string{"-console", fc.ts.URL}); err != nil { t.Fatalf("authWhoami: %v", err) } if !strings.Contains(out.String(), "accounts: paul@keymail.dev (bab), acme (bce)") { t.Fatalf("whoami must list memberships:\n%s", out.String()) } // Same command against a console that predates the endpoint: identity // only, silently — no error, no accounts line. fc.noAccounts.Store(true) out.Reset() if err := authWhoami(&out, []string{"-console", fc.ts.URL}); err != nil { t.Fatalf("authWhoami against an old console: %v", err) } if !strings.Contains(out.String(), "paul@keymail.dev at "+fc.ts.URL) { t.Fatalf("identity line missing:\n%s", out.String()) } if strings.Contains(out.String(), "accounts:") { t.Fatalf("old console must degrade silently:\n%s", out.String()) } } func TestAuthLoginDenied(t *testing.T) { useTempCredentials(t) fc := newFakeConsole(t) fc.denied.Store(true) var out bytes.Buffer err := authLogin(&out, []string{"-console", fc.ts.URL}) if err == nil || !strings.Contains(err.Error(), "denied") { t.Fatalf("denied login = %v, want a refusal", err) } f, _ := loadCredentials() if len(f.Credentials) != 0 { t.Fatal("a denied login stored a credential") } } // A credentials file anyone can read is a credential anyone can steal: the // CLI says so rather than pretending it is fine. func TestLooseCredentialPermissionsAreReported(t *testing.T) { path := useTempCredentials(t) f, _ := loadCredentials() f.put(credential{Console: "https://a.example", Address: "a@keymail.dev", Token: "t", ExpiresAt: time.Now().Add(time.Hour)}) if err := f.save(); err != nil { t.Fatal(err) } if err := os.Chmod(path, 0o644); err != nil { t.Fatal(err) } if warn := credentialPermWarning(); warn == "" || !strings.Contains(warn, path) { t.Fatalf("permission warning = %q, want it to name %s", warn, path) } }