Metadata-Version: 2.5
Name: firetail_finchly
Version: 0.0.1
Summary: Python SDK for the Finchly platform
Project-URL: Repository, https://github.com/firetail-io/finchly-sdk-py
Project-URL: Changelog, https://github.com/firetail-io/finchly-sdk-py/blob/main/CHANGELOG.md
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: pyjwt[crypto]<3,>=2.8
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# firetail_finchly

Python SDK for the [Finchly](https://github.com/firetail-io/finchly)
platform. A service or app uses it to register with a Finchly deployment,
verify who is calling it, and reach the platform's database, object store,
queue and other services.

Status: early. The package is tested, but only the first four modules
exist.

The SDK implements the platform API, which is specified in
`firetail-io/finchly` under `spec/`. This release speaks platform API `v1`
(draft).

## Install

```
pip install firetail_finchly
```

Requires Python 3.10 or later. Depends on PyJWT with its `crypto` extra.

## Use

```python
from firetail_finchly import load_config, load_manifest

config = load_config()                         # reads PLATFORM_* settings
manifest = load_manifest(config.manifest_path)
```

Both raise a `FinchlyError` with a stable `code` and a `problems` tuple that
names everything wrong, so a misconfigured container fails once with the
full picture.

### Who is calling

The gateway puts a short-lived signed token in the `x-platform-identity`
header of every request it proxies. It is the only identity a service
should accept.

```python
from firetail_finchly import IdentityError, IdentityVerifier

# Once, at startup. It caches the gateway's issuer and signing keys, and
# is safe to share between threads.
identity = IdentityVerifier(slug=manifest["slug"], gateway_url=config.gateway_url)

# Per request.
try:
    caller = identity.from_headers(request.headers)
    caller.subject   # user id, or "service:<slug>"
    caller.email     # None for a service calling as itself
    caller.groups    # platform groups
    caller.roles     # roles for this service: "user", "operator"
    caller.actor     # "service:<slug>" when a service acts for the user
except IdentityError as err:
    ...  # Unauthenticated: respond 401. err.reason is for logs only.
```

Any other `FinchlyError` from the verifier means the gateway could not be
reached; respond 503.

A token is rejected unless it is signed with ES256 by a key the gateway
publishes, names that gateway as issuer and this service as its only
audience, and has not expired. The rules are in `spec/identity-token.md` in
`firetail-io/finchly`.

No other header is ever consulted. On a path the manifest declares in
`publicPaths` there is no token, and the service authenticates the request
itself.

### Calling another service

Services never address each other directly. A call goes through the
gateway, signed by this instance's own key.

```python
from firetail_finchly import ServiceClient

# Once, at startup. Safe to share between threads.
service = ServiceClient(
    slug=manifest["slug"],
    gateway_url=config.gateway_url,
    credential=config.service_credential,
)
service.start()   # optional: fail now, not on the first call

# As the service itself.
response = service.call(
    "notification-service",
    "/api/send",
    method="POST",
    headers={"Content-Type": "application/json"},
    body=b'{"text": "hello"}',
)
response.status, response.headers, response.body, response.json()

# For a user: the target sees that user, and this service acting for them.
service.call("notification-service", "/api/inbox", as_user=caller.subject)
```

`call` returns the response, whatever its status.

- **403** means this service's manifest does not list the target in
  `calls`, or the user has no access to the target.
- **A redirect is handed back, not followed.**
- **Nothing is retried.** After a 401 the next call registers the key
  again, in case the gateway no longer knows it.

To use another HTTP client, such as `requests` or `httpx`, take the address
and the header from the client and send the request yourself. A token is
for one target and is valid for a minute, so get fresh headers each time:

```python
requests.post(
    service.url("notification-service", "/api/send"),
    headers=service.headers("notification-service"),
    json={"text": "hello"},
    allow_redirects=False,
)
```

The instance makes an ES256 key pair in memory the first time it is needed.
The private half never leaves the process. The public half is registered
with the gateway using the credential the service was deployed with, and
extended by itself for as long as the instance runs. The rules are in
`spec/service-token.md` and `spec/registration.md` in `firetail-io/finchly`.

Only a built-in service has a credential. An app's key is accepted when it
registers, which the `app` module will do; until then an app cannot use
`service`.

### Settings

| Variable | Required | Meaning |
|---|---|---|
| `PLATFORM_GATEWAY_URL` | yes | The gateway's internal address |
| `PLATFORM_MANIFEST_PATH` | no | Manifest path in the container. Default `/finchly/manifest.json` |
| `PLATFORM_APP_ADDRESS` | no | Address the gateway should use to reach this service |
| `PLATFORM_ENROLMENT_TOKEN` | no | Token for self-registration |
| `PLATFORM_SERVICE_CREDENTIAL` | no | What a built-in service registers its instance key with |

The enrolment token and the service credential are left out of the
config's `repr`, so logging the config does not leak them.

## Modules

The Python SDK may trail the Node SDK for modules that only Node services
use.

| Module | What it does | State |
|---|---|---|
| `config` | Read and validate the platform settings | Done |
| `manifest` | Load the manifest and check what the SDK depends on | Done |
| `identity` | Verify `x-platform-identity` | Done. Directory lookups (`list_users`, `members_of`) and `require_*` helpers are planned |
| `app` | Register with the platform, serve `/_platform/*`, renew keys, fetch settings | Next |
| `service` | Call other services through the gateway, as the service or for a user | Done for built-in services. An app's first key waits on `app` |
| `db` | PostgreSQL: queries, transactions, advisory locks, migrations | Planned |
| `blobs` | Object storage with conditional writes | Planned |
| `queue` | Publish, lease, ack, nack | Planned |
| `secrets` | Secrets and envelope encryption | Planned |
| `llm` | Model calls through the platform | Planned |
| `audit`, `usage`, `notify`, `schedule`, `connectors` | Clients for platform services | Planned |
| `ui` | Shared header, footer and theme | Not planned; Node only |

The manifest check here is not the full schema. The platform runs the full
check at registration and is the authority.

## Develop

```
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
python -m pytest
```

Without a local Python environment, run them in a container:

```
docker run --rm -v "$PWD":/src:ro python:3.12-slim sh -c \
  "cp -r /src /w && cd /w && pip install -q -e '.[dev]' && python -m pytest -q"
```

### Conformance vectors

`tests/conformance/` holds test vectors copied from `firetail-io/finchly`
(`conformance/vectors/`). Both SDKs must reach the verdict each vector
states. Do not edit them here: change them in `finchly`, regenerate, and
copy the file to both SDK repositories. Until `finchly` publishes its
conformance suite as an image, the copy is made by hand.

## Release

Each package version follows semver, independent of the Node SDK and of the
platform.

1. Changes land on `main` by pull request. Each one adds a line to
   `CHANGELOG.md` under "Unreleased".
2. To release, set the version in `src/firetail_finchly/_version.py`, move
   the changelog entries under that version, merge, and tag the merge
   commit `v` plus the version, for example `v1.2.0`.
3. The `release` workflow checks the tag matches the version, runs the
   tests, builds the sdist and wheel, and publishes.
4. A release candidate uses the PEP 440 form, `1.2.0rc1`, tagged
   `v1.2.0rc1`. pip does not install pre-releases unless asked.
5. A bad release is yanked on PyPI and followed by a patch release.

Publishing uses PyPI trusted publishing: the workflow proves its identity to
PyPI with its GitHub Actions token, so no PyPI token is stored in this
repository.

One-time setup, not yet done:

- On PyPI, add a pending trusted publisher for the project
  `firetail_finchly`: owner `firetail-io`, repository `finchly-sdk-py`,
  workflow `release.yml`, environment `pypi`.
- Create a GitHub environment called `pypi` in this repository, restricted
  to tags.

Still to add: the conformance suite from `firetail-io/finchly`, run in CI on
every change, once that suite exists.
