yamldap 0.0.8

A lightweight LDAP server that serves directory data from YAML files
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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
// Simplified LDAP protocol implementation for testing
// This implements a basic subset of LDAP without full ASN.1 complexity

use bytes::{Buf, BufMut, BytesMut};
use std::io::{self, Cursor};
use tokio_util::codec::{Decoder, Encoder};
use tracing::debug;

use super::protocol::*;

const LDAP_BIND_REQUEST: u8 = 0x60;
const LDAP_BIND_RESPONSE: u8 = 0x61;
const LDAP_UNBIND_REQUEST: u8 = 0x42;
const LDAP_SEARCH_REQUEST: u8 = 0x63;
const LDAP_SEARCH_RESULT_ENTRY: u8 = 0x64;
const LDAP_SEARCH_RESULT_DONE: u8 = 0x65;
const LDAP_COMPARE_REQUEST: u8 = 0x6e;
const LDAP_COMPARE_RESPONSE: u8 = 0x6f;

pub struct SimpleLdapCodec;

impl SimpleLdapCodec {
    fn read_length(buf: &mut Cursor<&[u8]>) -> io::Result<usize> {
        if buf.remaining() < 1 {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "Not enough data for length",
            ));
        }

        let first_byte = buf.get_u8();
        if first_byte & 0x80 == 0 {
            // Short form
            Ok(first_byte as usize)
        } else {
            // Long form
            let num_octets = (first_byte & 0x7f) as usize;
            if num_octets > 4 || buf.remaining() < num_octets {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "Invalid length encoding",
                ));
            }

            let mut length = 0usize;
            for _ in 0..num_octets {
                length = (length << 8) | (buf.get_u8() as usize);
            }
            Ok(length)
        }
    }

    fn write_length(buf: &mut BytesMut, length: usize) {
        if length < 128 {
            buf.put_u8(length as u8);
        } else if length < 256 {
            buf.put_u8(0x81);
            buf.put_u8(length as u8);
        } else if length < 65536 {
            buf.put_u8(0x82);
            buf.put_u16(length as u16);
        } else {
            // For larger lengths, use 3 bytes
            buf.put_u8(0x83);
            buf.put_u8((length >> 16) as u8);
            buf.put_u8((length >> 8) as u8);
            buf.put_u8(length as u8);
        }
    }

    fn read_string(buf: &mut Cursor<&[u8]>) -> io::Result<String> {
        // Read OCTET STRING tag (0x04)
        if buf.remaining() < 1 || buf.get_u8() != 0x04 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Expected OCTET STRING",
            ));
        }

        let length = Self::read_length(buf)?;
        if buf.remaining() < length {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "Not enough data for string",
            ));
        }

        let mut bytes = vec![0u8; length];
        buf.copy_to_slice(&mut bytes);

        String::from_utf8(bytes)
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8"))
    }

    fn write_string(buf: &mut BytesMut, s: &str) {
        buf.put_u8(0x04); // OCTET STRING tag
        Self::write_length(buf, s.len());
        buf.put_slice(s.as_bytes());
    }

    fn read_integer(buf: &mut Cursor<&[u8]>) -> io::Result<u32> {
        // Read INTEGER tag (0x02)
        if buf.remaining() < 1 || buf.get_u8() != 0x02 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Expected INTEGER",
            ));
        }

        let length = Self::read_length(buf)?;
        if length > 4 || buf.remaining() < length {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Invalid integer",
            ));
        }

        let mut value = 0u32;
        for _ in 0..length {
            value = (value << 8) | (buf.get_u8() as u32);
        }
        Ok(value)
    }

    fn write_integer(buf: &mut BytesMut, value: u32) {
        buf.put_u8(0x02); // INTEGER tag
        if value < 128 {
            buf.put_u8(1);
            buf.put_u8(value as u8);
        } else if value < 32768 {
            buf.put_u8(2);
            buf.put_u16(value as u16);
        } else {
            buf.put_u8(4);
            buf.put_u32(value);
        }
    }

    fn read_filter(cursor: &mut Cursor<&[u8]>) -> io::Result<String> {
        if cursor.remaining() < 1 {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "No filter data",
            ));
        }

        let tag = cursor.get_u8();
        let length = Self::read_length(cursor)?;

        // LDAP Filter tags:
        // 0xA0 - AND
        // 0xA1 - OR
        // 0xA2 - NOT
        // 0xA3 - Equality Match
        // 0xA4 - Substring
        // 0xA5 - Greater or Equal
        // 0xA6 - Less or Equal
        // 0x87 - Present (context-specific primitive 7)
        // 0xA8 - Approximate Match
        // 0xA9 - Extensible Match

        match tag {
            0xA0 => {
                // AND filter
                let _end_pos = cursor.position() + length as u64;
                let mut filters = Vec::new();
                while cursor.position() < _end_pos {
                    filters.push(Self::read_filter(cursor)?);
                }
                Ok(format!("(&{})", filters.join("")))
            }
            0xA1 => {
                // OR filter
                let _end_pos = cursor.position() + length as u64;
                let mut filters = Vec::new();
                while cursor.position() < _end_pos {
                    filters.push(Self::read_filter(cursor)?);
                }
                Ok(format!("(|{})", filters.join("")))
            }
            0xA2 => {
                // NOT filter
                let filter = Self::read_filter(cursor)?;
                Ok(format!("(!{})", filter))
            }
            0xA3 => {
                // Equality Match: (attr=value)
                let _end_pos = cursor.position() + length as u64;
                let attr = Self::read_string(cursor)?;
                let value = Self::read_string(cursor)?;
                Ok(format!("({}={})", attr, value))
            }
            0xA4 => {
                // Substring filter: (attr=*value*)
                let _end_pos = cursor.position() + length as u64;
                let attr = Self::read_string(cursor)?;

                // Read substring components
                if cursor.position() < _end_pos
                    && cursor.get_ref()[cursor.position() as usize] == 0x30
                {
                    cursor.get_u8(); // SEQUENCE tag
                    let _seq_len = Self::read_length(cursor)?;

                    let mut parts = Vec::new();
                    let mut has_initial = false;
                    let mut has_final = false;

                    while cursor.position() < _end_pos {
                        let sub_tag = cursor.get_u8();
                        let sub_len = Self::read_length(cursor)?;
                        let mut bytes = vec![0u8; sub_len];
                        cursor.copy_to_slice(&mut bytes);
                        let value = String::from_utf8(bytes).map_err(|_| {
                            io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8")
                        })?;

                        match sub_tag {
                            0x80 => {
                                // initial
                                has_initial = true;
                                parts.insert(0, value);
                            }
                            0x81 => {
                                // any
                                parts.push(format!("*{}", value));
                            }
                            0x82 => {
                                // final
                                has_final = true;
                                parts.push(format!("*{}", value));
                            }
                            _ => {}
                        }
                    }

                    let mut filter = format!("({}=", attr);
                    if !has_initial {
                        filter.push('*');
                    }
                    filter.push_str(&parts.join(""));
                    if !has_final {
                        filter.push('*');
                    }
                    filter.push(')');
                    Ok(filter)
                } else {
                    Ok(format!("({}=*)", attr))
                }
            }
            0xA5 => {
                // Greater or Equal: (attr>=value)
                let attr = Self::read_string(cursor)?;
                let value = Self::read_string(cursor)?;
                Ok(format!("({}>={})", attr, value))
            }
            0xA6 => {
                // Less or Equal: (attr<=value)
                let attr = Self::read_string(cursor)?;
                let value = Self::read_string(cursor)?;
                Ok(format!("({}<={})", attr, value))
            }
            0x87 => {
                // Present: (attr=*)
                let mut bytes = vec![0u8; length];
                cursor.copy_to_slice(&mut bytes);
                let attr = String::from_utf8(bytes)
                    .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8"))?;
                Ok(format!("({}=*)", attr))
            }
            _ => {
                // Unknown filter type, skip it
                cursor.set_position(cursor.position() + length as u64);
                Ok("(objectClass=*)".to_string()) // Default fallback
            }
        }
    }
}

