From c60eb3d805523ef1b10979f390b09e68133aa568 Mon Sep 17 00:00:00 2001 From: Yong Xiang Zhan Date: Sat, 5 Dec 2026 04:12:23 +0000 Subject: [PATCH] Support PKCE in the OAuth device authorization flow Keycloak rejects the device authorization request with "Missing parameter: code_challenge_method" when the client enforces PKCE, so `step oauth --console` and commands that use it, like `step ssh login --console`, fail with those clients. Retry the request with a code challenge when the server asks for one, and send the code verifier when polling for the token. The PKCE parameters are not sent by default because RFC 8628 doesn't define them, and Google rejects a token request that has a code_verifier. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 3 ++ command/oauth/cmd.go | 56 +++++++++++++++++++--- command/oauth/cmd_test.go | 98 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 150 insertions(+), 7 deletions(-) create mode 100644 command/oauth/cmd_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 86f56206..a652a376 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,6 +65,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. (smallstep/cli#1742). - Fix the use of ML-DSA keys in a KMS to sign tokens, which failed with `unsupported key type *mldsa.PublicKey` (smallstep/cli#1742). +- Fix the OAuth device authorization flow with Keycloak clients that enforce + PKCE, `step oauth --console` failed with + `Missing parameter: code_challenge_method` (smallstep/cli#1749). ### Security diff --git a/command/oauth/cmd.go b/command/oauth/cmd.go index 8e50df91..d4f0e158 100644 --- a/command/oauth/cmd.go +++ b/command/oauth/cmd.go @@ -867,17 +867,27 @@ func (o *oauth) DoDeviceAuthorization() (*token, error) { data.Set("client_secret", o.clientSecret) data.Set("scope", o.scope) - resp, err := postForm(o.deviceAuthzEndpoint, data) - if err != nil { - return nil, errors.Wrap(err, "http failure to identify device") - } - defer resp.Body.Close() - b, err := io.ReadAll(resp.Body) + statusCode, b, err := o.identifyDevice(data) if err != nil { return nil, err } - if resp.StatusCode >= 400 { + // RFC 8628 doesn't define PKCE for the device flow, but Keycloak requires + // it when the client enforces PKCE. Retry with a code challenge only when + // the server asks for one, as other servers reject the PKCE parameters, + // e.g. Google doesn't allow the code_verifier in the token request. + var usePKCE bool + if statusCode >= 400 && requiresCodeChallenge(b) { + s256 := sha256.Sum256([]byte(o.codeChallenge)) + data.Set("code_challenge_method", "S256") + data.Set("code_challenge", base64.RawURLEncoding.EncodeToString(s256[:])) + if statusCode, b, err = o.identifyDevice(data); err != nil { + return nil, err + } + usePKCE = true + } + + if statusCode >= 400 { var e struct { Error string } @@ -924,6 +934,9 @@ func (o *oauth) DoDeviceAuthorization() (*token, error) { data.Set("client_secret", o.clientSecret) data.Set("grant_type", "urn:ietf:params:oauth:grant-type:device_code") data.Set("device_code", idr.DeviceCode) + if usePKCE { + data.Set("code_verifier", o.codeChallenge) + } endPollIn := defaultDeviceAuthzExpiresIn if idr.ExpiresIn > 0 { @@ -951,6 +964,35 @@ func (o *oauth) DoDeviceAuthorization() (*token, error) { } } +// identifyDevice sends the device authorization request and returns the status +// code and the body of the response. +func (o *oauth) identifyDevice(data url.Values) (int, []byte, error) { + resp, err := postForm(o.deviceAuthzEndpoint, data) + if err != nil { + return 0, nil, errors.Wrap(err, "http failure to identify device") + } + defer resp.Body.Close() + b, err := io.ReadAll(resp.Body) + if err != nil { + return 0, nil, err + } + return resp.StatusCode, b, nil +} + +// requiresCodeChallenge returns true if the error in a device authorization +// response says that the PKCE parameters are missing. Keycloak responds with +// the description "Missing parameter: code_challenge_method". +func requiresCodeChallenge(b []byte) bool { + var e struct { + Error string `json:"error"` + ErrorDescription string `json:"error_description"` + } + if err := json.Unmarshal(b, &e); err != nil { + return false + } + return e.Error == "invalid_request" && strings.Contains(e.ErrorDescription, "code_challenge") +} + var errHTTPToken = errors.New("bad request; token not returned") func (o *oauth) deviceAuthzTokenPoll(data url.Values) (*token, error) { diff --git a/command/oauth/cmd_test.go b/command/oauth/cmd_test.go new file mode 100644 index 00000000..89e19b4a --- /dev/null +++ b/command/oauth/cmd_test.go @@ -0,0 +1,98 @@ +package oauth + +import ( + "crypto/sha256" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestDoDeviceAuthorization_PKCE(t *testing.T) { + tests := []struct { + name string + requiresPKCE bool + wantRequests int + }{ + {"server requires PKCE", true, 2}, + {"server does not require PKCE", false, 1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var challenge, method, verifier string + var requests int + var hasVerifier bool + + mux := http.NewServeMux() + mux.HandleFunc("/device", func(w http.ResponseWriter, r *http.Request) { + assert.NoError(t, r.ParseForm()) + requests++ + challenge = r.PostForm.Get("code_challenge") + method = r.PostForm.Get("code_challenge_method") + w.Header().Set("Content-Type", "application/json") + if tt.requiresPKCE && challenge == "" { + // This is the response of Keycloak when the client + // enforces PKCE. + w.WriteHeader(http.StatusBadRequest) + assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{ + "error": "invalid_request", + "error_description": "Missing parameter: code_challenge_method", + })) + return + } + assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{ + "device_code": "device-code", + "user_code": "USER-CODE", + "verification_uri": "https://example.com/device", + "expires_in": 60, + "interval": 1, + })) + }) + mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { + assert.NoError(t, r.ParseForm()) + assert.Equal(t, "device-code", r.PostForm.Get("device_code")) + hasVerifier = r.PostForm.Has("code_verifier") + verifier = r.PostForm.Get("code_verifier") + w.Header().Set("Content-Type", "application/json") + assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{ + "access_token": "access-token", + "id_token": "id-token", + })) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + o := &oauth{ + clientID: "client-id", + scope: "openid email", + deviceAuthzEndpoint: srv.URL + "/device", + tokenEndpoint: srv.URL + "/token", + codeChallenge: "a-random-code-verifier-that-is-at-least-43-characters-long", + } + + tok, err := o.DoDeviceAuthorization() + require.NoError(t, err) + assert.Equal(t, "id-token", tok.IDToken) + assert.Equal(t, tt.wantRequests, requests) + + if !tt.requiresPKCE { + // Google rejects the token request if it has a code_verifier. + assert.Empty(t, challenge) + assert.Empty(t, method) + assert.False(t, hasVerifier) + return + } + + // The challenge sent in the device authorization request must be + // the S256 transformation of the verifier sent in the token request. + sum := sha256.Sum256([]byte(verifier)) + assert.Equal(t, "S256", method) + assert.Equal(t, o.codeChallenge, verifier) + assert.Equal(t, base64.RawURLEncoding.EncodeToString(sum[:]), challenge) + }) + } +}