kekse 0.1.0

A strict, dependency-light cookie codec: a Set-Cookie builder and a Cookie-header parser built on the RFC 6265 grammar.
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
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
//! The response [`SetCookie`] — a [`Cookie`] kernel plus [`CookieAttributes`] —
//! its `Set-Cookie` parse and serialize, and the conversion straight into an
//! `http::HeaderValue`.

use std::borrow::Cow;
use std::fmt;

use rfc_6265::OffsetDateTime;
use rfc_6265::date::{format_imf_fixdate, parse_cookie_date, parse_imf_fixdate};

use crate::attributes::{CookieAttributes, Domain, Path};
use crate::cookie::Cookie;
use crate::encoding::{ValueEncoding, decode_cookie_value};
use crate::grammar::is_ws_char;
use crate::report::{PairIssue, Reported};
use crate::same_site::SameSite;
use crate::wire::split_checked_pair;

/// A `Set-Cookie:` response cookie: a [`Cookie`] kernel (name, value, wire
/// encoding) plus [`CookieAttributes`] (`HttpOnly`, `SameSite`, `Secure`,
/// `Path`, `Domain`, `Expires`, `Max-Age`). A `Set-Cookie` line is *fully
/// observed*, so the
/// flags are plain `bool` — present or absent on the line — never an `Option`.
///
/// Build one from a request [`Cookie`] with
/// [`Cookie::into_set_cookie`](crate::Cookie::into_set_cookie) (default
/// attributes) or [`Cookie::with_attributes`](crate::Cookie::with_attributes) (a
/// prebuilt set), or from scratch with [`new`](SetCookie::new). Set attributes
/// with the fluent verbs — [`secure`](SetCookie::secure),
/// [`http_only`](SetCookie::http_only), [`path`](SetCookie::path), … — which
/// delegate to the embedded [`CookieAttributes`]; the valueless flags are
/// nullary. Read them back through [`attributes`](SetCookie::attributes) as
/// fields (`sc.attributes().secure`, `sc.attributes().max_age`). Render with
/// [`to_set_cookie`](SetCookie::to_set_cookie) or convert straight into an
/// `http::HeaderValue` with `HeaderValue::try_from`. Attributes emit in a fixed
/// order — `HttpOnly`, `SameSite`, `Secure`, `Path`, `Domain`, `Expires`,
/// `Max-Age` — each only when set. The builder does **not** validate the name (check
/// [`is_cookie_name`](crate::is_cookie_name) at the call site if it is
/// untrusted); [`parse`](SetCookie::parse) does.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SetCookie<'a> {
    cookie: Cookie<'a>,
    attributes: CookieAttributes<'a>,
}

impl<'a> SetCookie<'a> {
    /// Pair a [`Cookie`] kernel with a set of [`CookieAttributes`]. The one true
    /// constructor — [`new`](SetCookie::new), `From<Cookie>`,
    /// `From<(Cookie, CookieAttributes)>`,
    /// [`Cookie::into_set_cookie`](crate::Cookie::into_set_cookie), and
    /// [`Cookie::with_attributes`](crate::Cookie::with_attributes) all route here.
    pub fn from_parts(cookie: Cookie<'a>, attributes: CookieAttributes<'a>) -> Self {
        Self { cookie, attributes }
    }

    /// Start a `Set-Cookie` for `name=value` with no attributes set and the
    /// default [`ValueEncoding`]. Shorthand for
    /// `Cookie::new(name, value).into_set_cookie()`.
    pub fn new(name: &'a str, value: impl Into<Cow<'a, str>>) -> Self {
        Self::from_parts(Cookie::new(name, value), CookieAttributes::default())
    }

    /// Parse one `Set-Cookie` header value into a `SetCookie` (RFC 6265 §5.2). An
    /// **unrecognised attribute is ignored** and the cookie is kept, per §5.2 — so
    /// a modern attribute this version does not model (`Partitioned`, `Priority`,
    /// …) never costs you the cookie. Use
    /// [`parse_strict`](SetCookie::parse_strict) to reject on an unknown attribute
    /// instead.
    ///
    /// Splits on the first `;` into the `name=value` pair and the attribute list,
    /// then the pair on its first `=`. The name must be a cookie-name token; the
    /// value runs through the same lenient pipeline as
    /// [`parse_pairs`](crate::parse_pairs) (one wrapping quote pair stripped,
    /// cookie-octets plus whitespace, percent-decoded). Attributes are matched
    /// ASCII-case-insensitively: `HttpOnly`, `Secure`, `SameSite`
    /// (`Strict`/`Lax`/`None`), `Path`, `Domain`, `Max-Age` (a `u64`; a negative
    /// or non-numeric delta is dropped), and `Expires` (the lenient RFC 6265
    /// §5.1.1 cookie-date here; [`parse_strict`](SetCookie::parse_strict) takes
    /// only the RFC 7231 IMF-fixdate — an unparseable date is dropped, cookie
    /// kept). Returns
    /// `None` when there is no usable pair — no `=`, an empty or non-token name,
    /// or a value outside the accepted set / with escapes that are not valid
    /// UTF-8. Never panics.
    pub fn parse(header_value: &'a str) -> Option<Self> {
        Self::parse_with(header_value, false, None).ok()
    }

    /// Like [`parse`](SetCookie::parse) but **strict**: an unrecognised attribute — or a
    /// **duplicate** of any attribute — rejects the whole cookie (`None`) instead of being ignored.
    /// A tripwire for cookies you minted yourself, where an attribute you did not emit (or emitted
    /// twice) signals something is wrong. A malformed *known* attribute (e.g. a non-numeric
    /// `Max-Age`) is dropped, not fatal, in both modes; lenient [`parse`](SetCookie::parse)
    /// tolerates duplicates (last-wins).
    ///
    /// Unlike [`parse_pairs_strict`](crate::parse_pairs_strict), strict mode does **not** tighten
    /// the cookie-*value* pipeline: one wrapping quote pair is still stripped and raw `SP`/`HTAB`
    /// inside the value is still accepted, exactly as in [`parse`](SetCookie::parse). This is
    /// deliberate — every managed [`ValueEncoding`], including
    /// [`Quoted`](ValueEncoding::Quoted) (which carries whitespace raw inside its quotes), must
    /// round-trip through the strict reader. Response-side strictness polices the *attributes*,
    /// not the value's escaping.
    pub fn parse_strict(header_value: &'a str) -> Option<Self> {
        Self::parse_with(header_value, true, None).ok()
    }

    /// [`parse`](SetCookie::parse), reporting: `Ok` carries the cookie plus every
    /// non-fatal drop as a [`SetCookieIssue`] (an ignored unknown attribute, a
    /// duplicate, a malformed known-attribute value, a valued flag), in wire
    /// order; `Err` is the single fatal issue — always an
    /// [`InvalidPair`](SetCookieIssue::InvalidPair) here, since lenient parsing
    /// only rejects a cookie whose `name=value` pair is unusable. The report is
    /// how a caller *observes* what fail-soft would silently cost — a mistyped
    /// `HttpOnly` or a `;`-fused attribute lands in `issues` instead of
    /// vanishing — and `!`[`is_clean`](Reported::is_clean) is the opt-in
    /// fail-hard gate.
    pub fn try_parse(
        header_value: &'a str,
    ) -> Result<Reported<Self, SetCookieIssue<'a>>, SetCookieIssue<'a>> {
        let mut issues = Vec::new();
        let value = Self::parse_with(header_value, false, Some(&mut issues))?;
        Ok(Reported { value, issues })
    }

