Skip to content
Open
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
56 changes: 49 additions & 7 deletions command/oauth/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down
98 changes: 98 additions & 0 deletions command/oauth/cmd_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
}