auth-framework 0.5.0-rc19

A comprehensive, production-ready authentication and authorization framework for Rust applications
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! TACACS+ (Terminal Access Controller Access-Control System Plus) protocol support.
//!
//! Provides TACACS+ packet construction, obfuscation/deobfuscation, and
//! authentication/authorization/accounting message handling per RFC 8907.

use crate::errors::{AuthError, Result};
use ring::digest::{Context, SHA256};
use serde::{Deserialize, Serialize};

/// TACACS+ protocol version.
const TACACS_MAJOR_VERSION: u8 = 0xC0; // Major version 12 (0xC)
const TACACS_MINOR_VERSION_DEFAULT: u8 = 0x00;

/// TACACS+ packet types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum TacacsPacketType {
    Authentication = 0x01,
    Authorization = 0x02,
    Accounting = 0x03,
}

/// TACACS+ authentication action.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum AuthenAction {
    Login = 0x01,
    ChangePassword = 0x02,
    SendAuth = 0x04,
}

/// TACACS+ authentication type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum AuthenType {
    Ascii = 0x01,
    Pap = 0x02,
    Chap = 0x03,
    MSChap = 0x05,
    MSChapV2 = 0x06,
}

/// TACACS+ authentication service.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum AuthenService {
    None = 0x00,
    Login = 0x01,
    Enable = 0x02,
    Ppp = 0x03,
}

/// TACACS+ authentication status (reply).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum AuthenStatus {
    Pass = 0x01,
    Fail = 0x02,
    GetData = 0x03,
    GetUser = 0x04,
    GetPass = 0x05,
    Restart = 0x06,
    Error = 0x07,
    Follow = 0x21,
}

/// TACACS+ authorization status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum AuthorStatus {
    PassAdd = 0x01,
    PassReplace = 0x02,
    Fail = 0x10,
    Error = 0x11,
    Follow = 0x21,
}

/// TACACS+ accounting flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcctFlags(pub u8);

impl AcctFlags {
    pub const START: Self = Self(0x02);
    pub const STOP: Self = Self(0x04);
    pub const WATCHDOG: Self = Self(0x08);

    pub fn is_start(self) -> bool {
        self.0 & 0x02 != 0
    }
    pub fn is_stop(self) -> bool {
        self.0 & 0x04 != 0
    }
    pub fn is_watchdog(self) -> bool {
        self.0 & 0x08 != 0
    }
}

/// TACACS+ packet header (12 bytes).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TacacsHeader {
    pub version: u8,
    pub packet_type: TacacsPacketType,
    pub seq_no: u8,
    pub flags: u8,
    pub session_id: u32,
    pub length: u32,
}

impl TacacsHeader {
    /// Create a new TACACS+ header.
    pub fn new(packet_type: TacacsPacketType, seq_no: u8, session_id: u32, body_len: u32) -> Self {
        Self {
            version: TACACS_MAJOR_VERSION | TACACS_MINOR_VERSION_DEFAULT,
            packet_type,
            seq_no,
            flags: 0x00, // encrypted (not unencrypted)
            session_id,
            length: body_len,
        }
    }

    /// Serialize header to 12-byte wire format.
    pub fn to_bytes(&self) -> [u8; 12] {
        let mut buf = [0u8; 12];
        buf[0] = self.version;
        buf[1] = self.packet_type as u8;
        buf[2] = self.seq_no;
        buf[3] = self.flags;
        buf[4..8].copy_from_slice(&self.session_id.to_be_bytes());
        buf[8..12].copy_from_slice(&self.length.to_be_bytes());
        buf
    }

