partitionline 0.1.0

Pure-Rust Apache Kafka client and protocol implementation
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
//! SaslHandshake (api 17, v0–v1) and SaslAuthenticate (api 36, v0–v2),
//! plus PLAIN / SCRAM / OAUTHBEARER helpers.

use std::collections::HashMap;
use std::time::Duration;

use bytes::{Buf, BufMut, BytesMut};

use super::buf;
use crate::error::{self, Error, Result};
use crate::net::BrokerConn;
use crate::protocol::api::ApiVersion;
use crate::protocol::api_keys::{pick_version, SASL_AUTHENTICATE, SASL_HANDSHAKE};

/// `true` when SaslHandshake `version` is flexible.
///
/// Official Kafka 4.0 JSON: `validVersions: "0-1"`, `flexibleVersions: "none"`.
/// v0 and v1 have the same fields. v1 exists so the client can then use
/// SaslAuthenticate. Version cannot be easily bumped (KAFKA-9577).
fn sasl_handshake_flexible(version: i16) -> Result<bool> {
    match version {
        0..=1 => Ok(false),
        other => Err(Error::protocol(format!(
            "SaslHandshake version {other} is not implemented"
        ))),
    }
}

/// `true` when SaslAuthenticate `version` is flexible (v2).
///
/// Official Kafka 4.0 JSON: `validVersions: "0-2"`, `flexibleVersions: "2+"`.
/// v0 and v1 request match (AuthBytes). v1+ SessionLifetimeMs.
fn sasl_authenticate_flexible(version: i16) -> Result<bool> {
    match version {
        0..=1 => Ok(false),
        2 => Ok(true),
        other => Err(Error::protocol(format!(
            "SaslAuthenticate version {other} is not implemented"
        ))),
    }
}

/// Pick SaslHandshake (0–1) and SaslAuthenticate (0–2) from ApiVersions.
///
/// `-1` on [`BrokerConn`] means unset because `0` is a spoken version.
pub fn apply_api_keys(conn: &mut BrokerConn, keys: &[ApiVersion]) {
    conn.sasl_handshake_version = keys
        .iter()
        .find(|k| k.api_key == SASL_HANDSHAKE)
        .and_then(|v| pick_version(v.min_version, v.max_version, 0, 1))
        .unwrap_or(-1);
    conn.sasl_authenticate_version = keys
        .iter()
        .find(|k| k.api_key == SASL_AUTHENTICATE)
        .and_then(|v| pick_version(v.min_version, v.max_version, 0, 2))
        .unwrap_or(-1);
}

fn spoken_sasl_versions(conn: &BrokerConn) -> Result<(i16, i16)> {
    let handshake = match conn.sasl_handshake_version {
        0..=1 => conn.sasl_handshake_version,
        _ => {
            return Err(Error::Unsupported(
                "broker does not support SaslHandshake v0-1".into(),
            ))
        }
    };
    let authenticate = match conn.sasl_authenticate_version {
        0..=2 => conn.sasl_authenticate_version,
        _ => {
            return Err(Error::Unsupported(
                "broker does not support SaslAuthenticate v0-2".into(),
            ))
        }
    };
    Ok((handshake, authenticate))
}

/// Encode SaslHandshake v0–v1 with the requested mechanism name.
///
/// Kafka 4.0 JSON: `validVersions: "0-1"`, `flexibleVersions: "none"`.
/// This crate speaks 0–1. v2+ is not spoken.
pub fn encode_sasl_handshake_request(
    buf: &mut BytesMut,
    version: i16,
    mechanism: &str,
) -> crate::error::Result<()> {
    let flexible = sasl_handshake_flexible(version)?;
    buf::put_string(buf, flexible, Some(mechanism))?;
    Ok(())
}

/// Decode SaslHandshake v0–v1: mechanism name.
pub fn decode_sasl_handshake_request<B: Buf>(buf: &mut B, version: i16) -> Result<String> {
    let flexible = sasl_handshake_flexible(version)?;
    Ok(buf::get_string(buf, flexible)?.unwrap_or_default())
}

/// Encode SaslHandshake v0–v1: error code plus enabled mechanism names.
pub fn encode_sasl_handshake_response(
    buf: &mut BytesMut,
    version: i16,
    error_code: i16,
    mechanisms: &[&str],
) -> crate::error::Result<()> {
    let flexible = sasl_handshake_flexible(version)?;
    buf.put_i16(error_code);
    buf::put_array_len(buf, flexible, Some(mechanisms.len()))?;
    for m in mechanisms {
        buf::put_string(buf, flexible, Some(m))?;
    }
    Ok(())
}

/// Decode SaslHandshake v0–v1: `(error_code, mechanisms)`.
pub fn decode_sasl_handshake_response<B: Buf>(
    buf: &mut B,
    version: i16,
) -> Result<(i16, Vec<String>)> {
    let flexible = sasl_handshake_flexible(version)?;
    let error_code = buf::get_i16(buf)?;
    let n = buf::get_array_len(buf, flexible)?.unwrap_or(0);
    let mut mechs = Vec::with_capacity(n);
    for _ in 0..n {
        mechs.push(buf::get_string(buf, flexible)?.unwrap_or_default());
    }
    Ok((error_code, mechs))
}

