# Copyright (C) 2019 Entr'ouvert # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # Usage : http --auth='key_name:key' --auth-type=publik-auth https://some.publik.api/endpoint/ import base64 import datetime import hashlib import hmac import random import urllib.parse from django.utils.encoding import force_bytes from httpie.plugins import AuthPlugin def sign_url(url, key, orig, algo='sha256', timestamp=None, nonce=None): parsed = urllib.parse.urlparse(url) new_query = sign_query(parsed.query, key, orig, algo, timestamp, nonce) return urllib.parse.urlunparse(parsed[:4] + (new_query,) + parsed[5:]) def sign_query(query, key, orig, algo='sha256', timestamp=None, nonce=None): if timestamp is None: timestamp = datetime.datetime.utcnow() timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%SZ') if nonce is None: nonce = hex(random.getrandbits(128))[2:] new_query = query if new_query: new_query += '&' new_query += urllib.parse.urlencode(( ('algo', algo), ('timestamp', timestamp), ('nonce', nonce), ('orig', orig))) signature = base64.b64encode(sign_string(new_query, key, algo=algo)) new_query += '&signature=' + urllib.parse.quote(signature) return new_query def sign_string(s, key, algo='sha256', timedelta=30): digestmod = getattr(hashlib, algo) hash = hmac.HMAC(force_bytes(key), digestmod=digestmod, msg=force_bytes(s)) return hash.digest() class ApiAuth: def __init__(self, access_id, secret_key): self.access_id = access_id self.secret_key = secret_key def __call__(self, r): r.url = sign_url(r.url, self.secret_key, self.access_id) return r class PublikAuthPlugin(AuthPlugin): name = 'PublikAuth auth' auth_type = 'publik-auth' description = 'Sign requests using the PublikAuth authentication method' def get_auth(self, username, password): return ApiAuth(username, password)