Skip to content

Commit 77a5f1c

Browse files
JonathanHuotmistral-vibe
authored andcommitted
Merge pull request #954 from hekhuisk/improve-device-workflow
Improve device workflow
1 parent 145a9a4 commit 77a5f1c

9 files changed

Lines changed: 462 additions & 81 deletions

File tree

‎docs/oauth2/endpoints/device.rst‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,15 @@ the device authorization endpoint.
5656
"verification_uri_complete":
5757
"https://example.com/device?user_code=WDJB-MJHT",
5858
"expires_in": 1800,
59-
"interval": 5
59+
"interval": 5,
60+
"scope": "example_scope"
6061
}
6162
63+
The ``scope`` key is not part of RFC 8628. It holds the scopes resolved for the
64+
request — either what the device asked for or what ``get_default_scopes``
65+
returned — so you can persist them alongside the ``device_code`` and
66+
``user_code``. It is omitted when no scopes were resolved.
67+
6268

6369
.. autoclass:: oauthlib.oauth2.DeviceAuthorizationEndpoint
6470
:members:

‎oauthlib/common.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,7 @@ def encode(x):
366366
"code_challenge": None,
367367
"code_challenge_method": None,
368368
"code_verifier": None,
369+
"device_code": None,
369370
"extra_credentials": None,
370371
"grant_type": None,
371372
"redirect_uri": None,

‎oauthlib/oauth2/rfc6749/grant_types/base.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -208,9 +208,9 @@ def validate_client_public(self, request):
208208

209209
if request.client is None or \
210210
not hasattr(request.client, 'client_id'):
211-
raise NotImplementedError('Authenticate client must set the '
212-
'request.client.client_id attribute '
213-
'in authenticate_client.')
211+
raise NotImplementedError('authenticate_client_id must set the '
212+
'request.client attribute to a client '
213+
'object with a client_id attribute.')
214214

215215
if not request.client_id:
216216
request.client_id = request.client.client_id

‎oauthlib/oauth2/rfc8628/endpoints/device_authorization.py‎

Lines changed: 17 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,12 @@
1010
from typing import Callable
1111

1212
from oauthlib.common import Request, generate_token
13-
from oauthlib.oauth2.rfc6749 import errors
13+
from oauthlib.oauth2.rfc6749 import utils
1414
from oauthlib.oauth2.rfc6749.endpoints.base import (
1515
BaseEndpoint,
1616
catch_errors_and_unavailability,
1717
)
18+
from oauthlib.oauth2.rfc8628.grant_types import DeviceCodeGrant
1819

1920
log = logging.getLogger(__name__)
2021