    /// [`parse_strict`](SetCookie::parse_strict), reporting — see
    /// [`try_parse`](SetCookie::try_parse). `Err` additionally covers the first
    /// [`UnknownAttribute`](SetCookieIssue::UnknownAttribute) or
    /// [`DuplicateAttribute`](SetCookieIssue::DuplicateAttribute), matching
    /// [`parse_strict`](SetCookie::parse_strict)'s rejections. A malformed
    /// known-attribute *value* stays non-fatal even here (exactly as in
    /// [`parse_strict`](SetCookie::parse_strict)) — but it is reported, so a
    /// caller gating on [`is_clean`](Reported::is_clean) is deliberately
    /// stricter than strict.
    pub fn try_parse_strict(
        header_value: &'a str,
    ) -> Result<Reported<Self, SetCookieIssue<'a>>, SetCookieIssue<'a>> {
        let mut issues = Vec::new();
        let value = Self::parse_with(header_value, true, Some(&mut issues))?;
        Ok(Reported { value, issues })
    }

    fn parse_with(
        header_value: &'a str,
        strict: bool,
        mut report: Option<&mut Vec<SetCookieIssue<'a>>>,
    ) -> Result<Self, SetCookieIssue<'a>> {
        // The leading segment is the `name=value` pair; everything after the first `;`
        // is attributes. `str::split` always yields the leading segment, even for "".
        let mut segments = header_value.split(';');
        let (name, raw_value) = split_checked_pair(segments.next().unwrap_or_default().as_bytes())
            .map_err(SetCookieIssue::InvalidPair)?;
        // The value pipeline is deliberately the lenient one in BOTH modes — see
        // `parse_strict`'s docs: every managed encoding must round-trip through it.
        let Some(value) = decode_cookie_value(raw_value, true) else {
            #[cfg(feature = "tracing")]
            tracing::debug!(
                cookie = %name,
                "rejecting Set-Cookie: value carries a byte outside the accepted \
                 set or percent-escapes that are not valid UTF-8"
            );
            return Err(SetCookieIssue::InvalidPair(PairIssue::InvalidValue {
                name,
                value: raw_value,
            }));
        };
        let mut set_cookie =
            Self::from_parts(Cookie::new(name, value), CookieAttributes::default());
        // Bits of recognised attributes already seen, so strict mode can reject a duplicate
        // (e.g. two `Domain=`). Lenient keeps last-wins, consistent across every attribute.
        let mut seen: u8 = 0;
        for piece in segments {
            let (attr, val) = match piece.split_once('=') {
                Some((a, v)) => (a.trim_matches(is_ws_char), v.trim_matches(is_ws_char)),
                None => (piece.trim_matches(is_ws_char), ""),
            };
            if attr.is_empty() {
                continue; // a stray or trailing `;` — not an attribute
            }
            let Some(known) = KnownAttribute::recognize(attr) else {
                let issue = SetCookieIssue::UnknownAttribute { name: attr };
                if strict {
                    // Strict (opt-in): an unrecognised attribute rejects the cookie.
                    return Err(issue);
                }
                // Default: an unrecognised attribute is ignored (RFC 6265 §5.2) —
                // logged and reported, so a mistyped flag never vanishes without
                // a trace.
                #[cfg(feature = "tracing")]
                tracing::debug!(
                    attribute = %attr.escape_debug(),
                    "ignoring an unrecognised attribute; the cookie is kept (RFC 6265 §5.2)"
                );
                record(&mut report, issue);
                continue;
            };
            if seen & known.bit() != 0 {
                let issue = SetCookieIssue::DuplicateAttribute { attribute: known };
                if strict {
                    // Strict: a repeated attribute rejects the whole cookie.
                    return Err(issue);
                }
                // Lenient keeps last-wins — logged and reported, since the
                // overwrite is invisible in the parsed result.
                #[cfg(feature = "tracing")]
                tracing::debug!(
                    attribute = known.name(),
                    "duplicate attribute; the last occurrence that parses wins"
                );
                record(&mut report, issue);
            }
            seen |= known.bit();
            let attributes = &mut set_cookie.attributes;
            match known {
                // The flags are presence-only: a value on them is not RFC 6265
                // shape, so it is reported — but the flag still sets, as ever.
                KnownAttribute::HttpOnly => {
                    if !val.is_empty() {
                        record(
                            &mut report,
                            SetCookieIssue::FlagWithValue {
                                attribute: known,
                                value: val,
                            },
                        );
                    }
                    attributes.http_only = true;
                }
                KnownAttribute::Secure => {
                    if !val.is_empty() {
                        record(
                            &mut report,
                            SetCookieIssue::FlagWithValue {
                                attribute: known,
                                value: val,
                            },
                        );
                    }
                    attributes.secure = true;
                }
                // `.ok()` drops an unrecognised token (keeping the cookie), same as
                // a malformed Max-Age — see `SameSite`'s case-insensitive `FromStr`.
                KnownAttribute::SameSite => {
                    if let Some(v) = noted(val.parse::<SameSite>().ok(), known, val, &mut report) {
                        attributes.same_site = Some(v);
                    }
                }
                // An invalid value (control byte, `;`, non-ASCII) is dropped like a
                // malformed Max-Age — the cookie is kept, the attribute discarded,
                // and an earlier valid occurrence survives (RFC 6265 §5.2.2:
                // "ignore the cookie-av", not the attribute).
                KnownAttribute::Path => {
                    if let Some(v) = noted(Path::new(val), known, val, &mut report) {
                        attributes.path = Some(v);
                    }
                }
                KnownAttribute::Domain => {
                    if let Some(v) = noted(Domain::new(val), known, val, &mut report) {
                        attributes.domain = Some(v);
                    }
                }
                KnownAttribute::MaxAge => {
                    if let Some(v) = noted(val.parse::<u64>().ok(), known, val, &mut report) {
                        attributes.max_age = Some(v);
                    }
                }
                // RFC 6265 §5.1.1 (lenient) / RFC 7231 IMF-fixdate (strict). An
                // unparseable date is dropped like any malformed known attribute —
                // the cookie survives.
                KnownAttribute::Expires => {
                    let parsed = if strict {
                        parse_imf_fixdate(val)
                    } else {
                        parse_cookie_date(val)
                    };
                    if let Some(v) = noted(parsed, known, val, &mut report) {
                        attributes.expires = Some(v);
                    }
                }
            }
        }
        Ok(set_cookie)
    }

    /// Choose how the value is escaped for the wire (delegates to the kernel).
    #[must_use]
    pub fn with_encoding(mut self, encoding: ValueEncoding) -> Self {
        self.cookie = self.cookie.with_encoding(encoding);
        self
    }

    /// Pair this cookie with a prebuilt [`CookieAttributes`] set, replacing any
    /// already attached — the way to apply a reusable, hardened attribute policy.
    #[must_use]
    pub fn with_attributes(mut self, attributes: CookieAttributes<'a>) -> Self {
        self.attributes = attributes;
        self
    }

    /// Add the `HttpOnly` attribute — a valueless presence flag (nullary). Reads
    /// back as `self.attributes().http_only`.
    #[must_use]
    pub fn http_only(mut self) -> Self {
        self.attributes.http_only = true;
        self
    }

    /// Add the `Secure` attribute — a valueless presence flag (nullary). Reads
    /// back as `self.attributes().secure`.
    #[must_use]
    pub fn secure(mut self) -> Self {
        self.attributes.secure = true;
        self
    }

    /// Set the `SameSite` attribute.
    #[must_use]
    pub fn same_site(mut self, same_site: SameSite) -> Self {
        self.attributes.same_site = Some(same_site);
        self
    }

    /// Set the `Path` attribute. An invalid path (control byte, `;`, or non-ASCII
    /// — see [`Path`](crate::Path)) is rejected and leaves the attribute unset.
    #[must_use]
    pub fn path(mut self, path: &'a str) -> Self {
        self.attributes.path = Path::new(path);
        self
    }

    /// Set the `Domain` attribute. Omit for a host-only cookie. An invalid domain
    /// (see [`Domain`](crate::Domain)) is rejected and leaves the attribute unset.
    #[must_use]
    pub fn domain(mut self, domain: &'a str) -> Self {
        self.attributes.domain = Domain::new(domain);
        self
    }

    /// Set the `Max-Age` attribute, in seconds. `0` instructs the client to
    /// delete the cookie. Rendered as a `u64` decimal — no saturation.
    #[must_use]
    pub fn max_age(mut self, seconds: u64) -> Self {
        self.attributes.max_age = Some(seconds);
        self
    }

    /// Set the `Expires` attribute — an absolute expiry instant, rendered as the
    /// RFC 7231 IMF-fixdate (always in GMT). Independent of
    /// [`max_age`](SetCookie::max_age); a client given both lets `Max-Age` win
    /// (RFC 6265 §5.3), but that is the client's concern, not the codec's.
    #[must_use]
    pub fn expires(mut self, when: OffsetDateTime) -> Self {
        self.attributes.expires = Some(when);
        self
    }

    /// The cookie-name.
    pub fn name(&self) -> &str {
        self.cookie.name()
    }

    /// The cookie-value, decoded — the logical value, not its wire encoding.
    pub fn value(&self) -> &str {
        self.cookie.value()
    }

    /// The value's wire encoding.
    pub fn encoding(&self) -> ValueEncoding {
        self.cookie.encoding()
    }

    /// Borrow the request [`Cookie`] kernel — name, value, encoding — setting the
    /// response attributes aside by *view*.
    pub fn cookie(&self) -> &Cookie<'a> {
        &self.cookie
    }

    /// Borrow the response [`CookieAttributes`]. Read a single attribute as a
    /// field: `sc.attributes().secure`, `sc.attributes().max_age`.
    pub fn attributes(&self) -> &CookieAttributes<'a> {
        &self.attributes
    }

    /// Drop the attributes, recovering the request [`Cookie`] kernel. A
    /// structural move — the value is **not** re-encoded, so a borrowed value
    /// stays borrowed. The inverse of
    /// [`Cookie::into_set_cookie`](crate::Cookie::into_set_cookie).
    pub fn into_cookie(self) -> Cookie<'a> {
        self.cookie
    }

    /// Take the response [`CookieAttributes`], discarding the kernel.
    pub fn into_attributes(self) -> CookieAttributes<'a> {
        self.attributes
    }

    /// Render the request `Cookie:` pair (`name=value`) — attributes ignored.
    /// Delegates to [`Cookie::to_request_pair`](crate::Cookie::to_request_pair).
    pub fn to_request_pair(&self) -> String {
        self.cookie.to_request_pair()
    }

    /// Render the response `Set-Cookie:` value — `name=value` plus the set
    /// attributes, in the fixed order `HttpOnly`, `SameSite`, `Secure`, `Path`,
    /// `Domain`, `Expires`, `Max-Age` (each only when set; a flag only when
    /// `true`).
    ///
    /// The pair and each rendered attribute are joined with `"; "` exactly once.
    /// Each attribute is a typed value that renders itself, and its name comes
    /// from the same constants the parser matches, so the separator and every
    /// attribute name live in a single place.
    pub fn to_set_cookie(&self) -> String {
        let attributes = self.set_cookie_attributes();
        std::iter::once(self.cookie.to_request_pair())
            .chain(attributes.iter().map(|attribute| attribute.to_string()))
            .collect::<Vec<_>>()
            .join("; ")
    }

    /// The set response attributes as typed values, in the canonical `Set-Cookie`
    /// order. A boolean flag appears only when `true`; an unset flag or absent
    /// attribute is omitted.
    fn set_cookie_attributes(&self) -> Vec<SetCookieAttribute<'a>> {
        let a = &self.attributes;
        [
            a.http_only.then_some(SetCookieAttribute::HttpOnly),
            a.same_site.map(SetCookieAttribute::SameSite),
            a.secure.then_some(SetCookieAttribute::Secure),
            a.path.map(|p| SetCookieAttribute::Path(p.as_str())),
            a.domain.map(|d| SetCookieAttribute::Domain(d.as_str())),
            a.expires.map(SetCookieAttribute::Expires),
            a.max_age.map(SetCookieAttribute::MaxAge),
        ]
        .into_iter()
        .flatten()
        .collect()
    }
}

