diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go index 84b673b..0a35b34 100644 --- a/internal/auth/auth_test.go +++ b/internal/auth/auth_test.go @@ -131,3 +131,109 @@ func TestResolveTokenOverrideSkipsKeychainRead(t *testing.T) { t.Fatalf("expected no keychain reads when token override set, got %d", store.getCalls) } } + +func TestResolveUsesOrgEnvWhenRequired(t *testing.T) { + t.Setenv("OMNI_ORG_KEY", "org-from-env") + t.Setenv("OMNI_PAT", "") + t.Setenv("OMNI_TOKEN", "") + t.Setenv("OMNI_TOKEN_TYPE", "") + t.Setenv("OMNI_URL", "") + t.Setenv("OMNI_PROFILE", "") + + cfg := &config.Config{ + CurrentProfile: "default", + Profiles: map[string]config.Profile{ + "default": {BaseURL: "https://acme.omniapp.co"}, + }, + } + + resolved, err := Resolve(cfg, Options{RequireAuth: "org"}) + if err != nil { + t.Fatalf("Resolve returned error: %v", err) + } + if resolved.Profile.TokenType != "org" { + t.Fatalf("expected org token type, got %q", resolved.Profile.TokenType) + } + if resolved.Profile.Token != "org-from-env" { + t.Fatalf("expected org token from env, got %q", resolved.Profile.Token) + } +} + +func TestResolveMissingURLFails(t *testing.T) { + t.Setenv("OMNI_PAT", "pat-from-env") + t.Setenv("OMNI_TOKEN", "") + t.Setenv("OMNI_URL", "") + + _, err := Resolve(&config.Config{Profiles: map[string]config.Profile{}}, Options{}) + if err == nil || !strings.Contains(err.Error(), "missing Omni URL") { + t.Fatalf("expected missing URL error, got %v", err) + } +} + +func TestResolveMissingRequiredCredentialFails(t *testing.T) { + cfg := &config.Config{ + CurrentProfile: "default", + Profiles: map[string]config.Profile{ + "default": {BaseURL: "https://acme.omniapp.co"}, + }, + } + + _, err := Resolve(cfg, Options{RequireAuth: "org"}) + if err == nil || !strings.Contains(err.Error(), "missing org API key") { + t.Fatalf("expected missing org key error, got %v", err) + } + + _, err = Resolve(cfg, Options{RequireAuth: "pat"}) + if err == nil || !strings.Contains(err.Error(), "missing PAT") { + t.Fatalf("expected missing PAT error, got %v", err) + } +} + +func TestSaveProfileNormalizesAndSetsCurrent(t *testing.T) { + cfg := &config.Config{} + + SaveProfile(cfg, "prod", config.Profile{ + BaseURL: " https://acme.omniapp.co ", + DefaultAuth: "pat", + OrgKey: " org-key ", + }, true) + + profile := cfg.Profiles["prod"] + if profile.BaseURL != "https://acme.omniapp.co" { + t.Fatalf("expected trimmed base URL, got %q", profile.BaseURL) + } + if profile.DefaultAuth != "org" { + t.Fatalf("expected default auth to switch to org, got %q", profile.DefaultAuth) + } + if profile.OrgKey != "org-key" { + t.Fatalf("expected trimmed org key, got %q", profile.OrgKey) + } + if cfg.CurrentProfile != "prod" { + t.Fatalf("expected current profile prod, got %q", cfg.CurrentProfile) + } +} + +func TestUseProfileAndRedactToken(t *testing.T) { + cfg := &config.Config{ + Profiles: map[string]config.Profile{ + "prod": {BaseURL: "https://acme.omniapp.co"}, + }, + } + + if err := UseProfile(cfg, "prod"); err != nil { + t.Fatalf("UseProfile returned error: %v", err) + } + if cfg.CurrentProfile != "prod" { + t.Fatalf("expected current profile prod, got %q", cfg.CurrentProfile) + } + if err := UseProfile(cfg, "missing"); err == nil || !strings.Contains(err.Error(), `profile "missing" not found`) { + t.Fatalf("expected missing profile error, got %v", err) + } + + if got := RedactToken("short"); got != "****" { + t.Fatalf("expected short token redaction, got %q", got) + } + if got := RedactToken("1234567890abcdef"); got != "1234...cdef" { + t.Fatalf("expected long token redaction, got %q", got) + } +} diff --git a/internal/cli/api_test.go b/internal/cli/api_test.go index 2b777de..1d6bb79 100644 --- a/internal/cli/api_test.go +++ b/internal/cli/api_test.go @@ -1,6 +1,17 @@ package cli -import "testing" +import ( + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/omni-co/omni-cli/internal/auth" + "github.com/omni-co/omni-cli/internal/config" +) func TestBuildAPIURL(t *testing.T) { cases := []struct { @@ -35,3 +46,150 @@ func TestHeaderArgsSet(t *testing.T) { t.Fatal("expected invalid header error") } } + +func TestRunAPICallSuccess(t *testing.T) { + var gotMethod string + var gotPath string + var gotAuth string + var gotHeader string + var gotBody string + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotMethod = r.Method + gotPath = r.URL.Path + gotAuth = r.Header.Get("Authorization") + gotHeader = r.Header.Get("X-Test") + bodyBytes := make([]byte, r.ContentLength) + _, _ = r.Body.Read(bodyBytes) + gotBody = string(bodyBytes) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"ok":true}`)) + })) + defer server.Close() + + rt := &runtime{ + JSON: true, + Resolved: &auth.Resolved{ + Profile: config.Profile{ + BaseURL: server.URL, + Token: "pat-token", + }, + }, + } + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runAPICall(rt, []string{ + "--method", "POST", + "--path", "documents", + "--body", `{"name":"Quarterly"}`, + "--header", "X-Test: hello", + }) + }) + + if exit != 0 { + t.Fatalf("expected exit 0, got %d (stderr=%q)", exit, stderr) + } + if !strings.Contains(stdout, `"ok": true`) { + t.Fatalf("expected success payload, got %q", stdout) + } + if strings.TrimSpace(stderr) != "" { + t.Fatalf("expected empty stderr, got %q", stderr) + } + if gotMethod != http.MethodPost { + t.Fatalf("expected POST method, got %q", gotMethod) + } + if gotPath != "/api/v1/documents" { + t.Fatalf("expected /api/v1/documents path, got %q", gotPath) + } + if gotAuth != "Bearer pat-token" { + t.Fatalf("expected bearer auth header, got %q", gotAuth) + } + if gotHeader != "hello" { + t.Fatalf("expected X-Test header, got %q", gotHeader) + } + if gotBody != `{"name":"Quarterly"}` { + t.Fatalf("expected request body to be forwarded, got %q", gotBody) + } +} + +func TestRunAPICallReadsBodyFile(t *testing.T) { + tmp := t.TempDir() + bodyPath := filepath.Join(tmp, "body.json") + if err := os.WriteFile(bodyPath, []byte(`{"from":"file"}`), 0o600); err != nil { + t.Fatalf("write body file: %v", err) + } + + var gotContentType string + var gotBody string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotContentType = r.Header.Get("Content-Type") + bodyBytes, _ := io.ReadAll(r.Body) + gotBody = string(bodyBytes) + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"created":true}`)) + })) + defer server.Close() + + rt := &runtime{ + JSON: true, + Resolved: &auth.Resolved{ + Profile: config.Profile{BaseURL: server.URL, Token: "org-token"}, + }, + } + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runAPICall(rt, []string{"--method", "POST", "--path", "/v1/documents", "--body-file", bodyPath}) + }) + if exit != 0 { + t.Fatalf("expected exit 0, got %d (stderr=%q)", exit, stderr) + } + if !strings.Contains(stdout, `"created": true`) { + t.Fatalf("expected created payload, got %q", stdout) + } + if gotContentType != "application/json" { + t.Fatalf("expected default application/json content type, got %q", gotContentType) + } + if gotBody != `{"from":"file"}` { + t.Fatalf("expected body file payload, got %q", gotBody) + } +} + +func TestRunAPICallUsageErrors(t *testing.T) { + rt := &runtime{JSON: true} + + _, stderr, exit := captureRuntimeIO(t, func() int { + return runAPICall(rt, []string{"--method", "POST", "--path", "/documents", "--body", "{}", "--body-file", "payload.json"}) + }) + if exit != 2 { + t.Fatalf("expected usage exit 2, got %d", exit) + } + if !strings.Contains(stderr, "provide either --body-file or --body") { + t.Fatalf("expected conflict message, got %q", stderr) + } + + _, stderr, exit = captureRuntimeIO(t, func() int { + return runAPICall(rt, []string{"--method", "GET"}) + }) + if exit != 2 { + t.Fatalf("expected usage exit 2 for missing path, got %d", exit) + } + if !strings.Contains(stderr, "--path is required") { + t.Fatalf("expected missing path message, got %q", stderr) + } +} + +func TestRunAPIHelp(t *testing.T) { + rt := &runtime{} + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runAPI(rt, nil) + }) + if exit != 0 { + t.Fatalf("expected exit 0, got %d", exit) + } + if !strings.Contains(stdout, "omni api commands:") { + t.Fatalf("expected API usage output, got %q", stdout) + } + if strings.TrimSpace(stderr) != "" { + t.Fatalf("expected empty stderr, got %q", stderr) + } +} diff --git a/internal/cli/auth_test.go b/internal/cli/auth_test.go index b4c82a0..476e318 100644 --- a/internal/cli/auth_test.go +++ b/internal/cli/auth_test.go @@ -2,6 +2,7 @@ package cli import ( "path/filepath" + "strings" "testing" "github.com/omni-co/omni-cli/internal/config" @@ -56,3 +57,108 @@ func TestRunAuthRemoveDeletesProfileAndKeychainRef(t *testing.T) { t.Fatalf("current profile should move away from removed profile") } } + +func TestRunAuthUseSetsCurrentProfile(t *testing.T) { + tmp := t.TempDir() + rt := &runtime{ + JSON: true, + ConfigPath: filepath.Join(tmp, "config.json"), + Config: &config.Config{ + CurrentProfile: "alpha", + Profiles: map[string]config.Profile{ + "alpha": {BaseURL: "https://alpha.omniapp.co"}, + "beta": {BaseURL: "https://beta.omniapp.co"}, + }, + }, + } + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runAuthUse(rt, []string{"beta"}) + }) + if exit != 0 { + t.Fatalf("expected exit 0, got %d (stderr=%q)", exit, stderr) + } + if rt.Config.CurrentProfile != "beta" { + t.Fatalf("expected current profile beta, got %q", rt.Config.CurrentProfile) + } + if !strings.Contains(stdout, `"current_profile": "beta"`) { + t.Fatalf("expected current profile in output, got %q", stdout) + } +} + +func TestRunAuthShowAndRedactConfiguredToken(t *testing.T) { + rt := &runtime{ + JSON: true, + Config: &config.Config{ + CurrentProfile: "alpha", + Profiles: map[string]config.Profile{ + "alpha": { + BaseURL: "https://alpha.omniapp.co", + DefaultAuth: "org", + PATToken: "1234567890abcdef", + PATStore: "config", + OrgKeyStore: "keychain", + OrgKeyRef: "alpha:org", + }, + }, + }, + } + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runAuthShow(rt, nil) + }) + if exit != 0 { + t.Fatalf("expected exit 0, got %d (stderr=%q)", exit, stderr) + } + if !strings.Contains(stdout, `"pat_token": "1234...cdef"`) { + t.Fatalf("expected PAT redaction in output, got %q", stdout) + } + if !strings.Contains(stdout, `"org_key": "stored-in-keychain"`) { + t.Fatalf("expected keychain marker in output, got %q", stdout) + } + if strings.TrimSpace(stderr) != "" { + t.Fatalf("expected empty stderr, got %q", stderr) + } + + if got := redactConfiguredToken("", "alpha:org"); got != "stored-in-keychain" { + t.Fatalf("expected keychain marker, got %q", got) + } + if got := redactConfiguredToken("1234567890abcdef", ""); got != "1234...cdef" { + t.Fatalf("expected redacted inline token, got %q", got) + } + if got := redactConfiguredToken("", ""); got != "" { + t.Fatalf("expected empty redaction when no credential exists, got %q", got) + } +} + +func TestRunAuthUsageAndMissingProfile(t *testing.T) { + rt := &runtime{ + JSON: true, + Config: &config.Config{ + Profiles: map[string]config.Profile{}, + }, + } + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runAuth(rt, nil) + }) + if exit != 0 { + t.Fatalf("expected exit 0, got %d", exit) + } + if !strings.Contains(stdout, "omni auth commands:") { + t.Fatalf("expected auth usage output, got %q", stdout) + } + if strings.TrimSpace(stderr) != "" { + t.Fatalf("expected empty stderr, got %q", stderr) + } + + _, stderr, exit = captureRuntimeIO(t, func() int { + return runAuthShow(rt, []string{"--profile", "missing"}) + }) + if exit != 1 { + t.Fatalf("expected exit 1 for missing profile, got %d", exit) + } + if !strings.Contains(stderr, codeConfigMissing) { + t.Fatalf("expected config missing error, got %q", stderr) + } +} diff --git a/internal/cli/helpers_test.go b/internal/cli/helpers_test.go new file mode 100644 index 0000000..6560f24 --- /dev/null +++ b/internal/cli/helpers_test.go @@ -0,0 +1,127 @@ +package cli + +import ( + "io" + "net/http" + "os" + "strings" + "testing" +) + +func TestFailFromHTTPStatusReturnsStructuredErrors(t *testing.T) { + tests := []struct { + name string + status int + want string + wantErr string + }{ + {name: "unauthorized", status: http.StatusUnauthorized, want: codeAuthUnauthorized, wantErr: "unauthorized: test context"}, + {name: "forbidden", status: http.StatusForbidden, want: codeAuthForbidden, wantErr: "permission denied: test context"}, + {name: "not found", status: http.StatusNotFound, want: codeAPIError, wantErr: "resource not found: test context"}, + {name: "other", status: http.StatusBadGateway, want: codeAPIError, wantErr: "unexpected API response: test context"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + rt := &runtime{JSON: true} + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return failFromHTTPStatus(rt, tc.status, "test context", []byte(`{"detail":"nope"}`)) + }) + if exit != 1 { + t.Fatalf("expected exit code 1, got %d", exit) + } + if strings.TrimSpace(stdout) != "" { + t.Fatalf("expected empty stdout, got %q", stdout) + } + if !strings.Contains(stderr, tc.want) || !strings.Contains(stderr, tc.wantErr) { + t.Fatalf("expected stderr to contain %q and %q, got %q", tc.want, tc.wantErr, stderr) + } + }) + } +} + +func TestSucceedOrFailPrintsSuccessPayload(t *testing.T) { + rt := &runtime{JSON: true} + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return succeedOrFail(rt, http.StatusOK, "api call", []byte(`{"ok":true}`)) + }) + if exit != 0 { + t.Fatalf("expected exit 0, got %d", exit) + } + if !strings.Contains(stdout, `"ok": true`) { + t.Fatalf("expected JSON body on stdout, got %q", stdout) + } + if strings.TrimSpace(stderr) != "" { + t.Fatalf("expected empty stderr, got %q", stderr) + } +} + +func TestParseRateLimitAndEnvHelpers(t *testing.T) { + headers := http.Header{} + headers.Set("X-RateLimit-Limit", "100") + headers.Set("X-RateLimit-Remaining", "42") + headers.Set("X-RateLimit-Reset", "1700000000") + resp := &http.Response{Header: headers} + rateLimit := parseRateLimit(resp) + if rateLimit["limit"] != 100 || rateLimit["remaining"] != 42 || rateLimit["reset"] != 1700000000 { + t.Fatalf("unexpected rate limit map: %#v", rateLimit) + } + if parseRateLimit(nil) != nil { + t.Fatal("expected nil rate limit map for nil response") + } + + t.Setenv("OMNI_VERBOSE", "yes") + if !parseEnvBool("OMNI_VERBOSE") { + t.Fatal("expected yes to parse as true") + } + t.Setenv("OMNI_VERBOSE", "0") + if parseEnvBool("OMNI_VERBOSE") { + t.Fatal("expected 0 to parse as false") + } +} + +func TestRequiredAuthForCommand(t *testing.T) { + if got := requiredAuthForCommand("admin"); got != "org" { + t.Fatalf("expected org auth for admin, got %q", got) + } + if got := requiredAuthForCommand("documents"); got != "" { + t.Fatalf("expected no forced auth for documents, got %q", got) + } +} + +func captureRuntimeIO(t *testing.T, fn func() int) (stdout, stderr string, exit int) { + t.Helper() + + oldStdout := os.Stdout + oldStderr := os.Stderr + + outR, outW, err := os.Pipe() + if err != nil { + t.Fatalf("create stdout pipe: %v", err) + } + errR, errW, err := os.Pipe() + if err != nil { + t.Fatalf("create stderr pipe: %v", err) + } + + os.Stdout = outW + os.Stderr = errW + + exit = fn() + + _ = outW.Close() + _ = errW.Close() + os.Stdout = oldStdout + os.Stderr = oldStderr + + outBytes, readErr := io.ReadAll(outR) + if readErr != nil { + t.Fatalf("read stdout: %v", readErr) + } + errBytes, readErr := io.ReadAll(errR) + if readErr != nil { + t.Fatalf("read stderr: %v", readErr) + } + + return string(outBytes), string(errBytes), exit +} diff --git a/internal/cli/pat_login_flow_test.go b/internal/cli/pat_login_flow_test.go index 6c9b181..0d8b14f 100644 --- a/internal/cli/pat_login_flow_test.go +++ b/internal/cli/pat_login_flow_test.go @@ -4,6 +4,7 @@ import ( "io" "os" "path/filepath" + "strings" "testing" "github.com/omni-co/omni-cli/internal/config" @@ -71,6 +72,72 @@ func TestRunAuthAddBothUsesBrowserLoginFlowForPAT(t *testing.T) { } } +func TestRunAuthAddOrgOnlyDoesNotTriggerPATLogin(t *testing.T) { + tmp := t.TempDir() + calledPATLogin := false + rt := &runtime{ + ConfigPath: filepath.Join(tmp, "config.json"), + Config: &config.Config{Profiles: map[string]config.Profile{}}, + Keychain: &mockSecretStore{available: false}, + PATLogin: func(baseURL string) (string, error) { + calledPATLogin = true + return "pat-from-browser", nil + }, + } + + exit := captureRuntimeOutput(t, func() int { + return runAuthAdd(rt, []string{ + "--name", "prod", + "--url", "https://acme.omniapp.co", + "--auth-mode", "org", + "--org-key", "org-key-123", + "--token-store", "config", + }) + }) + if exit != 0 { + t.Fatalf("expected exit 0, got %d", exit) + } + if calledPATLogin { + t.Fatal("expected org-only auth add to skip PAT login") + } + + profile := rt.Config.Profiles["prod"] + if profile.OrgKey != "org-key-123" || profile.PATToken != "" { + t.Fatalf("expected only org key stored, got %#v", profile) + } +} + +func TestRunAuthAddPATLoginFailureReturnsAuthError(t *testing.T) { + tmp := t.TempDir() + rt := &runtime{ + JSON: true, + ConfigPath: filepath.Join(tmp, "config.json"), + Config: &config.Config{Profiles: map[string]config.Profile{}}, + Keychain: &mockSecretStore{available: false}, + PATLogin: func(baseURL string) (string, error) { + return "", os.ErrPermission + }, + } + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runAuthAdd(rt, []string{ + "--name", "prod", + "--url", "https://acme.omniapp.co", + "--auth-mode", "pat", + "--token-store", "config", + }) + }) + if exit != 1 { + t.Fatalf("expected exit 1, got %d", exit) + } + if strings.TrimSpace(stdout) != "" { + t.Fatalf("expected empty stdout, got %q", stdout) + } + if !strings.Contains(stderr, codeAuthError) || !strings.Contains(stderr, "PAT browser login failed") { + t.Fatalf("expected auth error output, got %q", stderr) + } +} + func captureRuntimeOutput(t *testing.T, fn func() int) int { t.Helper() diff --git a/internal/cli/pat_login_test.go b/internal/cli/pat_login_test.go new file mode 100644 index 0000000..1601a89 --- /dev/null +++ b/internal/cli/pat_login_test.go @@ -0,0 +1,200 @@ +package cli + +import ( + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" +) + +func TestFetchProtectedResourceMetadataRequiresResource(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, `{"authorization_servers":["https://callbacks.omniapp.co"]}`) + })) + defer server.Close() + + _, err := fetchProtectedResourceMetadata(server.Client(), server.URL) + if err == nil || !strings.Contains(err.Error(), "missing resource") { + t.Fatalf("expected missing resource error, got %v", err) + } +} + +func TestFetchAuthorizationServerMetadataRequiresEndpoints(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, `{"authorization_endpoint":"https://auth.example/authorize"}`) + })) + defer server.Close() + + _, err := fetchAuthorizationServerMetadata(server.Client(), server.URL) + if err == nil || !strings.Contains(err.Error(), "incomplete authorization-server metadata") { + t.Fatalf("expected incomplete metadata error, got %v", err) + } +} + +func TestRegisterOAuthClientRequiresClientID(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Fatalf("expected POST, got %s", r.Method) + } + if got := r.Header.Get("Content-Type"); got != "application/json" { + t.Fatalf("expected JSON content type, got %q", got) + } + _, _ = io.WriteString(w, `{}`) + })) + defer server.Close() + + _, err := registerOAuthClient(server.Client(), server.URL, "http://127.0.0.1:1234/callback") + if err == nil || !strings.Contains(err.Error(), "missing client_id") { + t.Fatalf("expected missing client_id error, got %v", err) + } +} + +func TestBuildAuthorizationURLIncludesPKCEAndResource(t *testing.T) { + rawURL, err := buildAuthorizationURL( + "https://callbacks.omniapp.co/callback/mcp/oauth/authorize", + "https://callbacks.omniapp.co/callback/mcp", + "client-123", + "http://127.0.0.1:9999/callback", + "state-xyz", + "verifier-abc", + ) + if err != nil { + t.Fatalf("buildAuthorizationURL returned error: %v", err) + } + + parsed, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("parse authorization URL: %v", err) + } + query := parsed.Query() + if query.Get("client_id") != "client-123" { + t.Fatalf("expected client_id, got %q", query.Get("client_id")) + } + if query.Get("redirect_uri") != "http://127.0.0.1:9999/callback" { + t.Fatalf("expected redirect_uri, got %q", query.Get("redirect_uri")) + } + if query.Get("resource") != "https://callbacks.omniapp.co/callback/mcp" { + t.Fatalf("expected resource, got %q", query.Get("resource")) + } + if query.Get("code_challenge") != pkceS256("verifier-abc") { + t.Fatalf("expected PKCE code challenge, got %q", query.Get("code_challenge")) + } + if query.Get("code_challenge_method") != "S256" { + t.Fatalf("expected S256 code challenge method, got %q", query.Get("code_challenge_method")) + } +} + +func TestExchangeAuthorizationCodeSuccess(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Fatalf("expected POST, got %s", r.Method) + } + if got := r.Header.Get("Content-Type"); got != "application/x-www-form-urlencoded" { + t.Fatalf("expected form content type, got %q", got) + } + if err := r.ParseForm(); err != nil { + t.Fatalf("parse form: %v", err) + } + if r.Form.Get("grant_type") != "authorization_code" { + t.Fatalf("expected auth code grant, got %q", r.Form.Get("grant_type")) + } + if r.Form.Get("resource") != "https://callbacks.omniapp.co/callback/mcp" { + t.Fatalf("expected resource, got %q", r.Form.Get("resource")) + } + _, _ = io.WriteString(w, `{"access_token":"pat-123","token_type":"Bearer","scope":"mcp:access"}`) + })) + defer server.Close() + + tokenResp, err := exchangeAuthorizationCode( + server.Client(), + server.URL, + "https://callbacks.omniapp.co/callback/mcp", + "client-123", + "http://127.0.0.1:9999/callback", + "auth-code", + "code-verifier", + ) + if err != nil { + t.Fatalf("exchangeAuthorizationCode returned error: %v", err) + } + if tokenResp.AccessToken != "pat-123" || tokenResp.TokenType != "Bearer" { + t.Fatalf("unexpected token response: %#v", tokenResp) + } +} + +func TestExchangeAuthorizationCodeReturnsHTTPError(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "nope", http.StatusBadRequest) + })) + defer server.Close() + + _, err := exchangeAuthorizationCode(server.Client(), server.URL, "", "client-123", "http://127.0.0.1:9999/callback", "auth-code", "code-verifier") + if err == nil || !strings.Contains(err.Error(), "400 Bad Request") { + t.Fatalf("expected token endpoint HTTP error, got %v", err) + } +} + +func TestStartLoopbackListenerAndCallbackServer(t *testing.T) { + redirectURI, listener, err := startLoopbackListener() + if err != nil { + t.Fatalf("startLoopbackListener returned error: %v", err) + } + defer listener.Close() + + callbackCh := make(chan oauthCallbackResult, 1) + serverErrCh := make(chan error, 1) + srv := startOAuthCallbackServer(listener, callbackCh, serverErrCh) + defer srv.Close() + + resp, err := http.Get(redirectURI + "?code=auth-code&state=state-123") + if err != nil { + t.Fatalf("GET callback failed: %v", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read callback response: %v", err) + } + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected 200 response, got %d", resp.StatusCode) + } + if !strings.Contains(string(body), "Omni login complete") { + t.Fatalf("expected success body, got %q", string(body)) + } + + select { + case result := <-callbackCh: + if result.Code != "auth-code" || result.State != "state-123" || result.Err != "" { + t.Fatalf("unexpected callback result: %#v", result) + } + case err := <-serverErrCh: + t.Fatalf("callback server returned error: %v", err) + } +} + +func TestObtainPATValidatesInputsAndTrimsToken(t *testing.T) { + if _, err := obtainPAT(nil, "https://acme.omniapp.co"); err == nil || !strings.Contains(err.Error(), "unavailable") { + t.Fatalf("expected unavailable PAT login error, got %v", err) + } + if _, err := obtainPAT(&runtime{PATLogin: func(baseURL string) (string, error) { return "token", nil }}, " "); err == nil || !strings.Contains(err.Error(), "missing Omni URL") { + t.Fatalf("expected missing URL error, got %v", err) + } + + token, err := obtainPAT(&runtime{ + PATLogin: func(baseURL string) (string, error) { + if baseURL != "https://acme.omniapp.co" { + t.Fatalf("expected base URL to be passed through, got %q", baseURL) + } + return " pat-token ", nil + }, + }, "https://acme.omniapp.co") + if err != nil { + t.Fatalf("obtainPAT returned error: %v", err) + } + if token != "pat-token" { + t.Fatalf("expected trimmed token, got %q", token) + } +} diff --git a/internal/cli/resource_commands_test.go b/internal/cli/resource_commands_test.go new file mode 100644 index 0000000..6aa7821 --- /dev/null +++ b/internal/cli/resource_commands_test.go @@ -0,0 +1,209 @@ +package cli + +import ( + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "github.com/omni-co/omni-cli/internal/auth" + "github.com/omni-co/omni-cli/internal/config" +) + +func TestExecuteDoctorRunsWithoutSubcommandArgs(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/content": + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"records":[]}`)) + case "/api/v1/query/run": + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":"bad request"}`)) + case "/api/scim/v2/Users": + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"Resources":[]}`)) + default: + t.Fatalf("unexpected path %s", r.URL.Path) + } + })) + defer server.Close() + + tmp := t.TempDir() + configPath := filepath.Join(tmp, "config.json") + cfg := &config.Config{ + CurrentProfile: "default", + Profiles: map[string]config.Profile{ + "default": { + BaseURL: server.URL, + DefaultAuth: "org", + OrgKey: "org-token", + OrgKeyStore: "config", + }, + }, + } + if err := config.Save(configPath, cfg); err != nil { + t.Fatalf("save config: %v", err) + } + t.Setenv("OMNI_CONFIG", configPath) + + stdout, stderr, exit := captureExecute(t, []string{"--json", "doctor"}) + if exit != 0 { + t.Fatalf("expected exit 0, got %d (stderr=%q)", exit, stderr) + } + if !strings.Contains(stdout, `"status": "ok"`) { + t.Fatalf("expected doctor JSON output, got %q", stdout) + } + if strings.TrimSpace(stderr) != "" { + t.Fatalf("expected empty stderr, got %q", stderr) + } +} + +func TestRunFoldersCommandsMatchLiveValidatedShapes(t *testing.T) { + const folderID = "550e8400-e29b-41d4-a716-446655440000" + var sawList bool + var sawCreate bool + var sawPerms bool + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/folders": + sawList = true + if r.URL.Query().Get("pageSize") != "20" { + t.Fatalf("expected pageSize query, got %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"records":[],"pageInfo":{"hasNextPage":false,"nextCursor":null,"pageSize":20,"totalRecords":0}}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/folders": + sawCreate = true + if got := r.Header.Get("Authorization"); got != "Bearer org-token" { + t.Fatalf("expected org auth header, got %q", got) + } + body := mustReadAll(t, r) + if !strings.Contains(body, `"name":"Coverage Seed Folder"`) || !strings.Contains(body, `"scope":"organization"`) { + t.Fatalf("unexpected folder create body %q", body) + } + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"id":"` + folderID + `","name":"Coverage Seed Folder","path":"coverage-seed-folder","scope":"organization"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/folders/"+folderID+"/permissions": + sawPerms = true + _, _ = w.Write([]byte(`{"permits":[{"id":"user-1","type":"user","name":"Jamie Fry"}]}`)) + default: + t.Fatalf("unexpected %s %s", r.Method, r.URL.Path) + } + })) + defer server.Close() + + rt := &runtime{ + JSON: true, + Resolved: &auth.Resolved{ + ProfileName: "default", + Profile: config.Profile{ + BaseURL: server.URL, + Token: "org-token", + TokenType: "org", + }, + }, + } + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runFolders(rt, []string{"list", "--page-size", "20"}) + }) + if exit != 0 || !strings.Contains(stdout, `"records": []`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("folders list failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } + + stdout, stderr, exit = captureRuntimeIO(t, func() int { + return runFolders(rt, []string{"create", "--scope", "organization", "Coverage Seed Folder"}) + }) + if exit != 0 || !strings.Contains(stdout, folderID) || strings.TrimSpace(stderr) != "" { + t.Fatalf("folders create failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } + + stdout, stderr, exit = captureRuntimeIO(t, func() int { + return runFolders(rt, []string{"permissions", "get", folderID}) + }) + if exit != 0 || !strings.Contains(stdout, `"permits"`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("folders permissions get failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } + + if !sawList || !sawCreate || !sawPerms { + t.Fatalf("expected all folder endpoints to be exercised, got list=%v create=%v perms=%v", sawList, sawCreate, sawPerms) + } +} + +func TestRunFoldersCreateRequiresFlagsBeforeName(t *testing.T) { + _, stderr, exit := captureRuntimeIO(t, func() int { + return runFolders(&runtime{JSON: true}, []string{"create", "Coverage Seed Folder", "--scope", "organization"}) + }) + if exit != 2 { + t.Fatalf("expected usage exit 2, got %d", exit) + } + if !strings.Contains(stderr, "usage: omni folders create") { + t.Fatalf("expected usage error, got %q", stderr) + } +} + +func TestRunUserAttributesUsersAndSCIMListShapes(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/user-attributes": + _, _ = w.Write([]byte(`{"records":[{"name":"omni_user_email","system":true}]}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/users/email-only": + if r.URL.Query().Get("pageSize") != "20" { + t.Fatalf("expected users pageSize query, got %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"records":[],"pageInfo":{"hasNextPage":false,"nextCursor":null,"pageSize":20,"totalRecords":0}}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/scim/v2/Users": + if r.URL.Query().Get("count") != "20" { + t.Fatalf("expected scim count query, got %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"Resources":[{"id":"user-1","userName":"jamie@hawkfry.com"}],"itemsPerPage":1,"schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"],"startIndex":1,"totalResults":1}`)) + default: + t.Fatalf("unexpected %s %s", r.Method, r.URL.Path) + } + })) + defer server.Close() + + orgRT := &runtime{ + JSON: true, + Resolved: &auth.Resolved{ + ProfileName: "default", + Profile: config.Profile{ + BaseURL: server.URL, + Token: "org-token", + TokenType: "org", + }, + }, + } + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runUserAttributes(orgRT, []string{"list"}) + }) + if exit != 0 || !strings.Contains(stdout, `"omni_user_email"`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("user-attributes list failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } + + stdout, stderr, exit = captureRuntimeIO(t, func() int { + return runUsers(orgRT, []string{"list-email-only", "--page-size", "20"}) + }) + if exit != 0 || !strings.Contains(stdout, `"records": []`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("users list-email-only failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } + + stdout, stderr, exit = captureRuntimeIO(t, func() int { + return runSCIM(orgRT, []string{"users", "list", "--count", "20"}) + }) + if exit != 0 || !strings.Contains(stdout, `"userName": "jamie@hawkfry.com"`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("scim users list failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } +} + +func mustReadAll(t *testing.T, r *http.Request) string { + t.Helper() + body, err := io.ReadAll(r.Body) + if err != nil { + t.Fatalf("read request body: %v", err) + } + return string(body) +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 470bd71..d0810d6 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -142,7 +142,7 @@ func Execute(args []string, version string) int { case "auth": return runAuth(rt, cmdArgs) case "doctor", "query", "jobs", "documents", "models", "connections", "folders", "labels", "schedules", "dashboards", "agentic", "embed", "unstable", "user-attributes", "admin", "users", "scim", "ai", "api": - if len(cmdArgs) == 0 || wantsSubcommandHelp(cmdArgs) { + if (cmd != "doctor" && len(cmdArgs) == 0) || wantsSubcommandHelp(cmdArgs) { printCommandUsage(cmd) return 0 } diff --git a/internal/cli/setup_test.go b/internal/cli/setup_test.go new file mode 100644 index 0000000..13073a4 --- /dev/null +++ b/internal/cli/setup_test.go @@ -0,0 +1,68 @@ +package cli + +import ( + "strings" + "testing" +) + +func TestSetupValidationNoteForBothAuthMode(t *testing.T) { + note := setupValidationNote("both", map[string]validationSummary{ + "pat": { + Query: capabilityCheck{Status: "fail"}, + }, + "org": { + Query: capabilityCheck{Status: "pass"}, + Admin: capabilityCheck{Status: "pass"}, + }, + }) + + if note == "" { + t.Fatal("expected validation note for limited PAT in both mode") + } +} + +func TestSetupValidationNoteSkipsOtherCases(t *testing.T) { + if note := setupValidationNote("pat", map[string]validationSummary{}); note != "" { + t.Fatalf("expected no note outside both mode, got %q", note) + } + if note := setupValidationNote("both", map[string]validationSummary{ + "pat": {Query: capabilityCheck{Status: "pass"}}, + "org": {Query: capabilityCheck{Status: "pass"}, Admin: capabilityCheck{Status: "pass"}}, + }); note != "" { + t.Fatalf("expected no note when PAT validation passed, got %q", note) + } +} + +func TestApplyLegacySetupFlags(t *testing.T) { + authMode, defaultAuth, patToken, orgKey := applyLegacySetupFlags("", "", "", "", " legacy-org ", "org") + if authMode != "org" || defaultAuth != "org" || orgKey != "legacy-org" || patToken != "" { + t.Fatalf("unexpected org legacy mapping: authMode=%q defaultAuth=%q pat=%q org=%q", authMode, defaultAuth, patToken, orgKey) + } + + authMode, defaultAuth, patToken, orgKey = applyLegacySetupFlags("", "", "", "", " legacy-pat ", "pat") + if authMode != "pat" || defaultAuth != "pat" || patToken != "legacy-pat" || orgKey != "" { + t.Fatalf("unexpected PAT legacy mapping: authMode=%q defaultAuth=%q pat=%q org=%q", authMode, defaultAuth, patToken, orgKey) + } +} + +func TestEmitSetupValidationMessagesForBothMode(t *testing.T) { + stdout, stderr, exit := captureRuntimeIO(t, func() int { + emitSetupValidationMessages("both", map[string]validationSummary{ + "pat": {Query: capabilityCheck{Status: "fail", Message: "permission denied"}}, + "org": { + Query: capabilityCheck{Status: "pass", Message: "ok"}, + Admin: capabilityCheck{Status: "pass", Message: "ok"}, + }, + }) + return 0 + }) + if exit != 0 { + t.Fatalf("expected exit 0, got %d", exit) + } + if strings.TrimSpace(stdout) != "" { + t.Fatalf("expected empty stdout, got %q", stdout) + } + if !strings.Contains(stderr, "setup succeeded") { + t.Fatalf("expected user-facing success note, got %q", stderr) + } +} diff --git a/internal/cli/validation_test.go b/internal/cli/validation_test.go new file mode 100644 index 0000000..0517515 --- /dev/null +++ b/internal/cli/validation_test.go @@ -0,0 +1,117 @@ +package cli + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/omni-co/omni-cli/internal/client" +) + +func TestCollectValidationPATLimitedPermissions(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/content": + w.Header().Set("X-RateLimit-Limit", "100") + w.Header().Set("X-RateLimit-Remaining", "75") + w.Header().Set("X-RateLimit-Reset", "1700000000") + http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden) + case "/api/v1/query/run": + if r.Method != http.MethodPost { + t.Fatalf("expected query probe POST, got %s", r.Method) + } + http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden) + default: + t.Fatalf("unexpected path %s", r.URL.Path) + } + })) + defer server.Close() + + api, err := client.New(server.URL, "pat-token") + if err != nil { + t.Fatalf("client.New returned error: %v", err) + } + + summary, failure := collectValidation(context.Background(), api, "pat", false) + if failure != nil { + t.Fatalf("expected no fatal validation failure, got %v", failure) + } + if summary.Base.Status != "warn" || summary.Base.Message == "" { + t.Fatalf("expected base warning, got %#v", summary.Base) + } + if summary.Query.Status != "fail" || summary.Query.Message != "permission denied" { + t.Fatalf("expected query permission failure, got %#v", summary.Query) + } + if summary.Admin.Status != "skipped" { + t.Fatalf("expected admin to be skipped for PAT, got %#v", summary.Admin) + } + if len(summary.Capabilities) != 1 || summary.Capabilities[0] != "base_api" { + t.Fatalf("expected only base_api capability, got %#v", summary.Capabilities) + } + if summary.RateLimit["limit"] != 100 || summary.RateLimit["remaining"] != 75 { + t.Fatalf("expected parsed rate limit headers, got %#v", summary.RateLimit) + } +} + +func TestCollectValidationOrgFullAccess(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/content": + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"records":[]}`)) + case "/api/v1/query/run": + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"error":"bad request"}`)) + case "/api/scim/v2/Users": + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"Resources":[]}`)) + default: + t.Fatalf("unexpected path %s", r.URL.Path) + } + })) + defer server.Close() + + api, err := client.New(server.URL, "org-token") + if err != nil { + t.Fatalf("client.New returned error: %v", err) + } + + summary, failure := collectValidation(context.Background(), api, "org", true) + if failure != nil { + t.Fatalf("expected no validation failure, got %v", failure) + } + if summary.Base.Status != "pass" || summary.Query.Status != "pass" || summary.Admin.Status != "pass" { + t.Fatalf("expected full pass summary, got %#v", summary) + } + if got := strings.Join(summary.Capabilities, ","); got != "base_api,query_api,admin_scim" { + t.Fatalf("unexpected capabilities %q", got) + } +} + +func TestCollectValidationUnauthorizedFailsFast(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/v1/content" { + t.Fatalf("expected only base probe before failure, got %s", r.URL.Path) + } + http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized) + })) + defer server.Close() + + api, err := client.New(server.URL, "bad-token") + if err != nil { + t.Fatalf("client.New returned error: %v", err) + } + + summary, failure := collectValidation(context.Background(), api, "pat", false) + if failure == nil { + t.Fatal("expected validation failure for unauthorized token") + } + if failure.Code != codeAuthUnauthorized { + t.Fatalf("expected auth unauthorized failure code, got %#v", failure) + } + if summary.Base.Status != "fail" || summary.Base.Message != "unauthorized" { + t.Fatalf("expected unauthorized base summary, got %#v", summary.Base) + } +} diff --git a/internal/client/client_test.go b/internal/client/client_test.go new file mode 100644 index 0000000..03f70b7 --- /dev/null +++ b/internal/client/client_test.go @@ -0,0 +1,39 @@ +package client + +import "testing" + +func TestNormalizeBaseURL(t *testing.T) { + tests := []struct { + name string + in string + want string + }{ + {name: "trim whitespace", in: " https://acme.omniapp.co/ ", want: "https://acme.omniapp.co"}, + {name: "strip api", in: "https://acme.omniapp.co/api", want: "https://acme.omniapp.co"}, + {name: "strip api v1", in: "https://acme.omniapp.co/api/v1/", want: "https://acme.omniapp.co"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := normalizeBaseURL(tc.in); got != tc.want { + t.Fatalf("normalizeBaseURL(%q) = %q, want %q", tc.in, got, tc.want) + } + }) + } +} + +func TestParseBody(t *testing.T) { + if got := ParseBody(nil).(map[string]any); len(got) != 0 { + t.Fatalf("expected empty map for empty body, got %#v", got) + } + + parsed := ParseBody([]byte(`{"ok":true}`)).(map[string]any) + if parsed["ok"] != true { + t.Fatalf("expected parsed JSON body, got %#v", parsed) + } + + raw := ParseBody([]byte(`not-json`)).(map[string]any) + if raw["raw"] != "not-json" { + t.Fatalf("expected raw body wrapper, got %#v", raw) + } +} diff --git a/internal/client/retry_test.go b/internal/client/retry_test.go index 2e640ae..0ba142d 100644 --- a/internal/client/retry_test.go +++ b/internal/client/retry_test.go @@ -1,10 +1,12 @@ package client import ( + "context" "io" "net/http" "strings" "testing" + "time" ) type roundTripFunc func(*http.Request) (*http.Response, error) @@ -78,3 +80,35 @@ func TestParseRetryAfterSeconds(t *testing.T) { t.Fatalf("expected around 2s, got %v", d) } } + +func TestRetryHelpers(t *testing.T) { + if _, ok := newRetryTransport(nil).(*retryTransport); !ok { + t.Fatal("expected newRetryTransport to return retryTransport") + } + if !isRetryableError(io.EOF) { + t.Fatal("expected non-nil error to be retryable") + } + if isRetryableError(nil) { + t.Fatal("expected nil error to be non-retryable") + } + + future := time.Now().Add(1500 * time.Millisecond).UTC().Format(http.TimeFormat) + if d := parseRetryAfter(future); d <= 0 { + t.Fatalf("expected positive duration for HTTP date, got %v", d) + } + if d := parseRetryAfter("garbage"); d != 0 { + t.Fatalf("expected zero duration for invalid retry-after, got %v", d) + } +} + +func TestSleepBackoffReturnsOnCanceledContext(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com", nil) + + start := time.Now() + sleepBackoff(3, time.Second, req) + if elapsed := time.Since(start); elapsed > 50*time.Millisecond { + t.Fatalf("expected canceled backoff to return quickly, took %v", elapsed) + } +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..279005a --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,149 @@ +package config + +import ( + "os" + "path/filepath" + "reflect" + "testing" +) + +func TestLoadMissingFileReturnsEmptyConfig(t *testing.T) { + cfg, err := Load(filepath.Join(t.TempDir(), "missing.json")) + if err != nil { + t.Fatalf("Load returned error: %v", err) + } + if cfg.CurrentProfile != "" { + t.Fatalf("expected empty current profile, got %q", cfg.CurrentProfile) + } + if cfg.Profiles == nil || len(cfg.Profiles) != 0 { + t.Fatalf("expected empty profiles map, got %#v", cfg.Profiles) + } +} + +func TestSaveAndLoadNormalizesProfiles(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + input := &Config{ + CurrentProfile: "prod", + Profiles: map[string]Profile{ + "prod": { + BaseURL: " https://acme.omniapp.co/ ", + DefaultAuth: "PAT", + PATToken: " pat-token ", + OrgKeyRef: " org-ref ", + }, + }, + } + + if err := Save(path, input); err != nil { + t.Fatalf("Save returned error: %v", err) + } + + cfg, err := Load(path) + if err != nil { + t.Fatalf("Load returned error: %v", err) + } + + profile := cfg.Profiles["prod"] + if profile.BaseURL != "https://acme.omniapp.co/" { + t.Fatalf("expected trimmed base URL, got %q", profile.BaseURL) + } + if profile.DefaultAuth != "pat" { + t.Fatalf("expected normalized default auth, got %q", profile.DefaultAuth) + } + if profile.PATStore != "config" { + t.Fatalf("expected config PAT store, got %q", profile.PATStore) + } + if profile.PATToken != "pat-token" { + t.Fatalf("expected trimmed PAT token, got %q", profile.PATToken) + } + if profile.OrgKeyStore != "keychain" { + t.Fatalf("expected keychain org store, got %q", profile.OrgKeyStore) + } + if profile.OrgKeyRef != "org-ref" { + t.Fatalf("expected trimmed org ref, got %q", profile.OrgKeyRef) + } +} + +func TestNormalizeProfileMigratesLegacyOrgToken(t *testing.T) { + profile := normalizeProfile(Profile{ + BaseURL: " https://acme.omniapp.co ", + Token: " legacy-org ", + TokenType: " org ", + }) + + if profile.BaseURL != "https://acme.omniapp.co" { + t.Fatalf("expected trimmed base URL, got %q", profile.BaseURL) + } + if profile.OrgKey != "legacy-org" { + t.Fatalf("expected legacy org token to migrate, got %q", profile.OrgKey) + } + if profile.OrgKeyStore != "config" { + t.Fatalf("expected legacy org token to default to config store, got %q", profile.OrgKeyStore) + } + if profile.DefaultAuth != "org" { + t.Fatalf("expected default auth org, got %q", profile.DefaultAuth) + } + if profile.Token != "" || profile.TokenType != "" || profile.TokenStore != "" || profile.TokenRef != "" { + t.Fatalf("expected legacy fields cleared, got %#v", profile) + } +} + +func TestNormalizeProfileAdjustsDefaultAuthToAvailableCredential(t *testing.T) { + profile := normalizeProfile(Profile{ + DefaultAuth: "pat", + OrgKeyRef: "org-ref", + OrgKeyStore: "keychain", + }) + + if profile.DefaultAuth != "org" { + t.Fatalf("expected default auth to switch to org, got %q", profile.DefaultAuth) + } +} + +func TestProfileHelpers(t *testing.T) { + profile := Profile{ + PATToken: "pat-token", + OrgKeyRef: "org-ref", + } + + if !profile.HasPAT() { + t.Fatal("expected PAT to be configured") + } + if !profile.HasOrg() { + t.Fatal("expected org key to be configured") + } + if profile.AuthMode() != "both" { + t.Fatalf("expected auth mode both, got %q", profile.AuthMode()) + } + if got, want := profile.ConfiguredAuths(), []string{"pat", "org"}; !reflect.DeepEqual(got, want) { + t.Fatalf("expected configured auths %v, got %v", want, got) + } +} + +func TestDefaultStoreForCredential(t *testing.T) { + if got := defaultStoreForCredential("", "ref"); got != "keychain" { + t.Fatalf("expected keychain store for ref, got %q", got) + } + if got := defaultStoreForCredential("token", ""); got != "config" { + t.Fatalf("expected config store for token, got %q", got) + } + if got := defaultStoreForCredential("", ""); got != "" { + t.Fatalf("expected empty store when no credential is present, got %q", got) + } +} + +func TestDefaultPath(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + + path, err := DefaultPath() + if err != nil { + t.Fatalf("DefaultPath returned error: %v", err) + } + if path != filepath.Join(home, ".omni", "config.json") { + t.Fatalf("unexpected default path %q", path) + } + if _, err := os.Stat(filepath.Dir(path)); !os.IsNotExist(err) && err != nil { + t.Fatalf("unexpected stat error: %v", err) + } +} diff --git a/internal/secret/store_test.go b/internal/secret/store_test.go index dabb1d0..bba79c9 100644 --- a/internal/secret/store_test.go +++ b/internal/secret/store_test.go @@ -1,6 +1,9 @@ package secret -import "testing" +import ( + "strings" + "testing" +) type fakeStore struct{ available bool } @@ -36,3 +39,44 @@ func TestPickExplicitKeychainUnavailableErrors(t *testing.T) { t.Fatal("expected error, got nil") } } + +func TestConfigStoreOperations(t *testing.T) { + store := NewConfigStore() + if !store.Available() { + t.Fatal("expected config store to be available") + } + if store.Name() != "config" { + t.Fatalf("expected config store name, got %q", store.Name()) + } + if _, err := store.Save("default", ""); err == nil { + t.Fatal("expected empty token save to fail") + } + ref, err := store.Save("default", "token") + if err != nil { + t.Fatalf("Save returned error: %v", err) + } + if ref != "" { + t.Fatalf("expected config store save to return empty ref, got %q", ref) + } + if err := store.Delete("ignored"); err != nil { + t.Fatalf("Delete returned error: %v", err) + } + if _, err := store.Get("ignored"); err == nil || !strings.Contains(err.Error(), "does not support token references") { + t.Fatalf("expected unsupported get error, got %v", err) + } +} + +func TestPickConfigAndInvalidPreference(t *testing.T) { + picked, err := Pick("config", fakeStore{available: true}) + if err != nil { + t.Fatalf("Pick returned error: %v", err) + } + if picked.Name() != "config" { + t.Fatalf("expected config store, got %q", picked.Name()) + } + + _, err = Pick("bogus", fakeStore{available: true}) + if err == nil || !strings.Contains(err.Error(), "invalid token store") { + t.Fatalf("expected invalid token store error, got %v", err) + } +}