puressh 0.2.1

A pure-Rust SSH (Secure Shell) protocol library, in the spirit of libssh, built on purecrypto.
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
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
//! Server-side user authentication state machine (RFC 4252).

use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;

use crate::error::{Error, Result};
use crate::hostkey::{HostKeyVerify, host_key_verify_by_name};

use super::message::{
    AuthMethodPayload, SSH_MSG_SERVICE_REQUEST, SSH_MSG_USERAUTH_INFO_RESPONSE,
    SSH_MSG_USERAUTH_REQUEST, SecretString, ServiceAccept, ServiceRequest, UserauthFailure,
    UserauthInfoRequest, UserauthInfoResponse, UserauthPkOk, UserauthRequest, encode_success,
};

/// The account a userauth user name refers to: OpenSSH accepts
/// `user:style` (a BSD authentication style) and authenticates `user`.
fn account_name(user: &str) -> &str {
    user.split_once(':').map_or(user, |(u, _)| u)
}

/// A single authentication attempt presented by the client.
///
/// `Debug` is implemented manually so the cleartext `password` field is
/// never rendered — it is replaced by `"<redacted>"`. This prevents
/// accidental leakage through `tracing::debug!`, `dbg!`, `Result::unwrap`'s
/// `{:?}` formatter, and similar developer-ergonomics paths.
// `PublicKey` carries the parsed certificate facts inline; the other variants
// are a username and (for `Password`) one secret. The asymmetry is inherent —
// the attempt is short-lived and never stored in bulk — so boxing `CertInfo`
// would only add an allocation per publickey attempt.
#[allow(clippy::large_enum_variant)]
#[non_exhaustive]
pub enum AuthAttempt {
    /// `none` — bare probe.
    None {
        /// Requested user name.
        user: String,
    },
    /// `password` authentication.
    Password {
        /// Requested user name.
        user: String,
        /// Plaintext password, held in zeroize-on-drop storage so its
        /// bytes are wiped when the attempt is dropped. **Not** rendered by
        /// the [`core::fmt::Debug`] impl.
        password: SecretString,
    },
    /// `publickey` authentication.
    PublicKey {
        /// Requested user name.
        user: String,
        /// SSH algorithm name (e.g. `"ssh-ed25519"`). For a certificate this is
        /// the cert key-type name (e.g. `"ssh-ed25519-cert-v01@openssh.com"`).
        algorithm: String,
        /// Wire-format public-key blob. For a certificate this is the full
        /// certificate blob; the authenticator should consult `cert` instead of
        /// treating the blob as a plain key.
        public_blob: Vec<u8>,
        /// True if the client only probed (no signature); false if a signature
        /// was attached and verified successfully.
        probe_only: bool,
        /// True iff the signature was both present and verified by this layer.
        /// For a certificate, this additionally means the CA signature verified
        /// and the certificate's type/validity were accepted (the *trust* in
        /// the CA itself is still the authenticator's call).
        verified: bool,
        /// `Some` iff `algorithm` is an OpenSSH certificate key-type. Carries
        /// the parsed certificate facts the trust decision needs (CA key,
        /// principals, critical options, …). `None` for a plain public key, so
        /// existing plain-key authenticators are unaffected.
        cert: Option<CertInfo>,
    },
    /// `keyboard-interactive` request.
    KeyboardInteractive {
        /// Requested user name.
        user: String,
    },
}

impl core::fmt::Debug for AuthAttempt {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            AuthAttempt::None { user } => f.debug_struct("None").field("user", user).finish(),
            AuthAttempt::Password { user, password: _ } => f
                .debug_struct("Password")
                .field("user", user)
                .field("password", &"<redacted>")
                .finish(),
            AuthAttempt::PublicKey {
                user,
                algorithm,
                public_blob,
                probe_only,
                verified,
                cert,
            } => f
                .debug_struct("PublicKey")
                .field("user", user)
                .field("algorithm", algorithm)
                .field("public_blob", public_blob)
                .field("probe_only", probe_only)
                .field("verified", verified)
                .field("cert", cert)
                .finish(),
            AuthAttempt::KeyboardInteractive { user } => f
                .debug_struct("KeyboardInteractive")
                .field("user", user)
                .finish(),
        }
    }
}

/// The parsed certificate facts handed to an authenticator alongside a
/// certificate-based [`AuthAttempt::PublicKey`].
///
/// The auth layer has already verified the CA signature (under the configured
/// `CASignatureAlgorithms`) and the cert's type/validity by the time this is
/// produced for a *verified* attempt; the authenticator's remaining job is the
/// **trust** decision (is `ca_key_blob` a CA we accept?) and the **principal**
/// decision (is the login user authorized by `valid_principals` / an
/// `AuthorizedPrincipalsFile`?), plus honoring critical options.
#[derive(Debug, Clone)]
#[cfg(feature = "alloc")]
#[non_exhaustive]
pub struct CertInfo {
    /// The CA's public-key blob (`signature_key_blob`) — the key the
    /// authenticator must check against its trusted-CA set.
    pub ca_key_blob: Vec<u8>,
    /// The plain wire blob of the key *embedded* in the certificate (the key
    /// the client actually signed with). A KRL that revokes this key as a
    /// plain key must also refuse any certificate wrapping it — OpenSSH checks
    /// the embedded key, not the certificate blob, for explicit-key /
    /// fingerprint revocations.
    pub embedded_pubkey_blob: Vec<u8>,
    /// The CA's signature algorithm (e.g. `"ssh-ed25519"`, `"rsa-sha2-512"`).
    pub ca_algorithm: String,
    /// The certificate's key-id (free-form CA-stamped identity, for logging).
    pub key_id: String,
    /// Monotonic serial number assigned by the CA.
    pub serial: u64,
    /// The principals the certificate authorizes (never empty for a
    /// certificate that can authenticate: an empty list is refused).
    pub valid_principals: Vec<String>,
    /// Critical options as ordered `(name, data)` pairs — MUST be understood.
    pub critical_options: Vec<(String, Vec<u8>)>,
    /// Extensions as ordered `(name, data)` pairs — advisory.
    pub extensions: Vec<(String, Vec<u8>)>,
    /// Start of the validity window (Unix seconds).
    pub valid_after: u64,
    /// End of the validity window (Unix seconds, exclusive).
    pub valid_before: u64,
}