impl<'a> From<(Cookie<'a>, CookieAttributes<'a>)> for SetCookie<'a> {
    /// Pair a kernel with attributes — same as
    /// [`from_parts`](SetCookie::from_parts).
    fn from((cookie, attributes): (Cookie<'a>, CookieAttributes<'a>)) -> Self {
        SetCookie::from_parts(cookie, attributes)
    }
}

/// Canonical `Set-Cookie` attribute names — the single source of truth shared by
/// the parser (matched ASCII-case-insensitively) and the serializer (the
/// `Display` for `SetCookieAttribute`), so the reader and the writer can't drift.
mod attr_name {
    pub const HTTP_ONLY: &str = "HttpOnly";
    pub const SECURE: &str = "Secure";
    pub const SAME_SITE: &str = "SameSite";
    pub const PATH: &str = "Path";
    pub const DOMAIN: &str = "Domain";
    pub const MAX_AGE: &str = "Max-Age";
    pub const EXPIRES: &str = "Expires";
}

/// A recognised `Set-Cookie` attribute — the parser's dispatch unit, and the
/// attribute identity a [`SetCookieIssue`] names. Recognition (the private
/// `recognize`), strict duplicate accounting (`bit`), and application (the
/// `match` in `parse_with`) are separate phases: the compiler forces
/// [`name`](KnownAttribute::name) and the applying `match` to cover every
/// variant, and the duplicate bit derives from the discriminant, so none of the
/// three can drift the way a hand-numbered bitmask across an `if`/`else` chain
/// could.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KnownAttribute {
    /// The `HttpOnly` presence flag.
    HttpOnly,
    /// The `Secure` presence flag.
    Secure,
    /// The `SameSite` attribute.
    SameSite,
    /// The `Path` attribute.
    Path,
    /// The `Domain` attribute.
    Domain,
    /// The `Max-Age` attribute.
    MaxAge,
    /// The `Expires` attribute.
    Expires,
}

