sovereign-sdk-fastapi 1.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,427 @@
1
+ Metadata-Version: 2.4
2
+ Name: sovereign-sdk-fastapi
3
+ Version: 1.3.0
4
+ Summary: FastAPI/Starlette ASGI middleware for the Sovereign Systems SDK
5
+ Author-email: kenwalger <kenalger@comcast.net>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/kenwalger/sovereign-sdk
8
+ Project-URL: Repository, https://github.com/kenwalger/sovereign-sdk
9
+ Project-URL: Changelog, https://github.com/kenwalger/sovereign-sdk/blob/main/CHANGELOG.md
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Topic :: Security
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Requires-Python: >=3.12
16
+ Description-Content-Type: text/markdown
17
+ Requires-Dist: sovereign-sdk-core<2.0.0,>=1.3.0
18
+ Requires-Dist: starlette<1.0.0,>=0.35.0
19
+
20
+ # Sovereign Systems SDK
21
+
22
+ **High-Integrity Cryptographic Provenance and Inbound Protection Boundaries for Agentic Workflows.**
23
+
24
+ Sovereign Systems is a local-first AI WAF and compliance gate. It intercepts every inbound payload before it reaches a model or agentic loop, strips high-entropy boilerplate, and seals the result with an Ed25519-signed `ForensicReceipt` that gives enterprise auditors mathematical proof of un-tampered boundary transformation — all running on local silicon with no external service dependency.
25
+
26
+ Every boundary crossing produces a non-repudiable chain of custody: the receipt binds the sieved payload hash and the full transformation accounting inside a single cryptographic envelope. No post-hoc mutation of the output or its metrics can go undetected.
27
+
28
+ To learn more about the philosophy and reasoning behind this project, see [PHILOSOPHY.md](PHILOSOPHY.md).
29
+
30
+ ---
31
+
32
+ ## Why an AI WAF?
33
+
34
+ Modern agentic pipelines ingest user intent through prompt text. That text is routinely bloated with conversational filler — greetings, hedging adverbs, redundant preambles — that inflates token budgets and introduces non-deterministic reasoning noise without contributing semantic content. At the same time, enterprises operating LLM workloads need the same compliance guarantees they expect from a network WAF: proof that payloads were inspected, proof that the inspection was faithful, and an append-only audit log that is tamper-evident after the fact.
35
+
36
+ Sovereign Systems provides both:
37
+
38
+ - **Inbound boundary enforcement** — every payload is sieved before a model or tool sees it.
39
+ - **Cryptographic chain of custody** — every sieved payload is sealed with a node-local Ed25519 private key into a `ForensicReceipt` that persists forever.
40
+ - **Non-repudiation** — the receipt covers the output hash and the transformation accounting under the same signature, so neither the result nor the metrics can be altered without breaking verification.
41
+ - **Local-only execution** — no telemetry leaves the host; key material never leaves the node.
42
+
43
+ ---
44
+
45
+ ## Workspace Topography
46
+
47
+ This repository is managed as an integrated `uv` workspace separating the cryptographic data tier from the execution runtime:
48
+
49
+ ```text
50
+ .
51
+ ├── .github/
52
+ │ └── workflows/
53
+ │ ├── publish.yml # PyPI release pipeline
54
+ │ └── test.yml # CI test matrix
55
+
56
+ ├── examples/
57
+ │ └── fastapi_gateway/
58
+ │ ├── app.py # Example FastAPI server with SovereignMiddleware
59
+ │ └── client.py # Example HTTP client
60
+
61
+ ├── packages/
62
+ │ ├── sovereign-core/ # Pure data tier (zero high-compute dependencies)
63
+ │ │ ├── src/sovereign_core/
64
+ │ │ │ ├── cli.py # CLI entry points (sovereign-verify)
65
+ │ │ │ ├── crypto.py # Ed25519 key management & ForensicReceipt minting
66
+ │ │ │ ├── gateway.py # Prose Tax sieve & SovereignGateway high-level API
67
+ │ │ │ └── py.typed
68
+ │ │ └── tests/
69
+ │ │ ├── test_crypto.py
70
+ │ │ └── test_gateway.py
71
+ │ │
72
+ │ ├── sovereign-runtime/ # Compute/Execution tier (tool & model isolation)
73
+ │ │ └── src/sovereign_runtime/
74
+ │ │ ├── router.py # Intent-based pre-flight namespace exposure
75
+ │ │ ├── __main__.py # sovereign-node entry point
76
+ │ │ └── py.typed
77
+ │ │
78
+ │ └── sovereign-fastapi/ # FastAPI/Starlette ASGI middleware adapter
79
+ │ ├── src/sovereign_fastapi/
80
+ │ │ ├── middleware.py # SovereignMiddleware — sieve-and-sign request interceptor
81
+ │ │ └── py.typed
82
+ │ └── tests/
83
+ │ └── test_middleware.py
84
+
85
+ ├── example.env # Environment variable reference
86
+ ├── main.py # Workspace-level development entry point
87
+ ├── pyproject.toml # Monorepo configuration & workspace links
88
+ └── uv.lock # Deterministic dependency lockfile
89
+ ```
90
+
91
+ ---
92
+
93
+ ## The ForensicReceipt: Sealed Transformation Accounting
94
+
95
+ Every boundary crossing produces a `ForensicReceipt`. Understanding its structure explains exactly what an enterprise auditor can prove from the output alone.
96
+
97
+ ### What is sealed
98
+
99
+ The Ed25519 signature inside every receipt covers a single canonical manifest:
100
+
101
+ ```json
102
+ {
103
+ "metadata": { ... },
104
+ "payload_hash": "<sha256-of-sieved-content>",
105
+ "timestamp": "<utc-iso8601>"
106
+ }
107
+ ```
108
+
109
+ `payload_hash` is the SHA-256 digest of the exact sieved string delivered to the model or tool. When the Prose Tax sieve is active, `metadata` always contains a `prose_tax_summary` sub-object:
110
+
111
+ ```json
112
+ "prose_tax_summary": {
113
+ "raw_token_count": 12,
114
+ "optimized_token_count": 4,
115
+ "tokens_eliminated": 8,
116
+ "tax_savings_percentage": 66.6667,
117
+ "total_tokens_saved": 8
118
+ }
119
+ ```
120
+
121
+ Because `metadata` is bound inside the signed manifest, these token counts are just as tamper-evident as `payload_hash` itself. An auditor who holds only the node's public key can independently verify:
122
+
123
+ 1. **Output integrity** — the sieved content hasn't been altered after signing (`payload_hash`).
124
+ 2. **Transformation accounting** — the before/after token delta recorded at signing time hasn't been fabricated (`prose_tax_summary` is sealed under the same signature).
125
+ 3. **Identity provenance** — the receipt was minted by the expected node, not a rogue keypair (`public_key` key-pin assertion).
126
+
127
+ Together these three checks give mathematical proof that the boundary transformation was faithful and un-tampered — equivalent to a signed audit log with built-in integrity verification.
128
+
129
+ ### Verification workflow
130
+
131
+ ```python
132
+ import asyncio
133
+ import json
134
+ from sovereign_core.gateway import SovereignGateway
135
+ from sovereign_core.crypto import SovereignKeyManager
136
+
137
+ async def main():
138
+ gateway = SovereignGateway(signing_key=".keys/sovereign_identity.pem")
139
+ result = await gateway.sieve_and_sign("Hi! Please just help me now.")
140
+
141
+ # result.content == "help me now"
142
+ # result.receipt["metadata"]["prose_tax_summary"]["tokens_eliminated"] == 4
143
+
144
+ # Verify later — requires only the public key and the original sieved payload
145
+ is_valid = SovereignKeyManager.verify_receipt(
146
+ result.receipt,
147
+ {"content": result.content},
148
+ expected_public_key=gateway.export_public_key(),
149
+ )
150
+ assert is_valid # fails if any field was mutated after signing
151
+
152
+ asyncio.run(main())
153
+ ```
154
+
155
+ ---
156
+
157
+ ## Primary Developer Interface: `SovereignGateway`
158
+
159
+ `SovereignGateway` is the single entry point for application code. It wraps the full sieve-and-sign pipeline behind a clean four-method API.
160
+
161
+ ### One-shot macro (recommended)
162
+
163
+ `sieve_and_sign()` strips Prose Tax boilerplate, fuses the transformation telemetry into the receipt metadata, and seals everything in a single awaitable call:
164
+
165
+ ```python
166
+ import asyncio
167
+ from sovereign_core.gateway import SovereignGateway
168
+
169
+ async def main():
170
+ gateway = SovereignGateway(signing_key=".keys/sovereign_identity.pem")
171
+ result = await gateway.sieve_and_sign("Hi! Please just help me now.")
172
+
173
+ # result — SovereignBoundaryResponse (Pydantic model, fully typed)
174
+ # result.content — purified string, Prose Tax stripped ("help me now")
175
+ # result.receipt — ForensicReceipt with prose_tax_summary sealed inside
176
+
177
+ print(result.content)
178
+ print(result.receipt["payload_hash"])
179
+
180
+ asyncio.run(main())
181
+ ```
182
+
183
+ Inside a FastAPI route the gateway instance lives on the application object; the route itself is already async:
184
+
185
+ ```python
186
+ from sovereign_core.gateway import SovereignGateway
187
+
188
+ gateway = SovereignGateway(signing_key=".keys/sovereign_identity.pem")
189
+
190
+ @app.post("/api/v1/ingest")
191
+ async def handle_agent_input(raw_payload: dict):
192
+ result = await gateway.sieve_and_sign(raw_payload["text"])
193
+
194
+ await reasoning_ledger.append(
195
+ payload=result.content,
196
+ receipt=result.receipt,
197
+ )
198
+ return {
199
+ "status": "sovereign_verified",
200
+ "receipt_id": result.receipt["payload_hash"],
201
+ }
202
+ ```
203
+
204
+ ### Granular two-step workflow
205
+
206
+ When the clean context is needed before signing (e.g. for intermediate validation or logging):
207
+
208
+ ```python
209
+ import asyncio
210
+ from sovereign_core.gateway import SovereignGateway
211
+
212
+ async def main():
213
+ gateway = SovereignGateway(signing_key=".keys/sovereign_identity.pem")
214
+
215
+ # 1. Strip Prose Tax — remove boilerplate, normalize whitespace
216
+ clean_context = await gateway.sieve("Hi! Please just help me now.")
217
+
218
+ # 2. Cryptographically seal — transformation telemetry fused into metadata
219
+ receipt = gateway.sign(clean_context)
220
+
221
+ print(clean_context) # "help me now"
222
+ print(receipt["payload_hash"]) # SHA-256 of {"content": "help me now"}
223
+
224
+ asyncio.run(main())
225
+ ```
226
+
227
+ ### Independent receipt verification
228
+
229
+ Receipts produced by either workflow can be verified at any time using only the public key:
230
+
231
+ ```python
232
+ from sovereign_core.crypto import SovereignKeyManager
233
+
234
+ is_valid = SovereignKeyManager.verify_receipt(
235
+ receipt,
236
+ {"content": clean_context},
237
+ expected_public_key=gateway.export_public_key(),
238
+ )
239
+ ```
240
+
241
+ ---
242
+
243
+ ## ASGI Middleware for FastAPI / Starlette
244
+
245
+ `SovereignMiddleware` applies the sieve-and-sign boundary to every inbound JSON request transparently, without changes to route handlers:
246
+
247
+ ```python
248
+ from fastapi import FastAPI
249
+ from sovereign_fastapi.middleware import SovereignMiddleware
250
+
251
+ app = FastAPI()
252
+ app.add_middleware(
253
+ SovereignMiddleware,
254
+ signing_key=".keys/sovereign_identity.pem",
255
+ payload_field="text", # JSON key to sieve; omit to sieve the whole body
256
+ strict_mode=False, # True → return HTTP 422 on any interception error
257
+ )
258
+ ```
259
+
260
+ The middleware:
261
+ 1. Extracts the target field from the JSON body.
262
+ 2. Calls `sieve_and_sign()` on the gateway.
263
+ 3. Overwrites `request._body` so every downstream route handler sees the sieved payload.
264
+ 4. Caches the sealed receipt at `request.state.sovereign_receipt`.
265
+ 5. Injects `X-Sovereign-Receipt-Signature` and `X-Sovereign-Tokens-Saved` on the outbound response.
266
+
267
+ ---
268
+
269
+ ## Prose Tax Optimization
270
+
271
+ > **This feature is optional.** The cryptographic boundary and ForensicReceipt are produced whether or not any text is eliminated. Prose Tax optimization runs inside the audit envelope — every token count and savings metric is sealed alongside the output hash.
272
+
273
+ The sieve removes conversational boilerplate that inflates token budgets without contributing semantic content:
274
+
275
+ | Category | Examples stripped |
276
+ |---|---|
277
+ | Greeting tokens | `hi`, `hello`, `hey`, `greetings` |
278
+ | Hedging adverbs | `just`, `simply`, `actually`, `basically`, `probably` |
279
+ | Affirmation filler | `of course`, `certainly`, `absolutely`, `sure` |
280
+ | Preamble phrases | `I hope this`, `I hope that`, `I hope you` |
281
+ | Politeness tokens | `please`, `kindly` |
282
+
283
+ All patterns carry negative lookahead guards (e.g. `(?![-\w])`) so technical compound words (`hi-fi`, `just-in-time`, `certainly-not`) pass through unmarred.
284
+
285
+ ---
286
+
287
+ ## Local Development
288
+
289
+ ### Bootstrap
290
+
291
+ ```bash
292
+ uv sync
293
+ ```
294
+
295
+ ### Run tests
296
+
297
+ ```bash
298
+ uv run pytest
299
+ ```
300
+
301
+ ### Run the sovereign-node runtime
302
+
303
+ ```bash
304
+ uv run sovereign-node
305
+ ```
306
+
307
+ ---
308
+
309
+ ## Running the Workspace Examples
310
+
311
+ ### FastAPI Gateway Example
312
+
313
+ **1. Set your node secret** (required for Ed25519 key generation):
314
+
315
+ ```bash
316
+ export SOVEREIGN_NODE_SECRET=your-local-secret # Linux / macOS
317
+ $env:SOVEREIGN_NODE_SECRET = "your-local-secret" # Windows PowerShell
318
+ ```
319
+
320
+ **2. Start the example server:**
321
+
322
+ ```bash
323
+ uv run uvicorn examples.fastapi_gateway.app:app --reload
324
+ ```
325
+
326
+ The server starts on `http://127.0.0.1:8000`. On first boot it generates an Ed25519 keypair at `.keys/example_identity.pem`.
327
+
328
+ **3. In a second terminal, run the example client:**
329
+
330
+ ```bash
331
+ uv run python examples/fastapi_gateway/client.py
332
+ ```
333
+
334
+ ### Verifying a ForensicReceipt (CLI)
335
+
336
+ Export a receipt and the gateway's public key:
337
+
338
+ ```python
339
+ import asyncio
340
+ import json
341
+ from sovereign_core.gateway import SovereignGateway
342
+
343
+ async def main():
344
+ gateway = SovereignGateway()
345
+ result = await gateway.sieve_and_sign("example payload")
346
+
347
+ with open("receipt.json", "w") as f:
348
+ json.dump(result.receipt, f, indent=2)
349
+
350
+ print(gateway.export_public_key())
351
+
352
+ asyncio.run(main())
353
+ ```
354
+
355
+ Verify the receipt:
356
+
357
+ ```bash
358
+ uv run sovereign-verify \
359
+ --receipt receipt.json \
360
+ --public-key <base64-encoded-public-key>
361
+ ```
362
+
363
+ On success:
364
+
365
+ ```
366
+ Verified ✓ payload_hash: 4fec03e7...
367
+ ```
368
+
369
+ On tampered receipt:
370
+
371
+ ```
372
+ Tampered ✗ Receipt failed cryptographic verification.
373
+ payload_hash : 4fec03e7...
374
+ timestamp : 2026-05-22T...
375
+ ```
376
+
377
+ ---
378
+
379
+ ## Verification & Deep-Dive Diagnostics
380
+
381
+ ### Local Environment Configuration
382
+
383
+ `SOVEREIGN_NODE_SECRET` can be specified in a `.env` file at the repository root. The node entrypoint loads it automatically via `python-dotenv`:
384
+
385
+ ```bash
386
+ echo 'SOVEREIGN_NODE_SECRET=your-local-secret' > .env
387
+ ```
388
+
389
+ ### Standalone Tool Analysis Mode
390
+
391
+ ```bash
392
+ uv run sovereign-node --tool analyze
393
+ ```
394
+
395
+ ### Expected Console Output
396
+
397
+ ```
398
+ ====================================================
399
+ 🟢 Sovereign Node initialization sequence successful.
400
+ ====================================================
401
+ 🔄 Dispatching single tool execution: 'analyze'...
402
+ ⚠️ Standalone mode detected: Context empty. Hydrating baseline diagnostic state...
403
+
404
+ 🔒 Authenticated Forensic Receipt Proof:
405
+ {
406
+ "timestamp": "2026-05-22T15:00:00.000000+00:00",
407
+ "payload_hash": "4fec03e7083cca73cfb1152ae1d941b5a5a581fc725a43b3ee7df1d9ce697954",
408
+ "public_key": "<base64-encoded Ed25519 public key>",
409
+ "signature": "<base64-encoded Ed25519 signature>",
410
+ "metadata": {
411
+ "runtime": "async-sovereign-node",
412
+ "py_ver": "3.12.x",
413
+ "execution_success": true
414
+ }
415
+ }
416
+ ```
417
+
418
+ **Line-by-line interpretation:**
419
+
420
+ | Output line | What it proves |
421
+ |---|---|
422
+ | `🟢 Sovereign Node initialization sequence successful.` | Ed25519 keypair loaded or generated; `SOVEREIGN_NODE_SECRET` resolved; router and session context initialised. |
423
+ | `⚠️ Standalone mode detected …` | The `analyze` tool detected no upstream context and self-hydrated a baseline telemetry stream — expected behaviour in single-tool invocations. |
424
+ | `"payload_hash": "4fec03e7…"` | SHA-256 digest of the deterministically serialised execution payload. |
425
+ | `"public_key": "<base64>"` | Base64-encoded raw Ed25519 public key; verified by `_audit_receipt` before process exit. |
426
+ | `"signature": "<base64>"` | Ed25519 signature over `{"metadata": …, "payload_hash": …, "timestamp": …}`. Any mutation of these fields after issuance causes `verify_receipt` to return `False`. |
427
+ | `"execution_success": true` | The tool completed without raising an exception; the receipt is audit-clean. |