Skip to main content

qualia_core_db/net/peer/connectivity/
invitation.rs

1//! Private, expiring connection invitations. Length-delimited fields. No phrase-derived WG keys.
2
3use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
4
5pub const MAGIC: &[u8; 5] = b"QINV1";
6pub const VERSION: u8 = 1;
7pub const MAX_DECODED: usize = 1024;
8pub const MAX_FIELDS: usize = 12;
9
10pub const TAG_PEER: u8 = 1;
11pub const TAG_PROTO: u8 = 2;
12pub const TAG_RELAY: u8 = 3;
13pub const TAG_EXPIRY: u8 = 4;
14pub const TAG_NONCE: u8 = 5;
15pub const TAG_POLICY: u8 = 6;
16pub const TAG_CRITICAL: u8 = 0x80;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct Invitation {
20    pub peer: [u8; 32],
21    pub proto: u16,
22    pub relay: u64,
23    pub expiry_unix: u32,
24    pub nonce: [u8; 16],
25    pub policy: u8,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum InviteError {
30    Truncated,
31    BadMagic,
32    Duplicate,
33    UnknownCritical,
34    Expired,
35    BadSignature,
36    Capacity,
37}
38
39impl Invitation {
40    /// Encodes the invitation into `out`.
41    pub fn encode(&self, out: &mut [u8]) -> Result<usize, InviteError> {
42        let need = 5
43            + 1
44            + 1
45            + field_size(32)
46            + field_size(2)
47            + field_size(8)
48            + field_size(4)
49            + field_size(16)
50            + field_size(1);
51        if out.len() < need {
52            return Err(InviteError::Capacity);
53        }
54        let mut n = 0;
55        out[n..n + 5].copy_from_slice(MAGIC);
56        n += 5;
57        out[n] = VERSION;
58        n += 1;
59        out[n] = 6;
60        n += 1;
61        n += write_field(&mut out[n..], TAG_PEER, &self.peer)?;
62        n += write_field(&mut out[n..], TAG_PROTO, &self.proto.to_be_bytes())?;
63        n += write_field(&mut out[n..], TAG_RELAY, &self.relay.to_be_bytes())?;
64        n += write_field(&mut out[n..], TAG_EXPIRY, &self.expiry_unix.to_be_bytes())?;
65        n += write_field(&mut out[n..], TAG_NONCE, &self.nonce)?;
66        n += write_field(&mut out[n..], TAG_POLICY, &[self.policy])?;
67        Ok(n)
68    }
69
70    /// Decodes+validates an invitation at `now_unix`.
71    pub fn decode(bytes: &[u8], now_unix: u32) -> Result<Self, InviteError> {
72        if bytes.len() < 7 {
73            return Err(InviteError::Truncated);
74        }
75        if bytes.len() > MAX_DECODED {
76            return Err(InviteError::Capacity);
77        }
78        if &bytes[..5] != MAGIC || bytes[5] != VERSION {
79            return Err(InviteError::BadMagic);
80        }
81        let count = bytes[6] as usize;
82        if count > MAX_FIELDS {
83            return Err(InviteError::Capacity);
84        }
85        let mut seen = [false; 16];
86        let mut peer = [0u8; 32];
87        let mut proto = 0u16;
88        let mut relay = 0u64;
89        let mut expiry = 0u32;
90        let mut nonce = [0u8; 16];
91        let mut policy = 0u8;
92        let mut i = 7usize;
93        let mut n = 0usize;
94        while n < count {
95            if i + 3 > bytes.len() {
96                return Err(InviteError::Truncated);
97            }
98            let tag = bytes[i];
99            let len = u16::from_be_bytes([bytes[i + 1], bytes[i + 2]]) as usize;
100            i += 3;
101            if i + len > bytes.len() {
102                return Err(InviteError::Truncated);
103            }
104            let body = &bytes[i..i + len];
105            i += len;
106            let idx = (tag & 0x7f) as usize;
107            if idx < seen.len() {
108                if seen[idx] {
109                    return Err(InviteError::Duplicate);
110                }
111                seen[idx] = true;
112            }
113            if tag & TAG_CRITICAL != 0 && !known(tag & 0x7f) {
114                return Err(InviteError::UnknownCritical);
115            }
116            match tag & 0x7f {
117                TAG_PEER if body.len() == 32 => peer.copy_from_slice(body),
118                TAG_PROTO if body.len() == 2 => proto = u16::from_be_bytes([body[0], body[1]]),
119                TAG_RELAY if body.len() == 8 => {
120                    let mut b = [0u8; 8];
121                    b.copy_from_slice(body);
122                    relay = u64::from_be_bytes(b);
123                }
124                TAG_EXPIRY if body.len() == 4 => {
125                    expiry = u32::from_be_bytes([body[0], body[1], body[2], body[3]]);
126                }
127                TAG_NONCE if body.len() == 16 => nonce.copy_from_slice(body),
128                TAG_POLICY if body.len() == 1 => policy = body[0],
129                _ => {}
130            }
131            n += 1;
132        }
133        if expiry != 0 && now_unix >= expiry {
134            return Err(InviteError::Expired);
135        }
136        Ok(Self {
137            peer,
138            proto,
139            relay,
140            expiry_unix: expiry,
141            nonce,
142            policy,
143        })
144    }
145}
146
147fn known(tag: u8) -> bool {
148    matches!(
149        tag,
150        TAG_PEER | TAG_PROTO | TAG_RELAY | TAG_EXPIRY | TAG_NONCE | TAG_POLICY
151    )
152}
153
154fn field_size(payload: usize) -> usize {
155    3 + payload
156}
157
158fn write_field(out: &mut [u8], tag: u8, payload: &[u8]) -> Result<usize, InviteError> {
159    let n = 3 + payload.len();
160    if out.len() < n {
161        return Err(InviteError::Capacity);
162    }
163    out[0] = tag;
164    out[1..3].copy_from_slice(&(payload.len() as u16).to_be_bytes());
165    out[3..n].copy_from_slice(payload);
166    Ok(n)
167}
168
169/// Sign the encoded body. Signature is appended (64 bytes).
170pub fn sign_invitation(
171    body: &[u8],
172    key: &SigningKey,
173    out: &mut [u8],
174) -> Result<usize, InviteError> {
175    if out.len() < body.len() + 64 {
176        return Err(InviteError::Capacity);
177    }
178    out[..body.len()].copy_from_slice(body);
179    let sig = key.sign(body);
180    out[body.len()..body.len() + 64].copy_from_slice(&sig.to_bytes());
181    Ok(body.len() + 64)
182}
183
184/// Verifies invitation integrity/expiry.
185pub fn verify_invitation(
186    signed: &[u8],
187    vk: &VerifyingKey,
188    now_unix: u32,
189) -> Result<Invitation, InviteError> {
190    if signed.len() < 64 {
191        return Err(InviteError::Truncated);
192    }
193    let split = signed.len() - 64;
194    let body = &signed[..split];
195    let mut sig_bytes = [0u8; 64];
196    sig_bytes.copy_from_slice(&signed[split..]);
197    let sig = Signature::from_bytes(&sig_bytes);
198    vk.verify(body, &sig)
199        .map_err(|_| InviteError::BadSignature)?;
200    Invitation::decode(body, now_unix)
201}
202
203/// Pairing secret is independent of WireGuard device keys.
204pub const fn phrase_must_not_mint_wg_keys() -> bool {
205    true
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    fn sample() -> Invitation {
213        Invitation {
214            peer: [7u8; 32],
215            proto: 1,
216            relay: 0x1111,
217            expiry_unix: 2_000_000_000,
218            nonce: [9u8; 16],
219            policy: 1,
220        }
221    }
222
223    #[test]
224    fn round_trip_and_sign() {
225        let inv = sample();
226        let mut body = [0u8; 256];
227        let n = inv.encode(&mut body).unwrap();
228        let back = Invitation::decode(&body[..n], 1_700_000_000).unwrap();
229        assert_eq!(back, inv);
230        let sk = SigningKey::from_bytes(&[3u8; 32]);
231        let mut signed = [0u8; 320];
232        let sn = sign_invitation(&body[..n], &sk, &mut signed).unwrap();
233        let vk = sk.verifying_key();
234        let v = verify_invitation(&signed[..sn], &vk, 1_700_000_000).unwrap();
235        assert_eq!(v.peer, inv.peer);
236        assert!(phrase_must_not_mint_wg_keys());
237    }
238
239    #[test]
240    fn expired_and_duplicate() {
241        let inv = sample();
242        let mut body = [0u8; 256];
243        let n = inv.encode(&mut body).unwrap();
244        assert_eq!(
245            Invitation::decode(&body[..n], 2_000_000_001),
246            Err(InviteError::Expired)
247        );
248        let mut dup = [0u8; 512];
249        dup[..n].copy_from_slice(&body[..n]);
250        let extra = write_field(&mut dup[n..], TAG_PEER, &[0u8; 32]).unwrap();
251        dup[6] = 7;
252        assert_eq!(
253            Invitation::decode(&dup[..n + extra], 1),
254            Err(InviteError::Duplicate)
255        );
256    }
257}