Debian Codegraph @

src/globus_sdk/services/auth/flow_managers/native_app.py

raw
1 from __future__ import annotations
2
3 import base64
4 import hashlib
5 import logging
6 import os
7 import re
8 import typing as t
9 import urllib.parse
10
11 from globus_sdk._internal.utils import slash_join
12 from globus_sdk._missing import MISSING, MissingType, filter_missing
13 from globus_sdk.exc import GlobusSDKUsageError
14 from globus_sdk.scopes import Scope, ScopeParser
15
16 from ..response import OAuthAuthorizationCodeResponse
17 from .base import GlobusOAuthFlowManager
18
19 if t.TYPE_CHECKING:
20 import globus_sdk
21
22 log = logging.getLogger(__name__)
23
24
25 def _make_native_app_challenge(
26 verifier: str | MissingType = MISSING,
27 ) -> tuple[str, str]:
28 """
29 Produce a challenge and verifier for the Native App flow.
30 The verifier is an unhashed secret, and the challenge is a hashed version
31 of it. The challenge is sent at the start of the flow, and the secret is
32 sent at the end, proving that the same client that started the flow is
33 continuing it.
34
35 Hashing is always done with simple SHA256.
36
37 See RFC 7636 for details.
38
39 :param verifier: The code verifier string used to construct the code challenge. Must
40 be at least 43 characters long and not longer than 128 characters. Must only
41 contain the following characters: [a-zA-Z0-9~_.-].
42 """
43
44 if isinstance(verifier, str):
45 if not 43 <= len(verifier) <= 128:
46 raise GlobusSDKUsageError(
47 f"verifier must be 43-128 characters long: {len(verifier)}"
48 )
49 if bool(re.search(r"[^a-zA-Z0-9~_.-]", verifier)):
50 raise GlobusSDKUsageError("verifier contained invalid characters")
51
52 code_verifier: str = verifier
53 else:
54 log.debug(
55 "Autogenerating verifier secret. On low-entropy systems "
56 "this may be insecure"
57 )
58 code_verifier = (
59 base64.urlsafe_b64encode(os.urandom(32)).decode("utf-8").rstrip("=")
60 )
61
62 # hash it, pull out a digest
63 hashed_verifier = hashlib.sha256(code_verifier.encode("utf-8")).digest()
64 # urlsafe base64 encode that hash and strip the padding
65 code_challenge = (
66 base64.urlsafe_b64encode(hashed_verifier).decode("utf-8").rstrip("=")
67 )
68
69 # return the verifier and the encoded hash
70 return code_verifier, code_challenge
71
72
73 class GlobusNativeAppFlowManager(GlobusOAuthFlowManager):
74 """
75 This is the OAuth flow designated for use by clients wishing to
76 authenticate users in the absence of a Client Secret. Because these
77 applications run "natively" in the user's environment, they cannot
78 protect a secret.
79 Instead, a temporary secret is generated solely for this authentication
80 attempt.
81
82 :param auth_client: The client object on which this flow is based.
83 It is used to extract default values for the flow, and also to make calls to the
84 Auth service.
85 :param requested_scopes: The scopes on the token(s) being requested.
86 :param redirect_uri: The page that users should be directed to after authenticating
87 at the authorize URL. Defaults to 'https://auth.globus.org/v2/web/auth-code',
88 which displays the resulting ``auth_code`` for users to copy-paste back into
89 your application (and thereby be passed back to the
90 ``GlobusNativeAppFlowManager``)
91 :param state: The ``redirect_uri`` page will have this included in a query
92 parameter, so you can use it to pass information to that page if you use a
93 custom page. It defaults to the string '_default'
94 :param verifier: A secret used for the Native App flow. It will by default be a
95 freshly generated random string, known only to this
96 ``GlobusNativeAppFlowManager`` instance
97 :param refresh_tokens: When True, request refresh tokens in addition to access
98 tokens. [Default: ``False``]
99 :param prefill_named_grant: Prefill the named grant label on the consent page
100 """
101
102 def __init__(
103 self,
104 auth_client: globus_sdk.NativeAppAuthClient,
105 requested_scopes: str | Scope | t.Iterable[str | Scope],
106 redirect_uri: str | MissingType = MISSING,
107 state: str = "_default",
108 verifier: str | MissingType = MISSING,
109 refresh_tokens: bool = False,
110 prefill_named_grant: str | MissingType = MISSING,
111 ) -> None:
112 self.auth_client = auth_client
113
114 # set client_id, then check for validity
115 self.client_id = auth_client.client_id
116 if not self.client_id:
117 log.error(
118 "Invalid auth_client ID to start Native App Flow: {}".format(
119 self.client_id
120 )
121 )
122 raise GlobusSDKUsageError(
123 f'Invalid value for client_id. Got "{self.client_id}"'
124 )
125
126 # convert scopes iterable to string immediately on load
127 self.requested_scopes = ScopeParser.serialize(requested_scopes)
128
129 # default to `/v2/web/auth-code` on whatever environment we're looking
130 # at -- most typically it will be `https://auth.globus.org/`
131 self.redirect_uri = redirect_uri or (
132 slash_join(auth_client.base_url, "/v2/web/auth-code")
133 )
134
135 # make a challenge and secret to keep
136 # if the verifier is provided, it will just be passed back to us, and
137 # if not, one will be generated
138 self.verifier, self.challenge = _make_native_app_challenge(verifier)
139
140 # store the remaining parameters directly, with no transformation
141 self.refresh_tokens = refresh_tokens
142 self.state = state
143 self.prefill_named_grant = prefill_named_grant
144
145 log.debug(
146 "Starting Native App Flow with params: "
147 f"auth_client.client_id={auth_client.client_id} , "
148 f"redirect_uri={self.redirect_uri} , "
149 f"refresh_tokens={refresh_tokens} , "
150 f"state={state} , "
151 f"requested_scopes={self.requested_scopes} , "
152 f"verifier=<REDACTED>,challenge={self.challenge}"
153 )
154
155 if prefill_named_grant is not MISSING:
156 log.debug(f"prefill_named_grant={self.prefill_named_grant}")
157
158 def get_authorize_url(self, query_params: dict[str, t.Any] | None = None) -> str:
159 """
160 Start a Native App flow by getting the authorization URL to which users
161 should be sent.
162
163 :param query_params: Additional query parameters to include in the
164 authorize URL. Primarily for internal use
165
166 The returned URL string is encoded to be suitable to display to users
167 in a link or to copy into their browser. Users will be redirected
168 either to your provided ``redirect_uri`` or to the default location,
169 with the ``auth_code`` embedded in a query parameter.
170 """
171 authorize_base_url = slash_join(
172 self.auth_client.base_url, "/v2/oauth2/authorize"
173 )
174 log.debug(f"Building authorization URI. Base URL: {authorize_base_url}")
175 log.debug(f"query_params={query_params}")
176
177 params = {
178 "client_id": self.client_id,
179 "redirect_uri": self.redirect_uri,
180 "scope": self.requested_scopes,
181 "state": self.state,
182 "response_type": "code",
183 "code_challenge": self.challenge,
184 "code_challenge_method": "S256",
185 "access_type": (self.refresh_tokens and "offline") or "online",
186 "prefill_named_grant": self.prefill_named_grant,
187 **(query_params or {}),
188 }
189 params = filter_missing(params)
190
191 encoded_params = urllib.parse.urlencode(params)
192 return f"{authorize_base_url}?{encoded_params}"
193
194 def exchange_code_for_tokens(
195 self, auth_code: str
196 ) -> OAuthAuthorizationCodeResponse:
197 """
198 The second step of the Native App flow, exchange an authorization code
199 for access tokens (and refresh tokens if specified).
200
201 :param auth_code: The short-lived code to exchange for tokens
202 """
203 log.debug(
204 "Performing Native App auth_code exchange. "
205 "Sending verifier and client_id"
206 )
207 return self.auth_client.oauth2_token(
208 {
209 "client_id": self.client_id,
210 "grant_type": "authorization_code",
211 "code": auth_code.encode("utf-8"),
212 "code_verifier": self.verifier,
213 "redirect_uri": self.redirect_uri,
214 },
215 response_class=OAuthAuthorizationCodeResponse,
216 )