impl KnownAttribute {
    /// Every recognisable attribute. [`recognize`](KnownAttribute::recognize)
    /// scans this list, so a variant missing here would be unreachable from the
    /// wire — the recognition test walks it against every canonical name.
    const ALL: [Self; 7] = [
        Self::HttpOnly,
        Self::Secure,
        Self::SameSite,
        Self::Path,
        Self::Domain,
        Self::MaxAge,
        Self::Expires,
    ];

    /// The canonical wire name — the same `attr_name` constant the serializer
    /// renders, so reader and writer share one spelling per attribute.
    pub const fn name(self) -> &'static str {
        match self {
            Self::HttpOnly => attr_name::HTTP_ONLY,
            Self::Secure => attr_name::SECURE,
            Self::SameSite => attr_name::SAME_SITE,
            Self::Path => attr_name::PATH,
            Self::Domain => attr_name::DOMAIN,
            Self::MaxAge => attr_name::MAX_AGE,
            Self::Expires => attr_name::EXPIRES,
        }
    }

    /// Match a wire attribute name, ASCII-case-insensitively (RFC 6265 §5.2).
    fn recognize(attr: &str) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|known| attr.eq_ignore_ascii_case(known.name()))
    }

    /// This attribute's bit in the strict-mode duplicate mask, derived from the
    /// discriminant (7 variants fit a `u8`) — collision-free by construction.
    const fn bit(self) -> u8 {
        1 << (self as u8)
    }
}

/// Everything a `Set-Cookie` parse can drop or reject, with the offending wire
/// slice — borrowed from the header value, never allocated.
///
/// Yielded by [`SetCookie::try_parse`] / [`SetCookie::try_parse_strict`]: the
/// fatal case is the `Err`, the fail-soft drops fill
/// [`Reported::issues`]. Which variants are fatal is the mode's
/// choice — lenient rejects only [`InvalidPair`](SetCookieIssue::InvalidPair);
/// strict also rejects [`UnknownAttribute`](SetCookieIssue::UnknownAttribute)
/// and [`DuplicateAttribute`](SetCookieIssue::DuplicateAttribute). The
/// [`Display`](fmt::Display) form escapes the wire slices, so a rendered issue
/// never carries a raw control byte (CR/LF, NUL, …).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SetCookieIssue<'a> {
    /// No usable `name=value` pair — fatal in every mode; the wrapped
    /// [`PairIssue`] says why.
    InvalidPair(
        /// The pair-level defect, exactly as the request readers report it.
        PairIssue<'a>,
    ),
    /// An attribute name this version does not model — a genuinely new
    /// attribute (`Partitioned`, `Priority`, …), a mistyped one (`HttpOnlyy`),
    /// or two attributes fused by a forgotten `;`. Lenient: ignored
    /// (RFC 6265 §5.2). Strict: fatal.
    #[non_exhaustive]
    UnknownAttribute {
        /// The unrecognised, OWS-trimmed attribute name.
        name: &'a str,
    },
    /// A repeated known attribute. Lenient: last-wins (the overwrite is
    /// invisible in the parsed result). Strict: fatal.
    #[non_exhaustive]
    DuplicateAttribute {
        /// The attribute that repeated.
        attribute: KnownAttribute,
    },
    /// A recognised attribute whose value did not parse (`Max-Age=banana`, an
    /// unparseable `Expires`, an invalid `Path`/`Domain`/`SameSite`). The
    /// attribute is dropped, the cookie kept — in **both** modes.
    #[non_exhaustive]
    InvalidAttributeValue {
        /// The attribute whose value was refused.
        attribute: KnownAttribute,
        /// The OWS-trimmed value that did not parse.
        value: &'a str,
    },
    /// A value on a presence-only flag (`Secure=1`, `HttpOnly=x`). The flag is
    /// set and the value discarded, as ever — reported because that discard is
    /// otherwise invisible.
    #[non_exhaustive]
    FlagWithValue {
        /// The flag that carried a value.
        attribute: KnownAttribute,
        /// The discarded value.
        value: &'a str,
    },
}

impl fmt::Display for SetCookieIssue<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidPair(issue) => write!(f, "Set-Cookie {issue}"),
            Self::UnknownAttribute { name } => {
                write!(f, "unrecognised attribute `{}`", name.escape_debug())
            }
            Self::DuplicateAttribute { attribute } => {
                write!(f, "duplicate `{}` attribute", attribute.name())
            }
            Self::InvalidAttributeValue { attribute, value } => {
                write!(
                    f,
                    "malformed `{}` value `{}` (attribute dropped, cookie kept)",
                    attribute.name(),
                    value.escape_debug()
                )
            }
            Self::FlagWithValue { attribute, value } => {
                write!(
                    f,
                    "value `{}` on the presence-only `{}` flag (flag set, value discarded)",
                    value.escape_debug(),
                    attribute.name()
                )
            }
        }
    }
}

impl std::error::Error for SetCookieIssue<'_> {}

/// Push an issue into the report sink, when one is attached — the plain readers
/// pass `None` and stay allocation-free.
fn record<'a>(report: &mut Option<&mut Vec<SetCookieIssue<'a>>>, issue: SetCookieIssue<'a>) {
    if let Some(sink) = report.as_deref_mut() {
        sink.push(issue);
    }
}

/// Pass a known attribute's parse result through, debug-logging and reporting
/// the fail-soft drop when it is `None` — the malformed-known-attribute skip the
/// crate docs promise, observable like the readers' pair-level skips. The cookie
/// is kept either way; only the malformed occurrence is lost, and it never
/// erases an earlier valid one — RFC 6265 §5.2.2 ignores the *cookie-av*, not
/// the attribute (last-wins applies among the occurrences that parse).
fn noted<'a, T>(
    parsed: Option<T>,
    attribute: KnownAttribute,
    raw_value: &'a str,
    report: &mut Option<&mut Vec<SetCookieIssue<'a>>>,
) -> Option<T> {
    if parsed.is_none() {
        #[cfg(feature = "tracing")]
        tracing::debug!(
            attribute = attribute.name(),
            value = %raw_value.escape_debug(),
            "dropping a malformed known attribute; the cookie is kept"
        );
        record(
            report,
            SetCookieIssue::InvalidAttributeValue {
                attribute,
                value: raw_value,
            },
        );
    }
    parsed
}

