atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
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
//! Server-wide state and configuration.
//!
//! Everything in [`ServerContext`] is either immutable for the life of the
//! process or a registry keyed by something the client supplies on each
//! request. Nothing here is *session* state: the 2026-07-28 revision forbids a
//! server from inferring context from earlier requests on the same connection,
//! and an open stdio process is explicitly not a conversation.
//!
//! The blob cache is the one thing that looks like it might violate that. It
//! does not: its key is a content address derived entirely from the request's
//! own parameters, it changes no observable result, and deleting it changes
//! only latency.

use std::sync::Arc;

use atproto_identity::egress::{Allowlist, PublicResolver};
use atproto_identity::resolve::InnerIdentityResolver;
use reqwest::dns::Resolve;
use serde_json::Value;
use tokio::sync::{Semaphore, mpsc};

use crate::cache::BlobCache;
use crate::errors::ConfigError;
use crate::proto::cancel;
use crate::proto::subs;
use crate::proto::writer::Outgoing;

/// Default ceiling on one inbound message, in bytes.
///
/// Generous because `upload_blob` accepts `data_base64`: a 16 MiB blob arrives
/// as roughly 21.8 MB of base64 on a single line. The payload ceiling applies
/// in both directions once blobs exist.
pub const DEFAULT_MAX_MESSAGE_BYTES: usize = 33_554_432;

/// Default number of request handlers doing work at once.
pub const DEFAULT_MAX_CONCURRENT_REQUESTS: usize = 16;

/// Default ceiling on requests accepted but not yet answered.
pub const DEFAULT_MAX_QUEUED_REQUESTS: usize = 1024;

/// Default ceiling on a blob sent to a PDS, in bytes.
///
/// Matches the PDS default for `uploadBlob`.
pub const DEFAULT_BLOB_MAX_UPLOAD_BYTES: u64 = 16_777_216;

/// Default ceiling on a blob fetched from a repository, in bytes.
///
/// The same figure, but a separate knob: an operator lowering what this
/// process will pull from a peer is making a different decision from one
/// lowering what it will send. They shared a field, set by a variable named
/// `..._DOWNLOAD_BYTES`, so bounding uploads was something an operator got by
/// accident and could not do on purpose.
pub const DEFAULT_BLOB_MAX_DOWNLOAD_BYTES: u64 = 16_777_216;

/// Default ceiling on a blob returned to the model as base64, in bytes.
///
/// `resources/read` has one delivery mechanism: base64 inside a JSON-RPC
/// response. A 16 MiB blob is ~21.8 MB of base64, which at three to four
/// characters per token is hundreds of thousands of tokens if the host treats
/// it as text. This is a design constraint, not a tuning knob, and the default
/// is deliberately far below the transfer ceiling.
pub const DEFAULT_BLOB_MAX_INLINE_BYTES: u64 = 262_144;

/// Default ceiling on the on-disk blob cache, in bytes.
pub const DEFAULT_BLOB_CACHE_MAX_BYTES: u64 = 536_870_912;

/// Operational ceilings, all overridable by environment variable.
#[derive(Debug, Clone, Copy)]
pub struct Limits {
    /// Largest inbound message accepted, in bytes.
    pub max_message_bytes: usize,
    /// Handlers permitted to do work concurrently.
    pub max_concurrent_requests: usize,
    /// Requests accepted but unanswered before new ones are refused.
    pub max_queued_requests: usize,
    /// Largest blob this process will send to a PDS, in bytes.
    pub blob_max_upload_bytes: u64,
    /// Largest blob this process will fetch from a repository, in bytes.
    pub blob_max_download_bytes: u64,
    /// Largest blob returned to the model as base64, in bytes.
    pub blob_max_inline_bytes: u64,
    /// Whether a caller-named host may skip the service-endpoint policy.
    ///
    /// Off by default. The `endpoint` and `plc_directory_hostname` arguments
    /// name a host that this process will then connect to, and the caller is a
    /// model, so an unchecked one is an SSRF primitive reachable from a prompt
    /// -- which is what `blob.rs` says about the endpoints it takes from a DID
    /// document, where it applies the policy.
    ///
    /// The policy refuses plain HTTP, address literals, single-label hosts,
    /// embedded credentials and non-default ports. That also refuses
    /// `http://127.0.0.1:4800`, which is where this workspace's own `pds`
    /// listens by default, so development against a local server needs this.
    /// It is deliberately an environment variable and not a tool argument: an
    /// operator can widen the policy, a prompt cannot.
    pub allow_insecure_endpoints: bool,
    /// Whether a link card's image keeps its EXIF (`ATPMCP_PRESERVE_EXIF`).
    ///
    /// Off by default: `generate_bsky_post` removes the metadata from every
    /// thumbnail it uploads, because uploading a third party's image to the
    /// caller's PDS republishes whatever it carries, a photo's location
    /// included. On, an image at or under the thumbnail limit is uploaded as
    /// served, and a shrunk one gets its source's EXIF copied in. Like the
    /// waiver, an operator's choice and not a tool argument.
    pub preserve_exif: bool,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_message_bytes: DEFAULT_MAX_MESSAGE_BYTES,
            max_concurrent_requests: DEFAULT_MAX_CONCURRENT_REQUESTS,
            max_queued_requests: DEFAULT_MAX_QUEUED_REQUESTS,
            blob_max_upload_bytes: DEFAULT_BLOB_MAX_UPLOAD_BYTES,
            blob_max_download_bytes: DEFAULT_BLOB_MAX_DOWNLOAD_BYTES,
            blob_max_inline_bytes: DEFAULT_BLOB_MAX_INLINE_BYTES,
            allow_insecure_endpoints: false,
            preserve_exif: false,
        }
    }
}

impl Limits {
    /// Read the limits from the environment, falling back to the defaults for
    /// any variable that is unset or empty.
    ///
    /// # Errors
    ///
    /// A [`ConfigError`] for a value the server cannot use: a number that is
    /// not written as digits alone, one below its minimum, or a waiver that is
    /// neither on nor off. The server refuses to start on any of them rather
    /// than run with a default the operator did not choose.
    pub fn from_env() -> Result<Self, ConfigError> {
        Self::from_lookup(env_value)
    }

