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
61 changes: 57 additions & 4 deletions internal/oauth/callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net"
"net/http"
"sync"
"sync/atomic"
"time"
)

Expand All @@ -28,6 +29,13 @@ type callbackServer struct {
redirectURI string
state string
once sync.Once

// page is the server's own page for how the login went, if it has one.
page atomic.Pointer[resultPage]
// done is closed once the login has ended, after outcome is set.
done chan struct{}
outcome loginOutcome
ended sync.Once
}

// startCallbackServer binds the first available address in candidates (each a
Expand Down Expand Up @@ -61,6 +69,7 @@ func startCallbackServer(candidates []redirectTarget, state string) (*callbackSe
results: make(chan callbackResult, 1),
redirectURI: target.uri(),
state: state,
done: make(chan struct{}),
}

mux := http.NewServeMux()
Expand Down Expand Up @@ -106,20 +115,63 @@ func (c *callbackServer) handle(w http.ResponseWriter, r *http.Request) {
if description != "" {
message = fmt.Sprintf("%s: %s", errCode, description)
}
c.writePage(w, http.StatusOK, "Login failed", message)
outcome := loginOutcome{result: resultFailed, reason: reasonRefused}
if errCode == "access_denied" {
outcome = loginOutcome{result: resultDenied}
}
c.answer(w, r, outcome, http.StatusOK, "Login failed", message)
c.deliver(callbackResult{err: fmt.Errorf("authorization denied (%s)", message)})
return
}

code := query.Get("code")
if code == "" {
c.writePage(w, http.StatusBadRequest, "Login failed", "The login response contained no authorization code.")
c.answer(w, r, loginOutcome{result: resultFailed, reason: reasonRefused}, http.StatusBadRequest, "Login failed", "The login response contained no authorization code.")
c.deliver(callbackResult{err: fmt.Errorf("authorization response contained no code")})
return
}

c.writePage(w, http.StatusOK, "Signed in", "You can close this tab and return to your terminal.")
c.deliver(callbackResult{code: code})

// Nobody is signed in until the code is exchanged and the session stored,
// so the browser is not told before.
select {
case <-c.done:
case <-r.Context().Done():
return
}
if c.outcome.result == resultAuthorized {
c.answer(w, r, c.outcome, http.StatusOK, "Signed in", "You can close this tab and return to your terminal.")
} else {
c.answer(w, r, c.outcome, http.StatusOK, "Login failed", "Return to your terminal to see why.")
}
}

// ShowResultOn has the browser sent to page, when there is one, instead of
// being shown one from here.
func (c *callbackServer) ShowResultOn(page *resultPage) { c.page.Store(page) }

// Finish ends the login for the browser, which waits to be told how it went.
// Only the first call counts.
func (c *callbackServer) Finish(outcome loginOutcome) {
c.ended.Do(func() {
c.outcome = outcome
close(c.done)
})
}

// answer tells the browser how the login went: on the server's own page, or
// else with the heading and message here.
func (c *callbackServer) answer(w http.ResponseWriter, r *http.Request, outcome loginOutcome, status int, heading, message string) {
location := c.page.Load().address(outcome)
if location == "" {
c.writePage(w, status, heading, message)
return
}
// This address holds the authorization code.
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("Cache-Control", "no-store")
http.Redirect(w, r, location, http.StatusFound)
}

// deliver sends the first result and ignores any later ones, so a reloaded
Expand All @@ -140,8 +192,9 @@ func (c *callbackServer) Wait(ctx context.Context) (string, error) {
}

