|
| 1 | +"""OBS "Signature" (SSH) authentication as a ``requests`` auth handler. |
| 2 | +
|
| 3 | +Reproduces the OBS Signature challenge/response in-process (no ``osc``, no |
| 4 | +subprocess): the first request goes out unauthenticated (the session may |
| 5 | +already hold a cookie); on a 401 the ``WWW-Authenticate: Signature`` realm |
| 6 | +is read, an SSHSIG over ``(created): <epoch>`` is built with paramiko, and |
| 7 | +the request is resent exactly once with the ``Authorization: Signature`` |
| 8 | +header. Day-one scope is an Ed25519 key from an explicit file; encrypted, |
| 9 | +agent, and non-Ed25519 keys fail closed with a typed :class:`ObsConfigError`. |
| 10 | +The Authorization header and its signature are never logged. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import time |
| 16 | +from logging import getLogger |
| 17 | +from pathlib import Path |
| 18 | +from typing import Any, override |
| 19 | +from urllib.request import parse_http_list, parse_keqv_list |
| 20 | + |
| 21 | +import paramiko |
| 22 | +import requests |
| 23 | +import requests.auth |
| 24 | + |
| 25 | +from ...support.exceptions import ObsConfigError |
| 26 | +from . import sshsig |
| 27 | + |
| 28 | +logger = getLogger("mtui.data_sources.obs.auth") |
| 29 | + |
| 30 | +_SIGNATURE_SCHEME = "signature" |
| 31 | + |
| 32 | + |
| 33 | +def _challenge_params(response: requests.Response) -> dict[str, dict[str, str]]: |
| 34 | + """Parse ``WWW-Authenticate`` into ``{scheme: {param: value}}``. |
| 35 | +
|
| 36 | + Reads the RAW multi-value header list from urllib3 rather than |
| 37 | + ``response.headers['WWW-Authenticate']`` — ``requests`` comma-merges |
| 38 | + duplicate headers into a single unparseable string, which would hide a |
| 39 | + second challenge (e.g. ``Basic`` alongside ``Signature``). |
| 40 | + """ |
| 41 | + raw = getattr(response.raw, "headers", None) |
| 42 | + if raw is not None and hasattr(raw, "getlist"): |
| 43 | + lines = raw.getlist("WWW-Authenticate") |
| 44 | + else: # pragma: no cover - requests always exposes urllib3 raw headers |
| 45 | + merged = response.headers.get("WWW-Authenticate", "") |
| 46 | + lines = [merged] if merged else [] |
| 47 | + |
| 48 | + schemes: dict[str, dict[str, str]] = {} |
| 49 | + for line in lines: |
| 50 | + line = line.strip() |
| 51 | + if not line: |
| 52 | + continue |
| 53 | + scheme, _, rest = line.partition(" ") |
| 54 | + params: dict[str, str] = {} |
| 55 | + if rest.strip(): |
| 56 | + try: |
| 57 | + params = parse_keqv_list(parse_http_list(rest)) |
| 58 | + except ValueError: |
| 59 | + params = {} |
| 60 | + schemes[scheme.lower()] = params |
| 61 | + return schemes |
| 62 | + |
| 63 | + |
| 64 | +class ObsSignatureAuth(requests.auth.AuthBase): |
| 65 | + """A ``requests`` auth handler for OBS SSH-signature authentication.""" |
| 66 | + |
| 67 | + def __init__(self, user: str, sshkey_path: Path) -> None: |
| 68 | + """Initialise with the acting user and its Ed25519 private-key path.""" |
| 69 | + self.user = user |
| 70 | + self.sshkey_path = sshkey_path |
| 71 | + self._retried = False |
| 72 | + |
| 73 | + def _load_key(self) -> paramiko.Ed25519Key: |
| 74 | + """Load the Ed25519 key, failing closed (never prompting).""" |
| 75 | + try: |
| 76 | + return paramiko.Ed25519Key.from_private_key_file(str(self.sshkey_path)) |
| 77 | + except paramiko.PasswordRequiredException as e: |
| 78 | + raise ObsConfigError( |
| 79 | + f"ssh key {self.sshkey_path} is passphrase-protected; the native " |
| 80 | + "OBS backend needs an unencrypted key or an ssh-agent (agent " |
| 81 | + "support is not yet available)" |
| 82 | + ) from e |
| 83 | + except paramiko.SSHException as e: |
| 84 | + raise ObsConfigError( |
| 85 | + f"ssh key {self.sshkey_path} is not a usable Ed25519 key " |
| 86 | + f"({e}); only Ed25519 keys are supported by the native OBS " |
| 87 | + "backend today" |
| 88 | + ) from e |
| 89 | + except OSError as e: |
| 90 | + raise ObsConfigError( |
| 91 | + f"ssh key {self.sshkey_path} could not be read: {e}" |
| 92 | + ) from e |
| 93 | + |
| 94 | + def _authorization(self, realm: str) -> str: |
| 95 | + """Build the ``Authorization: Signature …`` header value for ``realm``.""" |
| 96 | + created = int(time.time()) |
| 97 | + blob = sshsig.sign_created(self._load_key(), realm, created) |
| 98 | + return ( |
| 99 | + f'Signature keyId="{self.user}",algorithm="ssh",' |
| 100 | + f'headers="(created)",created={created},signature="{blob}"' |
| 101 | + ) |
| 102 | + |
| 103 | + def handle_401( |
| 104 | + self, response: requests.Response, **kwargs: Any |
| 105 | + ) -> requests.Response: |
| 106 | + """On a 401 Signature challenge, sign and resend the request once.""" |
| 107 | + if response.status_code != 401 or self._retried: |
| 108 | + return response |
| 109 | + |
| 110 | + schemes = _challenge_params(response) |
| 111 | + if _SIGNATURE_SCHEME not in schemes: |
| 112 | + logger.error( |
| 113 | + "OBS returned 401 but did not offer Signature auth (offered: %s)", |
| 114 | + ", ".join(sorted(schemes)) or "nothing", |
| 115 | + ) |
| 116 | + return response |
| 117 | + |
| 118 | + self._retried = True |
| 119 | + realm = schemes[_SIGNATURE_SCHEME].get("realm", "") |
| 120 | + |
| 121 | + # Consume and release the challenge response before resending. |
| 122 | + _ = response.content |
| 123 | + response.close() |
| 124 | + |
| 125 | + prepared = response.request.copy() |
| 126 | + prepared.headers["Authorization"] = self._authorization(realm) |
| 127 | + |
| 128 | + retried = response.connection.send(prepared, **kwargs) |
| 129 | + retried.history.append(response) |
| 130 | + retried.request = prepared |
| 131 | + return retried |
| 132 | + |
| 133 | + @override |
| 134 | + def __call__(self, r: requests.PreparedRequest) -> requests.PreparedRequest: |
| 135 | + """Attach the 401 handler; the first request carries no Authorization.""" |
| 136 | + self._retried = False |
| 137 | + r.register_hook("response", self.handle_401) |
| 138 | + return r |
0 commit comments