/// One rendered `Set-Cookie` attribute — the typed unit the serializer emits.
///
/// [`to_set_cookie`](SetCookie::to_set_cookie) turns each set attribute into one
/// of these and joins their [`Display`](fmt::Display) with `"; "`. Their names
/// come from the `attr_name` constants the parser also matches, so the wire form
/// has a single source of truth. Boolean flags are presence-only: `HttpOnly` and
/// `Secure` render bare, with no `=value`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum SetCookieAttribute<'a> {
    HttpOnly,
    SameSite(SameSite),
    Secure,
    Path(&'a str),
    Domain(&'a str),
    Expires(OffsetDateTime),
    MaxAge(u64),
}

impl fmt::Display for SetCookieAttribute<'_> {
    /// Render the attribute *without* a leading separator;
    /// [`to_set_cookie`](SetCookie::to_set_cookie) joins the pieces with `"; "`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::HttpOnly => f.write_str(attr_name::HTTP_ONLY),
            Self::SameSite(same_site) => {
                write!(f, "{}={}", attr_name::SAME_SITE, same_site.as_str())
            }
            Self::Secure => f.write_str(attr_name::SECURE),
            Self::Path(path) => write!(f, "{}={}", attr_name::PATH, path),
            Self::Domain(domain) => write!(f, "{}={}", attr_name::DOMAIN, domain),
            Self::Expires(when) => {
                write!(f, "{}={}", attr_name::EXPIRES, format_imf_fixdate(when))
            }
            Self::MaxAge(seconds) => write!(f, "{}={}", attr_name::MAX_AGE, seconds),
        }
    }
}

impl TryFrom<SetCookie<'_>> for http::HeaderValue {
    type Error = http::header::InvalidHeaderValue;

    /// Render the **`Set-Cookie`** form (via
    /// [`to_set_cookie`](SetCookie::to_set_cookie)) into a `HeaderValue`. For the
    /// request `Cookie:` form, build from
    /// [`to_request_pair`](SetCookie::to_request_pair).
    ///
    /// # Errors
    ///
    /// Only under [`Raw`](ValueEncoding::Raw), where the caller owns
    /// wire-correctness, and only for a byte no header value may hold (CR, LF,
    /// NUL, or another control). The managed encodings are always header-safe and
    /// never error here.
    fn try_from(cookie: SetCookie<'_>) -> Result<Self, Self::Error> {
        http::HeaderValue::try_from(cookie.to_set_cookie())
    }
}

