Metadata-Version: 2.4
Name: systemathics-helpers
Version: 2.1.1
Summary: Systemathics gRPC client helpers: authenticated channel factory and token management
Author-email: Systemathics SAS <dev@systemathics.com>
License-Expression: LicenseRef-Proprietary
Keywords: grpc,ganymede,systemathics,finance,oauth
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: authlib>=1.8.0
Requires-Dist: certifi>=2023.7.22
Requires-Dist: grpcio>=1.60.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: keyring>=25.7.0

# systemathics-helpers

Python client helpers for the Systemathics **Ganymede** and **SNTR** gRPC APIs.

One call opens an authenticated channel. Where it connects and who you are come
from the environment, so the same notebook runs unchanged in the hosted
JupyterHub, in VSCode over a VPN, in a container, and in a scheduled job.

```python
from systemathics.helpers.channel import GrpcChannel

channel = GrpcChannel.for_product("GANYMEDE")   # or "SNTR"
```

Pass that channel to any generated stub. There is no token to plumb, no provider
to construct, and no refresh loop to write.

The types those stubs exchange — prices and money as fixed-point decimals
included — come with the client package, along with their conversions.

**If you are working in the hosted JupyterHub, you need to configure nothing.**
The rest of this page explains what happens on your behalf, and what to set when
you are working anywhere else.

---

## Authenticated channels in Python

```python
from systemathics.helpers.channel import GrpcChannel

channel = GrpcChannel.for_product("GANYMEDE")   # or "SNTR"
```

That line is the whole API. Pass the channel to any generated stub. Where it
connects and who you are come from the environment, by the rules in
**`how-it-works.md`**; this page covers what is specific to
Python.

To bypass resolution entirely:

```python
GrpcChannel.to_target("grpc://localhost:5000")
GrpcChannel.to_target("grpcs://host:443", token_provider=provider)
```

No environment named, and no credentials file carrying the product's target,
raises `MissingEnvironmentError`; a product with no endpoint raises
`ProductNotDeployedError`; no credential configured raises `NoCredentialsError`.

To see where a product would connect without building a channel:

```python
from systemathics.helpers.channel import resolve_endpoint

endpoint = resolve_endpoint("GANYMEDE")
endpoint.target         # the route, with .source saying which rung supplied it
endpoint.extra_roots    # PEM from the credentials file, or None
```

---

### How the bearer is attached

The channel you get back is a `bearer.AuthenticatedChannel`. On every call it asks
the credential provider for a token, adds the `authorization` header, then hands the
call to gRPC — for all four RPC kinds and every way of invoking them (`__call__`,
`with_call`, `future`).

A credential failure is raised by the stub call itself:

```python
stream = stub.HpTickBars(request)   # raises TokenExpiredError here
```

An expired token raises `TokenExpiredError`, a missing or empty token file
`TokenUnavailableError`, a rejected grant the provider's own error.

Why not a gRPC client interceptor: `grpc.intercept_channel` catches whatever an
interceptor raises and returns a failed-call object in place of the call. For a
streaming RPC that object is what the caller receives as the stream: its
`initial_metadata()` is `None`, and the real error appears only on iteration, so
code that reads the headers first fails with a `TypeError` naming neither the
token nor the reason. Wrapping the channel keeps the provider's error on the
caller's own stack.

Why not `CallCredentials`: gRPC refuses `CallCredentials`
on a plaintext transport, and `grpc.local_channel_credentials()` — the usual
workaround — is `LOCAL_TCP`, which gRPC core accepts only for loopback and Unix
socket peers. It cannot carry a credential to an in-cluster address at all.

#### Providers

Every mode is a provider exposing the same `get_token_sync` / `get_token` pair, so
they are interchangeable — pass any of them to `to_target`:

| Provider | Mode |
|---|---|
| `TokenFileProvider` | `token-file` |
| `M2mTokenProvider` | `m2m` |
| `DeviceCodeTokenProvider` | `device` |
| `PkceTokenProvider` | `pkce` |
| `RefreshTokenProvider` | `refresh` |
| `StaticTokenProvider` | `token` |

