| 1 |
# Copyright 2008 Canonical Ltd. |
| 2 |
|
| 3 |
# This file is part of launchpadlib. |
| 4 |
# |
| 5 |
# launchpadlib is free software: you can redistribute it and/or modify it |
| 6 |
# under the terms of the GNU Lesser General Public License as published by the |
| 7 |
# Free Software Foundation, version 3 of the License. |
| 8 |
# |
| 9 |
# launchpadlib is distributed in the hope that it will be useful, but WITHOUT |
| 10 |
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| 11 |
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License |
| 12 |
# for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU Lesser General Public License |
| 15 |
# along with launchpadlib. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
|
| 17 |
"""launchpadlib credentials and authentication support.""" |
| 18 |
|
| 19 |
__all__ = [ |
| 20 |
"AccessToken", |
| 21 |
"AnonymousAccessToken", |
| 22 |
"AuthorizeRequestTokenWithBrowser", |
| 23 |
"CredentialStore", |
| 24 |
"RequestTokenAuthorizationEngine", |
| 25 |
"Consumer", |
| 26 |
"Credentials", |
| 27 |
] |
| 28 |
|
| 29 |
from base64 import ( |
| 30 |
b64decode, |
| 31 |
b64encode, |
| 32 |
) |
| 33 |
import httplib2 |
| 34 |
from io import StringIO |
| 35 |
import json |
| 36 |
import os |
| 37 |
from select import select |
| 38 |
import stat |
| 39 |
from sys import stdin |
| 40 |
import time |
| 41 |
from urllib.parse import urlencode, urljoin, parse_qs |
| 42 |
import webbrowser |
| 43 |
|
| 44 |
from lazr.restfulclient.errors import HTTPError |
| 45 |
from lazr.restfulclient.authorize.oauth import ( |
| 46 |
AccessToken as _AccessToken, |
| 47 |
Consumer, |
| 48 |
OAuthAuthorizer, |
| 49 |
SystemWideConsumer, # Not used directly, just re-imported into here. |
| 50 |
) |
| 51 |
|
| 52 |
from launchpadlib import uris |
| 53 |
|
| 54 |
request_token_page = "+request-token" |
| 55 |
access_token_page = "+access-token" |
| 56 |
authorize_token_page = "+authorize-token" |
| 57 |
access_token_poll_time = 1 |
| 58 |
access_token_poll_timeout = 15 * 60 |
| 59 |
|
| 60 |
EXPLOSIVE_ERRORS = (MemoryError, KeyboardInterrupt, SystemExit) |
| 61 |
|
| 62 |
|
| 63 |
def _ssl_certificate_validation_disabled(): |
| 64 |
"""Whether the user has disabled SSL certificate connection. |
| 65 |
|
| 66 |
Some testing servers have broken certificates. Rather than raising an |
| 67 |
error, we allow an environment variable, |
| 68 |
``LP_DISABLE_SSL_CERTIFICATE_VALIDATION`` to disable the check. |
| 69 |
""" |
| 70 |
# XXX: Copied from lazr/restfulclient/_browser.py. Once it appears in a |
| 71 |
# released version of lazr.restfulclient, depend on that new version and |
| 72 |
# delete this copy. |
| 73 |
return bool(os.environ.get("LP_DISABLE_SSL_CERTIFICATE_VALIDATION", False)) |
| 74 |
|
| 75 |
|
| 76 |
def _http_post(url, headers, params): |
| 77 |
"""POST to ``url`` with ``headers`` and a body of urlencoded ``params``. |
| 78 |
|
| 79 |
Wraps it up to make sure we avoid the SSL certificate validation if our |
| 80 |
environment tells us to. Also, raises an error on non-200 statuses. |
| 81 |
""" |
| 82 |
cert_disabled = _ssl_certificate_validation_disabled() |
| 83 |
response, content = httplib2.Http( |
| 84 |
disable_ssl_certificate_validation=cert_disabled |
| 85 |
).request(url, method="POST", headers=headers, body=urlencode(params)) |
| 86 |
if response.status != 200: |
| 87 |
raise HTTPError(response, content) |
| 88 |
return response, content |
| 89 |
|
| 90 |
|
| 91 |
class Credentials(OAuthAuthorizer): |
| 92 |
"""Standard credentials storage and usage class. |
| 93 |
|
| 94 |
:ivar consumer: The consumer (application) |
| 95 |
:type consumer: `Consumer` |
| 96 |
:ivar access_token: Access information on behalf of the user |
| 97 |
:type access_token: `AccessToken` |
| 98 |
""" |
| 99 |
|
| 100 |
_request_token = None |
| 101 |
|
| 102 |
URI_TOKEN_FORMAT = "uri" |
| 103 |
DICT_TOKEN_FORMAT = "dict" |
| 104 |
ITEM_SEPARATOR = "<BR>" |
| 105 |
NEWLINE = "\n" |
| 106 |
|
| 107 |
def serialize(self): |
| 108 |
"""Turn this object into a string. |
| 109 |
|
| 110 |
This should probably be moved into OAuthAuthorizer. |
| 111 |
""" |
| 112 |
sio = StringIO() |
| 113 |
self.save(sio) |
| 114 |
serialized = sio.getvalue() |
| 115 |
if isinstance(serialized, str): |
| 116 |
serialized = serialized.encode("utf-8") |
| 117 |
return serialized |
| 118 |
|
| 119 |
@classmethod |
| 120 |
def from_string(cls, value): |
| 121 |
"""Create a `Credentials` object from a serialized string. |
| 122 |
|
| 123 |
This should probably be moved into OAuthAuthorizer. |
| 124 |
""" |
| 125 |
credentials = cls() |
| 126 |
if not isinstance(value, str): |
| 127 |
value = value.decode("utf-8") |
| 128 |
credentials.load(StringIO(value)) |
| 129 |
return credentials |
| 130 |
|
| 131 |
def get_request_token( |
| 132 |
self, |
| 133 |
context=None, |
| 134 |
web_root=uris.STAGING_WEB_ROOT, |
| 135 |
token_format=URI_TOKEN_FORMAT, |
| 136 |
): |
| 137 |
"""Request an OAuth token to Launchpad. |
| 138 |
|
| 139 |
Also store the token in self._request_token. |
| 140 |
|
| 141 |
This method must not be called on an object with no consumer |
| 142 |
specified or if an access token has already been obtained. |
| 143 |
|
| 144 |
:param context: The context of this token, that is, its scope of |
| 145 |
validity within Launchpad. |
| 146 |
:param web_root: The URL of the website on which the token |
| 147 |
should be requested. |
| 148 |
:token_format: How the token should be |
| 149 |
presented. URI_TOKEN_FORMAT means just return the URL to |
| 150 |
the page that authorizes the token. DICT_TOKEN_FORMAT |
| 151 |
means return a dictionary describing the token |
| 152 |
and the site's authentication policy. |
| 153 |
|
| 154 |
:return: If token_format is URI_TOKEN_FORMAT, the URL for the |
| 155 |
user to authorize the `AccessToken` provided by |
| 156 |
Launchpad. If token_format is DICT_TOKEN_FORMAT, a dict of |
| 157 |
information about the new access token. |
| 158 |
""" |
| 159 |
assert self.consumer is not None, "Consumer not specified." |
| 160 |
assert self.access_token is None, "Access token already obtained." |
| 161 |
web_root = uris.lookup_web_root(web_root) |
| 162 |
params = dict( |
| 163 |
oauth_consumer_key=self.consumer.key, |
| 164 |
oauth_signature_method="PLAINTEXT", |
| 165 |
oauth_signature="&", |
| 166 |
) |
| 167 |
url = web_root + request_token_page |
| 168 |
headers = {"Referer": web_root} |
| 169 |
if token_format == self.DICT_TOKEN_FORMAT: |
| 170 |
headers["Accept"] = "application/json" |
| 171 |
response, content = _http_post(url, headers, params) |
| 172 |
if isinstance(content, bytes): |
| 173 |
content = content.decode("utf-8") |
| 174 |
if token_format == self.DICT_TOKEN_FORMAT: |
| 175 |
params = json.loads(content) |
| 176 |
if context is not None: |
| 177 |
params["lp.context"] = context |
| 178 |
self._request_token = AccessToken.from_params(params) |
| 179 |
return params |
| 180 |
else: |
| 181 |
self._request_token = AccessToken.from_string(content) |
| 182 |
url = "%s%s?oauth_token=%s" % ( |
| 183 |
web_root, |
| 184 |
authorize_token_page, |
| 185 |
self._request_token.key, |
| 186 |
) |
| 187 |
if context is not None: |
| 188 |
self._request_token.context = context |
| 189 |
url += "&lp.context=%s" % context |
| 190 |
return url |
| 191 |
|
| 192 |
def exchange_request_token_for_access_token( |
| 193 |
self, web_root=uris.STAGING_WEB_ROOT |
| 194 |
): |
| 195 |
"""Exchange the previously obtained request token for an access token. |
| 196 |
|
| 197 |
This method must not be called unless get_request_token() has been |
| 198 |
called and completed successfully. |
| 199 |
|
| 200 |
The access token will be stored as self.access_token. |
| 201 |
|
| 202 |
:param web_root: The base URL of the website that granted the |
| 203 |
request token. |
| 204 |
""" |
| 205 |
assert ( |
| 206 |
self._request_token is not None |
| 207 |
), "get_request_token() doesn't seem to have been called." |
| 208 |
web_root = uris.lookup_web_root(web_root) |
| 209 |
params = dict( |
| 210 |
oauth_consumer_key=self.consumer.key, |
| 211 |
oauth_signature_method="PLAINTEXT", |
| 212 |
oauth_token=self._request_token.key, |
| 213 |
oauth_signature="&%s" % self._request_token.secret, |
| 214 |
) |
| 215 |
url = web_root + access_token_page |
| 216 |
headers = {"Referer": web_root} |
| 217 |
response, content = _http_post(url, headers, params) |
| 218 |
self.access_token = AccessToken.from_string(content) |
| 219 |
|
| 220 |
|
| 221 |
class AccessToken(_AccessToken): |
| 222 |
"""An OAuth access token.""" |
| 223 |
|
| 224 |
@classmethod |
| 225 |
def from_params(cls, params): |
| 226 |
"""Create and return a new `AccessToken` from the given dict.""" |
| 227 |
key = params["oauth_token"] |
| 228 |
secret = params["oauth_token_secret"] |
| 229 |
context = params.get("lp.context") |
| 230 |
return cls(key, secret, context) |
| 231 |
|
| 232 |
@classmethod |
| 233 |
def from_string(cls, query_string): |
| 234 |
"""Create and return a new `AccessToken` from the given string.""" |
| 235 |
if not isinstance(query_string, str): |
| 236 |
query_string = query_string.decode("utf-8") |
| 237 |
params = parse_qs(query_string, keep_blank_values=False) |
| 238 |
key = params["oauth_token"] |
| 239 |
assert len(key) == 1, "Query string must have exactly one oauth_token." |
| 240 |
key = key[0] |
| 241 |
secret = params["oauth_token_secret"] |
| 242 |
assert len(secret) == 1, "Query string must have exactly one secret." |
| 243 |
secret = secret[0] |
| 244 |
context = params.get("lp.context") |
| 245 |
if context is not None: |
| 246 |
assert ( |
| 247 |
len(context) == 1 |
| 248 |
), "Query string must have exactly one context" |
| 249 |
context = context[0] |
| 250 |
return cls(key, secret, context) |
| 251 |
|
| 252 |
|
| 253 |
class AnonymousAccessToken(_AccessToken): |
| 254 |
"""An OAuth access token that doesn't authenticate anybody. |
| 255 |
|
| 256 |
This token can be used for anonymous access. |
| 257 |
""" |
| 258 |
|
| 259 |
def __init__(self): |
| 260 |
super().__init__("", "") |
| 261 |
|
| 262 |
|
| 263 |
class CredentialStore: |
| 264 |
"""Store OAuth credentials locally. |
| 265 |
|
| 266 |
This is a generic superclass. To implement a specific way of |
| 267 |
storing credentials locally you'll need to subclass this class, |
| 268 |
and implement `do_save` and `do_load`. |
| 269 |
""" |
| 270 |
|
| 271 |
def __init__(self, credential_save_failed=None): |
| 272 |
"""Constructor. |
| 273 |
|
| 274 |
:param credential_save_failed: A callback to be invoked if the |
| 275 |
save to local storage fails. You should never invoke this |
| 276 |
callback yourself! Instead, you should raise an exception |
| 277 |
from do_save(). |
| 278 |
""" |
| 279 |
self.credential_save_failed = credential_save_failed |
| 280 |
|
| 281 |
def save(self, credentials, unique_consumer_id): |
| 282 |
"""Save the credentials and invoke the callback on failure. |
| 283 |
|
| 284 |
Do not override this method when subclassing. Override |
| 285 |
do_save() instead. |
| 286 |
""" |
| 287 |
try: |
| 288 |
self.do_save(credentials, unique_consumer_id) |
| 289 |
except EXPLOSIVE_ERRORS: |
| 290 |
raise |
| 291 |
except Exception as e: |
| 292 |
if self.credential_save_failed is None: |
| 293 |
raise e |
| 294 |
self.credential_save_failed() |
| 295 |
return credentials |
| 296 |
|
| 297 |
def do_save(self, credentials, unique_consumer_id): |
| 298 |
"""Store newly-authorized credentials locally for later use. |
| 299 |
|
| 300 |
:param credentials: A Credentials object to save. |
| 301 |
:param unique_consumer_id: A string uniquely identifying an |
| 302 |
OAuth consumer on a Launchpad instance. |
| 303 |
""" |
| 304 |
raise NotImplementedError() |
| 305 |
|
| 306 |
def load(self, unique_key): |
| 307 |
"""Retrieve credentials from a local store. |
| 308 |
|
| 309 |
This method is the inverse of `save`. |
| 310 |
|
| 311 |
There's no special behavior in this method--it just calls |
| 312 |
`do_load`. There _is_ special behavior in `save`, and this |
| 313 |
way, developers can remember to implement `do_save` and |
| 314 |
`do_load`, not `do_save` and `load`. |
| 315 |
|
| 316 |
:param unique_key: A string uniquely identifying an OAuth consumer |
| 317 |
on a Launchpad instance. |
| 318 |
|
| 319 |
:return: A `Credentials` object if one is found in the local |
| 320 |
store, and None otherise. |
| 321 |
""" |
| 322 |
return self.do_load(unique_key) |
| 323 |
|
| 324 |
def do_load(self, unique_key): |
| 325 |
"""Retrieve credentials from a local store. |
| 326 |
|
| 327 |
This method is the inverse of `do_save`. |
| 328 |
|
| 329 |
:param unique_key: A string uniquely identifying an OAuth consumer |
| 330 |
on a Launchpad instance. |
| 331 |
|
| 332 |
:return: A `Credentials` object if one is found in the local |
| 333 |
store, and None otherise. |
| 334 |
""" |
| 335 |
raise NotImplementedError() |
| 336 |
|
| 337 |
|
| 338 |
class KeyringCredentialStore(CredentialStore): |
| 339 |
"""Store credentials in the GNOME keyring or KDE wallet. |
| 340 |
|
| 341 |
This is a good solution for desktop applications and interactive |
| 342 |
scripts. It doesn't work for non-interactive scripts, or for |
| 343 |
integrating third-party websites into Launchpad. |
| 344 |
""" |
| 345 |
|
| 346 |
B64MARKER = b"<B64>" |
| 347 |
|
| 348 |
def __init__(self, credential_save_failed=None, fallback=False): |
| 349 |
super().__init__(credential_save_failed) |
| 350 |
self._fallback = None |
| 351 |
if fallback: |
| 352 |
self._fallback = MemoryCredentialStore(credential_save_failed) |
| 353 |
|
| 354 |
@staticmethod |
| 355 |
def _ensure_keyring_imported(): |
| 356 |
"""Ensure the keyring module is imported (postponing side effects). |
| 357 |
|
| 358 |
The keyring module initializes the environment-dependent backend at |
| 359 |
import time (nasty). We want to avoid that initialization because it |
| 360 |
may do things like prompt the user to unlock their password store |
| 361 |
(e.g., KWallet). |
| 362 |
""" |
| 363 |
if "keyring" not in globals(): |
| 364 |
global keyring |
| 365 |
import keyring |
| 366 |
if "NoKeyringError" not in globals(): |
| 367 |
global NoKeyringError |
| 368 |
try: |
| 369 |
from keyring.errors import NoKeyringError |
| 370 |
except ImportError: |
| 371 |
NoKeyringError = RuntimeError |
| 372 |
|
| 373 |
def do_save(self, credentials, unique_key): |
| 374 |
"""Store newly-authorized credentials in the keyring.""" |
| 375 |
self._ensure_keyring_imported() |
| 376 |
serialized = credentials.serialize() |
| 377 |
# Some users have reported problems with corrupted keyrings, both in |
| 378 |
# Gnome and KDE, when newlines are included in the password. Avoid |
| 379 |
# this problem by base 64 encoding the serialized value. |
| 380 |
serialized = self.B64MARKER + b64encode(serialized) |
| 381 |
try: |
| 382 |
keyring.set_password( |
| 383 |
"launchpadlib", unique_key, serialized.decode("utf-8") |
| 384 |
) |
| 385 |
except NoKeyringError as e: |
| 386 |
# keyring < 21.2.0 raises RuntimeError rather than anything more |
| 387 |
# specific. Make sure it's the exception we're interested in. |
| 388 |
if ( |
| 389 |
NoKeyringError == RuntimeError |
| 390 |
and "No recommended backend was available" not in str(e) |
| 391 |
): |
| 392 |
raise |
| 393 |
if self._fallback: |
| 394 |
self._fallback.save(credentials, unique_key) |
| 395 |
else: |
| 396 |
raise |
| 397 |
|
| 398 |
def do_load(self, unique_key): |
| 399 |
"""Retrieve credentials from the keyring.""" |
| 400 |
self._ensure_keyring_imported() |
| 401 |
try: |
| 402 |
credential_string = keyring.get_password( |
| 403 |
"launchpadlib", unique_key |
| 404 |
) |
| 405 |
except NoKeyringError as e: |
| 406 |
# keyring < 21.2.0 raises RuntimeError rather than anything more |
| 407 |
# specific. Make sure it's the exception we're interested in. |
| 408 |
if ( |
| 409 |
NoKeyringError == RuntimeError |
| 410 |
and "No recommended backend was available" not in str(e) |
| 411 |
): |
| 412 |
raise |
| 413 |
if self._fallback: |
| 414 |
return self._fallback.load(unique_key) |
| 415 |
else: |
| 416 |
raise |
| 417 |
if credential_string is not None: |
| 418 |
if isinstance(credential_string, str): |
| 419 |
credential_string = credential_string.encode("utf8") |
| 420 |
if credential_string.startswith(self.B64MARKER): |
| 421 |
try: |
| 422 |
credential_string = b64decode( |
| 423 |
credential_string[len(self.B64MARKER) :] |
| 424 |
) |
| 425 |
except TypeError: |
| 426 |
# The credential_string should be base 64 but cannot be |
| 427 |
# decoded. |
| 428 |
return None |
| 429 |
try: |
| 430 |
credentials = Credentials.from_string(credential_string) |
| 431 |
return credentials |
| 432 |
except Exception: |
| 433 |
# If any error occurs at this point the most reasonable thing |
| 434 |
# to do is return no credentials, which will require |
| 435 |
# re-authorization but the user will be able to proceed. |
| 436 |
return None |
| 437 |
return None |
| 438 |
|
| 439 |
|
| 440 |
class UnencryptedFileCredentialStore(CredentialStore): |
| 441 |
"""Store credentials unencrypted in a file on disk. |
| 442 |
|
| 443 |
This is a good solution for scripts that need to run without any |
| 444 |
user interaction. |
| 445 |
""" |
| 446 |
|
| 447 |
def __init__(self, filename, credential_save_failed=None): |
| 448 |
super().__init__(credential_save_failed) |
| 449 |
self.filename = filename |
| 450 |
|
| 451 |
def do_save(self, credentials, unique_key): |
| 452 |
"""Save the credentials to disk.""" |
| 453 |
credentials.save_to_path(self.filename) |
| 454 |
|
| 455 |
def do_load(self, unique_key): |
| 456 |
"""Load the credentials from disk.""" |
| 457 |
if ( |
| 458 |
os.path.exists(self.filename) |
| 459 |
and not os.stat(self.filename)[stat.ST_SIZE] == 0 |
| 460 |
): |
| 461 |
return Credentials.load_from_path(self.filename) |
| 462 |
return None |
| 463 |
|
| 464 |
|
| 465 |
class MemoryCredentialStore(CredentialStore): |
| 466 |
"""CredentialStore that stores keys only in memory. |
| 467 |
|
| 468 |
This can be used to provide a CredentialStore instance without |
| 469 |
actually saving any key to persistent storage. |
| 470 |
""" |
| 471 |
|
| 472 |
def __init__(self, credential_save_failed=None): |
| 473 |
super().__init__(credential_save_failed) |
| 474 |
self._credentials = {} |
| 475 |
|
| 476 |
def do_save(self, credentials, unique_key): |
| 477 |
"""Store the credentials in our dict""" |
| 478 |
self._credentials[unique_key] = credentials |
| 479 |
|
| 480 |
def do_load(self, unique_key): |
| 481 |
"""Retrieve the credentials from our dict""" |
| 482 |
return self._credentials.get(unique_key) |
| 483 |
|
| 484 |
|
| 485 |
class RequestTokenAuthorizationEngine: |
| 486 |
"""The superclass of all request token authorizers. |
| 487 |
|
| 488 |
This base class does not implement request token authorization, |
| 489 |
since that varies depending on how you want the end-user to |
| 490 |
authorize a request token. You'll need to subclass this class and |
| 491 |
implement `make_end_user_authorize_token`. |
| 492 |
""" |
| 493 |
|
| 494 |
UNAUTHORIZED_ACCESS_LEVEL = "UNAUTHORIZED" |
| 495 |
|
| 496 |
def __init__( |
| 497 |
self, |
| 498 |
service_root, |
| 499 |
application_name=None, |
| 500 |
consumer_name=None, |
| 501 |
allow_access_levels=None, |
| 502 |
): |
| 503 |
"""Base class initialization. |
| 504 |
|
| 505 |
:param service_root: The root of the Launchpad instance being |
| 506 |
used. |
| 507 |
|
| 508 |
:param application_name: The name of the application that |
| 509 |
wants to use launchpadlib. This is used in conjunction |
| 510 |
with a desktop-wide integration. |
| 511 |
|
| 512 |
If you specify this argument, your values for |
| 513 |
consumer_name and allow_access_levels are ignored. |
| 514 |
|
| 515 |
:param consumer_name: The OAuth consumer name, for an |
| 516 |
application that wants its own point of integration into |
| 517 |
Launchpad. In almost all cases, you want to specify |
| 518 |
application_name instead and do a desktop-wide |
| 519 |
integration. The exception is when you're integrating a |
| 520 |
third-party website into Launchpad. |
| 521 |
|
| 522 |
:param allow_access_levels: A list of the Launchpad access |
| 523 |
levels to present to the user. ('READ_PUBLIC' and so on.) |
| 524 |
Your value for this argument will be ignored during a |
| 525 |
desktop-wide integration. |
| 526 |
:type allow_access_levels: A list of strings. |
| 527 |
""" |
| 528 |
self.service_root = uris.lookup_service_root(service_root) |
| 529 |
self.web_root = uris.web_root_for_service_root(service_root) |
| 530 |
|
| 531 |
if application_name is None and consumer_name is None: |
| 532 |
raise ValueError( |
| 533 |
"You must provide either application_name or consumer_name." |
| 534 |
) |
| 535 |
|
| 536 |
if application_name is not None and consumer_name is not None: |
| 537 |
raise ValueError( |
| 538 |
"You must provide only one of application_name and " |
| 539 |
"consumer_name. (You provided %r and %r.)" |
| 540 |
% (application_name, consumer_name) |
| 541 |
) |
| 542 |
|
| 543 |
if consumer_name is None: |
| 544 |
# System-wide integration. Create a system-wide consumer |
| 545 |
# and identify the application using a separate |
| 546 |
# application name. |
| 547 |
allow_access_levels = ["DESKTOP_INTEGRATION"] |
| 548 |
consumer = SystemWideConsumer(application_name) |
| 549 |
else: |
| 550 |
# Application-specific integration. Use the provided |
| 551 |
# consumer name to create a consumer automatically. |
| 552 |
consumer = Consumer(consumer_name) |
| 553 |
application_name = consumer_name |
| 554 |
|
| 555 |
self.consumer = consumer |
| 556 |
self.application_name = application_name |
| 557 |
|
| 558 |
self.allow_access_levels = allow_access_levels or [] |
| 559 |
|
| 560 |
@property |
| 561 |
def unique_consumer_id(self): |
| 562 |
"""Return a string identifying this consumer on this host.""" |
| 563 |
return self.consumer.key + "@" + self.service_root |
| 564 |
|
| 565 |
def authorization_url(self, request_token): |
| 566 |
"""Return the authorization URL for a request token. |
| 567 |
|
| 568 |
This is the URL the end-user must visit to authorize the |
| 569 |
token. How exactly does this happen? That depends on the |
| 570 |
subclass implementation. |
| 571 |
""" |
| 572 |
page = "%s?oauth_token=%s" % (authorize_token_page, request_token) |
| 573 |
allow_permission = "&allow_permission=" |
| 574 |
if len(self.allow_access_levels) > 0: |
| 575 |
page += allow_permission + allow_permission.join( |
| 576 |
self.allow_access_levels |
| 577 |
) |
| 578 |
return urljoin(self.web_root, page) |
| 579 |
|
| 580 |
def __call__(self, credentials, credential_store): |
| 581 |
"""Authorize a token and associate it with the given credentials. |
| 582 |
|
| 583 |
If the credential store runs into a problem storing the |
| 584 |
credential locally, the `credential_save_failed` callback will |
| 585 |
be invoked. The callback will not be invoked if there's a |
| 586 |
problem authorizing the credentials. |
| 587 |
|
| 588 |
:param credentials: A `Credentials` object. If the end-user |
| 589 |
authorizes these credentials, this object will have its |
| 590 |
.access_token property set. |
| 591 |
|
| 592 |
:param credential_store: A `CredentialStore` object. If the |
| 593 |
end-user authorizes the credentials, they will be |
| 594 |
persisted locally using this object. |
| 595 |
|
| 596 |
:return: If the credentials are successfully authorized, the |
| 597 |
return value is the `Credentials` object originally passed |
| 598 |
in. Otherwise the return value is None. |
| 599 |
""" |
| 600 |
request_token_string = self.get_request_token(credentials) |
| 601 |
# Hand off control to the end-user. |
| 602 |
self.make_end_user_authorize_token(credentials, request_token_string) |
| 603 |
if credentials.access_token is None: |
| 604 |
# The end-user refused to authorize the application. |
| 605 |
return None |
| 606 |
# save() invokes the callback on failure. |
| 607 |
credential_store.save(credentials, self.unique_consumer_id) |
| 608 |
return credentials |
| 609 |
|
| 610 |
def get_request_token(self, credentials): |
| 611 |
"""Get a new request token from the server. |
| 612 |
|
| 613 |
:param return: The request token. |
| 614 |
""" |
| 615 |
authorization_json = credentials.get_request_token( |
| 616 |
web_root=self.web_root, token_format=Credentials.DICT_TOKEN_FORMAT |
| 617 |
) |
| 618 |
return authorization_json["oauth_token"] |
| 619 |
|
| 620 |
def make_end_user_authorize_token(self, credentials, request_token): |
| 621 |
"""Authorize the given request token using the given credentials. |
| 622 |
|
| 623 |
Your subclass must implement this method: it has no default |
| 624 |
implementation. |
| 625 |
|
| 626 |
Because an access token may expire or be revoked in the middle |
| 627 |
of a session, this method may be called at arbitrary points in |
| 628 |
a launchpadlib session, or even multiple times during a single |
| 629 |
session (with a different request token each time). |
| 630 |
|
| 631 |
In most cases, however, this method will be called at the |
| 632 |
beginning of a launchpadlib session, or not at all. |
| 633 |
""" |
| 634 |
raise NotImplementedError() |
| 635 |
|
| 636 |
|
| 637 |
class AuthorizeRequestTokenWithURL(RequestTokenAuthorizationEngine): |
| 638 |
"""Authorize using a URL. |
| 639 |
|
| 640 |
This authorizer simply shows the URL for the user to open for |
| 641 |
authorization, and waits until the server responds. |
| 642 |
""" |
| 643 |
|
| 644 |
WAITING_FOR_USER = ( |
| 645 |
"Please open this authorization page:\n" |
| 646 |
" (%s)\n" |
| 647 |
"in your browser. Use your browser to authorize\n" |
| 648 |
"this program to access Launchpad on your behalf." |
| 649 |
) |
| 650 |
WAITING_FOR_LAUNCHPAD = "Press Enter after authorizing in your browser." |
| 651 |
|
| 652 |
def output(self, message): |
| 653 |
"""Display a message. |
| 654 |
|
| 655 |
By default, prints the message to standard output. The message |
| 656 |
does not require any user interaction--it's solely |
| 657 |
informative. |
| 658 |
""" |
| 659 |
print(message) |
| 660 |
|
| 661 |
def notify_end_user_authorization_url(self, authorization_url): |
| 662 |
"""Notify the end-user of the URL.""" |
| 663 |
self.output(self.WAITING_FOR_USER % authorization_url) |
| 664 |
|
| 665 |
def check_end_user_authorization(self, credentials): |
| 666 |
"""Check if the end-user authorized""" |
| 667 |
try: |
| 668 |
credentials.exchange_request_token_for_access_token(self.web_root) |
| 669 |
except HTTPError as e: |
| 670 |
if e.response.status == 403: |
| 671 |
# The user decided not to authorize this |
| 672 |
# application. |
| 673 |
raise EndUserDeclinedAuthorization(e.content) |
| 674 |
else: |
| 675 |
if e.response.status != 401: |
| 676 |
# There was an error accessing the server. |
| 677 |
print("Unexpected response from Launchpad:") |
| 678 |
print(e) |
| 679 |
# The user has not made a decision yet. |
| 680 |
raise EndUserNoAuthorization(e.content) |
| 681 |
return credentials.access_token is not None |
| 682 |
|
| 683 |
def wait_for_end_user_authorization(self, credentials): |
| 684 |
"""Wait for the end-user to authorize""" |
| 685 |
self.output(self.WAITING_FOR_LAUNCHPAD) |
| 686 |
stdin.readline() |
| 687 |
self.check_end_user_authorization(credentials) |
| 688 |
|
| 689 |
def make_end_user_authorize_token(self, credentials, request_token): |
| 690 |
"""Have the end-user authorize the token using a URL.""" |
| 691 |
authorization_url = self.authorization_url(request_token) |
| 692 |
self.notify_end_user_authorization_url(authorization_url) |
| 693 |
self.wait_for_end_user_authorization(credentials) |
| 694 |
|
| 695 |
|
| 696 |
class AuthorizeRequestTokenWithBrowser(AuthorizeRequestTokenWithURL): |
| 697 |
"""Authorize using a URL that pops-up automatically in a browser. |
| 698 |
|
| 699 |
This authorizer simply opens up the end-user's web browser to a |
| 700 |
Launchpad URL and lets the end-user authorize the request token |
| 701 |
themselves. |
| 702 |
|
| 703 |
This is the same as its superclass, except this class also |
| 704 |
performs the browser automatic opening of the URL. |
| 705 |
""" |
| 706 |
|
| 707 |
WAITING_FOR_USER = ( |
| 708 |
"The authorization page:\n" |
| 709 |
" (%s)\n" |
| 710 |
"should be opening in your browser. Use your browser to authorize\n" |
| 711 |
"this program to access Launchpad on your behalf." |
| 712 |
) |
| 713 |
TIMEOUT_MESSAGE = "Press Enter to continue or wait (%d) seconds..." |
| 714 |
TIMEOUT = 5 |
| 715 |
TERMINAL_BROWSERS = ( |
| 716 |
"www-browser", |
| 717 |
"links", |
| 718 |
"links2", |
| 719 |
"lynx", |
| 720 |
"elinks", |
| 721 |
"elinks-lite", |
| 722 |
"netrik", |
| 723 |
"w3m", |
| 724 |
) |
| 725 |
WAITING_FOR_LAUNCHPAD = ( |
| 726 |
"Waiting to hear from Launchpad about your decision..." |
| 727 |
) |
| 728 |
|
| 729 |
def __init__( |
| 730 |
self, |
| 731 |
service_root, |
| 732 |
application_name, |
| 733 |
consumer_name=None, |
| 734 |
credential_save_failed=None, |
| 735 |
allow_access_levels=None, |
| 736 |
): |
| 737 |
"""Constructor. |
| 738 |
|
| 739 |
:param service_root: See `RequestTokenAuthorizationEngine`. |
| 740 |
:param application_name: See `RequestTokenAuthorizationEngine`. |
| 741 |
:param consumer_name: The value of this argument is |
| 742 |
ignored. If we have the capability to open the end-user's |
| 743 |
web browser, we must be running on the end-user's computer, |
| 744 |
so we should do a full desktop integration. |
| 745 |
:param credential_save_failed: See `RequestTokenAuthorizationEngine`. |
| 746 |
:param allow_access_levels: The value of this argument is |
| 747 |
ignored, for the same reason as consumer_name. |
| 748 |
""" |
| 749 |
# It doesn't look like we're doing anything here, but we |
| 750 |
# are discarding the passed-in values for consumer_name and |
| 751 |
# allow_access_levels. |
| 752 |
super().__init__( |
| 753 |
service_root, application_name, None, credential_save_failed |
| 754 |
) |
| 755 |
|
| 756 |
def notify_end_user_authorization_url(self, authorization_url): |
| 757 |
"""Notify the end-user of the URL.""" |
| 758 |
super().notify_end_user_authorization_url(authorization_url) |
| 759 |
|
| 760 |
try: |
| 761 |
browser_obj = webbrowser.get() |
| 762 |
browser = getattr(browser_obj, "basename", None) |
| 763 |
console_browser = browser in self.TERMINAL_BROWSERS |
| 764 |
except webbrowser.Error: |
| 765 |
browser_obj = None |
| 766 |
console_browser = False |
| 767 |
|
| 768 |
if console_browser: |
| 769 |
self.output(self.TIMEOUT_MESSAGE % self.TIMEOUT) |
| 770 |
# Wait a little time before attempting to launch browser, |
| 771 |
# give users the chance to press a key to skip it anyway. |
| 772 |
rlist, _, _ = select([stdin], [], [], self.TIMEOUT) |
| 773 |
if rlist: |
| 774 |
stdin.readline() |
| 775 |
|
| 776 |
if browser_obj is not None: |
| 777 |
webbrowser.open(authorization_url) |
| 778 |
|
| 779 |
def wait_for_end_user_authorization(self, credentials): |
| 780 |
"""Wait for the end-user to authorize""" |
| 781 |
self.output(self.WAITING_FOR_LAUNCHPAD) |
| 782 |
start_time = time.time() |
| 783 |
while credentials.access_token is None: |
| 784 |
time.sleep(access_token_poll_time) |
| 785 |
try: |
| 786 |
if self.check_end_user_authorization(credentials): |
| 787 |
break |
| 788 |
except EndUserNoAuthorization: |
| 789 |
pass |
| 790 |
if time.time() >= start_time + access_token_poll_timeout: |
| 791 |
raise TokenAuthorizationTimedOut( |
| 792 |
"Timed out after %d seconds." % access_token_poll_timeout |
| 793 |
) |
| 794 |
|
| 795 |
|
| 796 |
class TokenAuthorizationException(Exception): |
| 797 |
pass |
| 798 |
|
| 799 |
|
| 800 |
class RequestTokenAlreadyAuthorized(TokenAuthorizationException): |
| 801 |
pass |
| 802 |
|
| 803 |
|
| 804 |
class EndUserAuthorizationFailed(TokenAuthorizationException): |
| 805 |
"""Superclass exception for all failures of end-user authorization""" |
| 806 |
|
| 807 |
pass |
| 808 |
|
| 809 |
|
| 810 |
class EndUserDeclinedAuthorization(EndUserAuthorizationFailed): |
| 811 |
"""End-user declined authorization""" |
| 812 |
|
| 813 |
pass |
| 814 |
|
| 815 |
|
| 816 |
class EndUserNoAuthorization(EndUserAuthorizationFailed): |
| 817 |
"""End-user did not perform any authorization""" |
| 818 |
|
| 819 |
pass |
| 820 |
|
| 821 |
|
| 822 |
class TokenAuthorizationTimedOut(EndUserNoAuthorization): |
| 823 |
"""End-user did not perform any authorization in timeout period""" |
| 824 |
|
| 825 |
pass |
| 826 |
|
| 827 |
|
| 828 |
class ClientError(TokenAuthorizationException): |
| 829 |
pass |
| 830 |
|
| 831 |
|
| 832 |
class ServerError(TokenAuthorizationException): |
| 833 |
pass |
| 834 |
|
| 835 |
|
| 836 |
class NoLaunchpadAccount(TokenAuthorizationException): |
| 837 |
pass |
| 838 |
|
| 839 |
|
| 840 |
class TooManyAuthenticationFailures(TokenAuthorizationException): |
| 841 |
pass |