    /// [`Self::from_env`], with the variables read through `lookup`.
    ///
    /// The seam exists for tests: this workspace forbids `unsafe_code`, and
    /// under edition 2024 setting an environment variable is `unsafe`.
    ///
    /// # Errors
    ///
    /// As [`Self::from_env`].
    pub fn from_lookup(lookup: impl Fn(&str) -> Option<String>) -> Result<Self, ConfigError> {
        let mut limits = Self::default();
        let number = |name: &'static str, minimum: u64, default: u64| {
            parse_number(name, lookup(name).as_deref(), minimum, default)
        };

        if let Some(value) = number(
            "ATPMCP_MAX_MESSAGE_BYTES",
            1024,
            DEFAULT_MAX_MESSAGE_BYTES as u64,
        )? {
            limits.max_message_bytes = usize::try_from(value).unwrap_or(usize::MAX);
        }
        if let Some(value) = number(
            "ATPMCP_MAX_CONCURRENT_REQUESTS",
            1,
            DEFAULT_MAX_CONCURRENT_REQUESTS as u64,
        )? {
            limits.max_concurrent_requests = usize::try_from(value).unwrap_or(usize::MAX);
        }
        if let Some(value) = number(
            "ATPMCP_MAX_QUEUED_REQUESTS",
            1,
            DEFAULT_MAX_QUEUED_REQUESTS as u64,
        )? {
            limits.max_queued_requests = usize::try_from(value).unwrap_or(usize::MAX);
        }
        // One variable each. `ATPMCP_BLOB_MAX_DOWNLOAD_BYTES` used to set the
        // single shared field, so it bounded uploads too -- which its name does
        // not say and an operator could not have relied on.
        if let Some(value) = number(
            "ATPMCP_BLOB_MAX_UPLOAD_BYTES",
            1,
            DEFAULT_BLOB_MAX_UPLOAD_BYTES,
        )? {
            limits.blob_max_upload_bytes = value;
        }
        if let Some(value) = number(
            "ATPMCP_BLOB_MAX_DOWNLOAD_BYTES",
            1,
            DEFAULT_BLOB_MAX_DOWNLOAD_BYTES,
        )? {
            limits.blob_max_download_bytes = value;
        }
        // Zero is a real setting here, not a mistake: never return bytes inline.
        if let Some(value) = number(
            "ATPMCP_BLOB_MAX_INLINE_BYTES",
            0,
            DEFAULT_BLOB_MAX_INLINE_BYTES,
        )? {
            limits.blob_max_inline_bytes = value;
        }
        limits.allow_insecure_endpoints = parse_waiver(
            "ATPMCP_ALLOW_INSECURE_ENDPOINTS",
            lookup("ATPMCP_ALLOW_INSECURE_ENDPOINTS").as_deref(),
        )?;
        limits.preserve_exif = parse_waiver(
            "ATPMCP_PRESERVE_EXIF",
            lookup("ATPMCP_PRESERVE_EXIF").as_deref(),
        )?;

        Ok(limits)
    }
}

/// An environment variable's value, as [`Limits::from_lookup`] reads it.
///
/// A value that is not valid UTF-8 is passed on lossily rather than treated
/// as unset: it cannot parse as a number or a waiver either way, and refusing
/// it names it, where `std::env::var(..).ok()` would have dropped it quietly.
pub(crate) fn env_value(name: &str) -> Option<String> {
    match std::env::var(name) {
        Ok(value) => Some(value),
        Err(std::env::VarError::NotPresent) => None,
        Err(std::env::VarError::NotUnicode(raw)) => Some(raw.to_string_lossy().into_owned()),
    }
}

/// A numeric variable: `Ok(None)` when it is unset or empty, which keeps the
/// default; the value when it is digits alone and at least `minimum`.
///
/// Digits alone, because anything looser would be a guess about what the
/// operator meant. `16MiB`, `1M` and `1_048_576` are all refused, not read as
/// the prefix that happens to parse, and the error shows the accepted form.
/// Surrounding whitespace is trimmed, since an env file easily leaves some.
///
/// # Errors
///
/// [`ConfigError::NotANumber`] or [`ConfigError::BelowMinimum`].
pub(crate) fn parse_number(
    name: &'static str,
    raw: Option<&str>,
    minimum: u64,
    default: u64,
) -> Result<Option<u64>, ConfigError> {
    let Some(raw) = raw.map(str::trim).filter(|raw| !raw.is_empty()) else {
        return Ok(None);
    };
    if !raw.bytes().all(|byte| byte.is_ascii_digit()) {
        return Err(ConfigError::NotANumber {
            name,
            value: raw.to_string(),
            default,
        });
    }
    let value: u64 = raw.parse().map_err(|_| ConfigError::NotANumber {
        name,
        value: raw.to_string(),
        default,
    })?;
    if value < minimum {
        return Err(ConfigError::BelowMinimum {
            name,
            value,
            minimum,
        });
    }
    Ok(Some(value))
}

/// An on/off variable, such as the endpoint waiver or
/// `ATPMCP_PRESERVE_EXIF`: on for `1`, `true`, `yes` or `on`; off for `0`,
/// `false`, `no`, `off`, an empty value, or none at all. Case-insensitive.
///
/// Anything else is refused rather than read as off. Off is the safe reading,
/// so this is not about exposure; it is that `=y` or `=enabled` meant
/// something to whoever wrote it, and silently meaning the opposite is how an
/// operator ends up debugging a policy they believe they switched off.
///
/// # Errors
///
/// [`ConfigError::NotAWaiver`].
pub(crate) fn parse_waiver(name: &'static str, raw: Option<&str>) -> Result<bool, ConfigError> {
    let Some(raw) = raw else {
        return Ok(false);
    };
    match raw.trim().to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Ok(true),
        "" | "0" | "false" | "no" | "off" => Ok(false),
        _ => Err(ConfigError::NotAWaiver {
            name,
            value: raw.to_string(),
        }),
    }
}