/// Java `SaslHandshakeRequest` helpers.
pub struct SaslHandshakeRequest;

impl SaslHandshakeRequest {
    /// Java `SaslHandshakeRequest.getErrorResponse`.
    ///
    /// Mechanisms stay empty (the requested mechanism is not copied). v0
    /// and v1 bodies match (`flexibleVersions: "none"`).
    pub fn error_response(
        buf: &mut BytesMut,
        version: i16,
        error_code: i16,
    ) -> crate::error::Result<()> {
        encode_sasl_handshake_response(buf, version, error_code, &[])
    }
}

/// Java `SaslHandshakeResponse` helpers.
pub struct SaslHandshakeResponse;

impl SaslHandshakeResponse {
    /// Java `SaslHandshakeResponse.errorCounts`.
    ///
    /// Top-level `errorCode` only, including `NONE` (Java
    /// `Collections.singletonMap`). Mechanisms are not counted. This is
    /// not SaslAuthenticate `errorCounts`.
    #[must_use]
    pub fn error_counts(error_code: i16) -> HashMap<i16, i32> {
        HashMap::from([(error_code, 1)])
    }
}

/// Encode SaslAuthenticate v0–v2 with the SASL client bytes.
///
/// Kafka 4.0 JSON: `validVersions: "0-2"`, `flexibleVersions: "2+"`.
/// This crate speaks 0–2. v3+ is not spoken.
pub fn encode_sasl_authenticate_request(
    buf: &mut BytesMut,
    version: i16,
    auth_bytes: &[u8],
) -> crate::error::Result<()> {
    let flexible = sasl_authenticate_flexible(version)?;
    buf::put_bytes(buf, flexible, Some(auth_bytes))?;
    if flexible {
        buf::put_empty_tagged_fields(buf);
    }
    Ok(())
}

/// Decode SaslAuthenticate v0–v2: client/server SASL bytes.
pub fn decode_sasl_authenticate_request<B: Buf>(buf: &mut B, version: i16) -> Result<Vec<u8>> {
    let flexible = sasl_authenticate_flexible(version)?;
    let bytes = buf::get_bytes(buf, flexible)?.unwrap_or_default();
    if flexible {
        buf::skip_tagged_fields(buf)?;
    }
    Ok(bytes)
}

/// Encode SaslAuthenticate v0–v2: error, optional message, SASL bytes,
/// and v1+ SessionLifetimeMs.
///
/// Below v1 SessionLifetimeMs is omitted even when the body has a
/// non-zero value. Decode fills the JSON default (`0`). v2 is flexible.
pub fn encode_sasl_authenticate_response(
    buf: &mut BytesMut,
    version: i16,
    error_code: i16,
    message: Option<&str>,
    auth_bytes: &[u8],
    session_lifetime_ms: i64,
) -> crate::error::Result<()> {
    let flexible = sasl_authenticate_flexible(version)?;
    buf.put_i16(error_code);
    buf::put_string(buf, flexible, message)?;
    buf::put_bytes(buf, flexible, Some(auth_bytes))?;
    if version >= 1 {
        buf.put_i64(session_lifetime_ms);
    }
    if flexible {
        buf::put_empty_tagged_fields(buf);
    }
    Ok(())
}

/// Decode SaslAuthenticate v0–v2: `(error_code, error_message, auth_bytes,
/// session_lifetime_ms)`.
///
/// Below v1 SessionLifetimeMs is omitted; decode fills `0`.
pub fn decode_sasl_authenticate_response<B: Buf>(
    buf: &mut B,
    version: i16,
) -> Result<(i16, Option<String>, Vec<u8>, i64)> {
    let flexible = sasl_authenticate_flexible(version)?;
    let error_code = buf::get_i16(buf)?;
    let message = buf::get_string(buf, flexible)?;
    let bytes = buf::get_bytes(buf, flexible)?.unwrap_or_default();
    let session_lifetime_ms = if version >= 1 { buf::get_i64(buf)? } else { 0 };
    if flexible {
        buf::skip_tagged_fields(buf)?;
    }
    Ok((error_code, message, bytes, session_lifetime_ms))
}

/// Java `SaslAuthenticateRequest` helpers.
pub struct SaslAuthenticateRequest;

impl SaslAuthenticateRequest {
    /// Java `SaslAuthenticateRequest.getErrorResponse`.
    ///
    /// AuthBytes stay empty (the request bytes are not copied).
    /// SessionLifetimeMs is the JSON default (`0`) on v1+. The Java
    /// `throttleTimeMs` argument is unused (no throttle field).
    /// `ErrorMessage` stays the JSON default (null); official Java also
    /// sets the English `Errors.message` string. Encode still writes the
    /// caller's AuthBytes / message as-is.
    pub fn error_response(
        buf: &mut BytesMut,
        version: i16,
        error_code: i16,
    ) -> crate::error::Result<()> {
        encode_sasl_authenticate_response(buf, version, error_code, None, &[], 0)
    }
}

