-
Notifications
You must be signed in to change notification settings - Fork 13
Add an api:curl command as an authentication example usage
#261
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
Closed
Closed
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
6fd4e4e
feat(auth): introduce authenticated client in Go using the Legacy CLI
akalipetis 7e77910
feat: improve logging in the transport
akalipetis 85d89f2
feat: fix locking
akalipetis 37649cc
feat: simplify parsing of the JWT token
akalipetis c87c650
fixup! feat: simplify parsing of the JWT token
akalipetis de1283d
fix: handle error for token invalidation
akalipetis a82e1c2
fix: skip importing `go-jose` just for parsing a date
akalipetis 7bd0c7d
feat(auth): add an `api:curl` command as an authentication example usage
akalipetis 36fa1b4
feat: simplify the api:curl command
akalipetis 5cf91e8
fix: linting
akalipetis 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,207 @@ | ||
| package commands | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
|
|
||
| "github.com/spf13/cobra" | ||
|
|
||
| "github.com/platformsh/cli/internal/auth" | ||
| "github.com/platformsh/cli/internal/config" | ||
| ) | ||
|
|
||
| // newAPICurlCommand creates the `api:curl` command which performs an authenticated HTTP request | ||
| // against the configured API, using OAuth2 tokens from the credentials store and retrying once on 401. | ||
| func newAPICurlCommand(_ *config.Config) *cobra.Command { | ||
| var ( | ||
| method string | ||
| data string | ||
| jsonBody string | ||
| includeHeaders bool | ||
| headOnly bool | ||
| disableCompression bool | ||
| enableGlob bool // accepted for compatibility; no effect | ||
| failNoOutput bool | ||
| headerFlags []string | ||
| ) | ||
|
|
||
| cmd := &cobra.Command{ | ||
| Use: "api:curl [flags] [path]", | ||
| Short: "Run an authenticated cURL request on the Upsun API", | ||
| Args: cobra.RangeArgs(0, 1), | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| ctx := cmd.Context() | ||
| cfg := config.FromContext(ctx) | ||
|
|
||
| // Determine path/URL. | ||
| var target string | ||
| if len(args) > 0 { | ||
| target = args[0] | ||
| } else { | ||
| target = "/" | ||
| } | ||
|
|
||
| // Build absolute URL if a path was provided. | ||
| if !strings.HasPrefix(target, "http://") && !strings.HasPrefix(target, "https://") { | ||
| base := strings.TrimRight(cfg.API.BaseURL, "/") | ||
| if !strings.HasPrefix(target, "/") { | ||
| target = "/" + target | ||
| } | ||
| target = base + target | ||
| } | ||
|
|
||
| // Resolve method. | ||
| m := strings.ToUpper(strings.TrimSpace(method)) | ||
| if m == "" { | ||
| m = "GET" | ||
| } | ||
| if headOnly { | ||
| m = "HEAD" | ||
| } | ||
| if m == "GET" && (data != "" || jsonBody != "") { | ||
| m = "POST" | ||
| } | ||
| if data != "" && jsonBody != "" { | ||
| return fmt.Errorf("cannot use --data and --json together") | ||
| } | ||
|
|
||
| // Base transport: optionally disable compression. | ||
| baseRT := http.DefaultTransport | ||
| if t, ok := http.DefaultTransport.(*http.Transport); ok && disableCompression { | ||
| clone := t.Clone() | ||
| clone.DisableCompression = true | ||
| baseRT = clone | ||
| } | ||
|
|
||
| var httpClient *http.Client | ||
| // Use our retrying transport via NewClient and inject baseRT via context. | ||
| ctxWithRT := auth.WithTransport(ctx, baseRT) | ||
| legacyCLI := makeLegacyCLIWrapper(cfg, cmd.OutOrStdout(), cmd.ErrOrStderr(), cmd.InOrStdin()) | ||
| c, err := auth.NewLegacyCLIClient(ctxWithRT, legacyCLI) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| httpClient = c | ||
|
|
||
| // Build request. | ||
| var body io.Reader | ||
| if jsonBody != "" { | ||
| body = strings.NewReader(jsonBody) | ||
| } else if data != "" { | ||
| body = strings.NewReader(data) | ||
| } | ||
| req, err := http.NewRequestWithContext(ctx, m, target, body) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| // Set headers. | ||
| req.Header.Set("User-Agent", cfg.UserAgent()) | ||
| if jsonBody != "" { | ||
| req.Header.Set("Content-Type", "application/json") | ||
| } else if data != "" && req.Header.Get("Content-Type") == "" { | ||
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") | ||
| } | ||
| // Apply -H headers. | ||
| for _, h := range headerFlags { | ||
| h = strings.TrimSpace(h) | ||
| if h == "" { | ||
| continue | ||
| } | ||
| // Support "Name: value" and "Name=value" forms. | ||
| var name, value string | ||
| switch { | ||
| case strings.Contains(h, ":"): | ||
| parts := strings.SplitN(h, ":", 2) | ||
| name = strings.TrimSpace(parts[0]) | ||
| value = strings.TrimSpace(parts[1]) | ||
| case strings.Contains(h, "="): | ||
| parts := strings.SplitN(h, "=", 2) | ||
| name = strings.TrimSpace(parts[0]) | ||
| value = strings.TrimSpace(parts[1]) | ||
| default: | ||
| return fmt.Errorf("invalid header format: %q", h) | ||
| } | ||
| if name == "" { | ||
| return fmt.Errorf("invalid header: empty name in %q", h) | ||
| } | ||
| req.Header.Add(name, value) | ||
| } | ||
|
|
||
| // Execute request. | ||
| resp, err := httpClient.Do(req) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer func() { _ = resp.Body.Close() }() | ||
|
|
||
| // Handle -f/--fail behavior. | ||
| if failNoOutput && resp.StatusCode >= 400 { | ||
| return httpStatusError(target, resp) | ||
| } | ||
|
|
||
| // Output. | ||
| out := cmd.OutOrStdout() | ||
| // For HEAD requests, always show headers (like curl -I). For --include, add headers before body. | ||
| if includeHeaders || headOnly || strings.EqualFold(m, "HEAD") { | ||
| // Status line. | ||
| fmt.Fprintf(out, "%s %s\r\n", resp.Proto, resp.Status) | ||
| // Headers. | ||
| for k, vs := range resp.Header { | ||
| for _, v := range vs { | ||
| fmt.Fprintf(out, "%s: %s\r\n", k, v) | ||
| } | ||
| } | ||
| fmt.Fprint(out, "\r\n") | ||
| } | ||
|
|
||
| if !headOnly && !strings.EqualFold(m, "HEAD") { | ||
| if _, err := io.Copy(out, resp.Body); err != nil { | ||
| // Swallow broken pipe errors when piping output. | ||
| if !isBrokenPipe(err) { | ||
| return err | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return nil | ||
| }, | ||
| } | ||
|
|
||
| cmd.Flags().StringVarP(&method, "request", "X", "", "The request method to use") | ||
| cmd.Flags().StringVarP(&data, "data", "d", "", "Data to send") | ||
| cmd.Flags().StringVar(&jsonBody, "json", "", "JSON data to send") | ||
| cmd.Flags().BoolVarP(&includeHeaders, "include", "i", false, "Include headers in the output") | ||
| cmd.Flags().BoolVarP(&headOnly, "head", "I", false, "Fetch headers only") | ||
| cmd.Flags().BoolVar(&disableCompression, "disable-compression", false, "Do not request compressed responses") | ||
| cmd.Flags().BoolVar(&enableGlob, "enable-glob", false, "Enable curl globbing (no effect)") | ||
| cmd.Flags().BoolVarP(&failNoOutput, "fail", "f", false, "Fail with no output on an error response") | ||
| cmd.Flags().StringArrayVarP(&headerFlags, "header", "H", nil, "Extra header(s) (multiple values allowed)") | ||
|
|
||
| return cmd | ||
| } | ||
|
|
||
| func isBrokenPipe(err error) bool { | ||
| if err == nil { | ||
| return false | ||
| } | ||
| // This is a heuristic; on macOS broken pipe often contains this substring. | ||
| return strings.Contains(strings.ToLower(err.Error()), "broken pipe") | ||
| } | ||
|
|
||
| // httpStatusError renders a minimal error similar to curl -f behavior. | ||
| func httpStatusError(u string, resp *http.Response) error { | ||
| // Try to display a concise error with status and URL path. | ||
| parsed, _ := url.Parse(u) | ||
| target := u | ||
| if parsed != nil { | ||
| target = parsed.String() | ||
| } | ||
| // Do not dump body. | ||
| _, _ = io.Copy(io.Discard, resp.Body) | ||
| _ = resp.Body.Close() | ||
| return fmt.Errorf("server returned HTTP %d for %s", resp.StatusCode, target) | ||
| } | ||
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
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,40 @@ | ||
| package auth | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "log" | ||
| "net/http" | ||
| "os" | ||
|
|
||
| "golang.org/x/oauth2" | ||
|
|
||
| "github.com/platformsh/cli/internal/legacy" | ||
| ) | ||
|
|
||
| func NewLegacyCLIClient(ctx context.Context, wrapper *legacy.CLIWrapper) (*http.Client, error) { | ||
| ts, err := NewLegacyCLITokenSource(ctx, wrapper) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("oauth2: create token source: %w", err) | ||
| } | ||
|
|
||
| refresher, ok := ts.(refresher) | ||
| if !ok { | ||
| return nil, fmt.Errorf("token source does not implement refresher") | ||
| } | ||
| baseRT := http.DefaultTransport | ||
| if rt, ok := TransportFromContext(ctx); ok && rt != nil { | ||
| baseRT = rt | ||
| } | ||
| return &http.Client{ | ||
| Transport: &Transport{ | ||
| refresher: refresher, | ||
| base: &oauth2.Transport{ | ||
| Source: ts, | ||
| Base: baseRT, | ||
| }, | ||
| wrapper: wrapper, | ||
| logger: log.New(os.Stderr, "", 0), | ||
| }, | ||
| }, nil | ||
| } |
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,42 @@ | ||
| package auth | ||
|
|
||
| import ( | ||
| "encoding/base64" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "strings" | ||
| "time" | ||
| ) | ||
|
|
||
| // unsafeGetJWTExpiry parses a JWT without verifying its signature and returns its expiry time. | ||
| // WARNING: This is intentionally unsafe and must not be used for trust decisions. | ||
| func unsafeGetJWTExpiry(token string) (time.Time, error) { | ||
| if token == "" { | ||
| return time.Time{}, errors.New("jwt: empty token") | ||
| } | ||
| parts := strings.Split(token, ".") | ||
| if len(parts) < 2 { | ||
| return time.Time{}, fmt.Errorf("jwt: malformed token, expected 3 parts, got %d", len(parts)) | ||
| } | ||
| payloadSeg := parts[1] | ||
|
|
||
| // Base64 URL decode without padding as per RFC 7515. | ||
| payloadBytes, err := base64.RawURLEncoding.DecodeString(payloadSeg) | ||
| if err != nil { | ||
| return time.Time{}, fmt.Errorf("jwt: decode payload: %w", err) | ||
| } | ||
|
|
||
| var claims struct { | ||
| ExpiresAt *int64 `json:"exp,omitempty"` | ||
| } | ||
| if err := json.Unmarshal(payloadBytes, &claims); err != nil { | ||
| return time.Time{}, fmt.Errorf("jwt: unmarshal claims: %w", err) | ||
| } | ||
|
|
||
| if claims.ExpiresAt == nil { | ||
| return time.Time{}, errors.New("jwt: no expiry time found") | ||
| } | ||
|
|
||
| return time.Unix(*claims.ExpiresAt, 0), 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.
Just a note - this is good for testing, but the old command actually invoked
curl, whereas this is pure Go, so it may need a different name if it's ultimately wanted as a feature.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.
Sure! This is only to be used as an example command to test the client created in #260 - I won't keep this afterwards.