impl TryFrom<&SetCookie<'_>> for http::HeaderValue {
    type Error = http::header::InvalidHeaderValue;

    /// Borrowing counterpart to the owned `SetCookie` → `HeaderValue` conversion
    /// — renders the `Set-Cookie` form without consuming the cookie.
    ///
    /// # Errors
    ///
    /// Same as the owned conversion: only [`Raw`](ValueEncoding::Raw) with a
    /// header-unsafe byte (CR, LF, NUL, or another control) errors.
    fn try_from(cookie: &SetCookie<'_>) -> Result<Self, Self::Error> {
        http::HeaderValue::try_from(cookie.to_set_cookie())
    }
}

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

    // ---- the KnownAttribute dispatch table ---------------------------------

    #[test]
    fn known_attribute_bits_are_distinct_and_recognition_is_case_insensitive() {
        let mut mask = 0u8;
        for known in KnownAttribute::ALL {
            // Every bit is fresh — the mask can address each attribute independently.
            assert_eq!(mask & known.bit(), 0, "{known:?} bit collides");
            mask |= known.bit();
            // The canonical name and its case variants all recognize back to the variant.
            assert_eq!(KnownAttribute::recognize(known.name()), Some(known));
            assert_eq!(
                KnownAttribute::recognize(&known.name().to_ascii_uppercase()),
                Some(known)
            );
            assert_eq!(
                KnownAttribute::recognize(&known.name().to_ascii_lowercase()),
                Some(known)
            );
        }
        // An attribute this version does not model stays unrecognised.
        assert_eq!(KnownAttribute::recognize("Partitioned"), None);
        assert_eq!(KnownAttribute::recognize(""), None);
    }

    #[test]
    fn strict_rejects_a_duplicate_of_every_attribute() {
        // One duplicated occurrence per recognisable attribute — each must reject in
        // strict and keep last-wins in lenient.
        for (known, dup) in [
            (KnownAttribute::HttpOnly, "HttpOnly; HttpOnly"),
            (KnownAttribute::Secure, "Secure; Secure"),
            (KnownAttribute::SameSite, "SameSite=Lax; SameSite=Strict"),
            (KnownAttribute::Path, "Path=/a; Path=/b"),
            (KnownAttribute::Domain, "Domain=a.test; Domain=b.test"),
            (KnownAttribute::MaxAge, "Max-Age=1; Max-Age=2"),
            (
                KnownAttribute::Expires,
                "Expires=Sun, 06 Nov 1994 08:49:37 GMT; Expires=Mon, 07 Nov 1994 08:49:37 GMT",
            ),
        ] {
            let header = format!("n=v; {dup}");
            assert!(
                SetCookie::parse_strict(&header).is_none(),
                "strict must reject the duplicated {:?} in {header:?}",
                known.name()
            );
            assert!(
                SetCookie::parse(&header).is_some(),
                "lenient must keep the cookie for {header:?}"
            );
        }
        // The ALL table drives the loop above; make sure the loop covered it fully.
        assert_eq!(KnownAttribute::ALL.len(), 7);
    }

    // ---- rendering --------------------------------------------------------

    #[test]
    fn builder_attribute_order_is_fixed() {
        assert_eq!(SetCookie::new("n", "v").to_set_cookie(), "n=v");
        assert_eq!(
            SetCookie::new("n", "v").http_only().to_set_cookie(),
            "n=v; HttpOnly"
        );
        // Builder-call order is irrelevant; emission order is fixed.
        assert_eq!(
            SetCookie::new("n", "v")
                .max_age(60)
                .domain("example.test")
                .path("/app")
                .secure()
                .same_site(SameSite::None)
                .http_only()
                .to_set_cookie(),
            "n=v; HttpOnly; SameSite=None; Secure; Path=/app; Domain=example.test; Max-Age=60"
        );
        // A flag never called is simply absent.
        assert_eq!(
            SetCookie::new("n", "v")
                .same_site(SameSite::Lax)
                .to_set_cookie(),
            "n=v; SameSite=Lax"
        );
    }

    #[test]
    fn builder_max_age_is_u64_without_saturation() {
        assert!(
            SetCookie::new("n", "v")
                .max_age(u64::MAX)
                .to_set_cookie()
                .ends_with("; Max-Age=18446744073709551615")
        );
        assert!(
            SetCookie::new("n", "v")
                .max_age(0)
                .to_set_cookie()
                .ends_with("; Max-Age=0")
        );
    }

    #[test]
    fn hardened_session_cookie_shape() {
        // The shape an auth consumer composes (Percent encoding, full flags).
        let c = SetCookie::new("SID", "deadbeef")
            .with_encoding(ValueEncoding::Percent)
            .http_only()
            .same_site(SameSite::Strict)
            .secure()
            .path("/")
            .max_age(3600)
            .to_set_cookie();
        assert_eq!(
            c,
            "SID=deadbeef; HttpOnly; SameSite=Strict; Secure; Path=/; Max-Age=3600"
        );
    }

    #[test]
    fn with_attributes_applies_a_prebuilt_set() {
        // A hardened policy built once, attached to a kernel.
        let hardened = CookieAttributes::default()
            .http_only()
            .secure()
            .same_site(SameSite::Strict)
            .path("/")
            .max_age(3600);
        let c = Cookie::new("SID", "deadbeef")
            .with_encoding(ValueEncoding::Percent)
            .with_attributes(hardened);
        assert_eq!(
            c.to_set_cookie(),
            "SID=deadbeef; HttpOnly; SameSite=Strict; Secure; Path=/; Max-Age=3600"
        );
        // The (Cookie, CookieAttributes) tuple conversion is the same pairing.
        let parts: SetCookie<'_> =
            (Cookie::new("n", "v"), CookieAttributes::default().secure()).into();
        assert_eq!(parts.to_set_cookie(), "n=v; Secure");
    }

    #[test]
    fn set_cookie_attributes_are_typed_and_in_canonical_order() {
        let c = SetCookie::new("n", "v")
            .max_age(60)
            .domain("example.test")
            .path("/app")
            .secure()
            .same_site(SameSite::Lax)
            .http_only();
        // Builder-call order is irrelevant; the typed list is canonically ordered.
        assert_eq!(
            c.set_cookie_attributes(),
            vec![
                SetCookieAttribute::HttpOnly,
                SetCookieAttribute::SameSite(SameSite::Lax),
                SetCookieAttribute::Secure,
                SetCookieAttribute::Path("/app"),
                SetCookieAttribute::Domain("example.test"),
                SetCookieAttribute::MaxAge(60),
            ]
        );
        // A bare cookie has none.
        assert!(SetCookie::new("n", "v").set_cookie_attributes().is_empty());
    }

    #[test]
    fn set_cookie_attribute_renders_without_a_leading_separator() {
        assert_eq!(SetCookieAttribute::HttpOnly.to_string(), "HttpOnly");
        assert_eq!(SetCookieAttribute::Secure.to_string(), "Secure");
        assert_eq!(
            SetCookieAttribute::SameSite(SameSite::Strict).to_string(),
            "SameSite=Strict"
        );
        assert_eq!(SetCookieAttribute::Path("/").to_string(), "Path=/");
        assert_eq!(
            SetCookieAttribute::Domain("a.test").to_string(),
            "Domain=a.test"
        );
        assert_eq!(SetCookieAttribute::MaxAge(0).to_string(), "Max-Age=0");
    }

    // ---- accessors + transforms ------------------------------------------

    #[test]
    fn accessors_delegate_to_the_kernel_and_flags_are_bool() {
        let c = SetCookie::new("SID", "deadbeef").with_encoding(ValueEncoding::Percent);
        assert_eq!(c.name(), "SID");
        assert_eq!(c.value(), "deadbeef");
        assert_eq!(c.encoding(), ValueEncoding::Percent);
        // Flags are plain bool fields on the attributes — false on a fresh cookie.
        assert!(!c.attributes().http_only);
        assert!(!c.attributes().secure);
    }

    #[test]
    fn cookie_and_into_cookie_recover_the_kernel() {
        let sc = SetCookie::new("n", "v").path("/x").secure();
        // The borrowed view ignores the attributes.
        assert_eq!(sc.cookie().name(), "n");
        assert_eq!(sc.cookie().to_request_pair(), "n=v");
        // The attributes are readable as fields.
        assert!(sc.attributes().secure);
        assert_eq!(sc.attributes().path.map(|v| v.as_str()), Some("/x"));
        // Owned demotion drops the attributes; the request pair carries none.
        assert_eq!(sc.into_cookie().to_request_pair(), "n=v");
    }

    #[test]
    fn into_attributes_takes_the_attribute_set() {
        let attrs = SetCookie::new("n", "v")
            .secure()
            .max_age(60)
            .into_attributes();
        assert!(attrs.secure);
        assert_eq!(attrs.max_age, Some(60));
    }

    // ---- SetCookie -> HeaderValue ----------------------------------------

    #[test]
    fn try_into_header_value_is_byte_pinned() {
        // The exact bytes the auth consumer pins (its hardened-session test).
        let hv = http::HeaderValue::try_from(
            SetCookie::new("SID", "deadbeef")
                .with_encoding(ValueEncoding::Percent)
                .http_only()
                .same_site(SameSite::Strict)
                .secure()
                .path("/")
                .max_age(3600),
        )
        .unwrap();
        assert_eq!(
            hv.to_str().unwrap(),
            "SID=deadbeef; HttpOnly; SameSite=Strict; Secure; Path=/; Max-Age=3600"
        );
    }

    #[test]
    fn try_into_header_value_matches_to_set_cookie() {
        let c = SetCookie::new("n", "v").http_only().max_age(60);
        let via_ref = http::HeaderValue::try_from(&c).unwrap();
        let via_owned = http::HeaderValue::try_from(c.clone()).unwrap();
        assert_eq!(via_ref.to_str().unwrap(), c.to_set_cookie());
        assert_eq!(via_owned, via_ref);
    }

    #[test]
    fn try_into_header_value_rejects_raw_injection() {
        // Raw hands wire-correctness to the caller, so a CR/LF smuggle is caught
        // at the header boundary rather than silently emitted.
        let c = SetCookie::new("n", "x\r\nSet-Cookie: evil=1").with_encoding(ValueEncoding::Raw);
        assert!(http::HeaderValue::try_from(c).is_err());
    }

    #[test]
    fn raw_lets_non_ascii_through_construction_but_not_as_text() {
        // Raw hands wire-correctness to the caller. Non-ASCII UTF-8 bytes (>= 0x80)
        // are obs-text: HeaderValue *construction* accepts them — only CR/LF/NUL and
        // other controls are refused — so a Raw "café" forms a header value, but one
        // whose bytes are not visible-ASCII text, so `to_str()` then fails.
        let raw = http::HeaderValue::try_from(
            SetCookie::new("n", "café").with_encoding(ValueEncoding::Raw),
        )
        .expect("obs-text bytes are valid at header construction");
        assert!(
            raw.to_str().is_err(),
            "the header carries raw non-ASCII bytes, not visible-ASCII text"
        );
        // A managed encoding escapes the non-ASCII losslessly, so it stays header text.
        let managed = http::HeaderValue::try_from(
            SetCookie::new("n", "café").with_encoding(ValueEncoding::Percent),
        )
        .unwrap();
        assert_eq!(managed.to_str().unwrap(), "n=caf%C3%A9");
    }

    #[test]
    fn try_into_header_value_managed_never_errors() {
        let hostile = [
            "a;b",
            "a\r\nX: y",
            "a b",
            "café",
            "a,b",
            "a\"b",
            "a\\b",
            "\u{0}\u{1f}\u{7f}",
            "%41",
        ];
        for v in hostile {
            for enc in [
                ValueEncoding::Auto,
                ValueEncoding::Percent,
                ValueEncoding::Quoted,
            ] {
                let c = SetCookie::new("n", v).with_encoding(enc);
                let hv = http::HeaderValue::try_from(&c)
                    .unwrap_or_else(|e| panic!("managed {enc:?} of {v:?} must form a header: {e}"));
                assert_eq!(hv.to_str().unwrap(), c.to_set_cookie());
            }
        }
    }

    // ---- parse (Set-Cookie -> SetCookie) ---------------------------------

    #[test]
    fn parse_round_trips_a_built_set_cookie() {
        let wire = SetCookie::new("SID", "deadbeef")
            .with_encoding(ValueEncoding::Percent)
            .http_only()
            .same_site(SameSite::Strict)
            .secure()
            .path("/")
            .max_age(3600)
            .to_set_cookie();
        let parsed = SetCookie::parse(&wire).unwrap();
        assert_eq!(parsed.name(), "SID");
        assert_eq!(parsed.value(), "deadbeef");
        assert!(parsed.attributes().http_only && parsed.attributes().secure);
        assert_eq!(parsed.attributes().same_site, Some(SameSite::Strict));
        assert_eq!(parsed.attributes().path.map(|v| v.as_str()), Some("/"));
        assert_eq!(parsed.attributes().max_age, Some(3600));
        assert_eq!(parsed.attributes().domain, None);
        // Re-render is byte-equal (deadbeef is octet-clean).
        assert_eq!(parsed.to_set_cookie(), wire);
    }

    #[test]
    fn parse_decodes_value_like_the_request_reader() {
        assert_eq!(SetCookie::parse("pref=caf%C3%A9").unwrap().value(), "café");
        assert_eq!(SetCookie::parse(r#"pref="a b""#).unwrap().value(), "a b");
    }

    #[test]
    fn parse_attributes_are_case_insensitive() {
        let p =
            SetCookie::parse("n=v; SECURE; httponly; samesite=lax; PATH=/x; max-age=60").unwrap();
        assert!(p.attributes().secure && p.attributes().http_only);
        assert_eq!(p.attributes().same_site, Some(SameSite::Lax));
        assert_eq!(p.attributes().path.map(|v| v.as_str()), Some("/x"));
        assert_eq!(p.attributes().max_age, Some(60));
    }

    #[test]
    fn parse_strict_rejects_unknown_default_ignores() {
        // Strict (opt-in): an unrecognised attribute (`Priority`) rejects it.
        assert!(SetCookie::parse_strict("SID=x; Priority=High; Max-Age=60").is_none());
        // Default (RFC §5.2): the unknown attribute is ignored and the cookie survives.
        let p = SetCookie::parse("SID=x; Priority=High; Max-Age=60").unwrap();
        assert_eq!(p.value(), "x");
        assert_eq!(p.attributes().max_age, Some(60));
    }

    #[test]
    fn parse_reads_expires_as_a_date() {
        use time::macros::datetime;
        // `Expires` is a known attribute, parsed into an `OffsetDateTime` (lenient
        // RFC 6265 §5.1.1 here); the cookie and a coexisting `Max-Age` are kept.
        let p =
            SetCookie::parse("SID=x; Expires=Wed, 09 Jun 2021 10:18:14 GMT; Max-Age=60").unwrap();
        assert_eq!(p.value(), "x");
        assert_eq!(
            p.attributes().expires,
            Some(datetime!(2021-06-09 10:18:14 UTC))
        );
        assert_eq!(p.attributes().max_age, Some(60));
        // An unparseable date is dropped like any malformed known attribute; the
        // cookie survives.
        let bad = SetCookie::parse("SID=x; Expires=not-a-date").unwrap();
        assert_eq!(bad.attributes().expires, None);
        assert_eq!(bad.value(), "x");
    }

    #[test]
    fn parse_strict_tolerates_empty_and_trailing_semicolons() {
        // A stray or trailing `;` is not an "unknown attribute" — strict keeps it.
        assert_eq!(SetCookie::parse("SID=x;").unwrap().value(), "x");
        let p = SetCookie::parse("SID=x; ; Secure").unwrap();
        assert_eq!(p.value(), "x");
        assert!(p.attributes().secure);
    }

    #[test]
    fn parse_skips_malformed_attributes_but_keeps_the_cookie() {
        let p = SetCookie::parse("SID=x; Max-Age=banana; SameSite=Bogus; HttpOnly").unwrap();
        assert!(p.attributes().http_only);
        assert_eq!(p.attributes().max_age, None); // non-numeric dropped
        assert_eq!(p.attributes().same_site, None); // unrecognised SameSite dropped
        assert_eq!(p.value(), "x"); // cookie survives
    }

    #[test]
    fn parse_max_age_u64_and_negative() {
        assert_eq!(
            SetCookie::parse("n=v; Max-Age=18446744073709551615")
                .unwrap()
                .attributes()
                .max_age,
            Some(u64::MAX)
        );
        assert_eq!(
            SetCookie::parse("n=v; Max-Age=-1")
                .unwrap()
                .attributes()
                .max_age,
            None
        );
    }

    #[test]
    fn parse_rejects_no_equals_and_bad_name() {
        assert!(SetCookie::parse("HttpOnly").is_none()); // no name=value pair
        assert!(SetCookie::parse("na me=v; Secure").is_none()); // non-token name
        assert!(SetCookie::parse("").is_none());
        assert!(SetCookie::parse("=v").is_none()); // empty name
    }

    #[test]
    fn parse_splits_first_semicolon_then_first_equals() {
        let p = SetCookie::parse("a=b=c; Path=/x").unwrap();
        assert_eq!(p.name(), "a");
        assert_eq!(p.value(), "b=c"); // only the first '=' splits name/value
        assert_eq!(p.attributes().path.map(|v| v.as_str()), Some("/x"));
    }

    // ---- the reporting readers ---------------------------------------------

    #[test]
    fn try_parse_agrees_with_parse_and_renders_identically() {
        // The identity pin: try_parse's Ok/Err exactly mirrors parse's Some/None,
        // and the parsed cookie is the same cookie — over shapes covering clean,
        // droppy, duplicate, unknown, and fatal inputs.
        for header in [
            "SID=x; HttpOnly; Secure; Path=/; Max-Age=60",
            "SID=x; Max-Age=banana; SameSite=Bogus; HttpOnly",
            "n=v; Priority=High; Partitioned",
            "n=v; Path=/a; Path=/b",
            "n=v; Secure=1",
            "n=v; Expires=not-a-date",
            "HttpOnly",
            "na me=v; Secure",
            "",
            "=v",
        ] {
            let plain = SetCookie::parse(header);
            let reported = SetCookie::try_parse(header);
            assert_eq!(
                plain.is_some(),
                reported.is_ok(),
                "lenient fatality on {header:?}"
            );
            if let (Some(plain), Ok(reported)) = (plain, reported) {
                assert_eq!(plain, reported.value, "lenient cookie on {header:?}");
                assert_eq!(
                    plain.to_set_cookie(),
                    reported.value.to_set_cookie(),
                    "lenient rendering on {header:?}"
                );
            }
            let plain = SetCookie::parse_strict(header);
            let reported = SetCookie::try_parse_strict(header);
            assert_eq!(
                plain.is_some(),
                reported.is_ok(),
                "strict fatality on {header:?}"
            );
            if let (Some(plain), Ok(reported)) = (plain, reported) {
                assert_eq!(plain, reported.value, "strict cookie on {header:?}");
            }
        }
    }

    #[test]
    fn mistyped_or_fused_attribute_is_reported_not_silent() {
        // The safety case that motivated the report: a misspelled HttpOnly.
        let reported = SetCookie::try_parse("SID=x; Secure; HttpOnlyy").unwrap();
        assert!(reported.value.attributes().secure);
        assert!(!reported.value.attributes().http_only); // still dropped (§5.2)…
        assert_eq!(
            reported.issues,
            vec![SetCookieIssue::UnknownAttribute { name: "HttpOnlyy" }] // …but visible
        );
        // A forgotten `;` fusing two flags: both vanish from the parsed cookie,
        // one UnknownAttribute names the fused token.
        let reported = SetCookie::try_parse("SID=x; Secure HttpOnly").unwrap();
        assert!(!reported.value.attributes().secure);
        assert!(!reported.value.attributes().http_only);
        assert_eq!(
            reported.issues,
            vec![SetCookieIssue::UnknownAttribute {
                name: "Secure HttpOnly"
            }]
        );
        // Strict turns the unknown name into the fatal issue.
        assert_eq!(
            SetCookie::try_parse_strict("SID=x; HttpOnlyy"),
            Err(SetCookieIssue::UnknownAttribute { name: "HttpOnlyy" })
        );
    }

    #[test]
    fn malformed_known_values_are_reported_in_both_modes() {
        for (header, attribute, value) in [
            ("n=v; Max-Age=banana", KnownAttribute::MaxAge, "banana"),
            ("n=v; SameSite=Bogus", KnownAttribute::SameSite, "Bogus"),
            ("n=v; Expires=nonsense", KnownAttribute::Expires, "nonsense"),
            ("n=v; Path=a\u{1}b", KnownAttribute::Path, "a\u{1}b"),
        ] {
            let expected = vec![SetCookieIssue::InvalidAttributeValue { attribute, value }];
            let lenient = SetCookie::try_parse(header).unwrap();
            assert_eq!(lenient.issues, expected, "lenient {header:?}");
            // Strict keeps the cookie too — the drop is reported, not fatal —
            // so `!is_clean()` is the caller's stricter-than-strict gate.
            let strict = SetCookie::try_parse_strict(header).unwrap();
            assert_eq!(strict.issues, expected, "strict {header:?}");
            assert!(!strict.is_clean());
        }
        // Mode-relative dates: an RFC 850 date parses leniently but is an issue
        // under strict's IMF-fixdate-only reader.
        let rfc850 = "n=v; Expires=Sunday, 06-Nov-94 08:49:37 GMT";
        assert!(SetCookie::try_parse(rfc850).unwrap().is_clean());
        let strict = SetCookie::try_parse_strict(rfc850).unwrap();
        assert_eq!(
            strict.issues,
            vec![SetCookieIssue::InvalidAttributeValue {
                attribute: KnownAttribute::Expires,
                value: "Sunday, 06-Nov-94 08:49:37 GMT"
            }]
        );
    }

    #[test]
    fn duplicates_and_valued_flags_are_reported() {
        let reported = SetCookie::try_parse("n=v; Path=/a; Path=/b; Secure=1").unwrap();
        assert_eq!(
            reported.issues,
            vec![
                SetCookieIssue::DuplicateAttribute {
                    attribute: KnownAttribute::Path
                },
                SetCookieIssue::FlagWithValue {
                    attribute: KnownAttribute::Secure,
                    value: "1"
                },
            ],
            "issues arrive in wire order"
        );
        // Last-wins and flag-sets behave exactly as in plain parse.
        assert_eq!(
            reported.value.attributes().path.map(|p| p.as_str()),
            Some("/b")
        );
        assert!(reported.value.attributes().secure);
        // Strict: the duplicate is the fatal issue.
        assert_eq!(
            SetCookie::try_parse_strict("n=v; Path=/a; Path=/b"),
            Err(SetCookieIssue::DuplicateAttribute {
                attribute: KnownAttribute::Path
            })
        );
    }

    #[test]
    fn fatal_pair_issues_carry_the_pair_defect() {
        assert_eq!(
            SetCookie::try_parse("HttpOnly"),
            Err(SetCookieIssue::InvalidPair(PairIssue::MissingEquals {
                segment: b"HttpOnly"
            }))
        );
        assert_eq!(
            SetCookie::try_parse("na me=v; Secure"),
            Err(SetCookieIssue::InvalidPair(PairIssue::InvalidName {
                name: b"na me"
            }))
        );
        assert_eq!(
            SetCookie::try_parse("n=a\u{1}b; Secure"),
            Err(SetCookieIssue::InvalidPair(PairIssue::InvalidValue {
                name: "n",
                value: b"a\x01b"
            }))
        );
    }

    #[test]
    fn parse_keeps_earlier_valid_attribute_over_later_malformed() {
        // RFC 6265 §5.2.2: an unparseable cookie-av is ignored — it must not
        // erase an earlier valid occurrence of the same attribute.
        let p = SetCookie::parse("n=v; Max-Age=60; Max-Age=banana").unwrap();
        assert_eq!(p.attributes().max_age, Some(60));
        let p = SetCookie::parse("n=v; Domain=valid.example.com; Domain=café").unwrap();
        assert_eq!(
            p.attributes().domain.map(|d| d.as_str()),
            Some("valid.example.com")
        );
        // Among occurrences that PARSE, last-wins is unchanged.
        let p = SetCookie::parse("n=v; Max-Age=1; Max-Age=2").unwrap();
        assert_eq!(p.attributes().max_age, Some(2));
        // A malformed occurrence with no valid predecessor still leaves the
        // attribute unset.
        let p = SetCookie::parse("n=v; Max-Age=banana").unwrap();
        assert_eq!(p.attributes().max_age, None);
        // The report sees both the duplicate and the malformed value.
        let reported = SetCookie::try_parse("n=v; Max-Age=60; Max-Age=banana").unwrap();
        assert_eq!(
            reported.issues,
            vec![
                SetCookieIssue::DuplicateAttribute {
                    attribute: KnownAttribute::MaxAge
                },
                SetCookieIssue::InvalidAttributeValue {
                    attribute: KnownAttribute::MaxAge,
                    value: "banana"
                },
            ]
        );
        assert_eq!(reported.value.attributes().max_age, Some(60));
    }

    #[test]
    fn issue_display_never_echoes_wire_dangerous_bytes() {
        let issues = [
            SetCookieIssue::InvalidPair(PairIssue::InvalidValue {
                name: "n",
                value: b"a;b\r\n\x00",
            }),
            SetCookieIssue::UnknownAttribute {
                name: "Http\u{1}Only; evil",
            },
            SetCookieIssue::InvalidAttributeValue {
                attribute: KnownAttribute::Expires,
                value: "a\r\nSet-Cookie: evil=1",
            },
            SetCookieIssue::FlagWithValue {
                attribute: KnownAttribute::Secure,
                value: "x\u{0}y",
            },
        ];
        for issue in issues {
            let rendered = issue.to_string();
            for byte in [b'\r', b'\n', b'\0'] {
                assert!(
                    !rendered.bytes().any(|b| b == byte),
                    "{rendered:?} echoes {byte:#04x}"
                );
            }
        }
    }
}