@@ -52,6 +53,7 @@ def __init__(
5253
:param user_code_generator: a callable that returns a configurable user code
5354
"""
5455
self.request_validator = request_validator
56+
self.device_code_grant = DeviceCodeGrant(request_validator)
5557
self._expires_in = expires_in
5658
self._interval = interval
5759
self._verification_uri = verification_uri
@@ -101,44 +103,7 @@ def validate_device_authorization_request(self, request):
101103
.. _`Section 3.2.1. of [RFC6749]`: https://www.rfc-editor.org/rfc/rfc6749#section-3.2.1
102104
.. _`Section 2.2 of [RFC6749]`: https://www.rfc-editor.org/rfc/rfc6749#section-2.2
103105
"""
104-
105-
# First check duplicate parameters
106-
for param in ("client_id", "scope"):
107-
try:
108-
duplicate_params = request.duplicate_params
109-
except ValueError:
110-
raise errors.InvalidRequestFatalError(
111-
description="Unable to parse query string", request=request
112-
)
113-
if param in duplicate_params:
114-
raise errors.InvalidRequestFatalError(
115-
description="Duplicate %s parameter." % param, request=request
116-
)
117-
118-
# the "application/x-www-form-urlencoded" format, per Appendix B of [RFC6749]
119-
# https://www.rfc-editor.org/rfc/rfc6749#appendix-B
120-
if request.headers["Content-Type"] != "application/x-www-form-urlencoded":
121-
raise errors.InvalidRequestError(
122-
"Content-Type must be application/x-www-form-urlencoded",
123-
request=request,
124-
)
125-
126-
# REQUIRED. The client identifier as described in Section 2.2.
127-
# https://tools.ietf.org/html/rfc6749#section-2.2
128-
# TODO: extract client_id an helper validation function.
129-
if not request.client_id:
130-
raise errors.MissingClientIdError(request=request)
131-
132-
if not self.request_validator.validate_client_id(request.client_id, request):
133-
raise errors.InvalidClientIdError(request=request)
134-
135-
# The client authentication requirements of Section 3.2.1 of [RFC6749]
136-
# apply to requests on this endpoint, which means that confidential
137-
# clients (those that have established client credentials) authenticate
138-
# in the same manner as when making requests to the token endpoint, and
139-
# public clients provide the "client_id" parameter to identify
140-
# themselves.
141-
self._raise_on_invalid_client(request)
106+
self.device_code_grant.validate_device_authorization_request(request)
142107

143108
@catch_errors_and_unavailability
144109
def create_device_authorization_response(
@@ -189,6 +154,13 @@ def create_device_authorization_response(
189154
SHOULD wait between polling requests to the token endpoint. If no
190155
value is provided, clients MUST use 5 as the default.
191156
157+
scope
158+
**OPTIONAL.** The space delimited scopes resolved for this request,
159+
either the scopes the device asked for or the ones returned by
160+
``get_default_scopes``. Not defined by RFC 8628, it is included so
161+
the caller can persist the authorized scopes with the device_code.
162+
Omitted when no scopes were resolved.
163+
192164
**For example:**
193165
194166
.. code-block:: http
@@ -224,6 +196,12 @@ def create_device_authorization_response(
224196
if self.interval is not None:
225197
data["interval"] = self.interval
226198

199+
# ``validate_device_authorization_request`` resolves request.scopes,
200+
# falling back to ``get_default_scopes`` when the device omitted the
201+
# ``scope`` parameter. Echo the resolved value so callers can persist it
202+
# alongside the device_code/user_code without re-running the validator.
203+
if request.scopes:
204+
data["scope"] = utils.list_to_scope(request.scopes)
227205

228206
verification_uri_complete = self.verification_uri_complete(user_code)
229207
if verification_uri_complete:

‎oauthlib/oauth2/rfc8628/grant_types/device_code.py‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,40 @@
11
from __future__ import annotations
22
import json
3+
import logging
34

45
from typing import Callable
56

67
from oauthlib import common # noqa: TC001
78

89
from oauthlib.oauth2.rfc6749 import errors as rfc6749_errors
910
from 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

1216
class 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]:

‎oauthlib/oauth2/rfc8628/request_validator.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,41 @@ def client_authentication_required(self, request, *args, **kwargs):
2323
.. _`Section 3.1`: https://www.rfc-editor.org/rfc/rfc8628#section-3.1
2424
"""
2525
return True
26+
27+
def validate_device_code(self, client_id, code, request, *args, **kwargs):
28+
"""Validate a ``device_code`` and return its authorization status.
29+
30+
Called when a device polls the token endpoint. The implementation
31+
should look up the ``device_code``, confirm it was issued to the
32+
authenticating client, and report where it is in the authorization
33+
process described in `Section 3.5`_ by returning one of the
34+
``DeviceCodeGrant`` status constants:
35+
36+
- ``DEVICE_CODE_AUTHORIZED``: the end user approved the request.
37+
The implementation should also set ``request.user`` (and any
38+
scopes or claims to embed) so they end up on the issued token,
39+
which removes the need for a separate token validator.
40+
- ``DEVICE_CODE_PENDING``: the user has not yet completed the
41+
interaction; raises ``AuthorizationPendingError``.
42+
- ``DEVICE_CODE_SLOW_DOWN``: as pending, but the client is polling
43+
too quickly; raises ``SlowDownError``.
44+
- ``DEVICE_CODE_EXPIRED``: the ``device_code`` has expired; raises
45+
``ExpiredTokenError``.
46+
- ``DEVICE_CODE_DENIED``: the user denied the request; raises
47+
``AccessDenied``.
48+
49+
Returning ``None`` (or any unrecognized value) is treated as an
50+
unknown or invalid ``device_code`` and raises ``InvalidGrantError``.
51+
52+
:param client_id: Unicode client identifier.
53+
:param code: Unicode device_code.
54+
:param request: OAuthlib request.
55+
:type request: oauthlib.common.Request
56+
:rtype: str or None
57+
58+
Method is used by:
59+
- Device Code Grant
60+
61+
.. _`Section 3.5`: https://www.rfc-editor.org/rfc/rfc8628#section-3.5
62+
"""
63+
raise NotImplementedError("Subclasses must implement this method.")

0 commit comments

Comments
 (0)