pingap-plugin 0.16.1

Plugin for pingap
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
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
// Copyright 2024-2025 Tree xie.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{
    DryRun, Error, get_bool_conf, get_hash_key, get_int_conf, get_step_conf_in,
    get_str_conf,
};
use async_trait::async_trait;
use bytes::Bytes;
use http::header::RETRY_AFTER;
use http::{HeaderName, HeaderValue, StatusCode};
use humantime::parse_duration;
use pingap_config::{PluginCategory, PluginConf};
use pingap_core::{
    Ctx, HttpHeader, HttpResponse, Inflight, Plugin, PluginStep, Rate,
    RateLimitQuota, RequestPluginResult, ResponsePluginResult,
};
use pingap_core::{
    ensure_verified_client_ip, get_cookie_value, get_query_value,
    get_req_header_value,
};
use pingora::http::ResponseHeader;
use pingora::proxy::Session;
use std::borrow::Cow;
use std::time::Duration;
use tracing::debug;

type Result<T, E = Error> = std::result::Result<T, E>;

// LimitTag determines what value will be used as the rate limiting key
#[derive(PartialEq, Eq, Debug)]
pub enum LimitTag {
    Ip, // Use the client IP: through trusted proxies, else the peer's own
    RequestHeader, // Use value from a specified HTTP request header
    Cookie, // Use value from a specified cookie
    Query, // Use value from a specified URL query parameter
    /// The JA4 fingerprint of the TLS connection: every client with the
    /// same TLS stack shares one budget.
    Ja4,
    /// The client ip and the JA4 fingerprint together, the ip alone where
    /// there is no fingerprint: a script behind the address of an office
    /// does not use up the budget of the browsers behind it.
    IpJa4,
}

// Limiter implements rate limiting and concurrent request limiting
// It can be configured via TOML with settings like:
// ```toml
// type = "rate"          # or "inflight"
// tag = "cookie"         # or "header", "query", "ip"
// key = "session_id"     # name of header/cookie/query param to use
// max = 100             # maximum requests allowed
// interval = "60s"      # time window for rate limiting
// ```
/// A rate limiter or concurrent request limiter that can be configured to limit based on
/// different request attributes (IP, headers, cookies, query params)
pub struct Limiter {
    /// Determines what value will be used as the rate limiting key (IP, header, cookie, or query param)
    tag: LimitTag,

    /// Maximum number of requests allowed within any one interval (for rate
    /// limiting) or at the same time (for inflight limiting)
    max: f64,

    /// The name of the header/cookie/query parameter to use as the limiting key
    /// Only used when tag is not LimitTag::Ip
    key: String,

    /// Tracks concurrent requests using atomic counters.
    /// When a request completes, the counter automatically decrements via RAII guard.
    /// Only used when configured as an inflight limiter (type = "inflight")
    inflight: Option<Inflight>,

    /// Tracks request counts over a sliding time window.
    /// Automatically expires old requests based on configured interval.
    /// Only used when configured as a rate limiter (type = "rate")
    rate: Option<Rate>,

    /// When to apply the limiting logic:
    /// - PluginStep::Request: During initial request processing
    /// - PluginStep::ProxyUpstream: Before forwarding to upstream server
    plugin_step: PluginStep,

    /// Unique identifier for this limiter instance, used to distinguish between
    /// different limiters in the same application
    hash_value: String,

    /// `Retry-After` for a rate limiter's 429: the window length, the
    /// soonest the budget can have moved on.
    retry_after: Option<HttpHeader>,

    /// Whether the client is told its budget, in `X-RateLimit-Limit`,
    /// `X-RateLimit-Remaining` and `X-RateLimit-Reset`.
    headers: bool,

    /// The status of the response to a request over the limit, `429`
    /// unless set.
    status: StatusCode,

    /// Its body, in place of the one that names the count and the limit.
    message: Option<Bytes>,

    /// Whether a request without a value for the key is refused. It is let
    /// through, unlimited, unless `missing_key = "reject"`.
    reject_missing_key: bool,

    /// A request over the limit is let through and only logged.
    dry_run: DryRun,
}

/// What became of a request at the limiter.
enum Verdict {
    /// Let through, counted or - without a value for the key - not.
    Pass,
    /// Over the limit, by the count and the limit it was held to.
    Exceeded(f64),
    /// No value for the key, and the limiter was told to refuse that.
    MissingKey,
}

static X_RATELIMIT_LIMIT: HeaderName =
    HeaderName::from_static("x-ratelimit-limit");
static X_RATELIMIT_REMAINING: HeaderName =
    HeaderName::from_static("x-ratelimit-remaining");
static X_RATELIMIT_RESET: HeaderName =
    HeaderName::from_static("x-ratelimit-reset");

/// The three headers of `quota`, `X-RateLimit-Reset` left out where there
/// is no time to name.
fn quota_headers(quota: &RateLimitQuota) -> Vec<HttpHeader> {
    let mut headers = vec![
        (X_RATELIMIT_LIMIT.clone(), HeaderValue::from(quota.limit)),
        (
            X_RATELIMIT_REMAINING.clone(),
            HeaderValue::from(quota.remaining),
        ),
    ];
    if let Some(reset) = quota.reset {
        headers.push((X_RATELIMIT_RESET.clone(), HeaderValue::from(reset)));
    }
    headers
}

/// In how many seconds a client's budget is back in full if it sends
/// nothing more, from the two windows it is counted in: what is in the
/// current one fades over the whole of the next, what is left of the one
/// before is gone when the current one ends.
///
/// `fraction` is how much of the current window has passed.
fn seconds_to_reset(
    interval: Duration,
    prev_samples: isize,
    curr_samples: isize,
    fraction: f64,
) -> u64 {
    let left = 1.0 - fraction;
    let windows = if curr_samples > 0 {
        left + 1.0
    } else if prev_samples > 0 {
        left
    } else {
        return 0;
    };
    (interval.as_secs_f64() * windows).ceil().max(1.0) as u64
}