/// Java `SaslAuthenticateResponse` helpers.
pub struct SaslAuthenticateResponse;

impl SaslAuthenticateResponse {
    /// Java `SaslAuthenticateResponse.errorCounts`.
    ///
    /// Top-level `errorCode` only, including `NONE` (Java
    /// `Collections.singletonMap`). AuthBytes / ErrorMessage /
    /// SessionLifetimeMs are not counted. This is not SaslHandshake
    /// `errorCounts`.
    #[must_use]
    pub fn error_counts(error_code: i16) -> HashMap<i16, i32> {
        HashMap::from([(error_code, 1)])
    }
}

/// RFC 4616 PLAIN: `NUL authcid NUL passwd`.
pub fn plain_auth_bytes(user: &str, pass: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(user.len() + pass.len() + 2);
    out.push(0);
    out.extend_from_slice(user.as_bytes());
    out.push(0);
    out.extend_from_slice(pass.as_bytes());
    out
}

/// Parse RFC 4616 PLAIN client bytes into `(authcid, passwd)`.
pub fn parse_plain_auth_bytes(bytes: &[u8]) -> Option<(String, String)> {
    // RFC 4616: [authzid] NUL authcid NUL passwd. Clients send NUL user NUL pass.
    let mut parts = bytes.split(|b| *b == 0);
    let _authzid = parts.next()?;
    let user = std::str::from_utf8(parts.next()?).ok()?;
    let pass = std::str::from_utf8(parts.next()?).ok()?;
    Some((user.to_string(), pass.to_string()))
}

/// SaslHandshake + SaslAuthenticate for PLAIN.
pub async fn authenticate_plain(
    conn: &mut BrokerConn,
    user: &str,
    pass: &str,
    timeout: Duration,
) -> Result<()> {
    let (hs_version, auth_version) = spoken_sasl_versions(conn)?;
    let hs = conn
        .roundtrip_sasl(
            SASL_HANDSHAKE,
            hs_version,
            |buf| encode_sasl_handshake_request(buf, hs_version, "PLAIN"),
            timeout,
        )
        .await?;
    let (code, mechs) = decode_sasl_handshake_response(&mut hs.clone(), hs_version)?;
    if code != 0 {
        return Err(Error::broker(code, "SaslHandshake"));
    }
    if !mechs.iter().any(|m| m == "PLAIN") {
        return Err(Error::Unsupported(format!(
            "PLAIN not in mechanisms {mechs:?}"
        )));
    }
    let auth = plain_auth_bytes(user, pass);
    let body = conn
        .roundtrip_sasl(
            SASL_AUTHENTICATE,
            auth_version,
            |buf| encode_sasl_authenticate_request(buf, auth_version, &auth),
            timeout,
        )
        .await?;
    let (code, msg, _, _) = decode_sasl_authenticate_response(&mut body.clone(), auth_version)?;
    if code != 0 {
        return Err(Error::broker(
            if code == 0 {
                error::SASL_AUTHENTICATION_FAILED
            } else {
                code
            },
            msg.unwrap_or_else(|| "SaslAuthenticate".into()),
        ));
    }
    Ok(())
}

/// SaslHandshake + RFC 5802 client/server messages for SCRAM-SHA-256 or SHA-512.
pub async fn authenticate_scram(
    conn: &mut BrokerConn,
    alg: super::scram::ScramAlg,
    user: &str,
    pass: &str,
    timeout: Duration,
) -> Result<()> {
    let (hs_version, auth_version) = spoken_sasl_versions(conn)?;
    let name = alg.name();
    let hs = conn
        .roundtrip_sasl(
            SASL_HANDSHAKE,
            hs_version,
            |buf| encode_sasl_handshake_request(buf, hs_version, name),
            timeout,
        )
        .await?;
    let (code, mechs) = decode_sasl_handshake_response(&mut hs.clone(), hs_version)?;
    if code != 0 {
        return Err(Error::broker(code, "SaslHandshake"));
    }
    if !mechs.iter().any(|m| m == name) {
        return Err(Error::Unsupported(format!(
            "{name} not in mechanisms {mechs:?}"
        )));
    }
    let nonce = super::scram::client_nonce();
    let (first, bare) = super::scram::client_first(user, &nonce);
    let body = conn
        .roundtrip_sasl(
            SASL_AUTHENTICATE,
            auth_version,
            |buf| encode_sasl_authenticate_request(buf, auth_version, first.as_bytes()),
            timeout,
        )
        .await?;
    let (code, msg, bytes, _) = decode_sasl_authenticate_response(&mut body.clone(), auth_version)?;
    if code != 0 {
        return Err(Error::broker(
            code,
            msg.unwrap_or_else(|| "SaslAuthenticate".into()),
        ));
    }
    let server_first =
        String::from_utf8(bytes).map_err(|_| Error::protocol("scram server-first not utf8"))?;
    let client_final = super::scram::client_final(alg, pass, &bare, &server_first)?;
    let body = conn
        .roundtrip_sasl(
            SASL_AUTHENTICATE,
            auth_version,
            |buf| encode_sasl_authenticate_request(buf, auth_version, client_final.as_bytes()),
            timeout,
        )
        .await?;
    let (code, msg, bytes, _) = decode_sasl_authenticate_response(&mut body.clone(), auth_version)?;
    if code != 0 {
        return Err(Error::broker(
            code,
            msg.unwrap_or_else(|| "SaslAuthenticate".into()),
        ));
    }
    let server_final =
        String::from_utf8(bytes).map_err(|_| Error::protocol("scram server-final not utf8"))?;
    super::scram::verify_server_final(
        alg,
        pass,
        &bare,
        &server_first,
        &client_final,
        &server_final,
    )
}