---

### TLS trust

gRPC-Python uses its own bundled roots and does not read the OS trust store, so
`SSL_CERT_FILE` has no effect. An endpoint with a publicly trusted certificate
needs nothing configured.

For an endpoint behind a private CA, the credentials file's `ca_certificates` are
trusted in addition to the public roots. gRPC accepts a single root bundle and does
not expose its built-in one, so the public half of that bundle is `certifi`'s copy
of the Mozilla roots.

To take full control instead, pass credentials explicitly; they replace both:

```python
import grpc

creds = grpc.ssl_channel_credentials(root_certificates=open("ca.pem", "rb").read())
channel = GrpcChannel.for_product("GANYMEDE", ssl_credentials=creds)
```

---

### Diagnostics

```bash
systemathics-doctor      # one-shot: runtime, endpoint, credential, expiry, roles
```

Never raises, and exits non-zero on failure, so it is safe to tell a stuck user
*"run this and send me the output"*.

```python
import os
os.environ["SYSTEMATHICS_LOG_LEVEL"] = "debug"   # the decision trail
```

Set it before the channel is built; the ladder resolves once.

```python
from systemathics.helpers.channel import current_token, explain_token

print(explain_token(channel))   # fingerprint, remaining lifetime, claims
print(current_token(channel))   # the raw JWT
```

Both go through the channel's **own** provider, so they show what the next RPC
will really send. Rebuilding a provider from the same configuration would answer
plausibly and wrongly: it is a separate instance with its own cache.

#### A runtime warning worth heeding

The startup fingerprint reports the protobuf implementation. `implementation=upb`
(or `cpp`) is the native parser. `implementation=python` is the pure-Python
fallback — typically a musl image with no matching wheel — and it is *orders of
magnitude* slower on the message volumes these APIs return, so the helpers warn
about it. If RPCs are inexplicably slow, look for it first.

---

## How the helpers work

The helpers do one narrow job: **give you a channel to a Systemathics API that is
already authenticated as you, wherever you happen to be running.** Everything is
configured through the environment, and the rules on this page are the same in
every language the helpers exist in — one environment serves all of them.

---

### Three independent questions

The helpers answer these separately, and never let one variable settle two of
them.

| Question | Configured with |
|---|---|
| **Where** is the service? | `<PRODUCT>_GRPC_TARGET`, or the credentials file; `SYSTEMATHICS_ENV` |
| **How** do I reach it — TLS or plaintext? | *carried in the target's scheme* |
| **Who** am I? | `SYSTEMATHICS_AUTH` and the credential variables |

One flag deciding two of these at once is how you end up with an authenticated
plaintext channel that cannot exist, or a TLS endpoint reached over h2c. So
transport is never inferred — it is spelled out.

---

### Where: endpoint resolution

Two rungs, first match wins.

| Rung | Effect |
|---|---|
| `<PRODUCT>_GRPC_TARGET` | an exact endpoint — `GANYMEDE_GRPC_TARGET`, `SNTR_GRPC_TARGET` |
| `grpc_targets` in the **credentials file** | the endpoints of the environment the credential belongs to |

The credentials file is the one named by `SYSTEMATHICS_M2M_CREDENTIALS`. It is read
for its endpoints whichever credential ends up selected, because it describes an
environment as well as a client. The variable wins over the file, so a local or
in-cluster route can always be forced.

Endpoints are **deployment data, not library data**. In a hosted environment they
are provided for you; on a workstation they come from your own `.env`. The helpers
ship no registry of environments to hold them.

`SYSTEMATHICS_ENV` names the environment and, through it, the realm and issuer used
for authentication. It never names an endpoint. It is required unless the
credentials file carries the product's target; a file that does normally carries
its token endpoint too, so no issuer is needed and the file alone is the whole
configuration. The issuer is derived
as `https://sso.systemathics.com/realms/{SYSTEMATHICS_ENV}`; set
`SYSTEMATHICS_ISSUER` to override that for a realm outside the standard base, or a
local identity server.

