-
Notifications
You must be signed in to change notification settings - Fork 439
fix(cli): implement PKCE for secretless OAuth authorization-code login #3460
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
Merged
mergify
merged 2 commits into
mvanhorn:main
from
rob-coco:fix/oauth-pkce-secretless-login
Jul 6, 2026
+1,757
−4
Merged
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| package generator | ||
|
|
||
| import ( | ||
| "os" | ||
| "os/exec" | ||
| "path/filepath" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/mvanhorn/cli-printing-press/v4/internal/spec" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestOAuthLoginUsesPKCEWhenNoClientSecret(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| apiSpec := minimalSpec("oauth-pkce-login") | ||
| apiSpec.Auth = spec.AuthConfig{ | ||
| Type: "oauth2", | ||
| Header: "Authorization", | ||
| Format: "Bearer {token}", | ||
| OAuth2Grant: spec.OAuth2GrantAuthorizationCode, | ||
| AuthorizationURL: "https://accounts.example.com/oauth/authorize", | ||
| TokenURL: "https://accounts.example.com/oauth/token", | ||
| KeyURL: "https://console.example.com/oauth", | ||
| } | ||
|
|
||
| outputDir := filepath.Join(t.TempDir(), "oauth-pkce-login-pp-cli") | ||
| require.NoError(t, New(apiSpec, outputDir).Generate()) | ||
|
|
||
| authSrc, err := os.ReadFile(filepath.Join(outputDir, "internal", "cli", "auth.go")) | ||
| require.NoError(t, err) | ||
| auth := string(authSrc) | ||
|
|
||
| // Authorize request carries an S256 challenge on the secretless path. | ||
| require.Contains(t, auth, "codeVerifier, err = generatePKCEVerifier()") | ||
| require.Contains(t, auth, `params.Set("code_challenge", pkceCodeChallengeS256(codeVerifier))`) | ||
| require.Contains(t, auth, `params.Set("code_challenge_method", "S256")`) | ||
|
|
||
| // Token exchange authenticates with exactly one of client_secret or | ||
| // code_verifier (mutual exclusivity is validated behaviorally below); | ||
| // the bare authorization_code grant is gone. | ||
| require.Contains(t, auth, `tokenParams.Set("client_secret", clientSecret)`) | ||
| require.Contains(t, auth, `tokenParams.Set("code_verifier", codeVerifier)`) | ||
|
|
||
| // RFC 8252 loopback redirect: IP literal, never "localhost". | ||
| require.Contains(t, auth, `redirectURI := fmt.Sprintf("http://127.0.0.1:%d/callback"`) | ||
| require.NotContains(t, auth, `http://localhost:%d/callback`) | ||
|
|
||
| binPath := filepath.Join(outputDir, "oauth-pkce-login-pp-cli") | ||
| runGoCommand(t, outputDir, "build", "-o", binPath, "./cmd/oauth-pkce-login-pp-cli") | ||
|
|
||
| // Under verify-env the command prints the authorize URL it would launch; | ||
| // use that to assert live flag→params behavior without opening a browser | ||
| // or binding assumptions about the callback port. | ||
| runVerifyLogin := func(extraArgs ...string) string { | ||
| args := append([]string{"--config", filepath.Join(t.TempDir(), "config.toml"), "login", "--client-id", "test-client"}, extraArgs...) | ||
| cmd := exec.Command(binPath, args...) | ||
| cmd.Env = append(os.Environ(), "PRINTING_PRESS_VERIFY=1") | ||
| out, err := cmd.CombinedOutput() | ||
| require.NoError(t, err, "verify-env login failed: %s", string(out)) | ||
| return string(out) | ||
| } | ||
|
|
||
| secretless := runVerifyLogin() | ||
| require.Contains(t, secretless, "would launch:") | ||
| require.Contains(t, secretless, "code_challenge=") | ||
| require.Contains(t, secretless, "code_challenge_method=S256") | ||
| require.Contains(t, secretless, "127.0.0.1%3A8085%2Fcallback") | ||
| require.NotContains(t, secretless, "localhost") | ||
|
|
||
| withSecret := runVerifyLogin("--client-secret", "test-secret") | ||
| require.Contains(t, withSecret, "would launch:") | ||
| require.NotContains(t, withSecret, "code_challenge") | ||
|
|
||
| const runtimeTest = `package cli | ||
|
|
||
| import ( | ||
| "strings" | ||
| "testing" | ||
| ) | ||
|
|
||
| // Vector from RFC 7636 appendix B. | ||
| func TestPKCECodeChallengeS256MatchesRFC7636Vector(t *testing.T) { | ||
| const verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" | ||
| const want = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" | ||
| if got := pkceCodeChallengeS256(verifier); got != want { | ||
| t.Fatalf("pkceCodeChallengeS256() = %q, want %q", got, want) | ||
| } | ||
| } | ||
|
|
||
| func TestGeneratePKCEVerifierShapeAndUniqueness(t *testing.T) { | ||
| const unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" | ||
| first, err := generatePKCEVerifier() | ||
| if err != nil { | ||
| t.Fatalf("generatePKCEVerifier() error = %v", err) | ||
| } | ||
| if len(first) != 43 { | ||
| t.Fatalf("verifier length = %d, want 43", len(first)) | ||
| } | ||
| for _, r := range first { | ||
| if !strings.ContainsRune(unreserved, r) { | ||
| t.Fatalf("verifier contains %q, outside RFC 7636 unreserved set", r) | ||
| } | ||
| } | ||
| second, err := generatePKCEVerifier() | ||
| if err != nil { | ||
| t.Fatalf("generatePKCEVerifier() second call error = %v", err) | ||
| } | ||
| if first == second { | ||
| t.Fatalf("two verifiers are identical: %q", first) | ||
| } | ||
| } | ||
| ` | ||
| require.NoError(t, os.WriteFile(filepath.Join(outputDir, "internal", "cli", "oauth_pkce_test.go"), []byte(runtimeTest), 0o644)) | ||
| runGoCommand(t, outputDir, "test", "-race", "./internal/cli", "-run", "Test(PKCECodeChallengeS256|GeneratePKCEVerifier)") | ||
|
|
||
| require.Contains(t, auth, "http.NewRequestWithContext(cmd.Context(), http.MethodPost, tokenURL", "token exchange should be context-cancellable") | ||
| require.False(t, strings.Contains(auth, "http.PostForm(tokenURL"), "token exchange should use a client with its own timeout, not the shared default client") | ||
| } | ||
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
19 changes: 19 additions & 0 deletions
19
testdata/golden/cases/generate-golden-api-oauth2-authcode/artifacts.txt
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,19 @@ | ||
| # Locks the OAuth2 authorization_code + PKCE auth shape contract: | ||
| # | ||
| # parser.go → AuthConfig.OAuth2Grant=authorization_code, | ||
| # AuthorizationURL + TokenURL set | ||
| # generator.go → auth.go.tmpl selected (browser loopback login) | ||
| # auth.go.tmpl → RFC 8252 loopback redirect (127.0.0.1, not localhost), | ||
| # PKCE on the secretless path: generatePKCEVerifier / | ||
| # pkceCodeChallengeS256 / code_challenge_method=S256 on | ||
| # the authorize request, and exactly one of client_secret | ||
| # or code_verifier on the token exchange | ||
| # | ||
| # If a refactor regresses template selection or drops the PKCE branch, | ||
| # auth.go either disappears or loses the PKCE helpers and the harness | ||
| # fails with a content diff. | ||
| printing-press-oauth2-authcode/internal/cli/auth.go | ||
|
|
||
| # client.go carries refreshAccessToken, which must keep the public-client | ||
| # refresh shape (client_id always sent, client_secret only when present). | ||
| printing-press-oauth2-authcode/internal/client/client.go |
2 changes: 2 additions & 0 deletions
2
testdata/golden/cases/generate-golden-api-oauth2-authcode/command.txt
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,2 @@ | ||
| set -euo pipefail | ||
| "$BINARY" generate --spec testdata/golden/fixtures/golden-api-oauth2-authcode.yaml --output "$CASE_ACTUAL_DIR/printing-press-oauth2-authcode" --force --spec-url file://testdata/golden/fixtures/golden-api-oauth2-authcode.yaml --validate=false |
1 change: 1 addition & 0 deletions
1
testdata/golden/expected/generate-golden-api-oauth2-authcode/exit.txt
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 @@ | ||
| 0 |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.