/// [`authenticate_scram`] with [`super::scram::ScramAlg::Sha256`].
pub async fn authenticate_scram_sha256(
    conn: &mut BrokerConn,
    user: &str,
    pass: &str,
    timeout: Duration,
) -> Result<()> {
    authenticate_scram(conn, super::scram::ScramAlg::Sha256, user, pass, timeout).await
}

/// OAUTHBEARER with an unsecured JWT for `principal` (librdkafka unsecure jwt).
pub async fn authenticate_oauthbearer(
    conn: &mut BrokerConn,
    principal: &str,
    timeout: Duration,
) -> Result<()> {
    let token = super::oauth::unsecured_jwt_now(principal);
    authenticate_oauthbearer_token(conn, &token, timeout).await
}

/// OAUTHBEARER with a caller-supplied access token (OIDC or unsecured JWT).
pub async fn authenticate_oauthbearer_token(
    conn: &mut BrokerConn,
    token: &str,
    timeout: Duration,
) -> Result<()> {
    let (hs_version, auth_version) = spoken_sasl_versions(conn)?;
    let hs = conn
        .roundtrip_sasl(
            SASL_HANDSHAKE,
            hs_version,
            |buf| encode_sasl_handshake_request(buf, hs_version, "OAUTHBEARER"),
            timeout,
        )
        .await?;
    let (code, mechs) = decode_sasl_handshake_response(&mut hs.clone(), hs_version)?;
    if code != 0 {
        return Err(Error::broker(code, "SaslHandshake"));
    }
    if !mechs.iter().any(|m| m == "OAUTHBEARER") {
        return Err(Error::Unsupported(format!(
            "OAUTHBEARER not in mechanisms {mechs:?}"
        )));
    }
    let auth = super::oauth::client_initial(token);
    let body = conn
        .roundtrip_sasl(
            SASL_AUTHENTICATE,
            auth_version,
            |buf| encode_sasl_authenticate_request(buf, auth_version, &auth),
            timeout,
        )
        .await?;
    let (code, msg, bytes, _) = decode_sasl_authenticate_response(&mut body.clone(), auth_version)?;
    if code != 0 {
        return Err(Error::broker(
            code,
            msg.unwrap_or_else(|| "SaslAuthenticate".into()),
        ));
    }
    // RFC 7628 / librdkafka: empty server-first = success. Non-empty is an
    // error JSON; send a final SOH then fail.
    if !bytes.is_empty() {
        let err = String::from_utf8_lossy(&bytes).into_owned();
        drop(
            conn.roundtrip_sasl(
                SASL_AUTHENTICATE,
                auth_version,
                |buf| encode_sasl_authenticate_request(buf, auth_version, &[0x01]),
                timeout,
            )
            .await,
        );
        return Err(Error::protocol(format!("oauthbearer: {err}")));
    }
    Ok(())
}

