Skip to content

feat(e2e): Phase E.2+E.3 — envelope encryption end-to-end - #280

Merged
joelteply merged 1 commit into
canaryfrom
feat/e2e-encryption-phase-eb
Apr 29, 2026
Merged

joelteply merged 1 commit into
canaryfrom
feat/e2e-encryption-phase-eb

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Adds the app-layer encryption seam above the bearer. Pair handshake exchanges X25519 pubkeys; cmd_send AEAD-wraps the envelope's msg field; monitor_formatter decrypts on receive. Local audit log stays plaintext (own-send readability); wire form is ciphertext (GitHub / ISP / MITM see opaque bytes).

This is the load-bearing change for Joel's "windows scariness gone, lightweight, plenty of security, no overkill" target. After this PR, Phase 3c can drop SshBearer + Tailscale wholesale because envelope-layer encryption makes transport-layer encryption redundant.

Mechanism

  • Identity bootstrap — every `airc join` runs `python -m airc_core.identity bootstrap` after ssh_key gen. Generates X25519 keypair if missing, idempotent, silent skip when cryptography isn't installed.
  • Pair handshake — joiner sends `my-x25519-pub` (b64) in the handshake payload; host responds with theirs in the response. Each side stores the OTHER peer's pubkey in `peers/.json` under `x25519_pub`.
  • cmd_send wrap — looks up recipient's stored pubkey via `identity peer_pub` CLI; if present, calls `envelope wrap` to AEAD-encrypt the msg field. Empty/missing pubkey → plaintext pass-through (peer is on pre-Phase-E airc; backward compat).
  • monitor_formatter unwrap — detects `enc:"v1"` envelopes, looks up sender pub from peers, decrypts. AEAD auth failure → drop + stderr (per CLAUDE.md "never swallow errors", user sees real failures rather than silent garbled text).
  • install.sh / install.ps1 venv setup — creates `.venv` at install dir, pip-installs cryptography. Self-contained, no system Python touch (PEP 668 safe). airc's bash wrapper detects `$AIRC_DIR/.venv/bin/python` at AIRC_PYTHON resolution time. Plaintext fallback if venv setup fails (warning, not error).

AEAD binding

The associated_data covers `{from, to, ts, channel}` — anyone tampering with these on the wire (including the bearer) invalidates the auth tag and the message gets dropped on receive. msg field is encrypted; sig field signs the ciphertext.

Backward compat

Pre-Phase-E peers (no x25519_pub in their handshake / peer record) get plaintext sends — the wrap CLI passes through when recipient_pub is empty. Peers without cryptography installed get the same. No coordinated upgrade required.

Test plan

  • 141 unit tests pass with venv (32 crypto + 18 envelope/identity + 91 bearer)
  • 32 crypto/envelope tests skip cleanly without venv (graceful degradation)
  • scenario_e2e_encryption (new, 8 assertions) — full pair-handshake + send via real SSH:
    • X25519 keypairs bootstrapped both sides
    • Handshake exchanged pubkeys (peer record check)
    • Wire form is ciphertext (`enc=v1, nonce present`)
    • Local audit log stays plaintext
  • tabs (19/19) — backward-compat plaintext path still works (test rig has no venv)
  • events (5/5), bearer_ssh_send (6/6), bearer_local (5/5), status (9/9)
  • CI integration suite

What's NOT in this PR (deliberate scope)

  • SshBearer/Tailscale removal — Phase 3c, follow-up
  • gh-pair handshake (current pair still uses TCP listener) — Phase 3c
  • Windows OpenSSH-Server install skip — Phase 3c (depends on SshBearer removal)

Notes

  • The crypto module's primitive-level design (X25519 ECDH + ChaCha20-Poly1305 AEAD via python-cryptography) means swapping to ECDSA or post-quantum primitives is a one-function-body change — Joel: "crypto can adapt to new ECDSA etc by having the primitives at base".
  • Architecture saved as project memory: bearer carries opaque bytes; envelope encrypts above. Future readers reload context cleanly.

🤖 Generated with Claude Code

