Skip to content

feat(e2e): Phase E.1 — envelope-layer crypto primitives - #279

Merged
joelteply merged 1 commit into
canaryfrom
feat/e2e-crypto-primitives
Apr 29, 2026
Merged

joelteply merged 1 commit into
canaryfrom
feat/e2e-crypto-primitives

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

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)

  • X25519 ECDH (RFC 7748) — pairwise key agreement
  • HKDF-SHA256 (RFC 5869) — key derivation with `info` for domain separation
  • ChaCha20-Poly1305 AEAD (RFC 8439) — 12-byte nonce
  • 64-bit counter nonce encoder — replay-defense primitive
  • Truncated SHA-256 fingerprint — for invite-string display
  • URL-safe base64 helpers — JSON-envelope friendly

Adaptability (Joel's brief: "crypto can adapt to new ECDSA etc")

  • bytes-in / bytes-out interfaces → swap X25519 for X448 or PQ primitives by editing one function body
  • HKDF `info` string → migrate v1→v2 without breaking deployed peers on old keys
  • AEAD AD field → binds plaintext envelope metadata so swapping ChaCha for AES-GCM is wire-compatible

Test plan

  • venv-dev with cryptography installed: 32/32 pass in 15ms
  • system python without cryptography: 32/32 skip cleanly (graceful degradation; install.sh venv setup lands in E.2)
  • Existing bearer test suite (91 tests) unaffected by this PR
  • CI clean-install matrix

Coverage (32 tests)

Suite n What
X25519KeypairTests 6 generate, save/load round-trip, 0o600 mode, atomic write, length validation
ECDHDeriveTests 4 both peers derive same key, different pairs differ, info domain-separates
AEADTests 7 round-trip, AD authenticated, ct/nonce tampering fails, length validation
CounterNonceTests 4 round-trip, negative/overflow rejection, non-counter parse-rejection
FingerprintTests 5 deterministic, different keys → different, length validation
B64Tests 5 round-trip, no padding, URL-safe alphabet, unpadded decode
FullPairwiseScenarioTests 1 end-to-end Alice→Bob+Mallory: actual airc use case shape

Notes

  • No call sites yet — purely additive. E.2 wires into identity bootstrap + pair handshake; E.3 into cmd_send + monitor_formatter. After E.3 lands, transport-encryption becomes redundant and Phase 3c deletes SshBearer + Tailscale wholesale.
  • Existing tests skip cleanly on a fresh checkout without venv. `make test` / `integration.sh python_units` still passes the same way it did before this PR.

🤖 Generated with Claude Code

…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]>
Copilot AI review requested due to automatic review settings April 29, 2026 04:10
@joelteply
joelteply merged commit 9375850 into canary Apr 29, 2026
8 checks passed
@joelteply
joelteply deleted the feat/e2e-crypto-primitives branch April 29, 2026 04:12

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

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.py implementing keygen, ECDH+HKDF key derivation, AEAD encrypt/decrypt, counter nonces, fingerprints, and URL-safe base64 helpers.
  • Adds test/test_crypto.py covering the new crypto primitives with skip-on-missing-cryptography behavior.
  • Updates .gitignore to 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.

Comment thread lib/airc_core/crypto.py
Comment on lines +269 to +271
all do this)."""
if len(pub_raw) != 32:
raise ValueError("X25519 pubkey must be 32 bytes")

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Suggested change
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")

Copilot uses AI. Check for mistakes.
Comment thread lib/airc_core/crypto.py
Comment on lines +285 to +291
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)

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
Comment thread test/test_crypto.py
Comment on lines +29 to +34
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."
)

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Suggested change
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

Copilot uses AI. Check for mistakes.
Comment thread lib/airc_core/crypto.py
Comment on lines +285 to +292
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)

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
Comment thread lib/airc_core/crypto.py
path + ".tmp", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode
)
try:
os.write(fd, data)

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

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

_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.

Suggested change
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

Copilot uses AI. Check for mistakes.
Comment thread lib/airc_core/crypto.py
Comment on lines +307 to +309
fd = os.open(
path + ".tmp", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode
)

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
Comment thread lib/airc_core/crypto.py
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."""

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

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

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).

Suggested change
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}"
)

Copilot uses AI. Check for mistakes.
Comment thread lib/airc_core/crypto.py
Comment on lines +152 to +153
(None per HKDF spec) — both peers' identities are already in the
info string and the ECDH shared secret is high-entropy.

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Suggested change
(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.

Copilot uses AI. Check for mistakes.
joelteply added a commit that referenced this pull request Apr 29, 2026