From 0bf18b5f736b9965a2bb41eb95dab5567e7cec2b Mon Sep 17 00:00:00 2001 From: hawkfry Date: Sun, 15 Mar 2026 21:21:11 +0000 Subject: [PATCH 1/2] feat: add browser-based PAT auth setup --- README.md | 31 ++- docs/pat-auth-flow.md | 105 ++++++++ internal/auth/auth.go | 209 +++++++++++---- internal/cli/auth.go | 136 ++++++---- internal/cli/auth_contract_test.go | 56 ++-- internal/cli/auth_test.go | 14 +- internal/cli/completion.go | 2 +- internal/cli/pat_login.go | 391 ++++++++++++++++++++++++++++ internal/cli/pat_login_flow_test.go | 103 ++++++++ internal/cli/profile_save.go | 82 ++++-- internal/cli/profile_save_test.go | 67 +++-- internal/cli/root.go | 32 ++- internal/cli/schema.go | 3 +- internal/cli/setup.go | 247 ++++++++++++++---- internal/config/config.go | 147 ++++++++++- 15 files changed, 1389 insertions(+), 236 deletions(-) create mode 100644 docs/pat-auth-flow.md create mode 100644 internal/cli/pat_login.go create mode 100644 internal/cli/pat_login_flow_test.go diff --git a/README.md b/README.md index 0f205de..20f80a2 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Agent usage mapping is documented in `docs/agent-command-map.md`. ## Features in this scaffold - Profile-based auth in `~/.omni/config.json` -- Supports both PAT and org API key tokens +- Supports PAT auth, org API keys, or both in one profile - Token storage backends: `keychain` (macOS) or `config` fallback - Config precedence: flag > env > config file - `omni setup` wizard (interactive + non-interactive) @@ -56,7 +56,8 @@ Agent usage mapping is documented in `docs/agent-command-map.md`. - `--profile` - `--url` - `--token` -- `--token-type pat|org` +- `--auth pat|org` +- `--token-type pat|org` (legacy override) - `--config` - `--json` - `--plain` @@ -67,6 +68,9 @@ Agent usage mapping is documented in `docs/agent-command-map.md`. - `OMNI_PROFILE` - `OMNI_URL` +- `OMNI_AUTH` +- `OMNI_ORG_KEY` +- `OMNI_PAT` (manual override; PAT is normally acquired by browser login) - `OMNI_TOKEN` - `OMNI_TOKEN_TYPE` - `OMNI_CONFIG` @@ -109,9 +113,12 @@ omni completion fish > ~/.config/fish/completions/omni.fish ```bash omni setup -omni setup --non-interactive --profile prod --url https://acme.omniapp.co --token "$OMNI_PAT" --token-type pat --token-store auto -omni --no-input setup --profile prod --url https://acme.omniapp.co --token "$OMNI_PAT" --token-type pat -omni auth add --name prod --url https://acme.omniapp.co --token "$OMNI_PAT" --token-type pat --token-store keychain +omni setup --profile prod --url https://acme.omniapp.co --auth-mode pat --token-store auto +omni setup --non-interactive --profile prod --url https://acme.omniapp.co --auth-mode org --org-key "$OMNI_ORG_KEY" --token-store auto +omni setup --profile prod --url https://acme.omniapp.co --auth-mode both --org-key "$OMNI_ORG_KEY" --default-auth pat +omni --no-input setup --profile prod --url https://acme.omniapp.co --auth-mode org --org-key "$OMNI_ORG_KEY" +omni auth add --name prod --url https://acme.omniapp.co --auth-mode both --org-key "$OMNI_ORG_KEY" --default-auth pat --token-store keychain +omni --auth org documents list --page-size 20 omni schema omni schema documents permissions omni exit-codes --json @@ -160,6 +167,20 @@ omni query run --file query.json --result-type json --wait omni jobs status 12345 ``` +## Auth model + +- `omni setup` asks what auth to configure: `pat`, `org`, or `both` +- PAT setup uses browser login rather than asking the user to paste a token +- Profiles can store both a PAT and an org key at the same time +- General commands use the profile's `default_auth` +- Org-only commands such as `admin`, `users`, and `scim` automatically use the org key +- `--auth pat|org` forces a specific credential for the current command +- `OMNI_PAT`, `--token`, and `--token-type` are still accepted as manual/legacy overrides + +See also: + +- `docs/pat-auth-flow.md` + ## Command overview - `omni setup` diff --git a/docs/pat-auth-flow.md b/docs/pat-auth-flow.md new file mode 100644 index 0000000..102c450 --- /dev/null +++ b/docs/pat-auth-flow.md @@ -0,0 +1,105 @@ +# PAT Auth Flow + +This document explains how PAT authentication works in `omni-cli` and why it is implemented as a browser login flow instead of a pasted secret. + +## Summary + +- PAT is not treated as a user-entered API key in this CLI +- PAT setup uses a browser-based OAuth flow +- Org API key setup is still a direct prompt/input flow +- A profile can store: + - `pat` + - `org` + - `both` +- General commands use the profile's `default_auth` +- Org-only commands such as `admin`, `users`, and `scim` always use the org key + +## Why + +The main Omni API docs distinguish normal API-key usage from MCP OAuth PAT usage. In practice, the PAT flow used by Omni MCP is browser/OAuth based. That means prompting users to paste a PAT during setup is the wrong UX and the wrong model. + +## What We Verified + +We checked: + +- Omni MCP docs +- Omni API authentication docs +- The published `@omni-co/mcp` npm package +- The hosted OAuth discovery metadata on `callbacks.omniapp.co` + +Important finding: + +- The published `@omni-co/mcp` package does not implement the browser auth flow itself. It is an API-key bridge. +- The usable PAT auth contract comes from Omni's public OAuth discovery metadata, not from the npm package contents. + +## OAuth Endpoints Used + +These endpoints were publicly discoverable and used to implement PAT login: + +- Protected resource metadata: + - `https://callbacks.omniapp.co/.well-known/oauth-protected-resource` +- Authorization server metadata: + - `https://callbacks.omniapp.co/.well-known/oauth-authorization-server` +- Dynamic client registration: + - `https://callbacks.omniapp.co/oauth/register` + +Observed metadata includes: + +- authorization endpoint: + - `https://callbacks.omniapp.co/callback/mcp/oauth/authorize` +- token endpoint: + - `https://callbacks.omniapp.co/callback/mcp/oauth/token` +- scope: + - `mcp:access` +- PKCE: + - `S256` +- dynamic client registration: + - supported +- token endpoint auth method: + - `none` + +## Implemented PAT Flow + +The CLI PAT login flow is: + +1. Fetch protected resource metadata +2. Fetch authorization server metadata +3. Dynamically register a native OAuth client +4. Start a localhost callback listener on `127.0.0.1` +5. Generate PKCE verifier/challenge and state +6. Open browser to Omni authorization endpoint +7. Receive authorization code on loopback callback +8. Exchange code for bearer token +9. Store the returned token as the PAT credential for the profile + +The implementation lives in: + +- [internal/cli/pat_login.go](/Users/hawkfry/Documents/open-source/omni-opensource/omni-cli/internal/cli/pat_login.go) + +## Public Repo Caveat + +This repo is public. The current PAT implementation is considered acceptable to keep in a public repo because: + +- it uses public OAuth discovery metadata +- it uses standard OAuth 2.1 native-app patterns +- it does not expose secrets or bypass intended auth behavior + +But this should be treated as a currently working public integration point, not as a guaranteed permanent Omni CLI contract. + +In other words: + +- the flow is public enough to use +- the stability is not guaranteed unless Omni explicitly documents it as a supported standalone CLI auth contract + +If Omni changes hosted OAuth endpoints or MCP-related auth behavior, this implementation may need to be updated. + +## If This Breaks Later + +Re-check: + +- Omni MCP docs +- Omni API auth docs +- `callbacks.omniapp.co` OAuth discovery metadata +- whether Omni still supports loopback redirect URIs via dynamic client registration + +Do not reintroduce PAT as a pasted token during setup unless Omni explicitly changes their supported auth model. diff --git a/internal/auth/auth.go b/internal/auth/auth.go index 7fb933e..a4f5af6 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -15,8 +15,10 @@ type Options struct { URLFlag string TokenFlag string TokenTypeFlag string + AuthFlag string ConfigPath string TokenStore secret.Store + RequireAuth string } type Resolved struct { @@ -31,40 +33,32 @@ func Resolve(cfg *config.Config, opts Options) (*Resolved, error) { profileName = "default" } - profile := cfg.Profiles[profileName] - + stored := cfg.Profiles[profileName] + profile := stored profile.BaseURL = firstNonEmpty(opts.URLFlag, os.Getenv("OMNI_URL"), profile.BaseURL) - tokenOverride := firstNonEmpty(opts.TokenFlag, os.Getenv("OMNI_TOKEN")) - if tokenOverride != "" { - profile.Token = tokenOverride - } - profile.TokenType = normalizeTokenType(firstNonEmpty(opts.TokenTypeFlag, os.Getenv("OMNI_TOKEN_TYPE"), profile.TokenType)) - profile.TokenStore = normalizeTokenStore(profile.TokenStore) + profile.DefaultAuth = normalizeAuthKind(profile.DefaultAuth) - if profile.TokenType == "" { - profile.TokenType = "pat" - } - if profile.TokenStore == "" { - profile.TokenStore = "config" - } - if profile.Token == "" && profile.TokenStore == "keychain" && profile.TokenRef != "" { - if opts.TokenStore == nil || !opts.TokenStore.Available() { - return nil, errors.New("token is configured in keychain but keychain store is unavailable") - } - token, err := opts.TokenStore.Get(profile.TokenRef) - if err != nil { - return nil, fmt.Errorf("read token from keychain: %w", err) - } - profile.Token = token + selectedAuth := resolveAuthKind(stored, opts) + token, err := resolveToken(stored, selectedAuth, opts) + if err != nil { + return nil, err } if profile.BaseURL == "" { return nil, errors.New("missing Omni URL; set with --url or OMNI_URL or save in profile") } - if profile.Token == "" { - return nil, errors.New("missing API token; set with --token or OMNI_TOKEN or save in profile") + if token == "" { + switch selectedAuth { + case "org": + return nil, errors.New("missing org API key; configure one with `omni setup` or `omni auth add`") + default: + return nil, errors.New("missing PAT; configure one with `omni setup` or `omni auth add`") + } } + profile.Token = token + profile.TokenType = selectedAuth + return &Resolved{ ProfileName: profileName, Profile: profile, @@ -76,14 +70,32 @@ func SaveProfile(cfg *config.Config, profileName string, profile config.Profile, if cfg.Profiles == nil { cfg.Profiles = map[string]config.Profile{} } - profile.TokenType = normalizeTokenType(profile.TokenType) - if profile.TokenType == "" { - profile.TokenType = "pat" - } - profile.TokenStore = normalizeTokenStore(profile.TokenStore) - if profile.TokenStore == "" { - profile.TokenStore = "config" + + profile.BaseURL = strings.TrimSpace(profile.BaseURL) + profile.DefaultAuth = normalizeAuthKind(profile.DefaultAuth) + profile.PATStore = normalizeTokenStore(profile.PATStore) + profile.PATToken = strings.TrimSpace(profile.PATToken) + profile.PATRef = strings.TrimSpace(profile.PATRef) + profile.OrgKeyStore = normalizeTokenStore(profile.OrgKeyStore) + profile.OrgKey = strings.TrimSpace(profile.OrgKey) + profile.OrgKeyRef = strings.TrimSpace(profile.OrgKeyRef) + + switch { + case profile.DefaultAuth == "" && hasPAT(profile): + profile.DefaultAuth = "pat" + case profile.DefaultAuth == "" && hasOrg(profile): + profile.DefaultAuth = "org" + case profile.DefaultAuth == "pat" && !hasPAT(profile) && hasOrg(profile): + profile.DefaultAuth = "org" + case profile.DefaultAuth == "org" && !hasOrg(profile) && hasPAT(profile): + profile.DefaultAuth = "pat" } + + profile.Token = "" + profile.TokenType = "" + profile.TokenStore = "" + profile.TokenRef = "" + cfg.Profiles[profileName] = profile if setCurrent { cfg.CurrentProfile = profileName @@ -98,31 +110,134 @@ func UseProfile(cfg *config.Config, profileName string) error { return nil } -func normalizeTokenType(v string) string { - s := strings.ToLower(strings.TrimSpace(v)) - switch s { - case "", "pat", "org": - return s +func RedactToken(token string) string { + if len(token) <= 8 { + return "****" + } + return token[:4] + "..." + token[len(token)-4:] +} + +func resolveAuthKind(profile config.Profile, opts Options) string { + explicit := normalizeAuthKind(firstNonEmpty(opts.AuthFlag, opts.TokenTypeFlag, os.Getenv("OMNI_AUTH"), os.Getenv("OMNI_TOKEN_TYPE"))) + if explicit != "" { + return explicit + } + + required := normalizeAuthKind(opts.RequireAuth) + if required != "" { + return required + } + + defaultAuth := normalizeAuthKind(profile.DefaultAuth) + if defaultAuth != "" { + return defaultAuth + } + if hasPAT(profile) { + return "pat" + } + if hasOrg(profile) { + return "org" + } + if strings.TrimSpace(os.Getenv("OMNI_PAT")) != "" { + return "pat" + } + if strings.TrimSpace(os.Getenv("OMNI_ORG_KEY")) != "" { + return "org" + } + return "pat" +} + +func resolveToken(profile config.Profile, authKind string, opts Options) (string, error) { + if token := firstNonEmpty(opts.TokenFlag, os.Getenv("OMNI_TOKEN")); token != "" { + return token, nil + } + + switch authKind { + case "org": + if token := strings.TrimSpace(os.Getenv("OMNI_ORG_KEY")); token != "" { + return token, nil + } default: - return "" + if token := strings.TrimSpace(os.Getenv("OMNI_PAT")); token != "" { + return token, nil + } + } + + token, storeName, ref := storedCredential(profile, authKind) + if token != "" { + return token, nil } + if storeName == "keychain" && ref != "" { + if opts.TokenStore == nil || !opts.TokenStore.Available() { + return "", errors.New("token is configured in keychain but keychain store is unavailable") + } + keychainToken, err := opts.TokenStore.Get(ref) + if err != nil { + return "", fmt.Errorf("read token from keychain: %w", err) + } + return keychainToken, nil + } + + return "", nil } -func normalizeTokenStore(v string) string { - s := strings.ToLower(strings.TrimSpace(v)) - switch s { - case "", "config", "keychain": - return s +func storedCredential(profile config.Profile, authKind string) (token string, store string, ref string) { + switch authKind { + case "org": + if profile.OrgKey != "" || profile.OrgKeyRef != "" { + return strings.TrimSpace(profile.OrgKey), normalizeTokenStore(profile.OrgKeyStore), strings.TrimSpace(profile.OrgKeyRef) + } + default: + if profile.PATToken != "" || profile.PATRef != "" { + return strings.TrimSpace(profile.PATToken), normalizeTokenStore(profile.PATStore), strings.TrimSpace(profile.PATRef) + } + } + + legacyType := normalizeAuthKind(profile.TokenType) + if legacyType == "" { + legacyType = "pat" + } + if legacyType != authKind { + return "", "", "" + } + return strings.TrimSpace(profile.Token), normalizeTokenStore(profile.TokenStore), strings.TrimSpace(profile.TokenRef) +} + +func hasPAT(profile config.Profile) bool { + if strings.TrimSpace(profile.PATToken) != "" || strings.TrimSpace(profile.PATRef) != "" { + return true + } + legacyType := normalizeAuthKind(profile.TokenType) + return (legacyType == "" || legacyType == "pat") && (strings.TrimSpace(profile.Token) != "" || strings.TrimSpace(profile.TokenRef) != "") +} + +func hasOrg(profile config.Profile) bool { + if strings.TrimSpace(profile.OrgKey) != "" || strings.TrimSpace(profile.OrgKeyRef) != "" { + return true + } + return normalizeAuthKind(profile.TokenType) == "org" && (strings.TrimSpace(profile.Token) != "" || strings.TrimSpace(profile.TokenRef) != "") +} + +func normalizeAuthKind(v string) string { + switch strings.ToLower(strings.TrimSpace(v)) { + case "pat": + return "pat" + case "org": + return "org" default: return "" } } -func RedactToken(token string) string { - if len(token) <= 8 { - return "****" +func normalizeTokenStore(v string) string { + switch strings.ToLower(strings.TrimSpace(v)) { + case "config": + return "config" + case "keychain": + return "keychain" + default: + return "" } - return token[:4] + "..." + token[len(token)-4:] } func firstNonEmpty(values ...string) string { diff --git a/internal/cli/auth.go b/internal/cli/auth.go index f100f5b..0570837 100644 --- a/internal/cli/auth.go +++ b/internal/cli/auth.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "sort" + "strings" "github.com/omni-co/omni-cli/internal/auth" "github.com/omni-co/omni-cli/internal/config" @@ -46,13 +47,16 @@ func runAuthAdd(rt *runtime, args []string) int { fs := flag.NewFlagSet("auth add", flag.ContinueOnError) fs.SetOutput(io.Discard) - var name, url, token, tokenType, tokenStore string + var name, url, authMode, defaultAuth, patToken, orgKey, legacyToken, legacyTokenType, tokenStore string var setCurrent bool fs.StringVar(&name, "name", "default", "Profile name") fs.StringVar(&url, "url", "", "Omni instance URL") - fs.StringVar(&token, "token", "", "PAT or org API key") - fs.StringVar(&tokenType, "token-type", "pat", "pat or org") + fs.StringVar(&authMode, "auth-mode", "", "Auth setup: pat, org, or both") + fs.StringVar(&defaultAuth, "default-auth", "", "Default auth for general commands: pat or org") + fs.StringVar(&orgKey, "org-key", "", "Org API key to save") + fs.StringVar(&legacyToken, "token", "", "Legacy single token input") + fs.StringVar(&legacyTokenType, "token-type", "", "Legacy token type: pat or org") fs.StringVar(&tokenStore, "token-store", "auto", "auto, keychain, or config") fs.BoolVar(&setCurrent, "set-current", true, "Set as current profile") @@ -64,11 +68,44 @@ func runAuthAdd(rt *runtime, args []string) int { return usageFail(rt, err.Error()) } - if url == "" || token == "" { - return usageFail(rt, "--url and --token are required") + authMode, defaultAuth, patToken, orgKey = applyLegacySetupFlags(authMode, defaultAuth, patToken, orgKey, legacyToken, legacyTokenType) + authMode = normalizeSetupAuthMode(authMode) + defaultAuth = normalizeSetupAuthKind(defaultAuth) + + if url == "" { + return usageFail(rt, "--url is required") + } + if authMode == "" { + return usageFail(rt, "--auth-mode is required (pat, org, or both)") + } + switch authMode { + case "pat": + defaultAuth = "pat" + case "org": + defaultAuth = "org" + if strings.TrimSpace(orgKey) == "" { + return usageFail(rt, "--org-key is required for auth-mode org") + } + case "both": + if strings.TrimSpace(orgKey) == "" { + return usageFail(rt, "--org-key is required for auth-mode both") + } + if defaultAuth == "" { + return usageFail(rt, "--default-auth is required for auth-mode both") + } } - profile, warning, err := saveProfileWithToken(rt, name, url, tokenType, token, tokenStore, setCurrent) + if authMode == "pat" || authMode == "both" { + if strings.TrimSpace(patToken) == "" { + token, err := obtainPAT(rt, url) + if err != nil { + return fail(rt, 1, codeAuthError, "PAT browser login failed", map[string]any{"error": err.Error(), "base_url": url}) + } + patToken = token + } + } + + profile, warning, err := saveProfileWithCredentials(rt, name, url, defaultAuth, patToken, orgKey, tokenStore, setCurrent) if err != nil { return fail(rt, 1, codeConfigError, "failed to save profile", map[string]any{"error": err.Error()}) } @@ -77,9 +114,12 @@ func runAuthAdd(rt *runtime, args []string) int { } if err := output.Print(map[string]any{ - "ok": true, - "profile": name, - "token_store": profile.TokenStore, + "ok": true, + "profile": name, + "auth_mode": profile.AuthMode(), + "default_auth": profile.DefaultAuth, + "pat_store": profile.PATStore, + "org_store": profile.OrgKeyStore, }, rt.JSON, rt.Plain); err != nil { return fail(rt, 1, codeAPIError, "failed to print output", map[string]any{"error": err.Error()}) } @@ -95,16 +135,15 @@ func runAuthList(rt *runtime) int { sort.Strings(names) for _, name := range names { profile := rt.Config.Profiles[name] - store := profile.TokenStore - if store == "" { - store = "config" - } profiles = append(profiles, map[string]any{ - "name": name, - "base_url": profile.BaseURL, - "token_type": profile.TokenType, - "token_store": store, - "current": rt.Config.CurrentProfile == name, + "name": name, + "base_url": profile.BaseURL, + "auth_mode": profile.AuthMode(), + "default_auth": profile.DefaultAuth, + "configured_auths": profile.ConfiguredAuths(), + "pat_store": profile.PATStore, + "org_store": profile.OrgKeyStore, + "current": rt.Config.CurrentProfile == name, }) } if err := output.Print(map[string]any{"profiles": profiles}, rt.JSON, rt.Plain); err != nil { @@ -139,9 +178,8 @@ func runAuthRemove(rt *runtime, args []string) int { return fail(rt, 1, codeConfigMissing, "profile not found", map[string]any{"profile": name}) } - if profile.TokenStore == "keychain" && profile.TokenRef != "" && rt.Keychain != nil { - _ = rt.Keychain.Delete(profile.TokenRef) - } + deleteRemovedCredentialRef(rt.Keychain, profile.PATStore, profile.PATRef, "", "") + deleteRemovedCredentialRef(rt.Keychain, profile.OrgKeyStore, profile.OrgKeyRef, "", "") delete(rt.Config.Profiles, name) if rt.Config.CurrentProfile == name { rt.Config.CurrentProfile = "" @@ -164,11 +202,8 @@ func runAuthShow(rt *runtime, args []string) int { fs := flag.NewFlagSet("auth show", flag.ContinueOnError) fs.SetOutput(io.Discard) - var profile, url, token, tokenType string - fs.StringVar(&profile, "profile", "", "Profile name") - fs.StringVar(&url, "url", "", "Omni instance URL") - fs.StringVar(&token, "token", "", "PAT or org API key") - fs.StringVar(&tokenType, "token-type", "", "pat or org") + var profileName string + fs.StringVar(&profileName, "profile", "", "Profile name") if err := fs.Parse(args); err != nil { if errors.Is(err, flag.ErrHelp) { @@ -178,25 +213,28 @@ func runAuthShow(rt *runtime, args []string) int { return usageFail(rt, err.Error()) } - resolved, err := auth.Resolve(rt.Config, auth.Options{ - ProfileFlag: profile, - URLFlag: url, - TokenFlag: token, - TokenTypeFlag: tokenType, - ConfigPath: rt.ConfigPath, - TokenStore: rt.Keychain, - }) - if err != nil { - return fail(rt, 1, codeAuthError, "failed to resolve auth profile", map[string]any{"error": err.Error()}) + name := strings.TrimSpace(profileName) + if name == "" { + name = rt.Config.CurrentProfile + } + if name == "" { + name = "default" + } + profile, ok := rt.Config.Profiles[name] + if !ok { + return fail(rt, 1, codeConfigMissing, "profile not found", map[string]any{"profile": name}) } - profileCfg := rt.Config.Profiles[resolved.ProfileName] if err := output.Print(map[string]any{ - "profile": resolved.ProfileName, - "base_url": resolved.Profile.BaseURL, - "token_type": resolved.Profile.TokenType, - "token_store": profileCfg.TokenStore, - "token": auth.RedactToken(resolved.Profile.Token), + "profile": name, + "base_url": profile.BaseURL, + "auth_mode": profile.AuthMode(), + "default_auth": profile.DefaultAuth, + "configured_auths": profile.ConfiguredAuths(), + "pat_store": profile.PATStore, + "org_store": profile.OrgKeyStore, + "pat_token": redactConfiguredToken(profile.PATToken, profile.PATRef), + "org_key": redactConfiguredToken(profile.OrgKey, profile.OrgKeyRef), }, rt.JSON, rt.Plain); err != nil { return fail(rt, 1, codeAPIError, "failed to print output", map[string]any{"error": err.Error()}) } @@ -209,11 +247,21 @@ func saveConfig(rt *runtime) error { func printAuthUsage() { fmt.Print(`omni auth commands: - omni auth add --name --url --token [--token-type pat|org] [--token-store auto|keychain|config] + omni auth add --name --url --auth-mode [--default-auth ] [--org-key ] [--token-store auto|keychain|config] omni auth list omni auth remove omni auth use - omni auth show + omni auth show [--profile ] omni auth whoami `) } + +func redactConfiguredToken(token string, ref string) string { + if strings.TrimSpace(token) != "" { + return auth.RedactToken(strings.TrimSpace(token)) + } + if strings.TrimSpace(ref) != "" { + return "stored-in-keychain" + } + return "" +} diff --git a/internal/cli/auth_contract_test.go b/internal/cli/auth_contract_test.go index a799435..1e993b4 100644 --- a/internal/cli/auth_contract_test.go +++ b/internal/cli/auth_contract_test.go @@ -18,13 +18,16 @@ func TestAuthListJSONContractStable(t *testing.T) { CurrentProfile: "alpha", Profiles: map[string]config.Profile{ "zeta": { - BaseURL: "https://zeta.omniapp.co", - TokenType: "pat", + BaseURL: "https://zeta.omniapp.co", + DefaultAuth: "pat", + PATToken: "pat-token", + PATStore: "config", }, "alpha": { - BaseURL: "https://alpha.omniapp.co", - TokenType: "org", - TokenStore: "keychain", + BaseURL: "https://alpha.omniapp.co", + DefaultAuth: "org", + OrgKeyStore: "keychain", + OrgKeyRef: "alpha:org", }, }, } @@ -42,11 +45,14 @@ func TestAuthListJSONContractStable(t *testing.T) { var payload struct { Profiles []struct { - Name string `json:"name"` - BaseURL string `json:"base_url"` - TokenType string `json:"token_type"` - TokenStore string `json:"token_store"` - Current bool `json:"current"` + Name string `json:"name"` + BaseURL string `json:"base_url"` + AuthMode string `json:"auth_mode"` + DefaultAuth string `json:"default_auth"` + ConfiguredAuths []string `json:"configured_auths"` + PATStore string `json:"pat_store"` + OrgStore string `json:"org_store"` + Current bool `json:"current"` } `json:"profiles"` } if err := json.Unmarshal([]byte(stdout), &payload); err != nil { @@ -61,11 +67,14 @@ func TestAuthListJSONContractStable(t *testing.T) { if !payload.Profiles[0].Current { t.Fatalf("expected alpha to be current profile, got %#v", payload.Profiles[0]) } - if payload.Profiles[0].TokenStore != "keychain" { - t.Fatalf("expected alpha token_store keychain, got %q", payload.Profiles[0].TokenStore) + if payload.Profiles[0].AuthMode != "org" || payload.Profiles[0].DefaultAuth != "org" { + t.Fatalf("expected alpha org auth mode/default, got %#v", payload.Profiles[0]) } - if payload.Profiles[1].TokenStore != "config" { - t.Fatalf("expected default token_store config, got %q", payload.Profiles[1].TokenStore) + if payload.Profiles[0].OrgStore != "keychain" { + t.Fatalf("expected alpha org_store keychain, got %q", payload.Profiles[0].OrgStore) + } + if payload.Profiles[1].PATStore != "config" { + t.Fatalf("expected zeta pat_store config, got %q", payload.Profiles[1].PATStore) } } @@ -78,13 +87,16 @@ func TestAuthListPlainContractStable(t *testing.T) { CurrentProfile: "alpha", Profiles: map[string]config.Profile{ "zeta": { - BaseURL: "https://zeta.omniapp.co", - TokenType: "pat", + BaseURL: "https://zeta.omniapp.co", + DefaultAuth: "pat", + PATToken: "pat-token", + PATStore: "config", }, "alpha": { - BaseURL: "https://alpha.omniapp.co", - TokenType: "org", - TokenStore: "keychain", + BaseURL: "https://alpha.omniapp.co", + DefaultAuth: "org", + OrgKeyStore: "keychain", + OrgKeyRef: "alpha:org", }, }, } @@ -104,13 +116,13 @@ func TestAuthListPlainContractStable(t *testing.T) { if len(lines) != 3 { t.Fatalf("expected 3 plain lines, got %d: %q", len(lines), stdout) } - if lines[0] != "base_url\tcurrent\tname\ttoken_store\ttoken_type" { + if lines[0] != "auth_mode\tbase_url\tconfigured_auths\tcurrent\tdefault_auth\tname\torg_store\tpat_store" { t.Fatalf("unexpected plain header: %q", lines[0]) } - if lines[1] != "https://alpha.omniapp.co\ttrue\talpha\tkeychain\torg" { + if lines[1] != "org\thttps://alpha.omniapp.co\t[\"org\"]\ttrue\torg\talpha\tkeychain\t" { t.Fatalf("unexpected first plain row: %q", lines[1]) } - if lines[2] != "https://zeta.omniapp.co\tfalse\tzeta\tconfig\tpat" { + if lines[2] != "pat\thttps://zeta.omniapp.co\t[\"pat\"]\tfalse\tpat\tzeta\t\tconfig" { t.Fatalf("unexpected second plain row: %q", lines[2]) } } diff --git a/internal/cli/auth_test.go b/internal/cli/auth_test.go index 6f6d272..b4c82a0 100644 --- a/internal/cli/auth_test.go +++ b/internal/cli/auth_test.go @@ -29,16 +29,14 @@ func TestRunAuthRemoveDeletesProfileAndKeychainRef(t *testing.T) { CurrentProfile: "p1", Profiles: map[string]config.Profile{ "p1": { - BaseURL: "https://a.omniapp.co", - TokenType: "pat", - TokenStore: "keychain", - TokenRef: "ref-p1", + BaseURL: "https://a.omniapp.co", + PATStore: "keychain", + PATRef: "ref-p1", }, "p2": { - BaseURL: "https://b.omniapp.co", - TokenType: "pat", - TokenStore: "config", - Token: "abc", + BaseURL: "https://b.omniapp.co", + PATStore: "config", + PATToken: "abc", }, }, }, diff --git a/internal/cli/completion.go b/internal/cli/completion.go index c0ca14b..79d7d35 100644 --- a/internal/cli/completion.go +++ b/internal/cli/completion.go @@ -112,7 +112,7 @@ func zshCompletion() string { _omni() { local -a commands commands=( - 'setup:Configure Omni URL + token profile' + 'setup:Configure Omni URL and auth profile' 'schema:Print machine-readable command schema' 'exit-codes:Print stable automation exit codes' 'doctor:Run connectivity and capability checks' diff --git a/internal/cli/pat_login.go b/internal/cli/pat_login.go new file mode 100644 index 0000000..d806789 --- /dev/null +++ b/internal/cli/pat_login.go @@ -0,0 +1,391 @@ +package cli + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os/exec" + goruntime "runtime" + "strings" + "time" +) + +type PATLoginFunc func(baseURL string) (string, error) + +type oauthProtectedResourceMetadata struct { + AuthorizationServers []string `json:"authorization_servers"` + Resource string `json:"resource"` + ScopesSupported []string `json:"scopes_supported"` +} + +type oauthAuthorizationServerMetadata struct { + AuthorizationEndpoint string `json:"authorization_endpoint"` + CodeChallengeMethodsSupport []string `json:"code_challenge_methods_supported"` + GrantTypesSupported []string `json:"grant_types_supported"` + Issuer string `json:"issuer"` + RegistrationEndpoint string `json:"registration_endpoint"` + ResponseTypesSupported []string `json:"response_types_supported"` + ScopesSupported []string `json:"scopes_supported"` + TokenEndpoint string `json:"token_endpoint"` +} + +type oauthDynamicClientRegistrationResponse struct { + ClientID string `json:"client_id"` + RedirectURIs []string `json:"redirect_uris"` +} + +type oauthTokenResponse struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + Scope string `json:"scope"` +} + +type oauthCallbackResult struct { + Code string + State string + Err string +} + +func defaultPATLogin(baseURL string) (string, error) { + const callbackHost = "https://callbacks.omniapp.co" + + httpClient := &http.Client{Timeout: 30 * time.Second} + + resourceMeta, err := fetchProtectedResourceMetadata(httpClient, callbackHost+"/.well-known/oauth-protected-resource") + if err != nil { + return "", fmt.Errorf("fetch protected-resource metadata: %w", err) + } + authServerURL := callbackHost + if len(resourceMeta.AuthorizationServers) > 0 && strings.TrimSpace(resourceMeta.AuthorizationServers[0]) != "" { + authServerURL = strings.TrimSpace(resourceMeta.AuthorizationServers[0]) + } + authMeta, err := fetchAuthorizationServerMetadata(httpClient, strings.TrimRight(authServerURL, "/")+"/.well-known/oauth-authorization-server") + if err != nil { + return "", fmt.Errorf("fetch authorization-server metadata: %w", err) + } + + redirectURI, listener, err := startLoopbackListener() + if err != nil { + return "", fmt.Errorf("start loopback callback listener: %w", err) + } + defer listener.Close() + + clientReg, err := registerOAuthClient(httpClient, authMeta.RegistrationEndpoint, redirectURI) + if err != nil { + return "", fmt.Errorf("register OAuth client: %w", err) + } + + codeVerifier, err := randomBase64URL(32) + if err != nil { + return "", fmt.Errorf("generate PKCE code verifier: %w", err) + } + state, err := randomBase64URL(24) + if err != nil { + return "", fmt.Errorf("generate OAuth state: %w", err) + } + + callbackCh := make(chan oauthCallbackResult, 1) + serverErrCh := make(chan error, 1) + srv := startOAuthCallbackServer(listener, callbackCh, serverErrCh) + defer func() { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _ = srv.Shutdown(ctx) + }() + + authURL, err := buildAuthorizationURL(authMeta.AuthorizationEndpoint, resourceMeta.Resource, clientReg.ClientID, redirectURI, state, codeVerifier) + if err != nil { + return "", fmt.Errorf("build authorization URL: %w", err) + } + if err := openBrowser(authURL); err != nil { + return "", fmt.Errorf("open browser for PAT login: %w", err) + } + + callbackCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + + var callback oauthCallbackResult + select { + case callback = <-callbackCh: + case err := <-serverErrCh: + return "", fmt.Errorf("callback server failed: %w", err) + case <-callbackCtx.Done(): + return "", fmt.Errorf("timed out waiting for browser login callback") + } + if callback.Err != "" { + return "", fmt.Errorf("authorization failed: %s", callback.Err) + } + if callback.State != state { + return "", fmt.Errorf("authorization state mismatch") + } + if strings.TrimSpace(callback.Code) == "" { + return "", fmt.Errorf("authorization callback did not include a code") + } + + tokenResp, err := exchangeAuthorizationCode(httpClient, authMeta.TokenEndpoint, resourceMeta.Resource, clientReg.ClientID, redirectURI, callback.Code, codeVerifier) + if err != nil { + return "", fmt.Errorf("exchange authorization code: %w", err) + } + if !strings.EqualFold(strings.TrimSpace(tokenResp.TokenType), "bearer") { + return "", fmt.Errorf("unexpected token type %q", tokenResp.TokenType) + } + if strings.TrimSpace(tokenResp.AccessToken) == "" { + return "", fmt.Errorf("token response did not include an access token") + } + _ = baseURL + return strings.TrimSpace(tokenResp.AccessToken), nil +} + +func fetchProtectedResourceMetadata(httpClient *http.Client, metadataURL string) (oauthProtectedResourceMetadata, error) { + var meta oauthProtectedResourceMetadata + if err := getJSON(httpClient, metadataURL, &meta); err != nil { + return meta, err + } + if strings.TrimSpace(meta.Resource) == "" { + return meta, fmt.Errorf("missing resource in protected-resource metadata") + } + return meta, nil +} + +func fetchAuthorizationServerMetadata(httpClient *http.Client, metadataURL string) (oauthAuthorizationServerMetadata, error) { + var meta oauthAuthorizationServerMetadata + if err := getJSON(httpClient, metadataURL, &meta); err != nil { + return meta, err + } + if strings.TrimSpace(meta.AuthorizationEndpoint) == "" || strings.TrimSpace(meta.TokenEndpoint) == "" || strings.TrimSpace(meta.RegistrationEndpoint) == "" { + return meta, fmt.Errorf("incomplete authorization-server metadata") + } + return meta, nil +} + +func registerOAuthClient(httpClient *http.Client, registrationEndpoint string, redirectURI string) (oauthDynamicClientRegistrationResponse, error) { + body := map[string]any{ + "client_name": "omni-cli", + "application_type": "native", + "grant_types": []string{"authorization_code"}, + "response_types": []string{"code"}, + "redirect_uris": []string{redirectURI}, + "token_endpoint_auth_method": "none", + } + + var resp oauthDynamicClientRegistrationResponse + if err := postJSON(httpClient, registrationEndpoint, body, &resp); err != nil { + return resp, err + } + if strings.TrimSpace(resp.ClientID) == "" { + return resp, fmt.Errorf("registration response missing client_id") + } + return resp, nil +} + +func buildAuthorizationURL(authorizationEndpoint, resource, clientID, redirectURI, state, codeVerifier string) (string, error) { + u, err := url.Parse(strings.TrimSpace(authorizationEndpoint)) + if err != nil { + return "", err + } + codeChallenge := pkceS256(codeVerifier) + q := u.Query() + q.Set("client_id", clientID) + q.Set("redirect_uri", redirectURI) + q.Set("response_type", "code") + q.Set("scope", "mcp:access") + q.Set("state", state) + q.Set("code_challenge", codeChallenge) + q.Set("code_challenge_method", "S256") + if strings.TrimSpace(resource) != "" { + q.Set("resource", strings.TrimSpace(resource)) + } + u.RawQuery = q.Encode() + return u.String(), nil +} + +func exchangeAuthorizationCode(httpClient *http.Client, tokenEndpoint, resource, clientID, redirectURI, code, codeVerifier string) (oauthTokenResponse, error) { + form := url.Values{} + form.Set("grant_type", "authorization_code") + form.Set("client_id", clientID) + form.Set("redirect_uri", redirectURI) + form.Set("code", code) + form.Set("code_verifier", codeVerifier) + if strings.TrimSpace(resource) != "" { + form.Set("resource", strings.TrimSpace(resource)) + } + + req, err := http.NewRequest(http.MethodPost, strings.TrimSpace(tokenEndpoint), strings.NewReader(form.Encode())) + if err != nil { + return oauthTokenResponse{}, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + resp, err := httpClient.Do(req) + if err != nil { + return oauthTokenResponse{}, err + } + defer resp.Body.Close() + + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return oauthTokenResponse{}, err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return oauthTokenResponse{}, fmt.Errorf("token endpoint returned %s: %s", resp.Status, strings.TrimSpace(string(respBody))) + } + + var tokenResp oauthTokenResponse + if err := json.Unmarshal(respBody, &tokenResp); err != nil { + return oauthTokenResponse{}, fmt.Errorf("parse token response: %w", err) + } + return tokenResp, nil +} + +func startLoopbackListener() (string, net.Listener, error) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + return "", nil, err + } + addr, ok := listener.Addr().(*net.TCPAddr) + if !ok { + listener.Close() + return "", nil, fmt.Errorf("unexpected listener address type %T", listener.Addr()) + } + redirectURI := fmt.Sprintf("http://127.0.0.1:%d/callback", addr.Port) + return redirectURI, listener, nil +} + +func startOAuthCallbackServer(listener net.Listener, callbackCh chan<- oauthCallbackResult, serverErrCh chan<- error) *http.Server { + mux := http.NewServeMux() + mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { + result := oauthCallbackResult{ + Code: strings.TrimSpace(r.URL.Query().Get("code")), + State: strings.TrimSpace(r.URL.Query().Get("state")), + Err: firstNonEmpty(r.URL.Query().Get("error"), r.URL.Query().Get("error_description")), + } + select { + case callbackCh <- result: + default: + } + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if result.Err != "" { + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, "