#[cfg(feature = "alloc")]
impl CertInfo {
    /// Build a `CertInfo` by hand — for authenticator tests and tooling that
    /// has no wire certificate to parse. The validity window defaults to
    /// "always valid" (`0..u64::MAX`) and `critical_options` / `extensions`
    /// start empty; assign those fields afterwards as needed. Real
    /// connections go through [`CertInfo::from_certificate`].
    pub fn new(
        ca_key_blob: Vec<u8>,
        embedded_pubkey_blob: Vec<u8>,
        ca_algorithm: impl Into<String>,
        key_id: impl Into<String>,
        serial: u64,
        valid_principals: Vec<String>,
    ) -> Self {
        CertInfo {
            ca_key_blob,
            embedded_pubkey_blob,
            ca_algorithm: ca_algorithm.into(),
            key_id: key_id.into(),
            serial,
            valid_principals,
            critical_options: Vec::new(),
            extensions: Vec::new(),
            valid_after: 0,
            valid_before: u64::MAX,
        }
    }

    /// Build a `CertInfo` view from a parsed [`crate::cert::Certificate`].
    pub fn from_certificate(cert: &crate::cert::Certificate) -> Result<Self> {
        Ok(CertInfo {
            ca_key_blob: cert.signature_key_blob.clone(),
            embedded_pubkey_blob: cert.embedded_pubkey_blob.clone(),
            ca_algorithm: cert.ca_algorithm()?.into(),
            key_id: cert.key_id.clone(),
            serial: cert.serial,
            valid_principals: cert.valid_principals.clone(),
            critical_options: cert.critical_options.clone(),
            extensions: cert.extensions.clone(),
            valid_after: cert.valid_after,
            valid_before: cert.valid_before,
        })
    }

    /// True if the named extension is present.
    pub fn has_extension(&self, name: &str) -> bool {
        self.extensions.iter().any(|(n, _)| n == name)
    }

    /// The data of a critical option by name, if present.
    pub fn critical_option(&self, name: &str) -> Option<&[u8]> {
        self.critical_options
            .iter()
            .find(|(n, _)| n == name)
            .map(|(_, d)| d.as_slice())
    }
}

/// Authenticator's verdict on an attempt.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum AuthDecision {
    /// Accept fully — emit USERAUTH_SUCCESS.
    Accept,
    /// Partial accept — record the success but require more methods.
    PartialAccept {
        /// Methods the client must still satisfy.
        still_required: Vec<String>,
    },
    /// Reject — emit USERAUTH_FAILURE.
    Reject,
    /// Drive a keyboard-interactive round with these prompts.
    InteractiveRequest {
        /// Title block.
        name: String,
        /// Instructions to show.
        instruction: String,
        /// `(prompt, echo)` pairs.
        prompts: Vec<(String, bool)>,
    },
}

/// Pluggable policy: a server-side credential checker.
pub trait Authenticator: Send {
    /// Evaluate a one-shot attempt (none/password/publickey/keyboard-interactive request).
    fn evaluate(&mut self, attempt: AuthAttempt) -> AuthDecision;

    /// Restrictions for the session from the key that was just accepted
    /// (a verified publickey attempt): typically its `authorized_keys`
    /// options. Combined with a certificate's own restrictions.
    #[cfg(feature = "alloc")]
    fn key_restrictions(&mut self, user: &str, public_blob: &[u8]) -> Option<AuthCertCaps> {
        let _ = (user, public_blob);
        None
    }

    /// The methods a USERAUTH_FAILURE lists as able to continue. `offered`
    /// is every method the server accepts; the default lists them all. A
    /// policy with ordered requirements (OpenSSH's `AuthenticationMethods`)
    /// lists only those that can still lead to success, as OpenSSH does,
    /// so clients do not prompt for credentials that cannot help.
    #[cfg(feature = "alloc")]
    fn continuable_methods(&self, offered: &[&'static str]) -> Vec<String> {
        offered.iter().map(|m| (*m).into()).collect()
    }

    /// Evaluate the responses to a previously-issued `InteractiveRequest`.
    fn evaluate_interactive(&mut self, user: &str, responses: Vec<String>) -> AuthDecision {
        let _ = (user, responses);
        AuthDecision::Reject
    }

    /// Hook fired once, the first time the username for this connection is
    /// known (before the first attempt is evaluated). `methods` is the resolved
    /// `AuthenticationMethods` value for this user (space-separated
    /// alternatives, each a comma-separated chain — e.g.
    /// `["publickey,password", "publickey,keyboard-interactive"]`), or empty
    /// when no `AuthenticationMethods` is configured (single-factor: any one
    /// advertised method suffices). A multi-factor authenticator uses it to
    /// install the per-user chain set. The default is a no-op. Implementations
    /// that key off the username must reject a later username change themselves
    /// (OpenSSH terminates auth if the client switches usernames
    /// mid-userauth).
    fn on_user_resolved(&mut self, user: &str, methods: &[String]) {
        let _ = (user, methods);
    }
}

/// Per-connection capability facts carried out of a *successful* user-certificate
/// authentication, for the connection phase to enforce.
///
/// OpenSSH user certificates carry **extensions** that are default-deny: when an
/// extension is absent the corresponding capability is refused for the whole
/// connection. The auth layer captures the winning certificate's extension set
/// (and its `force-command` critical option) here so the connection phase can
/// gate `pty-req` / forwarding / agent / X11 — and apply the forced command —
/// without re-parsing the certificate.
///
/// `None` (i.e. plain public-key, password, or keyboard-interactive auth)
/// leaves every capability allowed, exactly as before certificates existed.
#[derive(Debug, Clone)]
#[cfg(feature = "alloc")]
#[non_exhaustive]
pub struct AuthCertCaps {
    /// `permit-pty` extension present ⇒ a `pty-req` may be honoured.
    pub permit_pty: bool,
    /// `permit-port-forwarding` present ⇒ `direct-tcpip` / `tcpip-forward` allowed.
    pub permit_port_forwarding: bool,
    /// `permit-agent-forwarding` present ⇒ `auth-agent-req@openssh.com` allowed.
    pub permit_agent_forwarding: bool,
    /// `permit-X11-forwarding` present ⇒ `x11-req` allowed.
    pub permit_x11_forwarding: bool,
    /// `permit-user-rc` present (or no `no-user-rc` key option) ⇒ the
    /// session may run `~/.ssh/rc`.
    pub permit_user_rc: bool,
    /// `environment="NAME=value"` key options, set in the session when
    /// `PermitUserEnvironment` allows.
    pub environment: Vec<String>,
    /// The decoded `force-command` critical option (an SSH `string`), if present.
    /// The connection phase runs this in place of the client's command/shell.
    pub force_command: Option<String>,
    /// `permitopen=` (authorized_keys): allowed `direct-tcpip` destinations,
    /// on top of `PermitOpen`. `None` ⇒ no extra restriction.
    pub permit_open: Option<Vec<crate::config::HostPort>>,
    /// `permitlisten=` (authorized_keys): allowed `tcpip-forward` binds, on
    /// top of `PermitListen`. `None` ⇒ no extra restriction.
    pub permit_listen: Option<Vec<crate::config::HostPort>>,
    /// `tunnel="n"` (authorized_keys): the only tun device unit a client may
    /// forward (`0x7fffffff` for any). `None` ⇒ the client's choice.
    pub force_tun_device: Option<u32>,
}

#[cfg(feature = "alloc")]
impl AuthCertCaps {
    /// Build the capability view from a verified user certificate's `CertInfo`.
    /// The `force-command` payload is itself a length-prefixed SSH `string`; it
    /// is decoded here so callers don't repeat the unwrap.
    ///
    /// A malformed `force-command` payload decodes to `None` here; the auth
    /// layer never reaches this point with one, because
    /// [`crate::cert::Certificate::require_known_critical_options`] rejects
    /// the certificate (fail-closed) before the userauth signature is even
    /// checked. Callers constructing this from their own `CertInfo` should
    /// apply the same check first.
    pub fn from_cert_info(ci: &CertInfo) -> Self {
        let force_command = ci
            .critical_option("force-command")
            .and_then(crate::cert::decode_option_string);
        AuthCertCaps {
            permit_pty: ci.has_extension("permit-pty"),
            permit_port_forwarding: ci.has_extension("permit-port-forwarding"),
            permit_agent_forwarding: ci.has_extension("permit-agent-forwarding"),
            permit_x11_forwarding: ci.has_extension("permit-X11-forwarding"),
            permit_user_rc: ci.has_extension("permit-user-rc"),
            environment: Vec::new(),
            force_command,
            permit_open: None,
            permit_listen: None,
            force_tun_device: None,
        }
    }

