Script 'mail_helper' called by obssrc Hello community, here is the log from the commit of package python-PyFxA for openSUSE:Factory checked in at 2026-11-23 12:26:18 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Comparing /work/SRC/openSUSE:Factory/python-PyFxA (Old) and /work/SRC/openSUSE:Factory/.python-PyFxA.new.1340718 (New) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Package is "python-PyFxA" Mon Nov 23 12:26:18 2026 rev:17 rq:1399805 version:0.9.0 Changes: -------- --- /work/SRC/openSUSE:Factory/python-PyFxA/python-PyFxA.changes 2026-05-26 16:34:27.217043614 +0200 +++ /work/SRC/openSUSE:Factory/.python-PyFxA.new.1340718/python-PyFxA.changes 2026-11-23 12:31:13.340451153 +0100 @@ -1,0 +2,35 @@ +Sun Nov 22 22:31:00 UTC 2026 - Dirk Müller <[email protected]> + +- update to 0.9.0: + * Move TOTP management to the /mfa/totp/* routes. /totp/destroy + was removed and /totp/create is being retired. + * Session.totp_create and totp_delete now take an MFA token from + the mfa_request_otp and mfa_verify_otp helpers; setup ends + with totp_setup_verify and totp_setup_complete. + * BearerTokenAuth now raises TrustError for non-loopback + http:// URLs, as FxA token auth does. This also affects + fxa.profile calls. + * Move password reset to /password/forgot/send_otp and + /password/forgot/verify_otp. The old send_code, resend_code + and status routes are gone. + * Client.send_reset_code now takes only service and returns a + PasswordForgotToken, with token and uid set by verify_code. + * Remove PasswordForgotToken.get_status, + Client.resend_reset_code and Client.get_reset_code_status; add + Client.verify_reset_otp. + * /password/change/start now requires a verified session token. + * Client.change_password now requires session_token and returns + the server response. start_password_change, + finish_password_change and finish_password_change_v2 also + require a session token. + * Session.change_password and Session.finish_password_change + switch to the server-issued session. + * A v2 login of a v1 account now signs in with v1 credentials + and upgrades via password change. + * Client.create_account no longer accepts preVerified or + preVerifyToken. The auth server no longer supports + preVerifyToken and ignores preVerified. + * fxa --create-user now verifies the new account with the + emailed code. + +------------------------------------------------------------------- Old: ---- pyfxa-0.8.2.tar.gz New: ---- pyfxa-0.9.0.tar.gz ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Other differences: ------------------ ++++++ python-PyFxA.spec ++++++ --- /var/tmp/diff_new_pack.OfVwmO/_old 2026-11-23 12:31:15.334535100 +0100 +++ /var/tmp/diff_new_pack.OfVwmO/_new 2026-11-23 12:31:15.338535268 +0100 @@ -24,7 +24,7 @@ %endif %{?sle15_python_module_pythons} Name: python-PyFxA -Version: 0.8.2 +Version: 0.9.0 Release: 0 Summary: Firefox Accounts client library for Python License: MPL-2.0 @@ -34,7 +34,6 @@ BuildRequires: %{python_module PyJWT} BuildRequires: %{python_module cryptography} BuildRequires: %{python_module hatchling} -BuildRequires: %{python_module hawkauthlib} BuildRequires: %{python_module parameterized} BuildRequires: %{python_module pip} BuildRequires: %{python_module pyotp} @@ -47,7 +46,6 @@ BuildRequires: python-rpm-macros Requires: python-PyJWT Requires: python-cryptography -Requires: python-hawkauthlib Requires: python-requests >= 2.4.2 %if %{with libalternatives} Requires: alts ++++++ pyfxa-0.8.2.tar.gz -> pyfxa-0.9.0.tar.gz ++++++ diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/CHANGES.txt new/pyfxa-0.9.0/CHANGES.txt --- old/pyfxa-0.8.2/CHANGES.txt 2020-02-02 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/CHANGES.txt 2020-02-02 01:00:00.000000000 +0100 @@ -3,6 +3,37 @@ This document describes changes between each past release. +0.9.0 (2026-10-06) +================== + +- Move TOTP management to the ``/mfa/totp/*`` routes. ``/totp/destroy`` was + removed server-side in January 2026 and ``/totp/create`` is being retired. + ``Session.totp_create`` and ``totp_delete`` now take an MFA token from the + new ``mfa_request_otp`` / ``mfa_verify_otp`` helpers, and setup finishes + with ``totp_setup_verify`` and ``totp_setup_complete``. +- ``BearerTokenAuth`` now raises ``TrustError`` over non-loopback ``http://``, + like the FxA token auth. This also applies to ``fxa.profile`` calls. +- Move password reset to the ``/password/forgot/send_otp`` and + ``/password/forgot/verify_otp`` routes. The ``send_code``, ``resend_code`` + and ``status`` routes were removed server-side in January 2026 and had been + returning 404. ``Client.send_reset_code`` now takes only ``service`` and + returns a ``PasswordForgotToken`` whose ``token`` and ``uid`` are set by + ``verify_code``. ``PasswordForgotToken.get_status``, + ``Client.resend_reset_code`` and ``Client.get_reset_code_status`` are + removed; ``Client.verify_reset_otp`` is new. +- ``/password/change/start`` now requires a verified session token. + ``Client.change_password`` takes a required ``session_token`` keyword and + returns the server response. ``Client.start_password_change``, + ``finish_password_change`` and ``finish_password_change_v2`` take a required + session token. ``Session.change_password`` and + ``Session.finish_password_change`` switch to the new session the server + issues. A v2 ``login`` of a v1 account now signs in with v1 + credentials first, then upgrades with a password change. +- ``Client.create_account`` no longer accepts ``preVerified`` or + ``preVerifyToken``. The auth-server no longer supports ``preVerifyToken`` + and is removing ``preVerified``, which it then ignores without an error. + ``fxa --create-user`` now verifies the new account with the emailed code. + 0.8.2 (2026-05-14) ================== diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/PKG-INFO new/pyfxa-0.9.0/PKG-INFO --- old/pyfxa-0.8.2/PKG-INFO 2020-02-02 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/PKG-INFO 2020-02-02 01:00:00.000000000 +0100 @@ -1,6 +1,6 @@ -Metadata-Version: 2.4 +Metadata-Version: 2.5 Name: pyfxa -Version: 0.8.2 +Version: 0.9.0 Summary: Firefox Accounts client library for Python Project-URL: Homepage, https://github.com/mozilla/PyFxA Author-email: Mozilla Services <[email protected]> @@ -18,7 +18,6 @@ Classifier: Programming Language :: Python :: 3.12 Requires-Python: >=3.8 Requires-Dist: cryptography -Requires-Dist: hawkauthlib Requires-Dist: pyjwt Requires-Dist: requests>=2.4.2 Description-Content-Type: text/x-rst diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/fxa/__init__.py new/pyfxa-0.9.0/fxa/__init__.py --- old/pyfxa-0.8.2/fxa/__init__.py 2020-02-02 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/fxa/__init__.py 2020-02-02 01:00:00.000000000 +0100 @@ -7,7 +7,7 @@ """ -__version__ = "0.8.2" +__version__ = "0.9.0" __ver_tuple__ = tuple(__version__.split(".")) diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/fxa/__main__.py new/pyfxa-0.9.0/fxa/__main__.py --- old/pyfxa-0.8.2/fxa/__main__.py 2020-02-02 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/fxa/__main__.py 2020-02-02 01:00:00.000000000 +0100 @@ -170,7 +170,7 @@ email, password = create_new_fxa_account( os.getenv('FXA_USER_SALT', args.get('fxa_user_salt')), account_server_url, args['prefix'], content_server_url) - except (ClientError, ValueError) as e: + except (ClientError, ValueError, RuntimeError) as e: logger.error(e) sys.exit(1) diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/fxa/_utils.py new/pyfxa-0.9.0/fxa/_utils.py --- old/pyfxa-0.8.2/fxa/_utils.py 2020-02-02 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/fxa/_utils.py 2020-02-02 01:00:00.000000000 +0100 @@ -13,19 +13,18 @@ import time import hashlib import hmac +import warnings from binascii import hexlify, unhexlify -from base64 import b64encode try: import cPickle as pickle except ImportError: # pragma: no cover import pickle -from urllib.parse import urlparse, urljoin +from urllib.parse import urljoin, urlparse import requests import requests.auth import requests.utils -import hawkauthlib from requests.adapters import HTTPAdapter from urllib3.util import Retry @@ -44,6 +43,21 @@ )) +# Typed Bearer-token prefix per FxA token kind. Must stay in sync with the +# auth-server table in `lib/routes/auth-schemes/bearer-fxa-token.js` and the +# auth-client `lib/bearer.ts`. The prefix keeps these tokens disjoint from the +# OAuth refresh-token scheme (plain `Bearer <hex>`) and from legacy Hawk on +# routes that accept more than one. See ADR-0022 / ADR-0050 and +# https://mozilla.github.io/ecosystem-platform/reference/authentication-schemes +TOKEN_PREFIXES = { + "sessionToken": "fxs", + "keyFetchToken": "fxk", + "accountResetToken": "fxar", + "passwordForgotToken": "fxpf", + "passwordChangeToken": "fxpc", +} + + def hexstr(data): """Like binascii.hexlify, but always returns a str instance.""" return hexlify(data).decode("ascii") @@ -146,7 +160,6 @@ * default base server URL * backoff protocol support * sensible request timeouts - * timestamp skew tracking with automatic retry on clockskew error * CI WAF bypass header injection """ @@ -172,7 +185,6 @@ self._session = session self._backoff_until = 0 self._backoff_response = None - self._clockskew = None # Reflect useful properties of the wrapped Session object. @@ -216,30 +228,19 @@ """Get the current timestamp, as seen by the client. This is a helper function that returns the current local time. - It's mostly here for symmetry with server_curtime() and to assist - in testability of this class. + It's mostly here to assist in testability of this class. """ return time.time() - def server_curtime(self): - """Get the current timestamp, as seen by the server. - - This is a helper function that automatically applies any detected - clock-skew, to report what the current timestamp is on the server - instead of on the client. - """ - return self.client_curtime() + (self._clockskew or 0) - # The actual request-making stuff. - def request(self, method, url, json=None, retry_auth_errors=True, **kwds): + def request(self, method, url, json=None, **kwds): """Make a request to the API and process the response. This method implements the low-level details of interacting with an FxA Web API, stripping away most of the details of HTTP. It will return the parsed JSON of a successful responses, or raise an exception - for an error response. It's also responsible for backoff handling - and clock-skew tracking. + for an error response. It's also responsible for backoff handling. """ # Don't make requests if we're in backoff. # Instead just synthesize a backoff response. @@ -247,7 +248,6 @@ if self._backoff_until >= self.client_curtime(): resp = pickle.loads(self._backoff_response) resp.request = None - resp.headers["Timestamp"] = str(int(self.server_curtime())) return resp else: self._backoff_until = 0 @@ -294,37 +294,6 @@ self._backoff_until = self.client_curtime() + retry_after self._backoff_response = pickle.dumps(resp) - # If we get a 401 with "serverTime" field in the body, then we're - # probably out of sync with the server's clock. Check our skew, - # adjust if necessary and try again. - if retry_auth_errors: - if resp.status_code == 401 and "serverTime" in body: - try: - server_timestamp = int(body["serverTime"]) - except ValueError: - msg = "API responded with non-integer serverTime: {0}" - msg = msg.format(body["serverTime"]) - raise fxa.errors.OutOfProtocolError(msg) - # If our guestimate is more than 30 seconds out, try again. - # This assumes the auth hook will use the updated clockskew. - if abs(server_timestamp - self.server_curtime()) > 30: - self._clockskew = server_timestamp - self.client_curtime() - return self.request(method, url, json, False, **kwds) - - # See if we need to adjust for clock skew between client and server. - # We do this automatically once per session in the hopes of avoiding - # having to retry subsequent auth failures. We do it *after* the retry - # checking above, because it wrecks the "were we out of sync?" check. - if self._clockskew is None and "timestamp" in resp.headers: - try: - server_timestamp = int(resp.headers["timestamp"]) - except ValueError: - msg = "API responded with non-integer timestamp: {0}" - msg = msg.format(resp.headers["timestamp"]) - raise fxa.errors.OutOfProtocolError(msg) - else: - self._clockskew = server_timestamp - self.client_curtime() - # Raise exceptions for any error responses. # XXX TODO: hooks for raising error subclass based on errno. if 400 <= resp.status_code < 500: @@ -351,40 +320,57 @@ return self.request("DELETE", url, **kwds) -class HawkTokenAuth(requests.auth.AuthBase): - """A requests auth hook implementing token-based hawk auth. +_LOOPBACK_HOSTS = frozenset(("localhost", "127.0.0.1", "0.0.0.0", "::1")) + + +def _reject_insecure_token_transport(url): + """Refuse to send a bearer credential over plaintext HTTP. - This auth hook implements the hkdf-derived-hawk-token auth scheme - as used by the Firefox Accounts auth server. It uses HKDF to derive - an id and secret key from a random 32-byte token, then signs the request - with those credentials using the Hawk request-signing scheme. + Unlike the old Hawk signature, the Bearer header is a replayable + credential, so its confidentiality depends entirely on TLS. Loopback hosts + are exempt so local development against an http auth-server still works. + """ + parsed = urlparse(url) + if parsed.scheme == "http" and parsed.hostname not in _LOOPBACK_HOSTS: + raise fxa.errors.TrustError( + "Refusing to send an FxA token over a non-HTTPS connection to " + f"{parsed.hostname}: the Bearer header is a replayable credential " + "and must only be sent over https." + ) + + +class FxATokenBearerAuth(requests.auth.AuthBase): + """A requests auth hook for FxA tokens delivered as prefixed Bearer tokens. + + This auth hook implements the prefixed-Bearer scheme that replaced Hawk on + the Firefox Accounts auth server (ADR-0022). It uses HKDF to derive an id + and bundle key from a random 32-byte token, then sends the id in the + Authorization header as ``Bearer <prefix>_<id>``, where ``<prefix>`` + identifies the token kind (see ``TOKEN_PREFIXES``). + + The HKDF derivation is scheme-neutral: the same id is what the legacy Hawk + strategy looked up server-side, and the bundle key is still used to + unbundle encrypted ``account/keys`` responses. """ def __init__(self, token, tokentype, apiclient=None): + try: + self.prefix = TOKEN_PREFIXES[tokentype] + except KeyError: + raise ValueError(f"unknown token kind: {tokentype!r}") from None tokendata = unhexlify(token) + # 96 bytes keeps id ([:32]) and bundle_key ([64:]) at server offsets; + # the middle 32 (old Hawk auth key) are unused. key_material = fxa.crypto.derive_key(tokendata, tokentype, 3*32) self.id = hexstr(key_material[:32]) - self.auth_key = key_material[32:64] self.bundle_key = key_material[64:] + # Unused by the Bearer scheme (Hawk read it for the request timestamp); + # retained for signature back-compat with callers and the auth setter. self.apiclient = apiclient def __call__(self, req): - # Requests doesn't include the port in the Host header by default. - # Ensure a fully-correct value so that signatures work properly. - req.headers["Host"] = urlparse(req.url).netloc - params = {} - if req.body: - body = _encoded(req.body, 'utf-8') - hasher = hashlib.sha256() - hasher.update(b"hawk.1.payload\napplication/json\n") - hasher.update(body) - hasher.update(b"\n") - hash = b64encode(hasher.digest()) - hash = hash.decode("ascii") - params["hash"] = hash - if self.apiclient is not None: - params["ts"] = str(int(self.apiclient.server_curtime())) - hawkauthlib.sign_request(req, self.id, self.auth_key, params=params) + _reject_insecure_token_transport(req.url) + req.headers["Authorization"] = f"Bearer {self.prefix}_{self.id}" return req def bundle(self, namespace, payload): @@ -396,6 +382,24 @@ return fxa.crypto.unbundle(self.bundle_key, namespace, payload) +class HawkTokenAuth(FxATokenBearerAuth): + """Deprecated alias for :class:`FxATokenBearerAuth`. + + Hawk signing was removed in the Bearer migration (ADR-0022); this name now + emits a prefixed Bearer header. Kept so existing imports keep working, but + it warns so callers know to switch to ``FxATokenBearerAuth``. + """ + + def __init__(self, *args, **kwds): + warnings.warn( + "HawkTokenAuth is deprecated and no longer uses Hawk; " + "use FxATokenBearerAuth instead.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwds) + + class BearerTokenAuth(requests.auth.AuthBase): """A requests auth hook implementing OAuth bearer-token-based auth. @@ -407,6 +411,7 @@ self.token = token def __call__(self, req): + _reject_insecure_token_transport(req.url) req.headers["Authorization"] = f"Bearer {self.token}" return req @@ -418,12 +423,6 @@ return value -def _encoded(value, encoding='utf-8'): - if not isinstance(value, bytes): - return value.encode(encoding) - return value - - def exactly_one_of(p1_val, p1_name, p2_val, p2_name): if p1_val and p2_val or not p1_val and not p2_val: raise ValueError(f"must specify exactly one of '{p1_name}' or '{p2_name}'") diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/fxa/core.py new/pyfxa-0.9.0/fxa/core.py --- old/pyfxa-0.8.2/fxa/core.py 2020-02-02 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/fxa/core.py 2020-02-02 01:00:00.000000000 +0100 @@ -9,7 +9,8 @@ from fxa.errors import ClientError from fxa._utils import ( APIClient, - HawkTokenAuth, + BearerTokenAuth, + FxATokenBearerAuth, exactly_one_of, hexstr ) @@ -76,8 +77,7 @@ "authPW": spwd.get_auth_pw_v1(), } - EXTRA_KEYS = ("service", "redirectTo", "resume", "preVerifyToken", - "preVerified") + EXTRA_KEYS = ("service", "redirectTo", "resume") for extra in kwds: if extra in EXTRA_KEYS: body[extra] = kwds[extra] @@ -114,35 +114,18 @@ verification_method=None, reason="login"): exactly_one_of(password, "password", stretchpwd, "stretchpwd") + upgrade = False if self.key_stretch_version == 2: version, salt = self.get_key_stretch_version(email) - salt = salt if version == 2 else create_salt(2, hexlify(token_bytes(16))) + upgrade = version != 2 + salt = salt if not upgrade else create_salt(2, hexlify(token_bytes(16))) spwd = StretchedPassword(2, email, salt, password, stretchpwd) - - try: - resp = self.start_password_change(email, spwd.v1) - key_fetch_token = resp["keyFetchToken"] - password_change_token = resp["passwordChangeToken"] - kb = self.fetch_keys(resp["keyFetchToken"], spwd.v1)[1] - resp = self.finish_password_change_v2( - password_change_token, - spwd, - kb - ) - body = { - "email": email, - "authPW": spwd.get_auth_pw_v2(), - "reason": reason, - } - except Exception as inst: - # If something goes wrong fallback to v1 logins! - print("Warning! v2 key stretch auto upgrade failed! Falling back to v1 login. " + - f"Reason: {inst}") - body = { - "email": email, - "authPW": spwd.get_auth_pw_v1(), - "reason": reason, - } + # A v1 account signs in with v1 credentials, then upgrades below. + body = { + "email": email, + "authPW": spwd.get_auth_pw_v1() if upgrade else spwd.get_auth_pw_v2(), + "reason": reason, + } else: spwd = StretchedPassword(1, email, None, password, stretchpwd) body = { @@ -162,7 +145,22 @@ resp = self.apiclient.post(url, body) # Repackage stretchpwd based on version - if self.key_stretch_version == 2: + if upgrade: + try: + change = self.start_password_change(email, spwd.v1, resp["sessionToken"]) + kb = self.fetch_keys(change["keyFetchToken"], spwd.v1)[1] + # The password change replaces the session, so use the new one. + resp = {**resp, **self.finish_password_change_v2( + change["passwordChangeToken"], spwd, kb, resp["sessionToken"], keys)} + stretchpwd_final = spwd + key_fetch_token = resp.get("keyFetchToken2") + except Exception as inst: + # Keep the v1 session, e.g. when it is not verified yet. + print("Warning! v2 key stretch auto upgrade failed! Continuing with v1 login. " + + f"Reason: {inst}") + stretchpwd_final = spwd.v1 + key_fetch_token = resp.get("keyFetchToken") + elif self.key_stretch_version == 2: stretchpwd_final = spwd key_fetch_token = resp.get("keyFetchTokenVersion2") else: @@ -224,14 +222,19 @@ def fetch_keys(self, key_fetch_token, stretchpwd): url = "/account/keys" - auth = HawkTokenAuth(key_fetch_token, "keyFetchToken", self.apiclient) + auth = FxATokenBearerAuth(key_fetch_token, "keyFetchToken", self.apiclient) resp = self.apiclient.get(url, auth=auth) bundle = unhexlify(resp["bundle"]) keys = auth.unbundle("account/keys", bundle) return unwrap_keys(keys, stretchpwd) def change_password(self, email, oldpwd=None, newpwd=None, - oldstretchpwd=None, newstretchpwd=None): + oldstretchpwd=None, newstretchpwd=None, *, session_token): + """Change the password using a verified ``session_token``. + + The server deletes every token on the account, so the returned + response carries the replacement ``sessionToken``. + """ exactly_one_of(oldpwd, "oldpwd", oldstretchpwd, "oldstretchpwd") exactly_one_of(newpwd, "newpwd", newstretchpwd, "newstretchpwd") @@ -241,42 +244,44 @@ new_spwd = StretchedPassword(2, email, salt, newpwd, newstretchpwd) if version == 2: - resp = self.start_password_change(email, old_spwd.v2) + resp = self.start_password_change(email, old_spwd.v2, session_token) kb = self.fetch_keys(resp["keyFetchToken2"], old_spwd.v2)[1] else: - resp = self.start_password_change(email, old_spwd.v1)["passwordChangeToken"] + resp = self.start_password_change(email, old_spwd.v1, session_token) kb = self.fetch_keys(resp["keyFetchToken"], old_spwd.v1)[1] - self.finish_password_change_v2( + return self.finish_password_change_v2( resp["passwordChangeToken"], new_spwd, - kb) + kb, + session_token) else: if oldpwd: oldstretchpwd = quick_stretch_password(email, oldpwd) if newpwd: newstretchpwd = quick_stretch_password(email, newpwd) - resp = self.start_password_change(email, oldstretchpwd) + resp = self.start_password_change(email, oldstretchpwd, session_token) kb = self.fetch_keys(resp["keyFetchToken"], oldstretchpwd)[1] new_wrapkb = derive_wrap_kb(kb, newstretchpwd) - self.finish_password_change(resp["passwordChangeToken"], newstretchpwd, new_wrapkb) + return self.finish_password_change( + resp["passwordChangeToken"], newstretchpwd, new_wrapkb, session_token) - def start_password_change(self, email, stretchpwd): + def start_password_change(self, email, stretchpwd, session_token): body = { "email": email, "oldAuthPW": hexstr(derive_auth_pw(stretchpwd)), } - return self.apiclient.post("/password/change/start", body) + auth = FxATokenBearerAuth(session_token, "sessionToken", self.apiclient) + return self.apiclient.post("/password/change/start", body, auth=auth) - def finish_password_change(self, token, stretchpwd, wrapkb): + def finish_password_change(self, token, stretchpwd, wrapkb, session_token): body = { "authPW": hexstr(derive_auth_pw(stretchpwd)), "wrapKb": hexstr(wrapkb), } - auth = HawkTokenAuth(token, "passwordChangeToken", self.apiclient) - self.apiclient.post("/password/change/finish", body, auth=auth) + return self._finish_password_change(token, body, session_token) - def finish_password_change_v2(self, token, spwd, kb): + def finish_password_change_v2(self, token, spwd, kb, session_token, keys=False): body = { "authPW": spwd.get_auth_pw_v1(), "wrapKb": spwd.get_wrapkb_v1(kb), @@ -284,9 +289,16 @@ "wrapKbVersion2": spwd.get_wrapkb_v2(kb), "clientSalt": spwd.v2_salt, } - auth = HawkTokenAuth(token, "passwordChangeToken", self.apiclient) + return self._finish_password_change(token, body, session_token, keys) - return self.apiclient.post("/password/change/finish", body, auth=auth) + def _finish_password_change(self, token, body, session_token, keys=False): + # Lets the replacement session keep the current session's verified state. + body["sessionToken"] = FxATokenBearerAuth(session_token, "sessionToken").id + url = "/password/change/finish" + if keys: + url += "?keys=true" + auth = FxATokenBearerAuth(token, "passwordChangeToken", self.apiclient) + return self.apiclient.post(url, body, auth=auth) def reset_account(self, email, token, password=None, stretchpwd=None): # TODO: Add support for recovery key! @@ -317,56 +329,47 @@ } url = "/account/reset" - auth = HawkTokenAuth(token, "accountResetToken", self.apiclient) + auth = FxATokenBearerAuth(token, "accountResetToken", self.apiclient) self.apiclient.post(url, body, auth=auth) - def send_reset_code(self, email, **kwds): + def send_reset_code(self, email, service=None): + """Email a one-time code that starts a password reset for ``email``. + + The server issues no token until the code is verified, so the + returned :class:`PasswordForgotToken` is only usable through + :meth:`PasswordForgotToken.verify_code`. + """ body = { "email": email, } - for extra in kwds: - if extra in ("service", "redirectTo", "resume"): - body[extra] = kwds[extra] - else: - msg = f"Unexpected keyword argument: {extra}" - raise TypeError(msg) - url = "/password/forgot/send_code" - resp = self.apiclient.post(url, body) - return PasswordForgotToken( - self, email, - resp["passwordForgotToken"], - resp["ttl"], - resp["codeLength"], - resp["tries"], - ) - - def resend_reset_code(self, email, token, **kwds): + if service is not None: + body["service"] = service + url = "/password/forgot/send_otp" + self.apiclient.post(url, body) + return PasswordForgotToken(self, email, service=service) + + def verify_reset_otp(self, email, code): + """Exchange the emailed one-time code for a ``passwordForgotToken``. + + Returns the raw response: ``token`` (the passwordForgotToken), the + server-issued ``code`` that :meth:`verify_reset_code` expects, + ``uid`` and ``emailToHashWith``. + """ body = { "email": email, + "code": code, } - for extra in kwds: - if extra in ("service", "redirectTo", "resume"): - body[extra] = kwds[extra] - else: - msg = f"Unexpected keyword argument: {extra}" - raise TypeError(msg) - url = "/password/forgot/resend_code" - auth = HawkTokenAuth(token, "passwordForgotToken", self.apiclient) - return self.apiclient.post(url, body, auth=auth) + url = "/password/forgot/verify_otp" + return self.apiclient.post(url, body) def verify_reset_code(self, token, code): body = { "code": code, } url = "/password/forgot/verify_code" - auth = HawkTokenAuth(token, "passwordForgotToken", self.apiclient) + auth = FxATokenBearerAuth(token, "passwordForgotToken", self.apiclient) return self.apiclient.post(url, body, auth=auth) - def get_reset_code_status(self, token): - url = "/password/forgot/status" - auth = HawkTokenAuth(token, "passwordForgotToken", self.apiclient) - return self.apiclient.get(url, auth=auth) - def verify_email_code(self, uid, code): body = { "uid": uid, @@ -424,7 +427,7 @@ self.verificationMethod = verificationMethod self.auth_timestamp = auth_timestamp self.keys = None - self._auth = HawkTokenAuth(token, "sessionToken", self.apiclient) + self._auth = FxATokenBearerAuth(token, "sessionToken", self.apiclient) self._key_fetch_token = key_fetch_token # Quick validation on stretchpwd @@ -500,18 +503,64 @@ url = "/recovery_email/resend_code" self.apiclient.post(url, body, auth=self._auth) - def totp_create(self): - url = "/totp/create" - return self.apiclient.post(url, {}, auth=self._auth) + def mfa_request_otp(self, action): + """Ask the server to email a one-time code for a sensitive ``action``. + + The code arrives in the ``X-Account-Change-Verify-Code`` header of the + email and is exchanged for a short-lived MFA token with + :meth:`mfa_verify_otp`. Requires a verified session. + """ + url = "/mfa/otp/request" + return self.apiclient.post(url, {"action": action}, auth=self._auth) + + def mfa_verify_otp(self, code, action): + """Exchange an emailed one-time code for an MFA token. + + The returned token is a JWT scoped to ``action`` and is what the + ``/mfa/*`` routes accept in place of the session token. + """ + url = "/mfa/otp/verify" + body = { + "code": code, + "action": action, + } + resp = self.apiclient.post(url, body, auth=self._auth) + return resp["accessToken"] + + def totp_create(self, mfa_token): + """Start TOTP setup and return the shared secret and QR code URL. + + ``mfa_token`` comes from :meth:`mfa_verify_otp` with the ``"2fa"`` + action. Nothing is stored on the account until + :meth:`totp_setup_complete` succeeds. + """ + url = "/mfa/totp/create" + return self.apiclient.post(url, {}, auth=BearerTokenAuth(mfa_token)) + + def totp_setup_verify(self, mfa_token, code): + """Prove possession of the pending TOTP secret with a current code.""" + url = "/mfa/totp/setup/verify" + body = { + "code": code, + } + resp = self.apiclient.post(url, body, auth=BearerTokenAuth(mfa_token)) + return resp["success"] + + def totp_setup_complete(self, mfa_token): + """Enable TOTP on the account once :meth:`totp_setup_verify` passed.""" + url = "/mfa/totp/setup/complete" + resp = self.apiclient.post(url, {}, auth=BearerTokenAuth(mfa_token)) + return resp["success"] def totp_exists(self): url = "/totp/exists" resp = self.apiclient.get(url, auth=self._auth) return resp["exists"] - def totp_delete(self): - url = "/totp/destroy" - return self.apiclient.post(url, {}, auth=self._auth) + def totp_delete(self, mfa_token): + """Remove TOTP from the account. ``mfa_token`` needs the ``"2fa"`` action.""" + url = "/mfa/totp/destroy" + return self.apiclient.post(url, {}, auth=BearerTokenAuth(mfa_token)) def totp_verify(self, code): url = "/session/verify/totp" @@ -526,14 +575,24 @@ def change_password(self, oldpwd, newpwd, oldstretchpwd=None, newstretchpwd=None): - return self.client.change_password(self.email, oldpwd, newpwd, - oldstretchpwd, newstretchpwd) + resp = self.client.change_password(self.email, oldpwd, newpwd, + oldstretchpwd, newstretchpwd, + session_token=self.token) + self._use_replacement_session(resp) + return resp def start_password_change(self, stretchpwd): - return self.client.start_password_change(self.email, stretchpwd) + return self.client.start_password_change(self.email, stretchpwd, self.token) def finish_password_change(self, token, stretchpwd, wrapkb): - return self.client.finish_password_change(token, stretchpwd, wrapkb) + resp = self.client.finish_password_change(token, stretchpwd, wrapkb, self.token) + self._use_replacement_session(resp) + return resp + + def _use_replacement_session(self, resp): + # A password change deletes this session; switch to the one the server issued. + self.token = resp["sessionToken"] + self._auth = FxATokenBearerAuth(self.token, "sessionToken", self.apiclient) def get_random_bytes(self): # XXX TODO: sanity-check the schema of the returned response @@ -541,31 +600,33 @@ class PasswordForgotToken: + """A password reset in progress, started by :meth:`Client.send_reset_code`. + + The auth server emails an 8-digit one-time code. Pass it to + :meth:`verify_code` to obtain the ``accountResetToken`` that + :meth:`Client.reset_account` needs. ``token``, ``uid`` and + ``email_to_hash_with`` are populated once the code has been verified. + """ - def __init__(self, client, email, token, ttl=0, code_length=16, - tries_remaining=1): + def __init__(self, client, email, service=None): self.client = client self.email = email - self.token = token - self.ttl = ttl - self.code_length = code_length - self.tries_remaining = tries_remaining + self.service = service + self.token = None + self.uid = None + self.email_to_hash_with = None def verify_code(self, code): - resp = self.client.verify_reset_code(self.token, code) + otp = self.client.verify_reset_otp(self.email, code) + self.token = otp["token"] + self.uid = otp["uid"] + self.email_to_hash_with = otp["emailToHashWith"] + resp = self.client.verify_reset_code(self.token, otp["code"]) return resp["accountResetToken"] - def resend_code(self, **kwds): - resp = self.client.resend_reset_code(self.email, self.token, **kwds) - self.ttl = resp["ttl"] - self.code_length = resp["codeLength"] - self.tries_remaining = resp["tries"] - - def get_status(self): - resp = self.client.get_reset_code_status(self.token) - self.ttl = resp["ttl"] - self.tries_remaining = resp["tries"] - return resp + def resend_code(self): + """Email a fresh one-time code.""" + self.client.send_reset_code(self.email, service=self.service) class StretchedPassword: diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/fxa/oauth.py new/pyfxa-0.9.0/fxa/oauth.py --- old/pyfxa-0.8.2/fxa/oauth.py 2020-02-02 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/fxa/oauth.py 2020-02-02 01:00:00.000000000 +0100 @@ -12,7 +12,7 @@ from fxa.cache import MemoryCache, DEFAULT_CACHE_EXPIRY from fxa.constants import PRODUCTION_URLS from fxa.errors import OutOfProtocolError, ScopeMismatchError, TrustError -from fxa._utils import APIClient, scope_matches, get_hmac, HawkTokenAuth +from fxa._utils import APIClient, scope_matches, get_hmac, FxATokenBearerAuth DEFAULT_SERVER_URL = PRODUCTION_URLS['oauth'] VERSION_SUFFIXES = ("/v1",) @@ -135,7 +135,7 @@ :param code_challenge: optional PKCE code challenge. :param code_challenge_method: optional PKCE code challenge method. """ - auth = HawkTokenAuth(session.token, "sessionToken", self.apiclient) + auth = FxATokenBearerAuth(session.token, "sessionToken", self.apiclient) if client_id is None: client_id = self.client_id diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/fxa/tests/test_core.py new/pyfxa-0.9.0/fxa/tests/test_core.py --- old/pyfxa-0.8.2/fxa/tests/test_core.py 2020-02-02 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/fxa/tests/test_core.py 2020-02-02 01:00:00.000000000 +0100 @@ -1,6 +1,7 @@ # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. +import json import os import time @@ -9,11 +10,12 @@ import pyotp import pytest import requests +import responses from parameterized import parameterized_class import fxa.errors -from fxa.core import Client, StretchedPassword -from fxa._utils import APIClient +from fxa.core import Client, PasswordForgotToken, Session, StretchedPassword +from fxa._utils import APIClient, FxATokenBearerAuth from fxa.tests.utils import ( unittest, @@ -145,32 +147,34 @@ password=DUMMY_PASSWORD, ) self.add_account_to_delete(acct, session) + # send_otp treats an unverified account as unknown. + verify_account(acct, self.client) + acct.clear() - # Initiate the password reset flow, and grab the verification code. + # Initiate the password reset flow, and grab the one-time code. pftok = self.client.send_reset_code(acct.email, service="foobar") - m = acct.wait_for_email(lambda m: "x-recovery-code" in m["headers"]) + m = acct.wait_for_email(lambda m: "x-password-forgot-otp" in m["headers"]) if not m: raise RuntimeError("Password reset email was not received") acct.clear() - code = m["headers"]["x-recovery-code"] + code = m["headers"]["x-password-forgot-otp"] # Try with an invalid code to test error handling. - tries = pftok.tries_remaining - self.assertTrue(tries > 1) - with self.assertRaises(Exception): + with self.assertRaises(fxa.errors.ClientError): pftok.verify_code(mutate_one_byte(code)) - pftok.get_status() - self.assertEqual(pftok.tries_remaining, tries - 1) + self.assertIsNone(pftok.token) # Re-send the code, as if we've lost the email. pftok.resend_code() - m = acct.wait_for_email(lambda m: "x-recovery-code" in m["headers"]) + m = acct.wait_for_email(lambda m: "x-password-forgot-otp" in m["headers"]) if not m: raise RuntimeError("Password reset email was not received") - self.assertEqual(m["headers"]["x-recovery-code"], code) + code = m["headers"]["x-password-forgot-otp"] # Now verify with the actual code, and reset the account. artok = pftok.verify_code(code) + self.assertIsNotNone(pftok.token) + self.assertEqual(pftok.uid, session.uid) self.client.reset_account( email=acct.email, token=artok, @@ -371,31 +375,37 @@ self.assertEqual(self.session.keys[1], keys[1]) def test_totp(self): - resp = self.session.totp_create() + # TOTP setup is guarded by a short-lived MFA token, obtained by + # verifying a code the server emails to the account. + self.session.mfa_request_otp("2fa") + m = self.acct.wait_for_email( + lambda m: "x-account-change-verify-code" in m["headers"]) + if not m: + raise RuntimeError("MFA code email was not received") + self.acct.clear() + mfa_token = self.session.mfa_verify_otp( + m["headers"]["x-account-change-verify-code"], "2fa") - # Should exist even if not verified - self.assertTrue(self.session.totp_exists()) + resp = self.session.totp_create(mfa_token) - # Creating again should work unless verified - resp = self.session.totp_create() + # Nothing is stored on the account until setup completes. + self.assertFalse(self.session.totp_exists()) - # Set session unverified to test next call - self.session.verified = False + # Creating again re-issues the same pending secret. + resp2 = self.session.totp_create(mfa_token) + self.assertEqual(resp2["secret"], resp["secret"]) - # Verify the code code = pyotp.TOTP(resp["secret"]).now() - self.assertTrue(self.session.totp_verify(code)) - self.assertTrue(self.session.verified) - - # Should exist + self.assertTrue(self.session.totp_setup_verify(mfa_token, code)) + self.assertTrue(self.session.totp_setup_complete(mfa_token)) self.assertTrue(self.session.totp_exists()) - # Double create causes a client error + # Creating again once TOTP is enabled is a client error. with self.assertRaises(fxa.errors.ClientError): - self.session.totp_create() + self.session.totp_create(mfa_token) # Remove the code - resp = self.session.totp_delete() + self.session.totp_delete(mfa_token) # And now should not exist self.assertFalse(self.session.totp_exists()) @@ -424,6 +434,199 @@ self.assertEqual(supplied.headers.get("fxa-ci"), "sekrit") +class TestCoreBearerAuthHeaders(unittest.TestCase): + """Mocked coverage that the migrated call sites send a prefixed Bearer + header with the right per-kind prefix (live tests are gated behind + FXA_RUN_LIVE_TESTS, so this is what guards the wire format in CI). + """ + + server_url = "https://server/v1" + + def setUp(self): + self.client = Client(self.server_url) + + @responses.activate + def test_session_token_call_site_sends_fxs_bearer(self): + responses.add(responses.GET, self.server_url + "/session/status", + json={"uid": "abc123"}, content_type="application/json") + session = Session( + client=self.client, email="[email protected]", + stretchpwd=b"\x00" * 32, uid="abc123", token="1234", + ) + session.check_session_status() + authz = responses.calls[0].request.headers["Authorization"] + self.assertRegex(authz, r"^Bearer fxs_[0-9a-f]{64}$") + + @responses.activate + def test_password_forgot_token_call_site_sends_fxpf_bearer(self): + responses.add(responses.POST, self.server_url + "/password/forgot/verify_code", + json={"accountResetToken": "ab" * 32}, + content_type="application/json") + self.client.verify_reset_code("1234", "deadbeef") + authz = responses.calls[0].request.headers["Authorization"] + self.assertRegex(authz, r"^Bearer fxpf_[0-9a-f]{64}$") + + @responses.activate + def test_password_change_start_sends_fxs_bearer(self): + responses.add(responses.POST, self.server_url + "/password/change/start", + json={}, content_type="application/json") + session = Session( + client=self.client, email="[email protected]", + stretchpwd=b"\x00" * 32, uid="abc123", token="1234", + ) + session.start_password_change(b"\x00" * 32) + authz = responses.calls[0].request.headers["Authorization"] + self.assertRegex(authz, r"^Bearer fxs_[0-9a-f]{64}$") + + @responses.activate + def test_password_change_finish_adopts_replacement_session(self): + responses.add(responses.POST, self.server_url + "/password/change/finish", + json={"uid": "abc123", "sessionToken": "ab" * 32}, + content_type="application/json") + session = Session( + client=self.client, email="[email protected]", + stretchpwd=b"\x00" * 32, uid="abc123", token="1234", + ) + old_id = FxATokenBearerAuth("1234", "sessionToken").id + session.finish_password_change("5678", b"\x00" * 32, b"\x00" * 32) + self.assertEqual(json.loads(responses.calls[0].request.body)["sessionToken"], old_id) + self.assertEqual(session.token, "ab" * 32) + self.assertEqual(session._auth.id, FxATokenBearerAuth("ab" * 32, "sessionToken").id) + + @responses.activate + def test_totp_setup_sends_plain_bearer_mfa_token(self): + responses.add(responses.POST, self.server_url + "/mfa/totp/create", + json={"secret": "s", "qrCodeUrl": "data:"}, + content_type="application/json") + session = Session( + client=self.client, email="[email protected]", + stretchpwd=b"\x00" * 32, uid="abc123", token="1234", + ) + session.totp_create("eyJ.mfa.jwt") + authz = responses.calls[0].request.headers["Authorization"] + self.assertEqual(authz, "Bearer eyJ.mfa.jwt") + + @responses.activate + def test_mfa_and_totp_call_sites(self): + session = Session( + client=self.client, email="[email protected]", + stretchpwd=b"\x00" * 32, uid="abc123", token="1234", + ) + # (method call, route, response, expected return, expected body, auth) + cases = [ + (lambda: session.mfa_request_otp("2fa"), "/mfa/otp/request", + {}, {}, {"action": "2fa"}, r"^Bearer fxs_[0-9a-f]{64}$"), + (lambda: session.mfa_verify_otp("123456", "2fa"), "/mfa/otp/verify", + {"accessToken": "eyJ.mfa.jwt"}, "eyJ.mfa.jwt", + {"code": "123456", "action": "2fa"}, r"^Bearer fxs_[0-9a-f]{64}$"), + (lambda: session.totp_setup_verify("eyJ.mfa.jwt", "654321"), + "/mfa/totp/setup/verify", {"success": True}, True, + {"code": "654321"}, r"^Bearer eyJ\.mfa\.jwt$"), + (lambda: session.totp_setup_complete("eyJ.mfa.jwt"), + "/mfa/totp/setup/complete", {"success": True}, True, + {}, r"^Bearer eyJ\.mfa\.jwt$"), + (lambda: session.totp_delete("eyJ.mfa.jwt"), "/mfa/totp/destroy", + {}, {}, {}, r"^Bearer eyJ\.mfa\.jwt$"), + ] + for call, route, resp, expected, body, authz in cases: + with self.subTest(route=route): + responses.add(responses.POST, self.server_url + route, + json=resp, content_type="application/json") + self.assertEqual(call(), expected) + req = responses.calls[-1].request + self.assertEqual(json.loads(req.body), body) + self.assertRegex(req.headers["Authorization"], authz) + + +class TestCorePasswordReset(unittest.TestCase): + """Mocked coverage of the OTP password-reset flow and its request shapes.""" + + server_url = "https://server/v1" + + def setUp(self): + self.client = Client(self.server_url) + + @responses.activate + def test_send_reset_code_posts_otp_request(self): + responses.add(responses.POST, self.server_url + "/password/forgot/send_otp", + json={}, content_type="application/json") + pftok = self.client.send_reset_code("[email protected]", service="sync") + body = json.loads(responses.calls[0].request.body) + self.assertEqual(body, {"email": "[email protected]", "service": "sync"}) + self.assertNotIn("Authorization", responses.calls[0].request.headers) + self.assertEqual(pftok.email, "[email protected]") + self.assertEqual(pftok.service, "sync") + self.assertIsNone(pftok.token) + + @responses.activate + def test_send_reset_code_omits_service_when_unset(self): + responses.add(responses.POST, self.server_url + "/password/forgot/send_otp", + json={}, content_type="application/json") + self.client.send_reset_code("[email protected]") + body = json.loads(responses.calls[0].request.body) + self.assertEqual(body, {"email": "[email protected]"}) + + @responses.activate + def test_verify_code_chains_otp_and_code_verification(self): + responses.add(responses.POST, self.server_url + "/password/forgot/verify_otp", + json={ + "code": "c0de" * 8, + "token": "12" * 32, + "uid": "abc123", + "emailToHashWith": "[email protected]", + }, content_type="application/json") + responses.add(responses.POST, self.server_url + "/password/forgot/verify_code", + json={"accountResetToken": "ab" * 32}, + content_type="application/json") + pftok = PasswordForgotToken(self.client, "[email protected]") + + artok = pftok.verify_code("12345678") + + self.assertEqual(artok, "ab" * 32) + otp_req, code_req = responses.calls[0].request, responses.calls[1].request + self.assertEqual(json.loads(otp_req.body), + {"email": "[email protected]", "code": "12345678"}) + self.assertNotIn("Authorization", otp_req.headers) + self.assertEqual(json.loads(code_req.body), {"code": "c0de" * 8}) + self.assertRegex(code_req.headers["Authorization"], r"^Bearer fxpf_[0-9a-f]{64}$") + self.assertEqual(pftok.token, "12" * 32) + self.assertEqual(pftok.uid, "abc123") + self.assertEqual(pftok.email_to_hash_with, "[email protected]") + + @responses.activate + def test_invalid_otp_leaves_token_unset(self): + responses.add(responses.POST, self.server_url + "/password/forgot/verify_otp", + json={"code": 400, "errno": 105, "error": "Bad Request", + "message": "Invalid verification code"}, + status=400, content_type="application/json") + pftok = PasswordForgotToken(self.client, "[email protected]") + with self.assertRaises(fxa.errors.ClientError): + pftok.verify_code("00000000") + self.assertIsNone(pftok.token) + self.assertEqual(len(responses.calls), 1) + + @responses.activate + def test_resend_code_posts_otp_request_again(self): + responses.add(responses.POST, self.server_url + "/password/forgot/send_otp", + json={}, content_type="application/json") + pftok = PasswordForgotToken(self.client, "[email protected]", service="sync") + pftok.resend_code() + body = json.loads(responses.calls[0].request.body) + self.assertEqual(body, {"email": "[email protected]", "service": "sync"}) + + +class TestCoreCreateAccount(unittest.TestCase): + + @responses.activate + def test_removed_preverify_keywords_raise_before_request(self): + client = Client("https://server/v1") + for kwarg in ("preVerified", "preVerifyToken"): + with self.subTest(kwarg=kwarg): + with self.assertRaises(TypeError): + client.create_account("[email protected]", "password", **{kwarg: True}) + self.assertEqual(len(responses.calls), 0) + + # helpers def verify_account(acct, client): def wait_for_email(m): diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/fxa/tests/test_oauth.py new/pyfxa-0.9.0/fxa/tests/test_oauth.py --- old/pyfxa-0.8.2/fxa/tests/test_oauth.py 2020-02-02 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/fxa/tests/test_oauth.py 2020-02-02 01:00:00.000000000 +0100 @@ -306,6 +306,9 @@ "client_id": self.client.client_id, "state": AnyStringValue(), }) + # The sessionToken is sent as a prefixed Bearer token, not Hawk-signed. + authz = responses.calls[0].request.headers["Authorization"] + self.assertRegex(authz, r"^Bearer fxs_[0-9a-f]{64}$") @responses.activate def test_authorize_code_with_explicit_scope(self): diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/fxa/tests/test_tools.py new/pyfxa-0.9.0/fxa/tests/test_tools.py --- old/pyfxa-0.8.2/fxa/tests/test_tools.py 2020-02-02 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/fxa/tests/test_tools.py 2020-02-02 01:00:00.000000000 +0100 @@ -1,10 +1,15 @@ # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. +import sys + from fxa.tests.utils import unittest +from fxa.__main__ import main as fxa_main from fxa.tests.mock_utilities import ( mock, mocked_core_client, mocked_oauth_client) +from fxa.errors import ClientError from fxa.tools.bearer import get_bearer_token +from fxa.tools.create_user import create_new_fxa_account class TestGetBearerToken(unittest.TestCase): def test_account_server_url_is_mandatory(self): @@ -50,3 +55,51 @@ core_client.return_value.login.return_value, 'profile' ) + + +class TestCreateNewFxaAccount(unittest.TestCase): + server_url = "https://api-accounts.stage.mozaws.net/v1" + + @mock.patch('fxa.tools.create_user.TestEmailAccount') + @mock.patch('fxa.core.Client') + def test_verifies_new_account_with_email_code(self, core_client, email_acct): + email_acct.return_value.wait_for_email.return_value = { + "headers": {"x-verify-code": "123456"}} + calls = mock.Mock() + calls.attach_mock(email_acct.return_value.clear, "clear") + calls.attach_mock(core_client.return_value.create_account, "create_account") + email, password = create_new_fxa_account( + fxa_user_salt="c2FsdA==", account_server_url=self.server_url) + # The inbox is cleared first, so an earlier run's code cannot be read. + self.assertEqual([c[0] for c in calls.mock_calls][:2], ["clear", "create_account"]) + core_client.return_value.create_account.assert_called_once_with( + email, password=password) + session = core_client.return_value.create_account.return_value + session.verify_email_code.assert_called_once_with("123456") + + @mock.patch('fxa.tools.create_user.TestEmailAccount') + @mock.patch('fxa.core.Client') + def test_existing_account_skips_verification(self, core_client, email_acct): + core_client.return_value.create_account.side_effect = ClientError( + {"errno": 101}) + create_new_fxa_account(account_server_url=self.server_url) + email_acct.return_value.wait_for_email.assert_not_called() + + @mock.patch('fxa.tools.create_user.TestEmailAccount') + @mock.patch('fxa.core.Client') + def test_raises_when_verification_email_missing(self, core_client, email_acct): + email_acct.return_value.wait_for_email.return_value = None + with self.assertRaises(RuntimeError): + create_new_fxa_account(account_server_url=self.server_url) + + @mock.patch('fxa.__main__.create_new_fxa_account', + side_effect=RuntimeError("Verification email was not received")) + def test_cli_logs_missing_email_and_exits(self, _create): + argv = ["fxa", "--create-user", + "--account-server", "https://api-accounts.stage.mozaws.net/v1"] + with mock.patch.object(sys, "argv", argv), \ + self.assertLogs("fxa-client", level="ERROR") as logs, \ + self.assertRaises(SystemExit) as exit_: + fxa_main() + self.assertEqual(exit_.exception.code, 1) + self.assertIn("Verification email was not received", logs.output[0]) diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/fxa/tests/test_utils.py new/pyfxa-0.9.0/fxa/tests/test_utils.py --- old/pyfxa-0.8.2/fxa/tests/test_utils.py 1970-01-01 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/fxa/tests/test_utils.py 2020-02-02 01:00:00.000000000 +0100 @@ -0,0 +1,119 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. +import warnings + +from fxa.tests.utils import unittest +from fxa._utils import ( + BearerTokenAuth, FxATokenBearerAuth, HawkTokenAuth, TOKEN_PREFIXES +) +from fxa.errors import TrustError + + +# Test vectors pinned against the HKDF derivation, shared with the +# fxa-auth-client `test/bearer.ts` vectors so the on-the-wire header format +# stays in lockstep with the auth-server parser. EXPECTED_IDS pins the derived +# id for every token kind so a regression that derived ids with the wrong HKDF +# namespace (e.g. using "sessionToken" for all kinds) would be caught. +SESSION_TOKEN = ( + "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf" +) +EXPECTED_IDS = { + "sessionToken": "c0a29dcf46174973da1378696e4c82ae10f723cf4f4d9f75e39f4ae3851595ab", + "keyFetchToken": "70db599cec9c040b10c790418f93fe77711fdea352a59e9b02d2336136d39f68", + "accountResetToken": "920fd5fc6cb03cabd2e6854c92d2976112e7b08728825acad1b7227874201f1f", + "passwordForgotToken": "f108185451329f7c94aa569f9efa09c8aeaef71029d341c83839e6820b870b88", + "passwordChangeToken": "9469deecfe3182a9573c7516650522e0d3032c467e909b64dd0d93f4d1253bde", +} + + +class Request: + def __init__(self, url="https://api.example.com/v1/session/status"): + self.method = "GET" + self.body = "" + self.url = url + self.headers = {"Content-Type": "application/json"} + + +class TestFxATokenBearerAuth(unittest.TestCase): + + def test_prefix_map_matches_server_side(self): + self.assertEqual(TOKEN_PREFIXES["sessionToken"], "fxs") + self.assertEqual(TOKEN_PREFIXES["keyFetchToken"], "fxk") + self.assertEqual(TOKEN_PREFIXES["accountResetToken"], "fxar") + self.assertEqual(TOKEN_PREFIXES["passwordForgotToken"], "fxpf") + self.assertEqual(TOKEN_PREFIXES["passwordChangeToken"], "fxpc") + + def test_emits_prefixed_bearer_header_for_session_token(self): + auth = FxATokenBearerAuth(SESSION_TOKEN, "sessionToken") + req = auth(Request()) + self.assertEqual( + req.headers["Authorization"], + f"Bearer fxs_{EXPECTED_IDS['sessionToken']}", + ) + + def test_derives_kind_specific_id_and_prefix_for_each_kind(self): + for kind, prefix in TOKEN_PREFIXES.items(): + auth = FxATokenBearerAuth(SESSION_TOKEN, kind) + header = auth(Request()).headers["Authorization"] + # Full header pinned per kind, so a wrong-namespace derivation fails. + self.assertEqual(header, f"Bearer {prefix}_{EXPECTED_IDS[kind]}") + + def test_does_not_sign_or_mutate_other_headers(self): + auth = FxATokenBearerAuth(SESSION_TOKEN, "sessionToken") + req = auth(Request()) + # Bearer is stateless: no Hawk-style Host/payload-hash munging. + self.assertNotIn("Host", req.headers) + + def test_unknown_token_kind_raises(self): + with self.assertRaises(ValueError): + FxATokenBearerAuth(SESSION_TOKEN, "notARealKind") + + def test_retains_bundle_key_for_key_fetch_unbundling(self): + # fetch_keys relies on the derived bundle_key to unbundle account/keys. + auth = FxATokenBearerAuth(SESSION_TOKEN, "keyFetchToken") + self.assertTrue(hasattr(auth, "bundle")) + self.assertTrue(hasattr(auth, "unbundle")) + self.assertEqual(len(auth.bundle_key), 32) + + def test_raises_when_token_sent_over_plaintext_http(self): + auth = FxATokenBearerAuth(SESSION_TOKEN, "sessionToken") + with self.assertRaises(TrustError): + auth(Request(url="http://accounts.example.com/v1/session/status")) + + def test_no_error_over_https_or_loopback(self): + auth = FxATokenBearerAuth(SESSION_TOKEN, "sessionToken") + # https and loopback hosts must not raise, so local http dev works. + auth(Request(url="https://accounts.example.com/v1/session/status")) + auth(Request(url="http://localhost:9000/v1/session/status")) + auth(Request(url="http://127.0.0.1:9000/v1/session/status")) + auth(Request(url="http://0.0.0.0:9000/v1/session/status")) + + +class TestBearerTokenAuth(unittest.TestCase): + + def test_raises_when_token_sent_over_plaintext_http(self): + auth = BearerTokenAuth("eyJ.mfa.jwt") + with self.assertRaises(TrustError): + auth(Request(url="http://accounts.example.com/v1/mfa/totp/create")) + + def test_no_error_over_https_or_loopback(self): + auth = BearerTokenAuth("eyJ.mfa.jwt") + auth(Request(url="https://accounts.example.com/v1/mfa/totp/create")) + auth(Request(url="http://localhost:9000/v1/mfa/totp/create")) + + +class TestHawkTokenAuthAlias(unittest.TestCase): + + def test_is_a_subclass_of_the_bearer_auth(self): + self.assertTrue(issubclass(HawkTokenAuth, FxATokenBearerAuth)) + + def test_emits_deprecation_warning_but_still_works(self): + with self.assertWarns(DeprecationWarning): + auth = HawkTokenAuth(SESSION_TOKEN, "sessionToken") + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + header = auth(Request()).headers["Authorization"] + self.assertEqual( + header, f"Bearer fxs_{EXPECTED_IDS['sessionToken']}" + ) diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/fxa/tools/create_user.py new/pyfxa-0.9.0/fxa/tools/create_user.py --- old/pyfxa-0.8.2/fxa/tools/create_user.py 2020-02-02 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/fxa/tools/create_user.py 2020-02-02 01:00:00.000000000 +0100 @@ -8,6 +8,7 @@ from fxa import core from fxa import errors +from fxa.tests.utils import TestEmailAccount FXA_ERROR_ACCOUNT_EXISTS = 101 @@ -20,20 +21,26 @@ else: fxa_user_salt = base64.urlsafe_b64decode(fxa_user_salt) - password = hmac.new(fxa_user_salt, b"loadtest").hexdigest() + password = hmac.new(fxa_user_salt, b"loadtest", "md5").hexdigest() email = "%[email protected]" % (prefix, password) client = core.Client(server_url=account_server_url) + inbox = TestEmailAccount(email) + # The address is fixed per salt, so drop codes from earlier runs. + inbox.clear() try: - client.create_account(email, - password=password, - preVerified=True) + session = client.create_account(email, password=password) except errors.ClientError as e: if e.errno != FXA_ERROR_ACCOUNT_EXISTS: raise - finally: return email, password + + m = inbox.wait_for_email(lambda m: "x-verify-code" in m["headers"]) + if not m: + raise RuntimeError("Verification email was not received") + session.verify_email_code(m["headers"]["x-verify-code"]) + return email, password else: message = ("You are not using dev or stage (%s), make sure your FxA " "test account exists: %s" % (account_server_url, diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pyfxa-0.8.2/pyproject.toml new/pyfxa-0.9.0/pyproject.toml --- old/pyfxa-0.8.2/pyproject.toml 2020-02-02 01:00:00.000000000 +0100 +++ new/pyfxa-0.9.0/pyproject.toml 2020-02-02 01:00:00.000000000 +0100 @@ -31,7 +31,6 @@ dynamic = [ "version" ] dependencies = [ "cryptography", - "hawkauthlib", "pyjwt", "requests>=2.4.2", ]
