Skip to content

feat(core): M4 — authentication: publickey Ed25519, authorized_keys, audit events - #78

Merged
gonzafg2 merged 8 commits into
mainfrom
feat/m4-auth
Jun 15, 2026
Merged

gonzafg2 merged 8 commits into
mainfrom
feat/m4-auth

Conversation

@gonzafg2

Copy link
Copy Markdown
Owner

M4 — Authentication (RFC 4252 §7)

Implementa la autenticación publickey Ed25519 del walking skeleton (Phase 1).

Archivos

Archivo Cambio
crates/quantumssh-core/src/auth.rs Nuevo — AuthorizedKeys, auth_signed_data, verify_auth_signature, payload builders
crates/quantumssh-core/src/transport.rs +457 líneas — ServiceResponse.accept(), UserAuth.authenticate(), AuthAccepted.reject_channel_open()
crates/quantumssh-core/src/server.rs Config.authorized_keys, nuevo flow en run_connection
crates/quantumssh-core/src/lib.rs pub mod auth;
crates/quantumssh/src/main.rs Flag --authorized-keys, carga startup
crates/quantumssh-core/tests/accept.rs +5 tests de integración M4
docs/plans/m4-authentication.md Plan de implementación

Verificación

  • cargo fmt --all -- --check ✓
  • cargo clippy --workspace --all-targets -- -D warnings ✓
  • cargo test --workspace (71 unit + 13 integration) ✓
  • cargo build --workspace --release ✓

Decisiones

  • MAX_AUTH_ATTEMPTS = 12 (per-source, no per-user — ADR-0024)
  • Opciones de authorized_keys ignoradas en Phase 1
  • AuthAccepted.reject_channel_open() como terminal M4: envía CHANNEL_OPEN_FAILURE limpio, listo para que M5 reemplace el reject por accept

@opencode-agent

Copy link
Copy Markdown

PR Review: feat(core): M4 — authentication

Verdict: Clean PR. One convention violation, zero security issues. All five MANIFIESTO commitments and threat-model hard rules pass.

CI independently confirmed: cargo clippy --workspace ✅, cargo test --workspace (71 + 13) ✅.


Findings

1. Missing #[must_use] on two public functions (convention, medium)

Rule: AGENTS.md — "Every public function is #[must_use] when it returns a value (even constructors)."

Location: crates/quantumssh-core/src/auth.rs

  • AuthorizedKeys::load (auth.rs:136) — returns Result<Self, AuthError>, no #[must_use]
  • verify_auth_signature (auth.rs:278) — returns Result<(), ()>, no #[must_use]

All other public value-returning functions in the module (lookup, auth_signed_data, build_failure_payload, build_pk_ok, build_success_payload) already carry the attribute. These two are the outliers.


What passes (all hard rules)

Rule Status
No first-party unsafe ✅ unsafe_code = "forbid" — auth.rs and transport.rs grep clean
Only mlkem768x25519-sha256 KEX ✅ unchanged
Zero legacy (RSA/DSA/CBC/password/compression) ✅ Ed25519-only publickey auth; build_failure_payload names only publickey; non-Ed25519 keys → UnsupportedKeyType
No new dependencies ✅ ed25519_dalek, sha2 already present
Fail closed ✅ wrong method/key/sig → FAILURE + auth.failed; exhausted budget → DISCONNECT_BY_APPLICATION
Type-state machine extended, not loosened ✅ UserAuth and AuthAccepted are new stages; no accept-and-branch regression
Audit events ADR-0024 compliant ✅ auth.succeeded: authenticated_identity, user, auth_method; auth.failed: auth_method, failure_count (per-source only — ADR-0024 §2.3 line 62); both on target: "audit"
Key material zeroized ✅ session_id is Zeroizing<[u8; 32]> through all stages; Debug impls use finish_non_exhaustive()
Auth events per-source, not per-user ✅ failure_count per-peer_addr span — no user-enumeration oracle (threat model §5.3.1, ADR-0024)
Server reads authorized_keys at startup, never writes ✅ std::fs::read_to_string in load() only
Pre-auth parse surface unchanged ✅ auth runs after encrypted transport is established

Implementation alignment with plan

The implementation follows docs/plans/m4-authentication.md exactly — stage propagation, audit target, PK_OK probe path, reject_channel_open terminal, MAX_AUTH_ATTEMPTS = 12. Integration tests cover the five M4 scenarios described in the plan.

github run

@opencode-agent

Copy link
Copy Markdown

cargo fmt and cargo clippy both pass. Here is the review.


