diff --git a/.github/workflows/starter.yml b/.github/workflows/starter.yml index e840cc9..6590c66 100644 --- a/.github/workflows/starter.yml +++ b/.github/workflows/starter.yml @@ -4,6 +4,7 @@ on: paths: - 'examples/odds_workspace.py' - 'examples/odds-migration/**' + - 'examples/support-report/**' - 'examples/test_odds_workspace.py' - 'parlay_api/**' - 'tests/**' @@ -14,6 +15,7 @@ on: paths: - 'examples/odds_workspace.py' - 'examples/odds-migration/**' + - 'examples/support-report/**' - 'parlay_api/**' - 'pyproject.toml' permissions: @@ -36,3 +38,5 @@ jobs: run: | python "$GITHUB_WORKSPACE/tests/test_installed_package.py" python -m pytest -q --import-mode=importlib "$GITHUB_WORKSPACE/tests/test_odds_coverage.py" "$GITHUB_WORKSPACE/tests/test_first_response.py" "$GITHUB_WORKSPACE/tests/test_migration_example.py" + - name: Exercise the offline support report + run: python -B -m unittest discover -s examples/support-report -p test_support_repro.py diff --git a/README.md b/README.md index 1365dda..33a0d08 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,8 @@ and invalid outcomes are excluded with diagnostics on stderr. Missing timestamps stay empty; timestamps are not freshness guarantees. The starter makes no rankings or profit claims, and has no automatic retries, polling or key storage. +If your first request fails, [prepare a private support report](examples/support-report/) from the HTTP status, route and optional request ID. The example runs offline. + ### Serve a private FastAPI snapshot [Run the FastAPI coverage starter](examples/fastapi-coverage/) to read game and @@ -251,4 +253,4 @@ checkout to verify the installed entry point and replay the same fixture tests. All test requests are mocked. Report bugs at [GitHub issues](https://github.com/JacobiusMakes/parlay-api-python/issues) -or contact [support](mailto:peakpotentialmediaventures@gmail.com). +or [contact Support privately](https://parlay-api.com/support). diff --git a/SUPPORT.md b/SUPPORT.md index 3d0bf2c..447e6f8 100644 --- a/SUPPORT.md +++ b/SUPPORT.md @@ -12,3 +12,5 @@ ParlayAPI is founder-run. Questions and bug reports land directly with the perso ## What helps For bugs, a minimal snippet that reproduces the problem plus your `parlayapi` package version and Python version gets you the fastest turnaround. + +For an account-specific request, [prepare a local support report](examples/support-report/) and paste the reviewed details into the [private support form](https://parlay-api.com/support) or reply in your existing Support thread. Keep keys, raw headers and private response bodies out of public issues. diff --git a/examples/first-response/README.md b/examples/first-response/README.md index d40761b..6d23ea4 100644 --- a/examples/first-response/README.md +++ b/examples/first-response/README.md @@ -13,6 +13,6 @@ Use the HTTP status and service error code to decide what to do with a failed re **Worked example.** You receive an NBA moneyline at 12:04:00 UTC. Its market last updated at 12:00:00 UTC. The observed age is 240 seconds. If your application requires a price no older than 90 seconds, withhold the quote. Game start time and a fresh timestamp on a different book cannot establish when this quote changed. -A separate HTTP 429 means a request-rate limit was reached. Pause callers sharing the limit and respect a supplied `Retry-After`. For a support reproduction, retain the request ID if supplied, the UTC time, status, error code and route template. Keep the key, raw authorization headers and private response out of the report. +A separate HTTP 429 means a request-rate limit was reached. Pause callers sharing the limit and respect a supplied `Retry-After`. To [prepare a private support report offline](../support-report/), retain the request ID if supplied, the UTC time, status, error code and route template. Keep the key, raw authorization headers and private response out of the report. [Check historical coverage](https://parlay-api.com/historical-coverage) · [Check current plan limits](https://parlay-api.com/pricing) · [Rehearse retry decisions offline](https://github.com/JacobiusMakes/parlayapi-notebooks/tree/main/labs/response-triage) · [Inspect an NBA response without a key](https://parlay-api.com/try) diff --git a/examples/support-report/README.md b/examples/support-report/README.md new file mode 100644 index 0000000..14f7f1e --- /dev/null +++ b/examples/support-report/README.md @@ -0,0 +1,41 @@ +# Prepare a private support report + +If a sports odds request returned an unexpected status, empty result or stale quote, record what you observed before retrying. This Python 3.9+ tool turns selected response metadata into a small JSON report on your computer. It requires no packages, API key or network connection. + +## Try the fictional request + +[Download the standalone kit](https://github.com/JacobiusMakes/parlay-api-python/releases/download/support-report-2026-12/parlayapi-support-report.zip), unzip it and run the following from the extracted directory. From a repository checkout, run it in `examples/support-report/`. + +```sh +python3 -B support_repro.py --input synthetic-example.json +``` + +The example shows a fictional HTTP 400 on the NBA odds route. Its error code is `QUERY_PARAMETER_TYPO` and its suggested parameter is `markets`. The HTTP date is 12:00:00 UTC and the client received the response at 12:00:02 UTC. Neither clock establishes when a sportsbook changed a price. + +## Record one request + +1. Copy `template.json` to `my-input.json`. Enter the HTTP status you actually received. For a timeout with no response, describe the timeout and local time to Support directly. A guessed HTTP status can send the investigation in the wrong direction. +2. Add any available fields from the table. Omit unavailable values. Enter selected metadata by hand. Keep raw logs, headers, curl commands, credentials and customer records on your machine. +3. Create a new report and open it locally to review it. + +```sh +python3 -B support_repro.py --input my-input.json --output my-report.json +``` + +| Optional input | What to enter | +| --- | --- | +| `observation.received_at` | Your client’s response time, including an offset, for example `2026-12-01T11:30:00-05:00`. The report converts it to UTC. | +| `observation.sport`, `market`, `region` | A supported sport key or filter you actually used. The sport choices are the six public preview sports. Market choices are `h2h`, `spreads` and `totals`. The script lists the supported regions. Leave any unsupported scope out and describe it privately. | +| `response_headers` | Copy individual `Date`, `Retry-After` or `x-requests-used`, `x-requests-remaining`, `x-requests-last` values as strings. | +| `diagnostics` | The HTTP method, known route template and recognized error code. Use a template such as `/v1/sports/{sport_key}/odds` or `/v1/try/{sport_key}/odds`. An optional `result_count` describes the reported top-level list only. | +| `response_headers.X-Request-ID` | The report omits the value by default. If you reviewed the response ID and want to give it privately to Support, rerun with `--include-request-id` and a new output filename. The tool accepts 16 or 32 hexadecimal characters. Callers can supply their own IDs, so the format alone cannot establish provenance. | + +The report labels a recognized supplied code separately from a default inferred from HTTP status. For example, a 403 alone cannot tell Support whether you ran out of credits. An HTTP 200 can still contain an empty board or an older quote. Use the [first-response guide](https://github.com/JacobiusMakes/parlay-api-python/tree/main/examples/first-response) to interpret those cases. + +## Give Support the reviewed facts + +Reply in your existing Support email thread when you have one. For a new technical question, open the [private support form](https://parlay-api.com/support), choose **Integration / API**, and paste the relevant reviewed JSON as text in **Message**. Include a short description of what you expected. The form accepts 10–5,000 characters in the message. Keep private request IDs out of public GitHub issues. + +For a freshness investigation, include the affected event, bookmaker, market and selection in the private message. Specify pregame or in-play and the period or line when applicable. Record the UTC time of your observation and any **separately timed** change you observed at the sportsbook. An HTTP response date alone cannot demonstrate a frozen price. + +The script sends nothing. It refuses credential or cookie header names, drops unrecognized response fields, and refuses to overwrite an existing report. On POSIX it creates the file with owner-only permissions. The fictional example and regression suite can be run locally with `python3 -B -m unittest discover -s . -p test_support_repro.py`. diff --git a/examples/support-report/support_repro.py b/examples/support-report/support_repro.py new file mode 100644 index 0000000..afcc835 --- /dev/null +++ b/examples/support-report/support_repro.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python3 +"""Offline, allowlisted ParlayAPI support metadata. No HTTP or environment reads.""" +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +from email.utils import parsedate_to_datetime +import json +import os +from pathlib import Path +import re +import sys + +MAX_INPUT_BYTES = 65536 +ROUTES = frozenset({ + "/v1/sports", "/v1/bookmakers", "/v1/status", "/v1/try/{sport_key}/odds", + "/v1/sports/{sport_key}/events", "/v1/sports/{sport_key}/odds", + "/v1/sports/{sport_key}/props", "/v1/sports/{sport_key}/scores", + "/v1/sports/{sport_key}/props/coverage", "/v1/sports/{sport_key}/odds/coverage", + "/v1/historical/sports/{sport_key}/odds", "", +}) +METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "TRACE", "CONNECT", "OTHER"}) +STATUS_CODES = { + 400: "BAD_REQUEST", 401: "UNAUTHORIZED", 402: "PAYMENT_REQUIRED", + 403: "FORBIDDEN", 404: "NOT_FOUND", 405: "METHOD_NOT_ALLOWED", + 409: "CONFLICT", 410: "GONE", 413: "PAYLOAD_TOO_LARGE", + 415: "UNSUPPORTED_MEDIA_TYPE", 422: "VALIDATION_ERROR", + 429: "TOO_MANY_REQUESTS", 451: "UNAVAILABLE_FOR_LEGAL_REASONS", + 500: "INTERNAL_SERVER_ERROR", 502: "BAD_GATEWAY", + 503: "SERVICE_UNAVAILABLE", 504: "GATEWAY_TIMEOUT", +} +ERROR_CODES = frozenset(STATUS_CODES.values()) | frozenset({ + "QUERY_PARAMETER_TYPO", "MISSING_KEY", "MISSING_API_KEY", "INVALID_KEY", + "KEY_ROTATED", "KEY_EXPIRED", "KEY_REVOKED", "OUT_OF_USAGE_CREDITS", + "CREDIT_LIMIT_REACHED", "EXCEEDED_FREQ_LIMIT", "UNKNOWN_BOOKMAKER", + "INVALID_SPORT", "INVALID_MARKET", "INVALID_REGION", "DB_POOL_SATURATED", + "TEMPORARILY_UNAVAILABLE", "odds_board_temporarily_unavailable", +}) +PARAMETERS = frozenset({"markets", "bookmakers", "regions", "oddsFormat", "dateFormat", "eventIds"}) +CREDIT_HEADERS = frozenset({"x-requests-used", "x-requests-remaining", "x-requests-last"}) +FORBIDDEN_HEADERS = frozenset({ + "authorization", "proxy-authorization", "x-api-key", "apikey", "api-key", + "api_key", "cookie", "set-cookie", +}) +SAFE_HEADERS = CREDIT_HEADERS | {"date", "retry-after", "x-request-id"} +SAFE_DIAGNOSTIC_FIELDS = frozenset({ + "schema", "status", "route", "method", "error_code", "result_count", "empty", + "suggested_parameters", "unknown_query_count", "query_truncated", +}) + + +class SafeInputError(ValueError): + """Messages are fixed codes, never copies of submitted values or paths.""" + + +def integer(value, minimum, maximum): + if type(value) is not int or not minimum <= value <= maximum: + raise SafeInputError("invalid_integer_metadata") + return value + + +def header_integer(value): + if not isinstance(value, str) or not re.fullmatch(r"[0-9]{1,13}", value): + raise SafeInputError("invalid_numeric_header") + return integer(int(value), 0, 10**12) + + +def header_date(value): + if not isinstance(value, str) or len(value) > 80 or "\r" in value or "\n" in value: + raise SafeInputError("invalid_date_header") + try: + stamp = parsedate_to_datetime(value) + if stamp.utcoffset() is None: + raise ValueError + return stamp.astimezone(timezone.utc).isoformat() + except (ValueError, TypeError, OverflowError) as exc: + raise SafeInputError("invalid_date_header") from exc + + +def enum_or_unknown(value, allowed): + return value if isinstance(value, str) and value in allowed else "unknown" + + +# Public sample sport keys and common odds filters. A report can omit any scope field. +SCOPE_VALUES = { + "sport": {"basketball_nba", "baseball_mlb", "icehockey_nhl", "americanfootball_nfl", "soccer_epl", "mma_mixed_martial_arts"}, + "market": {"h2h", "spreads", "totals"}, + "region": {"us", "us2", "uk", "eu", "fr", "au", "ca", "mx", "latam", "br", "asia"}, +} + + +def checked_observation(observation): + allowed = set(SCOPE_VALUES) | {"received_at"} + if not isinstance(observation, dict) or set(observation) - allowed: + raise SafeInputError("unsupported_observation_field") + result = {} + for name, values in SCOPE_VALUES.items(): + if name in observation: + value = observation[name] + if not isinstance(value, str) or value not in values: + raise SafeInputError("unsupported_observation_value") + result[name] = value + if "received_at" in observation: + value = observation["received_at"] + # Require an actual local receipt time, including its UTC offset. + if not isinstance(value, str) or not re.fullmatch( + r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:[.][0-9]{1,6})?(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])", value + ): + raise SafeInputError("invalid_receipt_time") + try: + iso_value = re.sub(r"[.]([0-9]{1,6})", lambda match: "." + match[1].ljust(6, "0"), value) + stamp = datetime.fromisoformat(iso_value.replace("Z", "+00:00")) + result["received_at_utc"] = stamp.astimezone(timezone.utc).isoformat() + except (ValueError, OverflowError) as exc: + raise SafeInputError("invalid_receipt_time") from exc + return result + + +def build_bundle(metadata, *, include_request_id=False): + if not isinstance(metadata, dict) or set(metadata) - {"http_status", "response_headers", "diagnostics", "observation"}: + raise SafeInputError("unsupported_input_shape") + status = integer(metadata.get("http_status"), 100, 599) + raw_headers = metadata.get("response_headers", {}) + diag = metadata.get("diagnostics", {}) + if not isinstance(raw_headers, dict) or len(raw_headers) > 64 or not isinstance(diag, dict) or len(diag) > 64: + raise SafeInputError("invalid_metadata_mapping") + headers = {} + for key, value in raw_headers.items(): + if not isinstance(key, str) or key != key.strip() or len(key) > 80: + raise SafeInputError("invalid_header_name") + name = key.lower() + if name in headers: + raise SafeInputError("duplicate_header_name") + if name in FORBIDDEN_HEADERS: + raise SafeInputError("remove_credential_or_cookie_header_before_use") + headers[name] = value + if "status" in diag and integer(diag["status"], 100, 599) != status: + raise SafeInputError("conflicting_http_status") + if "schema" in diag and integer(diag["schema"], 1, 1) != 1: + raise SafeInputError("unsupported_diagnostic_schema") + code = enum_or_unknown(diag.get("error_code"), ERROR_CODES) + supplied_code = code != "unknown" + if code == "unknown": + code = STATUS_CODES.get(status, "HTTP_ERROR" if status >= 400 else "none") + category = ("informational" if status < 200 else "success" if status < 300 else "redirect") if status < 400 else { + 401: "authentication", 403: "authorization", 404: "routing", + 405: "routing", 422: "validation", 429: "rate_limit", + }.get(status, "server_error" if status >= 500 else "request_error") + if code == "QUERY_PARAMETER_TYPO": + category = "validation" + elif code in {"OUT_OF_USAGE_CREDITS", "CREDIT_LIMIT_REACHED"}: + category = "quota" + result = { + "kit_schema": 1, + "http_status": status, + "http_2xx": 200 <= status < 300, + "diagnostic_category": category, + "error_code": code, + "error_code_source": "supplied" if supplied_code else "status_default", + "route_template": enum_or_unknown(diag.get("route"), ROUTES), + "method": enum_or_unknown(diag.get("method"), METHODS), + "response_metadata": {}, + "request_id_present": "x-request-id" in headers, + "request_id_included": False, + "omitted_header_count": sum(k not in SAFE_HEADERS for k in headers), + "omitted_diagnostic_field_count": sum(k not in SAFE_DIAGNOSTIC_FIELDS for k in diag), + "runtime": {"python": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}", + "platform_family": sys.platform if sys.platform in {"linux", "darwin", "win32"} else "other"}, + "bundle_generated_at_utc": datetime.now(timezone.utc).isoformat(), + "limitations": [ + "For a useful result, verify the selected event, market, outcome and source time.", + "result_count describes the reported top-level list length. Verify price availability separately.", + "HTTP Date and report creation time measure separate steps from a sportsbook update.", + "Missing metadata means unknown. Source update times and response bodies stay outside the report.", + "The person preparing this report supplied its observations.", + ], + } + if "observation" in metadata: + result["observation"] = checked_observation(metadata["observation"]) + for name in CREDIT_HEADERS & headers.keys(): + result["response_metadata"][name] = header_integer(headers[name]) + if "date" in headers: + result["response_metadata"]["http_date_utc"] = header_date(headers["date"]) + if "retry-after" in headers: + value = headers["retry-after"] + if isinstance(value, str) and re.fullmatch(r"[0-9]{1,13}", value): + result["response_metadata"]["retry_after_seconds"] = header_integer(value) + else: + result["response_metadata"]["retry_after_http_date_utc"] = header_date(value) + if include_request_id and "x-request-id" in headers: + rid = headers["x-request-id"] + if not isinstance(rid, str) or not re.fullmatch(r"(?:[0-9a-fA-F]{16}|[0-9a-fA-F]{32})", rid): + raise SafeInputError("request_id_not_in_narrow_supported_format") + result["request_id"] = rid.lower() + result["request_id_included"] = True + if "result_count" in diag: + count = integer(diag["result_count"], 0, 2**31 - 1) + if "empty" in diag and (type(diag["empty"]) is not bool or diag["empty"] != (count == 0)): + raise SafeInputError("conflicting_empty_result_metadata") + result.update(result_count=count, empty=count == 0) + elif "empty" in diag: + raise SafeInputError("empty_without_result_count") + if "unknown_query_count" in diag: + result["unknown_query_count"] = integer(diag["unknown_query_count"], 0, 64) + if "query_truncated" in diag: + if type(diag["query_truncated"]) is not bool: + raise SafeInputError("invalid_query_truncation_flag") + result["query_truncated"] = diag["query_truncated"] + suggestions = diag.get("suggested_parameters", []) + if not isinstance(suggestions, list) or len(suggestions) > 64: + raise SafeInputError("invalid_parameter_suggestions") + result["suggested_parameters"] = sorted({s for s in suggestions if isinstance(s, str) and s in PARAMETERS}) + return result + + +def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise SafeInputError("duplicate_json_key") + result[key] = value + return result + + +def parse_metadata(raw): + if len(raw) > MAX_INPUT_BYTES: + raise SafeInputError("input_exceeds_64k_limit") + try: + value = json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object, + parse_constant=reject_nonfinite) + except (UnicodeError, json.JSONDecodeError, RecursionError, ValueError) as exc: + if isinstance(exc, SafeInputError): + raise + raise SafeInputError("invalid_json_metadata") from exc + pending = [(value, 0)] + while pending: + item, depth = pending.pop() + if depth > 8: + raise SafeInputError("input_nesting_exceeds_limit") + if isinstance(item, (dict, list)): + children = item.values() if isinstance(item, dict) else item + pending.extend((child, depth + 1) for child in children) + return value + + +def reject_nonfinite(_): + raise SafeInputError("nonfinite_json_number") + + +class SafeParser(argparse.ArgumentParser): + def error(self, message): + self.exit(2, "Invalid command line; use --help. No submitted arguments were echoed.\n") + + +def main(argv=None): + parser = SafeParser(description=__doc__) + parser.add_argument("--input", help="Curated metadata JSON file; default is stdin.") + parser.add_argument("--output", help="Create a new mode0600 file; default is stdout. Never overwrites.") + parser.add_argument("--include-request-id", action="store_true", help="Opt in to a reviewed 16/32-character hex response request ID. Share privately with Support.") + args = parser.parse_args(argv) + try: + if args.input: + with Path(args.input).open("rb") as stream: + raw = stream.read(MAX_INPUT_BYTES + 1) + else: + raw = sys.stdin.buffer.read(MAX_INPUT_BYTES + 1) + bundle = build_bundle(parse_metadata(raw), include_request_id=args.include_request_id) + encoded = json.dumps(bundle, indent=2, sort_keys=True) + "\n" + if args.output: + fd = os.open(args.output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as stream: + stream.write(encoded) + else: + sys.stdout.write(encoded) + except SafeInputError as exc: + sys.stderr.write(f"Rejected metadata: {exc}. No bundle created.\n") + return 2 + except OSError: + sys.stderr.write("Input/output failed. Output is never overwritten; inspect any partial new file before reuse.\n") + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/support-report/synthetic-example.json b/examples/support-report/synthetic-example.json new file mode 100644 index 0000000..f873acc --- /dev/null +++ b/examples/support-report/synthetic-example.json @@ -0,0 +1,27 @@ +{ + "http_status": 400, + "response_headers": { + "X-Request-ID": "0123456789abcdef", + "Date": "Mon, 28 Sep 2026 12:00:00 GMT", + "x-requests-last": "0", + "x-requests-remaining": "1000" + }, + "diagnostics": { + "schema": 1, + "status": 400, + "route": "/v1/sports/{sport_key}/odds", + "method": "GET", + "error_code": "QUERY_PARAMETER_TYPO", + "suggested_parameters": [ + "markets" + ], + "unknown_query_count": 1, + "query_truncated": false + }, + "observation": { + "sport": "basketball_nba", + "region": "us", + "market": "h2h", + "received_at": "2026-09-28T08:00:02-04:00" + } +} diff --git a/examples/support-report/template.json b/examples/support-report/template.json new file mode 100644 index 0000000..0920984 --- /dev/null +++ b/examples/support-report/template.json @@ -0,0 +1,5 @@ +{ + "http_status": null, + "response_headers": {}, + "diagnostics": {} +} diff --git a/examples/support-report/test_support_repro.py b/examples/support-report/test_support_repro.py new file mode 100644 index 0000000..2f8457c --- /dev/null +++ b/examples/support-report/test_support_repro.py @@ -0,0 +1,229 @@ +"""Offline privacy and semantic boundaries; all inputs are synthetic.""" +from copy import deepcopy +import json +from pathlib import Path +import stat +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest + +from support_repro import MAX_INPUT_BYTES, SafeInputError, build_bundle, parse_metadata + +ROOT = Path(__file__).resolve().parent +SENTINEL = "SYNTHETIC_PRIVATE_VALUE_DO_NOT_COPY" + + +class SupportReproductionTests(unittest.TestCase): + def setUp(self): + self.example = json.loads((ROOT / "synthetic-example.json").read_text()) + + def cli(self, *args, raw=None): + return subprocess.run([sys.executable, "-B", str(ROOT / "support_repro.py"), *args], + input=raw, capture_output=True, text=True, timeout=5, cwd=ROOT) + + def test_opt_in_scope_and_distinct_receipt_clock(self): + bundle = build_bundle(self.example) + observation = bundle["observation"] + self.assertEqual(observation["received_at_utc"], "2026-09-28T12:00:02+00:00") + self.assertEqual(observation["market"], "h2h") + self.assertEqual(observation["sport"], "basketball_nba") + self.assertEqual(bundle["response_metadata"]["http_date_utc"], "2026-09-28T12:00:00+00:00") + self.assertNotIn("observation", build_bundle({"http_status": 200})) + + def test_observation_rejects_caller_text_and_missing_or_invalid_timezone(self): + for field, value in [("sport", SENTINEL), ("url", SENTINEL), ("market", ["h2h"]), + ("received_at", "2026-12-01T11:00:00"), + ("received_at", "2026-02-30T11:00:00Z"), + ("received_at", "2026-12-01T11:00:00+01:91")]: + with self.subTest(field=field, value=value): + process = self.cli(raw=json.dumps({"http_status": 200, "observation": {field: value}})) + self.assertEqual(process.returncode, 2) + self.assertEqual(process.stdout, "") + self.assertNotIn(value if isinstance(value, str) else SENTINEL, process.stderr) + + def test_unknown_reported_error_is_distinct_from_known_service_code(self): + known = build_bundle(self.example) + self.assertEqual(known["error_code_source"], "supplied") + unknown = build_bundle({"http_status": 403, "diagnostics": {"error_code": SENTINEL}}) + self.assertEqual(unknown["error_code_source"], "status_default") + self.assertEqual(unknown["error_code"], "FORBIDDEN") + self.assertNotIn(SENTINEL, json.dumps(unknown)) + + def test_real_typo_semantics_without_request_values(self): + result = build_bundle(self.example) + self.assertEqual(result["diagnostic_category"], "validation") + self.assertEqual(result["error_code"], "QUERY_PARAMETER_TYPO") + self.assertEqual(result["suggested_parameters"], ["markets"]) + self.assertEqual(result["route_template"], "/v1/sports/{sport_key}/odds") + self.assertEqual(result["response_metadata"]["x-requests-last"], 0) + self.assertNotIn("result_count", result) + self.assertNotIn("empty", result) + + def test_missing_is_not_zero_and_status_is_required(self): + result = build_bundle({"http_status": 200}) + self.assertEqual(result["response_metadata"], {}) + self.assertNotIn("result_count", result) + self.assertEqual(result["route_template"], "unknown") + for value in [None, True, "200", 99, 600]: + with self.subTest(value=value), self.assertRaises(SafeInputError): + build_bundle({"http_status": value}) + + def test_credentials_and_cookies_fail_without_echo(self): + for header in ["Authorization", "PROXY-AUTHORIZATION", "X-API-Key", "api_key", + "apiKey", "Cookie", "Set-Cookie"]: + value = deepcopy(self.example) + value["response_headers"][header] = SENTINEL + with self.subTest(header=header), self.assertRaisesRegex(SafeInputError, "^remove_credential_or_cookie_header_before_use$"): + build_bundle(value) + process = self.cli(raw=json.dumps(value)) + self.assertEqual(process.returncode, 2) + self.assertEqual(process.stdout, "") + self.assertNotIn(SENTINEL, process.stderr) + self.assertNotIn(header, process.stderr) + + def test_unknown_fields_customer_ids_and_response_data_are_omitted(self): + self.example["response_headers"]["X-Private-" + SENTINEL] = SENTINEL + self.example["diagnostics"].update({ + "user_id": 998877665544332211, + "email": SENTINEL, + "api_key": SENTINEL, + "query_values": {"eventIds": SENTINEL}, + "filters": {"bookmakers": SENTINEL}, + "sport_key": SENTINEL, + "odds": [{"customer": SENTINEL, "price": 123456.789}], + "free_form_error": SENTINEL, + }) + result = build_bundle(self.example) + encoded = json.dumps(result) + for private in [SENTINEL, "998877665544332211", "123456.789"]: + self.assertNotIn(private, encoded) + self.assertEqual(result["omitted_header_count"], 1) + self.assertEqual(result["omitted_diagnostic_field_count"], 8) + + def test_raw_urls_messages_and_method_values_cannot_escape(self): + diag = self.example["diagnostics"] + diag.update(route="https://example.invalid/?api_key=" + SENTINEL, + method=SENTINEL, error_code=SENTINEL, + suggested_parameters=[SENTINEL, {"markets": SENTINEL}, "markets"]) + result = build_bundle(self.example) + self.assertNotIn(SENTINEL, json.dumps(result)) + self.assertEqual(result["route_template"], "unknown") + self.assertEqual(result["method"], "unknown") + self.assertEqual(result["error_code"], "BAD_REQUEST") + self.assertEqual(result["suggested_parameters"], ["markets"]) + + def test_raw_capture_envelopes_are_not_supported(self): + for field in ["body", "request_url", "curl", "account", "response", "log"]: + value = {**self.example, field: SENTINEL} + with self.subTest(field=field), self.assertRaisesRegex(SafeInputError, "^unsupported_input_shape$"): + build_bundle(value) + + def test_request_id_omitted_by_default_and_opt_in_is_narrow(self): + result = build_bundle(self.example) + self.assertTrue(result["request_id_present"]) + self.assertFalse(result["request_id_included"]) + self.assertNotIn("0123456789abcdef", json.dumps(result)) + result = build_bundle(self.example, include_request_id=True) + self.assertEqual(result["request_id"], "0123456789abcdef") + for value in [SENTINEL, "caller@example.invalid", "a" * 16 + "\n", "pak_live_" + SENTINEL]: + self.example["response_headers"]["X-Request-ID"] = value + self.assertNotIn(value, json.dumps(build_bundle(self.example))) + with self.subTest(value=value), self.assertRaises(SafeInputError): + build_bundle(self.example, include_request_id=True) + + def test_generated_trace_id_format_is_supported_only_on_opt_in(self): + self.example["response_headers"]["X-Request-ID"] = "AB" * 16 + result = build_bundle(self.example, include_request_id=True) + self.assertEqual(result["request_id"], "ab" * 16) + + def test_quota_is_distinct_from_rate_limit(self): + quota = build_bundle({"http_status": 403, "diagnostics": {"error_code": "OUT_OF_USAGE_CREDITS"}}) + rate = build_bundle({"http_status": 429, "response_headers": {"Retry-After": "60"}}) + self.assertEqual(quota["diagnostic_category"], "quota") + self.assertEqual(rate["diagnostic_category"], "rate_limit") + self.assertEqual(rate["response_metadata"]["retry_after_seconds"], 60) + + def test_http_success_redirect_and_list_count_are_separate(self): + result = build_bundle({"http_status": 200, "diagnostics": {"result_count": 0, "empty": True}}) + self.assertTrue(result["http_2xx"]) + self.assertTrue(result["empty"]) + result = build_bundle({"http_status": 302}) + self.assertEqual(result["diagnostic_category"], "redirect") + self.assertFalse(result["http_2xx"]) + self.assertTrue(any("useful" in line for line in result["limitations"])) + result = build_bundle({"http_status": 103}) + self.assertEqual(result["diagnostic_category"], "informational") + self.assertFalse(result["http_2xx"]) + + def test_conflicting_status_and_count_are_rejected(self): + cases = [{"http_status": 200, "diagnostics": {"status": 500}}, + {"http_status": 200, "diagnostics": {"result_count": 0, "empty": False}}, + {"http_status": 200, "diagnostics": {"empty": True}}, + {"http_status": 200, "diagnostics": {"schema": 2}}] + for value in cases: + with self.subTest(value=value), self.assertRaises(SafeInputError): + build_bundle(value) + for value in [True, -1, 0.1, "0", 2**31]: + with self.subTest(value=value), self.assertRaises(SafeInputError): + build_bundle({"http_status": 200, "diagnostics": {"result_count": value}}) + + def test_malformed_allowlisted_header_values_cannot_leak(self): + for field in ["x-requests-used", "x-requests-remaining", "x-requests-last", "Date", "Retry-After"]: + for value in [SENTINEL, [SENTINEL], -1, True, "0\n" + SENTINEL]: + with self.subTest(field=field, value=value), self.assertRaises(SafeInputError): + build_bundle({"http_status": 200, "response_headers": {field: value}}) + + def test_http_dates_are_normalized_not_source_freshness(self): + result = build_bundle({"http_status": 429, "response_headers": { + "Date": "Mon, 28 Sep 2026 12:00:00 GMT", + "Retry-After": "Mon, 28 Sep 2026 12:05:00 GMT"}}) + self.assertEqual(result["response_metadata"]["http_date_utc"], "2026-09-28T12:00:00+00:00") + self.assertEqual(result["response_metadata"]["retry_after_http_date_utc"], "2026-09-28T12:05:00+00:00") + self.assertNotIn("source_timestamp", result) + + def test_duplicate_and_nonfinite_json_and_case_collisions_fail(self): + for raw in [b'{"http_status":200,"http_status":400}', b'{"http_status":NaN}', + b'{"http_status":Infinity}', b'\xff', b'{bad']: + with self.subTest(raw=raw), self.assertRaises(SafeInputError): + parse_metadata(raw) + with self.assertRaises(SafeInputError): + build_bundle({"http_status": 200, "response_headers": {"Date": "x", "date": "y"}}) + + def test_input_limit_and_nested_input_error_are_bounded(self): + with self.assertRaisesRegex(SafeInputError, "input_exceeds"): + parse_metadata(b" " * (MAX_INPUT_BYTES + 1)) + with self.assertRaises(SafeInputError): + parse_metadata(b"[" * 2000 + b"]" * 2000) + + def test_cli_creates_private_file_and_never_overwrites(self): + with TemporaryDirectory(dir=ROOT) as directory: + output = Path(directory) / "bundle.json" + result = self.cli("--input", str(ROOT / "synthetic-example.json"), "--output", str(output)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o600) + before = output.read_bytes() + result = self.cli("--input", str(ROOT / "synthetic-example.json"), "--output", str(output)) + self.assertEqual(result.returncode, 2) + self.assertEqual(output.read_bytes(), before) + + def test_rejected_input_creates_no_output_and_echoes_no_secret(self): + with TemporaryDirectory(dir=ROOT) as directory: + output = Path(directory) / "bundle.json" + result = self.cli("--output", str(output), raw='{"http_status": "' + SENTINEL + '"}') + self.assertEqual(result.returncode, 2) + self.assertFalse(output.exists()) + self.assertNotIn(SENTINEL, result.stdout + result.stderr) + result = self.cli("--unexpected", SENTINEL) + self.assertEqual(result.returncode, 2) + self.assertNotIn(SENTINEL, result.stdout + result.stderr) + + def test_input_not_mutated_and_runtime_contains_no_machine_identity(self): + before = deepcopy(self.example) + result = build_bundle(self.example) + self.assertEqual(self.example, before) + self.assertEqual(set(result["runtime"]), {"python", "platform_family"}) + + +if __name__ == "__main__": + unittest.main()