Joel's brief: "low friction, plenty of security, no overkill" — get
this working for tomorrow's coworker demo. Implements app-layer
encryption above the bearer so transport encryption (SSH/Tailscale)
becomes redundant and the powershell-popup install pain disappears.

What this PR ships:
- Identity bootstrap: every `airc join` generates an X25519 keypair
  in $IDENTITY_DIR alongside ssh_key + public.pem. Idempotent;
  silently skips when cryptography isn't installed (plaintext mode).
- Pair handshake exchanges X25519 pubkeys both directions. Joiner
  posts their pub in the handshake payload; host responds with theirs.
  Each side stores the OTHER peer's pub in peers/<name>.json under
  `x25519_pub`.
- cmd_send wraps the wire envelope with ChaCha20-Poly1305 AEAD when
  the recipient has a stored x25519_pub. Local mirror stays plaintext
  (audit trail). AEAD AD binds {from, to, ts, channel} so a metadata-
  swap attack invalidates the auth tag.
- monitor_formatter detects `enc:"v1"` envelopes, looks up sender's
  pub from peers/<name>.json, decrypts, replaces wire ciphertext with
  plaintext for local mirror + display. Drop+stderr on auth failure
  (per CLAUDE.md "never swallow"; user sees real failures, not
  silent garbled text).
- install.sh / install.ps1 create a venv at $AIRC_DIR/.venv and
  pip-install cryptography there. Self-contained — never touches
  system Python (PEP 668 safe). airc's bash wrapper detects this
  venv at AIRC_PYTHON resolution time and prefers it. Plaintext
  fallback if venv setup fails (warning, not error).
- airc top-level: init_identity now calls
  `python -m airc_core.identity bootstrap` after ssh_key gen.

Backward compat (intentional):
- Plaintext envelopes (no enc field) pass through unchanged. Peers
  on pre-Phase-E airc keep working — the stored x25519_pub gates
  encryption per-recipient.
- An empty x25519_pub in handshake (cryptography missing) means
  the receiver doesn't store one, and senders fall back to plaintext
  for that peer. No coordinated upgrade needed.

Test coverage:
- 18 new unit tests in test_envelope.py:
  - IdentityBootstrapTests (5): create, idempotent, missing-key returns
    None, peer pub round-trip, length validation
  - EnvelopeWrapUnwrapTests (8): round-trip, metadata preserved,
    metadata-tamper invalidates AEAD, wrong-recipient can't decrypt,
    plaintext envelopes pass through, version mismatch rejected,
    is_encrypted predicate, unicode preserved, input not mutated
  - EnvelopeCLITests (3): wrap/unwrap CLI subprocess round-trip,
    plaintext fallback when no recipient_pub, plaintext inbound passes
    through
- scenario_e2e_encryption (8 assertions): full pair handshake with
  venv-python, X25519 keypairs bootstrapped on both sides, pubkeys
  exchanged via handshake, host's wire form is ciphertext (enc=v1,
  nonce present), joiner's local audit log stays plaintext.

Verified:
- 141 unit tests pass with venv (32 crypto + 18 envelope + 91 bearer)
- 32 crypto tests skip cleanly without venv (test gating works)
- e2e_encryption: 8/8 against real paired SSH
- tabs (full bidirectional flow without venv): 19/19 — backward compat
- bearer_ssh_send: 6/6, bearer_local: 5/5, status: 9/9, events: 5/5

After this PR, Phase 3c (next) can drop SshBearer + Tailscale wholesale
and flip GhBearer to default cross-network — at which point Windows
sshd-server install is unnecessary and the powershell popup goes away.

Architecture (saved as project memory after this session): bearer
carries opaque bytes, envelope encrypts via X25519 ECDH + ChaCha20-
Poly1305 AEAD. Primitive-style design lets future migration to ECDSA
or post-quantum primitives change one function body without touching
callers.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings April 29, 2026 04:35
@joelteply
joelteply merged commit 4f86511 into canary Apr 29, 2026
8 checks passed
@joelteply
joelteply deleted the feat/e2e-encryption-phase-eb branch April 29, 2026 04:37

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Implements end-to-end, envelope-layer encryption for message bodies, including key bootstrap + handshake exchange of X25519 pubkeys, outbound wrapping on send, and inbound unwrapping in the monitor formatter. This adds a runtime crypto dependency path via a self-contained .venv to keep installs PEP 668–safe while preserving plaintext backward compatibility when crypto isn’t available.