A product with no endpoint from either rung is an error naming
`{PRODUCT}_GRPC_TARGET`.
It means *no endpoint is configured* — not "not deployed". Without a registry the
helpers cannot tell the difference, and do not pretend to.

#### The scheme carries the transport

| Scheme | Transport |
|---|---|
| `grpc://` `h2c://` | plaintext HTTP/2 — what in-cluster services speak |
| `grpc+tls://` `grpcs://` `https://` | TLS |
| `unix://` | Unix domain socket |

`https://` is accepted as a synonym so a value copied from a browser or a config
file works. A target with no scheme is rejected: its transport would be a guess.

```bash
GANYMEDE_GRPC_TARGET=grpc://ganymede-grpc-read-service.default.svc.cluster.local:5000
GANYMEDE_GRPC_TARGET=grpc+tls://ganymede.dev.example.com:443
GANYMEDE_GRPC_TARGET=grpc://192.168.1.42:5000
```

A target from the credentials file obeys the same grammar.

#### Extra trust roots

An endpoint whose certificate is issued by a private certificate authority needs
that CA trusted. The credentials file carries it as `ca_certificates`, and the
helpers trust it **in addition to** the public roots, never instead of them:

- only for a **TLS target** — a plaintext target has no certificate to verify;
- only for the **gRPC endpoint** — the token request goes to the identity service,
  whose certificate is publicly trusted, and keeps the public roots alone;
- whichever rung supplied the target, so a target forced with
  `<PRODUCT>_GRPC_TARGET` still benefits;
- never to excuse anything but an unknown issuer: a certificate whose name does
  not match the target is rejected, whoever signed it.

Adding rather than replacing means an endpoint that moves to a publicly trusted
certificate keeps working with the same file. TLS configuration you pass
explicitly takes precedence over the file — see each language's page.

---

### Who: the credential, and how it reaches the wire

#### The bearer is attached per call, before the call starts

On **every** call the channel asks its credential for a token and adds an
`authorization: Bearer ...` header. Every kind of call is covered — unary and all
three streaming kinds — because covering only unary calls is a silent bug in which
they authenticate and streams return 401. The header is ordinary metadata, so
plaintext (h2c) and TLS channels take one identical path.

Three consequences worth knowing:

- **A credential that cannot be obtained fails the call, with its own error.**
  An expired token, a missing or empty token file, a rejected grant — each raises
  its own error from the line that made the call, before anything is sent. Nothing
  is converted into a gRPC status or deferred to the first read of a stream.

  What can be checked locally is caught this way. A token that looks valid but
  that the server refuses — revoked, or missing a role — still reaches the server,
  and comes back as an ordinary `UNAUTHENTICATED` or `PERMISSION_DENIED`.

- **A channel built once keeps working.** No token is resolved at construction, so
  a channel created at startup is still valid days later; the credential renews
  underneath it.
- **A per-call header wins.** If you pass your own `authorization` metadata on a
  single call, the channel leaves it alone and does not consult its credential at
  all — that is how you reproduce one call as somebody else without touching the
  channel, and it works even when the channel's own credential is dead.

#### Where tokens come from

| Mode | Grant | Renewal |
|---|---|---|
| **`token-file`** | none — reads a file | re-reads every call, no cache |
| **`m2m`** | `client_credentials`, optionally `private_key_jwt` | re-requests near expiry |
| **`device`** | device authorization (RFC 8628) | `refresh_token`, persisted |
| **`pkce`** | authorization code + PKCE (RFC 7636) | `refresh_token`, persisted |
| **`refresh`** | `refresh_token` (RFC 6749 §6) | rotation persisted |
| **`token`** | none — a pasted string | never; fails with the expiry named |

#### How a mode is selected

The helpers **select** one mode from what you configured. They do not try modes in
turn until one works.

Three rules explain every decision in that diagram.

