Skip to main content

agentmux_srv/server/
local_proof.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The proof `agentmux-srv open` and a headless srv give each other before `open` asks for anything.
5//! SPEC_HEADLESS_SERVER_PACKAGE_AND_LOCAL_WEB_UI ยง3.
6//!
7//! `open` never sends the key. It sends a fresh nonce; srv answers with its own nonce and a MAC, made
8//! with the key, over both nonces and the address srv is bound to. `open` checks that MAC against the
9//! address it is talking to before it sends anything else, so a listener without the key, or one that
10//! forwards to the real srv from another port, gets nothing it can reuse. Each later request then
11//! carries a MAC of its method, path, body and a rising sequence number, under a key made from the
12//! key and both nonces, and each answer carries one too. Every MAC has its own label, so a MAC made
13//! for one purpose is never valid for another.
14
15use std::collections::HashMap;
16use std::sync::Mutex;
17use std::time::{Duration, Instant};
18
19use agentmux_common::secret_eq::secret_eq;
20use hmac::{Hmac, Mac};
21use sha2::{Digest, Sha256};
22
23pub(crate) const CHANNEL_HEADER: &str = "x-am-channel";
24pub(crate) const SEQ_HEADER: &str = "x-am-seq";
25pub(crate) const PROOF_HEADER: &str = "x-am-proof";
26
27/// A channel lives this long: more than a sign-in takes (a minute for the browser, a minute for the answer).
28const CHANNEL_LIFE: Duration = Duration::from_secs(5 * 60);
29/// At most this many channels at once; a new one beyond it replaces the oldest that has proved nothing.
30const MAX_CHANNELS: usize = 256;
31
32type Hmac256 = Hmac<Sha256>;
33
34/// MAC over length-prefixed parts under `key`, so no two part lists give the same input.
35fn mac(key: &[u8], label: &str, parts: &[&[u8]]) -> [u8; 32] {
36    let mut m = Hmac256::new_from_slice(key).expect("hmac takes any key length");
37    for part in std::iter::once(label.as_bytes()).chain(parts.iter().copied()) {
38        m.update(&(part.len() as u64).to_be_bytes());
39        m.update(part);
40    }
41    m.finalize().into_bytes().into()
42}
43
44/// A nonce is 32 random bytes as 64 lowercase hex characters.
45pub(crate) fn is_nonce(s: &str) -> bool {
46    s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
47}
48
49pub(crate) fn new_nonce() -> String {
50    super::local_session::random_secret()
51}
52
53/// What srv proves in its hello: it holds the key, and is bound to `bound` with `declared` as the
54/// other origin it accepts (empty when none).
55fn hello_proof(key: &[u8], nonce_c: &str, nonce_s: &str, bound: &str, declared: &str) -> String {
56    hex::encode(mac(key, "amx-srv-hello-v1", &[nonce_c.as_bytes(), nonce_s.as_bytes(), bound.as_bytes(), declared.as_bytes()]))
57}
58
59/// The key of one channel: made from the key and everything the hello proved.
60fn channel_key(key: &[u8], nonce_c: &str, nonce_s: &str, bound: &str, declared: &str) -> [u8; 32] {
61    mac(key, "amx-channel-v1", &[nonce_c.as_bytes(), nonce_s.as_bytes(), bound.as_bytes(), declared.as_bytes()])
62}
63
64fn request_proof(ck: &[u8; 32], seq: u64, method: &str, path: &str, body: &[u8]) -> String {
65    hex::encode(mac(ck, "amx-req-v1", &[&seq.to_be_bytes(), method.as_bytes(), path.as_bytes(), &Sha256::digest(body)]))
66}
67
68/// The proof on srv's answer to request number `seq`.
69pub(crate) fn response_proof(ck: &ChannelKey, seq: u64, status: u16, body: &[u8]) -> String {
70    hex::encode(mac(&ck.0, "amx-resp-v1", &[&seq.to_be_bytes(), &status.to_be_bytes(), &Sha256::digest(body)]))
71}
72
73/// A channel's key, kept in memory only.
74#[derive(Clone)]
75pub(crate) struct ChannelKey([u8; 32]);
76
77// ---- srv's side ----
78
79/// srv's answer to a hello.
80pub(crate) struct Hello {
81    pub channel: String,
82    pub nonce: String,
83    pub proof: String,
84}
85
86struct Channel {
87    key: ChannelKey,
88    last_seq: u64,
89    born: Instant,
90}
91
92/// The channels `open` has begun. Memory only.
93#[derive(Default)]
94pub(crate) struct Channels {
95    inner: Mutex<HashMap<String, Channel>>,
96}
97
98/// A request that proved itself: the answer to it is proved with this.
99pub(crate) struct Admitted {
100    pub key: ChannelKey,
101    pub seq: u64,
102}
103
104impl Channels {
105    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, Channel>> {
106        self.inner.lock().unwrap_or_else(|e| e.into_inner())
107    }
108
109    /// Begin a channel. `None` when the caller's nonce is not a nonce. Takes no secret from the caller:
110    /// anyone may ask, and what comes back proves only that srv holds the key.
111    pub(crate) fn hello(&self, key: &[u8], nonce_c: &str, bound: &str, declared: &str, now: Instant) -> Option<Hello> {
112        if !is_nonce(nonce_c) {
113            return None;
114        }
115        let nonce_s = new_nonce();
116        let id = new_nonce();
117        let mut map = self.lock();
118        map.retain(|_, c| now.duration_since(c.born) <= CHANNEL_LIFE);
119        if map.len() >= MAX_CHANNELS {
120            // A caller without the key can never move a channel off 0, so a flood replaces channels
121            // that have proved nothing first; one that has proved a request goes only when all have.
122            let victim = map
123                .iter()
124                .filter(|(_, c)| c.last_seq == 0)
125                .min_by_key(|(_, c)| c.born)
126                .or_else(|| map.iter().min_by_key(|(_, c)| c.born))
127                .map(|(id, _)| id.clone());
128            if let Some(victim) = victim {
129                map.remove(&victim);
130            }
131        }
132        let ck = ChannelKey(channel_key(key, nonce_c, &nonce_s, bound, declared));
133        map.insert(id.clone(), Channel { key: ck, last_seq: 0, born: now });
134        Some(Hello { channel: id, nonce: nonce_s.clone(), proof: hello_proof(key, nonce_c, &nonce_s, bound, declared) })
135    }
136
137    /// A request on a channel: its number is higher than any before it, and its proof covers the
138    /// method, path and body as srv received them. A request that fails changes nothing.
139    pub(crate) fn admit(&self, id: &str, seq: u64, method: &str, path: &str, body: &[u8], proof: &str, now: Instant) -> Option<Admitted> {
140        let mut map = self.lock();
141        let channel = map.get_mut(id)?;
142        if now.duration_since(channel.born) > CHANNEL_LIFE || seq <= channel.last_seq {
143            return None;
144        }
145        let expected = request_proof(&channel.key.0, seq, method, path, body);
146        if !secret_eq(proof.as_bytes(), expected.as_bytes()) {
147            return None;
148        }
149        channel.last_seq = seq;
150        Some(Admitted { key: channel.key.clone(), seq })
151    }
152
153    #[cfg(test)]
154    pub(crate) fn count(&self) -> usize {
155        self.lock().len()
156    }
157}
158
159// ---- open's side ----
160
161/// What srv said in its hello.
162pub(crate) struct HelloReply {
163    pub channel: String,
164    pub nonce: String,
165    /// The other origin srv says it accepts; covered by the proof, empty when none.
166    pub declared: String,
167    pub proof: String,
168}
169
170/// A hello that did not prove srv holds the key, or is bound to the address `open` is talking to.
171#[derive(Debug, PartialEq, Eq)]
172pub(crate) struct NotProved;
173
174/// `open`'s end of a channel, after srv proved itself.
175pub(crate) struct Client {
176    channel: String,
177    key: ChannelKey,
178    seq: u64,
179    declared: String,
180}
181
182impl Client {
183    /// Accept srv's hello only when its proof is made with this key, over this `nonce_c`, for exactly
184    /// the address `open` is talking to (`bound`, as `host:port`).
185    pub(crate) fn accept(key: &[u8], nonce_c: &str, bound: &str, reply: HelloReply) -> Result<Client, NotProved> {
186        if !is_nonce(&reply.nonce) || !is_nonce(&reply.channel) {
187            return Err(NotProved);
188        }
189        let expected = hello_proof(key, nonce_c, &reply.nonce, bound, &reply.declared);
190        if !secret_eq(reply.proof.as_bytes(), expected.as_bytes()) {
191            return Err(NotProved);
192        }
193        let ck = ChannelKey(channel_key(key, nonce_c, &reply.nonce, bound, &reply.declared));
194        Ok(Client { channel: reply.channel, key: ck, seq: 0, declared: reply.declared })
195    }
196
197    /// The other origin srv accepts, as srv proved it.
198    pub(crate) fn declared(&self) -> Option<&str> {
199        Some(self.declared.as_str()).filter(|d| !d.is_empty())
200    }
201
202    /// The headers of the next request: channel, number and proof.
203    pub(crate) fn sign(&mut self, method: &str, path: &str, body: &[u8]) -> Signed {
204        self.seq += 1;
205        Signed { channel: self.channel.clone(), seq: self.seq, proof: request_proof(&self.key.0, self.seq, method, path, body) }
206    }
207
208    /// Does srv's answer to request `seq` carry the proof of the channel?
209    pub(crate) fn answer_ok(&self, seq: u64, status: u16, body: &[u8], proof: &str) -> bool {
210        secret_eq(proof.as_bytes(), response_proof(&self.key, seq, status, body).as_bytes())
211    }
212}
213
214pub(crate) struct Signed {
215    pub channel: String,
216    pub seq: u64,
217    pub proof: String,
218}
219
220#[cfg(test)]
221#[path = "tests/local_proof_tests.rs"]
222mod tests;