    /// Parse header from 12-byte wire format.
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        if data.len() < 12 {
            return Err(AuthError::validation("TACACS+ header too short"));
        }
        let packet_type = match data[1] {
            0x01 => TacacsPacketType::Authentication,
            0x02 => TacacsPacketType::Authorization,
            0x03 => TacacsPacketType::Accounting,
            other => {
                return Err(AuthError::validation(format!(
                    "Unknown TACACS+ packet type: {other:#x}"
                )));
            }
        };
        Ok(Self {
            version: data[0],
            packet_type,
            seq_no: data[2],
            flags: data[3],
            session_id: u32::from_be_bytes([data[4], data[5], data[6], data[7]]),
            length: u32::from_be_bytes([data[8], data[9], data[10], data[11]]),
        })
    }
}

/// TACACS+ authentication START body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthenStartBody {
    pub action: AuthenAction,
    pub authen_type: AuthenType,
    pub authen_service: AuthenService,
    pub user: String,
    pub port: String,
    pub remote_address: String,
    pub data: Vec<u8>,
}

impl AuthenStartBody {
    /// Serialize to wire format.
    pub fn to_bytes(&self) -> Vec<u8> {
        let user_bytes = self.user.as_bytes();
        let port_bytes = self.port.as_bytes();
        let rem_bytes = self.remote_address.as_bytes();
        let mut buf = Vec::with_capacity(
            8 + user_bytes.len() + port_bytes.len() + rem_bytes.len() + self.data.len(),
        );

        buf.push(self.action as u8);
        buf.push(0x01); // priv_lvl = 1
        buf.push(self.authen_type as u8);
        buf.push(self.authen_service as u8);
        buf.push(user_bytes.len() as u8);
        buf.push(port_bytes.len() as u8);
        buf.push(rem_bytes.len() as u8);
        buf.push(self.data.len() as u8);
        buf.extend_from_slice(user_bytes);
        buf.extend_from_slice(port_bytes);
        buf.extend_from_slice(rem_bytes);
        buf.extend_from_slice(&self.data);

        buf
    }
}

/// TACACS+ authentication REPLY body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthenReplyBody {
    pub status: AuthenStatus,
    pub flags: u8,
    pub server_msg: String,
    pub data: Vec<u8>,
}

impl AuthenReplyBody {
    /// Parse from wire-format bytes.
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        if data.len() < 6 {
            return Err(AuthError::validation("TACACS+ authen reply too short"));
        }
        let status = match data[0] {
            0x01 => AuthenStatus::Pass,
            0x02 => AuthenStatus::Fail,
            0x03 => AuthenStatus::GetData,
            0x04 => AuthenStatus::GetUser,
            0x05 => AuthenStatus::GetPass,
            0x06 => AuthenStatus::Restart,
            0x07 => AuthenStatus::Error,
            0x21 => AuthenStatus::Follow,
            other => {
                return Err(AuthError::validation(format!(
                    "Unknown authen status: {other:#x}"
                )));
            }
        };
        let flags = data[1];
        let server_msg_len = u16::from_be_bytes([data[2], data[3]]) as usize;
        let data_len = u16::from_be_bytes([data[4], data[5]]) as usize;

        if data.len() < 6 + server_msg_len + data_len {
            return Err(AuthError::validation("TACACS+ authen reply truncated"));
        }

        let server_msg = String::from_utf8_lossy(&data[6..6 + server_msg_len]).to_string();
        let reply_data = data[6 + server_msg_len..6 + server_msg_len + data_len].to_vec();

        Ok(Self {
            status,
            flags,
            server_msg,
            data: reply_data,
        })
    }
}

// ── Authorization request/reply (RFC 8907 §6) ──────────────────────

/// TACACS+ authorization REQUEST body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorRequestBody {
    pub authen_method: u8,
    pub authen_type: AuthenType,
    pub authen_service: AuthenService,
    pub user: String,
    pub port: String,
    pub remote_address: String,
    /// Attribute-value pairs (e.g. "service=shell", "cmd=show").
    pub args: Vec<String>,
}