**Selection, not fallback.** A rotated M2M secret fails as *a rotated M2M
secret*. It does not fall through to an interactive grant, print a sign-in URL
into a log nobody reads, and hang until a job's deadline — with the symptom, a
timeout, a long way from the cause. It also keeps identity honest: falling through
would mean believing you run as `user-x-m2m` while actually running as a signed-in
human, which defeats the attribution M2M exists to provide.

**Nothing interactive is selected automatically.** **`device`** and
**`pkce`** must be named, so an unattended process cannot be surprised
into waiting for a human.

**Explicit configuration beats anything ambient.** A credential file you created
states what you want; a variable a spawner injected states only where you happen
to be running. So **`m2m`** sits above
**`token-file`**: in the hub both are present, and silently
ignoring the one you chose would be a bug.

There are exactly two sanctioned exceptions to strict selection. A **rejected
refresh token** may fall to an interactive sign-in, but only where the context is
interactive — never *into* a prompt from a process that cannot answer one. And
**failed discovery** may fall back to `SSO_TOKEN_URL`.

When nothing is configured you get an error, not a guess. It names the supported
path first, with the other modes subordinate. In the hosted hub the message is
different: the spawner is supposed to mount a credential, so reaching that point
means the mount is missing and the fix is on that side — it says so, rather than
sending a hub user to the portal for something they do not need.

#### Renewal, and why you can watch it

A token is cached until shortly before its `exp`, with a leeway so a call cannot
begin with a token that dies mid-flight. Renewal is reported at `info` as a single
event, because the transition is the thing you need and a per-call line buries it:

```
INFO   bearer acquired  sha256:f7f15aeb  expires_in=900s  azp=...
DEBUG  /.../GetEquity: attached bearer sha256:f7f15aeb
INFO   bearer renewed (was sha256:f7f15aeb)  sha256:2c9d0e41  expires_in=900s
```

A fingerprint that **stops moving while `expires_in` goes negative** is a renewal
bug, visible before any call fails.

Where rotation is in play a refresh token is single-use, and presenting a consumed
one can revoke the whole session. So the successor returned by each refresh is
persisted to `~/.systemathics/refresh-state.json` with a write-then-replace, and a
crash mid-write cannot leave a truncated credential behind. The file is shared by
every language the helpers exist in, so a sign-in made in one is reused by the
others.

#### Endpoint discovery

Endpoints are read once per issuer from
`{issuer}/.well-known/openid-configuration` and cached for the process. The
document supplies the token endpoint, and the device authorization endpoint when
the realm has that grant enabled — so a realm without device flow produces a clear
message rather than a 404 mid-sign-in.

If discovery fails, `SSO_TOKEN_URL` overrides it. That is the only fallback; a
discovery failure is otherwise reported with the issuer and the reason, because
*"discovery failed"* on its own leaves the reader nowhere.

---

### What the helpers deliberately do not do

**They never validate a token.** No JWKS fetch, no signature check, no audience
enforcement. Claims are decoded *without verifying*, and only for local expiry
checks and for logging.

That is not an omission. The gRPC service verifies the signature against the
realm's JWKS, checks `azp` against its authorized-parties list, and enforces roles.
A client that also verified would be duplicating the security boundary on the wrong
side of it, where the answer cannot be trusted anyway. If a token is bad, the
correct outcome is the server rejecting it.

The one place the helpers touch JOSE is the opposite direction: **`m2m`**
**signs** its own client assertion with your private key for `private_key_jwt`.

**They do not open a browser unless you ask.** No mode requiring human
interaction is ever selected automatically.

#### Log output is safe to share

Tokens appear as fingerprints, role claims are reduced to counts, and
`preferred_username` and `email` are omitted — `azp` and `sub` already identify a
caller for diagnostic purposes.

Raw tokens require `SYSTEMATHICS_LOG_TOKENS=1`, deliberately **not** folded into
`debug`. A JWT is a live bearer credential for the rest of its lifetime, so
emitting one should be a decision rather than a side effect of raising the log
level to investigate something else.

