1use 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
27const CHANNEL_LIFE: Duration = Duration::from_secs(5 * 60);
29const MAX_CHANNELS: usize = 256;
31
32type Hmac256 = Hmac<Sha256>;
33
34fn 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
44pub(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
53fn 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
59fn 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
68pub(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#[derive(Clone)]
75pub(crate) struct ChannelKey([u8; 32]);
76
77pub(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#[derive(Default)]
94pub(crate) struct Channels {
95 inner: Mutex<HashMap<String, Channel>>,
96}
97
98pub(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 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 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 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
159pub(crate) struct HelloReply {
163 pub channel: String,
164 pub nonce: String,
165 pub declared: String,
167 pub proof: String,
168}
169
170#[derive(Debug, PartialEq, Eq)]
172pub(crate) struct NotProved;
173
174pub(crate) struct Client {
176 channel: String,
177 key: ChannelKey,
178 seq: u64,
179 declared: String,
180}
181
182impl Client {
183 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 pub(crate) fn declared(&self) -> Option<&str> {
199 Some(self.declared.as_str()).filter(|d| !d.is_empty())
200 }
201
202 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 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;