Repository navigation
feat(e2e): Phase E.1 — envelope-layer crypto primitives - #279
Conversation
…ptable) Adds the app-layer cryptography module that's the foundation for Phase E.2 (pair-handshake key exchange) and E.3 (envelope encrypt/decrypt in cmd_send + monitor_formatter). Per the post-bearer-rewrite architecture (saved as project memory), security lives ABOVE the bearer so every transport becomes a dumb pipe — collapsing SSH+Tailscale's transport- encryption role into something we can delete. Primitives, all RFC-standard, all from the python-cryptography package: - X25519 ECDH (RFC 7748) for pairwise key agreement - HKDF-SHA256 (RFC 5869) for key derivation; `info` parameter domain-separates so v1 and v2 keys can coexist during rotation - ChaCha20-Poly1305 AEAD (RFC 8439) with 12-byte nonce - 64-bit counter nonce encoder (replay-defense building block) - Pubkey fingerprint (truncated SHA-256, for invite-string display) - URL-safe base64 helpers (no padding, JSON-friendly) Architecture properties this enables (Joel's brief 2026-04-28: "crypto can adapt to new ECDSA etc type approaches or algorithms, by having the primitives at base"): - Each function is bytes-in, bytes-out — swap X25519 for X448 or a post-quantum primitive by editing one function body, callers unaware. - HKDF info string lets us migrate (e.g. "airc-aead-v1" → "v2") without breaking deployed peers using the old key. - AEAD AD field binds plaintext envelope metadata so swapping in AES-GCM later doesn't change the wire format above this layer. Test gating — the cryptography package is a runtime dep (Phase E.2 will add the venv setup to install.sh). Until that lands, fresh checkouts without the package skip the 32-test suite cleanly rather than failing the whole test run. Verified both paths: - venv-dev with cryptography installed: 32/32 pass in 15ms - system python (no cryptography): 32/32 skip, exit OK No call sites yet — module is purely additive. Phase E.2 wires it into identity bootstrap + pair handshake; E.3 into cmd_send + monitor_formatter. Tests cover (32 total): - X25519KeypairTests (6): generate is random, save/load round-trip, private key 0o600 perms, atomic write (no .tmp leftover), wrong- length rejection - ECDHDeriveTests (4): pair derives matching key, different pairs derive different keys, info string domain-separates, length validation - AEADTests (7): round-trip, AD authenticated, tampered ct fails, tampered nonce fails, explicit counter nonce, key/nonce length validation - CounterNonceTests (4): round-trip, negative/overflow rejection, random-nonce parse-rejection - FingerprintTests (5): default + custom length, deterministic, different keys → different fingerprints, length validation - B64Tests (5): round-trip, no padding output, URL-safe alphabet, unpadded decode, type validation - FullPairwiseScenarioTests (1): end-to-end Alice → Bob with metadata AD-bound, Mallory's wrong key fails auth (the actual airc use case shape) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Adds a new envelope-layer cryptography module (X25519 + HKDF + ChaCha20-Poly1305, nonce helpers, fingerprints, base64 helpers) plus a dedicated unit test suite, as a foundation for upcoming pair handshake and envelope encrypt/decrypt phases.
Changes:
- Introduces
lib/airc_core/crypto.pyimplementing keygen, ECDH+HKDF key derivation, AEAD encrypt/decrypt, counter nonces, fingerprints, and URL-safe base64 helpers. - Adds
test/test_crypto.pycovering the new crypto primitives with skip-on-missing-cryptography behavior. - Updates
.gitignoreto ignore.venv-dev.
Reviewed changes
Copilot reviewed 2 out of 3 changed files in this pull request and generated 8 comments.
| File | Description |
|---|---|
lib/airc_core/crypto.py |
New cryptography primitives module (keygen, KDF, AEAD, nonce/fingerprint/b64 helpers, atomic write helper). |
test/test_crypto.py |
New unit tests for the crypto module, with dependency-based skipping. |
.gitignore |
Ignores .venv-dev directory. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| all do this).""" | ||
| if len(pub_raw) != 32: | ||
| raise ValueError("X25519 pubkey must be 32 bytes") |
There was a problem hiding this comment.
fingerprint() doesn’t validate the length argument. Negative/zero values return an empty string, and values > 64 silently truncate to the full digest length. Validate that length is an int in a sensible range (e.g., 1..64) and raise ValueError otherwise so callers don’t accidentally display an empty/ambiguous fingerprint.
| all do this).""" | |
| if len(pub_raw) != 32: | |
| raise ValueError("X25519 pubkey must be 32 bytes") | |
| all do this). `length` must be an int in the range 1..64.""" | |
| if len(pub_raw) != 32: | |
| raise ValueError("X25519 pubkey must be 32 bytes") | |
| if not isinstance(length, int) or not (1 <= length <= 64): | |
| raise ValueError("length must be an int in range 1..64") |
| def b64decode(s: str) -> bytes: | ||
| """Inverse of b64encode. Re-pads on decode since urlsafe_b64decode | ||
| rejects unpadded input. Raises ValueError on malformed input.""" | ||
| if not isinstance(s, str): | ||
| raise ValueError("b64decode expects str") | ||
| pad = "=" * (-len(s) % 4) | ||
| return base64.urlsafe_b64decode(s + pad) |
There was a problem hiding this comment.
b64decode() uses base64.urlsafe_b64decode(), which does not enable strict alphabet validation and can accept/discard non-base64 characters. For parsing untrusted envelope fields, consider using base64.b64decode(..., altchars=b"-_", validate=True) (after re-padding) so malformed input is rejected deterministically.
| except ImportError as e: | ||
| _HAS_CRYPTO = False | ||
| _SKIP_REASON = ( | ||
| f"cryptography package not available ({e}). " | ||
| f"Run install.sh to set up the venv with airc's runtime dependencies." | ||
| ) |
There was a problem hiding this comment.
The module-level import guard skips all tests on any ImportError from from airc_core import crypto. That can mask real bugs inside crypto.py (or other import-time issues) as “cryptography missing”. Consider only skipping when the missing module is specifically cryptography (e.g., catch ModuleNotFoundError and check e.name), and re-raise other ImportErrors so CI fails appropriately.
| except ImportError as e: | |
| _HAS_CRYPTO = False | |
| _SKIP_REASON = ( | |
| f"cryptography package not available ({e}). " | |
| f"Run install.sh to set up the venv with airc's runtime dependencies." | |
| ) | |
| except ModuleNotFoundError as e: | |
| if e.name == "cryptography" or ( | |
| e.name is not None and e.name.startswith("cryptography.") | |
| ): | |
| _HAS_CRYPTO = False | |
| _SKIP_REASON = ( | |
| f"cryptography package not available ({e}). " | |
| f"Run install.sh to set up the venv with airc's runtime dependencies." | |
| ) | |
| else: | |
| raise |
| def b64decode(s: str) -> bytes: | ||
| """Inverse of b64encode. Re-pads on decode since urlsafe_b64decode | ||
| rejects unpadded input. Raises ValueError on malformed input.""" | ||
| if not isinstance(s, str): | ||
| raise ValueError("b64decode expects str") | ||
| pad = "=" * (-len(s) % 4) | ||
| return base64.urlsafe_b64decode(s + pad) | ||
|
|
There was a problem hiding this comment.
b64decode()’s docstring says it “Raises ValueError on malformed input”, but base64.urlsafe_b64decode typically raises binascii.Error for bad base64. Either catch binascii.Error and re-raise ValueError (for a stable API) or update the docstring/typing to reflect the actual exception type.
| path + ".tmp", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode | ||
| ) | ||
| try: | ||
| os.write(fd, data) |
There was a problem hiding this comment.
_atomic_write_bytes() uses a single os.write(fd, data) call. os.write is allowed to perform partial writes, which can silently truncate the written key material. Use a loop (or wrap fd with a file object and call write()/flush()) to guarantee the full buffer is written before closing/replacing.
| os.write(fd, data) | |
| written = 0 | |
| while written < len(data): | |
| n = os.write(fd, data[written:]) | |
| if n == 0: | |
| raise OSError("os.write() wrote 0 bytes") | |
| written += n |
| fd = os.open( | ||
| path + ".tmp", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode | ||
| ) |
There was a problem hiding this comment.
The temp path is always path + ".tmp" and is opened without O_EXCL. Concurrent writers can clobber each other’s temp file, and a pre-existing/symlinked .tmp file could be followed/truncated. Prefer creating a unique temp file in the same directory (e.g., tempfile.mkstemp) and then os.replace it into place; on POSIX also consider O_NOFOLLOW where available.
| Why raw bytes rather than PEM/OpenSSH format: the only consumer of | ||
| these files is THIS module. PEM adds parser surface area and a | ||
| 150-byte armor that base64'd raw is just 44 bytes. Trade-off in our | ||
| favor: less code, fewer footguns.""" |
There was a problem hiding this comment.
save_keypair() writes whatever bytes it’s given without validating lengths. Since the rest of the module assumes 32-byte raw keys, validate priv_raw/pub_raw are exactly 32 bytes and raise ValueError early (before writing malformed key files to disk).
| favor: less code, fewer footguns.""" | |
| favor: less code, fewer footguns.""" | |
| if len(priv_raw) != _KEY_LEN: | |
| raise ValueError( | |
| f"X25519 private key is {len(priv_raw)} bytes; expected {_KEY_LEN}" | |
| ) | |
| if len(pub_raw) != _KEY_LEN: | |
| raise ValueError( | |
| f"X25519 public key is {len(pub_raw)} bytes; expected {_KEY_LEN}" | |
| ) |
| (None per HKDF spec) — both peers' identities are already in the | ||
| info string and the ECDH shared secret is high-entropy. |
There was a problem hiding this comment.
Docstring says “both peers' identities are already in the info string”, but the default info is a fixed constant (b"airc-aead-v1"). This is misleading; either adjust the wording (e.g., explain why salt=None is acceptable here) or incorporate context (such as both public keys / protocol version) into salt/info if that’s the intent.
| (None per HKDF spec) — both peers' identities are already in the | |
| info string and the ECDH shared secret is high-entropy. | |
| (None per HKDF spec); that is acceptable here because the X25519 | |
| ECDH shared secret is already high-entropy. `info` provides protocol | |
| and purpose separation only; it does not encode peer identities. |
Summary
Adds the app-layer cryptography module — foundation for Phase E.2 (pair handshake) and E.3 (envelope encrypt/decrypt). Per the post-bearer-rewrite architecture, security goes ABOVE the bearer so every transport becomes a dumb pipe and SSH/Tailscale's transport-encryption role collapses into something we can delete.
Primitives (all RFC-standard, python-cryptography package)
Adaptability (Joel's brief: "crypto can adapt to new ECDSA etc")
Test plan
Coverage (32 tests)
Notes
🤖 Generated with Claude Code