| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "sync/atomic" |
| 12 | "testing" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | // useTempCredentials points everything the CLI's console resolution reads — |
| 17 | // the credentials file, $HOME, the working directory, CARLOS_CONSOLE — at |
| 18 | // scratch space for the length of one test. Config resolution (config.go) |
| 19 | // consults all four; a developer's real ~/.carlos/config must never change |
| 20 | // a test's answer. The working directory is only scratch space because |
| 21 | // TestMain (main_test.go isolateTempRoot) keeps every t.TempDir() clear of |
| 22 | // a .carlos/config above it: discovery walks up from here. |
| 23 | func useTempCredentials(t *testing.T) string { |
| 24 | t.Helper() |
| 25 | home := t.TempDir() |
| 26 | t.Setenv("HOME", home) |
| 27 | t.Setenv("CARLOS_CONSOLE", "") |
| 28 | t.Chdir(t.TempDir()) |
| 29 | path := filepath.Join(t.TempDir(), "carlos", "credentials") |
| 30 | t.Setenv("CARLOS_CREDENTIALS", path) |
| 31 | return path |
| 32 | } |
| 33 | |
| 34 | func TestCredentialsRoundTripAndPermissions(t *testing.T) { |
| 35 | path := useTempCredentials(t) |
| 36 | |
| 37 | f, err := loadCredentials() |
| 38 | if err != nil { |
| 39 | t.Fatalf("loading a missing credentials file must be empty, not an error: %v", err) |
| 40 | } |
| 41 | if len(f.Credentials) != 0 { |
| 42 | t.Fatalf("fresh file = %v, want empty", f.Credentials) |
| 43 | } |
| 44 | |
| 45 | now := time.Now().UTC().Truncate(time.Second) |
| 46 | f.put(credential{Console: "https://platform.carlosframework.com", Address: "paul@keymail.dev", |
| 47 | Token: "tok-flagship", CreatedAt: now, ExpiresAt: now.Add(time.Hour)}) |
| 48 | f.put(credential{Console: "https://console.example.org", Address: "paul@self.host", |
| 49 | Token: "tok-self", CreatedAt: now, ExpiresAt: now.Add(time.Hour)}) |
| 50 | if err := f.save(); err != nil { |
| 51 | t.Fatal(err) |
| 52 | } |
| 53 | |
| 54 | // A bearer credential on disk is 0600, and the directory it lives in is |
| 55 | // not readable by anyone else either. |
| 56 | fi, err := os.Stat(path) |
| 57 | if err != nil { |
| 58 | t.Fatal(err) |
| 59 | } |
| 60 | if fi.Mode().Perm() != 0o600 { |
| 61 | t.Fatalf("credentials mode = %v, want 0600", fi.Mode().Perm()) |
| 62 | } |
| 63 | di, err := os.Stat(filepath.Dir(path)) |
| 64 | if err != nil { |
| 65 | t.Fatal(err) |
| 66 | } |
| 67 | if di.Mode().Perm()&0o077 != 0 { |
| 68 | t.Fatalf("credentials dir mode = %v, want no group/other bits", di.Mode().Perm()) |
| 69 | } |
| 70 | |
| 71 | back, err := loadCredentials() |
| 72 | if err != nil { |
| 73 | t.Fatal(err) |
| 74 | } |
| 75 | if len(back.Credentials) != 2 { |
| 76 | t.Fatalf("reloaded %d credentials, want 2", len(back.Credentials)) |
| 77 | } |
| 78 | // One entry per console origin: a laptop talks to the flagship AND a |
| 79 | // self-hosted deployment, and re-logging in replaces only the one. |
| 80 | back.put(credential{Console: "https://platform.carlosframework.com/", Address: "paul@keymail.dev", |
| 81 | Token: "tok-flagship-2", CreatedAt: now, ExpiresAt: now.Add(time.Hour)}) |
| 82 | if len(back.Credentials) != 2 { |
| 83 | t.Fatalf("re-login added an entry: %d, want 2", len(back.Credentials)) |
| 84 | } |
| 85 | if c := back.find("https://platform.carlosframework.com"); c == nil || c.Token != "tok-flagship-2" { |
| 86 | t.Fatalf("find after re-login = %+v, want the new token", c) |
| 87 | } |
| 88 | if c := back.find("https://console.example.org"); c == nil || c.Token != "tok-self" { |
| 89 | t.Fatal("re-logging in to one console disturbed another") |
| 90 | } |
| 91 | if !back.remove("https://console.example.org") || len(back.Credentials) != 1 { |
| 92 | t.Fatal("remove did not remove exactly one entry") |
| 93 | } |
| 94 | if back.remove("https://nobody.example") { |
| 95 | t.Fatal("removing an absent console reported success") |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | // With no -console flag the CLI picks the only credential it has, refuses to |
| 100 | // guess between several, and says how to fix it when there are none. |
| 101 | func TestCredentialSelection(t *testing.T) { |
| 102 | useTempCredentials(t) |
| 103 | f, _ := loadCredentials() |
| 104 | if _, err := f.pick(""); err == nil { |
| 105 | t.Fatal("picking from an empty credentials file must fail") |
| 106 | } else if !strings.Contains(err.Error(), "carlos auth login") { |
| 107 | t.Fatalf("empty-file error %q does not name the fix", err) |
| 108 | } |
| 109 | now := time.Now().UTC() |
| 110 | f.put(credential{Console: "https://a.example", Address: "a@keymail.dev", Token: "t1", ExpiresAt: now.Add(time.Hour)}) |
| 111 | c, err := f.pick("") |
| 112 | if err != nil || c.Console != "https://a.example" { |
| 113 | t.Fatalf("pick with one credential = %+v %v", c, err) |
| 114 | } |
| 115 | f.put(credential{Console: "https://b.example", Address: "b@keymail.dev", Token: "t2", ExpiresAt: now.Add(time.Hour)}) |
| 116 | if _, err := f.pick(""); err == nil || !strings.Contains(err.Error(), "-console") { |
| 117 | t.Fatalf("pick with two credentials = %v, want a refusal naming --console", err) |
| 118 | } |
| 119 | if c, err := f.pick("https://b.example/"); err != nil || c.Token != "t2" { |
| 120 | t.Fatalf("explicit pick = %+v %v", c, err) |
| 121 | } |
| 122 | if _, err := f.pick("https://c.example"); err == nil { |
| 123 | t.Fatal("picking a console we have no credential for must fail") |
| 124 | } |
| 125 | // An expired credential is not a credential. |
| 126 | f.put(credential{Console: "https://old.example", Address: "o@keymail.dev", Token: "t3", ExpiresAt: now.Add(-time.Minute)}) |
| 127 | if _, err := f.pick("https://old.example"); err == nil || !strings.Contains(err.Error(), "expired") { |
| 128 | t.Fatalf("expired pick = %v, want an expiry refusal", err) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | func TestNormalizeConsole(t *testing.T) { |
| 133 | for in, want := range map[string]string{ |
| 134 | "https://platform.carlosframework.com/": "https://platform.carlosframework.com", |
| 135 | "https://platform.carlosframework.com": "https://platform.carlosframework.com", |
| 136 | "http://127.0.0.1:8090/": "http://127.0.0.1:8090", |
| 137 | " https://platform.carlosframework.com ": "https://platform.carlosframework.com", |
| 138 | } { |
| 139 | got, err := normalizeConsole(in) |
| 140 | if err != nil || got != want { |
| 141 | t.Errorf("normalizeConsole(%q) = %q %v, want %q", in, got, err, want) |
| 142 | } |
| 143 | } |
| 144 | for _, bad := range []string{"", "platform.carlosframework.com", "ftp://x", "https://"} { |
| 145 | if got, err := normalizeConsole(bad); err == nil { |
| 146 | t.Errorf("normalizeConsole(%q) = %q, want an error", bad, got) |
| 147 | } |
| 148 | } |
| 149 | // http is for a console on this machine and nowhere else: over the network |
| 150 | // it posts a 90-day bearer token in clear text. |
| 151 | for _, bad := range []string{"http://platform.carlosframework.com", "http://192.168.1.4:8090"} { |
| 152 | if got, err := normalizeConsole(bad); err == nil { |
| 153 | t.Errorf("normalizeConsole(%q) = %q, want a refusal — http off-box", bad, got) |
| 154 | } |
| 155 | } |
| 156 | for _, ok := range []string{"http://localhost:8090", "http://127.0.0.1:8090", "http://[::1]:8090"} { |
| 157 | if _, err := normalizeConsole(ok); err != nil { |
| 158 | t.Errorf("normalizeConsole(%q) = %v, want a local console to be allowed", ok, err) |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | // A console can ask a CLI to wait; it cannot talk it into a hot loop or an |
| 164 | // endless one. |
| 165 | func TestPollBoundsAreEnforced(t *testing.T) { |
| 166 | if got := pollWait(0); got < time.Second { |
| 167 | t.Fatalf("pollWait(0) = %v — interval 0 must not mean spin", got) |
| 168 | } |
| 169 | if got := pollWait(-5); got < time.Second { |
| 170 | t.Fatalf("pollWait(-5) = %v, want the floor", got) |
| 171 | } |
| 172 | if got := pollWait(99999); got > 30*time.Second { |
| 173 | t.Fatalf("pollWait(99999) = %v, want the cap", got) |
| 174 | } |
| 175 | now := time.Now() |
| 176 | if got := loginDeadline(now, 99999999); got.After(now.Add(maxLoginWait)) { |
| 177 | t.Fatalf("loginDeadline with an absurd expires_in = %v, want it capped", got.Sub(now)) |
| 178 | } |
| 179 | if got := loginDeadline(now, 0); !got.After(now) { |
| 180 | t.Fatalf("loginDeadline with no expires_in = %v, want a sane default", got.Sub(now)) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | // fakeConsole answers the CLI endpoints the way the real console does, so the |
| 185 | // login loop can be driven end to end without a browser. |
| 186 | type fakeConsole struct { |
| 187 | ts *httptest.Server |
| 188 | polls atomic.Int32 |
| 189 | approved atomic.Bool |
| 190 | denied atomic.Bool |
| 191 | revoked atomic.Bool |
| 192 | noAccounts atomic.Bool // serve 404 on GET /api/cli/apps: a pre-5856dc5 console |
| 193 | lastAuth atomic.Value // string: the bearer the last request carried |
| 194 | label atomic.Value // string |
| 195 | } |
| 196 | |
| 197 | func newFakeConsole(t *testing.T) *fakeConsole { |
| 198 | t.Helper() |
| 199 | fc := &fakeConsole{} |
| 200 | mux := http.NewServeMux() |
| 201 | mux.HandleFunc("POST /auth/cli/start", func(w http.ResponseWriter, r *http.Request) { |
| 202 | if r.Header.Get("Content-Type") != "application/json" { |
| 203 | w.WriteHeader(http.StatusUnsupportedMediaType) |
| 204 | return |
| 205 | } |
| 206 | var req struct{ Label string } |
| 207 | json.NewDecoder(r.Body).Decode(&req) |
| 208 | fc.label.Store(req.Label) |
| 209 | json.NewEncoder(w).Encode(map[string]any{ |
| 210 | "user_code": "WXYZ-4823", "device_code": "device-secret", |
| 211 | "verification_uri": fc.ts.URL + "/auth/cli", |
| 212 | "verification_uri_complete": fc.ts.URL + "/auth/cli?code=WXYZ-4823", |
| 213 | "interval": 0, "expires_in": 600, |
| 214 | }) |
| 215 | }) |
| 216 | mux.HandleFunc("POST /auth/cli/poll", func(w http.ResponseWriter, r *http.Request) { |
| 217 | n := fc.polls.Add(1) |
| 218 | switch { |
| 219 | case fc.denied.Load(): |
| 220 | json.NewEncoder(w).Encode(map[string]any{"status": "denied", "interval": 0}) |
| 221 | case fc.approved.Load() || n >= 2: |
| 222 | json.NewEncoder(w).Encode(map[string]any{ |
| 223 | "status": "approved", "token": "cli-token", "address": "paul@keymail.dev", |
| 224 | "expires_at": time.Now().Add(90 * 24 * time.Hour).UTC().Format(time.RFC3339), |
| 225 | "console": fc.ts.URL, |
| 226 | }) |
| 227 | default: |
| 228 | json.NewEncoder(w).Encode(map[string]any{"status": "pending", "interval": 0}) |
| 229 | } |
| 230 | }) |
| 231 | mux.HandleFunc("GET /auth/cli/whoami", func(w http.ResponseWriter, r *http.Request) { |
| 232 | fc.lastAuth.Store(r.Header.Get("Authorization")) |
| 233 | if r.Header.Get("Authorization") != "Bearer cli-token" || fc.revoked.Load() { |
| 234 | w.WriteHeader(http.StatusUnauthorized) |
| 235 | json.NewEncoder(w).Encode(map[string]string{"error": "not signed in"}) |
| 236 | return |
| 237 | } |
| 238 | json.NewEncoder(w).Encode(map[string]any{ |
| 239 | "address": "paul@keymail.dev", "console": fc.ts.URL, "label": "paul@laptop", |
| 240 | "expires_at": time.Now().Add(90 * 24 * time.Hour).UTC().Format(time.RFC3339), |
| 241 | }) |
| 242 | }) |
| 243 | mux.HandleFunc("GET /api/cli/apps", func(w http.ResponseWriter, r *http.Request) { |
| 244 | if fc.noAccounts.Load() { |
| 245 | http.NotFound(w, r) |
| 246 | return |
| 247 | } |
| 248 | if r.Header.Get("Authorization") != "Bearer cli-token" { |
| 249 | w.WriteHeader(http.StatusUnauthorized) |
| 250 | json.NewEncoder(w).Encode(map[string]string{"error": "not signed in"}) |
| 251 | return |
| 252 | } |
| 253 | json.NewEncoder(w).Encode(map[string]any{"accounts": []map[string]any{ |
| 254 | {"sqid": "bab", "name": "paul@keymail.dev", "role": "owner", "apps": []string{}}, |
| 255 | {"sqid": "bce", "name": "acme", "role": "member", "apps": []string{"shop"}}, |
| 256 | }}) |
| 257 | }) |
| 258 | mux.HandleFunc("POST /auth/cli/revoke", func(w http.ResponseWriter, r *http.Request) { |
| 259 | if r.Header.Get("Authorization") != "Bearer cli-token" { |
| 260 | w.WriteHeader(http.StatusUnauthorized) |
| 261 | return |
| 262 | } |
| 263 | fc.revoked.Store(true) |
| 264 | json.NewEncoder(w).Encode(map[string]any{"revoked": true}) |
| 265 | }) |
| 266 | mux.HandleFunc("POST /auth/cli/accounts", func(w http.ResponseWriter, r *http.Request) { |
| 267 | if r.Header.Get("Authorization") != "Bearer cli-token" { |
| 268 | w.WriteHeader(http.StatusUnauthorized) |
| 269 | json.NewEncoder(w).Encode(map[string]string{"error": "not signed in"}) |
| 270 | return |
| 271 | } |
| 272 | var req struct{ Name string } |
| 273 | json.NewDecoder(r.Body).Decode(&req) |
| 274 | json.NewEncoder(w).Encode(map[string]any{ |
| 275 | "id": 7, "sqid": "bag", "name": req.Name, "owner": "paul@keymail.dev", |
| 276 | "url": fc.ts.URL + "/a/bag/", |
| 277 | }) |
| 278 | }) |
| 279 | fc.ts = httptest.NewServer(mux) |
| 280 | t.Cleanup(fc.ts.Close) |
| 281 | return fc |
| 282 | } |
| 283 | |
| 284 | func TestAuthLoginStoresACredential(t *testing.T) { |
| 285 | useTempCredentials(t) |
| 286 | fc := newFakeConsole(t) |
| 287 | var out bytes.Buffer |
| 288 | |
| 289 | if err := authLogin(&out, []string{"-console", fc.ts.URL, "-label", "paul@laptop"}); err != nil { |
| 290 | t.Fatalf("authLogin: %v\n%s", err, out.String()) |
| 291 | } |
| 292 | // The human is told where to go and what to TYPE — that IS the flow. |
| 293 | for _, want := range []string{fc.ts.URL + "/auth/cli", "type this code", "WXYZ-4823", "paul@keymail.dev"} { |
| 294 | if !strings.Contains(out.String(), want) { |
| 295 | t.Fatalf("login output missing %q:\n%s", want, out.String()) |
| 296 | } |
| 297 | } |
| 298 | // And never the ready-made ?code= link. Printing that would teach people |
| 299 | // that following a link somebody sent them is how this works, which is |
| 300 | // precisely the habit device-code phishing needs. |
| 301 | if strings.Contains(out.String(), "?code=") { |
| 302 | t.Fatalf("login printed a one-click approval link:\n%s", out.String()) |
| 303 | } |
| 304 | if got, _ := fc.label.Load().(string); got != "paul@laptop" { |
| 305 | t.Fatalf("label sent = %q, want paul@laptop", got) |
| 306 | } |
| 307 | f, err := loadCredentials() |
| 308 | if err != nil { |
| 309 | t.Fatal(err) |
| 310 | } |
| 311 | c := f.find(fc.ts.URL) |
| 312 | if c == nil || c.Token != "cli-token" || c.Address != "paul@keymail.dev" { |
| 313 | t.Fatalf("stored credential = %+v", c) |
| 314 | } |
| 315 | // The token is a secret: it must not be printed. |
| 316 | if strings.Contains(out.String(), "cli-token") { |
| 317 | t.Fatalf("login printed the token:\n%s", out.String()) |
| 318 | } |
| 319 | |
| 320 | // whoami asks the console, and says who and where. |
| 321 | out.Reset() |
| 322 | if err := authWhoami(&out, []string{"-console", fc.ts.URL}); err != nil { |
| 323 | t.Fatalf("authWhoami: %v", err) |
| 324 | } |
| 325 | if !strings.Contains(out.String(), "paul@keymail.dev") || !strings.Contains(out.String(), fc.ts.URL) { |
| 326 | t.Fatalf("whoami output:\n%s", out.String()) |
| 327 | } |
| 328 | |
| 329 | // logout revokes console-side and forgets locally. |
| 330 | out.Reset() |
| 331 | if err := authLogout(&out, []string{"-console", fc.ts.URL}); err != nil { |
| 332 | t.Fatalf("authLogout: %v", err) |
| 333 | } |
| 334 | if !fc.revoked.Load() { |
| 335 | t.Fatal("logout did not revoke the token at the console") |
| 336 | } |
| 337 | f, _ = loadCredentials() |
| 338 | if f.find(fc.ts.URL) != nil { |
| 339 | t.Fatal("logout left the credential on disk") |
| 340 | } |
| 341 | if err := authWhoami(&out, []string{"-console", fc.ts.URL}); err == nil { |
| 342 | t.Fatal("whoami after logout must fail") |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | // whoami closes the loop #157 opened: who am I, AND what can I act on. |
| 347 | // Memberships come from GET /api/cli/apps; a console too old to answer |
| 348 | // (bare 404) must not make whoami look broken — identity prints, the |
| 349 | // bonus line is simply absent. |
| 350 | func TestAuthWhoamiPrintsMemberships(t *testing.T) { |
| 351 | useTempCredentials(t) |
| 352 | fc := newFakeConsole(t) |
| 353 | var out bytes.Buffer |
| 354 | if err := authLogin(&out, []string{"-console", fc.ts.URL}); err != nil { |
| 355 | t.Fatalf("authLogin: %v", err) |
| 356 | } |
| 357 | |
| 358 | out.Reset() |
| 359 | if err := authWhoami(&out, []string{"-console", fc.ts.URL}); err != nil { |
| 360 | t.Fatalf("authWhoami: %v", err) |
| 361 | } |
| 362 | if !strings.Contains(out.String(), "accounts: paul@keymail.dev (bab), acme (bce)") { |
| 363 | t.Fatalf("whoami must list memberships:\n%s", out.String()) |
| 364 | } |
| 365 | |
| 366 | // Same command against a console that predates the endpoint: identity |
| 367 | // only, silently — no error, no accounts line. |
| 368 | fc.noAccounts.Store(true) |
| 369 | out.Reset() |
| 370 | if err := authWhoami(&out, []string{"-console", fc.ts.URL}); err != nil { |
| 371 | t.Fatalf("authWhoami against an old console: %v", err) |
| 372 | } |
| 373 | if !strings.Contains(out.String(), "paul@keymail.dev at "+fc.ts.URL) { |
| 374 | t.Fatalf("identity line missing:\n%s", out.String()) |
| 375 | } |
| 376 | if strings.Contains(out.String(), "accounts:") { |
| 377 | t.Fatalf("old console must degrade silently:\n%s", out.String()) |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | func TestAuthLoginDenied(t *testing.T) { |
| 382 | useTempCredentials(t) |
| 383 | fc := newFakeConsole(t) |
| 384 | fc.denied.Store(true) |
| 385 | var out bytes.Buffer |
| 386 | err := authLogin(&out, []string{"-console", fc.ts.URL}) |
| 387 | if err == nil || !strings.Contains(err.Error(), "denied") { |
| 388 | t.Fatalf("denied login = %v, want a refusal", err) |
| 389 | } |
| 390 | f, _ := loadCredentials() |
| 391 | if len(f.Credentials) != 0 { |
| 392 | t.Fatal("a denied login stored a credential") |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | // A credentials file anyone can read is a credential anyone can steal: the |
| 397 | // CLI says so rather than pretending it is fine. |
| 398 | func TestLooseCredentialPermissionsAreReported(t *testing.T) { |
| 399 | path := useTempCredentials(t) |
| 400 | f, _ := loadCredentials() |
| 401 | f.put(credential{Console: "https://a.example", Address: "a@keymail.dev", Token: "t", ExpiresAt: time.Now().Add(time.Hour)}) |
| 402 | if err := f.save(); err != nil { |
| 403 | t.Fatal(err) |
| 404 | } |
| 405 | if err := os.Chmod(path, 0o644); err != nil { |
| 406 | t.Fatal(err) |
| 407 | } |
| 408 | if warn := credentialPermWarning(); warn == "" || !strings.Contains(warn, path) { |
| 409 | t.Fatalf("permission warning = %q, want it to name %s", warn, path) |
| 410 | } |
| 411 | } |
| 412 | |