impl AuthorRequestBody {
    /// Serialize to wire format.
    pub fn to_bytes(&self) -> Vec<u8> {
        let user_bytes = self.user.as_bytes();
        let port_bytes = self.port.as_bytes();
        let rem_bytes = self.remote_address.as_bytes();
        let arg_count = self.args.len() as u8;

        // Fixed header: 8 bytes + arg_count * 1 (arg lengths) + variable fields
        let mut buf = Vec::new();
        buf.push(self.authen_method);
        buf.push(0x01); // priv_lvl
        buf.push(self.authen_type as u8);
        buf.push(self.authen_service as u8);
        buf.push(user_bytes.len() as u8);
        buf.push(port_bytes.len() as u8);
        buf.push(rem_bytes.len() as u8);
        buf.push(arg_count);

        // Argument lengths
        for arg in &self.args {
            buf.push(arg.len() as u8);
        }

        // Variable fields
        buf.extend_from_slice(user_bytes);
        buf.extend_from_slice(port_bytes);
        buf.extend_from_slice(rem_bytes);
        for arg in &self.args {
            buf.extend_from_slice(arg.as_bytes());
        }

        buf
    }
}

/// TACACS+ authorization REPLY body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorReplyBody {
    pub status: AuthorStatus,
    pub server_msg: String,
    pub data: Vec<u8>,
    pub args: Vec<String>,
}

impl AuthorReplyBody {
    /// Parse from wire-format bytes.
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        if data.len() < 6 {
            return Err(AuthError::validation("TACACS+ author reply too short"));
        }
        let status = match data[0] {
            0x01 => AuthorStatus::PassAdd,
            0x02 => AuthorStatus::PassReplace,
            0x10 => AuthorStatus::Fail,
            0x11 => AuthorStatus::Error,
            0x21 => AuthorStatus::Follow,
            other => {
                return Err(AuthError::validation(format!(
                    "Unknown author status: {other:#x}"
                )));
            }
        };

        let arg_count = data[1] as usize;
        let server_msg_len = u16::from_be_bytes([data[2], data[3]]) as usize;
        let data_len = u16::from_be_bytes([data[4], data[5]]) as usize;

        let mut offset = 6;
        // Read arg lengths
        if data.len() < offset + arg_count {
            return Err(AuthError::validation(
                "TACACS+ author reply truncated (arg lengths)",
            ));
        }
        let arg_lens: Vec<usize> = data[offset..offset + arg_count]
            .iter()
            .map(|&b| b as usize)
            .collect();
        offset += arg_count;

        // server_msg
        if data.len() < offset + server_msg_len {
            return Err(AuthError::validation(
                "TACACS+ author reply truncated (msg)",
            ));
        }
        let server_msg =
            String::from_utf8_lossy(&data[offset..offset + server_msg_len]).to_string();
        offset += server_msg_len;

        // data
        if data.len() < offset + data_len {
            return Err(AuthError::validation(
                "TACACS+ author reply truncated (data)",
            ));
        }
        let reply_data = data[offset..offset + data_len].to_vec();
        offset += data_len;

        // args
        let mut args = Vec::with_capacity(arg_count);
        for &len in &arg_lens {
            if data.len() < offset + len {
                return Err(AuthError::validation(
                    "TACACS+ author reply truncated (args)",
                ));
            }
            args.push(String::from_utf8_lossy(&data[offset..offset + len]).to_string());
            offset += len;
        }

        Ok(Self {
            status,
            server_msg,
            data: reply_data,
            args,
        })
    }
}

// ── Accounting request/reply (RFC 8907 §7) ──────────────────────────

/// TACACS+ accounting REQUEST body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AcctRequestBody {
    pub flags: AcctFlags,
    pub authen_method: u8,
    pub authen_type: AuthenType,
    pub authen_service: AuthenService,
    pub user: String,
    pub port: String,
    pub remote_address: String,
    /// Attribute-value pairs (e.g. "task_id=1", "start_time=now").
    pub args: Vec<String>,
}

