Skip to content
Open
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
11 changes: 10 additions & 1 deletion internal/pkg/cli/command/auth/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ var (

func NewLoginCmd() *cobra.Command {
var jsonOutput bool
var orgId string

cmd := &cobra.Command{
Use: "login",
Expand All @@ -58,6 +59,9 @@ func NewLoginCmd() *cobra.Command {
# Interactive login (opens a browser)
pc auth login

# Login scoped to a specific organization (enables SSO routing)
pc auth login --org "ORG_ID"

# Agentic login — first call returns a pending URL
pc auth login --json

Expand All @@ -66,11 +70,16 @@ func NewLoginCmd() *cobra.Command {
`),
GroupID: help.GROUP_AUTH.ID,
Run: func(cmd *cobra.Command, args []string) {
login.Run(cmd.Context(), login.Options{Json: jsonOutput})
opts := login.Options{Json: jsonOutput}
if cmd.Flags().Changed("org") {
opts.OrgId = &orgId
}
login.Run(cmd.Context(), opts)
},
}

cmd.Flags().BoolVarP(&jsonOutput, "json", "j", false, "emit JSON output")
cmd.Flags().StringVar(&orgId, "org", "", "Organization ID to authenticate into (enables SSO routing for organizations with SSO enforced)")

return cmd
}
11 changes: 10 additions & 1 deletion internal/pkg/cli/command/login/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ var (

func NewLoginCmd() *cobra.Command {
var jsonOutput bool
var orgId string

cmd := &cobra.Command{
Use: "login",
Expand All @@ -50,6 +51,9 @@ func NewLoginCmd() *cobra.Command {
# Interactive login (opens a browser)
pc login

# Login scoped to a specific organization (enables SSO routing)
pc login --org "ORG_ID"

# Agentic login — first call returns a pending URL
pc login --json

Expand All @@ -58,11 +62,16 @@ func NewLoginCmd() *cobra.Command {
`),
GroupID: help.GROUP_AUTH.ID,
Run: func(cmd *cobra.Command, args []string) {
login.Run(cmd.Context(), login.Options{Json: jsonOutput})
opts := login.Options{Json: jsonOutput}
if cmd.Flags().Changed("org") {
opts.OrgId = &orgId
}
login.Run(cmd.Context(), opts)
},
}

cmd.Flags().BoolVarP(&jsonOutput, "json", "j", false, "emit JSON output")
cmd.Flags().StringVar(&orgId, "org", "", "Organization ID to authenticate into (enables SSO routing for organizations with SSO enforced)")

return cmd
}
10 changes: 8 additions & 2 deletions internal/pkg/cli/command/target/target.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,11 @@ func NewTargetCmd() *cobra.Command {

// If the org chosen differs from the current orgId in the token, we need to login again
if currentTokenOrgId != "" && currentTokenOrgId != targetOrg.Id {
// Fetch SSO connection while the current token is still valid,
// before logout clears it.
ssoConn := login.ResolveSSOConnection(ctx, targetOrg.Id)
oauth.Logout()
err = login.GetAndSetAccessToken(ctx, &targetOrg.Id, login.Options{Json: options.json, Wait: true})
err = login.GetAndSetAccessToken(ctx, &targetOrg.Id, login.Options{Json: options.json, Wait: true, SSOConnection: ssoConn})
if err != nil {
msg.FailJSON(options.json, "Failed to get access token: %s", err)
exit.Error(err, "Error getting access token")
Expand Down Expand Up @@ -245,8 +248,11 @@ func NewTargetCmd() *cobra.Command {

// If the org chosen differs from the current orgId in the token, we need to login again
if currentTokenOrgId != org.Id {
// Fetch SSO connection while the current token is still valid,
// before logout clears it.
ssoConn := login.ResolveSSOConnection(ctx, org.Id)
oauth.Logout()
err = login.GetAndSetAccessToken(ctx, &org.Id, login.Options{Json: options.json, Wait: true})
err = login.GetAndSetAccessToken(ctx, &org.Id, login.Options{Json: options.json, Wait: true, SSOConnection: ssoConn})
if err != nil {
msg.FailJSON(options.json, "Failed to get access token: %s", err)
exit.Error(err, "Error getting access token")
Expand Down
68 changes: 46 additions & 22 deletions internal/pkg/utils/login/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ type Options struct {
// RunPostAuthSetup is not called in Wait mode; the caller is responsible
// for any post-auth state setup and output.
Wait bool
// OrgId pins the login flow to a specific organization.
OrgId *string
// SSOConnection is the Auth0 connection name to pass as `connection=` in the
// authorization URL, routing the browser directly to the org's IdP.
// Callers that hold a valid token before clearing credentials (e.g. pc target)
// should resolve this with FetchSSOConnection before logout, then pass it here.
SSOConnection *string
}

func Run(ctx context.Context, opts Options) {
Expand All @@ -62,7 +69,7 @@ func Run(ctx context.Context, opts Options) {
exit.Error(err, "Error checking for existing auth session")
}
if sess != nil {
if err := getAndSetAccessTokenJSON(ctx, nil, false, sess, result); err != nil {
if err := getAndSetAccessTokenJSON(ctx, opts.OrgId, false, opts.SSOConnection, sess, result); err != nil {
msg.FailMsg("Error acquiring access token while logging in: %s", err)
exit.Error(err, "Error acquiring access token while logging in")
}
Expand All @@ -80,26 +87,43 @@ func Run(ctx context.Context, opts Options) {
}

if !expired && token != nil && token.AccessToken != "" {
if opts.Json {
claims, err := oauth.ParseClaimsUnverified(token)
if err == nil {
fmt.Fprintln(os.Stdout, text.IndentJSON(struct {
Status string `json:"status"`
Email string `json:"email"`
OrgId string `json:"org_id"`
}{Status: "already_authenticated", Email: claims.Email, OrgId: claims.OrgId}))
} else {
fmt.Fprintln(os.Stdout, text.IndentJSON(struct {
Status string `json:"status"`
}{Status: "already_authenticated"}))
// If --org targets a different organization, re-authenticate now while
// the token is still valid so we can look up the SSO connection before
// clearing credentials.
differentOrg := false
if opts.OrgId != nil && *opts.OrgId != "" {
if claims, claimsErr := oauth.ParseClaimsUnverified(token); claimsErr == nil {
differentOrg = claims.OrgId != *opts.OrgId
}
}

if differentOrg {
opts.SSOConnection = ResolveSSOConnection(ctx, *opts.OrgId)
oauth.Logout()
// Fall through to GetAndSetAccessToken.
} else {
msg.WarnMsg("You are already logged in. Please log out first using %s.", style.Code("pc auth logout"))
// Same org (or no --org flag) — show "already logged in".
if opts.Json {
claims, err := oauth.ParseClaimsUnverified(token)
if err == nil {
fmt.Fprintln(os.Stdout, text.IndentJSON(struct {
Status string `json:"status"`
Email string `json:"email"`
OrgId string `json:"org_id"`
}{Status: "already_authenticated", Email: claims.Email, OrgId: claims.OrgId}))
} else {
fmt.Fprintln(os.Stdout, text.IndentJSON(struct {
Status string `json:"status"`
}{Status: "already_authenticated"}))
}
} else {
msg.WarnMsg("You are already logged in. Please log out first using %s.", style.Code("pc auth logout"))
}
return
}
return
}

err = GetAndSetAccessToken(ctx, nil, opts)
err = GetAndSetAccessToken(ctx, opts.OrgId, opts)
if err != nil {
msg.FailMsg("Error acquiring access token while logging in: %s", err)
exit.Error(err, "Error acquiring access token while logging in")
Expand Down Expand Up @@ -188,9 +212,9 @@ func GetAndSetAccessToken(ctx context.Context, orgId *string, opts Options) erro
// a terminal (agentic context), always use the JSON/daemon path.
opts.Json = opts.Json || !term.IsTerminal(int(os.Stdout.Fd()))
if opts.Json {
return getAndSetAccessTokenJSON(ctx, orgId, opts.Wait, nil, nil)
return getAndSetAccessTokenJSON(ctx, orgId, opts.Wait, opts.SSOConnection, nil, nil)
}
return getAndSetAccessTokenInteractive(ctx, orgId)
return getAndSetAccessTokenInteractive(ctx, orgId, opts.SSOConnection)
}

// getAndSetAccessTokenJSON is the agentic path: daemon-backed, non-blocking on stdin.
Expand All @@ -203,7 +227,7 @@ func GetAndSetAccessToken(ctx context.Context, orgId *string, opts Options) erro
// When wait is true (for callers like pc target that need a token on return): spawns
// daemon, blocks until auth completes, and returns with the token stored. RunPostAuthSetup
// is not called; the caller owns post-auth state and output.
func getAndSetAccessTokenJSON(ctx context.Context, orgId *string, wait bool, sess *SessionState, result *SessionResult) error {
func getAndSetAccessTokenJSON(ctx context.Context, orgId *string, wait bool, ssoConnection *string, sess *SessionState, result *SessionResult) error {
if sess == nil {
// No pre-fetched session — look one up now.
var err error
Expand Down Expand Up @@ -238,7 +262,7 @@ func getAndSetAccessTokenJSON(ctx context.Context, orgId *string, wait bool, ses
return fmt.Errorf("error creating new auth verifier and challenge: %w", err)
}

authURL, err := a.GetAuthURL(ctx, csrfState, challenge, orgId)
authURL, err := a.GetAuthURL(ctx, csrfState, challenge, orgId, ssoConnection)
if err != nil {
return fmt.Errorf("error getting auth URL: %w", err)
}
Expand Down Expand Up @@ -370,7 +394,7 @@ func printPendingJSON(authURL, sessionId string) {

// getAndSetAccessTokenInteractive is the original interactive path: inline callback server,
// optional [Enter]-to-open-browser prompt when stdin is a TTY.
func getAndSetAccessTokenInteractive(ctx context.Context, orgId *string) error {
func getAndSetAccessTokenInteractive(ctx context.Context, orgId *string, ssoConnection *string) error {
// If a daemon from a prior JSON-mode login exists, check whether it has
// already finished before deciding whether to block interactive login.
sess, result, err := findResumableSession()
Expand Down Expand Up @@ -398,7 +422,7 @@ func getAndSetAccessTokenInteractive(ctx context.Context, orgId *string) error {
return fmt.Errorf("error creating new auth verifier and challenge: %w", err)
}

authURL, err := a.GetAuthURL(ctx, csrfState, challenge, orgId)
authURL, err := a.GetAuthURL(ctx, csrfState, challenge, orgId, ssoConnection)
if err != nil {
return fmt.Errorf("error getting auth URL: %w", err)
}
Expand Down
105 changes: 105 additions & 0 deletions internal/pkg/utils/login/sso.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package login

import (
"context"
"encoding/json"
"io"
"net/http"

"github.com/pinecone-io/cli/internal/pkg/utils/configuration/config"
"github.com/pinecone-io/cli/internal/pkg/utils/environment"
"github.com/pinecone-io/cli/internal/pkg/utils/log"
"github.com/pinecone-io/cli/internal/pkg/utils/oauth"
)

// dashboardOrg is the subset of the dashboard API org response needed for SSO lookup.
type dashboardOrg struct {
Id string `json:"id"`
SSOConnectionName string `json:"sso_connection_name"`
EnforceSSO bool `json:"enforce_sso_authentication"`
}

type dashboardOrgsResponse struct {
NewOrgs []dashboardOrg `json:"newOrgs"`
}

// ResolveSSOConnection is a convenience wrapper around FetchSSOConnection that
// returns a pointer to the connection name when SSO is enforced for the org, or
// nil otherwise. Errors are logged at debug level and treated as "no SSO".
func ResolveSSOConnection(ctx context.Context, orgId string) *string {
conn, err := FetchSSOConnection(ctx, orgId)
if err != nil {
log.Debug().Err(err).Str("orgId", orgId).Msg("SSO connection lookup failed, proceeding without connection param")
}
if conn == "" {
return nil
}
return &conn
}

// FetchSSOConnection calls the private dashboard API to retrieve the Auth0
// connection name for the given orgId. It returns ("", nil) when the org has
// no SSO configured, enforce_sso_authentication is false, or any error occurs.
// Errors are non-fatal: the caller should proceed with a normal login URL.
func FetchSSOConnection(ctx context.Context, orgId string) (string, error) {
token, err := oauth.Token(ctx)
if err != nil || token == nil || token.AccessToken == "" {
log.Debug().Str("orgId", orgId).Msg("SSO lookup skipped: no valid token available")
return "", nil
}

envConfig, err := environment.GetEnvConfig(config.Environment.Get())
if err != nil {
return "", nil
}

return fetchSSOConnectionFromURL(ctx, orgId, token.AccessToken, http.DefaultClient, envConfig.DashboardUrl)
}

// fetchSSOConnectionFromURL is the testable core: it takes an explicit HTTP
// client and dashboard base URL so tests can inject a local httptest.Server.
func fetchSSOConnectionFromURL(ctx context.Context, orgId string, accessToken string, client *http.Client, dashboardURL string) (string, error) {
url := dashboardURL + "/v2/dashboard/organizations"
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", nil
}
req.Header.Set("Authorization", "Bearer "+accessToken)

resp, err := client.Do(req)
if err != nil {
log.Debug().Err(err).Str("orgId", orgId).Msg("SSO lookup: dashboard API request failed")
return "", nil
}
defer resp.Body.Close()

if resp.StatusCode < 200 || resp.StatusCode >= 300 {
log.Debug().Int("status", resp.StatusCode).Str("orgId", orgId).Msg("SSO lookup: dashboard API returned non-2xx")
return "", nil
}

body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
log.Debug().Err(err).Str("orgId", orgId).Msg("SSO lookup: failed to read dashboard API response")
return "", nil
}

var orgsResp dashboardOrgsResponse
if err := json.Unmarshal(body, &orgsResp); err != nil {
log.Debug().Err(err).Str("orgId", orgId).Msg("SSO lookup: failed to decode dashboard API response")
return "", nil
}

for _, org := range orgsResp.NewOrgs {
if org.Id == orgId {
if org.EnforceSSO && org.SSOConnectionName != "" {
log.Debug().Str("orgId", orgId).Str("connection", org.SSOConnectionName).Msg("SSO lookup: found connection")
return org.SSOConnectionName, nil
}
return "", nil
}
}

log.Debug().Str("orgId", orgId).Msg("SSO lookup: org not found in dashboard response")
return "", nil
}
Loading
Loading