-
Notifications
You must be signed in to change notification settings - Fork 2
feat(api, cmd): Add PKCE-based authentication flow with CLI integration and tests #79
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
tiulpin
wants to merge
1
commit into
main
Choose a base branch
from
tv/pkce
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,223 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "context" | ||
| "crypto/rand" | ||
| "crypto/sha256" | ||
| "encoding/base64" | ||
| "encoding/json" | ||
| "fmt" | ||
| "html" | ||
| "io" | ||
| "net" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
| "time" | ||
| ) | ||
|
|
||
| const ( | ||
| PkceIsEnabledPath = "/pkce/is_enabled.html" | ||
| PkceAuthorizePath = "/pkce/authorize.html" | ||
| PkceTokenPath = "/pkce/token.html" | ||
| CodeChallengeMethod = "S256" | ||
| DefaultCallbackPath = "/callback" | ||
| CallbackPortMin = 19000 | ||
| CallbackPortMax = 19100 | ||
| maxResponseBody = 64 * 1024 | ||
| ) | ||
|
|
||
| // AvailableScopes lists permissions to request via PKCE. | ||
| // The server filters these to only grant what it allows. | ||
| var AvailableScopes = []string{ | ||
| // View (read-only) | ||
| "VIEW_PROJECT", | ||
| "VIEW_BUILD_CONFIGURATION_SETTINGS", | ||
| "VIEW_AGENT_DETAILS", | ||
|
|
||
| // Builds | ||
| "RUN_BUILD", | ||
| "CANCEL_BUILD", | ||
| "TAG_BUILD", | ||
| "COMMENT_BUILD", | ||
| "PIN_UNPIN_BUILD", | ||
| "REORDER_BUILD_QUEUE", | ||
| "PATCH_BUILD_SOURCES", | ||
|
|
||
| // Jobs | ||
| "PAUSE_ACTIVATE_BUILD_CONFIGURATION", | ||
|
|
||
| // Projects (EDIT_PROJECT also covers build configuration editing) | ||
| "EDIT_PROJECT", | ||
|
|
||
| // Agents | ||
| "ENABLE_DISABLE_AGENT", | ||
| "AUTHORIZE_AGENT", | ||
| "ADMINISTER_AGENT", | ||
| "CONNECT_TO_AGENT", | ||
|
|
||
| // Pools | ||
| "MANAGE_AGENT_POOLS", | ||
| } | ||
|
|
||
| type TokenResponse struct { | ||
| AccessToken string `json:"access_token"` | ||
| TokenType string `json:"token_type"` | ||
| ValidUntil string `json:"valid_until"` | ||
| } | ||
|
|
||
| type CallbackResult struct { | ||
| Code string | ||
| State string | ||
| Error string | ||
| } | ||
|
|
||
| type CallbackServer struct { | ||
| Port int | ||
| ResultChan chan CallbackResult | ||
| server *http.Server | ||
| listener net.Listener | ||
| } | ||
|
|
||
| func GenerateCodeVerifier() (string, error) { | ||
| b := make([]byte, 32) | ||
| if _, err := rand.Read(b); err != nil { | ||
| return "", fmt.Errorf("generate random bytes: %w", err) | ||
| } | ||
| return base64.RawURLEncoding.EncodeToString(b), nil | ||
| } | ||
|
|
||
| func GenerateCodeChallenge(verifier string) string { | ||
| h := sha256.Sum256([]byte(verifier)) | ||
| return base64.RawURLEncoding.EncodeToString(h[:]) | ||
| } | ||
|
|
||
| func GenerateState() (string, error) { | ||
| b := make([]byte, 16) | ||
| if _, err := rand.Read(b); err != nil { | ||
| return "", fmt.Errorf("generate random bytes: %w", err) | ||
| } | ||
| return base64.RawURLEncoding.EncodeToString(b), nil | ||
| } | ||
|
|
||
| func BuildAuthorizeURL(serverURL, redirectURI, challenge, state string, scopes []string) string { | ||
| params := url.Values{} | ||
| params.Set("response_type", "code") | ||
| params.Set("redirect_uri", redirectURI) | ||
| params.Set("code_challenge", challenge) | ||
| params.Set("code_challenge_method", CodeChallengeMethod) | ||
| params.Set("state", state) | ||
| params.Set("scope", strings.Join(scopes, " ")) | ||
| return strings.TrimSuffix(serverURL, "/") + PkceAuthorizePath + "?" + params.Encode() | ||
| } | ||
|
|
||
| func FindAvailableListener() (net.Listener, int, error) { | ||
| for port := CallbackPortMin; port <= CallbackPortMax; port++ { | ||
| if l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port)); err == nil { | ||
| return l, port, nil | ||
| } | ||
| } | ||
| return nil, 0, fmt.Errorf("no available port in range %d-%d", CallbackPortMin, CallbackPortMax) | ||
| } | ||
|
|
||
| func IsPkceEnabled(ctx context.Context, serverURL string) (bool, error) { | ||
| req, err := http.NewRequestWithContext(ctx, "POST", strings.TrimSuffix(serverURL, "/")+PkceIsEnabledPath, nil) | ||
| if err != nil { | ||
| return false, err | ||
| } | ||
| resp, err := http.DefaultClient.Do(req) | ||
| if err != nil { | ||
| return false, fmt.Errorf("check PKCE status: %w", err) | ||
| } | ||
| defer func() { _ = resp.Body.Close() }() | ||
| return resp.StatusCode == http.StatusOK, nil | ||
| } | ||
|
|
||
| func NewCallbackServer(listener net.Listener, port int) *CallbackServer { | ||
| return &CallbackServer{ | ||
| Port: port, | ||
| ResultChan: make(chan CallbackResult, 1), | ||
| listener: listener, | ||
| } | ||
| } | ||
|
|
||
| func (cs *CallbackServer) Start() { | ||
| mux := http.NewServeMux() | ||
| mux.HandleFunc(DefaultCallbackPath, cs.handleCallback) | ||
| cs.server = &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second} | ||
| go func() { _ = cs.server.Serve(cs.listener) }() | ||
| } | ||
|
|
||
| func (cs *CallbackServer) handleCallback(w http.ResponseWriter, r *http.Request) { | ||
| q := r.URL.Query() | ||
| result := CallbackResult{Code: q.Get("code"), State: q.Get("state"), Error: q.Get("error")} | ||
|
|
||
| w.Header().Set("Content-Type", "text/html; charset=utf-8") | ||
| w.Header().Set("X-Content-Type-Options", "nosniff") | ||
| w.Header().Set("X-Frame-Options", "DENY") | ||
| w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'") | ||
|
|
||
| if result.Error != "" { | ||
| w.WriteHeader(http.StatusBadRequest) | ||
| _, _ = fmt.Fprintf(w, `<!DOCTYPE html><html><head><title>TeamCity CLI</title> | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Curious, is it normal to embed HTML like this? Maybe some template engine could be used, or do you think it's overkill in this case? |
||
| <style>body{font-family:system-ui,sans-serif;text-align:center;padding:50px}</style></head><body> | ||
| <h1 style="color:#ef4444">✗ Authentication failed</h1><p>Error: %s</p> | ||
| <p>Please return to the terminal.</p></body></html>`, html.EscapeString(result.Error)) | ||
| } else { | ||
| _, _ = fmt.Fprint(w, `<!DOCTYPE html><html><head><title>TeamCity CLI</title> | ||
| <style>body{font-family:system-ui,sans-serif;text-align:center;padding:50px}</style></head><body> | ||
| <h1 style="color:#22c55e">✓ Authentication successful!</h1> | ||
| <p>You can close this window and return to the terminal.</p> | ||
| <script>setTimeout(function(){window.close()},2000)</script></body></html>`) | ||
| } | ||
|
|
||
| select { | ||
| case cs.ResultChan <- result: | ||
| default: | ||
| } | ||
| } | ||
|
|
||
| func (cs *CallbackServer) Shutdown() { | ||
| if cs.server != nil { | ||
| ctx, cancel := context.WithTimeout(context.Background(), time.Second) | ||
| defer cancel() | ||
| _ = cs.server.Shutdown(ctx) | ||
| } | ||
| } | ||
|
|
||
| func DefaultScopes() []string { | ||
| return append([]string{}, AvailableScopes...) | ||
| } | ||
|
|
||
| func ExchangeCodeForToken(ctx context.Context, serverURL, code, verifier, redirectURI string) (*TokenResponse, error) { | ||
| data := url.Values{} | ||
| data.Set("code", code) | ||
| data.Set("code_verifier", verifier) | ||
| data.Set("redirect_uri", redirectURI) | ||
|
|
||
| req, err := http.NewRequestWithContext(ctx, "POST", strings.TrimSuffix(serverURL, "/")+PkceTokenPath, strings.NewReader(data.Encode())) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") | ||
|
|
||
| resp, err := http.DefaultClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("token request: %w", err) | ||
| } | ||
| defer func() { _ = resp.Body.Close() }() | ||
|
|
||
| body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBody)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("read response: %w", err) | ||
| } | ||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("token exchange failed (status %d): %s", resp.StatusCode, body) | ||
| } | ||
|
|
||
| var tokenResp TokenResponse | ||
| if err := json.Unmarshal(body, &tokenResp); err != nil { | ||
| return nil, fmt.Errorf("decode token response: %w", err) | ||
| } | ||
| return &tokenResp, nil | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am a bit worried that we're having a list of permissions embedded here. I think it would be better to have a REST API endpoint on TeamCity side which would provide this list.