Review: feat(core): M4 — Authentication (PR #78)

Verdict: Approve. The PR faithfully implements the M4 plan. No new dependencies. All five MANIFIESTO commitments are upheld. The type-state machine is correctly extended with accept(), authenticate(), and reject_channel_open() — each consumes self, preventing any stage confusion. Audit events match ADR-0024.

Findings

1. Hardcoded recipient_channel = 0 in CHANNEL_OPEN_FAILURE — transport.rs:829

RFC 4254 §5.1 requires the recipient_channel field in SSH_MSG_CHANNEL_OPEN_FAILURE to equal the sender_channel from the peer's SSH_MSG_CHANNEL_OPEN. The code writes w.put_uint32(0) unconditionally without parsing the peer's sender channel number. Impact is negligible since the session terminates immediately after, but this is technically non-conformant.

2. Unbounded probe enumeration via PK_OK (accepted per ADR-0024) — transport.rs:771-773

When a probe (signature_present=false) matches a known key, the server sends PK_OK without incrementing failure_count. This lets an attacker enumerate authorized keys without exhausting the MAX_AUTH_ATTEMPTS budget. RFC 4252 permits this behavior, and ADR-0024 (line 40) accepts the enumeration-oracle tradeoff — but operators should be aware that MAX_AUTH_ATTEMPTS = 12 does not bound key-probe rate, only signature-attempt rate.

What's correct

Rule Status
No first-party unsafe (ADR-0018) ✓
Only publickey / ssh-ed25519 (ADR-0021) ✓ — non-methods, non-Ed25519 get FAILURE
Fail closed — peer without PQ/Ed25519 rejected ✓
Key material zeroized (Zeroizing) / Debug safe ✓ — AuthorizedKeys::Debug uses finish_non_exhaustive()
Type-state machine, no accept-and-branch ✓ — ServiceResponse::deny()/accept() both consume self
Audit tier not suppressible, audit target ✓ — auth.succeeded/auth.failed emit on target: "audit"
authenticated_identity on auth.succeeded ✓ — SHA256: fingerprint per ADR-0024
Parser bounds explicit (pre-auth surface, §4.1) ✓ — KEY_BLOB_BOUND=1024, USER_NAME_BOUND=256, etc.
No stubs or placeholder code ✓ — reject_channel_open() is functional, handles all 4 message types
No new dependencies ✓
Unit + integration tests ✓ — 5 new integration tests covering success, wrong sig, non-method, PK_OK flow, MAX_ATTEMPTS

Test summary

cargo fmt --all -- --check     ✓
cargo clippy --workspace       ✓ (0 warnings)
cargo test --workspace         (71 unit + 13 integration, all passing per PR)

The AuthAccepted stage stores authenticated_identity and session_id (marked #[expect(dead_code)]) — these are correctly wired for M5 consumption, not placeholder data.

github run

@gonzafg2
gonzafg2 force-pushed the feat/m4-auth branch 2 times, most recently from 7fe7b1e to 7675951 Compare June 15, 2026 20:06
…audit events

Implementa Phase 1 Milestone 4 (RFC 4252 §7):
- Nuevo modulo auth: AuthorizedKeys parsing (solo ssh-ed25519,
  opciones ignoradas), auth_signed_data, verificacion de firma,
  payload builders.
- Transport type-state extendido: ServiceResponse.accept() ->
  UserAuth.authenticate() (loop, MAX_AUTH_ATTEMPTS=12) ->
  AuthAccepted.reject_channel_open() (terminal M4, channels en M5).
- session_id propagado por los stages cifrados para verificacion
  de firma.
- Server config gana authorized_keys: Arc<AuthorizedKeys>.
- CLI: nuevo flag requerido --authorized-keys <PATH>.
- 15 unit tests (parseo de keys, validacion de blob, fingerprint, KAT).
- 5 integration tests (auth success, firma incorrecta, metodo no
  publickey, PK_OK->success, max attempts -> DISCONNECT).
- host_key::base64_encode_nopad promovido a pub.

ADRs: 0021 (solo ssh-ed25519), 0024 (audit events auth.succeeded /
auth.failed), 0023 (channel scope diferido).

Closes #9 (M4 checklist item).

Signed-off-by: Gonzalo Fleming <[email protected]>
@opencode-agent

Copy link
Copy Markdown

PR Review: feat(core): M4 — authentication

Verdict: Clean PR with two convention violations and one minor observability note. All five MANIFIESTO commitments and threat-model hard rules pass. CI is green (71+13 tests).


Findings

1. Missing #[must_use] on two public functions (convention)

Rule: AGENTS.md — "Every public function is #[must_use] when it returns a value (even constructors)."

Function Location Returns
AuthorizedKeys::load auth.rs:136 Result<Self, AuthError>
verify_auth_signature auth.rs:278 Result<(), ()>

Every other public value-returning function in auth.rs already carries #[must_use] (lookup, auth_signed_data, build_failure_payload, build_pk_ok, build_success_payload). These two are the outliers.


2. Dead helper function in integration tests (convention)

Rule: CLAUDE.md — "No stubs, no mocks, no placeholder code. Everything committed must be functional."

Location: tests/accept.rs:592 — read_sealed_from_server is declared with #[expect(dead_code)] and never called. All test code calls client.read_sealed(&mut stream).await directly.


3. Duplicate connection.closed events from AuthAccepted::reject_channel_open (observability)

AuthAccepted::reject_channel_open() emits warn!("connection.closed", ...) before returning TransportError::Rejected(...). Then handle() in server.rs emits a second info!("connection.closed", ...) from the same error. Two events for one closure — follows the pre-existing pattern of other stages (e.g. ServiceResponse::deny uses "service denied" not "connection.closed"), so these particular arms create a new naming collision.


What passes (all hard rules)

Rule Status
No first-party unsafe ✅ forbid workspace — grep clean
Only mlkem768x25519-sha256 KEX ✅ unchanged
Zero legacy (RSA/DSA/CBC/password/compression) ✅ Ed25519-only; non-Ed25519 → UnsupportedKeyType; password → FAILURE naming only publickey
No new dependencies ✅ ed25519_dalek, sha2 already present
Fail closed ✅ wrong method/key/sig → FAILURE; budget exhausted → DISCONNECT_BY_APPLICATION
Type-state machine extended, not loosened ✅ UserAuth + AuthAccepted are new stages; no accept-and-branch
Audit events ADR-0024 compliant ✅ auth.succeeded: authenticated_identity, user, auth_method; auth.failed: auth_method, failure_count (per-source, no user field — prevents enumeration); both on target: "audit"
Key material zeroized ✅ session_id is Zeroizing<[u8; 32]> through all stages; Debug uses finish_non_exhaustive()
Server reads authorized_keys at startup, never writes ✅ std::fs::read_to_string in load() only
Pre-auth parse surface unchanged ✅ auth runs after encrypted transport is established

Implementation alignment with plan

The implementation follows docs/plans/m4-authentication.md precisely — stage propagation, audit target, PK_OK probe path, reject_channel_open terminal, MAX_AUTH_ATTEMPTS = 12. The auth.succeeded event was sensibly moved from server.rs into transport.rs (co-located with the verification logic), which is cleaner than the plan's sketch. Integration tests cover the five M4 scenarios.

github run

@opencode-agent

Copy link
Copy Markdown

PR Review: feat(core): M4 — authentication (#78)

The PR faithfully implements the M4 plan (docs/plans/m4-authentication.md). No new dependencies, no first-party unsafe, all five MANIFIESTO commitments upheld. The type-state machine is correctly extended — ServiceResponse::accept(), UserAuth::authenticate(), and AuthAccepted::reject_channel_open() each consume self, preventing stage confusion. Audit events match ADR-0024.


Findings

1. Missing #[must_use] on two public functions — convention violation (medium)

Rule: AGENTS.md — "Every public function is #[must_use] when it returns a value (even constructors)."

auth.rs has five public value-returning functions with #[must_use] (lookup:244, auth_signed_data:263, build_failure_payload:291, build_pk_ok:301, build_success_payload:311). Two are missing it:

  • AuthorizedKeys::load — auth.rs:136 — returns Result<Self, AuthError>
  • verify_auth_signature — auth.rs:278 — returns Result<(), ()>

2. Hardcoded recipient_channel = 0 in CHANNEL_OPEN_FAILURE — RFC 4254 §5.1 non-conformance (low)

transport.rs:829: w.put_uint32(0) writes a hardcoded channel number. RFC 4254 §5.1 requires this field to equal the peer's sender_channel from their SSH_MSG_CHANNEL_OPEN. The server should parse the channel-open to extract the peer's sender channel number and echo it back. Impact is negligible since the session terminates immediately after, but this is technically non-conformant.

3. PK_OK probe path does not increment failure_count — accepted design tradeoff (informational)

transport.rs:771-773: when a probe (signature_present=false) matches a known key, the server sends PK_OK without incrementing failure_count. This lets an attacker enumerate authorized keys without exhausting the MAX_AUTH_ATTEMPTS budget. RFC 4252 permits this, and ADR-0024 (line 40) accepts the enumeration-oracle tradeoff — but operators should know that the attempt budget bounds signature-attempt rate only, not probe rate.


What passes (all hard rules)

Rule Status
No first-party unsafe (unsafe_code = "forbid") ✓ auth.rs + transport.rs grep clean
Only mlkem768x25519-sha256 KEX ✓ unchanged
Zero legacy (no RSA/DSA/CBC/password/compression) ✓ Ed25519-only publickey; non-Ed25519 → UnsupportedKeyType
No new dependencies ✓ ed25519_dalek, sha2 already present
Fail closed ✓ wrong method/key/sig → FAILURE + auth.failed; exhausted budget → DISCONNECT_BY_APPLICATION
AEAD-only, keys zeroized ✓ session_id is Zeroizing<[u8; 32]> through all stages
Type-state machine, no accept-and-branch ✓ accept(), authenticate(), reject_channel_open() consume self
Audit events ADR-0024 compliant ✓ auth.succeeded: authenticated_identity, user, auth_method; auth.failed: auth_method, failure_count; both on target: "audit"
Pre-auth parse bounds explicit ✓ KEY_BLOB_BOUND=1024, USER_NAME_BOUND=256, etc.
No stubs or placeholder code ✓ reject_channel_open() handles all 4 message types
Debug never leaks key material ✓ AuthorizedKeys::Debug uses finish_non_exhaustive()

github run

@opencode-agent

Copy link
Copy Markdown

Review: feat(core): M4 — authentication (PR #78)

Verdict: Approve with two minor convention nits. Zero security issues. The type-state machine is correctly extended, audit events comply with ADR-0024, no MANIFIESTO commitments are broken. Both prior independent reviews agree.


Findings

1. Missing #[must_use] on two public value-returning functions (convention — AGENTS.md)

Rule: "Every public function is #[must_use] when it returns a value (even constructors)."

Function Location Return type
AuthorizedKeys::load auth.rs:136 Result<Self, AuthError>
verify_auth_signature auth.rs:278 Result<(), ()>

All other public value-returning functions in the module (lookup, auth_signed_data, build_failure_payload, build_pk_ok, build_success_payload) carry the attribute. These two are the outliers.

2. Hardcoded recipient_channel = 0 in CHANNEL_OPEN_FAILURE (RFC conformance — low)

Location: transport.rs:828

RFC 4254 §5.1 requires recipient_channel to equal the sender_channel from the peer's SSH_MSG_CHANNEL_OPEN. The code unconditionally writes w.put_uint32(0) without parsing the peer's channel number. Impact is negligible — the connection terminates immediately after — but technically non-conformant. M5 will replace this entirely.


What passes (all hard rules, verified independently)

Commitment Status
No first-party unsafe (unsafe_code = "forbid") ✅ auth.rs / transport.rs grep clean
Only mlkem768x25519-sha256 KEX ✅ KEX profile unchanged
Zero legacy (RSA/DSA/CBC/password/compression) ✅ Ed25519-only; non-methods → FAILURE naming only publickey; non-Ed25519 → UnsupportedKeyType
No new dependencies ✅ ed25519_dalek, sha2 already in workspace
Fail closed ✅ Wrong method/key/sig → SSH_MSG_USERAUTH_FAILURE; exhausted budget → DISCONNECT_BY_APPLICATION (11); no downgrade path
Type-state machine extended, not loosened ✅ ServiceResponse::accept(), UserAuth::authenticate(), AuthAccepted::reject_channel_open() all consume self
Audit events ADR-0024 compliant ✅ auth.succeeded: authenticated_identity (SHA256 fingerprint), user, auth_method; auth.failed: auth_method, failure_count (per-source span); both on target: "audit"
Pre-auth surface unchanged ✅ Auth runs after encrypted transport established; all parser bounds explicit (KEY_BLOB_BOUND=1024, etc.)
Key material zeroized / Debug-safe ✅ session_id: Zeroizing<[u8; 32]> through all stages; AuthorizedKeys::Debug uses finish_non_exhaustive()
No stubs or placeholder code ✅ AuthAccepted stores session_id and authenticated_identity for M5 (dead_code expected, not placeholder)
Server reads authorized_keys, never writes ✅ std::fs::read_to_string at startup only

Implementation fidelity to plan

The implementation follows docs/plans/m4-authentication.md exactly — stage propagation, audit target, PK_OK probe path, reject_channel_open terminal, MAX_AUTH_ATTEMPTS = 12. Integration tests cover all five M4 scenarios.

github run

@opencode-agent

Copy link
Copy Markdown

PR Review: feat(core): M4 — authentication

Verdict: Approve with two convention nits. The implementation faithfully follows the M4 plan. No security issues. All five MANIFIESTO commitments and threat-model hard rules pass.


Findings

1. Missing #[must_use] on two public functions (convention — already flagged in prior reviews)

Rule: AGENTS.md — "Every public function is #[must_use] when it returns a value (even constructors)."

Function Location Returns
AuthorizedKeys::load auth.rs:136 Result<Self, AuthError>
verify_auth_signature auth.rs:278 Result<(), ()>

All other public value-returning functions in auth.rs (lookup, auth_signed_data, build_failure_payload, build_pk_ok, build_success_payload) carry the attribute. These two are the outliers.


2. Hardcoded recipient_channel = 0 violates RFC 4254 §5.1 (cosmetic, no runtime impact)

Location: transport.rs:829

RFC 4254 §5.1 requires SSH_MSG_CHANNEL_OPEN_FAILURE's recipient_channel to echo the sender_channel from the peer's SSH_MSG_CHANNEL_OPEN. The code writes w.put_uint32(0) unconditionally without parsing the peer's field. Since the session terminates immediately after, this is a protocol-conformance issue with no observable effect — but it's technically a deviation. Fixing it would require parsing the sender_channel from the channel-open message before constructing the reply.


3. base64_encode_nopad visibility widened from pub(crate) to pub (host_key.rs:185)

This is legitimate — auth.rs in quantumssh-core calls it. However, it now leaks a crate-internal encoding utility into the public API surface. Consider re-exporting through auth or keeping a pub(crate) re-export path to avoid polluting the public API of host_key. Low priority.


What passes (all hard rules)

Rule Status
No first-party unsafe (ADR-0018) auth.rs and transport.rs grep clean
Only mlkem768x25519-sha256 KEX unchanged
Zero legacy Ed25519-only publickey; password/ssh-rsa correctly rejected; UnsupportedKeyType for non-Ed25519 in authorized_keys
No new dependencies ed25519_dalek, sha2 already present
Fail closed wrong method/key/sig → FAILURE; budget exhaustion → DISCONNECT_BY_APPLICATION
Type-state machine extended, not loosened ServiceResponse::accept(), UserAuth::authenticate(), AuthAccepted::reject_channel_open() all consume self
Audit events ADR-0024 compliant auth.succeeded: authenticated_identity, user, auth_method; auth.failed: auth_method, failure_count; both on target: "audit"
Key material zeroized session_id is Zeroizing<[u8; 32]> through all stages; Debug uses finish_non_exhaustive()
Auth events per-source, not per-user failure_count per-peer_addr — no user-enumeration oracle
Server reads authorized_keys at startup, never writes std::fs::read_to_string only
Pre-auth parse surface unchanged auth runs after encrypted transport established
No stubs reject_channel_open() is functional; authenticated_identity stored for M5 consumption with #[expect(dead_code)] — not placeholder

PK_OK probe enumeration (accepted tradeoff per ADR-0024)

Probe requests (signature_present=false) that match a known key send PK_OK without incrementing failure_count (transport.rs:771-773). This permits unbounded key-probe enumeration. ADR-0024 accepts this tradeoff; MAX_AUTH_ATTEMPTS = 12 bounds only signature-attempt rate, not probe rate. This is correctly documented and intentional.

github run

Fixes from all five automated reviews:

1. Add #[must_use] to AuthorizedKeys::load and verify_auth_signature
   (AGENTS.md convention), with #[allow(clippy::double_must_use)] for
   Result types that already carry the attribute.

2. Parse sender_channel from CHANNEL_OPEN and echo it as
   recipient_channel in CHANNEL_OPEN_FAILURE (RFC 4254 §5.1).

3. Remove unused read_sealed_from_server helper from integration tests
   (CLAUDE.md: no stubs, no placeholder code).

4. Rename log event in reject_channel_open from "connection.closed"
   to "channels land in M5" to avoid duplicate events with handle()
   in server.rs.

5. Keep base64_encode_nopad as pub (integration test consumers).

Signed-off-by: Gonzalo Fleming <[email protected]>
@opencode-agent

Copy link
Copy Markdown

PR Review: feat(core): M4 — authentication (#78)

Verdict: Approve with one convention note. The implementation faithfully follows the M4 plan. CI green — clippy 0 warnings, 71+13 tests pass, no unsafe. All five MANIFIESTO commitments and threat-model hard rules pass.

The two issues flagged in prior reviews (#[must_use] on load/verify_auth_signature, and hardcoded recipient_channel = 0) are already resolved in the current code.


Finding: base64_encode_nopad unnecessarily widened from pub(crate) to pub (API surface — low)

Rule: CLAUDE.md §4 — "Small surface, sharp edges."

Location: host_key.rs:185

The change from pub(crate) fn base64_encode_nopad → pub fn base64_encode_nopad leaks a crate-internal encoding utility into the library's public API. auth.rs (same crate) could access it at pub(crate) visibility. This is the only line changed in host_key.rs — the doc comment was updated to mention the authorized_keys usage, but the visibility change isn't needed for that.


What passes (all hard rules)

Rule Status
No first-party unsafe (forbid) ✅ grep clean on auth.rs + transport.rs
Only mlkem768x25519-sha256 KEX ✅ unchanged
Zero legacy (RSA/DSA/CBC/password/compression) ✅ Ed25519-only; non-Ed25519 → UnsupportedKeyType; non-methods → FAILURE naming only publickey
No new dependencies ✅ ed25519_dalek, sha2 already in workspace
Fail closed ✅ wrong method/key/sig → FAILURE; budget exhaustion → DISCONNECT_BY_APPLICATION (11)
Type-state machine extended, not loosened ✅ accept(), authenticate(), reject_channel_open() all consume self
Audit events ADR-0024 compliant ✅ auth.succeeded: authenticated_identity, user, auth_method; auth.failed: auth_method, failure_count (per-source, no user — prevents enumeration oracle); both on target: "audit"
Key material zeroized / Debug-safe ✅ session_id: Zeroizing<[u8; 32]> through all stages; AuthorizedKeys::Debug finish_non_exhaustive()
Recipient channel RFC 4254 §5.1 ✅ sender_channel parsed from peer's CHANNEL_OPEN, echoed back
(#[must_use]) on all public value-returning functions ✅ load, verify_auth_signature, lookup, etc. all carry the attribute
No stubs or dead code ✅ reject_channel_open() is functional; authenticated_identity stored for M5 with #[expect(dead_code)]

github run

Comment thread crates/quantumssh-core/src/auth.rs Resolved
Comment thread crates/quantumssh-core/src/auth.rs Resolved
Comment thread crates/quantumssh-core/src/auth.rs Resolved
Comment thread crates/quantumssh-core/src/transport.rs Resolved
@opencode-agent

Copy link
Copy Markdown

Here is my review of PR #78: feat(core): M4 — authentication.


Review: feat(core): M4 — authentication (PR #78)

Verdict: Request changes. One critical pre-auth parser bug blocks approval. Two medium-threat findings. All five MANIFIESTO commitments otherwise pass. 71+13 tests green, clippy clean.


Finding 1 (Critical — threat model §4.1): authorized_keys parser rejects valid keys when option values contain "ssh-"

Rule: CLAUDE.md — "The pre-authentication path is the highest-trust surface … Parser changes get extra scrutiny."

Location: crates/quantumssh-core/src/auth.rs:151

let Some(key_start) = trimmed.find("ssh-") else {

str::find is a substring search. In a perfectly valid entry like:

command="/usr/bin/ssh-agent" ssh-ed25519 AAAA… user@host

find("ssh-") matches inside the option value ssh-agent, so key_start points into the command string, not at ssh-ed25519:

  • remainder → ssh-agent" ssh-ed25519 AAAA…
  • tokens.next() → ssh-agent" (not ssh-ed25519)
  • Result: AuthError::UnsupportedKeyType

Because load() is called at startup (main.rs:230) and the error is fatal, the server refuses to boot on valid authorized_keys files. The command option is standard in OpenSSH deployments (forced commands for CI bots, git shells, backup agents), making this a realistic breakage.

The existing test ignore_options_before_key (auth.rs:368) uses command="dump",no-agent-forwarding — no "ssh-" in option values — so this path is untested.

Fix: Replace the substring search with token-level scanning via split_whitespace():

let mut tokens = trimmed.split_whitespace();
let algo = tokens
    .find(|&tok| tok.starts_with("ssh-"))
    .ok_or_else(|| AuthError::MalformedLine {
        line: line_no,
        reason: "no key type found".into(),
    })?;
if algo != KEY_ALGORITHM {
    return Err(AuthError::UnsupportedKeyType {
        line: line_no,
        found: algo.into(),
    });
}
let b64 = tokens.next().ok_or_else(|| /* ... */)?;

split_whitespace() produces tokens ["command=\"/usr/bin/ssh-agent\"", "ssh-ed25519", "AAAA…", "user@host"] — the option value is a single token, starts_with("ssh-") correctly skips it. The iterator is consumed through the key type, so the next .next() correctly returns the base64 blob.

Also add a regression test:

#[test]
fn ignore_option_value_containing_ssh_prefix() {
    let signing = SigningKey::from_bytes(&[50u8; 32]);
    let blob = build_ed25519_blob(&signing.verifying_key());
    let b64 = host_key::base64_encode_nopad(&blob);
    let content = format!("command=\"/usr/bin/ssh-agent\" ssh-ed25519 {b64} test\n");
    let path = temp_authorized_keys(&content);
    let keys = AuthorizedKeys::load(&path).expect("load");
    assert_eq!(keys.keys.len(), 1);
}

Finding 2 (Medium — threat model §4.3): AuthorizedKey derives Debug, exposing key material

Rule: CLAUDE.md — "Debug implementations never expose key material … use finish_non_exhaustive() or show only the fingerprint."

Location: crates/quantumssh-core/src/auth.rs:95

#[derive(Debug)]
pub struct AuthorizedKey {
    pub blob: Vec<u8>,
    pub fingerprint: String,
    pub verifying_key: VerifyingKey,
}

The #[derive(Debug)] prints blob and verifying_key bytes. While the outer AuthorizedKeys::Debug correctly uses finish_non_exhaustive(), the inner struct is independently Debug-able. Since AuthorizedKey is pub and returned by lookup(), a consumer could format it and leak key material.

Fix: Replace with manual Debug:

impl fmt::Debug for AuthorizedKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AuthorizedKey")
            .field("fingerprint", &self.fingerprint)
            .finish_non_exhaustive()
    }
}

Finding 3 (Low — CLAUDE.md commitment 4): base64_encode_nopad unnecessarily pub

Rule: CLAUDE.md — "Small surface, sharp edges."

Location: crates/quantumssh-core/src/host_key.rs:185

The visibility change pub(crate) → pub on base64_encode_nopad leaks a crate-internal encoding utility into the public API. auth.rs lives in the same crate and could access it at pub(crate). No justification for the API expansion is in the PR.


What passes (all hard rules)

Rule Status
No first-party unsafe (forbid) grep clean
Only mlkem768x25519-sha256 KEX unchanged
Zero legacy Ed25519-only; non-methods → FAILURE; non-Ed25519 → UnsupportedKeyType
No new dependencies ed25519_dalek, sha2 already in workspace
Fail closed wrong key/sig → FAILURE; budget exhausted → DISCONNECT (11)
Type-state machine extended, not loosened accept(), authenticate(), reject_channel_open() all consume self
Audit events ADR-0024 compliant auth.succeeded: authenticated_identity, auth_method; auth.failed: auth_method, failure_count; both on target: "audit"
Key material zeroized session_id: Zeroizing<[u8; 32]> through all stages
recipient_channel RFC 4254 §5.1 sender_channel parsed from peer, echoed back
#[must_use] on all public value-returning fns load, verify_auth_signature, etc. all present
No stubs AuthAccepted stores authenticated_identity for M5 with #[expect(dead_code)]
Server reads authorized_keys, never writes std::fs::read_to_string at startup only

github run

Comment thread crates/quantumssh-core/src/transport.rs Resolved
Comment thread crates/quantumssh-core/src/auth.rs Resolved
Comment thread crates/quantumssh-core/src/transport.rs Resolved
Comment thread docs/plans/m4-authentication.md Resolved
Comment thread crates/quantumssh-core/src/auth.rs Resolved
…tion

- Replace find("ssh-") substring search with token-based scan to avoid
  matching inside option values (e.g. command="/usr/bin/ssh-agent")
- Add regression test for option values containing ssh- prefix
- Wrap auth_signed_data return in Zeroizing<Vec<u8>> (threat model §4.3)
- Validate service_name == "ssh-connection" per RFC 4252 §6
- Remove placeholder session_id/authenticated_identity from AuthAccepted
- Replace AuthorizedKey #[derive(Debug)] with manual impl (fingerprint only)
- Fix MAX_AUTH_ATTEMPTS doc comment (ADR-0024 was incorrectly cited)
- Fix docs/plans inconsistency: 20 → MAX_AUTH_ATTEMPTS + 1 intentos

Signed-off-by: Gonzalo Fleming <[email protected]>
@gonzafg2

Copy link
Copy Markdown
Owner Author

Summary of Claude review fixes (d1a5fb0)

All 9 inline review comments from Claude[bot] addressed:

# Finding Fix
🔴 P0 Parser find("ssh-") matches inside option values split_whitespace() + starts_with("ssh-") token scan + regression test
🟠 P1 auth_signed_data returns non-zeroized Vec<u8> Return type changed to Zeroizing<Vec<u8>>
🟠 P2 service_name never validated Validated against "ssh-connection" (RFC 4252 §6)
🟡 P3 Placeholder fields in AuthAccepted session_id and authenticated_identity removed (re-introduced in M5)
🟡 P4 ADR-0024 incorrectly cited for MAX_AUTH_ATTEMPTS Comment now justifies 12 independently; ADR-0024 cited only for per-source semantics
🟡 — AuthorizedKey #[derive(Debug)] leaks key material Manual Debug impl showing only fingerprint
🟡 P5 Planning doc inconsistency (20 vs 12) + governance Fixed MAX_AUTH_ATTEMPTS + 1; docs/plans/ category deferred to separate issue

Verification: cargo fmt --check ✓, cargo clippy (0 warnings) ✓, cargo test (72 unit + 13 integration) ✓, cargo build --release ✓

@opencode-agent

Copy link
Copy Markdown

Review: feat(core): M4 — authentication (PR #78, post-fixup d1a5fb0)

Verdict: Approve. The d1a5fb0 fixup resolved all critical and medium findings flagged by prior reviews. Zero security issues remain. All five MANIFIESTO commitments and threat-model hard rules pass. 72 unit + 13 integration tests green, clippy clean.


What's been fixed (verified against current code)

# Prior finding Fix Verified at
P0 Parser find("ssh-") fooled by option values split_whitespace() token scan + regression test auth.rs:164
P1 auth_signed_data returns non-zeroized Vec<u8> Return type Zeroizing<Vec<u8>> auth.rs:273
P1 service_name never validated Checked against "ssh-connection" transport.rs:595
P2 AuthorizedKey #[derive(Debug)] leaks key material Custom Debug showing only fingerprint auth.rs:110
P3 Placeholder fields in AuthAccepted Removed; struct now only holds rx/tx ciphers transport.rs:160
-- #[must_use] missing on load + verify_auth_signature Both carry #[must_use] auth.rs:148,286
-- Hardcoded recipient_channel = 0 Parses sender_channel from peer, echoes it transport.rs:820
-- ADR-0024 cited for MAX_AUTH_ATTEMPTS Comment now justifies 12 independently auth.rs const

Remaining finding (low)

base64_encode_nopad unnecessarily pub — host_key.rs:185

Rule: CLAUDE.md commitment 4 — "Small surface, sharp edges."

The visibility change pub(crate) → pub leaks a crate-internal encoding utility into the library's public API. auth.rs lives in the same crate and accesses it just fine at pub(crate). No justification for the API expansion appears in the PR.

Also noted: docs/plans/m4-authentication.md lives outside CLAUDE.md's three defined document categories (docs/rfcs/, docs/adr/, PR/issues). The author acknowledged this and deferred the governance discussion to a separate issue. Not blocking.


What passes (all hard rules)

Rule Status
No first-party unsafe (forbid) grep clean on auth.rs + transport.rs
Only mlkem768x25519-sha256 KEX unchanged
Zero legacy Ed25519-only; non-methods → FAILURE; non-Ed25519 → UnsupportedKeyType
No new dependencies ed25519_dalek, sha2 already in workspace
Fail closed wrong key/sig → FAILURE; budget exhaustion → DISCONNECT (11)
Type-state machine extended, not loosened accept(), authenticate(), reject_channel_open() all consume self
Audit events ADR-0024 compliant auth.succeeded: authenticated_identity; auth.failed: auth_method, failure_count (per-source); both target: "audit"
Key material zeroized session_id: Zeroizing<[u8; 32]> through all stages; auth_signed_data → Zeroizing<Vec<u8>>
recipient_channel RFC 4254 §5.1 sender_channel parsed, echoed
Debug never leaks key material AuthorizedKey / AuthorizedKeys use finish_non_exhaustive()
#[must_use] on all public value-returning fns load, verify_auth_signature, lookup, auth_signed_data, builders all carry it
No stubs AuthAccepted has only ciphers; no #[expect(dead_code)]
Pre-auth parse surface bounded KEY_BLOB_BOUND=1024, USER_NAME_BOUND=256, etc.

github run

Comment thread crates/quantumssh-core/src/auth.rs Resolved
Comment thread crates/quantumssh-core/src/auth.rs Resolved
The signature field in SSH_MSG_USERAUTH_REQUEST uses a nested wire
encoding: string("ssh-ed25519") + string(raw_64_byte_sig). The server
was passing the outer blob directly to Signature::from_slice(), which
expects exactly 64 bytes and rejects real clients.

- Add inner parse in authenticate() to unwrap algo + raw sig before verify
- Update signed_auth_request test helper to emit RFC-conformant encoding
- Fix auth_failure_on_wrong_signature and max_auth_attempts test payloads

Signed-off-by: Gonzalo Fleming <[email protected]>
@opencode-agent

Copy link
Copy Markdown

All prior critical findings (P0 parser bug, P1 auth data zeroizing, signature unwrap, #[must_use], placeholder fields, recipient_channel echo, ADR citation) are resolved in the current code. Two low-signal governance findings remain:


Review: feat(core): M4 — authentication (PR #78, post-fixups)

Verdict: Approve. Zero security issues. All five MANIFIESTO commitments and every threat-model hard rule pass. 72 unit + 13 integration tests green, clippy clean.


Findings

1. base64_encode_nopad unnecessarily pub — API surface expansion (low)

Rule: CLAUDE.md commitment 4 — "Small surface, sharp edges." AGENTS.md — "Reject unjustified dependencies and scope creep."

Location: crates/quantumssh-core/src/host_key.rs:185

The visibility change pub(crate) → pub leaks a crate-internal encoding utility into the library's public API. auth.rs lives in the same crate and can access it at pub(crate). No justification for the API expansion appears in the PR. Consider reverting to pub(crate) or re-exporting through auth to avoid widening the library's surface.

2. docs/plans/m4-authentication.md — undefined governance lane (low)

Rule: CLAUDE.md lines 75-87 — three document categories exist: RFC (docs/rfcs/), ADR (docs/adr/), and plain PR/issue. docs/plans/ has no governance contract (immutability, review process, authoritative status). CLAUDE.md line 136 — "everything committed must be functional" — the plan contains pseudocode, stub signatures, and an internal inconsistency (MAX_AUTH_ATTEMPTS + 1 fix was only partial).

The author deferred this to a separate issue. Not blocking, but the doc should either migrate to docs/adr/ (if recording a locked-in decision) or stay in the PR description.


What passes (all hard rules)

Rule Status
No first-party unsafe (forbid workspace) grep clean on all changed files
Only mlkem768x25519-sha256 KEX unchanged
Zero legacy (RSA/DSA/CBC/password/compression) Ed25519-only; non-methods → FAILURE naming only publickey; non-Ed25519 → UnsupportedKeyType
No new dependencies ed25519_dalek, sha2, zeroize already in workspace
Fail closed wrong method/key/sig → FAILURE; budget exhausted → DISCONNECT (11)
Type-state machine extended, not loosened accept(), authenticate(), reject_channel_open() each consume self
Pre-auth parser bounded find("ssh-") bug fixed → split_whitespace() token scan + regression test; SERVICE_NAME_BOUND=64, KEY_BLOB_BOUND=1024, etc.
Audit events ADR-0024 compliant auth.succeeded: authenticated_identity, user, auth_method; auth.failed: auth_method, failure_count (per-source, no user); both on target: "audit"
Key material zeroized auth_signed_data → Zeroizing<Vec<u8>>; session_id is Zeroizing<[u8; 32]> through all stages
Debug never leaks keys AuthorizedKey/AuthorizedKeys use finish_non_exhaustive()
RFC 8709 §6 signature unwrap authenticate() unwraps string(algo) + string(raw_sig) before verify_auth_signature; test helper signed_auth_request emits RFC-conformant format
recipient_channel RFC 4254 §5.1 sender_channel parsed from peer, echoed
#[must_use] on all public value-returning fns load, verify_auth_signature, lookup, auth_signed_data, builders all carry it
No stubs AuthAccepted holds only ciphers; no #[expect(dead_code)]
service_name validated checked against "ssh-connection" (RFC 4252 §6)
Server reads authorized_keys, never writes std::fs::read_to_string at startup only

github run

Comment thread crates/quantumssh-core/src/transport.rs Resolved
@claude

claude Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

Code review

1 issue found. Checked for bugs and CLAUDE.md compliance.

Pre-auth parse inconsistency — sig_present silently swallows parse errors

In crates/quantumssh-core/src/transport.rs line 631, let sig_present = r.boolean().unwrap_or(false); is the only field in the pre-auth parse loop that silently defaults on failure instead of rejecting the connection.

Every adjacent field (service_name, method, key_algorithm, key_blob, signature) uses the strict pattern:

let Ok(x) = r.string(...) else {
    return Err(self.reject_sealed(protocol_error("malformed-userauth-request")).await);
};

CLAUDE.md requires fail-closed behaviour on the pre-authentication path — the highest-trust surface (§4.1). While not exploitable in isolation (a truncated-at-boolean packet is rejected by the next key_algorithm parse since the reader cursor is exhausted), this deviates from the explicit defensive convention applied to every other field in the same block.

Fix: replace unwrap_or(false) with the standard reject pattern:

let Ok(sig_present) = r.boolean() else {
    return Err(self.reject_sealed(protocol_error("malformed-userauth-request")).await);
};

See inline comment: #78 (comment)

r.boolean().unwrap_or(false) silently defaulted on parse failure,
violating the fail-closed convention applied to every other field
in the pre-auth authentication loop (CLAUDE.md §4.1).

Signed-off-by: Gonzalo Fleming <[email protected]>
@opencode-agent

Copy link
Copy Markdown

Review: feat(core): M4 — authentication (PR #78, post-fixups)

Verdict: Approve. All critical and medium findings from prior reviews are resolved. Zero security issues. All five MANIFIESTO commitments and threat-model hard rules pass. 72 unit + 13 integration tests green, clippy clean.


Findings

1. base64_encode_nopad visibility widened to pub — API surface growth (low)

Rule: CLAUDE.md commitment 4 — "Small surface, sharp edges."

Location: crates/quantumssh-core/src/host_key.rs:185

The change from pub(crate) to pub leaks a crate-internal encoding utility into the public API. Justified by integration test usage (tests/accept.rs:316 needs pub), but the companion base64_decode remains pub(crate) — the asymmetry is notable. Consider #[doc(hidden)] or a pub use re-export from a test_helpers module to signal that this is not part of the library's stable interface.

2. docs/plans/m4-authentication.md — undefined governance lane (low)

Rule: CLAUDE.md lines 75-87 — three document categories exist: RFC, ADR, and plain PR/issue. docs/plans/ has no governance contract (immutability, review process, authoritative status). The plan contains pseudocode and stub signatures inconsistent with the "everything committed must be functional" rule. Author acknowledged and deferred to a separate issue. Not blocking.

3. Duplicate connection.closed events from reject_channel_open (observability, low)

transport.rs:872 and transport.rs:876 emit warn!("connection.closed", ...) from AuthAccepted::reject_channel_open(), then server.rs:129 emits a second info!("connection.closed", ...) from handle(). Two events with identical name for the same closure — consider using distinct event names for the inner paths (as the channel open arm already does with "channels land in M5").


What passes (all hard rules)

Rule Status
No first-party unsafe (forbid workspace) grep clean on all changed files
Only mlkem768x25519-sha256 KEX unchanged
Zero legacy (RSA/DSA/CBC/password/compression) Ed25519-only; non-methods → FAILURE naming only publickey; non-Ed25519 → UnsupportedKeyType
No new dependencies ed25519_dalek, sha2, zeroize already in workspace
Fail closed wrong method/key/sig → FAILURE; budget exhausted → DISCONNECT (11)
Type-state machine extended, not loosened accept(), authenticate(), reject_channel_open() each consume self
Parser bounds explicit split_whitespace() token scan (fixes find("ssh-") bug); KEY_BLOB_BOUND=1024, etc.
Audit events ADR-0024 auth.succeeded: authenticated_identity, user, auth_method; auth.failed: auth_method, failure_count (per-source, no user); both target: "audit"
Key material zeroized auth_signed_data → Zeroizing<Vec<u8>>; session_id: Zeroizing<[u8; 32]> through all stages
Debug never leaks keys AuthorizedKey/AuthorizedKeys use finish_non_exhaustive()
RFC 4252 §7 sig unwrap authenticate() unwraps string(algo) + string(raw_sig) per RFC 8709 §6
recipient_channel RFC 4254 §5.1 sender_channel parsed from peer, echoed
#[must_use] on all public value-returning fns load, verify_auth_signature, lookup, builders all carry it
Pre-auth reject consistency sig_present uses strict reject pattern (not unwrap_or(false))
No stubs AuthAccepted holds only ciphers; no #[expect(dead_code)]
service_name validated checked against "ssh-connection" (RFC 4252 §6)
Server reads authorized_keys, never writes std::fs::read_to_string at startup only

Prior findings resolved (verified)

Finding Status
P0: Parser find("ssh-") fooled by option values Fixed — split_whitespace() token scan + regression test (auth.rs:165,388)
P1: auth_signed_data returns non-zeroized Vec<u8> Fixed — Zeroizing<Vec<u8>> (auth.rs:273)
P1: service_name never validated Fixed — checked against "ssh-connection" (transport.rs:595)
P1: RFC 4252 §7 sig field not unwrapped Fixed — nested encoding unwrapped (transport.rs:690-712)
P2: AuthorizedKey #[derive(Debug)] leaks keys Fixed — manual Debug with fingerprint only (auth.rs:110)
Placeholder fields in AuthAccepted Fixed — only rx/tx remain (transport.rs:160-163)
#[must_use] missing on load/verify_auth_signature Fixed (auth.rs:148,286)
recipient_channel = 0 hardcoded Fixed — echoes peer's sender_channel (transport.rs:849-852)
sig_present parse inconsistency Fixed — strict reject pattern (transport.rs:631-635)

github run

- Add #[doc(hidden)] to base64_encode_nopad to signal it's not part
  of the stable public API (exposed for integration tests only)
- Rename duplicate connection.closed events in reject_channel_open
  to specific event names (global-request-refused, peer-disconnected)
  so only server.rs handle() emits the canonical connection.closed

Signed-off-by: Gonzalo Fleming <[email protected]>
@opencode-agent

Copy link
Copy Markdown

All CI checks pass: cargo fmt clean, cargo clippy 0 warnings, 72 unit + 13 integration tests green.


Review: feat(core): M4 — authentication (PR #78, post-fixups)

Verdict: Approve. All critical and medium findings from prior reviews are resolved. Zero security issues. All five MANIFIESTO commitments and threat-model hard rules pass.


Findings

1. auth.succeeded emits user field not in ADR-0024 schema (low — ADR conformance)

Rule: ADR-0024 §Events table line 27 — the auth.succeeded event defines fields authenticated_identity, auth_method. ADRs are immutable except Status and errata (ADR-0015).

Location: transport.rs:745-751

info!(
    target: "audit",
    user = %user_name,           // ← not in ADR-0024 schema
    authenticated_identity = %ak.fingerprint,
    auth_method = method,
    "auth.succeeded"
);

The user field is useful context but was not part of the locked-in schema. Either add an erratum to ADR-0024 or remove the field. Not blocking — field is harmless and non-sensitive.


2. base64_encode_nopad remains pub (low — API surface, commitment 4)

Rule: CLAUDE.md commitment 4 — "Small surface, sharp edges."

Location: host_key.rs:189

The function carries #[doc(hidden)] and a comment warning it's not stable API, but is still pub. Integration tests at accept.rs:316 call it — a pub(crate) visibility would serve that use case. The only consumer outside the crate is the test binary, which could use a test_helpers re-export module instead of widening the library's public API.


3. docs/plans/m4-authentication.md — undefined governance lane (low — CLAUDE.md)

Rule: CLAUDE.md lines 75-87 — three document categories exist: RFC (docs/rfcs/), ADR (docs/adr/), and plain PR/issue. docs/plans/ has no governance contract (immutability, review process, authoritative status). Author acknowledged this and deferred to a separate issue. Not blocking.


What passes (all hard rules — independently verified)

Rule Status
No first-party unsafe (forbid workspace) ✓ grep clean on all changed files
Only mlkem768x25519-sha256 KEX ✓ unchanged
Zero legacy (RSA/DSA/CBC/password/compression) ✓ Ed25519-only; non-methods → FAILURE naming only publickey; non-Ed25519 → UnsupportedKeyType
No new dependencies ✓ ed25519_dalek, sha2, zeroize already in workspace
Fail closed ✓ wrong method/key/sig → FAILURE; budget exhausted → DISCONNECT (11)
Type-state machine extended, not loosened ✓ accept(), authenticate(), reject_channel_open() each consume self
Pre-auth parser bounded / correct ✓ split_whitespace() token scan (fixes find("ssh-") bug); KEY_BLOB_BOUND=1024, etc.
Audit events ADR-0024 ✓ auth.succeeded: authenticated_identity, auth_method; auth.failed: auth_method, failure_count (per-source); both target: "audit"
Key material zeroized ✓ auth_signed_data → Zeroizing<Vec<u8>>; session_id: Zeroizing<[u8; 32]> through all stages
Debug never leaks keys ✓ AuthorizedKey/AuthorizedKeys use finish_non_exhaustive()
RFC 4252 §7 / RFC 8709 §6 sig unwrap ✓ authenticate() unwraps nested string(algo) + string(raw_sig)
recipient_channel RFC 4254 §5.1 ✓ sender_channel parsed from peer, echoed
#[must_use] on all public value-returning fns ✓ load, verify_auth_signature, lookup, builders all carry it
Pre-auth reject consistency ✓ sig_present uses strict reject pattern (not unwrap_or(false))
No stubs / placeholder code ✓ AuthAccepted holds only ciphers
service_name validated ✓ checked against "ssh-connection" (RFC 4252 §6)
Server reads authorized_keys, never writes ✓ std::fs::read_to_string at startup only

Prior findings resolved (verified against current code)

Finding Status
P0: Parser find("ssh-") fooled by option values ✓ split_whitespace() token scan + regression test (auth.rs:164,388)
P1: auth_signed_data returns non-zeroized Vec<u8> ✓ Zeroizing<Vec<u8>> (auth.rs:273)
P1: service_name never validated ✓ checked against "ssh-connection" (transport.rs:595)
P1: RFC 4252 §7 sig field not unwrapped ✓ nested encoding unwrapped (transport.rs:690-712)
P2: AuthorizedKey #[derive(Debug)] leaks keys ✓ manual Debug with fingerprint only (auth.rs:110)
Placeholder fields in AuthAccepted ✓ only rx/tx remain (transport.rs:160-163)
#[must_use] missing on load/verify_auth_signature ✓ (auth.rs:148,286)
recipient_channel = 0 hardcoded ✓ echoes peer's sender_channel (transport.rs:849-852)
sig_present parse inconsistency ✓ strict reject pattern (transport.rs:631-635)

github run

ADR-0024 defines auth.succeeded with fields authenticated_identity and
auth_method. The user field was useful context but outside the
locked-in schema.

Signed-off-by: Gonzalo Fleming <[email protected]>
@opencode-agent

Copy link
Copy Markdown

All prior critical (P0) and medium (P1) findings are resolved. The code is in production-ready shape for the pre-alpha phase. Here is my review:


Review: feat(core): M4 — authentication (PR #78, post-fixups)

Verdict: Approve. Zero security issues. All five MANIFIESTO commitments and every threat-model hard rule pass. After multiple rounds of targeted fixes, the code is clean.

Resolved (verified against current HEAD)

# Prior finding Fix location
P0 Parser find("ssh-") fooled by option values auth.rs:164 — token-scan with starts_with("ssh-") + regression test (auth.rs:388)
P1 auth_signed_data non-zeroized Vec<u8> auth.rs:273 — Zeroizing<Vec<u8>> return type
P1 service_name never validated transport.rs:595-599 — checked against "ssh-connection"
P1 RFC 4252 §7 / RFC 8709 §6 sig nested encode not unwrapped transport.rs:690-712 — unwraps string(algo) + string(raw_sig) before verification
P2 AuthorizedKey #[derive(Debug)] leaks key material auth.rs:110-116 — manual Debug, fingerprint only
-- Placeholder fields in AuthAccepted transport.rs:160-163 — only rx/tx remain
-- #[must_use] missing on load/verify_auth_signature auth.rs:148,286 — both carry the attribute
-- recipient_channel = 0 hardcoded transport.rs:848-852 — echoes peer's sender_channel per RFC 4254 §5.1
-- sig_present parse inconsistency transport.rs:631-635 — strict reject pattern, matching every adjacent field
-- ADR-0024 incorrectly cited for MAX_AUTH_ATTEMPTS auth.rs:41-45 — per-source semantics attributed to ADR-0024, value 12 justified independently

Remaining (low — informational only)

1. base64_encode_nopad visibility widened to pub — host_key.rs:189

Rule: CLAUDE.md commitment 4 — "Small surface, sharp edges."

The function carries #[doc(hidden)] and a comment disclaiming it from the stable API, so the surface expansion is de-facto mitigated. Integration tests (accept.rs:316) are the only out-of-crate consumer. Low priority.

2. docs/plans/m4-authentication.md — undefined governance lane

Rule: CLAUDE.md lines 75-87 — three document categories exist: RFC, ADR, and plain PR/issue. docs/plans/ has no governance contract. The author deferred this to a separate issue. Not blocking.

What passes (all hard rules)

Rule Status
No first-party unsafe (forbid workspace) ✅
Only mlkem768x25519-sha256 KEX ✅ unchanged
Zero legacy (RSA/DSA/CBC/password/compression) ✅ Ed25519-only; non-Ed25519 → UnsupportedKeyType; non-publickey → FAILURE
No new dependencies ✅ ed25519_dalek, sha2, zeroize already in workspace
Fail closed ✅ wrong method/key/sig → FAILURE; budget exhausted → DISCONNECT (11)
Type-state machine extended, not loosened ✅ accept(), authenticate(), reject_channel_open() all consume self
Audit events ADR-0024 compliant ✅ auth.succeeded: authenticated_identity, auth_method; auth.failed: auth_method, failure_count (per-source, no user); both target: "audit"
Key material zeroized ✅ auth_signed_data → Zeroizing<Vec<u8>>; session_id: Zeroizing<[u8; 32]> through all stages
Debug never leaks keys ✅ AuthorizedKey/AuthorizedKeys use finish_non_exhaustive()
RFC 4252 §7 / RFC 8709 §6 sig format ✅ nested string(algo) + string(raw_sig) unwrapped before verification; signed_auth_request emits RFC-conformant format
recipient_channel RFC 4254 §5.1 ✅ peer's sender_channel echoed back
#[must_use] on all public value-returning fns ✅ load, verify_auth_signature, lookup, auth_signed_data, all builders
Pre-auth parse bounded ✅ KEY_BLOB_BOUND=1024, USER_NAME_BOUND=256, etc.; all fields strict-reject
No stubs / placeholder code ✅ AuthAccepted holds only ciphers; reject_channel_open() is functional
Server reads authorized_keys, never writes ✅ std::fs::read_to_string at startup only

Integration tests

5 new M4 tests (auth_success_then_channel_rejection, auth_failure_on_wrong_signature, auth_rejects_non_publickey_method, auth_pk_ok_then_signed_succeeds, max_auth_attempts_disconnects) — all exercise the real type-state path: service request → SERVICE_ACCEPT → USERAUTH_REQUEST → verification → terminal. The signed_auth_request helper uses RFC 8709 §6 nested encoding, so these tests validate RFC-conformant wire format.

github run

@gonzafg2

Copy link
Copy Markdown
Owner Author

Response to recurring low-severity findings

1. base64_encode_nopad visibility (pub vs pub(crate))

pub(crate) is not viable: integration tests in tests/accept.rs are a separate crate per Cargo's test model and require pub visibility. #[doc(hidden)] signals the function is not part of the stable public API. A test_helpers re-export module would add architectural indirection for a single-function use case — considered over-engineering for Phase 1. This is an accepted tradeoff documented in the function's doc comment.

2. docs/plans/m4-authentication.md — undefined governance lane

Acknowledged. The docs/plans/ directory was created organically during implementation. A separate issue will be opened to decide whether to migrate this content to an ADR, keep it as a living plan document, or remove it post-merge. This is a process concern, not a code defect, and does not block M4.

Verdict summary: Both items are informational only. No code change needed for this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant