| 1 |
package op |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"crypto/rand" |
| 6 |
"encoding/base64" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"math/big" |
| 10 |
"net/http" |
| 11 |
"net/url" |
| 12 |
"slices" |
| 13 |
"strings" |
| 14 |
"time" |
| 15 |
|
| 16 |
httphelper "github.com/zitadel/oidc/v3/pkg/http" |
| 17 |
"github.com/zitadel/oidc/v3/pkg/oidc" |
| 18 |
) |
| 19 |
|
| 20 |
type DeviceAuthorizationConfig struct { |
| 21 |
Lifetime time.Duration |
| 22 |
PollInterval time.Duration |
| 23 |
|
| 24 |
// UserFormURL is the complete URL where the user must go to authorize the device. |
| 25 |
// Deprecated: use UserFormPath instead. |
| 26 |
UserFormURL string |
| 27 |
|
| 28 |
// UserFormPath is the path where the user must go to authorize the device. |
| 29 |
// The hostname for the URL is taken from the request by IssuerFromContext. |
| 30 |
UserFormPath string |
| 31 |
UserCode UserCodeConfig |
| 32 |
} |
| 33 |
|
| 34 |
type UserCodeConfig struct { |
| 35 |
CharSet string |
| 36 |
CharAmount int |
| 37 |
DashInterval int |
| 38 |
} |
| 39 |
|
| 40 |
const ( |
| 41 |
CharSetBase20 = "BCDFGHJKLMNPQRSTVWXZ" |
| 42 |
CharSetDigits = "0123456789" |
| 43 |
) |
| 44 |
|
| 45 |
var ( |
| 46 |
UserCodeBase20 = UserCodeConfig{ |
| 47 |
CharSet: CharSetBase20, |
| 48 |
CharAmount: 8, |
| 49 |
DashInterval: 4, |
| 50 |
} |
| 51 |
UserCodeDigits = UserCodeConfig{ |
| 52 |
CharSet: CharSetDigits, |
| 53 |
CharAmount: 9, |
| 54 |
DashInterval: 3, |
| 55 |
} |
| 56 |
) |
| 57 |
|
| 58 |
func DeviceAuthorizationHandler(o OpenIDProvider) func(http.ResponseWriter, *http.Request) { |
| 59 |
return func(w http.ResponseWriter, r *http.Request) { |
| 60 |
if err := DeviceAuthorization(w, r, o); err != nil { |
| 61 |
RequestError(w, r, err, nil) |
| 62 |
} |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
func DeviceAuthorization(w http.ResponseWriter, r *http.Request, o OpenIDProvider) error { |
| 67 |
ctx, span := Tracer.Start(r.Context(), "DeviceAuthorization") |
| 68 |
r = r.WithContext(ctx) |
| 69 |
defer span.End() |
| 70 |
|
| 71 |
req, err := ParseDeviceCodeRequest(r, o) |
| 72 |
if err != nil { |
| 73 |
return err |
| 74 |
} |
| 75 |
response, err := createDeviceAuthorization(r.Context(), req, req.ClientID, o) |
| 76 |
if err != nil { |
| 77 |
return err |
| 78 |
} |
| 79 |
|
| 80 |
httphelper.MarshalJSON(w, response) |
| 81 |
return nil |
| 82 |
} |
| 83 |
|
| 84 |
func createDeviceAuthorization(ctx context.Context, req *oidc.DeviceAuthorizationRequest, clientID string, o OpenIDProvider) (*oidc.DeviceAuthorizationResponse, error) { |
| 85 |
ctx, span := Tracer.Start(ctx, "createDeviceAuthorization") |
| 86 |
defer span.End() |
| 87 |
|
| 88 |
storage, err := assertDeviceStorage(o.Storage()) |
| 89 |
if err != nil { |
| 90 |
return nil, err |
| 91 |
} |
| 92 |
config := o.DeviceAuthorization() |
| 93 |
|
| 94 |
deviceCode, _ := NewDeviceCode(RecommendedDeviceCodeBytes) |
| 95 |
userCode, err := NewUserCode([]rune(config.UserCode.CharSet), config.UserCode.CharAmount, config.UserCode.DashInterval) |
| 96 |
if err != nil { |
| 97 |
return nil, NewStatusError(err, http.StatusInternalServerError) |
| 98 |
} |
| 99 |
|
| 100 |
expires := time.Now().Add(config.Lifetime) |
| 101 |
err = storage.StoreDeviceAuthorization(ctx, clientID, deviceCode, userCode, expires, req.Scopes) |
| 102 |
if err != nil { |
| 103 |
return nil, NewStatusError(err, http.StatusInternalServerError) |
| 104 |
} |
| 105 |
|
| 106 |
var verification *url.URL |
| 107 |
if config.UserFormURL != "" { |
| 108 |
if verification, err = url.Parse(config.UserFormURL); err != nil { |
| 109 |
err = oidc.ErrServerError().WithParent(err).WithDescription("invalid URL for device user form") |
| 110 |
return nil, NewStatusError(err, http.StatusInternalServerError) |
| 111 |
} |
| 112 |
} else { |
| 113 |
if verification, err = url.Parse(IssuerFromContext(ctx)); err != nil { |
| 114 |
err = oidc.ErrServerError().WithParent(err).WithDescription("invalid URL for issuer") |
| 115 |
return nil, NewStatusError(err, http.StatusInternalServerError) |
| 116 |
} |
| 117 |
verification.Path = config.UserFormPath |
| 118 |
} |
| 119 |
|
| 120 |
response := &oidc.DeviceAuthorizationResponse{ |
| 121 |
DeviceCode: deviceCode, |
| 122 |
UserCode: userCode, |
| 123 |
VerificationURI: verification.String(), |
| 124 |
ExpiresIn: int(config.Lifetime / time.Second), |
| 125 |
Interval: int(config.PollInterval / time.Second), |
| 126 |
} |
| 127 |
|
| 128 |
verification.RawQuery = "user_code=" + userCode |
| 129 |
response.VerificationURIComplete = verification.String() |
| 130 |
return response, nil |
| 131 |
} |
| 132 |
|
| 133 |
func ParseDeviceCodeRequest(r *http.Request, o OpenIDProvider) (*oidc.DeviceAuthorizationRequest, error) { |
| 134 |
ctx, span := Tracer.Start(r.Context(), "ParseDeviceCodeRequest") |
| 135 |
r = r.WithContext(ctx) |
| 136 |
defer span.End() |
| 137 |
|
| 138 |
clientID, _, err := ClientIDFromRequest(r, o) |
| 139 |
if err != nil { |
| 140 |
return nil, err |
| 141 |
} |
| 142 |
client, err := o.Storage().GetClientByClientID(r.Context(), clientID) |
| 143 |
if err != nil { |
| 144 |
return nil, err |
| 145 |
} |
| 146 |
if !ValidateGrantType(client, oidc.GrantTypeDeviceCode) { |
| 147 |
return nil, oidc.ErrUnauthorizedClient().WithDescription("client missing grant type " + string(oidc.GrantTypeDeviceCode)) |
| 148 |
} |
| 149 |
|
| 150 |
req := new(oidc.DeviceAuthorizationRequest) |
| 151 |
if err := o.Decoder().Decode(req, r.Form); err != nil { |
| 152 |
return nil, oidc.ErrInvalidRequest().WithDescription("cannot parse device authentication request").WithParent(err) |
| 153 |
} |
| 154 |
req.ClientID = clientID |
| 155 |
|
| 156 |
return req, nil |
| 157 |
} |
| 158 |
|
| 159 |
// 16 bytes gives 128 bit of entropy. |
| 160 |
// results in a 22 character base64 encoded string. |
| 161 |
const RecommendedDeviceCodeBytes = 16 |
| 162 |
|
| 163 |
// NewDeviceCode generates a new cryptographically secure device code as a base64 encoded string. |
| 164 |
// The length of the string is nBytes * 4 / 3. |
| 165 |
// An error is never returned. |
| 166 |
// |
| 167 |
// TODO(v4): change return type to string alone. |
| 168 |
func NewDeviceCode(nBytes int) (string, error) { |
| 169 |
bytes := make([]byte, nBytes) |
| 170 |
rand.Read(bytes) |
| 171 |
return base64.RawURLEncoding.EncodeToString(bytes), nil |
| 172 |
} |
| 173 |
|
| 174 |
func NewUserCode(charSet []rune, charAmount, dashInterval int) (string, error) { |
| 175 |
var buf strings.Builder |
| 176 |
if dashInterval > 0 { |
| 177 |
buf.Grow(charAmount + charAmount/dashInterval - 1) |
| 178 |
} else { |
| 179 |
buf.Grow(charAmount) |
| 180 |
} |
| 181 |
|
| 182 |
max := big.NewInt(int64(len(charSet))) |
| 183 |
|
| 184 |
for i := 0; i < charAmount; i++ { |
| 185 |
if dashInterval != 0 && i != 0 && i%dashInterval == 0 { |
| 186 |
buf.WriteByte('-') |
| 187 |
} |
| 188 |
|
| 189 |
bi, err := rand.Int(rand.Reader, max) |
| 190 |
if err != nil { |
| 191 |
return "", fmt.Errorf("%w getting entropy for user code", err) |
| 192 |
} |
| 193 |
|
| 194 |
buf.WriteRune(charSet[int(bi.Int64())]) |
| 195 |
} |
| 196 |
|
| 197 |
return buf.String(), nil |
| 198 |
} |
| 199 |
|
| 200 |
func DeviceAccessToken(w http.ResponseWriter, r *http.Request, exchanger Exchanger) { |
| 201 |
ctx, span := Tracer.Start(r.Context(), "DeviceAccessToken") |
| 202 |
defer span.End() |
| 203 |
r = r.WithContext(ctx) |
| 204 |
|
| 205 |
if err := deviceAccessToken(w, r, exchanger); err != nil { |
| 206 |
RequestError(w, r, err, nil) |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
func deviceAccessToken(w http.ResponseWriter, r *http.Request, exchanger Exchanger) error { |
| 211 |
// use a limited context timeout shorter as the default |
| 212 |
// poll interval of 5 seconds. |
| 213 |
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Second) |
| 214 |
defer cancel() |
| 215 |
r = r.WithContext(ctx) |
| 216 |
|
| 217 |
clientID, clientAuthenticated, err := ClientIDFromRequest(r, exchanger) |
| 218 |
if err != nil { |
| 219 |
return err |
| 220 |
} |
| 221 |
|
| 222 |
req, err := ParseDeviceAccessTokenRequest(r, exchanger) |
| 223 |
if err != nil { |
| 224 |
return err |
| 225 |
} |
| 226 |
tokenRequest, err := CheckDeviceAuthorizationState(ctx, clientID, req.DeviceCode, exchanger) |
| 227 |
if err != nil { |
| 228 |
return err |
| 229 |
} |
| 230 |
|
| 231 |
client, err := exchanger.Storage().GetClientByClientID(ctx, clientID) |
| 232 |
if err != nil { |
| 233 |
return err |
| 234 |
} |
| 235 |
if clientAuthenticated != IsConfidentialType(client) { |
| 236 |
return oidc.ErrInvalidClient().WithParent(ErrNoClientCredentials). |
| 237 |
WithDescription("confidential client requires authentication") |
| 238 |
} |
| 239 |
|
| 240 |
resp, err := CreateDeviceTokenResponse(r.Context(), tokenRequest, exchanger, client) |
| 241 |
if err != nil { |
| 242 |
return err |
| 243 |
} |
| 244 |
|
| 245 |
httphelper.MarshalJSON(w, resp) |
| 246 |
return nil |
| 247 |
} |
| 248 |
|
| 249 |
func ParseDeviceAccessTokenRequest(r *http.Request, exchanger Exchanger) (*oidc.DeviceAccessTokenRequest, error) { |
| 250 |
req := new(oidc.DeviceAccessTokenRequest) |
| 251 |
if err := exchanger.Decoder().Decode(req, r.PostForm); err != nil { |
| 252 |
return nil, err |
| 253 |
} |
| 254 |
return req, nil |
| 255 |
} |
| 256 |
|
| 257 |
// DeviceAuthorizationState describes the current state of |
| 258 |
// the device authorization flow. |
| 259 |
// It implements the [IDTokenRequest] interface. |
| 260 |
type DeviceAuthorizationState struct { |
| 261 |
ClientID string |
| 262 |
Audience []string |
| 263 |
Scopes []string |
| 264 |
Expires time.Time // The time after we consider the authorization request timed-out |
| 265 |
Done bool // The user authenticated and approved the authorization request |
| 266 |
Denied bool // The user authenticated and denied the authorization request |
| 267 |
|
| 268 |
// The following fields are populated after Done == true |
| 269 |
Subject string |
| 270 |
AMR []string |
| 271 |
AuthTime time.Time |
| 272 |
} |
| 273 |
|
| 274 |
func (r *DeviceAuthorizationState) GetAMR() []string { |
| 275 |
return r.AMR |
| 276 |
} |
| 277 |
|
| 278 |
func (r *DeviceAuthorizationState) GetAudience() []string { |
| 279 |
if !slices.Contains(r.Audience, r.ClientID) { |
| 280 |
r.Audience = append(r.Audience, r.ClientID) |
| 281 |
} |
| 282 |
return r.Audience |
| 283 |
} |
| 284 |
|
| 285 |
func (r *DeviceAuthorizationState) GetAuthTime() time.Time { |
| 286 |
return r.AuthTime |
| 287 |
} |
| 288 |
|
| 289 |
func (r *DeviceAuthorizationState) GetClientID() string { |
| 290 |
return r.ClientID |
| 291 |
} |
| 292 |
|
| 293 |
func (r *DeviceAuthorizationState) GetScopes() []string { |
| 294 |
return r.Scopes |
| 295 |
} |
| 296 |
|
| 297 |
func (r *DeviceAuthorizationState) GetSubject() string { |
| 298 |
return r.Subject |
| 299 |
} |
| 300 |
|
| 301 |
func CheckDeviceAuthorizationState(ctx context.Context, clientID, deviceCode string, exchanger Exchanger) (*DeviceAuthorizationState, error) { |
| 302 |
ctx, span := Tracer.Start(ctx, "CheckDeviceAuthorizationState") |
| 303 |
defer span.End() |
| 304 |
|
| 305 |
storage, err := assertDeviceStorage(exchanger.Storage()) |
| 306 |
if err != nil { |
| 307 |
return nil, err |
| 308 |
} |
| 309 |
|
| 310 |
state, err := storage.GetDeviceAuthorizatonState(ctx, clientID, deviceCode) |
| 311 |
if errors.Is(err, context.DeadlineExceeded) { |
| 312 |
return nil, oidc.ErrSlowDown().WithParent(err) |
| 313 |
} |
| 314 |
if err != nil { |
| 315 |
return nil, oidc.ErrAccessDenied().WithParent(err) |
| 316 |
} |
| 317 |
if state.Denied { |
| 318 |
return state, oidc.ErrAccessDenied() |
| 319 |
} |
| 320 |
if state.Done { |
| 321 |
return state, nil |
| 322 |
} |
| 323 |
if time.Now().After(state.Expires) { |
| 324 |
return state, oidc.ErrExpiredDeviceCode() |
| 325 |
} |
| 326 |
return state, oidc.ErrAuthorizationPending() |
| 327 |
} |
| 328 |
|
| 329 |
func CreateDeviceTokenResponse(ctx context.Context, tokenRequest TokenRequest, creator TokenCreator, client Client) (*oidc.AccessTokenResponse, error) { |
| 330 |
/* TODO(v4): |
| 331 |
Change the TokenRequest argument type to *DeviceAuthorizationState. |
| 332 |
Breaking change that can not be done for v3. |
| 333 |
*/ |
| 334 |
ctx, span := Tracer.Start(ctx, "CreateDeviceTokenResponse") |
| 335 |
defer span.End() |
| 336 |
|
| 337 |
accessToken, refreshToken, validity, err := CreateAccessToken(ctx, tokenRequest, client.AccessTokenType(), creator, client, "") |
| 338 |
if err != nil { |
| 339 |
return nil, err |
| 340 |
} |
| 341 |
|
| 342 |
response := &oidc.AccessTokenResponse{ |
| 343 |
AccessToken: accessToken, |
| 344 |
RefreshToken: refreshToken, |
| 345 |
TokenType: oidc.BearerToken, |
| 346 |
ExpiresIn: uint64(validity.Seconds()), |
| 347 |
Scope: tokenRequest.GetScopes(), |
| 348 |
} |
| 349 |
|
| 350 |
// TODO(v4): remove type assertion |
| 351 |
if idTokenRequest, ok := tokenRequest.(IDTokenRequest); ok && slices.Contains(tokenRequest.GetScopes(), oidc.ScopeOpenID) { |
| 352 |
response.IDToken, err = CreateIDToken(ctx, IssuerFromContext(ctx), idTokenRequest, client.IDTokenLifetime(), accessToken, "", creator.Storage(), client) |
| 353 |
if err != nil { |
| 354 |
return nil, err |
| 355 |
} |
| 356 |
} |
| 357 |
|
| 358 |
return response, nil |
| 359 |
} |