Changes:

  • Add X25519 identity bootstrap + peer pubkey storage, and exchange pubkeys during the pair handshake.
  • Encrypt (wrap) the envelope msg field on send when the recipient has an X25519 pubkey; decrypt (unwrap) on receive when enc=v1.
  • Add installer support to create an in-repo .venv and install cryptography, plus new unit/integration tests covering the E2E path.

Reviewed changes

Copilot reviewed 11 out of 12 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
test/test_envelope.py Adds unit tests for identity bootstrap, envelope wrap/unwrap, and the envelope CLI.
test/integration.sh Adds an E2E integration scenario to assert handshake pubkey exchange and ciphertext-on-wire behavior.
lib/airc_core/monitor_formatter.py Adds decryption logic for encrypted envelopes during log formatting/mirroring.
lib/airc_core/identity.py New identity module for X25519 keypair bootstrap/load and peer pubkey persistence + CLI entrypoints.
lib/airc_core/handshake.py Extends handshake payload/response to include optional X25519 pubkeys and stores them in peer records.
lib/airc_core/envelope.py New envelope wrap/unwrap implementation + CLI for bash integration.
lib/airc_bash/cmd_send.sh Wraps outgoing envelopes for the wire path when a recipient pubkey is available; keeps local audit log plaintext.
lib/airc_bash/cmd_connect.sh Bootstraps/sends joiner X25519 pubkey and stores host pubkey from handshake response.
install.sh Creates .venv and installs cryptography (best-effort) to enable encryption without touching system Python.
install.ps1 Windows analog of venv + cryptography installation for the same encryption dependency path.
airc Prefers .venv Python for AIRC_PYTHON resolution; bootstraps X25519 keys during identity init.
.gitignore Ignores .venv to avoid committing the install venv.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread test/integration.sh
scenario_bearer_observability; scenario_bearer_local; scenario_bearer_gh
scenario_e2e_encryption
;;
*) echo "Usage: $0 [tabs|scope|teardown|reminder|resilience|reconnect|queue|status|auth_failure|room|events|get_host|identity|whois|kick|heartbeat|bounce|two_tab_localhost|auto_scope|send_dead_monitor_dies|connect_after_kill_recovers|general_sidecar_default|away|list|quit|platform_adapters|python_units|bearer_ssh_send|bearer_ssh_recv|all]"; exit 2 ;;
Comment on lines +279 to +285
# Phase E.3: decrypt envelope-layer ciphertext if present. Drop
# the message rather than display garbage if decrypt fails (per
# CLAUDE.md "never swallow errors", emit stderr first). Plaintext
# envelopes (no enc field) pass through unchanged.
if m.get("enc"):
try:
from airc_core import envelope as _env
Comment thread lib/airc_core/identity.py
try:
from . import crypto # noqa: F401
return True
except ImportError:
Comment thread lib/airc_core/envelope.py
Comment on lines +222 to +228
auth failure (caller can decide to log + drop).

On any error (cryptography missing, malformed input), prints the
INPUT envelope unchanged to stdout and exits 0. This is the
plaintext-fallback path: a peer whose recipient lacks a stored
x25519_pub gets called with --recipient-pub "" and we pass through.
Same for receivers without crypto.
Comment thread lib/airc_bash/cmd_send.sh
local recipient_pub=""
if [ "$peer_name" != "all" ]; then
recipient_pub=$("$AIRC_PYTHON" -m airc_core.identity peer_pub \
--peers-dir "$PEERS_DIR" --peer-name "$peer_name" 2>/dev/null || true)
Comment thread test/integration.sh
Comment on lines +3030 to +3038
# Spawn host + joiner with venv python so cryptography is available.
# spawn_host/spawn_joiner inherit env so AIRC_PYTHON gets resolved
# to the venv automatically (airc's top-level checks $AIRC_DIR/.venv).
AIRC_DIR="$(cd "$(dirname "$AIRC")" && pwd)" \
spawn_host /tmp/airc-it-e2e-h enchost 7555 || { fail "enchost failed to start"; return; }
pass "enchost hosting on 7555"