    /// Everything permitted, no forced command: the identity for
    /// [`Self::intersect`].
    pub fn unrestricted() -> Self {
        AuthCertCaps {
            permit_pty: true,
            permit_port_forwarding: true,
            permit_agent_forwarding: true,
            permit_x11_forwarding: true,
            permit_user_rc: true,
            environment: Vec::new(),
            force_command: None,
            permit_open: None,
            permit_listen: None,
            force_tun_device: None,
        }
    }

    /// Restrictions from an `authorized_keys` line's options (`restrict`,
    /// `no-pty`, `command=`, `permitopen=`, …).
    pub fn from_key_options(o: &crate::key::AuthorizedKeyOptions) -> Self {
        let list = |v: &[String]| {
            (!v.is_empty()).then(|| v.iter().filter_map(|e| parse_permit(e)).collect())
        };
        AuthCertCaps {
            permit_pty: o.allows_pty(),
            permit_port_forwarding: o.allows_port_forwarding(),
            permit_agent_forwarding: o.allows_agent_forwarding(),
            permit_x11_forwarding: o.allows_x11_forwarding(),
            permit_user_rc: o.allows_user_rc(),
            environment: o.environment.clone(),
            force_command: o.command.clone(),
            permit_open: list(&o.permit_open),
            permit_listen: list(&o.permit_listen),
            force_tun_device: o.tunnel.as_deref().and_then(|t| {
                if t.eq_ignore_ascii_case("any") {
                    Some(0x7fff_ffff)
                } else {
                    t.parse().ok()
                }
            }),
        }
    }

