/usr/share/pyshared/ubuntu-sso-client/ubuntu_sso/utils/webclient/common.py is in python-ubuntu-sso-client 3.0.0-0ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | # -*- coding: utf-8 -*-
#
# Copyright 2011-2012 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL. If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so. If you
# do not wish to do so, delete this exception statement from your
# version. If you delete this exception statement from all source
# files in the program, then also delete it here.
"""The common bits of a webclient."""
import cgi
import collections
import os
from httplib2 import iri2uri
from oauth import oauth
from twisted.internet import defer
from urlparse import urlparse
from ubuntu_sso import USER_SUCCESS, UI_PROXY_CREDS_DIALOG
from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils.runner import spawn_program
from ubuntu_sso.utils.ui import SSL_DETAILS_TEMPLATE
from ubuntu_sso.utils.webclient.timestamp import TimestampChecker
SSL_DIALOG = 'ubuntu-sso-ssl-certificate-qt'
logger = setup_logging("ubuntu_sso.utils.webclient.common")
class WebClientError(Exception):
"""An http error happened while calling the webservice."""
class UnauthorizedError(WebClientError):
"""The request ended with bad_request, unauthorized or forbidden."""
class ProxyUnauthorizedError(WebClientError):
"""Failure raised when there is an issue with the proxy auth."""
class Response(object):
"""A response object."""
def __init__(self, content, headers=None):
"""Initialize this instance."""
self.content = content
self.headers = headers
class HeaderDict(collections.defaultdict):
"""A case insensitive dict for headers."""
# pylint: disable=E1002
def __init__(self, *args, **kwargs):
"""Handle case-insensitive keys."""
super(HeaderDict, self).__init__(list, *args, **kwargs)
# pylint: disable=E1101
for key, value in self.items():
super(HeaderDict, self).__delitem__(key)
self[key] = value
def __setitem__(self, key, value):
"""Set the value with a case-insensitive key."""
super(HeaderDict, self).__setitem__(key.lower(), value)
def __getitem__(self, key):
"""Get the value with a case-insensitive key."""
return super(HeaderDict, self).__getitem__(key.lower())
def __delitem__(self, key):
"""Delete the item with the case-insensitive key."""
super(HeaderDict, self).__delitem__(key.lower())
def __contains__(self, key):
"""Check the containment with a case-insensitive key."""
return super(HeaderDict, self).__contains__(key.lower())
class BaseWebClient(object):
"""The webclient base class, to be extended by backends."""
timestamp_checker = None
def __init__(self, appname='', username=None, password=None,
oauth_sign_plain=False):
"""Initialize this instance."""
self.appname = appname
self.username = username
self.password = password
self.proxy_username = None
self.proxy_password = None
self.oauth_sign_plain = oauth_sign_plain
def request(self, iri, method="GET", extra_headers=None,
oauth_credentials=None, post_content=None):
"""Return a deferred that will be fired with a Response object."""
raise NotImplementedError
@classmethod
def get_timestamp_checker(cls):
"""Get the timestamp checker for this class of webclient."""
if cls.timestamp_checker is None:
cls.timestamp_checker = TimestampChecker(cls)
return cls.timestamp_checker
def get_timestamp(self):
"""Get a timestamp synchronized with the server."""
return self.get_timestamp_checker().get_faithful_time()
def force_use_proxy(self, settings):
"""Setup this webclient to use the given proxy settings."""
raise NotImplementedError
def iri_to_uri(self, iri):
"""Transform a unicode iri into a ascii uri."""
if not isinstance(iri, unicode):
raise TypeError('iri %r should be unicode.' % iri)
return bytes(iri2uri(iri))
def build_oauth_request(self, method, uri, credentials, timestamp,
parameters=None):
"""Build an oauth request given some credentials."""
consumer = oauth.OAuthConsumer(credentials["consumer_key"],
credentials["consumer_secret"])
token = oauth.OAuthToken(credentials["token"],
credentials["token_secret"])
if not parameters:
_, _, _, _, query, _ = urlparse(uri)
parameters = dict(cgi.parse_qsl(query))
if timestamp:
parameters["oauth_timestamp"] = timestamp
request = oauth.OAuthRequest.from_consumer_and_token(
http_url=uri,
http_method=method,
parameters=parameters,
oauth_consumer=consumer,
token=token)
if self.oauth_sign_plain:
sig_method = oauth.OAuthSignatureMethod_PLAINTEXT()
else:
sig_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
request.sign_request(sig_method, consumer, token)
return request
def build_oauth_headers(self, method, uri, credentials, timestamp):
"""Build oauth request headers given some credentials."""
request = self.build_oauth_request(method, uri, credentials, timestamp)
return request.to_header()
@defer.inlineCallbacks
def build_signed_iri(self, iri, credentials, parameters=None):
"""Build a new iri signing 'iri' with 'credentials'."""
uri = self.iri_to_uri(iri)
timestamp = yield self.get_timestamp()
request = self.build_oauth_request(method='GET', uri=uri,
credentials=credentials,
timestamp=timestamp,
parameters=parameters)
defer.returnValue(request.to_url())
def shutdown(self):
"""Shut down all pending requests (if possible)."""
@defer.inlineCallbacks
def _load_proxy_creds_from_keyring(self, domain):
"""Load the proxy creds from the keyring."""
from ubuntu_sso.keyring import Keyring
keyring = Keyring()
try:
creds = yield keyring.get_credentials(str(domain))
logger.debug('Got credentials from keyring.')
except Exception, e:
logger.error('Error when retrieving the creds.')
raise WebClientError('Error when retrieving the creds.', e)
if creds is not None:
# if we are loading the same creds it means that we got the wrong
# ones
if (self.proxy_username == creds['username'] and
self.proxy_password == creds['password']):
defer.returnValue(False)
else:
self.proxy_username = creds['username']
self.proxy_password = creds['password']
defer.returnValue(True)
logger.debug('Proxy creds not in keyring.')
defer.returnValue(False)
def _launch_proxy_creds_dialog(self, domain, retry):
"""Launch the dialog used to get the creds."""
from ubuntu_sso.utils import get_bin_dir
bin_dir = get_bin_dir()
args = (os.path.join(bin_dir, UI_PROXY_CREDS_DIALOG), '--domain',
domain)
if retry:
args += ('--retry',)
return spawn_program(args)
@defer.inlineCallbacks
def request_proxy_auth_credentials(self, domain, retry):
"""Request the auth creds to the user."""
if not retry:
if (self.proxy_username is not None
and self.proxy_password is not None):
logger.debug('Not retry and credentials are present.')
defer.returnValue(True)
else:
creds_loaded = yield self._load_proxy_creds_from_keyring(
domain)
if creds_loaded:
defer.returnValue(True)
try:
return_code = yield self._launch_proxy_creds_dialog(domain, retry)
except Exception, e:
logger.error('Error when running external ui process.')
raise WebClientError('Error when running external ui process.', e)
if return_code == USER_SUCCESS:
creds_loaded = yield self._load_proxy_creds_from_keyring(domain)
defer.returnValue(creds_loaded)
else:
logger.debug('Could not retrieve the credentials. Return code: %r',
return_code)
defer.returnValue(False)
def format_ssl_details(self, details):
"""Return a formatted string with the details."""
return SSL_DETAILS_TEMPLATE % details
def _launch_ssl_dialog(self, domain, details):
"""Launch a dialog used to approve the ssl cert."""
from ubuntu_sso.utils import get_bin_dir
bin_dir = get_bin_dir()
args = (os.path.join(bin_dir, SSL_DIALOG), '--domain', domain,
'--details', details,
'--appname', self.appname)
return spawn_program(args)
def _was_ssl_accepted(self, cert_details):
"""Return if the cert was already accepted."""
# TODO: Ensure that we look at pinned certs in a following branch
return False
@defer.inlineCallbacks
def request_ssl_cert_approval(self, domain, details):
"""Request the user for ssl approval."""
if self._was_ssl_accepted(details):
defer.returnValue(True)
return_code = yield self._launch_ssl_dialog(domain, details)
defer.returnValue(return_code == USER_SUCCESS)
|