/// Converts a plugin configuration into a Limiter instance
///
/// # Arguments
/// * `value` - Plugin configuration containing limiter settings
///
/// # Returns
/// * `Result<Self>` - New Limiter instance or error if configuration is invalid
///
/// # Configuration Options
/// * `type` - "rate" or "inflight"
/// * `tag` - "ip", "cookie", "header", or "query"
/// * `key` - Name of header/cookie/query parameter to use
/// * `max` - Maximum allowed requests/connections
/// * `interval` - Time window for rate limiting (e.g. "60s")
impl TryFrom<&PluginConf> for Limiter {
    type Error = Error;
    fn try_from(value: &PluginConf) -> Result<Self> {
        let hash_value = get_hash_key(value);
        let category = PluginCategory::Limit.to_string();
        let invalid = |message: String| Error::Invalid {
            category: category.clone(),
            message,
        };
        // Limiting only makes sense before the upstream is involved.
        let step = get_step_conf_in(
            value,
            &category,
            PluginStep::Request,
            &[PluginStep::Request, PluginStep::ProxyUpstream],
        )?;

        // Every setting here decides who gets limited, so a value that is
        // not one of the documented ones is an error rather than a silent
        // fallback: a misspelt `tag` used to limit by ip, a misspelt `type`
        // rate-limited, and a forgotten `max` rejected almost everything.
        let tag = match get_str_conf(value, "tag").as_str() {
            "" | "ip" => LimitTag::Ip,
            "cookie" => LimitTag::Cookie,
            "header" => LimitTag::RequestHeader,
            "query" => LimitTag::Query,
            "ja4" => LimitTag::Ja4,
            "ip_ja4" => LimitTag::IpJa4,
            other => {
                return Err(invalid(format!(
                    "Invalid tag({other}), expect ip, header, cookie, query, ja4 or ip_ja4"
                )));
            },
        };
        let key = get_str_conf(value, "key");
        let named = matches!(
            tag,
            LimitTag::RequestHeader | LimitTag::Cookie | LimitTag::Query
        );
        if named && key.is_empty() {
            return Err(invalid(
                "key is required for a header, cookie or query tag".to_string(),
            ));
        }
        let is_inflight = match get_str_conf(value, "type").as_str() {
            "" | "rate" => false,
            "inflight" => true,
            other => {
                return Err(invalid(format!(
                    "Invalid type({other}), expect rate or inflight"
                )));
            },
        };
        if !value.contains_key("max") {
            return Err(invalid("max is required".to_string()));
        }
        let max = get_int_conf(value, "max");
        if max < 0 {
            return Err(invalid("max must not be negative".to_string()));
        }

        // Parse time interval for rate limiting
        // Format examples: "10s", "1m", "2h"
        // Default: 10 seconds if not specified
        let interval = get_str_conf(value, "interval");
        let interval = if !interval.is_empty() {
            parse_duration(&interval).map_err(|e| invalid(e.to_string()))?
        } else {
            Duration::from_secs(10)
        };
        // The counter keeps its windows in milliseconds, and divides by
        // their length: one shorter than that is a division by zero on
        // the first request.
        if interval < Duration::from_millis(1) {
            return Err(invalid("interval must be at least 1ms".to_string()));
        }

        // Create either inflight or rate limiter based on config
        let mut inflight = None;
        let mut rate = None;
        let mut retry_after = None;
        let max = max as f64;
        if is_inflight {
            // Inflight limiter uses atomic counters to track concurrent requests
            inflight = Some(Inflight::new());
        } else {
            // Rate limiter uses time-bucketed counters
            rate = Some(Rate::new(interval));
            retry_after = Some((
                RETRY_AFTER,
                HeaderValue::from(interval.as_secs().max(1)),
            ));
        }

        // What a refused client is answered with. A status that is not an
        // error would tell it the request went through.
        let status = if value.contains_key("status") {
            u16::try_from(get_int_conf(value, "status"))
                .ok()
                .filter(|status| (400..600).contains(status))
                .and_then(|status| StatusCode::from_u16(status).ok())
                .ok_or_else(|| {
                    invalid("status must be between 400 and 599".to_string())
                })?
        } else {
            StatusCode::TOO_MANY_REQUESTS
        };
        let message = get_str_conf(value, "message");
        let message = (!message.is_empty()).then(|| Bytes::from(message));
        let reject_missing_key =
            match get_str_conf(value, "missing_key").as_str() {
                "" | "pass" => false,
                "reject" => true,
                other => {
                    return Err(invalid(format!(
                        "Invalid missing_key({other}), expect pass or reject"
                    )));
                },
            };

        Ok(Self {
            hash_value,
            tag,
            key,
            max,
            inflight,
            rate,
            plugin_step: step,
            retry_after,
            headers: get_bool_conf(value, "headers"),
            status,
            message,
            reject_missing_key,
            dry_run: DryRun::new(value),
        })
    }
}

/// What the configuration of a limit has that the limit does not read,
/// for the check of a configuration to say once, where building the plugin
/// said it at every reload and every save of the admin.
pub(crate) fn unread_keys(value: &PluginConf) -> Vec<String> {
    let mut found = vec![];
    // Left over from a header tag, say, in a form that keeps what it was
    // given: the limit goes by the tag. A tag that is none of them is an
    // error of its own, said when the plugin is built.
    let tag = get_str_conf(value, "tag");
    if matches!(tag.as_str(), "" | "ip" | "ja4" | "ip_ja4")
        && !get_str_conf(value, "key").is_empty()
    {
        let tag = if tag.is_empty() { "ip" } else { &tag };
        found.push(format!(
            "key is only read with a header, cookie or query tag, not with tag {tag}"
        ));
    }
    // `weight` blended the previous window into the estimate by a fixed
    // share. It has no part in the sliding window that replaced that, and
    // a config that still has it is told so instead of refused.
    if value.contains_key("weight") {
        found.push(
            "weight is no longer used: max is the number of requests in any one interval"
                .to_string(),
        );
    }
    found
}

impl Limiter {
    /// What the key is, for the client that did not send it.
    fn key_description(&self) -> String {
        match self.tag {
            LimitTag::Ip | LimitTag::IpJa4 => "the client address".to_string(),
            LimitTag::Ja4 => {
                "a TLS connection with a JA4 fingerprint".to_string()
            },
            LimitTag::RequestHeader => format!("the header {}", self.key),
            LimitTag::Cookie => format!("the cookie {}", self.key),
            LimitTag::Query => format!("the query parameter {}", self.key),
        }
    }
    /// Creates a new Limiter instance from plugin configuration
    ///
    /// # Arguments
    /// * `params` - Plugin configuration containing limiter settings like type, tag, key, max, etc.
    ///
    /// # Returns
    /// * `Result<Self>` - New Limiter instance or error if configuration is invalid
    ///
    /// # Example Configuration
    /// ```toml
    /// type = "rate"          # or "inflight"
    /// tag = "cookie"         # or "header", "query", "ip"
    /// key = "session_id"     # name of header/cookie/query param to use
    /// max = 100             # maximum requests allowed
    /// interval = "60s"      # time window for rate limiting
    /// ```
    pub fn new(params: &PluginConf) -> Result<Self> {
        debug!(
            params = pingap_config::masked_toml(params),
            "new limit plugin"
        );
        Self::try_from(params)
    }
    /// The error of a request that took the count to `value`.
    fn exceeded(&self, value: f64) -> Error {
        Error::Exceed {
            category: PluginCategory::Limit.to_string(),
            max: self.max,
            value,
        }
    }

    /// Counts the request, and fails when that takes it over the limit.
    #[cfg(test)]
    fn incr(&self, session: &Session, ctx: &mut Ctx) -> Result<()> {
        match self.check(session, ctx) {
            Verdict::Exceeded(value) => Err(self.exceeded(value)),
            _ => Ok(()),
        }
    }