---

### Environment variables

#### Where and how

| Variable | Purpose |
|---|---|
| `<PRODUCT>_GRPC_TARGET` | exact endpoint, scheme included |
| `SYSTEMATHICS_ENV` | environment name → realm and issuer |
| `SYSTEMATHICS_ISSUER` | override the derived issuer outright |
| `SSO_TOKEN_URL` | token endpoint, only if discovery fails |

The credentials file contributes here too: `grpc_targets` as the second endpoint
rung, `ca_certificates` as **extra trust roots**.

#### Who

| Variable | Purpose |
|---|---|
| `SYSTEMATHICS_AUTH` | force a mode: `auto` `none` `token` `device` `pkce` `refresh` `m2m` |
| `SYSTEMATHICS_M2M_CREDENTIALS` | credential file → selects **`m2m`** |
| `SYSTEMATHICS_TOKEN_FILE` | token file → selects **`token-file`** |
| `SYSTEMATHICS_TOKEN` | a pasted JWT, with **`SYSTEMATHICS_AUTH=token`** |
| `SSO_REFRESH_TOKEN` | a refresh token, with **`SYSTEMATHICS_AUTH=refresh`** |
| `SSO_CLIENT_ID` `SSO_CLIENT_SECRET` `SSO_CLIENT_KEY` | M2M parts supplied directly |
| `SYSTEMATHICS_INTERACTIVE` | `1` permits, `0` forbids, a prompt when no TTY is detectable |
| `SSO_IDP_HINT` | pre-select an identity provider (**`pkce`** only) |

#### Diagnosing

| Variable | Purpose |
|---|---|
| `SYSTEMATHICS_LOG_LEVEL` | `debug` \| `info` \| `warning` |
| `SYSTEMATHICS_LOG_TOKENS` | `1` puts raw bearer tokens in the log |

---

### When something is wrong

| Symptom | Likely cause |
|---|---|
| `UNAUTHENTICATED — 401` on every call | the token is not accepted — explain the channel's token and check its `azp` |
| `unauthorized_client` while refreshing | the token belongs to a confidential client and cannot be refreshed here |
| an error listing what to set | nothing was configured; it names the supported path first |
| an error naming `SYSTEMATHICS_ENV` and `SYSTEMATHICS_ISSUER` | M2M credentials without a token endpoint, and no issuer to discover one from |
| an error naming `SYSTEMATHICS_ENV` and `SYSTEMATHICS_M2M_CREDENTIALS` | no environment named, and no credentials file carrying the product's target |
| a certificate verification failure on the gRPC endpoint | it uses a private CA that the credentials file does not carry in `ca_certificates` |
| a sign-in prompt you did not ask for | cannot happen — interactive modes are never auto-selected |

---

## `token-file` — the hosted JupyterHub

Read the bearer from a file that something outside this process keeps current.

This is what you get in the hosted hub, without configuring anything.

| | |
|---|---|
| **Activated by** | `SYSTEMATHICS_TOKEN_FILE` — set by the spawner |
| **Also needs** | nothing |
| **Interactive?** | no |
| **Renews?** | nothing to renew — the file *is* the credential |
| **Provider** | `token.TokenFileProvider` |

```bash
SYSTEMATHICS_TOKEN_FILE=/var/run/systemathics/token   # the hub sets this
```

---

### How it works

The hub writes your access token into a Kubernetes Secret. The kubelet mounts that
Secret as a file in your pod. The helpers read the file on **every RPC**.

Re-authenticating in the browser is what replaces the credential. The next RPC
picks it up with **no server restart and no kernel restart**.

### Why a file, and not a variable

An environment variable is fixed when the process starts. It can be correct at
spawn and nothing more — when you re-authenticate, the UI session resets and the
variable cannot, so you are left with a working notebook whose every RPC returns
401 and nothing connecting the two symptoms.

Re-injection is not an available fix either: nothing can change a running
process's environment from outside. A file can be rewritten; a variable cannot.