impl Decoder for SimpleLdapCodec {
    type Item = LdapMessage;
    type Error = io::Error;

    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        // Fast path: check minimum size
        if src.len() < 5 {
            return Ok(None);
        }

        // Peek at the message to determine size without copying
        if src[0] != 0x30 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Expected SEQUENCE",
            ));
        }

        // Quick length check
        let (msg_length, header_len) = if src[1] & 0x80 == 0 {
            // Short form
            (src[1] as usize, 2)
        } else {
            let num_octets = (src[1] & 0x7f) as usize;
            if src.len() < 2 + num_octets {
                return Ok(None);
            }

            let mut length = 0usize;
            for i in 0..num_octets {
                length = (length << 8) | (src[2 + i] as usize);
            }
            (length, 2 + num_octets)
        };

        let total_len = header_len + msg_length;
        if src.len() < total_len {
            return Ok(None); // Need more data
        }

        // Now parse the message
        let mut cursor = Cursor::new(&src[..total_len]);
        cursor.set_position(header_len as u64); // Skip the header we already parsed

        // Read message ID
        let message_id = Self::read_integer(&mut cursor)?;

        // Read operation tag
        let op_tag = cursor.get_u8();

        debug!(
            "Received LDAP message: id={}, op_tag=0x{:02x}",
            message_id, op_tag
        );

        let protocol_op = match op_tag {
            LDAP_BIND_REQUEST => {
                // Read bind request length
                let _length = Self::read_length(&mut cursor)?;

                // Read version
                let version = Self::read_integer(&mut cursor)? as u8;

                // Read DN
                let dn = Self::read_string(&mut cursor)?;

                // Read authentication choice
                let auth = if cursor.remaining() > 0 {
                    let auth_tag = cursor.get_u8();
                    if auth_tag == 0x80 {
                        // Simple authentication
                        let pass_len = Self::read_length(&mut cursor)?;
                        let mut pass_bytes = vec![0u8; pass_len];
                        cursor.copy_to_slice(&mut pass_bytes);
                        let password = String::from_utf8(pass_bytes).map_err(|_| {
                            io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8")
                        })?;
                        BindAuthentication::Simple(password)
                    } else {
                        BindAuthentication::Anonymous
                    }
                } else {
                    BindAuthentication::Anonymous
                };

                LdapProtocolOp::BindRequest {
                    version,
                    dn,
                    authentication: auth,
                }
            }

            LDAP_UNBIND_REQUEST => LdapProtocolOp::UnbindRequest,

            LDAP_SEARCH_REQUEST => {
                // Read search request length
                let _length = Self::read_length(&mut cursor)?;

                // Read base DN
                let base_dn = Self::read_string(&mut cursor)?;

                // Read scope (ENUMERATED)
                if cursor.remaining() < 1 || cursor.get_u8() != 0x0A {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "Expected ENUMERATED for scope",
                    ));
                }
                let scope_len = Self::read_length(&mut cursor)?;
                if scope_len != 1 || cursor.remaining() < 1 {
                    return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid scope"));
                }
                let scope_value = cursor.get_u8();
                let scope = match scope_value {
                    0 => SearchScope::BaseObject,
                    1 => SearchScope::SingleLevel,
                    2 => SearchScope::WholeSubtree,
                    _ => SearchScope::WholeSubtree, // Default to subtree
                };

                // Read derefAliases (ENUMERATED)
                if cursor.remaining() < 1 || cursor.get_u8() != 0x0A {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "Expected ENUMERATED for derefAliases",
                    ));
                }
                let deref_len = Self::read_length(&mut cursor)?;
                if deref_len != 1 || cursor.remaining() < 1 {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "Invalid derefAliases",
                    ));
                }
                let _deref_value = cursor.get_u8(); // We'll use NeverDerefAliases for now

                // Read sizeLimit (INTEGER)
                let size_limit = Self::read_integer(&mut cursor)?;

                // Read timeLimit (INTEGER)
                let time_limit = Self::read_integer(&mut cursor)?;

                // Read typesOnly (BOOLEAN)
                if cursor.remaining() < 1 || cursor.get_u8() != 0x01 {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "Expected BOOLEAN for typesOnly",
                    ));
                }
                let bool_len = Self::read_length(&mut cursor)?;
                if bool_len != 1 || cursor.remaining() < 1 {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "Invalid boolean",
                    ));
                }
                let types_only = cursor.get_u8() != 0x00;

                // Read filter - this is complex, so we'll read it as a blob for now
                // and convert to string representation
                let filter = Self::read_filter(&mut cursor)?;

                // Read attributes (SEQUENCE OF OCTET STRING)
                let mut attributes = Vec::new();
                if cursor.remaining() > 0 && cursor.get_ref()[cursor.position() as usize] == 0x30 {
                    cursor.get_u8(); // SEQUENCE tag
                    let attrs_len = Self::read_length(&mut cursor)?;
                    let attrs_end = cursor.position() + attrs_len as u64;

                    while cursor.position() < attrs_end {
                        let attr = Self::read_string(&mut cursor)?;
                        attributes.push(attr);
                    }
                }

                LdapProtocolOp::SearchRequest {
                    base_dn,
                    scope,
                    deref_aliases: DerefAliases::NeverDerefAliases,
                    size_limit,
                    time_limit,
                    types_only,
                    filter,
                    attributes,
                }
            }

            LDAP_COMPARE_REQUEST => {
                // Read compare request length
                let _length = Self::read_length(&mut cursor)?;

                // Read DN
                let dn = Self::read_string(&mut cursor)?;

                // Read AttributeValueAssertion (SEQUENCE)
                if cursor.remaining() < 1 || cursor.get_u8() != 0x30 {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "Expected SEQUENCE for AttributeValueAssertion",
                    ));
                }
                let ava_len = Self::read_length(&mut cursor)?;
                let ava_end = cursor.position() + ava_len as u64;

                // Read attribute description
                let attribute = Self::read_string(&mut cursor)?;

                // Read assertion value
                let value = if cursor.position() < ava_end {
                    Self::read_string(&mut cursor)?
                } else {
                    String::new()
                };

                LdapProtocolOp::CompareRequest {
                    dn,
                    attribute,
                    value,
                }
            }

            _ => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Unsupported operation tag: 0x{:02x}", op_tag),
                ));
            }
        };

        src.advance(total_len);

        Ok(Some(LdapMessage {
            message_id,
            protocol_op,
        }))
    }
}

