Sahek commited on
Commit
ed3fb60
·
verified ·
1 Parent(s): e241e1b

Mirror GitHub kaymyg/caio

Browse files
Files changed (14) hide show
  1. .gitignore +12 -0
  2. CHANGELOG.md +54 -0
  3. CODE_OF_CONDUCT.md +56 -0
  4. CONTRIBUTING.md +71 -0
  5. LICENSE +21 -0
  6. README.md +133 -0
  7. SECURITY.md +54 -0
  8. caio/__init__.py +1 -0
  9. caio/core.py +127 -0
  10. caio/demo.py +16 -0
  11. pyproject.toml +29 -0
  12. requirements-dev.txt +3 -0
  13. requirements.txt +1 -0
  14. tests/test_caio.py +59 -0
.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .pytest_cache/
4
+ .coverage
5
+ .coverage.*
6
+ htmlcov/
7
+ .venv/
8
+ venv/
9
+ *.egg-info/
10
+ build/
11
+ dist/
12
+ .mypy_cache/
CHANGELOG.md ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here.
4
+ Format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
+
6
+ ## [0.3.0] - 2026-08-30
7
+
8
+ First tagged release. Version matches the prototype's own `__version__`.
9
+
10
+ ### Added
11
+
12
+ - `LineageChain`: hash-linked, Ed25519-signed ancestry from a human root
13
+ through devices/runtimes to individual agents.
14
+ - `Ledger`: thread-safe capability/resource delegation with conservation
15
+ enforcement (no double-spending a parent's budget across children).
16
+ - `Lease`: signed, time-boxed, nonce-scoped capability grant with replay
17
+ protection.
18
+ - `EvidenceGraph` / `Level`: multi-perspective (claim / host / network)
19
+ divergence detection with graduated escalation (NORMAL → OBSERVATION →
20
+ CAPABILITY_REDUCTION → NETWORK_RESTRICTION → QUARANTINE → TERMINATED).
21
+ - `Audit`: hash-chained, tamper-evident log of lease issuance and
22
+ evaluation events.
23
+ - `Gateway`: end-to-end `transact()` call tying all of the above together.
24
+ - `caio/demo.py`: end-to-end demonstration script.
25
+ - Initial test suite (5 tests): lineage tamper detection, ledger
26
+ conservation/double-spend rejection, replay rejection, defense-level
27
+ escalation to TERMINATED, audit tamper-evidence.
28
+ - CONTRIBUTING.md, SECURITY.md, CODE_OF_CONDUCT.md, issue templates
29
+ (including a bypass-report template), PR template, Dependabot.
30
+ - `pyproject.toml` for proper editable/pip installation (previously only a
31
+ bare `requirements.txt` with no packaging metadata).
32
+ - CI: pytest with coverage + demo smoke test across Python 3.10–3.12.
33
+
34
+ ### Fixed
35
+
36
+ - Expanded test coverage from 5 to 10 tests, closing real gaps found via
37
+ `pytest --cov` (not just added for count): `Gateway.transact()`'s
38
+ expired-lease rejection, tampered-signature rejection, and network-fuel
39
+ exhaustion (429) branches were previously unexercised entirely (0%
40
+ coverage on those lines), and defense-level escalation was only tested
41
+ via `EvidenceGraph.evaluate()` directly, never through `transact()`'s own
42
+ HTTP-style status mapping. `caio/core.py` is now at 100% line coverage.
43
+ - Split `requirements.txt` (runtime: `cryptography` only) from
44
+ `requirements-dev.txt` (adds `pytest`, `pytest-cov`) — the original file
45
+ mixed a runtime and a test-only dependency together.
46
+
47
+ ### Notes
48
+
49
+ - An earlier, more verbose rewrite of this prototype was proposed in a
50
+ prior conversation but was **not** adopted as the basis for this release
51
+ — it dropped real security-relevant features present in the actual
52
+ working prototype (nonce-based replay protection, the hash-chained audit
53
+ log, thread-safety locking) in exchange for more verbose code. This
54
+ release builds on the original, more complete implementation instead.
CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics,
8
+ gender identity and expression, level of experience, education,
9
+ socio-economic status, nationality, personal appearance, race, religion, or
10
+ sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to a positive environment:
15
+
16
+ - Demonstrating empathy and kindness toward other people
17
+ - Being respectful of differing opinions, viewpoints, and experiences
18
+ - Giving and gracefully accepting constructive feedback
19
+ - Focusing on what is best not just for us as individuals, but for the
20
+ overall community
21
+
22
+ Examples of unacceptable behavior:
23
+
24
+ - The use of sexualized language or imagery, and sexual attention or
25
+ advances of any kind
26
+ - Trolling, insulting or derogatory comments, and personal or political
27
+ attacks
28
+ - Public or private harassment
29
+ - Publishing others' private information without explicit permission
30
+
31
+ ## Enforcement Responsibilities
32
+
33
+ Project maintainers are responsible for clarifying and enforcing standards
34
+ of acceptable behavior and will take appropriate and fair corrective action
35
+ in response to any behavior deemed inappropriate, threatening, offensive, or
36
+ harmful.
37
+
38
+ ## Scope
39
+
40
+ This Code of Conduct applies within all project spaces (issues, pull
41
+ requests, discussions) and when an individual is officially representing the
42
+ project in public spaces.
43
+
44
+ ## Enforcement
45
+
46
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
47
+ reported to the maintainer via GitHub's private reporting tools. All
48
+ complaints will be reviewed and investigated promptly and fairly.
49
+
50
+ ## Attribution
51
+
52
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
53
+ version 2.1, available at
54
+ https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.
55
+
56
+ [homepage]: https://www.contributor-covenant.org
CONTRIBUTING.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to CAIO
2
+
3
+ Thanks for your interest. CAIO is a reference prototype synthesizing ideas
4
+ validated separately across several sibling projects (see the README's
5
+ "Relationship to other projects" section) — contributions that strengthen
6
+ the actual security properties (lineage integrity, capability conservation,
7
+ divergence detection, audit tamper-evidence) are especially valuable.
8
+
9
+ ## Getting set up
10
+
11
+ ```bash
12
+ git clone https://github.com/kaymyg/caio.git
13
+ cd caio
14
+ pip install -r requirements-dev.txt
15
+ pip install -e .
16
+
17
+ python -m caio.demo # see it work end to end
18
+ pytest -q --cov=caio --cov-report=term-missing # 10 tests, 100% on core.py
19
+ ```
20
+
21
+ ## Before opening a PR
22
+
23
+ CI runs the test suite with coverage and the demo script, across Python
24
+ 3.10–3.12, on every push and PR. Please run that locally first.
25
+
26
+ If you add a new branch or status code to `Gateway.transact()`, add a test
27
+ that exercises it through `gw.transact()` itself, not just the underlying
28
+ helper it calls — `test_transact_level_status_mapping` exists specifically
29
+ because the original test suite covered `EvidenceGraph.evaluate()` directly
30
+ but never asserted what `transact()` actually mapped that result to.
31
+
32
+ ## What especially matters here
33
+
34
+ - **This is a reference prototype, not a deployable network protocol.** The
35
+ agent key-binding check in `Gateway.transact()` is a local
36
+ sign/verify-with-a-fresh-nonce consistency check, not a real challenge
37
+ issued over an untrusted wire — be precise about this distinction in any
38
+ docs or code you touch, don't let it get oversold.
39
+ - **`Lease.expires_at` is checked; `Lease.issued_at` is not.** A lease
40
+ "valid" from a future timestamp still passes `Gateway.valid()`. This is a
41
+ known, documented gap (see README "Known Limitations"), not an oversight
42
+ to silently patch — if you fix it, make sure you understand why it was
43
+ left out (clock-skew tolerance) before tightening it.
44
+ - **The host-divergence detector checks two specific action strings**
45
+ (`CRITICAL_TAMPER`, `UNSANCTIONED_EXEC`), not general anomaly detection.
46
+ A generic claim/host mismatch only reaches `CAPABILITY_REDUCTION`, not
47
+ `QUARANTINE` — that's intentional graduated response, not a bug, but
48
+ don't describe it as catching "any divergence" in docs.
49
+ - **Nonce replay protection burns the nonce only after key-binding
50
+ succeeds** — preserve that ordering if you touch `transact()`; marking a
51
+ nonce used before authentication would let an attacker burn a legitimate
52
+ agent's nonce with a failed forged request.
53
+
54
+ ## Good places to start
55
+
56
+ - A real network-level challenge-response protocol to replace the local
57
+ key-binding consistency check
58
+ - `issued_at` validation (with configurable clock-skew tolerance)
59
+ - Persisting `Ledger`/`Audit`/`EvidenceGraph` state instead of in-memory only
60
+ - Expanding the host-action taxonomy beyond the current two hardcoded
61
+ "bad" actions, ideally via a configurable policy rather than more
62
+ hardcoded strings
63
+ - A real transport binding (HTTP middleware, gRPC interceptor) around
64
+ `Gateway.transact()`
65
+
66
+ For anything larger, please open an issue first to discuss the approach.
67
+
68
+ ## Commit style
69
+
70
+ Small, focused commits with a clear one-line summary. No strict format
71
+ enforced beyond that.
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kaymyg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CAIO — Cryptographically Attested Internet Overlay
2
+
3
+ [![CI](https://github.com/kaymyg/caio/actions/workflows/ci.yml/badge.svg)](https://github.com/kaymyg/caio/actions/workflows/ci.yml)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
5
+ [![Tests](https://img.shields.io/badge/tests-10%20passing-brightgreen)](tests/)
6
+ [![Coverage](https://img.shields.io/badge/coverage-100%25%20core.py-brightgreen)](tests/)
7
+
8
+ A small, dense reference prototype for one question: **when an autonomous
9
+ agent acts on a network, how do you cryptographically prove who it is,
10
+ what it's allowed to do, and whether it's telling the truth about what it
11
+ actually did?**
12
+
13
+ > ⚠️ **Reference prototype, not production security software.** Deliberately
14
+ > small enough to read in full in one sitting (~110 lines of actual logic).
15
+ > See "Known Limitations" below before using this for anything real.
16
+
17
+ ## Quick start
18
+
19
+ ```bash
20
+ git clone https://github.com/kaymyg/caio.git
21
+ cd caio
22
+ pip install -r requirements-dev.txt
23
+ pip install -e .
24
+
25
+ python -m caio.demo # see it work end to end
26
+ pytest -q --cov=caio --cov-report=term-missing
27
+ ```
28
+
29
+ Expected demo output:
30
+
31
+ ```
32
+ Lineage verified: True
33
+ Valid transaction: {'status': 200, 'level': 'NORMAL', 'route': 'VERIFIED_OVERLAY'}
34
+ Divergence attack: {'status': 500, 'reason': 'terminated'}
35
+ Audit verified: True
36
+ ```
37
+
38
+ ## What it actually does
39
+
40
+ Six small components, each independently testable:
41
+
42
+ * **`LineageChain`** — a hash-linked, Ed25519-signed chain from a human
43
+ root through devices/runtimes down to individual agents and sub-agents.
44
+ Each link is signed by its *parent*, so a node can't fabricate its own
45
+ ancestry. `verify()` walks the whole chain and catches any tampered node
46
+ or forged signature.
47
+ * **`Ledger`** — capability/resource delegation with real conservation: a
48
+ parent can only delegate compute/network/child-creation budget it
49
+ actually has, and delegating debits the parent atomically (thread-safe
50
+ via `RLock`). No double-spending a budget across two children.
51
+ * **`Lease`** — a signed, time-boxed, nonce-scoped capability grant listing
52
+ exactly which capabilities and endpoints an agent may use. Replay is
53
+ blocked by tracking spent nonces; tampering is blocked because the
54
+ signature covers the full canonical payload.
55
+ * **`EvidenceGraph` / `Level`** — the core idea: collect what the agent
56
+ *claims* it did, what the *host* independently observed, and what the
57
+ *network* independently observed, then check whether they agree. A
58
+ generic mismatch escalates to `CAPABILITY_REDUCTION`; specific dangerous
59
+ host actions escalate straight to `QUARANTINE`; a disallowed network
60
+ target escalates to `NETWORK_RESTRICTION`; host and network violations
61
+ together escalate to `TERMINATED`.
62
+ * **`Audit`** — a hash-chained, tamper-evident log (`prev` + `hash` per
63
+ entry, same shape as a blockchain's block-linking) of every lease
64
+ issuance and evaluation. `verify()` detects any alteration, reordering,
65
+ or deletion.
66
+ * **`Gateway`** — ties all of the above together into one call:
67
+ `transact()` validates the lease, checks replay, checks agent
68
+ key-binding, records evidence from all three perspectives, evaluates the
69
+ defense level, and returns an HTTP-style status.
70
+
71
+ ## Relationship to other projects
72
+
73
+ CAIO isn't a from-scratch idea — it's a deliberate synthesis of mechanisms
74
+ already built and independently tested across several sibling projects.
75
+ Each one validated a piece of this in isolation:
76
+
77
+ | Mechanism in CAIO | Proven independently in |
78
+ | --- | --- |
79
+ | Signed capability leases with trust-state gating | [`ubda-engine`](https://github.com/kaymyg/ubda-engine) — Data Access Capabilities, trust-state thresholds |
80
+ | Graduated escalation on breach (not binary allow/deny) | [`hydra-cage`](https://github.com/kaymyg/hydra-cage) — five-plane containment, eight-stage breach transition |
81
+ | Multi-perspective divergence detection (claim vs. reality) | [`multi-agent-mcl`](https://github.com/kaymyg/multi-agent-mcl) — behavioral vs. actual policy vector comparison |
82
+ | Risk-scored gating before an action executes | [`lean-agent-governance`](https://github.com/kaymyg/lean-agent-governance) — pre-runtime prompt/diff risk scoring |
83
+ | Hash-chained, independently-verifiable integrity | [`kaysentinel`](https://github.com/kaymyg/kaysentinel) — canonical hashing, structural + semantic verification gates |
84
+
85
+ CAIO takes the smallest working version of each of those ideas and wires
86
+ them into one coherent request path (`Gateway.transact()`), rather than
87
+ five separate systems. It's meant to be the concrete answer to "what would
88
+ it look like if these five ideas had to cooperate in a single call."
89
+
90
+ ## Known Limitations
91
+
92
+ Stated plainly rather than buried, since that's the standard the rest of
93
+ this account's projects hold themselves to:
94
+
95
+ * **The agent key-binding check is a local consistency check, not a real
96
+ network challenge-response protocol.** `Gateway.transact()` signs a
97
+ freshly generated nonce with the `agent_private_key` passed directly into
98
+ the call and immediately verifies it — this proves internal consistency
99
+ (the key matches what the lease claims), not that the request travelled
100
+ over an authenticated channel. A real deployment needs an actual
101
+ challenge issued over the wire.
102
+ * **`Lease.issued_at` is never validated**, only `expires_at`. A lease
103
+ claiming to be issued in the future still passes `Gateway.valid()`.
104
+ * **Host-divergence detection checks two hardcoded action strings**
105
+ (`CRITICAL_TAMPER`, `UNSANCTIONED_EXEC`), not general anomaly detection.
106
+ Any other kind of claim/host mismatch reaches `CAPABILITY_REDUCTION` at
107
+ most, not `QUARANTINE` — that's intentional graduated response, not a
108
+ bug, but it means the detector's actual coverage is narrower than
109
+ "catches divergence" might suggest at a glance.
110
+ * **Everything is in-memory.** `Ledger`, `Audit`, and `EvidenceGraph` state
111
+ don't survive a process restart; there's no persistence layer.
112
+ * **Single-process only.** No distributed consensus on lineage, ledger
113
+ balances, or audit log state across multiple gateway instances.
114
+
115
+ ## Contributing
116
+
117
+ Bug reports, new divergence scenarios, and PRs are welcome — see
118
+ [`CONTRIBUTING.md`](CONTRIBUTING.md) for setup and what CI checks.
119
+
120
+ ## Security
121
+
122
+ Found a way to forge lineage, double-spend a ledger balance, replay a
123
+ nonce, or make the audit log lie about tampering? Please see
124
+ [`SECURITY.md`](SECURITY.md) for how to report it responsibly rather than
125
+ opening a public issue.
126
+
127
+ ## Changelog
128
+
129
+ See [`CHANGELOG.md`](CHANGELOG.md).
130
+
131
+ ## License
132
+
133
+ MIT — see [`LICENSE`](LICENSE).
SECURITY.md ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ ## Scope
4
+
5
+ CAIO is a **reference prototype**, not production security software (the
6
+ README says so explicitly, and means it). It's small and dense enough to
7
+ read in full in one sitting — that's a deliberate design choice, and part
8
+ of the point is that the whole trust boundary is auditable at a glance.
9
+
10
+ What **is** a genuine finding here:
11
+
12
+ - A way to forge or extend a `Lineage` chain without the parent's private
13
+ key, or make `Lineage.verify()` return `True` for a tampered chain
14
+ - A way to make `Ledger.delegate()` allocate more resources to children
15
+ than the parent actually had (breaking conservation)
16
+ - A way to reuse a `Lease` nonce and pass `Gateway.transact()`'s replay
17
+ check a second time
18
+ - A way to make `Gateway.valid()` accept a lease whose signature doesn't
19
+ actually match its payload
20
+ - A way to make `Audit.verify()` return `True` after a log entry has been
21
+ altered, reordered, or deleted
22
+ - A way to get `EvidenceGraph.evaluate()` to under-classify a genuinely
23
+ divergent claim/host/network pattern (i.e., something that should reach
24
+ at least `CAPABILITY_REDUCTION` but doesn't)
25
+
26
+ What's a **known limitation, not a new finding** (see the README and
27
+ CONTRIBUTING.md before reporting):
28
+
29
+ - The agent key-binding check is a local consistency check, not a real
30
+ network challenge-response protocol
31
+ - `Lease.issued_at` isn't validated, only `expires_at`
32
+ - Host-divergence detection checks two specific hardcoded action strings,
33
+ not general anomaly detection
34
+ - Everything is in-memory; nothing here is persisted or distributed
35
+
36
+ ## Reporting
37
+
38
+ Please **do not** open a public GitHub issue for a working bypass of any of
39
+ the properties above — that publishes the technique before there's a fix.
40
+
41
+ Instead, use GitHub's private vulnerability reporting for this repository
42
+ (Security tab → "Report a vulnerability"). Please include:
43
+
44
+ - A minimal reproduction, ideally as a new test in the style of
45
+ `tests/test_caio.py`
46
+ - Which property it breaks (lineage integrity, conservation, replay
47
+ protection, signature validity, audit tamper-evidence, or divergence
48
+ detection)
49
+
50
+ ## Response expectations
51
+
52
+ Independent reference project — best-effort response, not a guaranteed
53
+ SLA. Genuine findings will be prioritized and credited (with permission)
54
+ once fixed.
caio/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = '0.3.0'
caio/core.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64, hashlib, json, time, uuid
2
+ from dataclasses import dataclass, field
3
+ from enum import IntEnum
4
+ from threading import RLock
5
+ from cryptography.exceptions import InvalidSignature
6
+ from cryptography.hazmat.primitives.asymmetric import ed25519
7
+
8
+
9
+ def canonical(x):
10
+ return json.dumps(x, sort_keys=True, separators=(',', ':'), default=list).encode()
11
+
12
+ def keypair():
13
+ p = ed25519.Ed25519PrivateKey.generate(); return p, p.public_key()
14
+
15
+ def pubkey(pub):
16
+ return base64.b64encode(pub.public_bytes_raw()).decode()
17
+
18
+ def pubkey_load(s): return ed25519.Ed25519PublicKey.from_public_bytes(base64.b64decode(s))
19
+ def sign(k, data): return base64.b64encode(k.sign(data)).decode()
20
+ def verify(k, sig, data):
21
+ try: k.verify(base64.b64decode(sig), data); return True
22
+ except (InvalidSignature, ValueError): return False
23
+
24
+ def sha(x): return hashlib.sha256(x).hexdigest()
25
+
26
+ @dataclass(frozen=True)
27
+ class LineageNode:
28
+ node_id: str; node_type: str; public_key: str; previous_hash: str; signature: str = ''
29
+ def digest(self): return sha(canonical({'node_id':self.node_id,'node_type':self.node_type,'public_key':self.public_key,'previous_hash':self.previous_hash}))
30
+
31
+ class Lineage:
32
+ def __init__(self, root): self.nodes=[root]
33
+ def append(self,node,parent_private):
34
+ if node.previous_hash != self.nodes[-1].digest(): raise ValueError('lineage link mismatch')
35
+ n=LineageNode(node.node_id,node.node_type,node.public_key,node.previous_hash,sign(parent_private,node.digest().encode()))
36
+ self.nodes.append(n); return n
37
+ def verify(self):
38
+ for a,b in zip(self.nodes,self.nodes[1:]):
39
+ if b.previous_hash != a.digest() or not verify(pubkey_load(a.public_key),b.signature,b.digest().encode()): return False
40
+ return True
41
+ @property
42
+ def tip(self): return self.nodes[-1].digest()
43
+
44
+ @dataclass
45
+ class Budget:
46
+ compute:int; network:int; children:int=0
47
+ def covers(self,b): return self.compute>=b.compute and self.network>=b.network and self.children>=b.children
48
+
49
+ @dataclass(frozen=True)
50
+ class LedgerEntry:
51
+ sequence:int; parent:str; child:str; budget:Budget
52
+
53
+ class Ledger:
54
+ def __init__(self): self.balances={}; self.entries=[]; self.seq=0; self.lock=RLock()
55
+ def init(self,agent,budget):
56
+ with self.lock:
57
+ if agent in self.balances: raise ValueError('duplicate agent')
58
+ self.balances[agent]=Budget(**vars(budget))
59
+ def delegate(self,parent,child,budget):
60
+ with self.lock:
61
+ p=self.balances[parent]
62
+ if not p.covers(budget): raise PermissionError('insufficient balance')
63
+ p.compute-=budget.compute; p.network-=budget.network; p.children-=budget.children
64
+ if child in self.balances: raise ValueError('duplicate child')
65
+ self.balances[child]=Budget(**vars(budget)); self.seq+=1
66
+ self.entries.append(LedgerEntry(self.seq,parent,child,budget))
67
+ def consume(self,agent,compute=0,network=0):
68
+ with self.lock:
69
+ b=self.balances[agent]
70
+ if b.compute<compute or b.network<network: raise PermissionError('fuel exhausted')
71
+ b.compute-=compute; b.network-=network
72
+
73
+ @dataclass
74
+ class Lease:
75
+ token_id:str; lineage_root:str; lineage_hash:str; agent_pubkey:str; capabilities:set; endpoints:set; budget:Budget; issued_at:float; expires_at:float; nonce:str; signature:str=''
76
+ def payload(self): return {'token_id':self.token_id,'lineage_root':self.lineage_root,'lineage_hash':self.lineage_hash,'agent_pubkey':self.agent_pubkey,'capabilities':sorted(self.capabilities),'endpoints':sorted(self.endpoints),'budget':vars(self.budget),'issued_at':self.issued_at,'expires_at':self.expires_at,'nonce':self.nonce}
77
+
78
+ class Level(IntEnum): NORMAL=0; OBSERVATION=1; CAPABILITY_REDUCTION=2; NETWORK_RESTRICTION=3; QUARANTINE=4; TERMINATED=5
79
+ @dataclass(frozen=True)
80
+ class Evidence:
81
+ id:str; agent:str; perspective:str; action:str; target:str; ts:float=field(default_factory=time.time)
82
+
83
+ class EvidenceGraph:
84
+ def __init__(self): self.events={}; self.state={}
85
+ def add(self,e): self.events.setdefault(e.agent,[]).append(e)
86
+ def evaluate(self,agent,lease):
87
+ ev=self.events.get(agent,[]); c=[e for e in ev if e.perspective=='CLAIM']; h=[e for e in ev if e.perspective=='HOST']; n=[e for e in ev if e.perspective=='NETWORK']; level=Level.NORMAL
88
+ if c and h and (c[-1].action!=h[-1].action or c[-1].target!=h[-1].target): level=max(level,Level.CAPABILITY_REDUCTION)
89
+ badhost=any(e.action in ('CRITICAL_TAMPER','UNSANCTIONED_EXEC') for e in h)
90
+ badnet=any(e.target not in lease.endpoints for e in n)
91
+ if badnet: level=max(level,Level.NETWORK_RESTRICTION)
92
+ if badhost: level=max(level,Level.QUARANTINE)
93
+ if badhost and badnet: level=Level.TERMINATED
94
+ self.state[agent]=level; return level
95
+
96
+ class Audit:
97
+ def __init__(self): self.rows=[]; self.tip='0'*64
98
+ def add(self,event,data):
99
+ r={'i':len(self.rows)+1,'ts':time.time(),'event':event,'data':data,'prev':self.tip}
100
+ r['hash']=sha(canonical(r)); self.tip=r['hash']; self.rows.append(r)
101
+ def verify(self):
102
+ prev='0'*64
103
+ for r in self.rows:
104
+ if r['prev']!=prev: return False
105
+ q=dict(r); h=q.pop('hash')
106
+ if sha(canonical(q))!=h: return False
107
+ prev=h
108
+ return True
109
+
110
+ class Gateway:
111
+ def __init__(self,issuer_public,graph,ledger): self.issuer=issuer_public; self.graph=graph; self.ledger=ledger; self.audit=Audit(); self.used=set()
112
+ def issue(self,lease,issuer_private): lease.signature=sign(issuer_private,canonical(lease.payload())); self.audit.add('LEASE_ISSUED',{'token':lease.token_id}); return lease
113
+ def valid(self,l): return verify(self.issuer,l.signature,canonical(l.payload())) and time.time()<l.expires_at
114
+ def transact(self,l,agent_private,action,endpoint,host_action,host_target,net_target):
115
+ if not self.valid(l): return {'status':401,'reason':'invalid/expired lease'}
116
+ if l.nonce in self.used: return {'status':409,'reason':'replay detected'}
117
+ if not verify(pubkey_load(l.agent_pubkey),sign(agent_private,(c:=uuid.uuid4().bytes)),c): return {'status':401,'reason':'agent binding failed'}
118
+ self.used.add(l.nonce); a=l.token_id
119
+ self.graph.add(Evidence(str(uuid.uuid4()),a,'CLAIM',action,endpoint)); self.graph.add(Evidence(str(uuid.uuid4()),a,'HOST',host_action,host_target)); self.graph.add(Evidence(str(uuid.uuid4()),a,'NETWORK','CONNECT',net_target))
120
+ level=self.graph.evaluate(a,l); self.audit.add('EVALUATED',{'agent':a,'level':int(level)})
121
+ if level>=Level.TERMINATED:return {'status':500,'reason':'terminated'}
122
+ if level>=Level.QUARANTINE:return {'status':403,'reason':'quarantined'}
123
+ if level>=Level.NETWORK_RESTRICTION:return {'status':403,'reason':'network restricted'}
124
+ if endpoint not in l.endpoints:return {'status':403,'reason':'endpoint outside lease'}
125
+ try:self.ledger.consume(a,network=1)
126
+ except PermissionError:return {'status':429,'reason':'network fuel exhausted'}
127
+ return {'status':200,'level':level.name,'route':'VERIFIED_OVERLAY'}
caio/demo.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time,uuid
2
+ from .core import *
3
+
4
+ def main():
5
+ rp,rpub=keypair(); ap,apub=keypair()
6
+ root=LineageNode('HUMAN-1','HUMAN',pubkey(rpub),'0'*64); chain=Lineage(root)
7
+ chain.append(LineageNode('AGENT-1','AGENT',pubkey(apub),chain.tip),rp)
8
+ ledger=Ledger(); ledger.init('AGENT-1',Budget(5000,1000,1)); graph=EvidenceGraph(); gw=Gateway(rpub,graph,ledger)
9
+ lease=Lease('AGENT-1','HUMAN-1',chain.tip,pubkey(apub),{'HTTP_GET'},{'api.trusted.local'},Budget(4000,500),time.time(),time.time()+60,str(uuid.uuid4()))
10
+ gw.issue(lease,rp)
11
+ print('Lineage verified:',chain.verify())
12
+ print('Valid transaction:',gw.transact(lease,ap,'HTTP_GET','api.trusted.local','HTTP_GET','api.trusted.local','api.trusted.local'))
13
+ attack=Lease(**{**vars(lease),'nonce':str(uuid.uuid4()),'signature':''}); gw.issue(attack,rp)
14
+ print('Divergence attack:',gw.transact(attack,ap,'HTTP_GET','api.trusted.local','UNSANCTIONED_EXEC','/etc/shadow','evil.example'))
15
+ print('Audit verified:',gw.audit.verify())
16
+ if __name__=='__main__': main()
pyproject.toml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "caio"
7
+ version = "0.3.0"
8
+ description = "Cryptographically Attested Internet Overlay -- reference prototype for cryptographic lineage, capability leasing, and multi-perspective divergence defense for autonomous agents"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "kaymyg" }]
13
+ dependencies = [
14
+ "cryptography>=43,<47",
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Topic :: Security",
22
+ "Topic :: Security :: Cryptography",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ dev = ["pytest>=8,<9", "pytest-cov>=4"]
27
+
28
+ [tool.setuptools.packages.find]
29
+ include = ["caio*"]
requirements-dev.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ -r requirements.txt
2
+ pytest>=8,<9
3
+ pytest-cov>=4
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ cryptography>=43,<47
tests/test_caio.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time,uuid
2
+ from caio.core import *
3
+
4
+ def setup():
5
+ rp,rpub=keypair(); ap,apub=keypair(); root=LineageNode('H','HUMAN',pubkey(rpub),'0'*64); chain=Lineage(root); chain.append(LineageNode('A','AGENT',pubkey(apub),chain.tip),rp)
6
+ ledger=Ledger(); ledger.init('A',Budget(100,10,1)); graph=EvidenceGraph(); gw=Gateway(rpub,graph,ledger)
7
+ lease=Lease('A','H',chain.tip,pubkey(apub),{'GET'},{'good'},Budget(50,5),time.time(),time.time()+60,str(uuid.uuid4())); gw.issue(lease,rp)
8
+ return rp,rpub,ap,chain,ledger,graph,gw,lease
9
+
10
+ def test_lineage(): assert setup()[3].verify()
11
+ def test_replay():
12
+ _,_,ap,_,_,_,gw,l=setup(); assert gw.transact(l,ap,'GET','good','GET','good','good')['status']==200; assert gw.transact(l,ap,'GET','good','GET','good','good')['status']==409
13
+ def test_conservation():
14
+ x=Ledger(); x.init('p',Budget(10,10,1)); x.delegate('p','c',Budget(5,5,1)); assert vars(x.balances['p'])=={'compute':5,'network':5,'children':0}
15
+ try:x.delegate('p','x',Budget(6,1,0)); assert False
16
+ except PermissionError:pass
17
+ def test_termination():
18
+ *_,graph,gw,l=setup(); graph.add(Evidence('1','A','CLAIM','GET','good')); graph.add(Evidence('2','A','HOST','UNSANCTIONED_EXEC','/etc/shadow')); graph.add(Evidence('3','A','NETWORK','CONNECT','evil')); assert graph.evaluate('A',l)==Level.TERMINATED
19
+ def test_audit(): assert setup()[6].audit.verify()
20
+
21
+ def test_expired_lease_rejected():
22
+ rp,rpub,ap,chain,ledger,graph,gw,l=setup()
23
+ l.expires_at=time.time()-1
24
+ res=gw.transact(l,ap,'GET','good','GET','good','good')
25
+ assert res['status']==401 and 'invalid/expired' in res['reason']
26
+
27
+ def test_tampered_signature_rejected():
28
+ rp,rpub,ap,chain,ledger,graph,gw,l=setup()
29
+ l.capabilities={'GET','ADMIN'} # mutate payload after signing -- signature no longer matches
30
+ res=gw.transact(l,ap,'GET','good','GET','good','good')
31
+ assert res['status']==401 and 'invalid/expired' in res['reason']
32
+
33
+ def test_endpoint_outside_lease_rejected():
34
+ # net_target must stay inside the lease so NETWORK_RESTRICTION doesn't
35
+ # fire first and mask this check -- this isolates the dedicated
36
+ # endpoint-outside-lease branch, which only triggers when the *claimed*
37
+ # endpoint diverges from an otherwise-allowed network target.
38
+ rp,rpub,ap,chain,ledger,graph,gw,l=setup()
39
+ res=gw.transact(l,ap,'GET','not-in-lease','GET','good','good')
40
+ assert res['status']==403 and 'endpoint' in res['reason']
41
+
42
+ def test_network_fuel_exhaustion():
43
+ rp,rpub,ap,chain,ledger,graph,gw,l=setup()
44
+ ledger.balances['A'].network=0 # drain the agent's remaining network budget
45
+ res=gw.transact(l,ap,'GET','good','GET','good','good')
46
+ assert res['status']==429 and 'fuel' in res['reason']
47
+
48
+ def test_transact_level_status_mapping():
49
+ # Exercises the QUARANTINE and NETWORK_RESTRICTION branches through the
50
+ # real gw.transact() call, not just EvidenceGraph.evaluate() directly --
51
+ # the existing test_termination only covered the graph-level evaluation,
52
+ # not the HTTP-style status code Gateway.transact() maps it to.
53
+ rp,rpub,ap,chain,ledger,graph,gw,l=setup()
54
+ quarantine=gw.transact(l,ap,'GET','good','UNSANCTIONED_EXEC','/etc/shadow','good')
55
+ assert quarantine['status']==403 and quarantine['reason']=='quarantined'
56
+
57
+ rp,rpub,ap,chain,ledger,graph,gw,l=setup()
58
+ restricted=gw.transact(l,ap,'GET','good','GET','good','not-allowed')
59
+ assert restricted['status']==403 and restricted['reason']=='network restricted'