/// The PLC directory a `did:plc` subject is resolved against when a call
/// names none of its own, and `PLC_HOSTNAME` is unset.
pub const DEFAULT_PLC_HOSTNAME: &str = atproto_identity::config::DEFAULT_PLC_HOSTNAME;

/// The PLC directory for this process: `PLC_HOSTNAME` read through `lookup`,
/// or [`DEFAULT_PLC_HOSTNAME`] when it is unset.
///
/// The value is checked by `atproto_identity::config::validate_plc_hostname`,
/// the check every binary in the workspace that reads the variable shares: a
/// host, a scheme only if it is a lowercase `http://` or `https://`, a `:`
/// after the host only for a port, and no query or fragment for the DID to be
/// appended to. It was used as given, so `PLC_HOSTNAME=""` became `https://`,
/// and the server started and then failed every `did:plc` resolution with a
/// request-URL error. Surrounding whitespace is trimmed.
///
/// An empty value is refused, not read as unset as a number's is. A number's
/// default is a limit; this default is another host, and a template that
/// expanded to nothing would quietly send every lookup to the public
/// directory.
///
/// Not the endpoint policy: the operator's directory is trusted, so
/// `http://localhost:2582` is accepted.
///
/// # Errors
///
/// [`ConfigError::NotAPlcDirectory`], atpmcp's own `config-4`, carrying the
/// shared check's reason.
pub(crate) fn plc_hostname(lookup: impl Fn(&str) -> Option<String>) -> Result<String, ConfigError> {
    const NAME: &str = "PLC_HOSTNAME";
    let Some(raw) = lookup(NAME) else {
        return Ok(DEFAULT_PLC_HOSTNAME.to_string());
    };
    atproto_identity::config::validate_plc_hostname(NAME, &raw).map_err(|error| {
        ConfigError::NotAPlcDirectory {
            name: NAME,
            value: raw.clone(),
            reason: match error {
                atproto_identity::errors::ConfigError::InvalidPlcHostname { reason, .. } => reason,
                // `#[non_exhaustive]`, and nothing else is returned today.
                other => other.to_string(),
            },
        }
    })
}

/// The nameservers `DNS_NAMESERVERS`, read through `lookup`, names: empty
/// when it is unset or empty, which means the system configuration.
///
/// Read so that the error a handle lookup gives without a readable system
/// configuration -- `error-atproto-identity-resolve-11`, which says to set
/// this -- names something this server honours. It was not read: the resolver
/// was always the system's, built with a constructor that panicked when that
/// configuration could not be read, so the server could not start at all in a
/// scratch container.
///
/// # Errors
///
/// [`ConfigError::NotANameserverList`], atpmcp's own `config-5`, naming the
/// entry that is not an address.
pub(crate) fn dns_nameservers(
    lookup: impl Fn(&str) -> Option<String>,
) -> Result<Vec<std::net::IpAddr>, ConfigError> {
    const NAME: &str = "DNS_NAMESERVERS";
    let raw = lookup(NAME).unwrap_or_default();
    let nameservers: atproto_identity::config::DnsNameservers =
        raw.clone()
            .try_into()
            .map_err(|error: anyhow::Error| ConfigError::NotANameserverList {
                name: NAME,
                value: raw.clone(),
                entry: match error.downcast_ref::<atproto_identity::errors::ConfigError>() {
                    Some(atproto_identity::errors::ConfigError::InvalidNameserverIP { value }) => {
                        value.clone()
                    }
                    _ => raw.clone(),
                },
                separator: atproto_identity::config::LIST_SEPARATOR,
            })?;
    Ok(nameservers.as_ref().clone())
}

/// Everything a handler needs, shared by every task.
pub struct ServerContext {
    /// Identity and handle resolution, and the HTTP client behind it.
    ///
    /// That client comes from [`identity_client`]: it follows redirects,
    /// because the handle specification allows them on
    /// `/.well-known/atproto-did`, but a few at most and each one checked
    /// against the endpoint policy.
    pub resolver: Arc<InnerIdentityResolver>,
    /// The client for every other JSON request: `invoke_xrpc`, `get_record`,
    /// the record fetch behind `get_lexicon` and `validate_xrpc`, and session
    /// refresh. From [`request_client`], so it follows **no redirects** and
    /// carries timeouts.
    pub request_client: reqwest::Client,
    /// The client used for blob transfers.
    ///
    /// Blob fetches go to a host named by a `serviceEndpoint` the DID's own
    /// subject publishes, so this client follows **no redirects**, like
    /// [`Self::request_client`]: a validated endpoint that answers
    /// `302 http://169.254.169.254/` would otherwise walk straight past the
    /// endpoint validation. It is separate because a blob can legitimately
    /// take far longer than a JSON document, so its total timeout is longer.
    pub blob_client: reqwest::Client,
    /// The client for web pages and their images: `generate_bsky_post`'s
    /// link card. From [`web_client`], so it follows a few redirects, each
    /// checked against the endpoint policy, as [`identity_client`] does.
    pub web_client: reqwest::Client,
    /// The content-addressed blob cache.
    pub cache: Arc<BlobCache>,
    /// Operational ceilings.
    pub limits: Limits,
    /// The one channel to stdout.
    pub out: mpsc::Sender<Outgoing>,
    /// Requests currently being handled.
    pub inflight: cancel::Registry,
    /// Open `subscriptions/listen` streams.
    pub subscriptions: subs::Registry,
    /// Concurrency budget for request handlers.
    pub permits: Arc<Semaphore>,
    /// This server's self-reported identity, stamped into every result.
    pub server_info: Value,
}

impl ServerContext {
    /// Assemble a context around an outbound channel.
    ///
    /// # Errors
    ///
    /// When the request client or the blob client cannot be built. See
    /// [`request_client`] for why that stops the server rather than falling
    /// back.
    pub fn new(
        resolver: Arc<InnerIdentityResolver>,
        cache: Arc<BlobCache>,
        limits: Limits,
        out: mpsc::Sender<Outgoing>,
    ) -> reqwest::Result<Self> {
        // The same inputs `main` builds the identity client's guard from, so
        // the four clients can't disagree about it.
        let guard =
            AddressGuard::for_config(limits.allow_insecure_endpoints, &resolver.plc_hostname);
        Ok(Self {
            request_client: request_client(&guard)?,
            blob_client: blob_client(&guard)?,
            web_client: web_client(&guard)?,
            resolver,
            cache,
            limits,
            out,
            inflight: cancel::Registry::new(),
            subscriptions: subs::Registry::new(),
            permits: Arc::new(Semaphore::new(limits.max_concurrent_requests)),
            server_info: serde_json::json!({
                "name": "atpmcp",
                "version": env!("CARGO_PKG_VERSION"),
            }),
        })
    }
}