The hub's own **refresh** token is not an option either. It belongs to a
confidential client and cannot be redeemed without that client's secret, which
must never reach a pod you have a shell in.

### Why there is no cache

The provider re-reads the file on every call and caches nothing. Caching would
mean inventing invalidation — watching mtimes, or the reload-signal machinery
(SIGHUP handlers, cert-reloader sidecars) that exists across the Kubernetes
ecosystem purely because consumers cache what the kubelet already keeps current.

The cost of not caching is nothing that matters: the mount is tmpfs, the file is a
couple of kilobytes, so a read is microseconds against a millisecond-scale RPC —
and it happens once per call, not once per streamed message.

No lock is needed either, which follows from the same choice: with no cache there
is no shared mutable state to protect. Concurrent reads are safe because the
kubelet swaps Secret volumes atomically — it writes a new timestamped directory
and then moves the `..data` symlink, so a reader sees the old token or the new one,
never a half-written file.

---

### When it stops working

Three distinguishable states, because the remedies read alike and the diagnoses do
not.

| Message | Means | Do |
|---|---|---|
| *no credential at … Nothing has written one yet* | the Secret does not exist | stop and start your server from the hub control panel |
| *the credential at … is empty, which means the session that issued it has ended* | the writer cleared it | reload the JupyterHub page and sign in |
| *token expired `<when>` (azp=…)* | stale credential | same — and the moment is named, so clock skew is separable |

Without the empty case, a dead session would present a stale token and collect a
bare `UNAUTHENTICATED — 401` from the server instead of an instruction.

### Overriding it

`token-file` is ambient — it reflects where you are running. If you want a
different identity in the hub, configure one and it wins:

```python
import os
os.environ["SYSTEMATHICS_M2M_CREDENTIALS"] = "/home/jovyan/m2m.json"
```

**`m2m`** sits above `token-file` in the ladder precisely so this works
without having to unset anything.

---

## `m2m` — machine-to-machine

**The supported path everywhere outside the hosted hub.** A credential belonging
to you, usable with no browser and no human present, renewed for as long as the
client is active.

| | |
|---|---|
| **Activated by** | `SYSTEMATHICS_M2M_CREDENTIALS` — or `SSO_CLIENT_ID` + a key/secret |
| **Also needs** | nothing, when the file carries its endpoints; otherwise `SYSTEMATHICS_ENV` and a target |
| **Interactive?** | no — nothing to click, ever |
| **Renews?** | yes, by re-requesting; no refresh token involved |
| **Provider** | `m2m.M2mTokenProvider` |

```bash
SYSTEMATHICS_M2M_CREDENTIALS=./m2m-credentials.json
```

When the file carries its token endpoint and the product's target — see
**what the file can also carry** — that one variable
is the whole configuration. Otherwise add the environment and the endpoint:

```bash
SYSTEMATHICS_ENV=<environment>
GANYMEDE_GRPC_TARGET=grpc+tls://<host>:443
SYSTEMATHICS_M2M_CREDENTIALS=./m2m-credentials.json
```

`SYSTEMATHICS_ENV` names your environment. The value is part of the configuration
you were given, and matches the realm that issues your tokens.

---

### Getting a credential

In the dashboard portal: **M2M clients → Create → Download for SDK**. Point the
variable at the file it saves. That is the whole setup.

The portal's plain **Download .pem** works too — the client id is read from the
filename, so do not rename that file.

### How it works

The first exchange — discovering the token endpoint — is skipped when the
credentials file carries `token_endpoint`, which leaves one fewer network
dependency on the way to the first call.

**Renewal is a re-request, not a refresh.** The token is cached until shortly
before `exp`, then a new one is obtained the same way as the first. No refresh
token exists, so there is nothing to rotate, nothing to persist, and nothing to go
stale between runs.

That is why this is the right mode for a CronJob, a CI job, or anything that runs
unattended for an arbitrary length of time. It has no session to outlive.

---

### The two credential shapes

The helpers detect which they were given.