impl Encoder<LdapMessage> for SimpleLdapCodec {
    type Error = io::Error;

    fn encode(&mut self, item: LdapMessage, dst: &mut BytesMut) -> Result<(), Self::Error> {
        // Reserve space for the message
        dst.reserve(256);

        // We'll write the message content first, then wrap it
        let mut content = BytesMut::new();

        // Write message ID
        Self::write_integer(&mut content, item.message_id);

        // Write protocol operation
        match item.protocol_op {
            LdapProtocolOp::BindResponse { ref result } => {
                // Start bind response
                let mut bind_content = BytesMut::new();

                // Write result code
                Self::write_integer(&mut bind_content, result.result_code as u32);

                // Write matched DN
                Self::write_string(&mut bind_content, &result.matched_dn);

                // Write diagnostic message
                Self::write_string(&mut bind_content, &result.diagnostic_message);

                // Wrap bind response
                content.put_u8(LDAP_BIND_RESPONSE);
                Self::write_length(&mut content, bind_content.len());
                content.put(bind_content);
            }

            LdapProtocolOp::SearchResultEntry {
                ref dn,
                ref attributes,
            } => {
                let mut entry_content = BytesMut::new();

                // Write DN
                Self::write_string(&mut entry_content, dn);

                // Write attributes sequence
                let mut attrs_content = BytesMut::new();

                for (name, values) in attributes {
                    let mut attr_content = BytesMut::new();

                    // Write attribute name
                    Self::write_string(&mut attr_content, name);

                    // Write values SET
                    let mut values_content = BytesMut::new();
                    for value in values {
                        Self::write_string(&mut values_content, value);
                    }

                    attr_content.put_u8(0x31); // SET tag
                    Self::write_length(&mut attr_content, values_content.len());
                    attr_content.put(values_content);

                    // Wrap attribute in SEQUENCE
                    attrs_content.put_u8(0x30); // SEQUENCE tag
                    Self::write_length(&mut attrs_content, attr_content.len());
                    attrs_content.put(attr_content);
                }

                // Write attributes SEQUENCE
                entry_content.put_u8(0x30); // SEQUENCE tag
                Self::write_length(&mut entry_content, attrs_content.len());
                entry_content.put(attrs_content);

                // Wrap search result entry
                content.put_u8(LDAP_SEARCH_RESULT_ENTRY);
                Self::write_length(&mut content, entry_content.len());
                content.put(entry_content);
            }

            LdapProtocolOp::SearchResultDone { ref result } => {
                let mut done_content = BytesMut::new();

                // Write result code
                Self::write_integer(&mut done_content, result.result_code as u32);

                // Write matched DN
                Self::write_string(&mut done_content, &result.matched_dn);

                // Write diagnostic message
                Self::write_string(&mut done_content, &result.diagnostic_message);

                // Wrap search result done
                content.put_u8(LDAP_SEARCH_RESULT_DONE);
                Self::write_length(&mut content, done_content.len());
                content.put(done_content);
            }

            LdapProtocolOp::CompareResponse { ref result } => {
                let mut response_content = BytesMut::new();

                // Write result code
                Self::write_integer(&mut response_content, result.result_code as u32);

                // Write matched DN
                Self::write_string(&mut response_content, &result.matched_dn);

                // Write diagnostic message
                Self::write_string(&mut response_content, &result.diagnostic_message);

                // Wrap compare response
                content.put_u8(LDAP_COMPARE_RESPONSE);
                Self::write_length(&mut content, response_content.len());
                content.put(response_content);
            }

            _ => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "Unsupported operation for encoding",
                ));
            }
        }

        // Wrap the entire message in a SEQUENCE
        dst.put_u8(0x30); // SEQUENCE tag
        Self::write_length(dst, content.len());
        dst.put(content);

        Ok(())
    }
}

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

    #[test]
    fn test_read_write_length_short_form() {
        // Test short form (< 128)
        let mut buf = BytesMut::new();
        SimpleLdapCodec::write_length(&mut buf, 42);

        let mut cursor = Cursor::new(buf.as_ref());
        let length = SimpleLdapCodec::read_length(&mut cursor).unwrap();
        assert_eq!(length, 42);
    }

    #[test]
    fn test_read_write_length_long_form_1_byte() {
        // Test long form with 1 byte (128-255)
        let mut buf = BytesMut::new();
        SimpleLdapCodec::write_length(&mut buf, 200);

        let mut cursor = Cursor::new(buf.as_ref());
        let length = SimpleLdapCodec::read_length(&mut cursor).unwrap();
        assert_eq!(length, 200);
    }

    #[test]
    fn test_read_write_length_long_form_2_bytes() {
        // Test long form with 2 bytes (256-65535)
        let mut buf = BytesMut::new();
        SimpleLdapCodec::write_length(&mut buf, 1000);

        let mut cursor = Cursor::new(buf.as_ref());
        let length = SimpleLdapCodec::read_length(&mut cursor).unwrap();
        assert_eq!(length, 1000);
    }

    #[test]
    fn test_read_write_length_long_form_3_bytes() {
        // Test long form with 3 bytes (>= 65536)
        let mut buf = BytesMut::new();
        SimpleLdapCodec::write_length(&mut buf, 100000);

        let mut cursor = Cursor::new(buf.as_ref());
        let length = SimpleLdapCodec::read_length(&mut cursor).unwrap();
        assert_eq!(length, 100000);
    }

    #[test]
    fn test_read_length_insufficient_data() {
        let buf = vec![];
        let mut cursor = Cursor::new(buf.as_ref());
        let result = SimpleLdapCodec::read_length(&mut cursor);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
    }

    #[test]
    fn test_read_length_invalid_long_form() {
        // Long form with too many octets
        let buf = vec![0x85]; // Claims 5 octets but we don't have them
        let mut cursor = Cursor::new(buf.as_ref());
        let result = SimpleLdapCodec::read_length(&mut cursor);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_read_write_string() {
        let mut buf = BytesMut::new();
        SimpleLdapCodec::write_string(&mut buf, "hello world");

        let mut cursor = Cursor::new(buf.as_ref());
        let string = SimpleLdapCodec::read_string(&mut cursor).unwrap();
        assert_eq!(string, "hello world");
    }

    #[test]
    fn test_read_string_invalid_tag() {
        let buf = vec![0x05]; // Wrong tag
        let mut cursor = Cursor::new(buf.as_ref());
        let result = SimpleLdapCodec::read_string(&mut cursor);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_read_string_insufficient_data() {
        let buf = vec![0x04, 0x10]; // Claims 16 bytes but we don't have them
        let mut cursor = Cursor::new(buf.as_ref());
        let result = SimpleLdapCodec::read_string(&mut cursor);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
    }

    #[test]
    fn test_read_string_invalid_utf8() {
        let buf = vec![0x04, 0x02, 0xFF, 0xFF]; // Invalid UTF-8
        let mut cursor = Cursor::new(buf.as_ref());
        let result = SimpleLdapCodec::read_string(&mut cursor);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_read_write_integer() {
        let mut buf = BytesMut::new();
        SimpleLdapCodec::write_integer(&mut buf, 42);

        let mut cursor = Cursor::new(buf.as_ref());
        let value = SimpleLdapCodec::read_integer(&mut cursor).unwrap();
        assert_eq!(value, 42);
    }

    #[test]
    fn test_read_integer_invalid_tag() {
        let buf = vec![0x03]; // Wrong tag
        let mut cursor = Cursor::new(buf.as_ref());
        let result = SimpleLdapCodec::read_integer(&mut cursor);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_decode_empty_buffer() {
        let mut codec = SimpleLdapCodec;
        let mut buf = BytesMut::new();
        let result = codec.decode(&mut buf).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_decode_partial_message() {
        let mut codec = SimpleLdapCodec;
        let mut buf = BytesMut::from(&[0x30, 0x10][..]); // SEQUENCE with length 16 but no content
        let result = codec.decode(&mut buf).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_decode_invalid_sequence_tag() {
        let mut codec = SimpleLdapCodec;
        let mut buf = BytesMut::from(&[0x31, 0x02, 0x00, 0x00, 0x00][..]); // Wrong tag with 5 bytes
        let result = codec.decode(&mut buf);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_encode_bind_request() {
        let mut codec = SimpleLdapCodec;
        let mut buf = BytesMut::new();

        let msg = LdapMessage {
            message_id: 1,
            protocol_op: LdapProtocolOp::BindRequest {
                version: 3,
                dn: "".to_string(), // Anonymous bind
                authentication: BindAuthentication::Anonymous,
            },
        };

        // BindRequest encoding is not implemented in SimpleLdapCodec
        let result = codec.encode(msg, &mut buf);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_encode_bind_response() {
        let mut codec = SimpleLdapCodec;
        let mut buf = BytesMut::new();

        let msg = LdapMessage {
            message_id: 1,
            protocol_op: LdapProtocolOp::BindResponse {
                result: LdapResult::success(),
            },
        };

        let result = codec.encode(msg, &mut buf);
        assert!(result.is_ok());
        assert!(!buf.is_empty());
    }

    #[test]
    fn test_encode_search_result_entry() {
        let mut codec = SimpleLdapCodec;
        let mut buf = BytesMut::new();

        let mut attrs = HashMap::new();
        attrs.insert("cn".to_string(), vec!["test".to_string()]);

        let msg = LdapMessage {
            message_id: 2,
            protocol_op: LdapProtocolOp::SearchResultEntry {
                dn: "cn=test,dc=example,dc=com".to_string(),
                attributes: attrs,
            },
        };

        let result = codec.encode(msg, &mut buf);
        assert!(result.is_ok());
        assert!(!buf.is_empty());
    }

    #[test]
    fn test_encode_search_result_done() {
        let mut codec = SimpleLdapCodec;
        let mut buf = BytesMut::new();

        let msg = LdapMessage {
            message_id: 3,
            protocol_op: LdapProtocolOp::SearchResultDone {
                result: LdapResult::error(LdapResultCode::NoSuchObject, "Not found".to_string()),
            },
        };

        let result = codec.encode(msg, &mut buf);
        assert!(result.is_ok());
        assert!(!buf.is_empty());
    }

    #[test]
    fn test_encode_unsupported_operation() {
        let mut codec = SimpleLdapCodec;
        let mut buf = BytesMut::new();

        let msg = LdapMessage {
            message_id: 1,
            protocol_op: LdapProtocolOp::UnbindRequest,
        };

        let result = codec.encode(msg, &mut buf);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_roundtrip_bind_response() {
        let mut codec = SimpleLdapCodec;

        // Encode
        let original = LdapMessage {
            message_id: 42,
            protocol_op: LdapProtocolOp::BindResponse {
                result: LdapResult::success(),
            },
        };

        let mut buf = BytesMut::new();
        codec.encode(original.clone(), &mut buf).unwrap();

        // This test would require implementing decode for BindResponse
        // For now, just check that encoding succeeded
        assert!(!buf.is_empty());
        assert_eq!(buf[0], 0x30); // SEQUENCE tag
    }

    #[test]
    fn test_write_integer_various_sizes() {
        // Test single byte integer
        let mut buf = BytesMut::new();
        SimpleLdapCodec::write_integer(&mut buf, 127);
        assert_eq!(buf[0], 0x02); // INTEGER tag
        assert_eq!(buf[1], 0x01); // length
        assert_eq!(buf[2], 127);

        // Test multi-byte integer
        let mut buf = BytesMut::new();
        SimpleLdapCodec::write_integer(&mut buf, 300);
        assert_eq!(buf[0], 0x02); // INTEGER tag
        assert_eq!(buf[1], 0x02); // length
        assert_eq!(buf[2], 0x01); // high byte
        assert_eq!(buf[3], 0x2C); // low byte (300 = 0x012C)
    }

    #[test]
    fn test_read_integer_multi_byte() {
        // Test reading multi-byte integer
        let buf = vec![0x02, 0x02, 0x01, 0x2C]; // INTEGER 300
        let mut cursor = Cursor::new(buf.as_ref());
        let value = SimpleLdapCodec::read_integer(&mut cursor).unwrap();
        assert_eq!(value, 300);
    }

    #[test]
    fn test_decode_with_debug_logging() {
        let mut codec = SimpleLdapCodec;
        let mut buf = BytesMut::new();

        // Create a simple bind request
        buf.put_u8(0x30); // SEQUENCE
        buf.put_u8(0x0C); // length 12
        buf.put_u8(0x02); // INTEGER (message ID)
        buf.put_u8(0x01); // length 1
        buf.put_u8(0x01); // value 1
        buf.put_u8(0x60); // Bind Request
        buf.put_u8(0x07); // length 7
        buf.put_u8(0x02); // INTEGER (version)
        buf.put_u8(0x01); // length 1
        buf.put_u8(0x03); // value 3
        buf.put_u8(0x04); // OCTET STRING (DN)
        buf.put_u8(0x00); // length 0 (empty)
        buf.put_u8(0x80); // Simple auth
        buf.put_u8(0x00); // length 0 (anonymous)

        let result = codec.decode(&mut buf);
        assert!(result.is_ok());
        let msg = result.unwrap().unwrap();
        assert_eq!(msg.message_id, 1);
    }

    #[test]
    fn test_decode_compare_request() {
        let mut codec = SimpleLdapCodec;
        let mut buf = BytesMut::new();

        // Build the compare request content first
        let mut compare_content = BytesMut::new();

        // DN
        compare_content.put_u8(0x04); // OCTET STRING
        compare_content.put_u8(0x0e); // length 14
        compare_content.put_slice(b"cn=test,dc=com");

        // AttributeValueAssertion SEQUENCE
        compare_content.put_u8(0x30); // SEQUENCE
        compare_content.put_u8(0x0a); // length 10

        // Attribute
        compare_content.put_u8(0x04); // OCTET STRING
        compare_content.put_u8(0x02); // length 2
        compare_content.put_slice(b"cn");

        // Value
        compare_content.put_u8(0x04); // OCTET STRING
        compare_content.put_u8(0x04); // length 4
        compare_content.put_slice(b"test");

        let compare_len = compare_content.len();

        // Build the message
        let mut message_content = BytesMut::new();

        // Message ID
        message_content.put_u8(0x02); // INTEGER
        message_content.put_u8(0x01); // length 1
        message_content.put_u8(0x01); // value 1

        // CompareRequest [APPLICATION 14]
        message_content.put_u8(0x6e); // Compare request tag
        message_content.put_u8(compare_len as u8); // length
        message_content.put(compare_content);

        // Wrap in SEQUENCE
        buf.put_u8(0x30); // SEQUENCE
        buf.put_u8(message_content.len() as u8);
        buf.put(message_content);

        let result = codec.decode(&mut buf);
        if let Err(e) = &result {
            panic!("Decode failed: {:?}", e);
        }
        assert!(result.is_ok());
        let msg = result.unwrap().unwrap();
        assert_eq!(msg.message_id, 1);

        match msg.protocol_op {
            LdapProtocolOp::CompareRequest {
                dn,
                attribute,
                value,
            } => {
                assert_eq!(dn, "cn=test,dc=com");
                assert_eq!(attribute, "cn");
                assert_eq!(value, "test");
            }
            _ => panic!("Expected CompareRequest"),
        }
    }

    #[test]
    fn test_encode_compare_response() {
        let mut codec = SimpleLdapCodec;

        // Test CompareTrue response
        let msg = LdapMessage {
            message_id: 1,
            protocol_op: LdapProtocolOp::CompareResponse {
                result: LdapResult {
                    result_code: LdapResultCode::CompareTrue,
                    matched_dn: "cn=test,dc=com".to_string(),
                    diagnostic_message: String::new(),
                },
            },
        };

        let mut buf = BytesMut::new();
        let result = codec.encode(msg, &mut buf);
        assert!(result.is_ok());
        assert!(!buf.is_empty());
        assert_eq!(buf[0], 0x30); // SEQUENCE tag

        // Verify the response tag is correct
        let mut found_response_tag = false;
        for i in 0..buf.len() {
            if buf[i] == LDAP_COMPARE_RESPONSE {
                found_response_tag = true;
                break;
            }
        }
        assert!(found_response_tag, "Compare response tag not found");
    }
}