alpine-protocol-rs 2.0.16

Authenticated Lighting Protocol (alpine): secure control-plane + streaming guard for lighting data.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use async_trait::async_trait;
use ed25519_dalek::Signature;

use crate::crypto::{identity::NodeCredentials, KeyExchange, SessionKeys, X25519KeyExchange};
use crate::handshake::{
    client::ClientHandshake, server::ServerHandshake, ChallengeAuthenticator, HandshakeContext,
    HandshakeError, HandshakeOutcome, HandshakeParticipant, HandshakeTransport,
};
use crate::messages::{CapabilitySet, DeviceIdentity, SessionEstablished};
use crate::profile::{CompiledStreamProfile, StreamProfile};

pub mod state;
use state::{SessionState, SessionStateError};

impl From<SessionStateError> for HandshakeError {
    fn from(err: SessionStateError) -> Self {
        HandshakeError::Protocol(err.to_string())
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AlnpRole {
    Controller,
    Node,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum JitterStrategy {
    HoldLast,
    Drop,
    Lerp,
}

#[derive(Debug, Clone)]
pub struct AlnpSession {
    pub role: AlnpRole,
    state: Arc<Mutex<SessionState>>,
    last_keepalive: Arc<Mutex<Instant>>,
    jitter: Arc<Mutex<JitterStrategy>>,
    streaming_enabled: Arc<Mutex<bool>>,
    timeout: Duration,
    session_established: Arc<Mutex<Option<SessionEstablished>>>,
    session_keys: Arc<Mutex<Option<SessionKeys>>>,
    compiled_profile: Arc<Mutex<Option<CompiledStreamProfile>>>,
    profile_locked: Arc<Mutex<bool>>,
}

impl AlnpSession {
    pub fn new(role: AlnpRole) -> Self {
        Self {
            role,
            state: Arc::new(Mutex::new(SessionState::Init)),
            last_keepalive: Arc::new(Mutex::new(Instant::now())),
            jitter: Arc::new(Mutex::new(JitterStrategy::HoldLast)),
            streaming_enabled: Arc::new(Mutex::new(true)),
            timeout: Duration::from_secs(10),
            session_established: Arc::new(Mutex::new(None)),
            session_keys: Arc::new(Mutex::new(None)),
            compiled_profile: Arc::new(Mutex::new(None)),
            profile_locked: Arc::new(Mutex::new(false)),
        }
    }

    pub fn established(&self) -> Option<SessionEstablished> {
        self.session_established.lock().ok().and_then(|s| s.clone())
    }

    pub fn keys(&self) -> Option<SessionKeys> {
        self.session_keys.lock().ok().and_then(|k| k.clone())
    }

    pub fn state(&self) -> SessionState {
        self.state
            .lock()
            .map(|g| g.clone())
            .unwrap_or(SessionState::Failed("state poisoned".to_string()))
    }

    pub fn ensure_streaming_ready(&self) -> Result<SessionEstablished, HandshakeError> {
        let state = self.state();
        match state {
            SessionState::Ready { .. } | SessionState::Streaming { .. } => {
                self.established().ok_or_else(|| {
                    HandshakeError::Authentication(
                        "session missing even though state is ready".into(),
                    )
                })
            }
            SessionState::Failed(reason) => Err(HandshakeError::Authentication(reason)),
            _ => Err(HandshakeError::Authentication(
                "session not ready; streaming blocked".into(),
            )),
        }
    }

    pub fn update_keepalive(&self) {
        if let Ok(mut k) = self.last_keepalive.lock() {
            *k = Instant::now();
        }
    }

    pub fn check_timeouts(&self) -> Result<(), HandshakeError> {
        let now = Instant::now();
        if let Ok(state) = self.state.lock() {
            if state.check_timeout(self.timeout, now) {
                self.fail("session timeout".into());
                return Err(HandshakeError::Transport("session timeout".into()));
            }
        }
        Ok(())
    }

    /// Sets the stream profile that determines runtime behavior.
    ///
    /// This method locks the profile until streaming begins to enforce immutability.
    pub fn set_stream_profile(&self, profile: CompiledStreamProfile) -> Result<(), HandshakeError> {
        let locked = self
            .profile_locked
            .lock()
            .map_err(|_| HandshakeError::Protocol("profile lock poisoned".into()))?;
        if *locked {
            return Err(HandshakeError::Protocol(
                "stream profile cannot be changed after streaming starts".into(),
            ));
        }
        let mut compiled = self
            .compiled_profile
            .lock()
            .map_err(|_| HandshakeError::Protocol("compiled profile lock poisoned".into()))?;
        *compiled = Some(profile);
        Ok(())
    }

    /// Returns the bound profile's config ID, if set.
    ///
    /// The `config_id` is computed from the normalized profile and never changes.
    #[must_use]
    pub fn profile_config_id(&self) -> Option<String> {
        self.compiled_profile
            .lock()
            .ok()
            .and_then(|guard| guard.clone().map(|profile| profile.config_id().to_string()))
    }

    /// Retrieves the compiled profile, if configured.
    ///
    /// Once streaming starts this returns the same object that controls runtime behavior.
    #[must_use]
    pub fn compiled_profile(&self) -> Option<CompiledStreamProfile> {
        self.compiled_profile
            .lock()
            .ok()
            .and_then(|guard| guard.clone())
    }

    #[cfg(test)]
    pub(crate) fn set_locked_profile_for_testing(&self, profile: CompiledStreamProfile) {
        let mut compiled = self.compiled_profile.lock().unwrap();
        *compiled = Some(profile);
        *self.profile_locked.lock().unwrap() = true;
    }

    pub fn set_jitter_strategy(&self, strat: JitterStrategy) {
        if let Ok(mut j) = self.jitter.lock() {
            *j = strat;
        }
    }

    pub fn jitter_strategy(&self) -> JitterStrategy {
        self.jitter
            .lock()
            .map(|j| *j)
            .unwrap_or(JitterStrategy::Drop)
    }

    pub fn close(&self) {
        if let Ok(mut state) = self.state.lock() {
            *state = SessionState::Closed;
        }
    }

    pub fn fail(&self, reason: String) {
        if let Ok(mut state) = self.state.lock() {
            *state = SessionState::Failed(reason);
        }
    }

    fn transition(&self, next: SessionState) -> Result<(), SessionStateError> {
        let mut state = self.state.lock().unwrap();
        let current = state.clone();
        *state = current.transition(next)?;
        Ok(())
    }

    pub fn set_streaming_enabled(&self, enabled: bool) {
        if let Ok(mut flag) = self.streaming_enabled.lock() {
            *flag = enabled;
        }
    }

    pub fn mark_streaming(&self) {
        if let Ok(mut state) = self.state.lock() {
            let current = state.clone();
            if let SessionState::Ready { .. } = current {
                let _ = current
                    .transition(SessionState::Streaming {
                        since: Instant::now(),
                    })
                    .map(|next| *state = next);
            }
        }
        if let Ok(mut locked) = self.profile_locked.lock() {
            *locked = true;
        }
    }

    pub fn streaming_enabled(&self) -> bool {
        self.streaming_enabled.lock().map(|f| *f).unwrap_or(false)
    }

    fn apply_outcome(&self, outcome: HandshakeOutcome) {
        if let Ok(mut guard) = self.session_established.lock() {
            *guard = Some(outcome.established);
        }
        if let Ok(mut guard) = self.session_keys.lock() {
            *guard = Some(outcome.keys);
        }
    }

    pub async fn connect<T, A, K>(
        identity: DeviceIdentity,
        capabilities: CapabilitySet,
        authenticator: A,
        key_exchange: K,
        context: HandshakeContext,
        transport: &mut T,
    ) -> Result<Self, HandshakeError>
    where
        T: HandshakeTransport + Send,
        A: ChallengeAuthenticator + Send + Sync,
        K: KeyExchange + Send + Sync,
    {
        let session = Self::new(AlnpRole::Controller);
        session.transition(SessionState::Handshake)?;
        let driver = ClientHandshake {
            identity,
            capabilities,
            authenticator,
            key_exchange,
            context,
        };

        let outcome = driver.run(transport).await?;
        session.transition(SessionState::Authenticated {
            since: Instant::now(),
        })?;
        session.transition(SessionState::Ready {
            since: Instant::now(),
        })?;
        session.apply_outcome(outcome);
        Ok(session)
    }

    pub async fn accept<T, A, K>(
        identity: DeviceIdentity,
        capabilities: CapabilitySet,
        authenticator: A,
        key_exchange: K,
        context: HandshakeContext,
        transport: &mut T,
    ) -> Result<Self, HandshakeError>
    where
        T: HandshakeTransport + Send,
        A: ChallengeAuthenticator + Send + Sync,
        K: KeyExchange + Send + Sync,
    {
        let session = Self::new(AlnpRole::Node);
        session.transition(SessionState::Handshake)?;
        let driver = ServerHandshake {
            identity,
            capabilities,
            authenticator,
            key_exchange,
            context,
        };

        let outcome = driver.run(transport).await?;
        session.transition(SessionState::Authenticated {
            since: Instant::now(),
        })?;
        session.transition(SessionState::Ready {
            since: Instant::now(),
        })?;
        session.apply_outcome(outcome);
        Ok(session)
    }
}

/// Shared-secret authenticator placeholder for signing and verification.
pub struct StaticKeyAuthenticator {
    secret: Vec<u8>,
}

impl StaticKeyAuthenticator {
    pub fn new(secret: Vec<u8>) -> Self {
        Self { secret }
    }
}

impl Default for StaticKeyAuthenticator {
    fn default() -> Self {
        Self::new(b"default-alnp-secret".to_vec())
    }
}

impl ChallengeAuthenticator for StaticKeyAuthenticator {
    fn sign_challenge(&self, nonce: &[u8]) -> Vec<u8> {
        let mut sig = Vec::with_capacity(self.secret.len() + nonce.len());
        sig.extend_from_slice(&self.secret);
        sig.extend_from_slice(nonce);
        sig
    }

    fn verify_challenge(&self, nonce: &[u8], signature: &[u8]) -> bool {
        signature.ends_with(nonce) && signature.starts_with(&self.secret)
    }
}

/// Ed25519-based authenticator using loaded credentials.
pub struct Ed25519Authenticator {
    creds: NodeCredentials,
}

impl Ed25519Authenticator {
    pub fn new(creds: NodeCredentials) -> Self {
        Self { creds }
    }
}

impl ChallengeAuthenticator for Ed25519Authenticator {
    fn sign_challenge(&self, nonce: &[u8]) -> Vec<u8> {
        self.creds.sign(nonce).to_vec()
    }

    fn verify_challenge(&self, nonce: &[u8], signature: &[u8]) -> bool {
        if let Ok(sig) = Signature::from_slice(signature) {
            self.creds.verify(nonce, &sig)
        } else {
            false
        }
    }
}

/// Simplified in-memory transport useful for unit tests and examples.
pub struct LoopbackTransport {
    inbox: Vec<crate::handshake::HandshakeMessage>,
}

impl LoopbackTransport {
    pub fn new() -> Self {
        Self { inbox: Vec::new() }
    }
}

#[cfg(test)]
mod session_tests {
    use super::*;

    #[test]
    fn profile_lock_prevents_profile_swaps() {
        let session = AlnpSession::new(AlnpRole::Controller);
        let compiled = StreamProfile::auto().compile().unwrap();
        session.set_stream_profile(compiled.clone()).unwrap();
        session.mark_streaming();
        assert!(session.set_stream_profile(compiled).is_err());
    }

    #[test]
    fn config_id_matches_profile() {
        let session = AlnpSession::new(AlnpRole::Controller);
        let compiled = StreamProfile::realtime().compile().unwrap();
        session.set_stream_profile(compiled.clone()).unwrap();
        assert_eq!(session.profile_config_id().unwrap(), compiled.config_id());
    }

    #[test]
    fn config_id_stays_locked_after_streaming() {
        let session = AlnpSession::new(AlnpRole::Controller);
        let compiled = StreamProfile::install().compile().unwrap();
        session.set_stream_profile(compiled.clone()).unwrap();
        let before_config = session.profile_config_id().unwrap();
        session.mark_streaming();
        assert_eq!(session.profile_config_id().unwrap(), before_config);
        assert!(session
            .set_stream_profile(StreamProfile::default().compile().unwrap())
            .is_err());
    }
}

#[async_trait]
impl HandshakeTransport for LoopbackTransport {
    async fn send(
        &mut self,
        msg: crate::handshake::HandshakeMessage,
    ) -> Result<(), HandshakeError> {
        self.inbox.push(msg);
        Ok(())
    }

    async fn recv(&mut self) -> Result<crate::handshake::HandshakeMessage, HandshakeError> {
        if self.inbox.is_empty() {
            return Err(HandshakeError::Transport("loopback queue empty".into()));
        }
        Ok(self.inbox.remove(0))
    }
}

/// Helper builder to quickly create a controller-side session with defaults.
pub async fn example_controller_session<T: HandshakeTransport + Send>(
    identity: DeviceIdentity,
    transport: &mut T,
) -> Result<AlnpSession, HandshakeError> {
    AlnpSession::connect(
        identity,
        CapabilitySet::default(),
        StaticKeyAuthenticator::default(),
        X25519KeyExchange::new(),
        HandshakeContext::default(),
        transport,
    )
    .await
}

/// Helper builder to quickly create a node-side session with defaults.
pub async fn example_node_session<T: HandshakeTransport + Send>(
    identity: DeviceIdentity,
    transport: &mut T,
) -> Result<AlnpSession, HandshakeError> {
    AlnpSession::accept(
        identity,
        CapabilitySet::default(),
        StaticKeyAuthenticator::default(),
        X25519KeyExchange::new(),
        HandshakeContext::default(),
        transport,
    )
    .await
}