#### `private_key_jwt` (RFC 7523) — what the portal issues

You hold a private key; the authorization server holds the public half. Each token
request carries a short-lived JWT assertion signed with your key, whose `aud` is
the token endpoint.

**The private key never leaves your machine and never crosses the network.** That
is the reason to prefer this over a shared secret: there is no long-lived secret in
flight to intercept, and a compromised server-side record cannot be replayed
against you.

#### `client_secret_post`

A shared `client_id` and `client_secret`, posted to the token endpoint. For a
client provisioned somewhere other than the portal.

### Accepted file formats

The loader takes the portal's output as-is, without transcription:

- the **`Download for SDK` JSON** — `client_id`, `private_key`, `kid`,
  `algorithm`, `token_endpoint`
- the portal's **`CreatedClientResponse`** verbatim, including its nested `client`
  object
- a bare **`<clientId>.pem`** — the client id comes from the filename
- flat JSON in either **camelCase or snake_case**

Detection is anchored: a file is treated as PEM only if its content *starts* with
a PEM marker, so JSON that happens to contain an inline `privateKeyPem` is still
parsed as JSON.

#### What the file can also carry

Besides the client, a JSON credential can describe the environment it belongs to,
so nothing else needs configuring:

| Key | camelCase | Holds |
|---|---|---|
| `grpc_targets` | `grpcTargets` | product name → target, in the **target grammar** |
| `ca_certificates` | `caCertificates` | PEM certificates to trust for the gRPC endpoints, in addition to the public roots |

```json
{
  "client_id": "user-alice-research-m2m",
  "private_key": "-----BEGIN PRIVATE KEY-----\n...",
  "token_endpoint": "https://sso.example.com/realms/<environment>/protocol/openid-connect/token",
  "grpc_targets": { "GANYMEDE": "grpc+tls://ganymede.example.com:443" },
  "ca_certificates": "-----BEGIN CERTIFICATE-----\n..."
}
```

- Product names are case-insensitive.
- `<PRODUCT>_GRPC_TARGET` still wins over `grpc_targets`.
- `ca_certificates` applies to TLS gRPC targets only, never to the token request;
  **extra trust roots** has the rules.
- Both keys are optional, and a malformed value is an error naming the key rather
  than something silently ignored.

A bare `.pem` cannot carry either, so it always needs `SYSTEMATHICS_ENV` and a target.

### Supplying the parts directly

Where a file is awkward — a CI secret store, for instance:

```bash
SSO_CLIENT_ID=user-alice-research-m2m
SSO_CLIENT_KEY=/run/secrets/alice.pem      # private_key_jwt
# or
SSO_CLIENT_SECRET=...                       # client_secret_post
```

---

### Identity and attribution

The token's `azp` is your client id, typically `user-<name>-<purpose>-m2m`. The
APIs admit that shape by pattern, and the portal records an owner against the
client — so a request is attributable to a person even though no person was
present when it ran.

Keep that in mind when choosing between this and an interactive mode: `m2m` says
*"this automation, owned by Alice"*. A signed-in session says *"Alice, right
now"*. They are not interchangeable in an audit trail.

### Operational note

A client outlives the person who created it. If someone leaves, their M2M clients
keep working until disabled — that is a deprovisioning task, not something the
credential expires its way out of.

### When it fails

| Symptom | Cause |
|---|---|
| `invalid_client` | the client id is wrong, or the key does not match the registered public key |
| `unauthorized_client` | the client exists but the `client_credentials` grant is not enabled on it |
| a message naming the credential file | the file is unreadable, or in none of the accepted shapes |
| a message naming `grpc_targets` or `ca_certificates` | that key is present but malformed: not an object of strings, or not PEM certificates |
| `UNAUTHENTICATED — 401` from the API | the token is fine but `azp` is not admitted, or roles are missing |

The last one is the one to watch: authentication succeeded and *authorisation*
failed. `explain_token(channel)` in Python, or `channel.ExplainToken()` in .NET,
shows the `azp` and the role counts actually present.
