fancy-service-token (Python)
Verify Fancy service tokens in a Python sidecar. A Laravel app signs a
short-lived token on every request it makes to its sidecar
(particle-academy/fancy-service-token);
this package checks it before the request body is read and refuses every
other caller with a named reason.
- Framework-free core, plus pure-ASGI middleware for Starlette and FastAPI.
- HMAC-SHA256 with the standard library only (
hmac,compare_digest). No JWT library, no cryptography of our own, zero runtime dependencies. - Refusals carry one reason from a fixed set, never exception text, and no log line ever contains a token or a secret.
- The verified request id reaches your handlers and your logs.
The Node mirror is @particle-academy/fancy-service-token.
All three legs run the same fixture file byte for byte.
For agents. This package is not listed on the Fancy MCP catalog server yet. The server,
https://ui.particle.academy/mcp(streamable HTTP, no API key; MCP idfancy-ui), lists the released Fancy packages with install commands and docs. How an agent installs and uses this package is in AGENTS.md.
Install
pip install fancy-service-token
FastAPI
from fastapi import Depends, FastAPI
from fancy_service_token import Claims, Key, ServiceTokenMiddleware, Verifier
from fancy_service_token.depends import service_token_claims
verifier = Verifier(
keys=[Key("k2026b", bytes.fromhex(os.environ["SERVICE_TOKEN_KEY"]))],
audience="ocr-sidecar",
issuer="laravel-app",
)
app = FastAPI()
app.add_middleware(ServiceTokenMiddleware, verifier=verifier)
@app.post("/ocr")
def ocr(job: Job, claims: Claims = Depends(service_token_claims)):
log.info("ocr for %s", claims.request_id)
Verification lives in the middleware, not in a dependency, on purpose:
FastAPI reads and validates a request body before it resolves dependencies, so a
dependency cannot refuse "before the body is read". service_token_claims only
hands the verified claims to a handler. If the middleware is missing it refuses
with 401 rather than returning nothing, so a forgotten add_middleware fails
closed.
Starlette
from starlette.middleware import Middleware
app = Starlette(routes=routes, middleware=[Middleware(ServiceTokenMiddleware, verifier=verifier)])
async def handler(request):
claims = request.state.service_token # or service_token_claims(request)
Refusals
Every refusal is 401 with Cache-Control: no-store, a
WWW-Authenticate: FancyServiceToken error="<reason>" header, and this body:
{"error": "service_token_refused", "reason": "expired"}
| reason | means |
|---|---|
missing |
no token header, or an empty one |
malformed |
not a well-formed fst1 token (see the format below), longer than max_token_bytes, a lifetime above max_lifetime, no nonce while require_nonce is on, or the token header sent twice |
bad_signature |
the HMAC does not match, the key id is unknown, the key is a previous key past its grace window, or the issuer is not the configured one (no key is held for that issuer) |
expired |
now >= exp + clock_skew |
not_yet_valid |
now + clock_skew < iat |
wrong_audience |
signed correctly, for a different sidecar |
replayed |
the nonce was already accepted (or the replay store is full: it fails closed) |
A WebSocket handshake is refused with a close (1008) before accept.
Request id
The token carries the caller's request id, signed. After verification it is in
request.state.service_token.request_id, in current_request_id() for the
duration of the request, and on every log record through a filter:
handler.addFilter(RequestIdLogFilter())
logging.Formatter("%(asctime)s %(request_id)s %(message)s")
Use it to join a sidecar log line to the Laravel request that caused it.
Configuration
Every limit is a constructor argument with a secure default.
| argument | default | |
|---|---|---|
keys |
required | Key(kid, secret_bytes, accept_until=None); secrets of at least min_key_bytes |
audience |
required | this sidecar's name |
issuer |
required | the Laravel app's name |
clock_skew |
10 |
seconds of tolerance on both ends of the window |
max_lifetime |
300 |
the longest exp - iat accepted |
max_token_bytes |
1024 |
checked before any parsing |
require_nonce |
True |
refuse tokens without a nonce |
min_key_bytes |
32 |
|
replay_store |
MemoryReplayStore() |
anything with an atomic add(key, expires_at, now) -> bool; None turns replay checks off |
clock |
time.time |
ServiceTokenMiddleware(app, verifier=..., header="x-fancy-service-token", exempt_paths=()).
exempt_paths are exact matches, for a health check.
MemoryReplayStore(max_entries=100_000) is per process. A sidecar running
several workers needs a shared store, or a nonce accepted by one worker can be
replayed against another.
Key rotation
Sign with the new key in Laravel; here, hold both, and give the old one an
accept_until:
keys = [Key("k2026b", new_secret), Key("k2026a", old_secret, accept_until=1793000030)]
After accept_until (unix seconds, inclusive) a token signed with the old key is
bad_signature.
The token format (fst1)
fst1.<payload>.<signature>
-
payloadis the unpadded base64url (RFC 4648 section 5) of seven ASCII fields joined by a single LF (0x0A), in this order, with no trailing LF:# field grammar 1 kidkey id1-64 of [A-Za-z0-9._-]2 ississuer1-128 of [A-Za-z0-9._:/-]3 audaudience1-128 of [A-Za-z0-9._:/-]4 iatissued atunix seconds, decimal, 1-12 digits, no leading zero 5 expexpires atas iat; must be greater thaniat6 ridrequest id1-128 of [A-Za-z0-9._:-]7 nonceempty, or 16-128 of [A-Za-z0-9_-] -
signatureis the unpadded base64url ofHMAC-SHA256(secret, ASCII("fst1." + payload)): always 32 bytes, so always 43 characters. -
base64url must be canonical: the right alphabet, no padding, no whitespace, and the unused low bits of the last character clear. A second spelling of the same bytes is
malformed. -
The token is sent in one header,
X-Fancy-Service-Tokenby default.
The verifier checks, in this order, and stops at the first failure (the order decides the reason when a token is wrong in two ways, and the fixtures pin it):
- absent or empty:
missing - longer than
max_token_bytes:malformed - not exactly three dot-separated parts, prefix not
fst1, signature not 43 characters, either part not canonical base64url:malformed - payload not ASCII, not exactly seven fields, a field outside its grammar,
exp <= iat,exp - iat > max_lifetime, or no nonce while one is required:malformed - unknown
kid, HMAC mismatch (compared in constant time), a previous key pastaccept_until, orissnot the configured issuer:bad_signature audnot this sidecar:wrong_audiencenow + clock_skew < iat:not_yet_validnow >= exp + clock_skew:expired- nonce already recorded:
replayed. The nonce is recorded only here, so a token refused for any earlier reason never spends one.
There is no alg field and nothing to negotiate: one format, one algorithm.
Conformance
conformance/service-token-v1.json is generated by scripts/build_fixtures.py
from the format definition alone (raw hmac, not this package) and copied byte
for byte into the PHP and Node repositories. Each suite pins its SHA-256.
License
MIT
Metadata
Release files for fancy-service-token 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fancy_service_token-0.1.0.tar.gz | 24.1 kB | With provenance | Details for fancy_service_token-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fancy_service_token-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for fancy_service_token-0.1.0-py3-none-any.whl |
Total release size: 36.5 kB
Release files / fancy_service_token-0.1.0.tar.gz
| Download URL | fancy_service_token-0.1.0.tar.gz |
|---|---|
| Size | 24.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9137bb42a2f2b902e8b24cb80a18f6a65eb37c996e0834c63e5aa98346da0b82
|
|
BLAKE2b-256 checksum How to use checksums |
6fc27f02d580fb3c44ca0d2135ec6c6cab41ad5875c27e4cdf295142e9d059ce
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.
Transparency logRelease files / fancy_service_token-0.1.0-py3-none-any.whl
| Download URL | fancy_service_token-0.1.0-py3-none-any.whl |
|---|---|
| Size | 12.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
db719586d2121360133f4a0523061eb096804bb3544c78256336eabe51a59e10
|
|
BLAKE2b-256 checksum How to use checksums |
134034e46793e2aa77db3e63d7fa31878a11090c4ffbeba031c749b7d0a47d73
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.
Transparency logSecurity for fancy-service-token 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for fancy_service_token-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.