    /// Both sets of restrictions at once (a certificate and the
    /// `authorized_keys` line that trusted it). `None` when they force
    /// different commands, which OpenSSH refuses too.
    pub fn intersect(self, other: AuthCertCaps) -> Option<AuthCertCaps> {
        let force_command = match (self.force_command, other.force_command) {
            (Some(a), Some(b)) if a != b => return None,
            (a, b) => a.or(b),
        };
        let both = |a: Option<Vec<crate::config::HostPort>>, b: Option<Vec<_>>| match (a, b) {
            (Some(a), Some(b)) => Some(a.into_iter().filter(|e| b.contains(e)).collect()),
            (a, b) => a.or(b),
        };
        let mut environment = self.environment;
        environment.extend(other.environment);
        Some(AuthCertCaps {
            permit_pty: self.permit_pty && other.permit_pty,
            permit_port_forwarding: self.permit_port_forwarding && other.permit_port_forwarding,
            permit_agent_forwarding: self.permit_agent_forwarding && other.permit_agent_forwarding,
            permit_x11_forwarding: self.permit_x11_forwarding && other.permit_x11_forwarding,
            permit_user_rc: self.permit_user_rc && other.permit_user_rc,
            environment,
            force_command,
            permit_open: both(self.permit_open, other.permit_open),
            permit_listen: both(self.permit_listen, other.permit_listen),
            force_tun_device: self.force_tun_device.or(other.force_tun_device),
        })
    }
}

/// `host:port`, `[v6]:port` or (for `permitlisten`) a bare `port`; `*` for
/// any port.
#[cfg(feature = "alloc")]
fn parse_permit(spec: &str) -> Option<crate::config::HostPort> {
    let (host, port) = if let Some(rest) = spec.strip_prefix('[') {
        let (h, p) = rest.split_once("]:")?;
        (String::from(h), p)
    } else if let Some((h, p)) = spec.rsplit_once(':') {
        (String::from(h), p)
    } else {
        (String::from("*"), spec)
    };
    let port = if port == "*" {
        None
    } else {
        Some(port.parse().ok()?)
    };
    Some(crate::config::HostPort { host, port })
}

/// What the harness should do next on behalf of the server.
#[non_exhaustive]
pub enum ServerStep {
    /// Send this payload to the peer.
    Send(Vec<u8>),
    /// Authentication finished; send this payload (USERAUTH_SUCCESS) and treat
    /// the connection as authenticated for `user`.
    Authenticated {
        /// The USERAUTH_SUCCESS payload to transmit.
        payload: Vec<u8>,
        /// The validated user name.
        user: String,
        /// `Some` iff the credential that completed authentication was a user
        /// certificate; carries that cert's connection-phase capability gates
        /// (default-deny extensions + `force-command`). `None` for plain-key /
        /// password / keyboard-interactive auth (all capabilities allowed).
        cert_caps: Option<AuthCertCaps>,
        /// The methods that succeeded, one per line as OpenSSH's sshd
        /// records them for `ExposeAuthInfo` (`publickey ssh-ed25519
        /// AAAA…`, `password`, `keyboard-interactive/pam`).
        auth_info: String,
    },
    /// Disconnect the peer with the given (static) reason.
    Disconnect(&'static str),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
    AwaitingServiceRequest,
    AwaitingRequest,
    AwaitingInfoResponse,
    Done,
}

/// Server-side userauth driver.
pub struct ServerAuth {
    service: &'static str,
    session_id: Vec<u8>,
    accepted_methods: Vec<&'static str>,
    auth: Box<dyn Authenticator>,
    state: State,
    pending_user: Option<String>,
    /// The keys (a certificate's embedded key) already accepted as a factor
    /// of a multi-factor chain: OpenSSH refuses one offered again, so
    /// `publickey,publickey` takes two different keys.
    used_keys: Vec<Vec<u8>>,
    /// The host key this server presented in the key exchange, which a
    /// `publickey-hostbound-v00@openssh.com` request must name.
    host_key: Option<Vec<u8>>,
    /// One line per method that succeeded (see `ServerStep::Authenticated`).
    auth_info: String,
    /// Number of prompts issued in the in-flight keyboard-interactive
    /// `InteractiveRequest`, retained so the matching INFO_RESPONSE can be
    /// rejected when its response count does not equal the prompt count
    /// (RFC 4256 §3.4). `Some` only while [`State::AwaitingInfoResponse`];
    /// `.take()`n alongside `pending_user`.
    pending_prompt_count: Option<usize>,
    /// The username carried by the *first* USERAUTH_REQUEST seen. Once set,
    /// every later request must carry the same name — OpenSSH terminates
    /// authentication if the client switches usernames mid-userauth. `None`
    /// until the first request that carries a username.
    first_user: Option<String>,
    /// Default-off opt-in: when false (the default), any `AuthAttempt::None`
    /// is short-circuited to `AuthDecision::Reject` **before** the
    /// [`Authenticator`] sees it. This protects against an
    /// accept-everything authenticator silently letting unauthenticated
    /// clients in via the bare-probe `"none"` method.
    allow_none: bool,
    /// `MaxAuthTries` (OpenSSH): disconnect after this many failed attempts.
    /// `None` ⇒ unlimited (the historical behaviour, modulo `MAX_AUTH_STEPS`
    /// in the server loop).
    max_auth_tries: Option<u32>,
    /// Count of failed attempts so far (each USERAUTH_FAILURE without partial
    /// success). Compared against `max_auth_tries`.
    failed_attempts: u32,
    /// Current wall-clock time (Unix seconds), injected by the server at the
    /// std edge for certificate validity checks. `0` (the default) makes every
    /// not-yet-valid certificate fail closed, which is the safe default if a
    /// caller forgets to thread real time in.
    now: u64,
    /// Resolved `CASignatureAlgorithms` — the signature algorithms a CA may use
    /// when signing a user certificate. Empty ⇒ the built-in default set.
    ca_signature_algorithms: Vec<String>,
    /// Capability facts captured from the most recent *verified* user-cert
    /// publickey attempt (extensions + `force-command`). Held across a possible
    /// multi-factor PartialAccept so the eventual `Authenticated` step can carry
    /// it. `None` until a verified cert attempt is seen.
    pending_cert_caps: Option<AuthCertCaps>,
}

impl ServerAuth {
    /// Build a new server-side driver. `methods` advertises what we accept in
    /// USERAUTH_FAILURE continuations (e.g. `["publickey", "password"]`).
    ///
    /// By default, the `"none"` method is hard-rejected before the
    /// [`Authenticator`] sees it (see [`Self::allow_none`]).
    pub fn new(
        session_id: Vec<u8>,
        methods: Vec<&'static str>,
        auth: Box<dyn Authenticator>,
    ) -> Self {
        Self {
            service: "ssh-connection",
            session_id,
            accepted_methods: methods,
            auth,
            state: State::AwaitingServiceRequest,
            pending_user: None,
            used_keys: Vec::new(),
            host_key: None,
            auth_info: String::new(),
            pending_prompt_count: None,
            first_user: None,
            allow_none: false,
            max_auth_tries: None,
            failed_attempts: 0,
            now: 0,
            ca_signature_algorithms: Vec::new(),
            pending_cert_caps: None,
        }
    }

    /// Inject the current wall-clock time (Unix seconds) used for certificate
    /// validity checks. Servers should set this from `SystemTime` at accept
    /// time; left unset it defaults to `0`, which fails every certificate's
    /// not-yet-valid check (fail-closed).
    pub fn set_now(&mut self, now: u64) -> &mut Self {
        self.now = now;
        self
    }

    /// Set the resolved `CASignatureAlgorithms` allow-list used when verifying
    /// a user certificate's CA signature. Empty (the default) ⇒ the built-in
    /// default set (`config::algos::CA_SIGNATURE_DEFAULTS`).
    pub fn set_ca_signature_algorithms(&mut self, algos: Vec<String>) -> &mut Self {
        self.ca_signature_algorithms = algos;
        self
    }

    /// Set the `MaxAuthTries` limit. After this many failed attempts the
    /// driver emits [`ServerStep::Disconnect`] instead of another
    /// USERAUTH_FAILURE. `None` (the default) means unlimited.
    pub fn set_max_auth_tries(&mut self, max: Option<u32>) -> &mut Self {
        self.max_auth_tries = max;
        self
    }

