11from __future__ import annotations
22import json
3+ import logging
34
45from typing import Callable
56
67from oauthlib import common # noqa: TC001
78
89from oauthlib .oauth2 .rfc6749 import errors as rfc6749_errors
910from oauthlib .oauth2 .rfc6749 .grant_types .base import GrantTypeBase
11+ from oauthlib .oauth2 .rfc8628 import errors as rfc8628_errors
12+
13+ log = logging .getLogger (__name__ )
1014
1115
1216class DeviceCodeGrant (GrantTypeBase ):
17+ #: Maps a non-authorized device code status to the RFC 8628 Section 3.5
18+ #: error it raises. The status strings are the errors' own ``error`` codes,
19+ #: keeping a single source of truth.
20+ _device_code_errors = {
21+ cls .error : cls
22+ for cls in (
23+ rfc8628_errors .AuthorizationPendingError ,
24+ rfc8628_errors .SlowDownError ,
25+ rfc8628_errors .ExpiredTokenError ,
26+ rfc8628_errors .AccessDenied ,
27+ )
28+ }
29+
30+ #: Authorization statuses returned by
31+ #: :meth:`RequestValidator.validate_device_code`, per RFC 8628 Section 3.5.
32+ DEVICE_CODE_AUTHORIZED = "authorized"
33+ DEVICE_CODE_PENDING = rfc8628_errors .AuthorizationPendingError .error
34+ DEVICE_CODE_SLOW_DOWN = rfc8628_errors .SlowDownError .error
35+ DEVICE_CODE_EXPIRED = rfc8628_errors .ExpiredTokenError .error
36+ DEVICE_CODE_DENIED = rfc8628_errors .AccessDenied .error
37+
1338 def create_authorization_response (
1439 self , request : common .Request , token_handler : Callable
1540 ) -> tuple [dict , str , int ]:
@@ -33,6 +58,61 @@ def create_authorization_response(
3358
3459 return self .create_token_response (request , token_handler )
3560
61+ def validate_device_authorization_request (self , request : common .Request ) -> None :
62+ """Validate the device authorization request.
63+
64+ The client_id is required if the client is not authenticating with the
65+ authorization server as described in `Section 3.2.1. of [RFC6749]`_.
66+ The client identifier as described in `Section 2.2 of [RFC6749]`_.
67+
68+ :param request: OAuthlib request.
69+ :type request: oauthlib.common.Request
70+
71+ .. _`Section 3.2.1. of [RFC6749]`: https://www.rfc-editor.org/rfc/rfc6749#section-3.2.1
72+ .. _`Section 2.2 of [RFC6749]`: https://www.rfc-editor.org/rfc/rfc6749#section-2.2
73+ """
74+ # First check duplicate parameters
75+ for param in ("client_id" , "scope" ):
76+ try :
77+ duplicate_params = request .duplicate_params
78+ except ValueError :
79+ raise rfc6749_errors .InvalidRequestFatalError (
80+ description = "Unable to parse query string" , request = request
81+ )
82+ if param in duplicate_params :
83+ raise rfc6749_errors .InvalidRequestFatalError (
84+ description = "Duplicate %s parameter." % param , request = request
85+ )
86+
87+ # the "application/x-www-form-urlencoded" format, per Appendix B of [RFC6749]
88+ # https://www.rfc-editor.org/rfc/rfc6749#appendix-B
89+ content_type = request .headers .get ("Content-Type" , "" )
90+ content_type = content_type .split (";" , 1 )[0 ].strip ().lower ()
91+ if content_type != "application/x-www-form-urlencoded" :
92+ raise rfc6749_errors .InvalidRequestError (
93+ "Content-Type must be application/x-www-form-urlencoded" , request = request
94+ )
95+
96+ # REQUIRED. The client identifier as described in Section 2.2.
97+ # https://tools.ietf.org/html/rfc6749#section-2.2
98+ if not request .client_id :
99+ raise rfc6749_errors .MissingClientIdError (request = request )
100+
101+ if not self .request_validator .validate_client_id (request .client_id , request ):
102+ raise rfc6749_errors .InvalidClientIdError (request = request )
103+
104+ # The client authentication requirements of Section 3.2.1 of [RFC6749]
105+ # apply to requests on this endpoint, which means that confidential
106+ # clients (those that have established client credentials) authenticate
107+ # in the same manner as when making requests to the token endpoint, and
108+ # public clients provide the "client_id" parameter to identify
109+ # themselves.
110+ self .validate_client_authentication (request )
111+
112+ # OPTIONAL. The scope of the access request as defined by Section 3.3
113+ # of [RFC6749]. https://www.rfc-editor.org/rfc/rfc8628#section-3.1
114+ self .validate_scopes (request )
115+
36116 def validate_token_request (self , request : common .Request ) -> None :
37117 """
38118 Performs the necessary check against the request to ensure
@@ -60,11 +140,67 @@ def validate_token_request(self, request: common.Request) -> None:
60140 # Ensure client is authorized use of this grant type
61141 self .validate_grant_type (request )
62142
143+ # Validate the device_code first: per RFC 8628 Section 3.4 the token
144+ # request carries no scope, so the validator must populate
145+ # request.user and request.scopes from the stored authorization before
146+ # validate_scopes runs (otherwise it would fall back to default scopes).
147+ self .validate_device_code (request )
148+
63149 self .validate_scopes (request )
64150
65151 for validator in self .custom_validators .post_token :
66152 validator (request )
67153
154+ def validate_device_code (self , request : common .Request ) -> None :
155+ """Validate the ``device_code`` and its authorization status.
156+
157+ Delegates to :meth:`RequestValidator.validate_device_code`, which
158+ returns one of the ``DEVICE_CODE_*`` statuses, and maps it to the
159+ appropriate RFC 8628 Section 3.5 error.
160+
161+ :param request: OAuthlib request.
162+ :type request: oauthlib.common.Request
163+ """
164+ if not request .device_code :
165+ raise rfc6749_errors .InvalidRequestError (
166+ "Missing device_code parameter." , request = request
167+ )
168+
169+ status = self .request_validator .validate_device_code (
170+ request .client_id , request .device_code , request
171+ )
172+ if status == self .DEVICE_CODE_AUTHORIZED :
173+ # The validator is expected to populate these from the stored
174+ # authorization; if it did not, validate_scopes will silently fall
175+ # back to the client's default scopes.
176+ if getattr (request , "user" , None ) is None :
177+ log .debug ("request.user was not set on device_code validation." )
178+ if getattr (request , "scopes" , None ) is None and request .scope is None :
179+ raise rfc6749_errors .ServerError (
180+ description = "validate_device_code must set request.scopes for an authorized device_code." ,
181+ request = request ,
182+ )
183+ if getattr (request , "scopes" , None ) is None :
184+ log .debug ("request.scopes was not set on device_code validation." )
185+ return
186+
187+ # A recognized non-authorized status maps to its RFC 8628 polling
188+ # error; anything else means the device_code is unknown or invalid.
189+ error_class = self ._device_code_errors .get (status )
190+ if error_class is not None :
191+ raise error_class (request = request )
192+
193+ # None is the documented "unknown/invalid device_code" return. Any
194+ # other unrecognized value most likely signals a validator that did
195+ # not return a DEVICE_CODE_* status, so surface it for debugging.
196+ if status is not None :
197+ log .warning (
198+ "validate_device_code returned unrecognized status %r; treating "
199+ "the device_code as invalid. Return one of the "
200+ "DeviceCodeGrant.DEVICE_CODE_* constants." , status
201+ )
202+ raise rfc6749_errors .InvalidGrantError (request = request )
203+
68204 def create_token_response (
69205 self , request : common .Request , token_handler : Callable
70206 ) -> tuple [dict , str , int ]:
0 commit comments