| 1 |
# Copyright 2009-2018 Canonical Ltd. |
| 2 |
|
| 3 |
# This file is part of lazr.restfulclient. |
| 4 |
# |
| 5 |
# lazr.restfulclient is free software: you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU Lesser General Public License as |
| 7 |
# published by the Free Software Foundation, either version 3 of the |
| 8 |
# License, or (at your option) any later version. |
| 9 |
# |
| 10 |
# lazr.restfulclient is distributed in the hope that it will be useful, but |
| 11 |
# WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 13 |
# Lesser General Public License for more details. |
| 14 |
# |
| 15 |
# You should have received a copy of the GNU Lesser General Public |
| 16 |
# License along with lazr.restfulclient. If not, see |
| 17 |
# <http://www.gnu.org/licenses/>. |
| 18 |
|
| 19 |
"""OAuth classes for use with lazr.restfulclient.""" |
| 20 |
|
| 21 |
|
| 22 |
try: |
| 23 |
# Python 3, SafeConfigParser was renamed to just ConfigParser. |
| 24 |
from configparser import ConfigParser as SafeConfigParser |
| 25 |
except ImportError: |
| 26 |
from ConfigParser import SafeConfigParser |
| 27 |
|
| 28 |
import os |
| 29 |
import platform |
| 30 |
import socket |
| 31 |
import stat |
| 32 |
|
| 33 |
import six |
| 34 |
from oauthlib import oauth1 |
| 35 |
from six.moves.urllib.parse import parse_qs, urlencode |
| 36 |
|
| 37 |
from lazr.restfulclient.authorize import HttpAuthorizer |
| 38 |
from lazr.restfulclient.errors import CredentialsFileError |
| 39 |
|
| 40 |
__metaclass__ = type |
| 41 |
__all__ = [ |
| 42 |
"AccessToken", |
| 43 |
"Consumer", |
| 44 |
"OAuthAuthorizer", |
| 45 |
"SystemWideConsumer", |
| 46 |
] |
| 47 |
|
| 48 |
|
| 49 |
CREDENTIALS_FILE_VERSION = "1" |
| 50 |
|
| 51 |
|
| 52 |
# For compatibility, Consumer and AccessToken are defined using terminology |
| 53 |
# from the older oauth library rather than the newer oauthlib. |
| 54 |
class Consumer: |
| 55 |
"""An OAuth consumer (application).""" |
| 56 |
|
| 57 |
def __init__(self, key, secret="", application_name=None): |
| 58 |
"""Initialize |
| 59 |
|
| 60 |
:param key: The OAuth consumer key |
| 61 |
:param secret: The OAuth consumer secret. Don't use this. It's |
| 62 |
a misfeature, and lazr.restful doesn't expect it. |
| 63 |
:param application_name: An application name, if different |
| 64 |
from the consumer key. If present, this will be used in |
| 65 |
the User-Agent header. |
| 66 |
""" |
| 67 |
self.key = key |
| 68 |
self.secret = secret |
| 69 |
self.application_name = application_name |
| 70 |
|
| 71 |
|
| 72 |
class AccessToken: |
| 73 |
"""An OAuth access token.""" |
| 74 |
|
| 75 |
def __init__(self, key, secret="", context=None): |
| 76 |
self.key = key |
| 77 |
self.secret = secret |
| 78 |
self.context = context |
| 79 |
|
| 80 |
def to_string(self): |
| 81 |
return urlencode( |
| 82 |
[ |
| 83 |
("oauth_token_secret", self.secret), |
| 84 |
("oauth_token", self.key), |
| 85 |
] |
| 86 |
) |
| 87 |
|
| 88 |
__str__ = to_string |
| 89 |
|
| 90 |
@classmethod |
| 91 |
def from_string(cls, s): |
| 92 |
params = parse_qs(s, keep_blank_values=False) |
| 93 |
key = params["oauth_token"][0] |
| 94 |
secret = params["oauth_token_secret"][0] |
| 95 |
return cls(key, secret) |
| 96 |
|
| 97 |
|
| 98 |
class TruthyString(six.text_type): |
| 99 |
"""A Unicode string which is always true.""" |
| 100 |
|
| 101 |
def __bool__(self): |
| 102 |
return True |
| 103 |
|
| 104 |
__nonzero__ = __bool__ |
| 105 |
|
| 106 |
|
| 107 |
class SystemWideConsumer(Consumer): |
| 108 |
"""A consumer associated with the logged-in user rather than an app. |
| 109 |
|
| 110 |
This can be used to share a single OAuth token among multiple |
| 111 |
desktop applications. The OAuth consumer key will be derived from |
| 112 |
system information (platform and hostname). |
| 113 |
""" |
| 114 |
|
| 115 |
KEY_FORMAT = "System-wide: %s (%s)" |
| 116 |
|
| 117 |
def __init__(self, application_name, secret=""): |
| 118 |
"""Constructor. |
| 119 |
|
| 120 |
:param application_name: An application name. This will be |
| 121 |
used in the User-Agent header. |
| 122 |
:param secret: The OAuth consumer secret. Don't use this. It's |
| 123 |
a misfeature, and lazr.restful doesn't expect it. |
| 124 |
""" |
| 125 |
super(SystemWideConsumer, self).__init__( |
| 126 |
self.consumer_key, secret, application_name |
| 127 |
) |
| 128 |
|
| 129 |
@property |
| 130 |
def consumer_key(self): |
| 131 |
"""The system-wide OAuth consumer key for this computer. |
| 132 |
|
| 133 |
This key identifies the platform and the computer's |
| 134 |
hostname. It does not identify the active user. |
| 135 |
""" |
| 136 |
try: |
| 137 |
import distro |
| 138 |
|
| 139 |
distname = distro.name() |
| 140 |
except Exception: |
| 141 |
# This can happen due to various kinds of failures with the data |
| 142 |
# sources used by the distro module. |
| 143 |
distname = "" |
| 144 |
if distname == "": |
| 145 |
distname = platform.system() # (eg. "Windows") |
| 146 |
return self.KEY_FORMAT % (distname, socket.gethostname()) |
| 147 |
|
| 148 |
|
| 149 |
class OAuthAuthorizer(HttpAuthorizer): |
| 150 |
"""A client that signs every outgoing request with OAuth credentials.""" |
| 151 |
|
| 152 |
def __init__( |
| 153 |
self, |
| 154 |
consumer_name=None, |
| 155 |
consumer_secret="", |
| 156 |
access_token=None, |
| 157 |
oauth_realm="OAuth", |
| 158 |
application_name=None, |
| 159 |
): |
| 160 |
self.consumer = None |
| 161 |
if consumer_name is not None: |
| 162 |
self.consumer = Consumer( |
| 163 |
consumer_name, consumer_secret, application_name |
| 164 |
) |
| 165 |
self.access_token = access_token |
| 166 |
self.oauth_realm = oauth_realm |
| 167 |
|
| 168 |
@property |
| 169 |
def user_agent_params(self): |
| 170 |
"""Any information necessary to identify this user agent. |
| 171 |
|
| 172 |
In this case, the OAuth consumer name. |
| 173 |
""" |
| 174 |
params = {} |
| 175 |
if self.consumer is None: |
| 176 |
return params |
| 177 |
params["oauth_consumer"] = self.consumer.key |
| 178 |
if self.consumer.application_name is not None: |
| 179 |
params["application"] = self.consumer.application_name |
| 180 |
return params |
| 181 |
|
| 182 |
def load(self, readable_file): |
| 183 |
"""Load credentials from a file-like object. |
| 184 |
|
| 185 |
This overrides the consumer and access token given in the constructor |
| 186 |
and replaces them with the values read from the file. |
| 187 |
|
| 188 |
:param readable_file: A file-like object to read the credentials from |
| 189 |
:type readable_file: Any object supporting the file-like `read()` |
| 190 |
method |
| 191 |
""" |
| 192 |
# Attempt to load the access token from the file. |
| 193 |
parser = SafeConfigParser() |
| 194 |
if hasattr(parser, "read_file"): |
| 195 |
reader = parser.read_file |
| 196 |
else: |
| 197 |
reader = parser.readfp |
| 198 |
reader(readable_file) |
| 199 |
# Check the version number and extract the access token and |
| 200 |
# secret. Then convert these to the appropriate instances. |
| 201 |
if not parser.has_section(CREDENTIALS_FILE_VERSION): |
| 202 |
raise CredentialsFileError( |
| 203 |
"No configuration for version %s" % CREDENTIALS_FILE_VERSION |
| 204 |
) |
| 205 |
consumer_key = parser.get(CREDENTIALS_FILE_VERSION, "consumer_key") |
| 206 |
consumer_secret = parser.get( |
| 207 |
CREDENTIALS_FILE_VERSION, "consumer_secret" |
| 208 |
) |
| 209 |
self.consumer = Consumer(consumer_key, consumer_secret) |
| 210 |
access_token = parser.get(CREDENTIALS_FILE_VERSION, "access_token") |
| 211 |
access_secret = parser.get(CREDENTIALS_FILE_VERSION, "access_secret") |
| 212 |
self.access_token = AccessToken(access_token, access_secret) |
| 213 |
|
| 214 |
@classmethod |
| 215 |
def load_from_path(cls, path): |
| 216 |
"""Convenience method for loading credentials from a file. |
| 217 |
|
| 218 |
Open the file, create the Credentials and load from the file, |
| 219 |
and finally close the file and return the newly created |
| 220 |
Credentials instance. |
| 221 |
|
| 222 |
:param path: In which file the credential file should be saved. |
| 223 |
:type path: string |
| 224 |
:return: The loaded Credentials instance. |
| 225 |
:rtype: `Credentials` |
| 226 |
""" |
| 227 |
credentials = cls() |
| 228 |
credentials_file = open(path, "r") |
| 229 |
credentials.load(credentials_file) |
| 230 |
credentials_file.close() |
| 231 |
return credentials |
| 232 |
|
| 233 |
def save(self, writable_file): |
| 234 |
"""Write the credentials to the file-like object. |
| 235 |
|
| 236 |
:param writable_file: A file-like object to write the credentials to |
| 237 |
:type writable_file: Any object supporting the file-like `write()` |
| 238 |
method |
| 239 |
:raise CredentialsFileError: when there is either no consumer or no |
| 240 |
access token |
| 241 |
""" |
| 242 |
if self.consumer is None: |
| 243 |
raise CredentialsFileError("No consumer") |
| 244 |
if self.access_token is None: |
| 245 |
raise CredentialsFileError("No access token") |
| 246 |
|
| 247 |
parser = SafeConfigParser() |
| 248 |
parser.add_section(CREDENTIALS_FILE_VERSION) |
| 249 |
parser.set(CREDENTIALS_FILE_VERSION, "consumer_key", self.consumer.key) |
| 250 |
parser.set( |
| 251 |
CREDENTIALS_FILE_VERSION, "consumer_secret", self.consumer.secret |
| 252 |
) |
| 253 |
parser.set( |
| 254 |
CREDENTIALS_FILE_VERSION, "access_token", self.access_token.key |
| 255 |
) |
| 256 |
parser.set( |
| 257 |
CREDENTIALS_FILE_VERSION, "access_secret", self.access_token.secret |
| 258 |
) |
| 259 |
parser.write(writable_file) |
| 260 |
|
| 261 |
def save_to_path(self, path): |
| 262 |
"""Convenience method for saving credentials to a file. |
| 263 |
|
| 264 |
Create the file, call self.save(), and close the |
| 265 |
file. Existing files are overwritten. The resulting file will |
| 266 |
be readable and writable only by the user. |
| 267 |
|
| 268 |
:param path: In which file the credential file should be saved. |
| 269 |
:type path: string |
| 270 |
""" |
| 271 |
credentials_file = os.fdopen( |
| 272 |
os.open( |
| 273 |
path, |
| 274 |
(os.O_CREAT | os.O_TRUNC | os.O_WRONLY), |
| 275 |
(stat.S_IREAD | stat.S_IWRITE), |
| 276 |
), |
| 277 |
"w", |
| 278 |
) |
| 279 |
self.save(credentials_file) |
| 280 |
credentials_file.close() |
| 281 |
|
| 282 |
def authorizeRequest(self, absolute_uri, method, body, headers): |
| 283 |
"""Sign a request with OAuth credentials.""" |
| 284 |
client = oauth1.Client( |
| 285 |
self.consumer.key, |
| 286 |
client_secret=self.consumer.secret, |
| 287 |
resource_owner_key=TruthyString(self.access_token.key or ""), |
| 288 |
resource_owner_secret=self.access_token.secret, |
| 289 |
signature_method=oauth1.SIGNATURE_PLAINTEXT, |
| 290 |
realm=self.oauth_realm, |
| 291 |
) |
| 292 |
# The older oauth library (which may still be used on the server) |
| 293 |
# requires the oauth_token parameter to be present and will fail |
| 294 |
# authentication if it isn't. This hack forces it to be present |
| 295 |
# even if its value is the empty string. |
| 296 |
client.resource_owner_key = TruthyString(client.resource_owner_key) |
| 297 |
_, signed_headers, _ = client.sign(absolute_uri) |
| 298 |
for key, value in signed_headers.items(): |
| 299 |
# client.sign returns Unicode headers; convert these to native |
| 300 |
# strings. |
| 301 |
if six.PY2: |
| 302 |
key = key.encode("UTF-8") |
| 303 |
value = value.encode("UTF-8") |
| 304 |
headers[key] = value |