    /// Replace the advertised method set (the `USERAUTH_FAILURE`
    /// continuations). The server re-resolves its `sshd_config` policy once the
    /// username is first known — a `Match User`/`Match Group` block may then
    /// change `PubkeyAuthentication` / `AuthenticationMethods`, which adjusts
    /// what is offered for the remaining attempts.
    pub fn set_accepted_methods(&mut self, methods: Vec<&'static str>) -> &mut Self {
        self.accepted_methods = methods;
        self
    }

    /// The currently-advertised method set (the `USERAUTH_FAILURE`
    /// continuations).
    pub fn accepted_methods(&self) -> &[&'static str] {
        &self.accepted_methods
    }

    /// Notify the underlying [`Authenticator`] that the connection's username
    /// is now known (see [`Authenticator::on_user_resolved`]). The server loop
    /// calls this once, on the first USERAUTH_REQUEST that carries a username,
    /// alongside the `Match`-based method-set re-resolve. `methods` is the
    /// resolved `AuthenticationMethods` chain set for this user.
    pub fn notify_user_resolved(&mut self, user: &str, methods: &[String]) {
        self.auth.on_user_resolved(user, methods);
    }

    /// The method name carried by an inbound `USERAUTH_REQUEST` payload, or
    /// `None` if `payload` is not a well-formed request. Lets the caller learn
    /// the username/method *before* the attempt is evaluated, so a re-resolved
    /// policy can be applied (see [`Self::set_accepted_methods`]). The name
    /// is the account's: a `user:style` suffix is dropped.
    pub fn peek_request(payload: &[u8]) -> Option<(String, &'static str)> {
        let req = UserauthRequest::decode(payload).ok()?;
        let method = match req.method {
            AuthMethodPayload::None => "none",
            AuthMethodPayload::Password { .. } => "password",
            AuthMethodPayload::PublicKey { .. } => "publickey",
            AuthMethodPayload::KeyboardInteractive { .. } => "keyboard-interactive",
            AuthMethodPayload::Other { .. } => "",
        };
        Some((String::from(account_name(&req.user)), method))
    }

    /// Reject an attempt whose method is no longer advertised (e.g. a
    /// `Match User` block dropped `publickey`). Counts as a failed attempt for
    /// `MaxAuthTries` and emits `USERAUTH_FAILURE` (or `Disconnect` once the
    /// limit is exceeded) carrying the *current* method set — without ever
    /// consulting the [`Authenticator`].
    ///
    /// `user` is the username the rejected request carried (from
    /// [`Self::peek_request`]). It is pinned exactly as [`Self::on_packet`]
    /// pins it: the first username seen on the connection is the only one
    /// accepted for the rest of userauth, and a later request under a
    /// different name yields [`ServerStep::Disconnect`]. Without this, a
    /// client whose *first* request was rejected here could switch names on
    /// its second request and have it evaluated under the first user's
    /// re-resolved policy.
    pub fn reject_unadvertised(&mut self, user: &str) -> Result<ServerStep> {
        if let Some(step) = self.pin_user(user) {
            return Ok(step);
        }
        self.emit_failure()
    }

    /// Pin the connection's username to the first request's value. OpenSSH
    /// disconnects if the client changes the login name mid-userauth; every
    /// probe and every real attempt for a connection must carry the same
    /// name. (The `none`- and pubkey-probe flows all reuse the same
    /// username, so this only fires on an actual switch.) Returns the
    /// `Disconnect` step on a switch, `None` when the name is consistent.
    fn pin_user(&mut self, user: &str) -> Option<ServerStep> {
        match &self.first_user {
            Some(prev) if prev != user => Some(ServerStep::Disconnect(
                "auth: username changed mid-authentication",
            )),
            None => {
                self.first_user = Some(user.into());
                None
            }
            _ => None,
        }
    }

    /// The host key this server presented in the key exchange: a client's
    /// `publickey-hostbound-v00@openssh.com` request must name it.
    pub fn set_host_key(&mut self, host_key: Vec<u8>) {
        self.host_key = Some(host_key);
    }

    /// Opt in to letting the [`Authenticator`] see `AuthAttempt::None`.
    ///
    /// By default this is `false` and the server short-circuits every
    /// `"none"` userauth method to a [`UserauthFailure`] before invoking
    /// the authenticator — RFC 4252 §5.2 describes `"none"` as a probe
    /// the client uses to *learn* which methods the server allows, not
    /// as a credential. Letting an accept-everything authenticator
    /// answer that probe with `Accept` would silently authenticate any
    /// client; the gate prevents that footgun.
    ///
    /// Enable only if your authenticator deliberately uses `"none"` as
    /// a real credential (e.g. an anonymous-access tier that does not
    /// require any secret).
    pub fn allow_none(&mut self, allow: bool) -> &mut Self {
        self.allow_none = allow;
        self
    }

    /// Process an inbound payload from the peer.
    pub fn on_packet(&mut self, payload: &[u8]) -> Result<ServerStep> {
        if payload.is_empty() {
            return Err(Error::Format("auth: empty payload"));
        }
        let msg_type = payload[0];
        match self.state {
            State::AwaitingServiceRequest => {
                if msg_type != SSH_MSG_SERVICE_REQUEST {
                    return Err(Error::Protocol("auth: expected SERVICE_REQUEST"));
                }
                let req = ServiceRequest::decode(payload)?;
                if req.service != "ssh-userauth" {
                    return Err(Error::Protocol("auth: unknown service requested"));
                }
                self.state = State::AwaitingRequest;
                let accept = ServiceAccept {
                    service: "ssh-userauth".into(),
                };
                Ok(ServerStep::Send(accept.encode()))
            }
            State::AwaitingRequest => {
                if msg_type != SSH_MSG_USERAUTH_REQUEST {
                    return Err(Error::Protocol("auth: expected USERAUTH_REQUEST"));
                }
                let req = UserauthRequest::decode(payload)?;
                // Pin the username before *any* verdict on this request —
                // including the service-name rejection below — so no
                // rejected first request leaves the name unpinned.
                if let Some(step) = self.pin_user(account_name(&req.user)) {
                    return Ok(step);
                }
                if req.service != self.service {
                    return self.emit_failure();
                }
                self.handle_request(req)
            }
            State::AwaitingInfoResponse => {
                if msg_type != SSH_MSG_USERAUTH_INFO_RESPONSE {
                    return Err(Error::Protocol("auth: expected INFO_RESPONSE"));
                }
                let mut resp = UserauthInfoResponse::decode(payload)?;
                let user = self
                    .pending_user
                    .take()
                    .ok_or(Error::Protocol("auth: info response without pending user"))?;
                let prompt_count = self.pending_prompt_count.take();
                // `core::mem::take` the responses out instead of moving the
                // field (which `UserauthInfoResponse`'s zeroizing `Drop` impl
                // forbids). The drained source leaves an empty Vec behind;
                // ownership of the response strings passes to the
                // authenticator via the `Vec<String>` trait API.
                let responses = core::mem::take(&mut resp.responses);
                self.state = State::AwaitingRequest;
                // RFC 4256 §3.4: num-responses MUST equal the num-prompts the
                // server issued. A mismatch is a malformed/forged response —
                // treat it as a failed attempt rather than forwarding the
                // wrong-shaped responses to the authenticator.
                if prompt_count != Some(responses.len()) {
                    return self.emit_failure();
                }
                let decision = self.auth.evaluate_interactive(&user, responses);
                self.record_success(&decision, "keyboard-interactive/pam".into());
                self.apply_decision(decision, &user)
            }
            State::Done => Ok(ServerStep::Disconnect("auth: already finished")),
        }
    }