impl AcctRequestBody {
    /// Serialize to wire format.
    pub fn to_bytes(&self) -> Vec<u8> {
        let user_bytes = self.user.as_bytes();
        let port_bytes = self.port.as_bytes();
        let rem_bytes = self.remote_address.as_bytes();
        let arg_count = self.args.len() as u8;

        let mut buf = Vec::new();
        buf.push(self.flags.0);
        buf.push(self.authen_method);
        buf.push(0x01); // priv_lvl
        buf.push(self.authen_type as u8);
        buf.push(self.authen_service as u8);
        buf.push(user_bytes.len() as u8);
        buf.push(port_bytes.len() as u8);
        buf.push(rem_bytes.len() as u8);
        buf.push(arg_count);

        // Argument lengths
        for arg in &self.args {
            buf.push(arg.len() as u8);
        }

        // Variable fields
        buf.extend_from_slice(user_bytes);
        buf.extend_from_slice(port_bytes);
        buf.extend_from_slice(rem_bytes);
        for arg in &self.args {
            buf.extend_from_slice(arg.as_bytes());
        }

        buf
    }
}

/// TACACS+ accounting status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum AcctStatus {
    Success = 0x01,
    Error = 0x02,
    Follow = 0x21,
}

/// TACACS+ accounting REPLY body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AcctReplyBody {
    pub status: AcctStatus,
    pub server_msg: String,
    pub data: Vec<u8>,
}

impl AcctReplyBody {
    /// Parse from wire-format bytes.
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        if data.len() < 5 {
            return Err(AuthError::validation("TACACS+ acct reply too short"));
        }
        let server_msg_len = u16::from_be_bytes([data[0], data[1]]) as usize;
        let data_len = u16::from_be_bytes([data[2], data[3]]) as usize;
        let status = match data[4] {
            0x01 => AcctStatus::Success,
            0x02 => AcctStatus::Error,
            0x21 => AcctStatus::Follow,
            other => {
                return Err(AuthError::validation(format!(
                    "Unknown acct status: {other:#x}"
                )));
            }
        };

        let offset = 5;
        if data.len() < offset + server_msg_len + data_len {
            return Err(AuthError::validation("TACACS+ acct reply truncated"));
        }
        let server_msg =
            String::from_utf8_lossy(&data[offset..offset + server_msg_len]).to_string();
        let reply_data = data[offset + server_msg_len..offset + server_msg_len + data_len].to_vec();

        Ok(Self {
            status,
            server_msg,
            data: reply_data,
        })
    }
}

/// Obfuscate or deobfuscate a TACACS+ packet body using the shared secret.
///
/// The same function is used for both encryption and decryption (XOR-based).
/// Per RFC 8907 §4.6:
///   pseudo_pad = MD5(session_id || key || version || seq_no || previous_pad...)
pub fn obfuscate(header: &TacacsHeader, secret: &[u8], body: &mut [u8]) {
    if secret.is_empty() || body.is_empty() {
        return;
    }

    let mut pad = Vec::new();
    let session_id_bytes = header.session_id.to_be_bytes();

    // First block
    let mut ctx = Context::new(&SHA256);
    ctx.update(&session_id_bytes);
    ctx.update(secret);
    ctx.update(&[header.version]);
    ctx.update(&[header.seq_no]);
    let digest = ctx.finish();
    pad.extend_from_slice(digest.as_ref());

    // Subsequent blocks
    while pad.len() < body.len() {
        let mut ctx = Context::new(&SHA256);
        ctx.update(&session_id_bytes);
        ctx.update(secret);
        ctx.update(&[header.version]);
        ctx.update(&[header.seq_no]);
        let prev_start = pad.len().saturating_sub(32);
        ctx.update(&pad[prev_start..]);
        let digest = ctx.finish();
        pad.extend_from_slice(digest.as_ref());
    }

    // XOR
    for (i, b) in body.iter_mut().enumerate() {
        *b ^= pad[i];
    }
}

