Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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__)"
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
__pycache__/
*.pyc
.pytest_cache/
build/
dist/
*.egg-info/
__pycache__/
.pytest_cache/
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<id>;sig=<base64>` 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`.
6 changes: 0 additions & 6 deletions build/lib/infinihash_baas/__init__.py

This file was deleted.

136 changes: 0 additions & 136 deletions build/lib/infinihash_baas/client.py

This file was deleted.

36 changes: 0 additions & 36 deletions infinihash_baas.egg-info/PKG-INFO

This file was deleted.

11 changes: 0 additions & 11 deletions infinihash_baas.egg-info/SOURCES.txt

This file was deleted.

1 change: 0 additions & 1 deletion infinihash_baas.egg-info/dependency_links.txt

This file was deleted.

4 changes: 0 additions & 4 deletions infinihash_baas.egg-info/requires.txt

This file was deleted.

1 change: 0 additions & 1 deletion infinihash_baas.egg-info/top_level.txt

This file was deleted.

1 change: 1 addition & 0 deletions infinihash_baas/__init__.py
Original file line number Diff line number Diff line change
@@ -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,
)

Expand Down
66 changes: 65 additions & 1 deletion infinihash_baas/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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=<id>;sig=<base64>``, 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=<id>;sig=<base64>`` 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=<unix>,v1=<hmac_sha256(secret, "<t>.<body>")>`.

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading
Loading