    fn handle_request(&mut self, req: UserauthRequest) -> Result<ServerStep> {
        // `user:style` names the account `user` (OpenSSH's BSD auth style,
        // ignored here); a signature covers the name as sent.
        let wire_user = req.user.clone();
        let user = String::from(account_name(&req.user));
        // The username was pinned by `on_packet` (see `pin_user`) before we
        // got here.
        match req.method {
            AuthMethodPayload::None => {
                // Hard gate: refuse `"none"` unless the caller explicitly
                // opted in via `allow_none(true)`. Without this gate an
                // overly-permissive [`Authenticator`] (e.g. one that returns
                // `Accept` for any well-formed request) would let an
                // unauthenticated client through the bare RFC 4252 §5.2
                // probe. The authenticator is never consulted in this path.
                if !self.allow_none {
                    return self.emit_failure();
                }
                let decision = self.auth.evaluate(AuthAttempt::None { user: user.clone() });
                self.apply_decision(decision, &user)
            }
            AuthMethodPayload::Password {
                password,
                new_password: _,
            } => {
                let decision = self.auth.evaluate(AuthAttempt::Password {
                    user: user.clone(),
                    password,
                });
                self.record_success(&decision, "password".into());
                self.apply_decision(decision, &user)
            }
            AuthMethodPayload::PublicKey {
                signature_present,
                algorithm,
                public_blob,
                signature,
                host_key,
            } => {
                // `publickey-hostbound-v00@openssh.com` names this server's
                // host key, or the request is refused (OpenSSH's check).
                if let Some(named) = &host_key
                    && self.host_key.as_ref() != Some(named)
                {
                    return self.emit_failure();
                }
                self.handle_publickey(
                    user,
                    &wire_user,
                    signature_present,
                    algorithm,
                    public_blob,
                    signature,
                    host_key,
                )
            }
            AuthMethodPayload::KeyboardInteractive {
                language_tag: _,
                submethods: _,
            } => {
                let decision = self
                    .auth
                    .evaluate(AuthAttempt::KeyboardInteractive { user: user.clone() });
                self.apply_decision(decision, &user)
            }
            AuthMethodPayload::Other { .. } => self.emit_failure(),
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn handle_publickey(
        &mut self,
        user: String,
        wire_user: &str,
        signature_present: bool,
        algorithm: String,
        public_blob: Vec<u8>,
        signature: Option<Vec<u8>>,
        host_key: Option<Vec<u8>>,
    ) -> Result<ServerStep> {
        let is_cert = crate::cert::is_cert_name(&algorithm);
        // The key itself, whether offered plain or as a certificate.
        let key_blob = if is_cert {
            match crate::cert::Certificate::parse(&public_blob) {
                Ok(c) => c.embedded_pubkey_blob().to_vec(),
                Err(_) => return self.emit_failure(),
            }
        } else {
            public_blob.clone()
        };
        if self.used_keys.contains(&key_blob) {
            return self.emit_failure();
        }

        if !signature_present {
            // Probe (no signature). For a certificate, parse it so the
            // authenticator can decide whether to invite a signature, but do
            // not yet require CA validity — the binding signature comes next.
            let cert_info = if is_cert {
                match crate::cert::Certificate::parse(&public_blob) {
                    // The offered algorithm name must be one we know and
                    // must belong to the embedded key's family, exactly as
                    // for the signed step — otherwise the PK_OK we would
                    // echo back invites a signature we can never accept.
                    Ok(c) if cert_plain_algorithm(&algorithm, &c).is_some() => {
                        Some(CertInfo::from_certificate(&c)?)
                    }
                    // A malformed cert blob is not a probe we can honour.
                    _ => return self.emit_failure(),
                }
            } else {
                None
            };
            let decision = self.auth.evaluate(AuthAttempt::PublicKey {
                user: user.clone(),
                algorithm: algorithm.clone(),
                public_blob: public_blob.clone(),
                probe_only: true,
                verified: false,
                cert: cert_info,
            });
            return match decision {
                AuthDecision::Accept | AuthDecision::PartialAccept { .. } => {
                    let pk_ok = UserauthPkOk {
                        algorithm,
                        public_blob,
                    };
                    Ok(ServerStep::Send(pk_ok.encode()))
                }
                AuthDecision::Reject => self.emit_failure(),
                AuthDecision::InteractiveRequest { .. } => {
                    Err(Error::Protocol("auth: interactive on publickey probe"))
                }
            };
        }

        let sig = match signature {
            Some(s) => s,
            None => return Err(Error::Format("auth: missing signature")),
        };

        // For a certificate, verify the CA signature, type, validity and
        // critical-options BEFORE the userauth signature check, then build the
        // userauth-signature verifier from the cert's EMBEDDED key. The signed
        // data hashes the cert key-type name + the full cert blob, which is
        // already what `algorithm` / `public_blob` carry — so the standard
        // `publickey_signed_data` is correct as-is.
        let (verifier, cert_info): (Box<dyn HostKeyVerify>, Option<CertInfo>) = if is_cert {
            let cert = match crate::cert::Certificate::parse(&public_blob) {
                Ok(c) => c,
                Err(_) => return self.emit_failure(),
            };
            // Bind the request's `algorithm` to the certificate and to the
            // signature (RFC 8332 §3.2, OpenSSH `sshkey_check_sigtype`): the
            // cert name must be one we know, its plain form must belong to
            // the embedded key's family, and the signature blob must be
            // made with exactly that plain algorithm. Otherwise a client
            // could offer `rsa-sha2-512-cert-v01@openssh.com` and sign with
            // `rsa-sha2-256` (or SHA-1 `ssh-rsa`, if enabled) — the
            // advertised hash would be meaningless.
            let plain = match cert_plain_algorithm(&algorithm, &cert) {
                Some(p) => p,
                None => return self.emit_failure(),
            };
            if signature_algorithm(&sig) != Some(plain) {
                return self.emit_failure();
            }
            if cert.check_type(crate::cert::CertType::User).is_err()
                || cert.check_validity(self.now).is_err()
                || cert.require_known_critical_options().is_err()
            {
                return self.emit_failure();
            }
            let ca_algos: Vec<&str> = if self.ca_signature_algorithms.is_empty() {
                crate::config::algos::CA_SIGNATURE_DEFAULTS.to_vec()
            } else {
                self.ca_signature_algorithms
                    .iter()
                    .map(|s| s.as_str())
                    .collect()
            };
            if cert.verify_ca_signature(&ca_algos).is_err() {
                return self.emit_failure();
            }
            // The verifier is keyed on the *negotiated* plain name (which
            // also applies the `ssh-rsa` SHA-1 gate), never on whatever
            // name the signature blob happens to carry.
            let v = match host_key_verify_by_name(plain, cert.embedded_pubkey_blob()) {
                Ok(v) => v,
                Err(_) => return self.emit_failure(),
            };
            (v, Some(CertInfo::from_certificate(&cert)?))
        } else {
            (host_key_verify_by_name(&algorithm, &public_blob)?, None)
        };

        let signed = super::message::publickey_signed_data_bound(
            &self.session_id,
            wire_user,
            self.service,
            &algorithm,
            &public_blob,
            host_key.as_deref(),
        );
        if verifier.verify(&signed, &sig).is_err() {
            return self.emit_failure();
        }

        // Capture the cert's connection-phase capability gates (default-deny
        // extensions + `force-command`) BEFORE evaluating, so an eventual
        // Accept — possibly several factors later under a multi-factor chain —
        // can carry them. The authenticator still owns the *trust* verdict; we
        // only record what a successful cert would authorize. Overwrites any
        // previously-captured caps so the last verified cert wins (matching the
        // last-cert-verified semantics of a repeated publickey factor).
        if let Some(ci) = &cert_info {
            self.pending_cert_caps = Some(AuthCertCaps::from_cert_info(ci));
        }

        let decision = self.auth.evaluate(AuthAttempt::PublicKey {
            user: user.clone(),
            algorithm,
            public_blob: public_blob.clone(),
            probe_only: false,
            verified: true,
            cert: cert_info,
        });
        // The accepted key's own restrictions (authorized_keys options),
        // on top of a certificate's.
        let decision = match decision {
            d @ (AuthDecision::Accept | AuthDecision::PartialAccept { .. }) => {
                match self.auth.key_restrictions(&user, &public_blob) {
                    None => d,
                    Some(r) => match self.pending_cert_caps.take() {
                        None => {
                            self.pending_cert_caps = Some(r);
                            d
                        }
                        Some(c) => match c.intersect(r) {
                            Some(both) => {
                                self.pending_cert_caps = Some(both);
                                d
                            }
                            None => AuthDecision::Reject,
                        },
                    },
                }
            }
            other => other,
        };
        if matches!(decision, AuthDecision::PartialAccept { .. }) {
            self.used_keys.push(key_blob);
        }
        let key_type = crate::format::Reader::new(&public_blob)
            .read_string()
            .ok()
            .and_then(|t| core::str::from_utf8(t).ok())
            .unwrap_or("");
        let line = alloc::format!(
            "publickey {key_type} {}",
            crate::key::base64::encode(&public_blob)
        );
        self.record_success(&decision, line);
        self.apply_decision(decision, &user)
    }

    /// Note a method that succeeded (fully or as one factor).
    fn record_success(&mut self, decision: &AuthDecision, line: String) {
        if matches!(
            decision,
            AuthDecision::Accept | AuthDecision::PartialAccept { .. }
        ) {
            self.auth_info.push_str(&line);
            self.auth_info.push('\n');
        }
    }

    fn apply_decision(&mut self, decision: AuthDecision, user: &str) -> Result<ServerStep> {
        match decision {
            AuthDecision::Accept => {
                self.state = State::Done;
                Ok(ServerStep::Authenticated {
                    payload: encode_success(),
                    user: user.into(),
                    cert_caps: self.pending_cert_caps.take(),
                    auth_info: core::mem::take(&mut self.auth_info),
                })
            }
            AuthDecision::PartialAccept { still_required } => {
                let failure = UserauthFailure {
                    continuations: still_required,
                    partial_success: true,
                };
                Ok(ServerStep::Send(failure.encode()))
            }
            AuthDecision::Reject => self.emit_failure(),
            AuthDecision::InteractiveRequest {
                name,
                instruction,
                prompts,
            } => {
                let prompt_count = prompts.len();
                let req = UserauthInfoRequest {
                    name,
                    instruction,
                    language: String::new(),
                    prompts,
                };
                self.state = State::AwaitingInfoResponse;
                self.pending_user = Some(user.into());
                self.pending_prompt_count = Some(prompt_count);
                Ok(ServerStep::Send(req.encode()))
            }
        }
    }

    #[cfg(test)]
    fn failed_attempts(&self) -> u32 {
        self.failed_attempts
    }

    /// The username pinned by the first USERAUTH_REQUEST, if any.
    #[cfg(test)]
    fn pinned_user(&self) -> Option<&str> {
        self.first_user.as_deref()
    }

    fn emit_failure(&mut self) -> Result<ServerStep> {
        // A USERAUTH_FAILURE (without partial success) is a failed attempt;
        // count it and disconnect once MaxAuthTries is exceeded. OpenSSH
        // counts the attempt then drops the connection on the *next* failure
        // past the limit; we disconnect as soon as the count exceeds the
        // limit so a limit of N permits exactly N failed attempts.
        self.failed_attempts = self.failed_attempts.saturating_add(1);
        if let Some(max) = self.max_auth_tries
            && self.failed_attempts > max
        {
            self.state = State::Done;
            return Ok(ServerStep::Disconnect("Too many authentication failures"));
        }
        let cont = self.auth.continuable_methods(&self.accepted_methods);
        let failure = UserauthFailure {
            continuations: cont,
            partial_success: false,
        };
        Ok(ServerStep::Send(failure.encode()))
    }
}

/// Resolve the plain signature-algorithm name a userauth `algorithm` of
/// certificate type pins, checking it against the certificate's embedded key
/// family. `None` if the name is unknown or names a different key family
/// (an ed25519 cert offered as `rsa-sha2-512-cert-v01@openssh.com`, say).
/// Mirrors the KEX-side check in `host_key_verify_by_name`'s cert branch.
fn cert_plain_algorithm(algorithm: &str, cert: &crate::cert::Certificate) -> Option<&'static str> {
    let plain = crate::cert::cert_name_to_plain(algorithm)?;
    let family_ok = match cert.embedded_algorithm() {
        "ssh-rsa" => matches!(plain, "rsa-sha2-256" | "rsa-sha2-512" | "ssh-rsa"),
        other => plain == other,
    };
    family_ok.then_some(plain)
}

/// The leading algorithm-name string of an SSH signature blob.
fn signature_algorithm(sig_blob: &[u8]) -> Option<&str> {
    let mut r = crate::format::Reader::new(sig_blob);
    core::str::from_utf8(r.read_string().ok()?).ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::message::{AuthMethodPayload, SecretString, ServiceRequest, UserauthRequest};

    struct RejectAll;
    impl Authenticator for RejectAll {
        fn evaluate(&mut self, _attempt: AuthAttempt) -> AuthDecision {
            AuthDecision::Reject
        }
    }

    fn service_req() -> Vec<u8> {
        ServiceRequest {
            service: "ssh-userauth".into(),
        }
        .encode()
    }

    fn password_req() -> Vec<u8> {
        UserauthRequest {
            user: "alice".into(),
            service: "ssh-connection".into(),
            method: AuthMethodPayload::Password {
                password: SecretString::from("wrong"),
                new_password: None,
            },
        }
        .encode()
    }

    #[test]
    fn max_auth_tries_disconnects() {
        let mut sa = ServerAuth::new(vec![1, 2, 3], vec!["password"], Box::new(RejectAll));
        sa.set_max_auth_tries(Some(2));
        // Service request → accept.
        assert!(matches!(
            sa.on_packet(&service_req()).unwrap(),
            ServerStep::Send(_)
        ));
        // First two failures emit USERAUTH_FAILURE.
        assert!(matches!(
            sa.on_packet(&password_req()).unwrap(),
            ServerStep::Send(_)
        ));
        assert!(matches!(
            sa.on_packet(&password_req()).unwrap(),
            ServerStep::Send(_)
        ));
        assert_eq!(sa.failed_attempts(), 2);
        // Third failure exceeds the limit ⇒ Disconnect.
        assert!(matches!(
            sa.on_packet(&password_req()).unwrap(),
            ServerStep::Disconnect(_)
        ));
    }

    #[test]
    fn peek_request_extracts_user_and_method() {
        let (user, method) = ServerAuth::peek_request(&password_req()).expect("decoded");
        assert_eq!(user, "alice");
        assert_eq!(method, "password");
        // A non-request payload yields None.
        assert!(ServerAuth::peek_request(&service_req()).is_none());
    }

    #[test]
    fn reject_unadvertised_counts_and_uses_current_methods() {
        let mut sa = ServerAuth::new(vec![1, 2, 3], vec!["publickey"], Box::new(RejectAll));
        // A Match block re-resolve drops publickey for this user.
        sa.set_accepted_methods(vec![]);
        assert!(sa.accepted_methods().is_empty());
        assert!(matches!(
            sa.reject_unadvertised("alice").unwrap(),
            ServerStep::Send(_)
        ));
        assert_eq!(sa.failed_attempts(), 1);
        // The rejected request's username is pinned exactly like a request
        // that reached the authenticator would have been.
        assert_eq!(sa.pinned_user(), Some("alice"));
        // A later unadvertised attempt under a different name disconnects
        // without counting as another failure.
        assert!(matches!(
            sa.reject_unadvertised("bob").unwrap(),
            ServerStep::Disconnect(_)
        ));
        assert_eq!(sa.failed_attempts(), 1);
    }

    #[test]
    fn service_mismatch_rejection_still_pins_username() {
        // A first request refused for naming the wrong service must still
        // pin its username, so the next request cannot switch names.
        let mut sa = ServerAuth::new(vec![1, 2, 3], vec!["password"], Box::new(RejectAll));
        sa.on_packet(&service_req()).unwrap();
        let bad_service = UserauthRequest {
            user: "alice".into(),
            service: "not-ssh-connection".into(),
            method: AuthMethodPayload::None,
        }
        .encode();
        assert!(matches!(
            sa.on_packet(&bad_service).unwrap(),
            ServerStep::Send(_)
        ));
        assert_eq!(sa.pinned_user(), Some("alice"));
        let bob = UserauthRequest {
            user: "bob".into(),
            service: "ssh-connection".into(),
            method: AuthMethodPayload::Password {
                password: SecretString::from("x"),
                new_password: None,
            },
        }
        .encode();
        assert!(matches!(
            sa.on_packet(&bob).unwrap(),
            ServerStep::Disconnect(_)
        ));
    }

    #[test]
    fn no_limit_keeps_failing() {
        let mut sa = ServerAuth::new(vec![1], vec!["password"], Box::new(RejectAll));
        sa.on_packet(&service_req()).unwrap();
        for _ in 0..10 {
            assert!(matches!(
                sa.on_packet(&password_req()).unwrap(),
                ServerStep::Send(_)
            ));
        }
    }
}