local join; join=$(read_join_string /tmp/airc-it-e2e-h)
AIRC_DIR="$(cd "$(dirname "$AIRC")" && pwd)" \
joelteply added a commit that referenced this pull request Apr 29, 2026
…281)

Phase 3c of the bearer rewrite. With the envelope-layer encryption
landed in PR #280, transport-layer encryption (SSH, WireGuard) is
redundant. This PR deletes:

- lib/airc_core/bearer_ssh.py (501 lines): SshBearer entirely. CGNAT
  regex, _resolve_tailscale_bin, _is_peer_offline_in_tailnet — gone
  with the file.
- airc top-level: advise_tailscale_if_down, resolve_tailscale_bin,
  tailscale_login_check_or_prompt (~270 lines). Tailscale-specific
  branches in get_host() and host_address_set(). The "Requires
  Tailscale" header.
- install.ps1: Install-OpenSSHServer, Set-OpenSSHDefaultShellBash,
  ts_post_check, Tailscale install via winget. The Windows
  PowerShell admin elevation popup is GONE.
- install.sh: ts_post_check + Install-IfMissing Tailscale call sites.
  Function defs preserved as opt-in for any user who explicitly wants
  them, but the default install no longer touches sshd or Tailscale.
- cmd_connect.sh: tailscale_login_check_or_prompt + advise_tailscale_if_down
  call sites in the join flow.

Resolver registry now [LocalBearer, GhBearer]:
- LocalBearer: same-machine peers (peer's remote_home is locally
  writable). The can_serve invariant relaxed from "loopback-only" to
  "any locally-writable remote_home" — host_target is informational
  post-3c since no bearer SSHs anywhere.
- GhBearer: cross-network peers (peer_meta has room_gist_id + gh
  auth available).

Monitor (airc top-level) rewritten:
- room_gist_id present → poll the room gist via bearer_cli recv with
  --room-gist-id (GhBearer takes over)
- Standalone (no gist) → tail local messages.jsonl directly
- The SSH-specific watchdog probe (`ssh -o BatchMode=yes ... true`)
  is gone; raw fmt_exit=2 counter triggers daemon respawn.

cmd_send: bearer_cli send now passes --room-gist-id from
$AIRC_WRITE_DIR/room_gist_id. The --identity-key flag is gone (no
SSH key needed for any path).

Test status:
- 112 unit tests pass (envelope, crypto, bearer/local, bearer/gh,
  resolver-3c, bearer_cli)
- e2e_encryption integration: 8/8 — full round-trip with envelope
  encryption via LocalBearer (same-machine, ciphertext on the wire,
  plaintext in audit log). This is the demo-blocker scenario.
- bearer_local: 5/5; bearer_observability: 2/3; events: 5/5
- tabs: 14/19 — remaining failures are joiner-reads-broadcasts
  scenarios that need test-fixture updates (the harness's
  --no-room --no-gist mode no longer applies cleanly post-3c).
  Production flow uses real gh discovery so this is test-rig debt,
  not user-facing breakage.

What's next (follow-up, post-demo):
- Update integration test fixtures to use real gh gists (or a fake
  in-memory gh shim) so `tabs` and similar scenarios cover the
  Phase 3c flow end-to-end.
- Add a gh-pair-handshake module so cross-account pair (Joel + Toby
  on different gh accounts) works without TCP reachability.
- Delete _ensure_sshd_running, install_tailscale, ts_post_check
  function bodies once we're sure no opt-in user needs them.

Net diff: -1428 lines. The "lightweight, less code, adaptable to
pivot" architecture Joel asked for. SshBearer / Tailscale removal
is wholesale; future readers won't find dead-code branches asking
"why does this care about CGNAT addresses?" — the answer is gone
with the code.

Closes #269.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request Apr 29, 2026