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
106 changes: 106 additions & 0 deletions internal/auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
160 changes: 159 additions & 1 deletion internal/cli/api_test.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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)
}
}
106 changes: 106 additions & 0 deletions internal/cli/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cli

import (
"path/filepath"
"strings"
"testing"

"github.com/omni-co/omni-cli/internal/config"
Expand Down Expand Up @@ -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)
}
}
Loading
Loading