|
| 1 | +# @oagen-ignore-file |
| 2 | +# This file is hand-maintained. AuthKit Actions helpers for request |
| 3 | +# verification and response signing. These are client-side cryptographic |
| 4 | +# helpers that will always be hand-maintained. |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import hashlib |
| 9 | +import hmac |
| 10 | +import json |
| 11 | +import time |
| 12 | +from typing import Any, Dict, Literal, Optional, Union |
| 13 | + |
| 14 | +DEFAULT_TOLERANCE = 30 # seconds (stricter than webhooks' 180s) |
| 15 | + |
| 16 | +ActionType = Literal["authentication", "user_registration"] |
| 17 | + |
| 18 | +_ACTION_TYPE_TO_RESPONSE_OBJECT = { |
| 19 | + "authentication": "authentication_action_response", |
| 20 | + "user_registration": "user_registration_action_response", |
| 21 | +} |
| 22 | + |
| 23 | + |
| 24 | +def _verify_signature( |
| 25 | + *, |
| 26 | + payload: Union[bytes, str], |
| 27 | + sig_header: str, |
| 28 | + secret: str, |
| 29 | + tolerance: int = DEFAULT_TOLERANCE, |
| 30 | +) -> None: |
| 31 | + """Verify an HMAC-SHA256 signature header. Raises ValueError on failure.""" |
| 32 | + try: |
| 33 | + issued_part, sig_part = sig_header.split(", ") |
| 34 | + except (ValueError, AttributeError) as exc: |
| 35 | + raise ValueError( |
| 36 | + "Unable to extract timestamp and signature hash from header", |
| 37 | + sig_header, |
| 38 | + ) from exc |
| 39 | + |
| 40 | + issued_timestamp = issued_part[2:] |
| 41 | + signature_hash = sig_part[3:] |
| 42 | + |
| 43 | + current_time = time.time() |
| 44 | + timestamp_in_seconds = int(issued_timestamp) / 1000 |
| 45 | + seconds_since_issued = current_time - timestamp_in_seconds |
| 46 | + |
| 47 | + if seconds_since_issued > tolerance: |
| 48 | + raise ValueError("Timestamp outside the tolerance zone") |
| 49 | + |
| 50 | + body_str = payload.decode("utf-8") if isinstance(payload, bytes) else payload |
| 51 | + unhashed_string = f"{issued_timestamp}.{body_str}" |
| 52 | + expected_signature = hmac.new( |
| 53 | + secret.encode("utf-8"), |
| 54 | + unhashed_string.encode("utf-8"), |
| 55 | + digestmod=hashlib.sha256, |
| 56 | + ).hexdigest() |
| 57 | + |
| 58 | + if not hmac.compare_digest(signature_hash, expected_signature): |
| 59 | + raise ValueError( |
| 60 | + "Signature hash does not match the expected signature hash for payload" |
| 61 | + ) |
| 62 | + |
| 63 | + |
| 64 | +def _compute_signature(payload_str: str, secret: str) -> str: |
| 65 | + """Compute HMAC-SHA256 hex digest for a signed payload string.""" |
| 66 | + return hmac.new( |
| 67 | + secret.encode("utf-8"), |
| 68 | + payload_str.encode("utf-8"), |
| 69 | + digestmod=hashlib.sha256, |
| 70 | + ).hexdigest() |
| 71 | + |
| 72 | + |
| 73 | +class Actions: |
| 74 | + """AuthKit Actions request verification and response signing.""" |
| 75 | + |
| 76 | + def verify_header( |
| 77 | + self, |
| 78 | + *, |
| 79 | + payload: Union[bytes, str], |
| 80 | + sig_header: str, |
| 81 | + secret: str, |
| 82 | + tolerance: int = DEFAULT_TOLERANCE, |
| 83 | + ) -> None: |
| 84 | + """Verify the signature of an Actions request.""" |
| 85 | + _verify_signature( |
| 86 | + payload=payload, sig_header=sig_header, secret=secret, tolerance=tolerance, |
| 87 | + ) |
| 88 | + |
| 89 | + def construct_action( |
| 90 | + self, |
| 91 | + *, |
| 92 | + payload: Union[bytes, str], |
| 93 | + sig_header: str, |
| 94 | + secret: str, |
| 95 | + tolerance: int = DEFAULT_TOLERANCE, |
| 96 | + ) -> Dict[str, Any]: |
| 97 | + """Verify and deserialize an Actions request payload.""" |
| 98 | + self.verify_header( |
| 99 | + payload=payload, sig_header=sig_header, secret=secret, tolerance=tolerance, |
| 100 | + ) |
| 101 | + body = payload.decode("utf-8") if isinstance(payload, bytes) else payload |
| 102 | + return json.loads(body) |
| 103 | + |
| 104 | + def sign_response( |
| 105 | + self, |
| 106 | + *, |
| 107 | + action_type: ActionType, |
| 108 | + verdict: Literal["Allow", "Deny"], |
| 109 | + error_message: Optional[str] = None, |
| 110 | + secret: str, |
| 111 | + ) -> Dict[str, Any]: |
| 112 | + """Build and sign an Actions response.""" |
| 113 | + timestamp = int(time.time() * 1000) |
| 114 | + response_payload: Dict[str, Any] = { |
| 115 | + "timestamp": timestamp, |
| 116 | + "verdict": verdict, |
| 117 | + } |
| 118 | + if error_message is not None: |
| 119 | + response_payload["error_message"] = error_message |
| 120 | + |
| 121 | + payload_json = json.dumps(response_payload, separators=(",", ":")) |
| 122 | + signed_payload = f"{timestamp}.{payload_json}" |
| 123 | + signature = _compute_signature(signed_payload, secret) |
| 124 | + object_type = _ACTION_TYPE_TO_RESPONSE_OBJECT[action_type] |
| 125 | + |
| 126 | + return { |
| 127 | + "object": object_type, |
| 128 | + "payload": response_payload, |
| 129 | + "signature": signature, |
| 130 | + } |
| 131 | + |
| 132 | + |
| 133 | +class AsyncActions: |
| 134 | + """Async variant of AuthKit Actions helpers.""" |
| 135 | + |
| 136 | + def verify_header( |
| 137 | + self, |
| 138 | + *, |
| 139 | + payload: Union[bytes, str], |
| 140 | + sig_header: str, |
| 141 | + secret: str, |
| 142 | + tolerance: int = DEFAULT_TOLERANCE, |
| 143 | + ) -> None: |
| 144 | + """Verify the signature of an Actions request.""" |
| 145 | + _verify_signature( |
| 146 | + payload=payload, sig_header=sig_header, secret=secret, tolerance=tolerance, |
| 147 | + ) |
| 148 | + |
| 149 | + def construct_action( |
| 150 | + self, |
| 151 | + *, |
| 152 | + payload: Union[bytes, str], |
| 153 | + sig_header: str, |
| 154 | + secret: str, |
| 155 | + tolerance: int = DEFAULT_TOLERANCE, |
| 156 | + ) -> Dict[str, Any]: |
| 157 | + """Verify and deserialize an Actions request payload.""" |
| 158 | + self.verify_header( |
| 159 | + payload=payload, sig_header=sig_header, secret=secret, tolerance=tolerance, |
| 160 | + ) |
| 161 | + body = payload.decode("utf-8") if isinstance(payload, bytes) else payload |
| 162 | + return json.loads(body) |
| 163 | + |
| 164 | + def sign_response( |
| 165 | + self, |
| 166 | + *, |
| 167 | + action_type: ActionType, |
| 168 | + verdict: Literal["Allow", "Deny"], |
| 169 | + error_message: Optional[str] = None, |
| 170 | + secret: str, |
| 171 | + ) -> Dict[str, Any]: |
| 172 | + """Build and sign an Actions response.""" |
| 173 | + timestamp = int(time.time() * 1000) |
| 174 | + response_payload: Dict[str, Any] = { |
| 175 | + "timestamp": timestamp, |
| 176 | + "verdict": verdict, |
| 177 | + } |
| 178 | + if error_message is not None: |
| 179 | + response_payload["error_message"] = error_message |
| 180 | + |
| 181 | + payload_json = json.dumps(response_payload, separators=(",", ":")) |
| 182 | + signed_payload = f"{timestamp}.{payload_json}" |
| 183 | + signature = _compute_signature(signed_payload, secret) |
| 184 | + object_type = _ACTION_TYPE_TO_RESPONSE_OBJECT[action_type] |
| 185 | + |
| 186 | + return { |
| 187 | + "object": object_type, |
| 188 | + "payload": response_payload, |
| 189 | + "signature": signature, |
| 190 | + } |
0 commit comments