diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b24b189..b94bf3b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,4 +29,4 @@ jobs: - name: Examples import cleanly run: | python -m py_compile examples/*.py - python -c "import infinihash_kyc as k; print(k.__version__)" + python -c "import infinihash_baas as k; print(k.__version__)" diff --git a/.gitignore b/.gitignore index 75c6182..54511b0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,8 @@ __pycache__/ *.pyc .pytest_cache/ +build/ +dist/ +*.egg-info/ +__pycache__/ +.pytest_cache/ diff --git a/README.md b/README.md index 8356618..e100088 100644 --- a/README.md +++ b/README.md @@ -16,4 +16,31 @@ r.pay_invoice(inv["id"], idempotency_key="INV-1-pay-1") # retries never double - `verify_webhook_signature(secret, raw_body, header)` is fail-closed. - `create_sandbox_key(email)` gets a free, instant sandbox key (no sign-up); `examples/sandbox_quickstart.py` goes from nothing to a paid sandbox invoice. - Examples: `examples/capabilities.py` (no key needed), `examples/sandbox_quickstart.py`, `examples/invoice_and_collect.py`. -- Reference: https://rails-api.infinihash.com/api/docs. Get started: https://onboard.infinihash.com. +- Reference: https://rails-api.infinihash.com/docs/openapi.public.json (public OpenAPI spec; the full `/api/docs` reference needs an API key). Get started: https://onboard.infinihash.com. + +## Verifying a signed records export + +`records_export()` returns parsed JSON, which **cannot** be verified because the signature covers the exact response bytes. For evidence you will verify or keep, use `records_export_signed()`: + +```python +r = Rails("ihb_...") +exp = r.records_export_signed(from_="2026-01-01T00:00:00Z") # format="csv" also works +# exp == {"body": b"...", "signature": "ed25519;keyid=...;sig=...", "key_id": "...", "sha256": "..."} +key = r.signing_key() # {"alg": "ed25519", "keyId": ..., "publicKeyPem": ...}; no API key needed +assert exp["key_id"] == key["keyId"] +``` + +`signature` is the `X-Infinihash-Export-Signature` header: `ed25519;keyid=;sig=` over the exact body bytes, or `unsigned` when the deployment has no signing key. Store `body` as-is. Re-serialising the JSON breaks the signature. + +This SDK only depends on `requests`, so it does not verify Ed25519 itself. With the [`cryptography`](https://pypi.org/project/cryptography/) package installed: + +```python +import base64 +from cryptography.hazmat.primitives.serialization import load_pem_public_key +from infinihash_baas import parse_export_signature + +sig = base64.b64decode(parse_export_signature(exp["signature"])["sig"]) +load_pem_public_key(key["publicKeyPem"].encode()).verify(sig, exp["body"]) # raises InvalidSignature if tampered +``` + +Or with OpenSSL 3: write `body` to `export.json`, the decoded `sig` to `export.sig` and `publicKeyPem` to `pub.pem`, then run `openssl pkeyutl -verify -pubin -inkey pub.pem -rawin -in export.json -sigfile export.sig`. diff --git a/build/lib/infinihash_baas/__init__.py b/build/lib/infinihash_baas/__init__.py deleted file mode 100644 index 5591ad0..0000000 --- a/build/lib/infinihash_baas/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from .client import ( # noqa: F401 - Rails, RailsError, CapabilityUnavailable, verify_webhook_signature, create_sandbox_key, - PRODUCTION_URL, SANDBOX_URL, -) - -__version__ = "0.1.0" diff --git a/build/lib/infinihash_baas/client.py b/build/lib/infinihash_baas/client.py deleted file mode 100644 index 365ebb8..0000000 --- a/build/lib/infinihash_baas/client.py +++ /dev/null @@ -1,136 +0,0 @@ -"""Thin client for the Infinihash Rails (BaaS) API. - -Design rules that mirror the service: - * every money-moving POST carries an Idempotency-Key (generated if you do not - pass one) so a retry can never move money twice; - * capabilities are read from the host (GET /api/v1/capabilities), never - assumed -- escrow and refunds are unavailable on every current deployment, - and `require()` raises CapabilityUnavailable instead of letting you find out - from a 409 in the middle of a flow; - * webhook signatures are verified fail-closed. -""" -import hashlib -import hmac -import time -import uuid - -import requests - -PRODUCTION_URL = "https://rails-api.infinihash.com" -SANDBOX_URL = "https://rails-sandbox.infinihash.com" - - -class RailsError(Exception): - def __init__(self, status, body): - self.status, self.body = status, body - code = body.get("code") if isinstance(body, dict) else None - super().__init__("HTTP %s%s: %s" % (status, " " + code if code else "", body)) - - -class CapabilityUnavailable(Exception): - pass - - -def create_sandbox_key(email, base_url=SANDBOX_URL, timeout=30, session=None): - """Get a free, instant sandbox API key (POST /api/v1/sandbox/keys). Sandbox host only. - - Returns the server's dict: ``apiKey`` (shown once), ``customerId`` (a starter customer to - invoice), ``baseUrl``. The key works only on the sandbox host; production refuses it. - """ - if base_url.rstrip("/") == PRODUCTION_URL.rstrip("/"): - raise ValueError("sandbox keys are issued by the sandbox host, not production") - return Rails(None, base_url=base_url, timeout=timeout, session=session)._request( - "POST", "/api/v1/sandbox/keys", json={"email": email}, auth=False) - - -class Rails: - def __init__(self, api_key=None, base_url=PRODUCTION_URL, timeout=30, session=None): - self.base_url = base_url.rstrip("/") - self.api_key = api_key - self.timeout = timeout - self._s = session or requests.Session() - - # -- transport --------------------------------------------------------- - def _request(self, method, path, json=None, params=None, idempotency_key=None, auth=True): - headers = {"Accept": "application/json"} - if auth: - if not self.api_key: - raise ValueError("api_key is required for this call") - headers["Authorization"] = "Bearer " + self.api_key - if method == "POST": - headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4()) - r = self._s.request(method, self.base_url + path, json=json, params=params, - headers=headers, timeout=self.timeout) - try: - body = r.json() - except ValueError: - body = {"raw": r.text} - if r.status_code >= 400: - raise RailsError(r.status_code, body) - return body - - # -- public, no key ---------------------------------------------------- - def health(self): - return self._request("GET", "/health", auth=False) - - def capabilities(self): - return self._request("GET", "/api/v1/capabilities", auth=False) - - def require(self, capability): - """Raise CapabilityUnavailable unless this host offers `capability`.""" - entry = self.capabilities().get("capabilities", {}).get(capability) - if not entry or not entry.get("available"): - raise CapabilityUnavailable("%s is not available on %s" % (capability, self.base_url)) - return entry - - # -- invoices ---------------------------------------------------------- - def create_invoice(self, number, customer_id, line_items, **fields): - body = dict(fields, number=number, customerId=customer_id, lineItems=line_items) - return self._request("POST", "/api/v1/invoices", json=body) - - def get_invoice(self, invoice_id): - return self._request("GET", "/api/v1/invoices/%s" % invoice_id) - - def list_invoices(self, status=None): - return self._request("GET", "/api/v1/invoices", params={"status": status} if status else None) - - def send_invoice(self, invoice_id): - return self._request("POST", "/api/v1/invoices/%s/send" % invoice_id) - - def pay_invoice(self, invoice_id, amount_cents=None, source=None, idempotency_key=None): - body = {} - if amount_cents is not None: - body["amountCents"] = amount_cents - if source is not None: - body["source"] = source - return self._request("POST", "/api/v1/invoices/%s/pay" % invoice_id, json=body, - idempotency_key=idempotency_key) - - # -- statements and evidence ------------------------------------------ - def usage(self, month=None): - return self._request("GET", "/api/v1/usage", params={"month": month} if month else None) - - def records_export(self): - """Signed (Ed25519) tenant records export; verify with signing_key().""" - return self._request("GET", "/api/v1/records/export") - - def signing_key(self): - return self._request("GET", "/api/v1/records/signing-key", auth=False) - - -def verify_webhook_signature(secret, body, header, tolerance_seconds=300, now=None): - """Verify `X-Infinihash-Signature: t=,v1=.")>`. - - Fail-closed: returns False on any malformed header, stale timestamp or - mismatch. `body` must be the raw request bytes/str, not re-serialised JSON. - """ - try: - parts = dict(p.split("=", 1) for p in header.split(",")) - t, v1 = int(parts["t"]), parts["v1"] - except Exception: - return False - if abs((now if now is not None else time.time()) - t) > tolerance_seconds: - return False - raw = body if isinstance(body, bytes) else body.encode("utf-8") - expected = hmac.new(secret.encode("utf-8"), str(t).encode() + b"." + raw, hashlib.sha256).hexdigest() - return hmac.compare_digest(expected, v1) diff --git a/infinihash_baas.egg-info/PKG-INFO b/infinihash_baas.egg-info/PKG-INFO deleted file mode 100644 index 45dc3b4..0000000 --- a/infinihash_baas.egg-info/PKG-INFO +++ /dev/null @@ -1,36 +0,0 @@ -Metadata-Version: 2.4 -Name: infinihash-baas -Version: 0.1.0 -Summary: Python SDK for Infinihash Rails (BaaS): invoices, collection, settlement, signed records export. -Author: Infinihash -License: MIT -Project-URL: Homepage, https://onboard.infinihash.com -Project-URL: API reference, https://rails-api.infinihash.com/api/docs -Project-URL: Source, https://github.com/Infinihash/baas-python -Requires-Python: >=3.8 -Description-Content-Type: text/markdown -License-File: LICENSE -Requires-Dist: requests>=2.28 -Provides-Extra: test -Requires-Dist: pytest>=7; extra == "test" -Dynamic: license-file - -# infinihash-baas - -Python SDK for **Infinihash Rails** (BaaS): invoices, ACH/stablecoin collection, settlement, signed records export. - - pip install "git+https://github.com/Infinihash/baas-python@v0.1.0" - -```python -from infinihash_baas import Rails, SANDBOX_URL -r = Rails("ihb_...", base_url=SANDBOX_URL) # build against the sandbox first -inv = r.create_invoice("INV-1", customer_id, [{"description": "Work", "unitCents": 25000}]) -r.send_invoice(inv["id"]) -r.pay_invoice(inv["id"], idempotency_key="INV-1-pay-1") # retries never double-move money -``` - -- `Rails().capabilities()` / `require("...")` read what the host really offers (escrow and refunds are unavailable on every current deployment). -- `verify_webhook_signature(secret, raw_body, header)` is fail-closed. -- `create_sandbox_key(email)` gets a free, instant sandbox key (no sign-up); `examples/sandbox_quickstart.py` goes from nothing to a paid sandbox invoice. -- Examples: `examples/capabilities.py` (no key needed), `examples/sandbox_quickstart.py`, `examples/invoice_and_collect.py`. -- Reference: https://rails-api.infinihash.com/api/docs. Get started: https://onboard.infinihash.com. diff --git a/infinihash_baas.egg-info/SOURCES.txt b/infinihash_baas.egg-info/SOURCES.txt deleted file mode 100644 index 46f1e06..0000000 --- a/infinihash_baas.egg-info/SOURCES.txt +++ /dev/null @@ -1,11 +0,0 @@ -LICENSE -README.md -pyproject.toml -infinihash_baas/__init__.py -infinihash_baas/client.py -infinihash_baas.egg-info/PKG-INFO -infinihash_baas.egg-info/SOURCES.txt -infinihash_baas.egg-info/dependency_links.txt -infinihash_baas.egg-info/requires.txt -infinihash_baas.egg-info/top_level.txt -tests/test_client.py \ No newline at end of file diff --git a/infinihash_baas.egg-info/dependency_links.txt b/infinihash_baas.egg-info/dependency_links.txt deleted file mode 100644 index 8b13789..0000000 --- a/infinihash_baas.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/infinihash_baas.egg-info/requires.txt b/infinihash_baas.egg-info/requires.txt deleted file mode 100644 index 327a7ce..0000000 --- a/infinihash_baas.egg-info/requires.txt +++ /dev/null @@ -1,4 +0,0 @@ -requests>=2.28 - -[test] -pytest>=7 diff --git a/infinihash_baas.egg-info/top_level.txt b/infinihash_baas.egg-info/top_level.txt deleted file mode 100644 index 0742e63..0000000 --- a/infinihash_baas.egg-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -infinihash_baas diff --git a/infinihash_baas/__init__.py b/infinihash_baas/__init__.py index 5591ad0..bd48aeb 100644 --- a/infinihash_baas/__init__.py +++ b/infinihash_baas/__init__.py @@ -1,5 +1,6 @@ from .client import ( # noqa: F401 Rails, RailsError, CapabilityUnavailable, verify_webhook_signature, create_sandbox_key, + parse_export_signature, PRODUCTION_URL, SANDBOX_URL, ) diff --git a/infinihash_baas/client.py b/infinihash_baas/client.py index 365ebb8..6961ebf 100644 --- a/infinihash_baas/client.py +++ b/infinihash_baas/client.py @@ -69,6 +69,21 @@ def _request(self, method, path, json=None, params=None, idempotency_key=None, a raise RailsError(r.status_code, body) return body + def _raw(self, method, path, params=None): + """Authenticated request that returns the response itself (bytes + headers).""" + if not self.api_key: + raise ValueError("api_key is required for this call") + headers = {"Accept": "*/*", "Authorization": "Bearer " + self.api_key} + r = self._s.request(method, self.base_url + path, params=params, + headers=headers, timeout=self.timeout) + if r.status_code >= 400: + try: + body = r.json() + except ValueError: + body = {"raw": r.text} + raise RailsError(r.status_code, body) + return r + # -- public, no key ---------------------------------------------------- def health(self): return self._request("GET", "/health", auth=False) @@ -111,13 +126,62 @@ def usage(self, month=None): return self._request("GET", "/api/v1/usage", params={"month": month} if month else None) def records_export(self): - """Signed (Ed25519) tenant records export; verify with signing_key().""" + """Tenant records export, parsed as JSON. + + The parsed dict cannot be verified: the Ed25519 signature covers the + exact response bytes, which this method discards. Use + records_export_signed() for evidence you intend to verify or keep. + """ return self._request("GET", "/api/v1/records/export") + def records_export_signed(self, from_=None, to=None, format=None): + """Signed tenant records export with the exact bytes the signature covers. + + Returns ``{"body": bytes, "signature": str | None, "key_id": str | None, + "sha256": str | None}``: + + * ``body`` -- the raw response body. Store and verify these bytes; + re-serialising parsed JSON breaks the signature. + * ``signature`` -- the ``X-Infinihash-Export-Signature`` header, + ``ed25519;keyid=;sig=``, or ``unsigned`` when the + deployment has no signing key. + * ``key_id`` -- the ``keyid`` from that header (match it against + ``signing_key()["keyId"]``), or None when unsigned. + * ``sha256`` -- the ``X-Infinihash-Export-SHA256`` header (hex). + + ``from_`` / ``to`` are ISO-8601 bounds on createdAt; ``format`` is + ``"json"`` (default) or ``"csv"``. See the README for verification. + """ + params = {k: v for k, v in (("from", from_), ("to", to), ("format", format)) if v is not None} + r = self._raw("GET", "/api/v1/records/export", params=params or None) + signature = r.headers.get("X-Infinihash-Export-Signature") + return { + "body": r.content, + "signature": signature, + "key_id": parse_export_signature(signature).get("keyid"), + "sha256": r.headers.get("X-Infinihash-Export-SHA256"), + } + def signing_key(self): return self._request("GET", "/api/v1/records/signing-key", auth=False) +def parse_export_signature(header): + """Split ``ed25519;keyid=;sig=`` into ``{"alg", "keyid", "sig"}``. + + Returns {} for a missing, ``unsigned`` or malformed header. + """ + if not header or header == "unsigned": + return {} + parts = header.split(";") + out = {"alg": parts[0]} + for p in parts[1:]: + if "=" in p: + k, v = p.split("=", 1) + out[k] = v + return out if out.get("alg") == "ed25519" and out.get("sig") else {} + + def verify_webhook_signature(secret, body, header, tolerance_seconds=300, now=None): """Verify `X-Infinihash-Signature: t=,v1=.")>`. diff --git a/pyproject.toml b/pyproject.toml index 7859c95..aa9a9e9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,7 +17,7 @@ test = ["pytest>=7"] [project.urls] Homepage = "https://onboard.infinihash.com" -"API reference" = "https://rails-api.infinihash.com/api/docs" +"API reference" = "https://rails-api.infinihash.com/docs/openapi.public.json" Source = "https://github.com/Infinihash/baas-python" [tool.setuptools.packages.find] diff --git a/tests/test_client.py b/tests/test_client.py index b22bc9c..c242d2c 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -81,3 +81,64 @@ def test_create_sandbox_key_posts_email_without_auth_and_refuses_production(): assert out["apiKey"] == "ihb_sbx_x" with pytest.raises(ValueError): create_sandbox_key("a@example.com", base_url=PRODUCTION_URL, session=s) + + +# -- E-18: signed records export keeps the bytes and the signature ---------- + +class RawResp: + def __init__(self, status, content, headers): + self.status_code, self.content, self.headers = status, content, headers + self.text = content.decode("utf-8", "replace") + + def json(self): + import json + return json.loads(self.content) + + +# Header shape from infinihash-baas src/lib/recordsExport.js (buildExport). +EXPORT_BODY = b'{\n "tenantId": "t1",\n "counts": {"invoices": 1}\n}\n' +EXPORT_SIG = "ed25519;keyid=0123456789abcdef;sig=" + "QUJD" * 21 + "QQ==" +EXPORT_SHA = hashlib.sha256(EXPORT_BODY).hexdigest() + + +def test_records_export_signed_returns_raw_body_signature_and_key_id(): + s = FakeSession(RawResp(200, EXPORT_BODY, { + "X-Infinihash-Export-Signature": EXPORT_SIG, + "X-Infinihash-Export-SHA256": EXPORT_SHA, + })) + out = Rails("k", session=s).records_export_signed(from_="2026-01-01T00:00:00Z", format="csv") + assert out == {"body": EXPORT_BODY, "signature": EXPORT_SIG, + "key_id": "0123456789abcdef", "sha256": EXPORT_SHA} + method, url, kw = s.calls[0] + assert (method, url) == ("GET", "https://rails-api.infinihash.com/api/v1/records/export") + assert kw["params"] == {"from": "2026-01-01T00:00:00Z", "format": "csv"} + assert kw["headers"]["Authorization"] == "Bearer k" + + +def test_records_export_signed_unsigned_deployment(): + s = FakeSession(RawResp(200, EXPORT_BODY, {"X-Infinihash-Export-Signature": "unsigned"})) + out = Rails("k", session=s).records_export_signed() + assert out["signature"] == "unsigned" and out["key_id"] is None and out["body"] == EXPORT_BODY + assert s.calls[0][2]["params"] is None + + +def test_records_export_signed_error_raises_and_needs_key(): + s = FakeSession(RawResp(401, b'{"code": "unauthorized"}', {})) + with pytest.raises(RailsError) as e: + Rails("k", session=s).records_export_signed() + assert e.value.status == 401 + with pytest.raises(ValueError): + Rails(session=FakeSession(None)).records_export_signed() + + +def test_records_export_is_unchanged_parsed_json(): + s = FakeSession(FakeResp(200, {"tenantId": "t1"})) + assert Rails("k", session=s).records_export() == {"tenantId": "t1"} + + +def test_parse_export_signature(): + from infinihash_baas import parse_export_signature + p = parse_export_signature(EXPORT_SIG) + assert p["alg"] == "ed25519" and p["keyid"] == "0123456789abcdef" and p["sig"].endswith("QQ==") + for bad in (None, "", "unsigned", "hmac;sig=x", "ed25519;keyid=a"): + assert parse_export_signature(bad) == {}