// Close shuts the server down, allowing in-flight responses a moment to reach
// the browser.
// the browser. One still waiting for the login to end is told that it failed.
func (c *callbackServer) Close() {
c.Finish(loginOutcome{result: resultFailed})
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = c.server.Shutdown(ctx)
Expand Down
5 changes: 4 additions & 1 deletion internal/oauth/login_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ type fakeAuthServer struct {
accessTokenTTL int64
rotateRefresh bool
promptValues []string // advertised as prompt_values_supported
resultURI string // advertised as authorization_result_uri
refuseCodes bool
}

type pendingCode struct {
Expand Down Expand Up @@ -79,6 +81,7 @@ func (f *fakeAuthServer) handleDiscovery(w http.ResponseWriter, r *http.Request)
ResponseTypesSupported: []string{"code"},
CodeChallengeMethodsSupported: []string{"S256"},
PromptValuesSupported: promptValues,
AuthorizationResultURI: f.resultURI,
})
}

Expand Down Expand Up @@ -155,7 +158,7 @@ func (f *fakeAuthServer) handleToken(w http.ResponseWriter, r *http.Request) {
switch r.PostForm.Get("grant_type") {
case "authorization_code":
pending, ok := f.codes[r.PostForm.Get("code")]
if !ok {
if !ok || f.refuseCodes {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_grant"})
return
}
Expand Down
3 changes: 3 additions & 0 deletions internal/oauth/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ type Metadata struct {
// endpoint accepts (OpenID Connect Prompt Create 1.0). Signup needs
// "create" here.
PromptValuesSupported []string `json:"prompt_values_supported"`
// AuthorizationResultURI is the server's own page for how a login went
// (not part of RFC 8414). Empty leaves the CLI to show its own.
AuthorizationResultURI string `json:"authorization_result_uri,omitempty"`
}

// fallbackMetadata mirrors the published document at
Expand Down
19 changes: 16 additions & 3 deletions internal/oauth/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func parseRedirectTarget(raw string) (redirectTarget, error) {
return redirectTarget{}, fmt.Errorf("redirect URI %q is not a loopback http URI", raw)
}
host := u.Hostname()
if host != "127.0.0.1" && host != "localhost" && host != "::1" {
if !isLoopbackHost(host) {
return redirectTarget{}, fmt.Errorf("redirect URI %q is not a loopback address", raw)
}
port, err := strconv.Atoi(u.Port())
Expand All @@ -124,6 +124,10 @@ func parseRedirectTarget(raw string) (redirectTarget, error) {
return redirectTarget{Host: host, Port: port, Path: path}, nil
}

func isLoopbackHost(host string) bool {
return host == "127.0.0.1" || host == "localhost" || host == "::1"
}

// settings resolves the issuer, resource, and any pre-registered client from
// the environment.
type settings struct {
Expand Down Expand Up @@ -247,6 +251,7 @@ func Login(ctx context.Context, getenv func(string) string, opts LoginOptions) (
return nil, err
}
defer callback.Close()
callback.ShowResultOn(newResultPage(md, client.ClientID, getenv, opts.OnAuthURL != nil))

scopes := opts.Scopes
if len(scopes) == 0 {
Expand Down Expand Up @@ -299,7 +304,15 @@ func Login(ctx context.Context, getenv func(string) string, opts LoginOptions) (
return nil, err
}

tok, err := exchangeCode(ctx, httpClient, md, client.ClientID, code, verifier.verifier, callback.RedirectURI(), cfg.Resource)
session, err := completeLogin(ctx, md, cfg, client.ClientID, code, verifier.verifier, callback.RedirectURI(), scopes)
// The browser is still waiting: the page it gets says how this went.
callback.Finish(outcomeOf(err))
return session, err
}

// completeLogin exchanges the authorization code and stores the session.
func completeLogin(ctx context.Context, md Metadata, cfg settings, clientID, code, verifier, redirectURI string, scopes []string) (*Session, error) {
tok, err := exchangeCode(ctx, httpClient, md, clientID, code, verifier, redirectURI, cfg.Resource)
if err != nil {
return nil, fmt.Errorf("exchange authorization code: %w", err)
}
Expand All @@ -308,7 +321,7 @@ func Login(ctx context.Context, getenv func(string) string, opts LoginOptions) (
session := &Session{
Issuer: md.Issuer,
TokenEndpoint: md.TokenEndpoint,
ClientID: client.ClientID,
ClientID: clientID,
Resource: cfg.Resource,
Scope: firstNonEmpty(tok.Scope, strings.Join(scopes, " ")),
TokenType: firstNonEmpty(tok.TokenType, "Bearer"),
Expand Down
133 changes: 133 additions & 0 deletions internal/oauth/resultpage.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// This file is not generated by Speakeasy — it is where 'vf auth login' sends
// the browser once it knows how sign-in went.
//
// The authorization server may host a page for that, named by
// authorization_result_uri in its metadata. It is told which of a few things
// happened and never words, names or links: the client's name and icon come
// from its registration. A server without one leaves the CLI to show its own
// page.

package oauth

import (
"errors"
"net/url"
)

// The outcomes the hosted page knows.
const (
resultAuthorized = "authorized"
resultDenied = "denied"
resultFailed = "failed"
)

// The reasons it gives for resultFailed.
const (
reasonRefused = "refused"
reasonUnreachable = "unreachable"
reasonNotSaved = "not_saved"
)

// What the person does next.
const (
nextContinue = "continue" // go back to the command, which carries on
nextClose = "close" // nothing: an agent is waiting on the command
)

// loginOutcome is how a login went, as far as the browser is told.
type loginOutcome struct {
result string
reason string
}

// outcomeOf is how a login that got its authorization code went.
func outcomeOf(err error) loginOutcome {
var tokErr *tokenError
switch {
case err == nil:
return loginOutcome{result: resultAuthorized}
case errors.Is(err, ErrStoreSession):
return loginOutcome{result: resultFailed, reason: reasonNotSaved}
case errors.As(err, &tokErr):
return loginOutcome{result: resultFailed, reason: reasonRefused}
default:
return loginOutcome{result: resultFailed, reason: reasonUnreachable}
}
}

// resultPage is the hosted page for one login.
type resultPage struct {
uri *url.URL
clientID string
place string
next string
returnTo string
}

// newResultPage returns the hosted page for a login, or nil when the server
// has none, or not one to send a browser to.
func newResultPage(md Metadata, clientID string, getenv func(string) string, agentMode bool) *resultPage {
uri, err := url.Parse(md.AuthorizationResultURI)
if err != nil || uri.Host == "" {
return nil
}
if uri.Scheme != "https" && (uri.Scheme != "http" || !isLoopbackHost(uri.Hostname())) {
return nil
}

page := &resultPage{uri: uri, clientID: clientID, next: nextContinue, returnTo: appHere(getenv)}
if agentMode {
page.next = nextClose
}
// Over SSH the browser is on another computer than the one signed in.
if getenv("SSH_CONNECTION") == "" {
page.place = "this_computer"
}
return page
}

// address is where the page says how the login went. A nil page has none.
func (p *resultPage) address(outcome loginOutcome) string {
if p == nil {
return ""
}

returnTo := p.returnTo
if returnTo == "" && outcome.result == resultAuthorized {
returnTo = "voiceflow"
}

uri := *p.uri
query := uri.Query()
for _, param := range [][2]string{
{"client_id", p.clientID},
{"result", outcome.result},
{"reason", outcome.reason},
{"place", p.place},
{"next", p.next},
{"return_to", returnTo},
} {
if param[1] != "" {
query.Set(param[0], param[1])
}
Comment on lines +110 to +112
}
uri.RawQuery = query.Encode()
return uri.String()
}

// appHere names the app the command runs in, when the hosted page has a link
// that brings it back to the front.
func appHere(getenv func(string) string) string {
switch {
case getenv("CLAUDE_CODE_ENTRYPOINT") == "claude-desktop":
return "claude"
case getenv("SSH_CONNECTION") != "":
return "" // an editor's link opens it on the browser's computer
Comment on lines +122 to +125
case getenv("CURSOR_TRACE_ID") != "":
return "cursor"
case getenv("__CFBundleIdentifier") == "com.microsoft.VSCode":
return "vscode"
default:
return ""
}
}
Loading
Loading