/// Whether this process's HTTP clients check the addresses they connect to.
///
/// [`host_policy`](crate::host_policy) checks URLs, and only syntactically: a
/// public-looking name whose address record is `127.0.0.1`, `10.0.0.5` or
/// `169.254.169.254` passes it, and the request goes there. -04 §11.2 has
/// requests to internal-network, loopback and link-local addresses "rejected
/// unless explicitly permitted by configuration". With the guard on, every
/// client here looks names up through atproto-identity's
/// [`PublicResolver`], which drops every address that isn't public before the
/// connector sees it, so the address checked is the address dialled.
///
/// It is on unless the operator set `ATPMCP_ALLOW_INSECURE_ENDPOINTS`, and
/// the waiver lifts it for every client, an endpoint read from a DID document
/// included. That is a choice: the alternative was a second, always-guarded
/// client for DID-document endpoints, and atproto-pds and atproto-entryway
/// have one switch each. The URL rule that a DID document's endpoint is
/// always checked does not change; see [`host_policy`](crate::host_policy).
///
/// The operator's `PLC_HOSTNAME` is configuration, not a caller-named host,
/// so it is admitted whatever it resolves to. A `plc_directory_hostname`
/// argument is not. Proxies are honoured, as in atproto-pds's `PeerClient`:
/// behind one, the proxy resolves the target and this guard sees only the
/// proxy's own name.
#[derive(Clone)]
pub struct AddressGuard {
    guarded: bool,
    allowlist: Allowlist,
    lookup: Option<Arc<dyn Resolve>>,
}

impl std::fmt::Debug for AddressGuard {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AddressGuard")
            .field("guarded", &self.guarded)
            .field("allowlist", &self.allowlist)
            .field("lookup", &self.lookup.as_ref().map(|_| "custom"))
            .finish()
    }
}

impl AddressGuard {
    /// The guard for this configuration: on unless `waived`
    /// (`ATPMCP_ALLOW_INSECURE_ENDPOINTS`), admitting the host
    /// `plc_hostname` names. A bare hostname and a URL both work, as for
    /// `PLC_HOSTNAME` itself; an address literal adds nothing, since a literal
    /// is never looked up.
    #[must_use]
    pub fn for_config(waived: bool, plc_hostname: &str) -> Self {
        let mut allowlist = Allowlist::new();
        if let Some(host) =
            reqwest::Url::parse(&atproto_identity::plc::directory_base(plc_hostname))
                .ok()
                .and_then(|url| url.domain().map(str::to_string))
        {
            allowlist = allowlist.host(&host);
        }
        Self {
            guarded: !waived,
            allowlist,
            lookup: None,
        }
    }

    /// Whether the guard is on.
    #[must_use]
    pub fn is_guarded(&self) -> bool {
        self.guarded
    }

    /// Look names up with `lookup` instead of the system resolver, guarded or
    /// not. For tests, which point a public-looking name at a loopback
    /// listener.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn with_lookup(mut self, lookup: Arc<dyn Resolve>) -> Self {
        self.lookup = Some(lookup);
        self
    }

    /// Install the guard, or the plain lookup, on `builder`.
    fn apply(&self, builder: reqwest::ClientBuilder) -> reqwest::ClientBuilder {
        match (self.guarded, self.lookup.clone()) {
            (true, lookup) => {
                let resolver = match lookup {
                    Some(lookup) => PublicResolver::over(lookup),
                    None => PublicResolver::new(),
                };
                builder.dns_resolver(resolver.with_allowlist(self.allowlist.clone()))
            }
            (false, Some(lookup)) => builder.dns_resolver(lookup),
            (false, None) => builder,
        }
    }
}

/// How long any client here may take to open a connection.
const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// How long a JSON request may take from start to finish: an identity
/// document, an XRPC call, a lexicon record. Without it, a host that never
/// finishes its response holds a concurrency permit forever.
const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// Build the client identity resolution uses: handles, `did:web` and the PLC
/// directory.
///
/// It follows redirects, because the handle specification allows them on
/// `/.well-known/atproto-did`, under atproto-identity's
/// [`validated_policy`](atproto_identity::redirect::validated_policy): at most
/// [`MAX_REDIRECTS`](atproto_identity::redirect::MAX_REDIRECTS), each checked
/// against the endpoint policy and never waived. `atpdid` builds its client on
/// the same policy.
///
/// There is no fallback to a default client, here or for [`request_client`]
/// and [`blob_client`]. A default client follows ten redirects anywhere,
/// including `http://` and loopback, and has no timeout, which is the hole
/// these clients exist to close, so a build failure stops the server instead.
///
/// All four, with [`web_client`], carry `guard`; see [`AddressGuard`].
///
/// # Errors
///
/// When reqwest cannot build the client.
pub fn identity_client(guard: &AddressGuard) -> reqwest::Result<reqwest::Client> {
    guard
        .apply(reqwest::Client::builder())
        .connect_timeout(CONNECT_TIMEOUT)
        .timeout(REQUEST_TIMEOUT)
        .redirect(atproto_identity::redirect::validated_policy())
        .build()
}

/// Build the client for every JSON request that is not identity resolution.
///
/// It follows no redirects, under
/// [`host_policy::no_redirects`](crate::host_policy::no_redirects). The
/// endpoint policy checks the URL a request starts at, and a redirect would
/// otherwise take it, and on a 307 its body, to wherever the host said. As for
/// [`identity_client`], a build failure stops the server rather than falling
/// back to a client that follows anything.
///
/// # Errors
///
/// When reqwest cannot build the client.
pub fn request_client(guard: &AddressGuard) -> reqwest::Result<reqwest::Client> {
    guard
        .apply(reqwest::Client::builder())
        .connect_timeout(CONNECT_TIMEOUT)
        .timeout(REQUEST_TIMEOUT)
        .redirect(crate::host_policy::no_redirects())
        .build()
}