/// Generate a random TACACS+ session ID.
pub fn generate_session_id() -> Result<u32> {
    use ring::rand::{SecureRandom, SystemRandom};
    let rng = SystemRandom::new();
    let mut buf = [0u8; 4];
    rng.fill(&mut buf)
        .map_err(|_| AuthError::crypto("Failed to generate session ID".to_string()))?;
    Ok(u32::from_be_bytes(buf))
}

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

    #[test]
    fn test_header_roundtrip() {
        let h = TacacsHeader::new(TacacsPacketType::Authentication, 1, 0xDEADBEEF, 42);
        let bytes = h.to_bytes();
        assert_eq!(bytes.len(), 12);
        let h2 = TacacsHeader::from_bytes(&bytes).unwrap();
        assert_eq!(h2.packet_type, TacacsPacketType::Authentication);
        assert_eq!(h2.session_id, 0xDEADBEEF);
        assert_eq!(h2.length, 42);
        assert_eq!(h2.seq_no, 1);
    }

    #[test]
    fn test_header_too_short() {
        assert!(TacacsHeader::from_bytes(&[0; 5]).is_err());
    }

    #[test]
    fn test_header_unknown_type() {
        let mut bytes = TacacsHeader::new(TacacsPacketType::Authentication, 1, 1, 0).to_bytes();
        bytes[1] = 0xFF;
        assert!(TacacsHeader::from_bytes(&bytes).is_err());
    }

    #[test]
    fn test_authen_start_body_serialization() {
        let body = AuthenStartBody {
            action: AuthenAction::Login,
            authen_type: AuthenType::Pap,
            authen_service: AuthenService::Login,
            user: "admin".to_string(),
            port: "tty0".to_string(),
            remote_address: "10.0.0.1".to_string(),
            data: b"password".to_vec(),
        };
        let bytes = body.to_bytes();
        assert_eq!(bytes[0], AuthenAction::Login as u8);
        assert_eq!(bytes[2], AuthenType::Pap as u8);
        assert_eq!(bytes[4], 5); // user len
    }

    #[test]
    fn test_authen_reply_parsing() {
        let mut data = vec![0x01, 0x00]; // Pass, no flags
        data.extend_from_slice(&3u16.to_be_bytes()); // server_msg_len=3
        data.extend_from_slice(&0u16.to_be_bytes()); // data_len=0
        data.extend_from_slice(b"OK!");

        let reply = AuthenReplyBody::from_bytes(&data).unwrap();
        assert_eq!(reply.status, AuthenStatus::Pass);
        assert_eq!(reply.server_msg, "OK!");
        assert!(reply.data.is_empty());
    }

    #[test]
    fn test_authen_reply_too_short() {
        assert!(AuthenReplyBody::from_bytes(&[0x01, 0x00]).is_err());
    }

    #[test]
    fn test_obfuscate_deobfuscate_roundtrip() {
        let header = TacacsHeader::new(TacacsPacketType::Authentication, 1, 12345, 11);
        let secret = b"shared-secret";
        let original = b"hello world".to_vec();
        let mut encrypted = original.clone();

        obfuscate(&header, secret, &mut encrypted);
        assert_ne!(encrypted, original, "obfuscation should change data");

        obfuscate(&header, secret, &mut encrypted);
        assert_eq!(
            encrypted, original,
            "double obfuscation should restore data"
        );
    }

    #[test]
    fn test_obfuscate_empty_secret_noop() {
        let header = TacacsHeader::new(TacacsPacketType::Authentication, 1, 1, 5);
        let mut data = b"hello".to_vec();
        let orig = data.clone();
        obfuscate(&header, b"", &mut data);
        assert_eq!(data, orig);
    }

    #[test]
    fn test_generate_session_id() {
        let id1 = generate_session_id().unwrap();
        let id2 = generate_session_id().unwrap();
        // Probabilistically these should differ (2^32 space)
        // Just check they don't panic
        assert!(id1 != 0 || id2 != 0);
    }

    #[test]
    fn test_acct_flags() {
        let start = AcctFlags::START;
        assert!(start.is_start());
        assert!(!start.is_stop());
        assert!(!start.is_watchdog());

        let stop = AcctFlags::STOP;
        assert!(stop.is_stop());
    }

    #[test]
    fn test_packet_type_values() {
        assert_eq!(TacacsPacketType::Authentication as u8, 0x01);
        assert_eq!(TacacsPacketType::Authorization as u8, 0x02);
        assert_eq!(TacacsPacketType::Accounting as u8, 0x03);
    }

    // ── Authorization ───────────────────────────────────────────

    #[test]
    fn test_author_request_serialization() {
        let body = AuthorRequestBody {
            authen_method: 0x06, // TACACS+
            authen_type: AuthenType::Pap,
            authen_service: AuthenService::Login,
            user: "admin".to_string(),
            port: "tty0".to_string(),
            remote_address: "10.0.0.1".to_string(),
            args: vec!["service=shell".to_string(), "cmd=show".to_string()],
        };
        let bytes = body.to_bytes();
        assert_eq!(bytes[0], 0x06); // authen_method
        assert_eq!(bytes[7], 2); // arg_count
        // arg lengths follow
        assert_eq!(bytes[8], 13); // "service=shell".len()
        assert_eq!(bytes[9], 8); // "cmd=show".len()
    }

    #[test]
    fn test_author_reply_parsing() {
        // Build: status | arg_cnt | server_msg_len | data_len | arg_lens | msg | data | args
        let mut data = vec![0x01]; // PassAdd
        data.push(2); // arg_count
        data.extend_from_slice(&2u16.to_be_bytes()); // server_msg_len
        data.extend_from_slice(&0u16.to_be_bytes()); // data_len
        data.push(6); // arg0 len ("priv=1")
        data.push(6); // arg1 len ("role=a")
        data.extend_from_slice(b"OK"); // server_msg
        // no data
        data.extend_from_slice(b"priv=1role=a"); // args concatenated

        let reply = AuthorReplyBody::from_bytes(&data).unwrap();
        assert_eq!(reply.status, AuthorStatus::PassAdd);
        assert_eq!(reply.server_msg, "OK");
        assert_eq!(reply.args.len(), 2);
        assert_eq!(reply.args[0], "priv=1");
        assert_eq!(reply.args[1], "role=a");
    }

    #[test]
    fn test_author_reply_too_short() {
        assert!(AuthorReplyBody::from_bytes(&[0x01]).is_err());
    }

    // ── Accounting ──────────────────────────────────────────────

    #[test]
    fn test_acct_request_serialization() {
        let body = AcctRequestBody {
            flags: AcctFlags::START,
            authen_method: 0x06,
            authen_type: AuthenType::Pap,
            authen_service: AuthenService::Login,
            user: "admin".to_string(),
            port: "tty0".to_string(),
            remote_address: "10.0.0.1".to_string(),
            args: vec!["task_id=1".to_string()],
        };
        let bytes = body.to_bytes();
        assert_eq!(bytes[0], AcctFlags::START.0); // flags
        assert_eq!(bytes[8], 1); // arg_count
    }

    #[test]
    fn test_acct_reply_parsing() {
        let mut data = Vec::new();
        data.extend_from_slice(&4u16.to_be_bytes()); // server_msg_len
        data.extend_from_slice(&0u16.to_be_bytes()); // data_len
        data.push(0x01); // status = Success
        data.extend_from_slice(b"Done"); // server_msg

        let reply = AcctReplyBody::from_bytes(&data).unwrap();
        assert_eq!(reply.status, AcctStatus::Success);
        assert_eq!(reply.server_msg, "Done");
    }

    #[test]
    fn test_acct_reply_too_short() {
        assert!(AcctReplyBody::from_bytes(&[0x00, 0x01]).is_err());
    }
}