/// Run the one configured SASL mechanism, or return immediately when none is set.
pub async fn authenticate(
    conn: &mut BrokerConn,
    sasl_plain: Option<&(String, String)>,
    sasl_scram: Option<&(String, String)>,
    sasl_scram_sha512: Option<&(String, String)>,
    sasl_oauthbearer: Option<&str>,
    sasl_oidc: Option<&super::oidc::OidcConfig>,
    timeout: Duration,
) -> Result<()> {
    let n = [
        sasl_plain.is_some(),
        sasl_scram.is_some(),
        sasl_scram_sha512.is_some(),
        sasl_oauthbearer.is_some(),
        sasl_oidc.is_some(),
    ]
    .into_iter()
    .filter(|x| *x)
    .count();
    if n > 1 {
        return Err(Error::protocol(
            "set only one of sasl_plain, sasl_scram, sasl_scram_sha512, sasl_oauthbearer, sasl_oauthbearer_oidc",
        ));
    }
    if let Some((u, p)) = sasl_plain {
        return authenticate_plain(conn, u, p, timeout).await;
    }
    if let Some((u, p)) = sasl_scram {
        return authenticate_scram(conn, super::scram::ScramAlg::Sha256, u, p, timeout).await;
    }
    if let Some((u, p)) = sasl_scram_sha512 {
        return authenticate_scram(conn, super::scram::ScramAlg::Sha512, u, p, timeout).await;
    }
    if let Some(oidc) = sasl_oidc {
        let token = super::oidc::fetch_client_credentials_token(oidc, timeout).await?;
        return authenticate_oauthbearer_token(conn, &token, timeout).await;
    }
    if let Some(principal) = sasl_oauthbearer {
        return authenticate_oauthbearer(conn, principal, timeout).await;
    }
    Ok(())
}

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

    use bytes::Buf;

    #[test]
    fn plain_bytes_roundtrip() {
        let b = plain_auth_bytes("alice", "secret");
        assert_eq!(
            parse_plain_auth_bytes(&b),
            Some(("alice".into(), "secret".into()))
        );
    }

    #[test]
    fn handshake_roundtrip() {
        let mut buf = BytesMut::new();
        encode_sasl_handshake_request(&mut buf, 1, "PLAIN").unwrap();
        assert_eq!(
            decode_sasl_handshake_request(&mut &buf[..], 1).unwrap(),
            "PLAIN"
        );
        let mut resp = BytesMut::new();
        encode_sasl_handshake_response(&mut resp, 1, 0, &["PLAIN"]).unwrap();
        let (c, m) = decode_sasl_handshake_response(&mut &resp[..], 1).unwrap();
        assert_eq!(c, 0);
        assert_eq!(m, vec!["PLAIN".to_string()]);
    }

    #[test]
    fn sasl_handshake_error_response_matches_java() {
        // Java SaslHandshakeRequest.getErrorResponse: ErrorCode only.
        // Mechanisms stay empty (the requested mechanism is not copied).
        // v0 and v1 response bodies match (never flexible).
        for version in [0_i16, 1] {
            let mut expected = BytesMut::new();
            encode_sasl_handshake_response(&mut expected, version, 16, &[]).unwrap();
            let mut got = BytesMut::new();
            SaslHandshakeRequest::error_response(&mut got, version, 16).unwrap();
            assert_eq!(
                &got[..],
                &expected[..],
                "SaslHandshake v{version} getErrorResponse must match empty-Mechanisms encode"
            );
            let mut cur = &got[..];
            let (err, mechs) = decode_sasl_handshake_response(&mut cur, version).unwrap();
            assert_eq!(err, 16);
            assert!(mechs.is_empty(), "v{version} Mechanisms must be empty");
            assert!(
                cur.is_empty(),
                "SaslHandshake v{version} getErrorResponse leftover-empty; leftover {} bytes",
                cur.len()
            );
        }
        let mut v0 = BytesMut::new();
        SaslHandshakeRequest::error_response(&mut v0, 0, 16).unwrap();
        let mut v1 = BytesMut::new();
        SaslHandshakeRequest::error_response(&mut v1, 1, 16).unwrap();
        assert_eq!(&v0[..], &v1[..], "v0 and v1 getErrorResponse bodies match");
        let mut with_plain = BytesMut::new();
        encode_sasl_handshake_response(&mut with_plain, 1, 16, &["PLAIN"]).unwrap();
        assert_ne!(
            &v1[..],
            &with_plain[..],
            "getErrorResponse must not copy the requested mechanism"
        );
    }

    #[test]
    fn sasl_handshake_response_error_counts_matches_java() {
        // Java SaslHandshakeResponse.errorCounts:
        // Collections.singletonMap(Errors.forCode(data.errorCode()), 1),
        // including NONE. Official Java SaslHandshakeResponse.errorCounts.
        // Java error() is Errors.forCode only (identity on i16; not mapped).
        // Mechanisms are not counted. This is not SaslAuthenticate
        // errorCounts / enabledMechanisms.
        assert_eq!(
            SaslHandshakeResponse::error_counts(0),
            HashMap::from([(0, 1)]),
            "NONE is a singleton 1, not an empty map"
        );
        assert_eq!(
            SaslHandshakeResponse::error_counts(crate::error::UNSUPPORTED_SASL_MECHANISM),
            HashMap::from([(crate::error::UNSUPPORTED_SASL_MECHANISM, 1)])
        );
        for version in 0..=1_i16 {
            let mut resp = BytesMut::new();
            encode_sasl_handshake_response(
                &mut resp,
                version,
                crate::error::UNSUPPORTED_SASL_MECHANISM,
                &["PLAIN"],
            )
            .unwrap();
            let mut cur = &resp[..];
            let (err, ..) = decode_sasl_handshake_response(&mut cur, version).unwrap();
            assert_eq!(
                SaslHandshakeResponse::error_counts(err),
                HashMap::from([(crate::error::UNSUPPORTED_SASL_MECHANISM, 1)]),
                "SaslHandshake v{version} errorCounts must count the decoded code"
            );
            assert!(
                cur.is_empty(),
                "SaslHandshake v{version} errorCounts leftover-empty; leftover {} bytes",
                cur.len()
            );
        }
    }

    #[test]
    fn sasl_authenticate_error_response_matches_java() {
        // Java SaslAuthenticateRequest.getErrorResponse: ErrorCode only.
        // AuthBytes stay empty (the request bytes are not copied).
        // SessionLifetimeMs is the JSON default (0) on v1+. ErrorMessage
        // stays the JSON default (null). The Java throttleTimeMs argument
        // is unused (no throttle field).
        for version in [0_i16, 1, 2] {
            let mut expected = BytesMut::new();
            encode_sasl_authenticate_response(&mut expected, version, 16, None, &[], 0).unwrap();
            let mut got = BytesMut::new();
            SaslAuthenticateRequest::error_response(&mut got, version, 16).unwrap();
            assert_eq!(
                &got[..],
                &expected[..],
                "SaslAuthenticate v{version} getErrorResponse must match empty-AuthBytes encode"
            );
            let mut cur = &got[..];
            let (err, msg, bytes, lifetime) =
                decode_sasl_authenticate_response(&mut cur, version).unwrap();
            assert_eq!(err, 16);
            assert_eq!(msg, None, "v{version} ErrorMessage stays JSON default null");
            assert!(bytes.is_empty(), "v{version} AuthBytes must be empty");
            assert_eq!(
                lifetime, 0,
                "v{version} SessionLifetimeMs stays JSON default 0"
            );
            assert!(
                cur.is_empty(),
                "SaslAuthenticate v{version} Request.getErrorResponse leftover-empty; leftover {} bytes",
                cur.len()
            );
        }
        for version in [0_i16, 1, 2] {
            let mut got = BytesMut::new();
            SaslAuthenticateRequest::error_response(&mut got, version, 0).unwrap();
            let mut cur = &got[..];
            let (err, msg, bytes, lifetime) =
                decode_sasl_authenticate_response(&mut cur, version).unwrap();
            assert_eq!(err, 0);
            assert_eq!(msg, None);
            assert!(bytes.is_empty());
            assert_eq!(lifetime, 0);
            assert!(
                cur.is_empty(),
                "SaslAuthenticate v{version} Request.getErrorResponse empty leftover-empty; leftover {} bytes",
                cur.len()
            );
        }
        let mut v0 = BytesMut::new();
        SaslAuthenticateRequest::error_response(&mut v0, 0, 16).unwrap();
        let mut v1 = BytesMut::new();
        SaslAuthenticateRequest::error_response(&mut v1, 1, 16).unwrap();
        let mut v2 = BytesMut::new();
        SaslAuthenticateRequest::error_response(&mut v2, 2, 16).unwrap();
        assert_ne!(
            &v0[..],
            &v1[..],
            "v1 getErrorResponse adds SessionLifetimeMs"
        );
        assert_ne!(
            &v1[..],
            &v2[..],
            "v2 getErrorResponse uses compact strings/bytes"
        );
        let mut with_bytes = BytesMut::new();
        encode_sasl_authenticate_response(&mut with_bytes, 1, 16, None, b"token", 0).unwrap();
        assert_ne!(
            &v1[..],
            &with_bytes[..],
            "getErrorResponse must not copy the request AuthBytes"
        );
    }

    #[test]
    fn sasl_authenticate_response_error_counts_matches_java() {
        // Java SaslAuthenticateResponse.errorCounts:
        // Collections.singletonMap(Errors.forCode(data.errorCode()), 1),
        // including NONE. Official Java SaslAuthenticateResponse.errorCounts.
        // Java error() is Errors.forCode only (identity on i16; not mapped).
        // AuthBytes / ErrorMessage / SessionLifetimeMs are not counted.
        // This is not SaslHandshake errorCounts / errorMessage /
        // sessionLifetimeMs / saslAuthBytes.
        assert_eq!(
            SaslAuthenticateResponse::error_counts(0),
            HashMap::from([(0, 1)]),
            "NONE is a singleton 1, not an empty map"
        );
        assert_eq!(
            SaslAuthenticateResponse::error_counts(crate::error::SASL_AUTHENTICATION_FAILED),
            HashMap::from([(crate::error::SASL_AUTHENTICATION_FAILED, 1)])
        );
        for version in 0..=2_i16 {
            let mut resp = BytesMut::new();
            encode_sasl_authenticate_response(
                &mut resp,
                version,
                crate::error::SASL_AUTHENTICATION_FAILED,
                None,
                b"token",
                3_600_000,
            )
            .unwrap();
            let mut cur = &resp[..];
            let (err, ..) = decode_sasl_authenticate_response(&mut cur, version).unwrap();
            assert_eq!(
                SaslAuthenticateResponse::error_counts(err),
                HashMap::from([(crate::error::SASL_AUTHENTICATION_FAILED, 1)]),
                "SaslAuthenticate v{version} errorCounts must count the decoded code"
            );
            assert!(
                cur.is_empty(),
                "SaslAuthenticate v{version} errorCounts leftover-empty; leftover {} bytes",
                cur.len()
            );
        }
    }

    #[test]
    fn sasl_handshake_v0_matches_v1_and_does_not_speak_v2() {
        // Official Kafka 4.0 JSON: validVersions 0-1, flexibleVersions none.
        // "Version 1 is the same as version 0" plus SaslAuthenticate support.
        // This crate speaks 0–1. v2+ is not spoken.
        let mut v0 = BytesMut::new();
        encode_sasl_handshake_request(&mut v0, 0, "PLAIN").unwrap();
        let mut v1 = BytesMut::new();
        encode_sasl_handshake_request(&mut v1, 1, "PLAIN").unwrap();
        assert_eq!(v0.as_ref(), v1.as_ref(), "v0 and v1 request bodies match");
        let mut cur = v0.as_ref();
        assert_eq!(decode_sasl_handshake_request(&mut cur, 0).unwrap(), "PLAIN");
        assert!(!cur.has_remaining(), "v0 request leftover-empty");
        let mut cur = v1.as_ref();
        assert_eq!(decode_sasl_handshake_request(&mut cur, 1).unwrap(), "PLAIN");
        assert!(!cur.has_remaining(), "v1 request leftover-empty");
        let err = encode_sasl_handshake_request(&mut BytesMut::new(), 2, "PLAIN").unwrap_err();
        assert!(
            err.to_string().contains("not implemented"),
            "v2 is not spoken, got {err}"
        );
        let mut empty: &[u8] = &[];
        let err = decode_sasl_handshake_request(&mut empty, 2).unwrap_err();
        assert!(
            err.to_string().contains("not implemented"),
            "v2 decode is not spoken, got {err}"
        );
        assert_eq!(crate::protocol::api_keys::pick_version(0, 0, 0, 1), Some(0));
        assert_eq!(crate::protocol::api_keys::pick_version(0, 1, 0, 1), Some(1));
        assert_eq!(crate::protocol::api_keys::pick_version(2, 2, 0, 1), None);

        v0.clear();
        encode_sasl_handshake_response(&mut v0, 0, 0, &["PLAIN"]).unwrap();
        v1.clear();
        encode_sasl_handshake_response(&mut v1, 1, 0, &["PLAIN"]).unwrap();
        assert_eq!(v0.as_ref(), v1.as_ref(), "v0 and v1 response bodies match");
        let mut cur = v0.as_ref();
        let (c, m) = decode_sasl_handshake_response(&mut cur, 0).unwrap();
        assert_eq!(c, 0);
        assert_eq!(m, vec!["PLAIN".to_string()]);
        assert!(!cur.has_remaining(), "v0 response leftover-empty");
        v0.clear();
        let err = encode_sasl_handshake_response(&mut v0, 2, 0, &["PLAIN"]).unwrap_err();
        assert!(
            err.to_string().contains("not implemented"),
            "v2 response is not spoken, got {err}"
        );
    }

    #[test]
    fn sasl_authenticate_v0_v1_v2_and_does_not_speak_v3() {
        // Official Kafka 4.0 JSON: validVersions 0-2, flexibleVersions 2+.
        // v0 and v1 request match (AuthBytes). v1+ SessionLifetimeMs.
        // v2 is compact bytes plus tagged fields. This crate speaks 0–2.
        let auth = b"token";
        let mut v0 = BytesMut::new();
        encode_sasl_authenticate_request(&mut v0, 0, auth).unwrap();
        let mut v1 = BytesMut::new();
        encode_sasl_authenticate_request(&mut v1, 1, auth).unwrap();
        let mut v2 = BytesMut::new();
        encode_sasl_authenticate_request(&mut v2, 2, auth).unwrap();
        assert_eq!(v0.as_ref(), v1.as_ref(), "v0 and v1 request bodies match");
        assert_ne!(
            v1.as_ref(),
            v2.as_ref(),
            "v2 request uses compact AuthBytes"
        );
        let mut cur = v0.as_ref();
        assert_eq!(decode_sasl_authenticate_request(&mut cur, 0).unwrap(), auth);
        assert!(!cur.has_remaining(), "v0 request leftover-empty");
        let mut cur = v1.as_ref();
        assert_eq!(decode_sasl_authenticate_request(&mut cur, 1).unwrap(), auth);
        assert!(!cur.has_remaining(), "v1 request leftover-empty");
        let mut cur = v2.as_ref();
        assert_eq!(decode_sasl_authenticate_request(&mut cur, 2).unwrap(), auth);
        assert!(!cur.has_remaining(), "v2 request leftover-empty");
        let err = encode_sasl_authenticate_request(&mut BytesMut::new(), 3, auth).unwrap_err();
        assert!(
            err.to_string().contains("not implemented"),
            "v3 is not spoken, got {err}"
        );
        let mut empty: &[u8] = &[];
        let err = decode_sasl_authenticate_request(&mut empty, 3).unwrap_err();
        assert!(
            err.to_string().contains("not implemented"),
            "v3 decode is not spoken, got {err}"
        );
        assert_eq!(crate::protocol::api_keys::pick_version(0, 0, 0, 2), Some(0));
        assert_eq!(crate::protocol::api_keys::pick_version(0, 1, 0, 2), Some(1));
        assert_eq!(crate::protocol::api_keys::pick_version(0, 2, 0, 2), Some(2));
        assert_eq!(crate::protocol::api_keys::pick_version(3, 3, 0, 2), None);

        v0.clear();
        encode_sasl_authenticate_response(&mut v0, 0, 0, None, auth, 0).unwrap();
        v1.clear();
        encode_sasl_authenticate_response(&mut v1, 1, 0, None, auth, 0).unwrap();
        v2.clear();
        encode_sasl_authenticate_response(&mut v2, 2, 0, None, auth, 0).unwrap();
        assert_ne!(
            v0.as_ref(),
            v1.as_ref(),
            "v1 response adds SessionLifetimeMs"
        );
        assert_ne!(
            v1.as_ref(),
            v2.as_ref(),
            "v2 response uses compact strings/bytes"
        );
        let mut cur = v0.as_ref();
        let (c, msg, bytes, lifetime) = decode_sasl_authenticate_response(&mut cur, 0).unwrap();
        assert_eq!(c, 0);
        assert_eq!(msg, None);
        assert_eq!(bytes, auth);
        assert_eq!(lifetime, 0, "v0 omits SessionLifetimeMs; decode fills 0");
        assert!(!cur.has_remaining(), "v0 response leftover-empty");
        let mut cur = v1.as_ref();
        let (c, _, bytes, lifetime) = decode_sasl_authenticate_response(&mut cur, 1).unwrap();
        assert_eq!(c, 0);
        assert_eq!(bytes, auth);
        assert_eq!(lifetime, 0);
        assert!(!cur.has_remaining(), "v1 response leftover-empty");
        let mut cur = v2.as_ref();
        let (c, _, bytes, lifetime) = decode_sasl_authenticate_response(&mut cur, 2).unwrap();
        assert_eq!(c, 0);
        assert_eq!(bytes, auth);
        assert_eq!(lifetime, 0);
        assert!(!cur.has_remaining(), "v2 response leftover-empty");
        v0.clear();
        let err = encode_sasl_authenticate_response(&mut v0, 3, 0, None, auth, 0).unwrap_err();
        assert!(
            err.to_string().contains("not implemented"),
            "v3 response is not spoken, got {err}"
        );
    }

    #[test]
    fn sasl_authenticate_session_lifetime_matches_java() {
        let auth = b"token";
        for version in [1_i16, 2] {
            let mut buf = BytesMut::new();
            encode_sasl_authenticate_response(&mut buf, version, 0, None, auth, 3_600_000).unwrap();
            let mut cur = buf.as_ref();
            let (c, msg, bytes, lifetime) =
                decode_sasl_authenticate_response(&mut cur, version).unwrap();
            assert_eq!(c, 0);
            assert_eq!(msg, None);
            assert_eq!(bytes, auth);
            assert_eq!(lifetime, 3_600_000);
            assert!(
                cur.is_empty(),
                "SaslAuthenticate v{version} SessionLifetimeMs leftover-empty"
            );
        }

        let mut buf = BytesMut::new();
        encode_sasl_authenticate_response(&mut buf, 0, 0, None, auth, 3_600_000).unwrap();
        let mut cur = buf.as_ref();
        let (_, _, _, lifetime) = decode_sasl_authenticate_response(&mut cur, 0).unwrap();
        assert!(
            cur.is_empty(),
            "SaslAuthenticate v0 SessionLifetimeMs leftover-empty"
        );
        assert_eq!(
            lifetime, 0,
            "SaslAuthenticate v0 omits SessionLifetimeMs even when the body has a non-zero value"
        );

        let mut with = BytesMut::new();
        encode_sasl_authenticate_response(&mut with, 1, 0, None, auth, 3_600_000).unwrap();
        let mut zero = BytesMut::new();
        encode_sasl_authenticate_response(&mut zero, 1, 0, None, auth, 0).unwrap();
        assert_ne!(
            &with[..],
            &zero[..],
            "v1 SessionLifetimeMs is not always the JSON default 0"
        );
        let mut v0_nonzero = BytesMut::new();
        encode_sasl_authenticate_response(&mut v0_nonzero, 0, 0, None, auth, 3_600_000).unwrap();
        let mut v0_zero = BytesMut::new();
        encode_sasl_authenticate_response(&mut v0_zero, 0, 0, None, auth, 0).unwrap();
        assert_eq!(
            &v0_nonzero[..],
            &v0_zero[..],
            "v0 encode omits SessionLifetimeMs even when the body has a non-zero value"
        );
    }
}