Omni login failed

You can close this window and return to the CLI.

") + return + } + _, _ = io.WriteString(w, "

Omni login complete

You can close this window and return to the CLI.

") + }) + + srv := &http.Server{Handler: mux} + go func() { + if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed { + serverErrCh <- err + } + }() + return srv +} + +func getJSON(httpClient *http.Client, rawURL string, out any) error { + resp, err := httpClient.Get(strings.TrimSpace(rawURL)) + if err != nil { + return err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("%s returned %s: %s", rawURL, resp.Status, strings.TrimSpace(string(body))) + } + if err := json.Unmarshal(body, out); err != nil { + return fmt.Errorf("parse %s response: %w", rawURL, err) + } + return nil +} + +func postJSON(httpClient *http.Client, rawURL string, payload any, out any) error { + body, err := json.Marshal(payload) + if err != nil { + return err + } + + req, err := http.NewRequest(http.MethodPost, strings.TrimSpace(rawURL), strings.NewReader(string(body))) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + + resp, err := httpClient.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("%s returned %s: %s", rawURL, resp.Status, strings.TrimSpace(string(respBody))) + } + if err := json.Unmarshal(respBody, out); err != nil { + return fmt.Errorf("parse %s response: %w", rawURL, err) + } + return nil +} + +func pkceS256(codeVerifier string) string { + sum := sha256.Sum256([]byte(codeVerifier)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +func randomBase64URL(n int) (string, error) { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(b), nil +} + +func openBrowser(rawURL string) error { + rawURL = strings.TrimSpace(rawURL) + if rawURL == "" { + return fmt.Errorf("empty URL") + } + + var cmd *exec.Cmd + switch goruntime.GOOS { + case "darwin": + cmd = exec.Command("open", rawURL) + case "windows": + cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", rawURL) + default: + cmd = exec.Command("xdg-open", rawURL) + } + if err := cmd.Start(); err != nil { + return err + } + return cmd.Process.Release() +} + +func obtainPAT(rt *runtime, baseURL string) (string, error) { + if strings.TrimSpace(baseURL) == "" { + return "", fmt.Errorf("missing Omni URL for PAT login") + } + if rt == nil || rt.PATLogin == nil { + return "", fmt.Errorf("PAT login flow is unavailable") + } + token, err := rt.PATLogin(baseURL) + if err != nil { + return "", err + } + if strings.TrimSpace(token) == "" { + return "", fmt.Errorf("PAT login returned an empty token") + } + return strings.TrimSpace(token), nil +} diff --git a/internal/cli/pat_login_flow_test.go b/internal/cli/pat_login_flow_test.go new file mode 100644 index 0000000..6c9b181 --- /dev/null +++ b/internal/cli/pat_login_flow_test.go @@ -0,0 +1,103 @@ +package cli + +import ( + "io" + "os" + "path/filepath" + "testing" + + "github.com/omni-co/omni-cli/internal/config" +) + +func TestRunSetupPATUsesBrowserLoginFlow(t *testing.T) { + tmp := t.TempDir() + 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) { + return "pat-from-browser", nil + }, + } + + exit := captureRuntimeOutput(t, func() int { + return runSetup(rt, []string{ + "--profile", "prod", + "--url", "https://acme.omniapp.co", + "--auth-mode", "pat", + "--token-store", "config", + "--non-interactive", + "--no-validate", + }, setupDefaults{}) + }) + if exit != 0 { + t.Fatalf("expected exit 0, got %d", exit) + } + + profile := rt.Config.Profiles["prod"] + if profile.PATToken != "pat-from-browser" { + t.Fatalf("expected PAT from browser login, got %#v", profile) + } +} + +func TestRunAuthAddBothUsesBrowserLoginFlowForPAT(t *testing.T) { + tmp := t.TempDir() + 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) { + return "pat-from-browser", nil + }, + } + + exit := captureRuntimeOutput(t, func() int { + return runAuthAdd(rt, []string{ + "--name", "prod", + "--url", "https://acme.omniapp.co", + "--auth-mode", "both", + "--org-key", "org-key-123", + "--default-auth", "pat", + "--token-store", "config", + }) + }) + if exit != 0 { + t.Fatalf("expected exit 0, got %d", exit) + } + + profile := rt.Config.Profiles["prod"] + if profile.PATToken != "pat-from-browser" || profile.OrgKey != "org-key-123" { + t.Fatalf("expected browser PAT and org key stored, got %#v", profile) + } +} + +func captureRuntimeOutput(t *testing.T, fn func() int) 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 + + _, _ = io.ReadAll(outR) + _, _ = io.ReadAll(errR) + + return exit +} diff --git a/internal/cli/profile_save.go b/internal/cli/profile_save.go index 92ef87b..6b569ff 100644 --- a/internal/cli/profile_save.go +++ b/internal/cli/profile_save.go @@ -9,42 +9,86 @@ import ( "github.com/omni-co/omni-cli/internal/secret" ) -func saveProfileWithToken(rt *runtime, profileName, baseURL, tokenType, token, tokenStorePref string, setCurrent bool) (config.Profile, string, error) { +func saveProfileWithCredentials(rt *runtime, profileName, baseURL, defaultAuth, patToken, orgKey, tokenStorePref string, setCurrent bool) (config.Profile, string, error) { store, err := secret.Pick(tokenStorePref, rt.Keychain) if err != nil { return config.Profile{}, "", err } newProfile := config.Profile{ - BaseURL: strings.TrimSpace(baseURL), - TokenType: strings.TrimSpace(tokenType), + BaseURL: strings.TrimSpace(baseURL), + DefaultAuth: strings.TrimSpace(defaultAuth), } - warning := "" - if store.Name() == "keychain" { - ref, saveErr := store.Save(profileName, token) - if saveErr != nil { - return config.Profile{}, "", fmt.Errorf("save token in keychain: %w", saveErr) + if token := strings.TrimSpace(patToken); token != "" { + if err := applyCredential(store, tokenStorePref, profileName, "pat", token, &newProfile); err != nil { + return config.Profile{}, "", err } - newProfile.TokenStore = "keychain" - newProfile.TokenRef = ref - newProfile.Token = "" - } else { - newProfile.TokenStore = "config" - newProfile.Token = token - if tokenStorePref == "auto" && rt.Keychain != nil && !rt.Keychain.Available() { - warning = "keychain unavailable; token stored in config file" + } + if token := strings.TrimSpace(orgKey); token != "" { + if err := applyCredential(store, tokenStorePref, profileName, "org", token, &newProfile); err != nil { + return config.Profile{}, "", err } } prev := rt.Config.Profiles[profileName] - if prev.TokenStore == "keychain" && prev.TokenRef != "" && newProfile.TokenStore != "keychain" && rt.Keychain != nil { - _ = rt.Keychain.Delete(prev.TokenRef) - } + deleteRemovedCredentialRef(rt.Keychain, prev.PATStore, prev.PATRef, newProfile.PATStore, newProfile.PATRef) + deleteRemovedCredentialRef(rt.Keychain, prev.OrgKeyStore, prev.OrgKeyRef, newProfile.OrgKeyStore, newProfile.OrgKeyRef) auth.SaveProfile(rt.Config, profileName, newProfile, setCurrent) if err := config.Save(rt.ConfigPath, rt.Config); err != nil { return config.Profile{}, "", err } + warning := "" + if tokenStorePref == "auto" && rt.Keychain != nil && !rt.Keychain.Available() { + warning = "keychain unavailable; tokens stored in config file" + } return rt.Config.Profiles[profileName], warning, nil } + +func applyCredential(store secret.Store, tokenStorePref, profileName, authKind, token string, profile *config.Profile) error { + if store.Name() == "keychain" { + refName := credentialRefName(profileName, authKind) + ref, err := store.Save(refName, token) + if err != nil { + return fmt.Errorf("save %s credential in keychain: %w", authKind, err) + } + switch authKind { + case "org": + profile.OrgKeyStore = "keychain" + profile.OrgKeyRef = ref + profile.OrgKey = "" + default: + profile.PATStore = "keychain" + profile.PATRef = ref + profile.PATToken = "" + } + return nil + } + + switch authKind { + case "org": + profile.OrgKeyStore = "config" + profile.OrgKey = token + profile.OrgKeyRef = "" + default: + profile.PATStore = "config" + profile.PATToken = token + profile.PATRef = "" + } + return nil +} + +func credentialRefName(profileName, authKind string) string { + return strings.TrimSpace(profileName) + ":" + strings.TrimSpace(authKind) +} + +func deleteRemovedCredentialRef(store secret.Store, previousStore, previousRef, newStore, newRef string) { + if store == nil || previousStore != "keychain" || strings.TrimSpace(previousRef) == "" { + return + } + if newStore == "keychain" && strings.TrimSpace(newRef) == strings.TrimSpace(previousRef) { + return + } + _ = store.Delete(previousRef) +} diff --git a/internal/cli/profile_save_test.go b/internal/cli/profile_save_test.go index 0384907..cf79942 100644 --- a/internal/cli/profile_save_test.go +++ b/internal/cli/profile_save_test.go @@ -29,33 +29,33 @@ func (m *mockSecretStore) Delete(ref string) error { return nil } -func TestSaveProfileWithTokenAutoUsesKeychain(t *testing.T) { +func TestSaveProfileWithCredentialsAutoUsesKeychain(t *testing.T) { tmp := t.TempDir() rt := &runtime{ ConfigPath: filepath.Join(tmp, "config.json"), Config: &config.Config{Profiles: map[string]config.Profile{}}, - Keychain: &mockSecretStore{available: true, saveRef: "profile-ref"}, + Keychain: &mockSecretStore{available: true}, } - profile, warning, err := saveProfileWithToken(rt, "prod", "https://acme.omniapp.co", "pat", "super-token", "auto", true) + profile, warning, err := saveProfileWithCredentials(rt, "prod", "https://acme.omniapp.co", "pat", "super-token", "", "auto", true) if err != nil { - t.Fatalf("saveProfileWithToken returned error: %v", err) + t.Fatalf("saveProfileWithCredentials returned error: %v", err) } if warning != "" { t.Fatalf("expected no warning, got %q", warning) } - if profile.TokenStore != "keychain" { - t.Fatalf("expected keychain token store, got %q", profile.TokenStore) + if profile.PATStore != "keychain" { + t.Fatalf("expected keychain PAT store, got %q", profile.PATStore) } - if profile.TokenRef != "profile-ref" { - t.Fatalf("expected token ref profile-ref, got %q", profile.TokenRef) + if profile.PATRef != "prod:pat" { + t.Fatalf("expected PAT ref prod:pat, got %q", profile.PATRef) } - if profile.Token != "" { - t.Fatalf("expected no plaintext token in config profile, got %q", profile.Token) + if profile.PATToken != "" { + t.Fatalf("expected no plaintext PAT in config profile, got %q", profile.PATToken) } } -func TestSaveProfileWithTokenAutoFallsBackToConfig(t *testing.T) { +func TestSaveProfileWithCredentialsAutoFallsBackToConfig(t *testing.T) { tmp := t.TempDir() rt := &runtime{ ConfigPath: filepath.Join(tmp, "config.json"), @@ -63,42 +63,61 @@ func TestSaveProfileWithTokenAutoFallsBackToConfig(t *testing.T) { Keychain: &mockSecretStore{available: false}, } - profile, warning, err := saveProfileWithToken(rt, "prod", "https://acme.omniapp.co", "pat", "super-token", "auto", true) + profile, warning, err := saveProfileWithCredentials(rt, "prod", "https://acme.omniapp.co", "pat", "super-token", "", "auto", true) if err != nil { - t.Fatalf("saveProfileWithToken returned error: %v", err) + t.Fatalf("saveProfileWithCredentials returned error: %v", err) } if warning == "" { t.Fatal("expected fallback warning, got empty string") } - if profile.TokenStore != "config" { - t.Fatalf("expected config token store, got %q", profile.TokenStore) + if profile.PATStore != "config" { + t.Fatalf("expected config PAT store, got %q", profile.PATStore) } - if profile.Token != "super-token" { - t.Fatalf("expected plaintext token in config fallback, got %q", profile.Token) + if profile.PATToken != "super-token" { + t.Fatalf("expected plaintext PAT in config fallback, got %q", profile.PATToken) } } -func TestSaveProfileWithTokenDeletesOldKeychainRefWhenSwitchingToConfig(t *testing.T) { +func TestSaveProfileWithCredentialsDeletesOldKeychainRefWhenSwitchingToConfig(t *testing.T) { store := &mockSecretStore{available: true} tmp := t.TempDir() rt := &runtime{ ConfigPath: filepath.Join(tmp, "config.json"), Config: &config.Config{Profiles: map[string]config.Profile{ "prod": { - BaseURL: "https://acme.omniapp.co", - TokenType: "pat", - TokenStore: "keychain", - TokenRef: "old-ref", + BaseURL: "https://acme.omniapp.co", + PATStore: "keychain", + PATRef: "old-ref", }, }}, Keychain: store, } - _, _, err := saveProfileWithToken(rt, "prod", "https://acme.omniapp.co", "pat", "new-token", "config", true) + _, _, err := saveProfileWithCredentials(rt, "prod", "https://acme.omniapp.co", "pat", "new-token", "", "config", true) if err != nil { - t.Fatalf("saveProfileWithToken returned error: %v", err) + t.Fatalf("saveProfileWithCredentials returned error: %v", err) } if len(store.deleteRefs) != 1 || store.deleteRefs[0] != "old-ref" { t.Fatalf("expected old keychain ref deletion, got %#v", store.deleteRefs) } } + +func TestSaveProfileWithCredentialsStoresBothAuths(t *testing.T) { + tmp := t.TempDir() + rt := &runtime{ + ConfigPath: filepath.Join(tmp, "config.json"), + Config: &config.Config{Profiles: map[string]config.Profile{}}, + Keychain: &mockSecretStore{available: false}, + } + + profile, _, err := saveProfileWithCredentials(rt, "prod", "https://acme.omniapp.co", "pat", "pat-token", "org-token", "config", true) + if err != nil { + t.Fatalf("saveProfileWithCredentials returned error: %v", err) + } + if profile.DefaultAuth != "pat" { + t.Fatalf("expected default auth pat, got %q", profile.DefaultAuth) + } + if profile.PATToken != "pat-token" || profile.OrgKey != "org-token" { + t.Fatalf("expected both credentials stored, got %#v", profile) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index c32e3e6..470bd71 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -26,6 +26,7 @@ type runtime struct { Config *config.Config Resolved *auth.Resolved Keychain secret.Store + PATLogin PATLoginFunc } func Execute(args []string, version string) int { @@ -35,6 +36,7 @@ func Execute(args []string, version string) int { var profile string var url string var token string + var authMode string var tokenType string var configPath string var asJSON bool @@ -45,6 +47,7 @@ func Execute(args []string, version string) int { global.StringVar(&profile, "profile", "", "Profile name to use") global.StringVar(&url, "url", "", "Omni instance URL") global.StringVar(&token, "token", "", "Omni API token (PAT or org key)") + global.StringVar(&authMode, "auth", "", "Auth to use: pat or org") global.StringVar(&tokenType, "token-type", "", "Token type: pat or org") global.StringVar(&configPath, "config", "", "Config file path") global.BoolVar(&asJSON, "json", false, "Print JSON output") @@ -98,6 +101,7 @@ func Execute(args []string, version string) int { ConfigPath: configPath, Config: cfg, Keychain: secret.NewKeychainStore(), + PATLogin: defaultPATLogin, } remaining := global.Args() @@ -132,10 +136,8 @@ func Execute(args []string, version string) int { return runCompletion(rt, cmdArgs) case "setup": return runSetup(rt, cmdArgs, setupDefaults{ - Profile: profile, - URL: url, - Token: token, - TokenType: tokenType, + Profile: profile, + URL: url, }) case "auth": return runAuth(rt, cmdArgs) @@ -150,16 +152,18 @@ func Execute(args []string, version string) int { URLFlag: url, TokenFlag: token, TokenTypeFlag: tokenType, + AuthFlag: authMode, ConfigPath: configPath, TokenStore: rt.Keychain, + RequireAuth: requiredAuthForCommand(cmd), }) if err != nil { details := map[string]any{"error": err.Error()} if err.Error() == "missing Omni URL; set with --url or OMNI_URL or save in profile" { return fail(rt, 1, codeConfigMissing, "missing Omni URL configuration", details) } - if err.Error() == "missing API token; set with --token or OMNI_TOKEN or save in profile" { - return fail(rt, 1, codeConfigMissing, "missing API token configuration", details) + if strings.HasPrefix(err.Error(), "missing PAT") || strings.HasPrefix(err.Error(), "missing org API key") { + return fail(rt, 1, codeConfigMissing, "missing Omni auth configuration", details) } if len(cfg.Profiles) == 0 { return fail(rt, 1, codeConfigMissing, "no profiles configured; run `omni setup`", details) @@ -231,6 +235,15 @@ func Execute(args []string, version string) int { } } +func requiredAuthForCommand(cmd string) string { + switch cmd { + case "admin", "users", "scim": + return "org" + default: + return "" + } +} + func printUsage() { fmt.Print(`omni - Omni CLI @@ -242,7 +255,7 @@ Commands: exit-codes Print stable automation exit codes doctor Check connectivity, auth, and capabilities completion Generate shell completion scripts - setup Configure Omni URL + token profile + setup Configure Omni URL and auth profile auth Manage profiles and tokens documents List and inspect documents models Manage models @@ -267,6 +280,7 @@ Commands: Global flags: --profile --url + --auth --token --token-type --config @@ -282,7 +296,7 @@ Examples: omni doctor --json omni completion zsh omni setup - omni setup --non-interactive --profile prod --url https://acme.omniapp.co --token $OMNI_PAT --token-type pat + omni setup --profile prod --url https://acme.omniapp.co --auth-mode both --org-key $OMNI_ORG_KEY --default-auth pat omni documents list --page-size 20 omni documents rename wk_abc123 --name "Q1 Dashboard" omni documents permissions add wk_abc123 --file permits.json @@ -307,7 +321,7 @@ Examples: omni ai generate-query --model-id --prompt "Revenue by month" omni ai workbook --model-id --prompt "Top 10 customers by revenue" omni api call --method GET --path /api/v1/documents - omni auth add --name prod --url https://acme.omniapp.co --token $OMNI_PAT --token-type pat --token-store auto + omni auth add --name prod --url https://acme.omniapp.co --auth-mode org --org-key $OMNI_ORG_KEY --token-store auto omni auth use prod omni query run --file query.json --wait --result-type json omni jobs status 12345 diff --git a/internal/cli/schema.go b/internal/cli/schema.go index dbf4a9e..a0342bb 100644 --- a/internal/cli/schema.go +++ b/internal/cli/schema.go @@ -117,7 +117,7 @@ func commandSchemaRoot() *schemaCommand { schemaCmd("zsh", "Generate zsh completion script", ""), schemaCmd("fish", "Generate fish completion script", ""), ), - schemaCmd("setup", "Configure Omni URL + token profile", "omni setup"), + schemaCmd("setup", "Configure Omni URL and auth profile", "omni setup"), schemaCmd("auth", "Manage profiles and tokens", "omni auth ", schemaCmd("add", "Add auth profile", ""), schemaCmd("list", "List auth profiles", ""), @@ -384,6 +384,7 @@ func commandSchemaRoot() *schemaCommand { root.Flags = []schemaFlag{ {Name: "--profile", Type: "string", Description: "Profile name to use"}, {Name: "--url", Type: "string", Description: "Omni instance URL"}, + {Name: "--auth", Type: "string", Description: "Auth to use: pat or org"}, {Name: "--token", Type: "string", Description: "Omni API token (PAT or org key)"}, {Name: "--token-type", Type: "string", Description: "Token type: pat or org"}, {Name: "--config", Type: "string", Description: "Config file path"}, diff --git a/internal/cli/setup.go b/internal/cli/setup.go index fd66da6..a5940b5 100644 --- a/internal/cli/setup.go +++ b/internal/cli/setup.go @@ -17,10 +17,8 @@ import ( ) type setupDefaults struct { - Profile string - URL string - Token string - TokenType string + Profile string + URL string } func runSetup(rt *runtime, args []string, defaults setupDefaults) int { @@ -28,12 +26,15 @@ func runSetup(rt *runtime, args []string, defaults setupDefaults) int { fs.SetOutput(io.Discard) profileDefault := firstNonEmpty(defaults.Profile, "default") - tokenTypeDefault := firstNonEmpty(defaults.TokenType, "pat") var profile string var url string - var token string - var tokenType string + var authMode string + var defaultAuth string + var patToken string + var orgKey string + var legacyToken string + var legacyTokenType string var tokenStore string var nonInteractive bool var noValidate bool @@ -42,8 +43,11 @@ func runSetup(rt *runtime, args []string, defaults setupDefaults) int { fs.StringVar(&profile, "profile", profileDefault, "Profile name") fs.StringVar(&url, "url", defaults.URL, "Omni instance URL") - fs.StringVar(&token, "token", defaults.Token, "PAT or org API key") - fs.StringVar(&tokenType, "token-type", tokenTypeDefault, "pat or org") + fs.StringVar(&authMode, "auth-mode", "", "Auth setup: pat, org, or both") + fs.StringVar(&defaultAuth, "default-auth", "", "Default auth for general commands: pat or org") + fs.StringVar(&orgKey, "org-key", "", "Org API key to save") + fs.StringVar(&legacyToken, "token", "", "Legacy single token input") + fs.StringVar(&legacyTokenType, "token-type", "", "Legacy token type: pat or org") fs.StringVar(&tokenStore, "token-store", "auto", "auto, keychain, or config") fs.BoolVar(&nonInteractive, "non-interactive", false, "Disable prompts; require all values via flags/env") fs.BoolVar(&noValidate, "no-validate", false, "Skip API validation step") @@ -58,6 +62,8 @@ func runSetup(rt *runtime, args []string, defaults setupDefaults) int { return usageFail(rt, err.Error()) } + authMode, defaultAuth, patToken, orgKey = applyLegacySetupFlags(authMode, defaultAuth, patToken, orgKey, legacyToken, legacyTokenType) + if rt.NoInput { nonInteractive = true } @@ -77,26 +83,37 @@ func runSetup(rt *runtime, args []string, defaults setupDefaults) int { if err != nil { return fail(rt, 1, codeUsageError, "setup prompt failed", map[string]any{"error": err.Error()}) } - tokenType, err = promptInput(reader, "Token type (pat|org)", tokenType) + authMode, err = promptInput(reader, "Auth setup (pat|org|both)", firstNonEmpty(authMode, "pat")) if err != nil { return fail(rt, 1, codeUsageError, "setup prompt failed", map[string]any{"error": err.Error()}) } + authMode = normalizeSetupAuthMode(authMode) + if authMode == "both" { + defaultAuth, err = promptInput(reader, "Default auth for general commands (pat|org)", firstNonEmpty(defaultAuth, "pat")) + if err != nil { + return fail(rt, 1, codeUsageError, "setup prompt failed", map[string]any{"error": err.Error()}) + } + } tokenStore, err = promptInput(reader, "Token store (auto|keychain|config)", tokenStore) if err != nil { return fail(rt, 1, codeUsageError, "setup prompt failed", map[string]any{"error": err.Error()}) } - if strings.TrimSpace(token) == "" { - token, err = promptSecretInput(reader, "Token") - if err != nil { - return fail(rt, 1, codeUsageError, "setup prompt failed", map[string]any{"error": err.Error()}) + if authMode == "org" || authMode == "both" { + if strings.TrimSpace(orgKey) == "" { + orgKey, err = promptSecretInput(reader, "Org API key") + if err != nil { + return fail(rt, 1, codeUsageError, "setup prompt failed", map[string]any{"error": err.Error()}) + } } } } profile = strings.TrimSpace(profile) url = strings.TrimSpace(url) - token = strings.TrimSpace(token) - tokenType = normalizeSetupTokenType(tokenType) + authMode = normalizeSetupAuthMode(authMode) + defaultAuth = normalizeSetupAuthKind(defaultAuth) + patToken = strings.TrimSpace(patToken) + orgKey = strings.TrimSpace(orgKey) tokenStore = normalizeTokenStoreSetting(tokenStore) if profile == "" { @@ -105,40 +122,64 @@ func runSetup(rt *runtime, args []string, defaults setupDefaults) int { if url == "" { return usageFail(rt, "missing Omni URL; set --url") } - if token == "" { - return usageFail(rt, "missing token; set --token") - } - if tokenType == "" { - return usageFail(rt, fmt.Sprintf("invalid token type %q; use pat or org", tokenType)) + if authMode == "" { + return usageFail(rt, "missing auth setup; set --auth-mode to pat, org, or both") } if tokenStore == "" { return usageFail(rt, fmt.Sprintf("invalid token store %q; use auto, keychain, or config", tokenStore)) } - - validated := false - var summary validationSummary - if !noValidate { - api, err := client.New(url, token) - if err != nil { - return fail(rt, 1, codeConfigError, "failed to create API client", map[string]any{"error": err.Error()}) + switch authMode { + case "pat": + defaultAuth = "pat" + case "org": + defaultAuth = "org" + if orgKey == "" { + return usageFail(rt, "missing org API key; set --org-key") } - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSec)*time.Second) - defer cancel() + case "both": + if orgKey == "" { + return usageFail(rt, "missing org API key; set --org-key") + } + if defaultAuth == "" { + return usageFail(rt, "missing default auth; set --default-auth to pat or org") + } + default: + return usageFail(rt, fmt.Sprintf("invalid auth setup %q; use pat, org, or both", authMode)) + } - summary, vErr := collectValidation(ctx, api, tokenType, tokenType == "org") - if vErr != nil { - return fail(rt, 1, vErr.Code, vErr.Message, vErr.Details) + if authMode == "pat" || authMode == "both" { + if strings.TrimSpace(patToken) == "" { + token, err := obtainPAT(rt, url) + if err != nil { + return fail(rt, 1, codeAuthError, "PAT browser login failed", map[string]any{"error": err.Error(), "base_url": url}) + } + patToken = token } - validated = summary.Base.Status != "fail" - if summary.Query.Status == "fail" { - output.Errorf("warning: query capability validation failed (%s)", summary.Query.Message) + } + + validated := false + validationResults := map[string]validationSummary{} + if !noValidate { + if patToken != "" { + summary, vErr := validateSetupCredential(url, patToken, "pat", timeoutSec) + if vErr != nil { + return fail(rt, 1, vErr.Code, vErr.Message, vErr.Details) + } + validationResults["pat"] = summary + validated = validated || summary.Base.Status != "fail" } - if summary.Admin.Status == "fail" { - output.Errorf("warning: admin capability validation failed (%s)", summary.Admin.Message) + if orgKey != "" { + summary, vErr := validateSetupCredential(url, orgKey, "org", timeoutSec) + if vErr != nil { + return fail(rt, 1, vErr.Code, vErr.Message, vErr.Details) + } + validationResults["org"] = summary + validated = validated || summary.Base.Status != "fail" } + emitSetupValidationMessages(authMode, validationResults) } - profileCfg, warning, err := saveProfileWithToken(rt, profile, url, tokenType, token, tokenStore, setCurrent) + profileCfg, warning, err := saveProfileWithCredentials(rt, profile, url, defaultAuth, patToken, orgKey, tokenStore, setCurrent) if err != nil { return fail(rt, 1, codeConfigError, "failed to save profile", map[string]any{"error": err.Error()}) } @@ -147,16 +188,26 @@ func runSetup(rt *runtime, args []string, defaults setupDefaults) int { } result := map[string]any{ - "ok": true, - "profile": profile, - "base_url": url, - "token_type": tokenType, - "token_store": profileCfg.TokenStore, - "set_current": setCurrent, - "validated": validated, + "ok": true, + "profile": profile, + "base_url": url, + "auth_mode": profileCfg.AuthMode(), + "default_auth": profileCfg.DefaultAuth, + "configured_auths": profileCfg.ConfiguredAuths(), + "set_current": setCurrent, + "validated": validated, + } + if note := setupValidationNote(authMode, validationResults); note != "" { + result["note"] = note + } + if patToken != "" { + result["pat_token_store"] = profileCfg.PATStore + } + if orgKey != "" { + result["org_key_store"] = profileCfg.OrgKeyStore } if !noValidate { - result["validation"] = summary + result["validation"] = validationResults } if err := output.Print(result, rt.JSON, rt.Plain); err != nil { @@ -165,12 +216,88 @@ func runSetup(rt *runtime, args []string, defaults setupDefaults) int { return 0 } +func validateSetupCredential(url, token, authKind string, timeoutSec int) (validationSummary, *validationFailure) { + api, err := client.New(url, token) + if err != nil { + return validationSummary{}, &validationFailure{Code: codeConfigError, Message: "failed to create API client", Details: map[string]any{"error": err.Error()}} + } + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSec)*time.Second) + defer cancel() + return collectValidation(ctx, api, authKind, authKind == "org") +} + +func emitSetupValidationMessages(authMode string, validationResults map[string]validationSummary) { + patSummary, hasPAT := validationResults["pat"] + orgSummary, hasOrg := validationResults["org"] + + if hasPAT && patSummary.Query.Status == "fail" { + if authMode == "both" && hasOrg && orgSummary.Query.Status == "pass" && orgSummary.Admin.Status == "pass" { + output.Errorf("note: PAT authenticated but has limited permissions on this instance (%s). Org key validation passed and setup succeeded.", patSummary.Query.Message) + } else { + output.Errorf("warning: PAT query capability validation failed (%s)", patSummary.Query.Message) + } + } + if hasOrg && orgSummary.Query.Status == "fail" { + output.Errorf("warning: org-key query capability validation failed (%s)", orgSummary.Query.Message) + } + if hasOrg && orgSummary.Admin.Status == "fail" { + output.Errorf("warning: org-key admin capability validation failed (%s)", orgSummary.Admin.Message) + } +} + +func setupValidationNote(authMode string, validationResults map[string]validationSummary) string { + if authMode != "both" { + return "" + } + patSummary, hasPAT := validationResults["pat"] + orgSummary, hasOrg := validationResults["org"] + if !hasPAT || !hasOrg { + return "" + } + if patSummary.Query.Status == "fail" && orgSummary.Query.Status == "pass" && orgSummary.Admin.Status == "pass" { + return "PAT login worked, but this PAT has limited permissions on this instance. The org key passed full validation, so setup succeeded." + } + return "" +} + +func applyLegacySetupFlags(authMode, defaultAuth, patToken, orgKey, token, tokenType string) (string, string, string, string) { + token = strings.TrimSpace(token) + tokenType = normalizeSetupAuthKind(tokenType) + if token == "" || tokenType == "" { + return authMode, defaultAuth, patToken, orgKey + } + switch tokenType { + case "org": + if strings.TrimSpace(orgKey) == "" { + orgKey = token + } + if strings.TrimSpace(authMode) == "" { + authMode = "org" + } + if strings.TrimSpace(defaultAuth) == "" { + defaultAuth = "org" + } + default: + if strings.TrimSpace(patToken) == "" { + patToken = token + } + if strings.TrimSpace(authMode) == "" { + authMode = "pat" + } + if strings.TrimSpace(defaultAuth) == "" { + defaultAuth = "pat" + } + } + return authMode, defaultAuth, patToken, orgKey +} + func printSetupUsage() { fmt.Print(`omni setup: - omni setup [--profile ] [--url ] [--token ] [--token-type pat|org] + omni setup [--profile ] [--url ] [--auth-mode ] + [--default-auth ] [--org-key ] [--token-store auto|keychain|config] [--timeout-seconds 20] - omni setup --non-interactive --profile --url --token --token-type pat|org - omni --no-input setup --profile --url --token --token-type pat|org + omni setup --non-interactive --profile --url --auth-mode both --org-key --default-auth pat + omni --no-input setup --profile --url --auth-mode org --org-key `) } @@ -208,10 +335,22 @@ func promptSecretInput(reader *bufio.Reader, label string) (string, error) { return strings.TrimSpace(text), nil } -func normalizeSetupTokenType(v string) string { - s := strings.ToLower(strings.TrimSpace(v)) - switch s { - case "", "pat": +func normalizeSetupAuthMode(v string) string { + switch strings.ToLower(strings.TrimSpace(v)) { + case "pat": + return "pat" + case "org": + return "org" + case "both": + return "both" + default: + return "" + } +} + +func normalizeSetupAuthKind(v string) string { + switch strings.ToLower(strings.TrimSpace(v)) { + case "pat": return "pat" case "org": return "org" diff --git a/internal/config/config.go b/internal/config/config.go index 45c644a..a38981d 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -6,12 +6,22 @@ import ( "fmt" "os" "path/filepath" + "strings" ) type Profile struct { - BaseURL string `json:"base_url"` + BaseURL string `json:"base_url"` + DefaultAuth string `json:"default_auth,omitempty"` + PATToken string `json:"pat_token,omitempty"` + PATStore string `json:"pat_token_store,omitempty"` + PATRef string `json:"pat_token_ref,omitempty"` + OrgKey string `json:"org_key,omitempty"` + OrgKeyStore string `json:"org_key_store,omitempty"` + OrgKeyRef string `json:"org_key_ref,omitempty"` + + // Legacy single-token fields kept for backward-compatible reads. Token string `json:"token,omitempty"` - TokenType string `json:"token_type"` + TokenType string `json:"token_type,omitempty"` TokenStore string `json:"token_store,omitempty"` TokenRef string `json:"token_ref,omitempty"` } @@ -49,6 +59,9 @@ func Load(path string) (*Config, error) { if cfg.Profiles == nil { cfg.Profiles = map[string]Profile{} } + for name, profile := range cfg.Profiles { + cfg.Profiles[name] = normalizeProfile(profile) + } return &cfg, nil } @@ -59,6 +72,9 @@ func Save(path string, cfg *Config) error { if cfg.Profiles == nil { cfg.Profiles = map[string]Profile{} } + for name, profile := range cfg.Profiles { + cfg.Profiles[name] = normalizeProfile(profile) + } dir := filepath.Dir(path) if err := os.MkdirAll(dir, 0o700); err != nil { @@ -80,3 +96,130 @@ func Save(path string, cfg *Config) error { return nil } + +func normalizeProfile(profile Profile) Profile { + profile.BaseURL = strings.TrimSpace(profile.BaseURL) + profile.DefaultAuth = normalizeAuthKind(profile.DefaultAuth) + + profile.PATStore = normalizeTokenStore(profile.PATStore) + profile.PATToken = strings.TrimSpace(profile.PATToken) + profile.PATRef = strings.TrimSpace(profile.PATRef) + if profile.PATStore == "" && (profile.PATToken != "" || profile.PATRef != "") { + profile.PATStore = defaultStoreForCredential(profile.PATToken, profile.PATRef) + } + + profile.OrgKeyStore = normalizeTokenStore(profile.OrgKeyStore) + profile.OrgKey = strings.TrimSpace(profile.OrgKey) + profile.OrgKeyRef = strings.TrimSpace(profile.OrgKeyRef) + if profile.OrgKeyStore == "" && (profile.OrgKey != "" || profile.OrgKeyRef != "") { + profile.OrgKeyStore = defaultStoreForCredential(profile.OrgKey, profile.OrgKeyRef) + } + + legacyType := normalizeAuthKind(profile.TokenType) + legacyToken := strings.TrimSpace(profile.Token) + legacyStore := normalizeTokenStore(profile.TokenStore) + legacyRef := strings.TrimSpace(profile.TokenRef) + if legacyStore == "" && (legacyToken != "" || legacyRef != "") { + legacyStore = defaultStoreForCredential(legacyToken, legacyRef) + } + switch legacyType { + case "org": + if profile.OrgKey == "" && profile.OrgKeyRef == "" { + profile.OrgKey = legacyToken + profile.OrgKeyStore = legacyStore + profile.OrgKeyRef = legacyRef + } + case "pat", "": + if profile.PATToken == "" && profile.PATRef == "" { + profile.PATToken = legacyToken + profile.PATStore = legacyStore + profile.PATRef = legacyRef + } + } + + if profile.DefaultAuth == "" { + switch { + case profile.HasPAT(): + profile.DefaultAuth = "pat" + case profile.HasOrg(): + profile.DefaultAuth = "org" + } + } + if profile.DefaultAuth == "pat" && !profile.HasPAT() && profile.HasOrg() { + profile.DefaultAuth = "org" + } + if profile.DefaultAuth == "org" && !profile.HasOrg() && profile.HasPAT() { + profile.DefaultAuth = "pat" + } + + profile.Token = "" + profile.TokenType = "" + profile.TokenStore = "" + profile.TokenRef = "" + + return profile +} + +func (p Profile) HasPAT() bool { + return strings.TrimSpace(p.PATToken) != "" || strings.TrimSpace(p.PATRef) != "" +} + +func (p Profile) HasOrg() bool { + return strings.TrimSpace(p.OrgKey) != "" || strings.TrimSpace(p.OrgKeyRef) != "" +} + +func (p Profile) AuthMode() string { + switch { + case p.HasPAT() && p.HasOrg(): + return "both" + case p.HasPAT(): + return "pat" + case p.HasOrg(): + return "org" + default: + return "" + } +} + +func (p Profile) ConfiguredAuths() []string { + auths := make([]string, 0, 2) + if p.HasPAT() { + auths = append(auths, "pat") + } + if p.HasOrg() { + auths = append(auths, "org") + } + return auths +} + +func normalizeAuthKind(v string) string { + switch strings.ToLower(strings.TrimSpace(v)) { + case "pat": + return "pat" + case "org": + return "org" + default: + return "" + } +} + +func normalizeTokenStore(v string) string { + switch strings.ToLower(strings.TrimSpace(v)) { + case "config": + return "config" + case "keychain": + return "keychain" + default: + return "" + } +} + +func defaultStoreForCredential(token string, ref string) string { + if strings.TrimSpace(ref) != "" { + return "keychain" + } + if strings.TrimSpace(token) != "" { + return "config" + } + return "" +} From 9953eca55ceebf14806f886bde5c5997559ddfa7 Mon Sep 17 00:00:00 2001 From: hawkfry Date: Sun, 15 Mar 2026 21:26:43 +0000 Subject: [PATCH 2/2] chore: add pull request template --- .github/PULL_REQUEST_TEMPLATE.md | 41 ++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..660018b --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,41 @@ + + +## Why are we changing this? + + + +## What has changed? + + + +## How to test it and expected results? + + + +## Checklist: + + + +- [ ] My pull request represents one logical piece of work. +- [ ] My commits are related to the pull request and look clean. +- [ ] My code follows our coding conventions. +- [ ] My code has appropriate tests and documentation.