    /// Notes what is left of this limit for the response headers, unless
    /// another limit of the request has less left.
    ///
    /// The limit that refuses the request is the one the refusal is about:
    /// its budget is what is reported, whatever another limit noted before
    /// it, and nothing at all when it is not one that reports.
    ///
    /// In a dry run a refusal is not made, and the headers are not told of
    /// it either: the client sees what it would see without this limit.
    fn note_quota(&self, ctx: &mut Ctx, value: f64, reset: Option<u64>) {
        let refused = value > self.max;
        if refused && self.dry_run.is_on() {
            return;
        }
        if !self.headers {
            if refused {
                ctx.state.rate_limit = None;
            }
            return;
        }
        let quota = RateLimitQuota {
            limit: self.max as u64,
            remaining: (self.max - value).max(0.0) as u64,
            reset,
        };
        if refused
            || ctx
                .state
                .rate_limit
                .is_none_or(|noted| quota.remaining < noted.remaining)
        {
            ctx.state.rate_limit = Some(quota);
        }
    }

    /// The value the request is counted by, empty where it has none.
    /// Borrowed where possible: `Rate` and `Inflight` only need `Hash`.
    fn key_of<'a>(
        &self,
        session: &'a Session,
        ctx: &'a mut Ctx,
    ) -> Cow<'a, str> {
        match self.tag {
            LimitTag::Query => Cow::Borrowed(
                get_query_value(session.req_header(), &self.key)
                    .unwrap_or_default(),
            ),
            LimitTag::RequestHeader => Cow::Borrowed(
                get_req_header_value(session.req_header(), &self.key)
                    .unwrap_or_default(),
            ),
            LimitTag::Cookie => Cow::Borrowed(
                get_cookie_value(session.req_header(), &self.key)
                    .unwrap_or_default(),
            ),
            // Plain http, or a server without `ja4 = true`: no value.
            LimitTag::Ja4 => Cow::Borrowed(
                ctx.conn
                    .ja4
                    .as_ref()
                    .map(|ja4| ja4.ja4())
                    .unwrap_or_default(),
            ),
            LimitTag::IpJa4 => {
                let ja4 = ctx.conn.ja4.clone();
                let ip = ensure_verified_client_ip(session, ctx);
                match ja4 {
                    Some(ja4) if !ip.is_empty() => {
                        Cow::Owned(format!("{ip} {}", ja4.ja4()))
                    },
                    _ => Cow::Borrowed(ip),
                }
            },
            // An address the client cannot choose: its own behind
            // trusted proxies, the peer's without them. By whatever
            // `X-Forwarded-For` said, a new value with every request was a
            // new client every time and nothing was ever limited.
            _ => Cow::Borrowed(ensure_verified_client_ip(session, ctx)),
        }
    }

    /// Counts the request against its key and says what became of it.
    fn check(&self, session: &Session, ctx: &mut Ctx) -> Verdict {
        let key = self.key_of(session, ctx);

        // No value for the key (a missing header or cookie): unlimited,
        // unless told to refuse it.
        if key.is_empty() {
            return if self.reject_missing_key {
                Verdict::MissingKey
            } else {
                Verdict::Pass
            };
        }

        // Track request based on limiter type.
        // Pass `&Cow` (Sized) rather than `&str` — pingora-limits requires `T: Hash + Sized`.
        let mut reset = None;
        let value = if let Some(rate) = &self.rate {
            // For rate limiting:
            rate.observe(&key, 1); // Record this request
            // The requests of the last `interval`, this one included: all
            // of the current window, and of the previous one the share
            // that still lies within an interval from now. It used to be
            // half of each, as a rate per second, so a client new to the
            // limiter - nothing in its previous window - got twice `max`
            // before it was stopped.
            let max = self.max;
            let (value, seconds) = rate.rate_with(&key, |info| {
                let value = info.prev_samples.max(0) as f64
                    * (1.0 - info.current_interval_fraction)
                    + info.curr_samples.max(0) as f64;
                // By what stays counted: a request that is refused is
                // taken off again below.
                let counted = if value > max {
                    info.curr_samples - 1
                } else {
                    info.curr_samples
                };
                let seconds = seconds_to_reset(
                    info.interval,
                    info.prev_samples,
                    counted,
                    info.current_interval_fraction,
                );
                (value, seconds)
            });
            reset = Some(seconds);
            // A request that is turned away is taken off again, so what is
            // counted is what was let through: a client over its limit
            // goes on getting `max` per interval and not, for as long as
            // it keeps asking, nothing at all. It is counted first and
            // checked after so that requests arriving together see each
            // other.
            if value > self.max {
                rate.observe(&key, -1);
            }
            value
        } else if let Some(inflight) = &self.inflight {
            // For inflight limiting:
            // Increment counter
            // Store guard in context - when guard is dropped, counter auto-decrements
            // Added to the others, never in place of one: a second inflight
            // limit on the location used to drop the guard of the first,
            // which released its count at once and so never limited.
            let (guard, value) = inflight.incr(&key, 1);
            ctx.state.guards.push(guard);
            value as f64
        } else {
            0.0
        };

        self.note_quota(ctx, value, reset);
        if value > self.max {
            return Verdict::Exceeded(value);
        }
        Verdict::Pass
    }
}

#[async_trait]
impl Plugin for Limiter {
    /// Returns unique identifier for this limiter instance
    #[inline]
    fn config_key(&self) -> Cow<'_, str> {
        Cow::Borrowed(&self.hash_value)
    }

    /// Handles incoming HTTP requests by applying configured limits
    ///
    /// # Arguments
    /// * `step` - Current plugin execution step
    /// * `session` - Mutable HTTP session
    /// * `ctx` - Mutable state context
    ///
    /// # Returns
    /// * `pingora::Result<Option<HttpResponse>>` - None to continue processing,
    ///   Some(response) with 429 status if limit exceeded
    ///
    /// # Effects
    /// * Increments and checks appropriate limit counter
    /// * Returns 429 Too Many Requests if limit exceeded
    #[inline]
    async fn handle_request(
        &self,
        step: PluginStep,
        session: &mut Session,
        ctx: &mut Ctx,
    ) -> pingora::Result<RequestPluginResult> {
        // Only run at configured plugin step
        if step != self.plugin_step {
            return Ok(RequestPluginResult::Skipped);
        }

        let verdict = self.check(session, ctx);
        // In a dry run the request goes on, and holding its place among
        // those in flight would count it where a refused one is gone:
        // what is logged would no longer be what would be refused.
        if self.dry_run.is_on()
            && self.inflight.is_some()
            && matches!(verdict, Verdict::Exceeded(_))
        {
            ctx.state.guards.pop();
        }
        let response = match verdict {
            Verdict::Pass => return Ok(RequestPluginResult::Continue),
            // Over the limit: 429 Too Many Requests, unless set otherwise.
            Verdict::Exceeded(value) => {
                let mut headers: Vec<HttpHeader> =
                    self.retry_after.iter().cloned().collect();
                // The response of this plugin is not shown to its own
                // `handle_response`: the budget goes on it here.
                if self.headers
                    && let Some(quota) = &ctx.state.rate_limit
                {
                    headers.extend(quota_headers(quota));
                }
                let body = self
                    .message
                    .clone()
                    .unwrap_or_else(|| self.exceeded(value).to_string().into());
                HttpResponse {
                    status: self.status,
                    headers: (!headers.is_empty()).then_some(headers),
                    body,
                    ..Default::default()
                }
            },
            // Not a request too many: one that does not say who it is from.
            Verdict::MissingKey => HttpResponse {
                status: StatusCode::BAD_REQUEST,
                body: format!(
                    "Plugin limit, {} is required",
                    self.key_description()
                )
                .into(),
                ..Default::default()
            },
        };
        // What the request was counted by, for the log of a dry run.
        let session: &Session = session;
        Ok(self.dry_run.refuse("limit", session, ctx, response, |ctx| {
            self.key_of(session, ctx).into_owned()
        }))
    }

    /// Tells the client its budget on the response of the upstream.
    #[inline]
    async fn handle_response(
        &self,
        _session: &mut Session,
        ctx: &mut Ctx,
        upstream_response: &mut ResponseHeader,
    ) -> pingora::Result<ResponsePluginResult> {
        let Some(quota) = ctx.state.rate_limit.filter(|_| self.headers) else {
            return Ok(ResponsePluginResult::Unchanged);
        };
        for (name, value) in quota_headers(&quota) {
            let _ = upstream_response.insert_header(name, value);
        }
        Ok(ResponsePluginResult::Modified)
    }

    /// And on the response another plugin answered with, a `401` after
    /// this limiter counted the request for one.
    #[inline]
    fn handles_plugin_response(&self) -> bool {
        self.headers
    }
}

register_plugin!("limit", Limiter);

#[cfg(test)]
mod tests {
    use super::*;
    use http::StatusCode;
    use pingap_config::PluginConf;
    use pingap_core::{Ctx, PluginStep};
    use pingora::proxy::Session;
    use pretty_assertions::assert_eq;
    use std::time::Duration;
    use tokio_test::io::Builder;

    /// The context of a request from `peer`. No trusted proxies are
    /// configured in a unit test, so the peer's address is the client ip.
    fn from_peer(peer: &str) -> Ctx {
        let mut ctx = Ctx::default();
        ctx.conn.remote_addr = Some(peer.to_string());
        ctx
    }

    async fn new_session() -> Session {
        let headers = [
            "Host: github.com",
            "Referer: https://github.com/",
            "User-Agent: pingap/0.1.1",
            "Cookie: deviceId=abc",
            "Accept: application/json",
            "X-Uuid: 138q71",
            "X-Forwarded-For: 1.1.1.1, 192.168.1.2",
        ]
        .join("\r\n");
        let input_header =
            format!("GET /vicanso/pingap?key=1 HTTP/1.1\r\n{headers}\r\n\r\n");
        let mock_io = Builder::new().read(input_header.as_bytes()).build();
        let mut session = Session::new_h1(Box::new(mock_io));
        session.read_request().await.unwrap();
        session
    }

    #[test]
    fn test_limit_params() {
        let params = Limiter::try_from(
            &toml::from_str::<PluginConf>(
                r###"
type = "inflight"
tag = "cookie"
key = "deviceId"
max = 10
"###,
            )
            .unwrap(),
        )
        .unwrap();
        assert_eq!("request", params.plugin_step.to_string());
        assert_eq!(true, params.inflight.is_some());
        assert_eq!(LimitTag::Cookie, params.tag);
        assert_eq!("deviceId", params.key);

        let result = Limiter::try_from(
            &toml::from_str::<PluginConf>(
                r###"
step = "response"
type = "inflight"
tag = "cookie"
key = "deviceId"
max = 10
"###,
            )
            .unwrap(),
        );
        assert_eq!(
            "Plugin limit invalid, message: Invalid step(response), expect one of: request, proxy_upstream",
            result.err().unwrap().to_string()
        );

        // Settings that decide who is limited are checked, not defaulted.
        for (conf, expect) in [
            (
                "tag = \"cookies\"\nkey = \"a\"\nmax = 1",
                "Invalid tag(cookies)",
            ),
            ("tag = \"header\"\nmax = 1", "key is required"),
            ("type = \"inflght\"\nmax = 1", "Invalid type(inflght)"),
            ("type = \"rate\"", "max is required"),
            ("max = -1", "max must not be negative"),
            (
                "max = 1\ninterval = \"0s\"",
                "interval must be at least 1ms",
            ),
            // Regression: shorter than the counter's unit, which divided
            // by it and brought the process down on the first request.
            (
                "max = 1\ninterval = \"500us\"",
                "interval must be at least 1ms",
            ),
        ] {
            let err =
                Limiter::try_from(&toml::from_str::<PluginConf>(conf).unwrap())
                    .err()
                    .unwrap()
                    .to_string();
            assert_eq!(true, err.contains(expect), "{conf}: {err}");
        }

        // A rate limiter tells the client when to come back.
        let params = Limiter::try_from(
            &toml::from_str::<PluginConf>("max = 10\ninterval = \"30s\"")
                .unwrap(),
        )
        .unwrap();
        assert_eq!(
            Some("30"),
            params
                .retry_after
                .as_ref()
                .and_then(|(_, value)| value.to_str().ok())
        );
        let params = Limiter::try_from(
            &toml::from_str::<PluginConf>("type = \"inflight\"\nmax = 10")
                .unwrap(),
        )
        .unwrap();
        assert_eq!(true, params.retry_after.is_none());
    }

    #[tokio::test]
    async fn test_new_cookie_limiter() {
        let limiter = Limiter::new(
            &toml::from_str::<PluginConf>(
                r###"
type = "inflight"
tag = "cookie"
key = "deviceId"
max = 10
    "###,
            )
            .unwrap(),
        )
        .unwrap();

        assert_eq!(LimitTag::Cookie, limiter.tag);
        let mut ctx = Ctx {
            ..Default::default()
        };
        let session = new_session().await;

        limiter.incr(&session, &mut ctx).unwrap();
        assert_eq!(1, ctx.state.guards.len());
    }
    #[tokio::test]
    async fn test_new_req_header_limiter() {
        let limiter = Limiter::new(
            &toml::from_str::<PluginConf>(
                r###"
type = "inflight"
tag = "header"
key = "X-Uuid"
max = 10
    "###,
            )
            .unwrap(),
        )
        .unwrap();
        assert_eq!(LimitTag::RequestHeader, limiter.tag);
        let mut ctx = Ctx {
            ..Default::default()
        };
        let session = new_session().await;

        limiter.incr(&session, &mut ctx).unwrap();
        assert_eq!(1, ctx.state.guards.len());
    }
    #[tokio::test]
    async fn test_new_query_limiter() {
        let limiter = Limiter::new(
            &toml::from_str::<PluginConf>(
                r###"
type = "inflight"
tag = "query"
key = "key"
max = 10
    "###,
            )
            .unwrap(),
        )
        .unwrap();
        assert_eq!(LimitTag::Query, limiter.tag);
        let mut ctx = Ctx {
            ..Default::default()
        };
        let session = new_session().await;

        limiter.incr(&session, &mut ctx).unwrap();
        assert_eq!(1, ctx.state.guards.len());
    }
    #[tokio::test]
    async fn test_new_ip_limiter() {
        let limiter = Limiter::new(
            &toml::from_str::<PluginConf>(
                r###"
type = "inflight"
max = 10
"###,
            )
            .unwrap(),
        )
        .unwrap();
        assert_eq!(LimitTag::Ip, limiter.tag);
        let mut ctx = from_peer("1.1.1.1");
        let session = new_session().await;

        limiter.incr(&session, &mut ctx).unwrap();
        assert_eq!(1, ctx.state.guards.len());
    }
    #[tokio::test]
    async fn test_inflight_limit() {
        let limiter = Limiter::new(
            &toml::from_str::<PluginConf>(
                r###"
type = "inflight"
max = 0
"###,
            )
            .unwrap(),
        )
        .unwrap();

        let headers = ["X-Forwarded-For: 1.1.1.1"].join("\r\n");
        let input_header =
            format!("GET /vicanso/pingap?size=1 HTTP/1.1\r\n{headers}\r\n\r\n");
        let mock_io = Builder::new().read(input_header.as_bytes()).build();
        let mut session = Session::new_h1(Box::new(mock_io));
        session.read_request().await.unwrap();
        let result = limiter
            .handle_request(
                PluginStep::Request,
                &mut session,
                &mut from_peer("1.1.1.1"),
            )
            .await
            .unwrap();

        let RequestPluginResult::Respond(resp) = result else {
            panic!("result is not Respond");
        };
        assert_eq!(StatusCode::TOO_MANY_REQUESTS, resp.status);

        let limiter = Limiter::new(
            &toml::from_str::<PluginConf>(
                r###"
type = "inflight"
max = 1
"###,
            )
            .unwrap(),
        )
        .unwrap();
        let result = limiter
            .handle_request(
                PluginStep::Request,
                &mut session,
                &mut from_peer("1.1.1.1"),
            )
            .await
            .unwrap();

        assert_eq!(true, result == RequestPluginResult::Continue);
    }

    /// Regression: a request had room for one inflight guard. A second
    /// inflight limit on the location took the place of the first one's
    /// guard, which released that limiter's count while the request was
    /// still running: the first limit never limited anything.
    #[tokio::test]
    async fn test_two_inflight_limits_on_one_request() {
        let new_limiter = |tag: &str, key: &str| {
            Limiter::new(
                &toml::from_str::<PluginConf>(&format!(
                    "type = \"inflight\"\ntag = \"{tag}\"\nkey = \"{key}\"\nmax = 1"
                ))
                .unwrap(),
            )
            .unwrap()
        };
        let by_app = new_limiter("header", "X-App");
        let by_user = new_limiter("header", "X-User");
        let new_session = async || {
            let mock_io = Builder::new()
                .read(b"GET / HTTP/1.1\r\nX-App: a\r\nX-User: u\r\n\r\n")
                .build();
            let mut session = Session::new_h1(Box::new(mock_io));
            session.read_request().await.unwrap();
            session
        };

        // The first request passes both limits and holds both counts.
        let mut session = new_session().await;
        let mut first = Ctx::default();
        for limiter in [&by_app, &by_user] {
            let result = limiter
                .handle_request(PluginStep::Request, &mut session, &mut first)
                .await
                .unwrap();
            assert_eq!(true, result == RequestPluginResult::Continue);
        }
        assert_eq!(2, first.state.guards.len());

        // While it is running, a second one is over the first limit already.
        let mut session = new_session().await;
        let mut second = Ctx::default();
        let result = by_app
            .handle_request(PluginStep::Request, &mut session, &mut second)
            .await
            .unwrap();
        let RequestPluginResult::Respond(resp) = result else {
            panic!("the first limit must still be counting the first request");
        };
        assert_eq!(StatusCode::TOO_MANY_REQUESTS, resp.status);
        drop(second);

        // When the first request ends, both counts are released.
        drop(first);
        let mut session = new_session().await;
        let mut third = Ctx::default();
        for limiter in [&by_app, &by_user] {
            let result = limiter
                .handle_request(PluginStep::Request, &mut session, &mut third)
                .await
                .unwrap();
            assert_eq!(true, result == RequestPluginResult::Continue);
        }
    }

    #[tokio::test]
    async fn test_rate_limit() {
        let limiter = Limiter::new(
            &toml::from_str::<PluginConf>(
                r###"
type = "rate"
max = 1
interval = "1s"
"###,
            )
            .unwrap(),
        )
        .unwrap();

        let headers = ["X-Forwarded-For: 1.1.1.1"].join("\r\n");
        let input_header =
            format!("GET /vicanso/pingap?size=1 HTTP/1.1\r\n{headers}\r\n\r\n");
        let mock_io = Builder::new().read(input_header.as_bytes()).build();
        let mut session = Session::new_h1(Box::new(mock_io));
        session.read_request().await.unwrap();
        let result = limiter
            .handle_request(
                PluginStep::Request,
                &mut session,
                &mut from_peer("1.1.1.1"),
            )
            .await
            .unwrap();

        assert_eq!(true, result == RequestPluginResult::Continue);

        let _ = limiter
            .handle_request(
                PluginStep::Request,
                &mut session,
                &mut from_peer("1.1.1.1"),
            )
            .await
            .unwrap();

        // wait for the next loop
        tokio::time::sleep(Duration::from_secs(1)).await;
        let result = limiter
            .handle_request(
                PluginStep::Request,
                &mut session,
                &mut from_peer("1.1.1.1"),
            )
            .await
            .unwrap();
        let RequestPluginResult::Respond(resp) = result else {
            panic!("result is not Respond");
        };
        assert_eq!(StatusCode::TOO_MANY_REQUESTS, resp.status);
        assert_eq!(
            Some("1"),
            resp.headers
                .as_ref()
                .and_then(|headers| headers.first())
                .and_then(|(_, value)| value.to_str().ok())
        );

        // wait for rate limiter to reset
        tokio::time::sleep(Duration::from_secs(1)).await;
        let result = limiter
            .handle_request(
                PluginStep::Request,
                &mut session,
                &mut from_peer("1.1.1.1"),
            )
            .await
            .unwrap();
        assert_eq!(true, result == RequestPluginResult::Continue);
    }

    /// How many of `total` requests in a row a limiter lets through.
    async fn admitted(
        limiter: &Limiter,
        total: usize,
        peer: &str,
        headers: impl Fn(usize) -> String,
    ) -> usize {
        let mut count = 0;
        for index in 0..total {
            let input = format!(
                "GET /vicanso/pingap HTTP/1.1\r\n{}\r\n",
                headers(index)
            );
            let mock_io = Builder::new().read(input.as_bytes()).build();
            let mut session = Session::new_h1(Box::new(mock_io));
            session.read_request().await.unwrap();
            let result = limiter
                .handle_request(
                    PluginStep::Request,
                    &mut session,
                    &mut from_peer(peer),
                )
                .await
                .unwrap();
            if result == RequestPluginResult::Continue {
                count += 1;
            }
        }
        count
    }

    fn new_rate_limiter(conf: &str) -> Limiter {
        Limiter::new(
            &toml::from_str::<PluginConf>(&format!("type = \"rate\"\n{conf}"))
                .unwrap(),
        )
        .unwrap()
    }

    /// Regression: `max` is the number of requests in an interval. The
    /// estimate took half of the current window and half of the previous
    /// one, so a client with nothing in its previous window got through
    /// twice as often before it was stopped - and with `weight = 0`,
    /// which looked at the previous window alone, every time.
    #[tokio::test]
    async fn test_rate_limit_admits_max_per_interval() {
        let no_headers = |_: usize| String::new();
        let limiter = new_rate_limiter("max = 5\ninterval = \"1m\"");
        assert_eq!(5, admitted(&limiter, 30, "1.1.1.1", no_headers).await);
        // Another client has its own count.
        assert_eq!(5, admitted(&limiter, 30, "1.1.1.2", no_headers).await);
        // What was turned away is not counted: the first client is at its
        // limit, not beyond it.
        let count = limiter
            .rate
            .as_ref()
            .unwrap()
            .rate_with(&Cow::Borrowed("1.1.1.1"), |info| {
                info.curr_samples + info.prev_samples
            });
        assert_eq!(5, count);

        // `weight` is accepted and changes nothing.
        for weight in [0, 50, 100] {
            let limiter = new_rate_limiter(&format!(
                "max = 5\ninterval = \"1m\"\nweight = {weight}"
            ));
            assert_eq!(
                5,
                admitted(&limiter, 30, "1.1.1.1", no_headers).await,
                "{weight}"
            );
        }

        // An interval shorter than a second is counted like any other;
        // `max` used to be taken per second there and the estimate per
        // interval.
        let limiter = new_rate_limiter("max = 3\ninterval = \"500ms\"");
        assert_eq!(3, admitted(&limiter, 10, "1.1.1.1", no_headers).await);
    }

    /// One request from `peer` through the limiter: whether it went on, or
    /// the response it was answered with, and what the upstream's response
    /// came back with from `handle_response`.
    async fn one_request(
        limiter: &Limiter,
        peer: &str,
        headers: &str,
    ) -> (Option<HttpResponse>, Vec<(String, String)>) {
        let input = format!("GET /vicanso/pingap HTTP/1.1\r\n{headers}\r\n");
        let mock_io = Builder::new().read(input.as_bytes()).build();
        let mut session = Session::new_h1(Box::new(mock_io));
        session.read_request().await.unwrap();
        let mut ctx = from_peer(peer);
        let result = limiter
            .handle_request(PluginStep::Request, &mut session, &mut ctx)
            .await
            .unwrap();
        let mut upstream_response = ResponseHeader::build(200, None).unwrap();
        limiter
            .handle_response(&mut session, &mut ctx, &mut upstream_response)
            .await
            .unwrap();
        let quota = upstream_response
            .headers
            .iter()
            .map(|(name, value)| {
                (name.to_string(), value.to_str().unwrap().to_string())
            })
            .collect();
        match result {
            RequestPluginResult::Respond(resp) => (Some(resp), quota),
            _ => (None, quota),
        }
    }

    fn header_of(resp: &HttpResponse, name: &str) -> Option<String> {
        resp.headers.iter().flatten().find_map(|(key, value)| {
            (key.as_str() == name).then(|| value.to_str().unwrap().to_string())
        })
    }

    /// `headers = true`: the client is told its budget, on what the
    /// upstream answers and on the refusal alike.
    #[tokio::test]
    async fn test_rate_limit_headers() {
        let limiter =
            new_rate_limiter("max = 3\ninterval = \"1m\"\nheaders = true");
        assert_eq!(true, limiter.handles_plugin_response());
        for remaining in ["2", "1", "0"] {
            let (resp, quota) = one_request(&limiter, "1.1.1.1", "").await;
            assert_eq!(true, resp.is_none());
            assert_eq!(3, quota.len(), "{quota:?}");
            assert_eq!(
                ("x-ratelimit-limit".to_string(), "3".to_string()),
                quota[0]
            );
            assert_eq!(
                ("x-ratelimit-remaining".to_string(), remaining.to_string()),
                quota[1]
            );
            // All of it is back once the window in progress and the next
            // have passed: between one minute and two from now.
            assert_eq!("x-ratelimit-reset", quota[2].0);
            let reset: u64 = quota[2].1.parse().unwrap();
            assert_eq!(true, (60..=120).contains(&reset), "{reset}");
        }
        // The fourth is refused, and says the same of the budget.
        let (resp, _) = one_request(&limiter, "1.1.1.1", "").await;
        let resp = resp.unwrap();
        assert_eq!(StatusCode::TOO_MANY_REQUESTS, resp.status);
        assert_eq!(Some("60".to_string()), header_of(&resp, "retry-after"));
        assert_eq!(
            Some("3".to_string()),
            header_of(&resp, "x-ratelimit-limit")
        );
        assert_eq!(
            Some("0".to_string()),
            header_of(&resp, "x-ratelimit-remaining")
        );
        assert_eq!(true, header_of(&resp, "x-ratelimit-reset").is_some());
        // Another client has all of its own.
        let (_, quota) = one_request(&limiter, "1.1.1.2", "").await;
        assert_eq!("2", quota[1].1);

        // Not asked for: nothing is added, anywhere.
        let silent = new_rate_limiter("max = 1\ninterval = \"1m\"");
        assert_eq!(false, silent.handles_plugin_response());
        let (resp, quota) = one_request(&silent, "1.1.1.1", "").await;
        assert_eq!((true, 0), (resp.is_none(), quota.len()));
        let (resp, _) = one_request(&silent, "1.1.1.1", "").await;
        assert_eq!(None, header_of(&resp.unwrap(), "x-ratelimit-limit"));

        // A limit on concurrent requests has no time to name.
        let inflight = Limiter::new(
            &toml::from_str::<PluginConf>(
                "type = \"inflight\"\nmax = 5\nheaders = true",
            )
            .unwrap(),
        )
        .unwrap();
        let (_, quota) = one_request(&inflight, "1.1.1.1", "").await;
        assert_eq!(
            vec![
                ("x-ratelimit-limit".to_string(), "5".to_string()),
                ("x-ratelimit-remaining".to_string(), "4".to_string()),
            ],
            quota
        );
    }

    /// Of two limits that report, the one with less left is what the
    /// client is told.
    #[tokio::test]
    async fn test_the_tightest_limit_is_reported() {
        let wide =
            new_rate_limiter("max = 100\ninterval = \"1m\"\nheaders = true");
        let narrow =
            new_rate_limiter("max = 2\ninterval = \"1m\"\nheaders = true");
        for limiters in [[&wide, &narrow], [&narrow, &wide]] {
            let mock_io =
                Builder::new().read(b"GET / HTTP/1.1\r\n\r\n").build();
            let mut session = Session::new_h1(Box::new(mock_io));
            session.read_request().await.unwrap();
            let mut ctx = from_peer("2.2.2.2");
            for limiter in limiters {
                limiter
                    .handle_request(PluginStep::Request, &mut session, &mut ctx)
                    .await
                    .unwrap();
            }
            assert_eq!(Some(2), ctx.state.rate_limit.map(|quota| quota.limit));
        }

        // The limit that refuses is the one the refusal is about: its
        // budget is reported, also where another has no more left ...
        let through = async |limiters: &[&Limiter], peer: &str| {
            let mock_io =
                Builder::new().read(b"GET / HTTP/1.1\r\n\r\n").build();
            let mut session = Session::new_h1(Box::new(mock_io));
            session.read_request().await.unwrap();
            let mut ctx = from_peer(peer);
            let mut refused = false;
            for limiter in limiters {
                let result = limiter
                    .handle_request(PluginStep::Request, &mut session, &mut ctx)
                    .await
                    .unwrap();
                if matches!(result, RequestPluginResult::Respond(_)) {
                    refused = true;
                    break;
                }
            }
            (refused, ctx.state.rate_limit.map(|quota| quota.limit))
        };
        let two =
            new_rate_limiter("max = 2\ninterval = \"1m\"\nheaders = true");
        let one =
            new_rate_limiter("max = 1\ninterval = \"1m\"\nheaders = true");
        assert_eq!((false, Some(1)), through(&[&two, &one], "3.3.3.3").await);
        // `two` is at 0 left after this one, and so is `one`, which refuses.
        assert_eq!((true, Some(1)), through(&[&two, &one], "3.3.3.3").await);

        // ... and nothing is, where the one that refuses does not report:
        // the budget another noted is not that of this refusal.
        let quiet = new_rate_limiter("max = 1\ninterval = \"1m\"");
        assert_eq!(
            (false, Some(100)),
            through(&[&wide, &quiet], "4.4.4.4").await
        );
        assert_eq!((true, None), through(&[&wide, &quiet], "4.4.4.4").await);
    }

    #[test]
    fn test_seconds_to_reset() {
        let minute = Duration::from_secs(60);
        // Nothing counted: nothing to wait for.
        assert_eq!(0, seconds_to_reset(minute, 0, 0, 0.5));
        // Only the window before: gone when the current one ends.
        assert_eq!(30, seconds_to_reset(minute, 4, 0, 0.5));
        // The current window fades over the whole of the next.
        assert_eq!(90, seconds_to_reset(minute, 0, 1, 0.5));
        assert_eq!(120, seconds_to_reset(minute, 3, 1, 0.0));
        // Never less than a second while something is counted.
        assert_eq!(1, seconds_to_reset(Duration::from_millis(100), 1, 1, 0.99));
    }

    /// `status` and `message` are what a refused client gets, and
    /// `missing_key = "reject"` refuses the request that names no key.
    #[tokio::test]
    async fn test_limit_rejection_is_configurable() {
        let limiter = new_rate_limiter(
            "max = 1\ninterval = \"1m\"\nstatus = 503\nmessage = \"slow down\"",
        );
        assert_eq!(
            true,
            one_request(&limiter, "1.1.1.1", "").await.0.is_none()
        );
        let resp = one_request(&limiter, "1.1.1.1", "").await.0.unwrap();
        assert_eq!(StatusCode::SERVICE_UNAVAILABLE, resp.status);
        assert_eq!("slow down", String::from_utf8_lossy(&resp.body));
        // Without them: 429 and the count.
        let limiter = new_rate_limiter("max = 1\ninterval = \"1m\"");
        one_request(&limiter, "1.1.1.1", "").await;
        let resp = one_request(&limiter, "1.1.1.1", "").await.0.unwrap();
        assert_eq!(StatusCode::TOO_MANY_REQUESTS, resp.status);
        assert_eq!(
            "Plugin limit, exceed limit 2/1",
            String::from_utf8_lossy(&resp.body)
        );

        // A request without the key: let through and not counted, unless
        // told to refuse it.
        let by_key =
            "max = 1\ninterval = \"1m\"\ntag = \"header\"\nkey = \"X-Api-Key\"";
        let lenient = new_rate_limiter(by_key);
        for _ in 0..3 {
            let (resp, _) = one_request(&lenient, "1.1.1.1", "").await;
            assert_eq!(true, resp.is_none());
        }
        let strict =
            new_rate_limiter(&format!("{by_key}\nmissing_key = \"reject\""));
        let resp = one_request(&strict, "1.1.1.1", "").await.0.unwrap();
        assert_eq!(StatusCode::BAD_REQUEST, resp.status);
        assert_eq!(
            "Plugin limit, the header X-Api-Key is required",
            String::from_utf8_lossy(&resp.body)
        );
        // With it, it is limited as before.
        let with_key = "X-Api-Key: abc\r\n";
        assert_eq!(
            true,
            one_request(&strict, "1.1.1.1", with_key).await.0.is_none()
        );
        let resp = one_request(&strict, "1.1.1.1", with_key).await.0.unwrap();
        assert_eq!(StatusCode::TOO_MANY_REQUESTS, resp.status);

        // Values that are not ones.
        let invalid = |conf: &str| {
            Limiter::new(
                &toml::from_str::<PluginConf>(&format!("max = 1\n{conf}"))
                    .unwrap(),
            )
            .err()
            .unwrap()
            .to_string()
        };
        for status in [200, 302, 399, 600, -1, 70000] {
            assert_eq!(
                "Plugin limit invalid, message: status must be between 400 and 599",
                invalid(&format!("status = {status}")),
            );
        }
        assert_eq!(
            "Plugin limit invalid, message: Invalid missing_key(deny), expect pass or reject",
            invalid("missing_key = \"deny\"")
        );
    }

    /// Regression: the client ip was whatever `X-Forwarded-For` said when
    /// no trusted proxies are configured. A new value with every request
    /// was a new client every time, and nothing was limited.
    #[tokio::test]
    async fn test_limit_by_ip_ignores_a_forged_address() {
        let limiter = new_rate_limiter("max = 5\ninterval = \"1m\"");
        let forged =
            |index: usize| format!("X-Forwarded-For: 9.9.9.{index}\r\n");
        assert_eq!(5, admitted(&limiter, 30, "1.1.1.1", forged).await);
        let forged = |index: usize| format!("X-Real-IP: 9.9.8.{index}\r\n");
        assert_eq!(0, admitted(&limiter, 30, "1.1.1.1", forged).await);
    }

    /// `ctx` on a connection whose ClientHello was `hello`.
    fn with_ja4(mut ctx: Ctx, hello: Vec<u8>) -> Ctx {
        ctx.conn.ja4 = pingap_core::Ja4Fingerprint::from_client_hello(&hello)
            .map(std::sync::Arc::new);
        ctx
    }

    /// The hello of the JA4 specification's example, a browser.
    fn browser() -> Vec<u8> {
        pingap_core::ja4::testing::spec_example_body()
    }

    /// A hello with nothing in it, another TLS stack.
    fn script() -> Vec<u8> {
        pingap_core::ja4::testing::client_hello_body(0x9999, &[], Some(&[]))
    }

    #[test]
    fn test_unread_keys() {
        let unread = |conf: &str| {
            unread_keys(&toml::from_str::<PluginConf>(conf).unwrap())
        };
        assert_eq!(Vec::<String>::new(), unread("max = 1"));
        assert_eq!(
            Vec::<String>::new(),
            unread("tag = \"header\"\nkey = \"X-User\"\nmax = 1")
        );
        assert_eq!(
            vec![
                "key is only read with a header, cookie or query tag, not with tag ip"
                    .to_string()
            ],
            unread("key = \"X-User\"\nmax = 1")
        );
        // a misspelt tag is the error of the plugin, not this
        assert_eq!(
            Vec::<String>::new(),
            unread("tag = \"Header\"\nkey = \"X-User\"\nmax = 1")
        );
        assert_eq!(
            vec![
                "key is only read with a header, cookie or query tag, not with tag ja4".to_string(),
                "weight is no longer used: max is the number of requests in any one interval".to_string(),
            ],
            unread("tag = \"ja4\"\nkey = \"X-User\"\nweight = 50\nmax = 1")
        );
    }

    /// `tag = "ja4"`: one budget for every client with the same TLS
    /// stack, whatever its address.
    #[tokio::test]
    async fn test_limit_by_ja4() {
        let limiter =
            new_rate_limiter("tag = \"ja4\"\nmax = 1\ninterval = \"1m\"");
        assert_eq!(LimitTag::Ja4, limiter.tag);
        let session = new_session().await;
        let mut first = with_ja4(from_peer("1.1.1.1"), browser());
        assert_eq!(true, limiter.incr(&session, &mut first).is_ok());
        let mut second = with_ja4(from_peer("2.2.2.2"), browser());
        assert_eq!(true, limiter.incr(&session, &mut second).is_err());
        // another stack has a budget of its own
        let mut other = with_ja4(from_peer("2.2.2.2"), script());
        assert_eq!(true, limiter.incr(&session, &mut other).is_ok());
        // plain http, or a server without `ja4`: nothing to count by
        for _ in 0..3 {
            let mut plain = from_peer("1.1.1.1");
            assert_eq!(true, limiter.incr(&session, &mut plain).is_ok());
        }

        // unless told to turn that away
        let strict = new_rate_limiter(
            "tag = \"ja4\"\nmax = 1\nmissing_key = \"reject\"",
        );
        let mut session = new_session().await;
        let RequestPluginResult::Respond(resp) = strict
            .handle_request(
                PluginStep::Request,
                &mut session,
                &mut from_peer("1.1.1.1"),
            )
            .await
            .unwrap()
        else {
            panic!("a request without a fingerprint is turned away");
        };
        assert_eq!(StatusCode::BAD_REQUEST, resp.status);
        assert_eq!(
            Bytes::from_static(
                b"Plugin limit, a TLS connection with a JA4 fingerprint is required"
            ),
            resp.body
        );
    }

    /// `tag = "ip_ja4"`: the address and the fingerprint together, the
    /// address alone where there is no fingerprint.
    #[tokio::test]
    async fn test_limit_by_ip_and_ja4() {
        let limiter =
            new_rate_limiter("tag = \"ip_ja4\"\nmax = 1\ninterval = \"1m\"");
        assert_eq!(LimitTag::IpJa4, limiter.tag);
        let session = new_session().await;
        // one address, two TLS stacks: two budgets
        let mut browser_one = with_ja4(from_peer("1.1.1.1"), browser());
        assert_eq!(true, limiter.incr(&session, &mut browser_one).is_ok());
        let mut script_one = with_ja4(from_peer("1.1.1.1"), script());
        assert_eq!(true, limiter.incr(&session, &mut script_one).is_ok());
        let mut script_two = with_ja4(from_peer("1.1.1.1"), script());
        assert_eq!(true, limiter.incr(&session, &mut script_two).is_err());
        // the same stack at another address is another client
        let mut elsewhere = with_ja4(from_peer("2.2.2.2"), script());
        assert_eq!(true, limiter.incr(&session, &mut elsewhere).is_ok());
        // no fingerprint: counted by the address
        let mut plain = from_peer("3.3.3.3");
        assert_eq!(true, limiter.incr(&session, &mut plain).is_ok());
        let mut plain = from_peer("3.3.3.3");
        assert_eq!(true, limiter.incr(&session, &mut plain).is_err());
    }

    /// In a dry run a request over the limit goes on, and what is counted
    /// is what would have been let through.
    #[tokio::test]
    async fn test_limit_dry_run() {
        let limiter = new_rate_limiter(
            "max = 1\ninterval = \"1m\"\nmessage = \"slow down\"\ndry_run = true",
        );
        assert_eq!(true, limiter.dry_run.is_on());
        // every one of them goes on, where one would without the dry run
        let no_headers = |_: usize| String::new();
        assert_eq!(5, admitted(&limiter, 5, "1.1.1.1", no_headers).await);
        // the refused ones were taken off again: the count is at the limit,
        // and the next request takes it one over, not five
        let session = new_session().await;
        assert_eq!(
            "Plugin limit, exceed limit 2/1",
            limiter
                .incr(&session, &mut from_peer("1.1.1.1"))
                .err()
                .unwrap()
                .to_string()
        );

        // An inflight limit does not keep the place of a request it would
        // have refused: refused, it would be gone already.
        let limiter = Limiter::new(
            &toml::from_str::<PluginConf>(
                "type = \"inflight\"\nmax = 1\ndry_run = true",
            )
            .unwrap(),
        )
        .unwrap();
        let mut ctx = from_peer("1.1.1.1");
        let mut session = new_session().await;
        let result = limiter
            .handle_request(PluginStep::Request, &mut session, &mut ctx)
            .await
            .unwrap();
        assert_eq!(RequestPluginResult::Continue, result);
        assert_eq!(1, ctx.state.guards.len());
        let mut over = from_peer("1.1.1.1");
        let result = limiter
            .handle_request(PluginStep::Request, &mut session, &mut over)
            .await
            .unwrap();
        assert_eq!(RequestPluginResult::Continue, result);
        assert_eq!(0, over.state.guards.len());
        // so the next one is counted as the second in flight, not the third
        let mut next = from_peer("1.1.1.1");
        assert_eq!(
            "Plugin limit, exceed limit 2/1",
            limiter.incr(&session, &mut next).err().unwrap().to_string()
        );
    }

    /// A refusal a dry run does not make is not shown to the client in
    /// the quota headers, nor does it take away those of another limit.
    #[tokio::test]
    async fn test_dry_run_leaves_the_quota_headers_alone() {
        let enforced =
            new_rate_limiter("max = 5\ninterval = \"1m\"\nheaders = true");
        let watched =
            new_rate_limiter("max = 1\ninterval = \"1m\"\ndry_run = true");
        let reporting = new_rate_limiter(
            "max = 1\ninterval = \"1m\"\nheaders = true\ndry_run = true",
        );
        let session = new_session().await;
        // the watched limits use up their one request
        let mut first = from_peer("2.2.2.2");
        let _ = watched.check(&session, &mut first);
        let _ = reporting.check(&session, &mut first);

        // and are over it with the next, which the enforced limit reports
        let mut ctx = from_peer("2.2.2.2");
        enforced.incr(&session, &mut ctx).unwrap();
        let noted = ctx.state.rate_limit;
        assert_eq!(Some(4), noted.map(|quota| quota.remaining));
        assert_eq!(
            true,
            matches!(watched.check(&session, &mut ctx), Verdict::Exceeded(_))
        );
        assert_eq!(
            true,
            matches!(reporting.check(&session, &mut ctx), Verdict::Exceeded(_))
        );
        assert_eq!(noted, ctx.state.rate_limit);
    }
}