/// Build the hardened client used for blob transfers: [`CONNECT_TIMEOUT`],
/// two minutes for the whole transfer, and no redirects, so a `3xx` is an
/// answer the caller refuses rather than a hop to wherever the host said.
///
/// As for [`identity_client`], a build failure stops the server. This used
/// to fall back to `reqwest::Client::new()`, which follows ten redirects
/// anywhere and has no timeout, on the reasoning that a server that cannot
/// start is worse than one running with the defaults; for a client whose
/// endpoints a DID document or a model names, the defaults are the hole.
///
/// # Errors
///
/// When reqwest cannot build the client.
fn blob_client(guard: &AddressGuard) -> reqwest::Result<reqwest::Client> {
    guard
        .apply(reqwest::Client::builder())
        .connect_timeout(CONNECT_TIMEOUT)
        .timeout(std::time::Duration::from_secs(120))
        .redirect(reqwest::redirect::Policy::none())
        .build()
}

/// Build the client for web pages and the images they name.
///
/// A link card is read from a page a caller names, and its image from a URL
/// that page names, so both hosts are a third party's choice. The first URL
/// goes through the endpoint policy before the request; every redirect after
/// it goes through atproto-identity's
/// [`validated_policy`](atproto_identity::redirect::validated_policy), as on
/// [`identity_client`], because the web redirects as a matter of course
/// (`http` to `https`, a bare domain to `www`, a CDN) and a client that
/// refused every redirect would fail on much of it. The hop check is never
/// waived, so with `ATPMCP_ALLOW_INSECURE_ENDPOINTS` set the first URL may be
/// a local server but a redirect still may not lead to one.
///
/// It names itself in `User-Agent`, as `atpmcp/<version>`, because some
/// hosts refuse a request without one; it says nothing about the user.
///
/// # Errors
///
/// When reqwest cannot build the client.
pub fn web_client(guard: &AddressGuard) -> reqwest::Result<reqwest::Client> {
    guard
        .apply(reqwest::Client::builder())
        .connect_timeout(CONNECT_TIMEOUT)
        .timeout(REQUEST_TIMEOUT)
        .redirect(atproto_identity::redirect::validated_policy())
        .user_agent(concat!("atpmcp/", env!("CARGO_PKG_VERSION")))
        .build()
}

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

    /// A lookup over a fixed set of variables, standing in for the environment.
    fn lookup(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
        let vars: Vec<(String, String)> = vars
            .iter()
            .map(|(name, value)| ((*name).to_string(), (*value).to_string()))
            .collect();
        move |name| {
            vars.iter()
                .find(|(key, _)| key == name)
                .map(|(_, value)| value.clone())
        }
    }

    #[test]
    fn unset_and_empty_variables_keep_the_defaults() {
        let defaults = Limits::default();
        for vars in [
            vec![],
            vec![
                ("ATPMCP_BLOB_MAX_UPLOAD_BYTES", ""),
                ("ATPMCP_MAX_MESSAGE_BYTES", "  "),
                ("ATPMCP_ALLOW_INSECURE_ENDPOINTS", ""),
            ],
        ] {
            let limits = Limits::from_lookup(lookup(&vars)).expect("defaults are valid");
            assert_eq!(limits.blob_max_upload_bytes, defaults.blob_max_upload_bytes);
            assert_eq!(limits.max_message_bytes, defaults.max_message_bytes);
            assert!(!limits.allow_insecure_endpoints);
        }
    }

    #[test]
    fn a_whole_number_sets_the_limit() {
        let limits = Limits::from_lookup(lookup(&[
            ("ATPMCP_BLOB_MAX_UPLOAD_BYTES", "1048576"),
            ("ATPMCP_BLOB_MAX_INLINE_BYTES", "0"),
            ("ATPMCP_MAX_CONCURRENT_REQUESTS", " 4 "),
        ]))
        .expect("valid values");
        assert_eq!(limits.blob_max_upload_bytes, 1_048_576);
        assert_eq!(limits.blob_max_inline_bytes, 0, "zero means never inline");
        assert_eq!(limits.max_concurrent_requests, 4);
    }

    /// The case the finding was about: an operator lowering a ceiling with a
    /// value that did not parse got the default and no word about it.
    #[test]
    fn a_value_that_is_not_digits_alone_is_refused_by_name() {
        for value in ["1M", "16MiB", "1_048_576", "1e6", "-1", "0x100000"] {
            let error = Limits::from_lookup(lookup(&[("ATPMCP_BLOB_MAX_UPLOAD_BYTES", value)]))
                .expect_err(value);
            assert!(
                matches!(
                    &error,
                    ConfigError::NotANumber {
                        name: "ATPMCP_BLOB_MAX_UPLOAD_BYTES",
                        ..
                    }
                ),
                "{value}: {error}"
            );
            let message = error.to_string();
            assert!(message.starts_with("error-atpmcp-config-1 "), "{message}");
            assert!(
                message.contains("16777216"),
                "shows the accepted form: {message}"
            );
        }
    }

    /// A value below a floor used to be raised to it without a word.
    #[test]
    fn a_value_below_its_minimum_is_refused() {
        for (name, value) in [
            ("ATPMCP_MAX_MESSAGE_BYTES", "100"),
            ("ATPMCP_MAX_CONCURRENT_REQUESTS", "0"),
            ("ATPMCP_MAX_QUEUED_REQUESTS", "0"),
            ("ATPMCP_BLOB_MAX_DOWNLOAD_BYTES", "0"),
        ] {
            let error = Limits::from_lookup(lookup(&[(name, value)])).expect_err(name);
            assert!(
                matches!(error, ConfigError::BelowMinimum { name: n, .. } if n == name),
                "{name}={value}: {error}"
            );
        }
    }

    #[test]
    fn preserving_exif_is_off_unless_switched_on() {
        assert!(!Limits::from_lookup(lookup(&[])).unwrap().preserve_exif);
        for on in ["1", "true", " ON "] {
            let limits = Limits::from_lookup(lookup(&[("ATPMCP_PRESERVE_EXIF", on)])).unwrap();
            assert!(limits.preserve_exif, "{on:?} preserves");
        }
        for off in ["0", "off", ""] {
            let limits = Limits::from_lookup(lookup(&[("ATPMCP_PRESERVE_EXIF", off)])).unwrap();
            assert!(!limits.preserve_exif, "{off:?} strips");
        }
        let error =
            Limits::from_lookup(lookup(&[("ATPMCP_PRESERVE_EXIF", "keep")])).expect_err("refused");
        assert!(
            error
                .to_string()
                .starts_with("error-atpmcp-config-3 ATPMCP_PRESERVE_EXIF=\"keep\""),
            "{error}"
        );
    }

    #[test]
    fn the_waiver_is_on_off_or_refused() {
        for on in ["1", "true", "YES", " on "] {
            let limits =
                Limits::from_lookup(lookup(&[("ATPMCP_ALLOW_INSECURE_ENDPOINTS", on)])).unwrap();
            assert!(limits.allow_insecure_endpoints, "{on:?} waives");
        }
        for off in ["0", "false", "No", "off", ""] {
            let limits =
                Limits::from_lookup(lookup(&[("ATPMCP_ALLOW_INSECURE_ENDPOINTS", off)])).unwrap();
            assert!(!limits.allow_insecure_endpoints, "{off:?} keeps the policy");
        }
        for neither in ["y", "enabled", "2"] {
            let error =
                Limits::from_lookup(lookup(&[("ATPMCP_ALLOW_INSECURE_ENDPOINTS", neither)]))
                    .expect_err(neither);
            assert!(
                error.to_string().starts_with("error-atpmcp-config-3 "),
                "{neither:?}: {error}"
            );
        }
    }

    /// `DNS_NAMESERVERS` is read with the workspace's shared parser: unset or
    /// empty is the system configuration, a list is split on its separator,
    /// and an entry that is not an address is refused, naming it.
    #[test]
    fn dns_nameservers_are_read_and_a_bad_entry_is_named() {
        assert!(dns_nameservers(lookup(&[])).unwrap().is_empty());
        assert!(
            dns_nameservers(lookup(&[("DNS_NAMESERVERS", "")]))
                .unwrap()
                .is_empty()
        );
        assert_eq!(
            dns_nameservers(lookup(&[("DNS_NAMESERVERS", " 1.1.1.1 ;::1")])).unwrap(),
            vec![
                "1.1.1.1".parse::<std::net::IpAddr>().unwrap(),
                "::1".parse().unwrap()
            ]
        );

        let error = dns_nameservers(lookup(&[("DNS_NAMESERVERS", "1.1.1.1,8.8.8.8")]))
            .expect_err("a comma is not the separator");
        assert_eq!(
            error.to_string(),
            "error-atpmcp-config-5 DNS_NAMESERVERS=\"1.1.1.1,8.8.8.8\" is not a list of \
             nameserver addresses: \"1.1.1.1,8.8.8.8\" is not an IP address. Separate \
             addresses with ';', like 1.1.1.1;8.8.8.8"
        );
        let error = dns_nameservers(lookup(&[("DNS_NAMESERVERS", "1.1.1.1;resolver")]))
            .expect_err("a name is not an address");
        assert!(
            matches!(&error, ConfigError::NotANameserverList { entry, .. } if entry == "resolver"),
            "{error}"
        );
    }

    /// The finding: an empty or malformed `PLC_HOSTNAME` was used as given,
    /// so the server started and failed every `did:plc` resolution later.
    #[test]
    fn an_unusable_plc_hostname_is_refused_by_name() {
        for value in [
            "",
            "   ",
            "has space",
            "plc.example.com?x=1",
            "plc.example.com#top",
            "http://",
            "https:///",
            "/",
            "HTTPS://plc.example.com",
            "ftp://plc.example.com",
            "https://https://plc.example.com",
        ] {
            let error = plc_hostname(lookup(&[("PLC_HOSTNAME", value)])).expect_err(value);
            assert!(
                matches!(
                    &error,
                    ConfigError::NotAPlcDirectory {
                        name: "PLC_HOSTNAME",
                        ..
                    }
                ),
                "{value:?}: {error}"
            );
            let message = error.to_string();
            assert!(
                message.starts_with("error-atpmcp-config-4 PLC_HOSTNAME="),
                "{value:?}: {message}"
            );
        }
    }

    /// A scheme written with one slash, or none, has no `://` to strip, so it
    /// used to reach `directory_base` whole: `http:/x` became `https://http:/x`,
    /// a URL whose host is `http`, and the server started against it. A colon
    /// with no port after it is refused the same way.
    #[test]
    fn a_colon_that_is_not_a_port_is_refused() {
        for value in [
            "http:/x",
            "https:x",
            "http:/",
            "https:/",
            "http:",
            "http:/127.0.0.1:2582",
            "plc.example.com:",
            "http://plc.example.com:x",
        ] {
            let error = plc_hostname(lookup(&[("PLC_HOSTNAME", value)])).expect_err(value);
            let message = error.to_string();
            assert!(
                message.starts_with("error-atpmcp-config-4 PLC_HOSTNAME="),
                "{value:?}: {message}"
            );
            assert!(
                message.contains("is not followed by a port number"),
                "{value:?}: {message}"
            );
        }
    }

    /// Well-formed only, not the host policy: the operator's directory is
    /// trusted, so plain HTTP, loopback and a port are all fine.
    #[test]
    fn a_hostname_or_an_http_url_is_accepted_as_written() {
        for (value, expected) in [
            ("plc.directory", "plc.directory"),
            ("plc.example.com:2582", "plc.example.com:2582"),
            ("localhost:2582", "localhost:2582"),
            ("http://[::1]:2582", "http://[::1]:2582"),
            ("[::1]", "[::1]"),
            ("user:pw@plc.example.com", "user:pw@plc.example.com"),
            ("https://plc.directory/", "https://plc.directory/"),
            ("http://localhost:2582", "http://localhost:2582"),
            ("http://127.0.0.1:2582", "http://127.0.0.1:2582"),
            (
                "https://mirror.example.com/plc",
                "https://mirror.example.com/plc",
            ),
            (" plc.directory\n", "plc.directory"),
        ] {
            assert_eq!(
                plc_hostname(lookup(&[("PLC_HOSTNAME", value)])).expect(value),
                expected,
                "{value:?}"
            );
        }
        assert_eq!(plc_hostname(lookup(&[])).unwrap(), DEFAULT_PLC_HOSTNAME);
    }

    #[test]
    fn defaults_keep_the_inline_ceiling_well_below_the_transfer_ceiling() {
        let limits = Limits::default();
        assert!(limits.blob_max_inline_bytes < limits.blob_max_download_bytes);
        assert!(limits.blob_max_inline_bytes < limits.blob_max_upload_bytes);
    }

    #[test]
    fn the_message_ceiling_admits_a_base64_encoded_maximum_blob() {
        // A blob at the transfer ceiling arrives as 4/3 its size in base64,
        // plus JSON framing. If this ever fails, `upload_blob` with
        // `data_base64` is silently unusable at its documented maximum.
        let limits = Limits::default();
        let encoded = limits.blob_max_upload_bytes.div_ceil(3) * 4;
        assert!(
            (limits.max_message_bytes as u64) > encoded,
            "message ceiling {} must exceed base64-encoded blob size {encoded}",
            limits.max_message_bytes
        );
    }

    /// Read one HTTP request from `stream`, head and body, so that answering
    /// it and closing does not reset a connection that still has bytes unread.
    fn read_request(stream: &mut std::net::TcpStream) {
        use std::io::Read as _;
        let mut raw = Vec::new();
        let mut buffer = [0u8; 4096];
        let head_end = loop {
            if let Some(end) = raw.windows(4).position(|window| window == b"\r\n\r\n") {
                break end + 4;
            }
            let read = stream.read(&mut buffer).expect("read");
            assert!(read > 0, "the connection closed mid-request");
            raw.extend_from_slice(&buffer[..read]);
        };
        let head = String::from_utf8_lossy(&raw[..head_end]).to_ascii_lowercase();
        let length: usize = head
            .lines()
            .find_map(|line| line.strip_prefix("content-length:"))
            .map_or(0, |value| value.trim().parse().expect("a length"));
        while raw.len() < head_end + length {
            let read = stream.read(&mut buffer).expect("read");
            assert!(read > 0, "the connection closed mid-body");
            raw.extend_from_slice(&buffer[..read]);
        }
    }

    /// A host that answers one request with `status` and `Location: location`,
    /// and its URL.
    fn redirecting(status: u16, location: String) -> String {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
        let url = format!("http://{}", listener.local_addr().expect("addr"));
        std::thread::spawn(move || {
            use std::io::Write as _;
            if let Ok((mut stream, _)) = listener.accept() {
                read_request(&mut stream);
                let _ = write!(
                    stream,
                    "HTTP/1.1 {status} Redirect\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                );
            }
        });
        url
    }

    /// Whether anything connected to `listener`. A connection that completed
    /// waits in the backlog whether or not the client stayed, so an empty
    /// backlog means nothing reached it.
    fn was_reached(listener: &std::net::TcpListener) -> bool {
        listener.set_nonblocking(true).expect("nonblocking");
        listener.accept().is_ok()
    }

    /// The finding, at the client: a host that passed the endpoint policy
    /// answers a procedure with `307` to a loopback service. A 307 sends the
    /// body again, so following it would POST the model's JSON there.
    #[tokio::test]
    async fn the_request_client_follows_no_redirect() {
        let target = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
        let location = format!(
            "http://{}/containers/create",
            target.local_addr().expect("addr")
        );
        let start = redirecting(307, location.clone());

        let error = request_client(&AddressGuard::for_config(false, DEFAULT_PLC_HOSTNAME))
            .expect("client")
            .post(format!("{start}/xrpc/com.atproto.repo.createRecord"))
            .json(&serde_json::json!({ "note": "model-supplied" }))
            .send()
            .await
            .expect_err("a redirect is refused, not followed");
        assert!(error.is_redirect(), "{error:?}");
        assert!(format!("{error:?}").contains(&location), "{error:?}");
        assert!(!was_reached(&target), "the redirect was followed");
    }

    /// The files under `src/`, recursively.
    fn sources(dir: &std::path::Path, found: &mut Vec<std::path::PathBuf>) {
        for entry in std::fs::read_dir(dir).expect("read src") {
            let path = entry.expect("entry").path();
            if path.is_dir() {
                sources(&path, found);
            } else if path.extension().is_some_and(|ext| ext == "rs") {
                found.push(path);
            }
        }
    }

    /// 65zf: `blob_client` fell back to `reqwest::Client::new()` -- no
    /// timeout, ten redirects anywhere -- when its builder failed, the
    /// fallback `identity_client`'s docs call the hole it exists to close. No
    /// client outside test code is a default one now: every builder failure
    /// is an error. Test code is everything from a file's first
    /// `#[cfg(test)]` on; comments are skipped.
    #[test]
    fn no_client_outside_test_code_is_a_default_one() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
        let mut files = Vec::new();
        sources(&root, &mut files);
        assert!(files.len() > 10, "found {} files", files.len());
        let mut offenders = Vec::new();
        for file in files {
            let text = std::fs::read_to_string(&file).expect("read");
            let code = text.split("#[cfg(test)]").next().unwrap_or_default();
            for (number, line) in code.lines().enumerate() {
                if line.trim_start().starts_with("//") {
                    continue;
                }
                if line.contains("Client::new()") || line.contains("Client::default()") {
                    offenders.push(format!("{}:{}", file.display(), number + 1));
                }
            }
        }
        assert!(offenders.is_empty(), "default clients: {offenders:?}");
    }

    /// Identity resolution follows redirects, since the handle specification
    /// allows them, but not to where the endpoint policy would refuse to go.
    #[tokio::test]
    async fn the_identity_client_refuses_a_redirect_the_policy_would() {
        let target = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
        let location = format!(
            "http://{}/.well-known/atproto-did",
            target.local_addr().expect("addr")
        );
        let start = redirecting(302, location.clone());

        let error = identity_client(&AddressGuard::for_config(false, DEFAULT_PLC_HOSTNAME))
            .expect("client")
            .get(format!("{start}/.well-known/atproto-did"))
            .send()
            .await
            .expect_err("a loopback hop is refused");
        assert!(error.is_redirect(), "{error:?}");
        let refusal = std::error::Error::source(&error)
            .and_then(|source| source.downcast_ref::<atproto_identity::errors::RedirectError>());
        assert!(
            matches!(
                refusal,
                Some(atproto_identity::errors::RedirectError::EndpointRefused { hop, .. })
                    if *hop == location
            ),
            "the refusal names the hop: {error:?}"
        );
        assert!(!was_reached(&target), "the redirect was followed");
    }

    /// A lookup that answers every name with loopback, standing in for a
    /// public name whose address record is `127.0.0.1`.
    struct Loopback;

    impl Resolve for Loopback {
        fn resolve(&self, _name: reqwest::dns::Name) -> reqwest::dns::Resolving {
            Box::pin(async {
                let addrs: reqwest::dns::Addrs = Box::new(std::iter::once(
                    std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
                ));
                Ok(addrs)
            })
        }
    }

    /// A loopback listener that answers every request `200 OK`, and its port.
    async fn ok_server() -> u16 {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind");
        let port = listener.local_addr().expect("addr").port();
        tokio::spawn(async move {
            while let Ok((mut socket, _)) = listener.accept().await {
                tokio::spawn(async move {
                    let mut request = [0u8; 4096];
                    let _ = socket.read(&mut request).await;
                    let _ = socket
                        .write_all(
                            b"HTTP/1.1 200 OK\r\ncontent-length: 0\r\nconnection: close\r\n\r\n",
                        )
                        .await;
                });
            }
        });
        port
    }

    /// An error and every source under it, joined.
    fn chain(error: &dyn std::error::Error) -> String {
        let mut text = error.to_string();
        let mut source = error.source();
        while let Some(next) = source {
            text.push_str(" / ");
            text.push_str(&next.to_string());
            source = next.source();
        }
        text
    }

    /// The four clients, built over `guard`.
    fn clients(guard: &AddressGuard) -> [(&'static str, reqwest::Client); 4] {
        [
            ("identity", identity_client(guard).expect("identity client")),
            ("request", request_client(guard).expect("request client")),
            ("blob", blob_client(guard).expect("blob client")),
            ("web", web_client(guard).expect("web client")),
        ]
    }

    /// The finding (gwf8): the endpoint policy is syntactic, so a public name
    /// resolving to loopback passed it and the request went there. With the
    /// guard on, every client refuses it at connect time, and the refusal
    /// names the address.
    #[tokio::test]
    async fn the_guard_refuses_a_name_that_resolves_to_loopback() {
        let port = ok_server().await;
        let guard =
            AddressGuard::for_config(false, DEFAULT_PLC_HOSTNAME).with_lookup(Arc::new(Loopback));
        assert!(guard.is_guarded());
        let url = format!("http://pds.example.com:{port}/");
        for (which, client) in clients(&guard) {
            let error = client.get(&url).send().await.expect_err(which);
            assert!(error.is_connect(), "{which}: {error:?}");
            let chain = chain(&error);
            assert!(
                chain.contains("error-atproto-identity-egress-1"),
                "{which}: {chain}"
            );
            assert!(chain.contains("127.0.0.1"), "{which}: {chain}");
        }
    }

    /// ATPMCP_ALLOW_INSECURE_ENDPOINTS lifts the guard for every client, as
    /// Nick chose: the same request connects.
    #[tokio::test]
    async fn the_waiver_lifts_the_guard_for_every_client() {
        let port = ok_server().await;
        let guard =
            AddressGuard::for_config(true, DEFAULT_PLC_HOSTNAME).with_lookup(Arc::new(Loopback));
        assert!(!guard.is_guarded());
        let url = format!("http://pds.example.com:{port}/");
        for (which, client) in clients(&guard) {
            let response = client.get(&url).send().await.expect(which);
            assert_eq!(response.status(), reqwest::StatusCode::OK, "{which}");
        }
    }

    /// The operator's PLC_HOSTNAME is configuration, so with the guard on it
    /// connects whatever it resolves to, in each form PLC_HOSTNAME takes, and
    /// every other name is still refused.
    #[tokio::test]
    async fn the_configured_plc_host_is_admitted_and_nothing_else() {
        let port = ok_server().await;
        for plc_hostname in [
            "plc.example.com",
            "https://plc.example.com",
            "plc.example.com:2582",
        ] {
            let guard =
                AddressGuard::for_config(false, plc_hostname).with_lookup(Arc::new(Loopback));
            for (which, client) in clients(&guard) {
                let response = client
                    .get(format!("http://plc.example.com:{port}/"))
                    .send()
                    .await
                    .unwrap_or_else(|error| panic!("{plc_hostname} {which}: {error:?}"));
                assert_eq!(response.status(), reqwest::StatusCode::OK);
                let error = client
                    .get(format!("http://pds.example.com:{port}/"))
                    .send()
                    .await
                    .expect_err(which);
                assert!(
                    chain(&error).contains("error-atproto-identity-egress-1"),
                    "{plc_hostname} {which}: {error:?}"
                );
            }
        }
    }

    /// An address literal as PLC_HOSTNAME admits nothing: a literal is never
    /// looked up, so there is no name to put on the allowlist.
    #[test]
    fn a_literal_plc_hostname_adds_no_host() {
        let guard = AddressGuard::for_config(false, "http://127.0.0.1:2582");
        assert!(guard.allowlist.is_empty(), "{guard:?}");
        let guard = AddressGuard::for_config(false, DEFAULT_PLC_HOSTNAME);
        assert!(
            guard.allowlist.allows_host(DEFAULT_PLC_HOSTNAME),
            "{guard:?}"
        );
    }
}