Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -1268,6 +1268,16 @@
}
}
}
},
"410": {
"description": "Error response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/openApiErrorSchema"
}
}
}
}
}
}
Expand Down
54 changes: 37 additions & 17 deletions internal/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"os/exec"
"runtime"
"strings"
"sync/atomic"
"time"

"github.com/Life-USTC/CLI/internal/config"
Expand Down Expand Up @@ -254,6 +255,35 @@ func callbackRedirectURI(addr net.Addr) string {
return fmt.Sprintf("http://%s/callback", addr.String())
}

type callbackResult struct {
code string
state string
err string
}

func oauthCallbackHandler(results chan<- callbackResult) http.HandlerFunc {
var delivered atomic.Bool
return func(w http.ResponseWriter, r *http.Request) {
if !delivered.CompareAndSwap(false, true) {
http.Error(w, "Authentication callback was already received. You can close this tab.", http.StatusConflict)
return
}
q := r.URL.Query()
result := callbackResult{code: q.Get("code"), state: q.Get("state"), err: q.Get("error")}
select {
case results <- result:
default:
http.Error(w, "Authentication callback could not be delivered. Return to the terminal and retry.", http.StatusServiceUnavailable)
return
}
if result.err != "" {
_, _ = w.Write([]byte("<html><body><h2>Authentication failed</h2><p>You can close this tab.</p></body></html>"))
return
}
_, _ = w.Write([]byte("<html><body><h2>Authentication successful!</h2><p>You can close this tab and return to the terminal.</p></body></html>"))
}
}

// Login runs the full OAuth2 Authorization Code + PKCE flow.
// Returns a credential to store.
func Login(server string) (*config.Credential, error) {
Expand All @@ -278,6 +308,7 @@ func Login(server string) (*config.Credential, error) {
if err != nil {
return nil, err
}
defer func() { _ = listener.Close() }()
redirectURI := callbackRedirectURI(listener.Addr())

// Register client
Expand Down Expand Up @@ -314,28 +345,17 @@ func Login(server string) (*config.Credential, error) {
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
)

// Channel for callback result
type callbackResult struct {
code string
state string
err string
}
ch := make(chan callbackResult, 1)

mux := http.NewServeMux()
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if e := q.Get("error"); e != "" {
ch <- callbackResult{err: e}
_, _ = w.Write([]byte("<html><body><h2>Authentication failed</h2><p>You can close this tab.</p></body></html>"))
return
}
ch <- callbackResult{code: q.Get("code"), state: q.Get("state")}
_, _ = w.Write([]byte("<html><body><h2>Authentication successful!</h2><p>You can close this tab and return to the terminal.</p></body></html>"))
})
mux.HandleFunc("/callback", oauthCallbackHandler(ch))
srv := &http.Server{Handler: mux}
go func() { _ = srv.Serve(listener) }()
defer func() { _ = srv.Shutdown(context.Background()) }()
defer func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = srv.Shutdown(shutdownCtx)
}()

// Open browser
fmt.Println()
Expand Down
48 changes: 48 additions & 0 deletions internal/auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"crypto/rand"
"crypto/rsa"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"testing"
Expand All @@ -13,6 +15,52 @@ import (
"github.com/go-jose/go-jose/v4/jwt"
)

func TestOAuthCallbackHandlerDeliversOnlyFirstRequest(t *testing.T) {
results := make(chan callbackResult, 1)
handler := oauthCallbackHandler(results)

first := httptest.NewRecorder()
handler(first, httptest.NewRequest(http.MethodGet, "/callback?code=first&state=state-1", nil))
if first.Code != http.StatusOK {
t.Fatalf("first status = %d", first.Code)
}
result := <-results
if result.code != "first" || result.state != "state-1" || result.err != "" {
t.Fatalf("result = %#v", result)
}

repeated := httptest.NewRecorder()
handler(repeated, httptest.NewRequest(http.MethodGet, "/callback?code=second&state=state-2", nil))
if repeated.Code != http.StatusConflict {
t.Fatalf("repeated status = %d, want %d", repeated.Code, http.StatusConflict)
}
select {
case extra := <-results:
t.Fatalf("unexpected repeated result: %#v", extra)
default:
}
}

func TestOAuthCallbackHandlerDoesNotBlockWhenResultBufferIsFull(t *testing.T) {
results := make(chan callbackResult, 1)
results <- callbackResult{code: "occupied"}
handler := oauthCallbackHandler(results)
done := make(chan struct{})
response := httptest.NewRecorder()
go func() {
handler(response, httptest.NewRequest(http.MethodGet, "/callback?error=denied", nil))
close(done)
}()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("callback handler blocked on a full result channel")
}
if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
}
}

func TestCallbackRedirectURIMatchesLoopbackListener(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
Expand Down
8 changes: 8 additions & 0 deletions internal/openapi/client.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading