diff --git a/.changeset/nip05-egress-proxy.md b/.changeset/nip05-egress-proxy.md
new file mode 100644
index 000000000..802f96f59
--- /dev/null
+++ b/.changeset/nip05-egress-proxy.md
@@ -0,0 +1,6 @@
+---
+---
+
+feat(config): verify NIP-05 names through an egress proxy with a pinned address
+
+`nip05.proxy` returns with its two modes: `disabled` (the default) connects directly and ignores `HTTPS_PROXY`, and `pin` reaches the HTTP or HTTPS proxy in `HTTPS_PROXY` with `CONNECT
:` naming the address the relay checked, so the proxy never resolves the host; TLS runs through the tunnel with the host name as `servername`, one redirect is followed per hop with fresh pinning, and a refused CONNECT, a private address, a name mismatch or a deadline fails the verification closed.
diff --git a/CLAUDE.md b/CLAUDE.md
index 2341eff77..b2bc091dc 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -125,6 +125,12 @@ resolver 3:
`reqwest` (`default-features = false` with `rustls-tls`, so no new TLS stack) behind the
`HttpClient` seam, and tokio's `process`/`fs` for the DVM worker pipes, the onion key file
and the operator CLI's spawn seam (ADR 0015, D11). Nothing else may take those features.
+ `nostream-services` also owns the NIP-05 egress tunnel: `hyper`'s `client` connection,
+ `hyper-util`'s `TokioIo`, `http-body-util`, `rustls` + `tokio-rustls` (`ring`, no
+ `aws-lc-rs`) and `webpki-roots` — the same TLS stack reqwest already uses, taken directly
+ because reqwest's tunnel writes the host name into the CONNECT line and the port must pin
+ the resolved address instead (ADR 0023); `percent-encoding` and `base64` decode the
+ proxy URL's credentials.
The branch's other third-party additions are `aes` and `cbc`, in `nostream-core`, for the
NIP-04 body NIP-47 encrypts (ADR 0010, A23); `bech32` in `nostream-core` for NIP-19 `npub`
decoding; and `flate2` and `xz2` in `nostream-cli` for `export`'s two codecs (ADR 0015, D6).
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 4d555d713..f0cb0c6b0 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -257,7 +257,8 @@ The settings below are listed in alphabetical order by name. Please keep this ta
| nip05.domainBlacklist | List of domains blocked from NIP-05 verification. Authors with NIP-05 at these domains will be rejected. |
| nip05.domainWhitelist | List of domains allowed for NIP-05 verification. If set, only authors verified at these domains can publish. |
| nip05.maxConsecutiveFailures | Number of consecutive verification failures before giving up on an author. Defaults to 20. |
-| nip05.mode | NIP-05 verification mode: `enabled` requires verification, `passive` verifies without blocking, `disabled` does nothing. Defaults to `disabled`. |
+| nip05.mode | NIP-05 verification mode: `enabled` requires verification, `passive` verifies without blocking, `disabled` does nothing. Defaults to `disabled`. Verification requests go out directly over HTTPS and ignore `HTTPS_PROXY` unless `nip05.proxy` is `pin`, so the relay needs direct outbound HTTPS or `nip05.proxy`; a domain or redirect target that resolves to a loopback, private or link-local address is not contacted. A change takes effect after a restart. |
+| nip05.proxy | How NIP-05 verification requests reach the internet: `disabled` (default) connects directly and ignores `HTTPS_PROXY`; `pin` goes through the HTTP or HTTPS proxy in `HTTPS_PROXY` (`NO_PROXY` is not read). The relay resolves the host itself, refuses a private address, and asks the proxy for `CONNECT :443` with the address it checked, then checks the certificate against the host name, a redirect target included. A proxy that refuses the `CONNECT` makes the verification fail with a reason naming the proxy and the host. With `pin` and no `HTTPS_PROXY` the connection is direct. A change to `nip05.proxy` or `HTTPS_PROXY` takes effect after a restart. |
| nip05.verifyExpiration | Time in milliseconds before a successful NIP-05 verification expires and needs re-checking. Defaults to 604800000 (1 week). |
| nip05.verifyUpdateFrequency | Minimum interval in milliseconds between re-verification attempts for a given author. Defaults to 86400000 (24 hours). |
| nip42.authRequired | When true, clients must NIP-42 AUTH as the event author before publishing events. Advertised in NIP-11 as `limitation.restricted_writes` (not `auth_required`, which means AUTH before any connection action). Defaults to false. |
@@ -324,7 +325,8 @@ The settings below are listed in alphabetical order by name. Please keep this ta
| nip05.domainBlacklist | List of domains blocked from NIP-05 verification. Authors with NIP-05 at these domains will be rejected. |
| nip05.domainWhitelist | List of domains allowed for NIP-05 verification. If set, only authors verified at these domains can publish. |
| nip05.maxConsecutiveFailures | Number of consecutive verification failures before giving up on an author. Defaults to 20. |
-| nip05.mode | NIP-05 verification mode: `enabled` requires verification, `passive` verifies without blocking, `disabled` does nothing. Defaults to `disabled`. |
+| nip05.mode | NIP-05 verification mode: `enabled` requires verification, `passive` verifies without blocking, `disabled` does nothing. Defaults to `disabled`. Verification requests go out directly over HTTPS and ignore `HTTPS_PROXY` unless `nip05.proxy` is `pin`, so the relay needs direct outbound HTTPS or `nip05.proxy`; a domain or redirect target that resolves to a loopback, private or link-local address is not contacted. A change takes effect after a restart. |
+| nip05.proxy | How NIP-05 verification requests reach the internet: `disabled` (default) connects directly and ignores `HTTPS_PROXY`; `pin` goes through the HTTP or HTTPS proxy in `HTTPS_PROXY` (`NO_PROXY` is not read). The relay resolves the host itself, refuses a private address, and asks the proxy for `CONNECT :443` with the address it checked, then checks the certificate against the host name, a redirect target included. A proxy that refuses the `CONNECT` makes the verification fail with a reason naming the proxy and the host. With `pin` and no `HTTPS_PROXY` the connection is direct. A change to `nip05.proxy` or `HTTPS_PROXY` takes effect after a restart. |
| nip05.verifyExpiration | Time in milliseconds before a successful NIP-05 verification expires and needs re-checking. Defaults to 604800000 (1 week). |
| nip05.verifyUpdateFrequency | Minimum interval in milliseconds between re-verification attempts for a given author. Defaults to 86400000 (24 hours). |
| paymentProcessors.lnbits.baseURL | Base URL of your Lnbits instance. |
diff --git a/Cargo.lock b/Cargo.lock
index 0125d5570..0c9f412c4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1576,26 +1576,34 @@ version = "0.1.0"
name = "nostream-services"
version = "0.1.0"
dependencies = [
+ "base64 0.22.1",
"chrono",
"futures-util",
"hex",
"hmac 0.13.0",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
"nostream-config",
"nostream-core",
"nostream-relay",
"nostream-scan",
"nostream-storage",
+ "percent-encoding",
"reqwest",
+ "rustls",
"serde_json",
"serde_yaml",
"sha2 0.11.1",
"tempfile",
"thiserror",
"tokio",
+ "tokio-rustls",
"tokio-tungstenite",
"tracing",
"tracing-subscriber",
"url",
+ "webpki-roots 1.0.10",
]
[[package]]
@@ -2267,6 +2275,7 @@ version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
+ "log",
"once_cell",
"ring",
"rustls-pki-types",
diff --git a/Cargo.toml b/Cargo.toml
index 65f2cff82..87956a96e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -25,10 +25,11 @@ futures-util = "0.3"
getrandom = "0.3"
heed = { version = "0.20", features = ["read-txn-no-tls"] }
hex = "0.4.3"
-hyper = { version = "1", features = ["server", "http1"] }
-hyper-util = { version = "0.1", features = ["tokio", "service"] }
hkdf = "0.13.0"
hmac = "0.13.0"
+http-body-util = "0.1.5"
+hyper = { version = "1", features = ["server", "http1", "client"] }
+hyper-util = { version = "0.1", features = ["tokio", "service"] }
negentropy = "0.5.2"
nostream-admin = { path = "crates/nostream-admin" }
nostream-cli = { path = "crates/nostream-cli" }
@@ -43,8 +44,10 @@ nostreamd = { path = "crates/nostreamd" }
opentelemetry = "0.33.1"
opentelemetry-otlp = { version = "0.33.1", default-features = false, features = ["trace", "grpc-tonic"] }
opentelemetry_sdk = { version = "0.33.1", default-features = false, features = ["trace", "rt-tokio"] }
+percent-encoding = "2.3.2"
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
rmcp = { version = "3.11", features = ["server", "transport-io", "transport-async-rw"] }
+rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
scrypt = "0.11"
secp256k1 = "0.33.1"
serde = { version = "1", features = ["derive"] }
@@ -55,12 +58,14 @@ sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio",
tempfile = "3"
thiserror = "2"
tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "process", "rt-multi-thread", "signal", "sync", "time"] }
+tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12", "logging"] }
tokio-tungstenite = { version = "0.30", features = ["connect", "handshake", "rustls-tls-webpki-roots"] }
tracing = "0.1"
tracing-opentelemetry = "0.34"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
url = "2"
uuid = { version = "1", features = ["v4"] }
+webpki-roots = "1"
xz2 = "0.1"
# Nothing reads debug info here. The 66 integration-test binaries this workspace links are
diff --git a/crates/nostream-admin/tests/route_shapes.rs b/crates/nostream-admin/tests/route_shapes.rs
index 992be589d..438893977 100644
--- a/crates/nostream-admin/tests/route_shapes.rs
+++ b/crates/nostream-admin/tests/route_shapes.rs
@@ -143,6 +143,9 @@ async fn get_settings_answers_the_settings() {
assert_eq!(response.status, 200);
assert_json(&response);
assert_keys(&response, &["settings"]);
+ // Value 52 keeps a key only when the shipped defaults carry it; `nip05.proxy` is now one
+ // of them (job 052), so the admin view exposes it.
+ assert_eq!(response.json()["settings"]["nip05"]["proxy"], "disabled");
}
#[tokio::test]
diff --git a/crates/nostream-config/src/settings.rs b/crates/nostream-config/src/settings.rs
index 58077fca2..989aad95e 100644
--- a/crates/nostream-config/src/settings.rs
+++ b/crates/nostream-config/src/settings.rs
@@ -645,6 +645,14 @@ pub enum Nip05Mode {
Disabled,
}
+/// `nip05.proxy` (`src/@types/settings.ts` `Nip05Proxy`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Nip05Proxy {
+ Disabled,
+ Pin,
+}
+
/// `nip45` (`src/@types/settings.ts` `Nip45Settings`).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Nip45Settings {
@@ -708,6 +716,9 @@ pub struct Nip05Settings {
pub domain_whitelist: Option>,
#[serde(skip_serializing_if = "Option::is_none")]
pub domain_blacklist: Option>,
+ /// How verification requests reach the internet; `None` is `disabled`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub proxy: Option,
}
/// `admin.nip98` (`src/@types/settings.ts` `AdminNip98Settings`).
diff --git a/crates/nostream-config/src/validate.rs b/crates/nostream-config/src/validate.rs
index 9661bcf00..ff5465eff 100644
--- a/crates/nostream-config/src/validate.rs
+++ b/crates/nostream-config/src/validate.rs
@@ -267,6 +267,13 @@ pub fn validate_document(candidate: &Value, defaults: &Value) -> Vec {
);
}
+ // Wrong types are the shape walk's to report; this rule is about the value.
+ if let Some(Value::String(proxy)) = key_path(candidate, &["nip05", "proxy"])
+ && !matches!(proxy.as_str(), "disabled" | "pin")
+ {
+ issues.push(Issue::new("nip05.proxy", "proxy must be disabled or pin"));
+ }
+
// `nip66` retention, `nip77` caps, subscription plans and peering are modelled by the
// typed settings above but were not validated: the document is shared with the
// TypeScript app, which rejects these documents, so `config validate` blessing them
@@ -599,10 +606,14 @@ fn validate_shape(
}
_ => {
if matches!(candidate, Value::Null) && !matches!(schema, Value::Null) {
- issues.push(Issue::new(
- rendered,
- format!("Expected {}, got null", js_typeof(schema)),
- ));
+ // `nip05.proxy: null` is unset, exactly as an absent key is (ADR 0023, D4):
+ // a v3 document may write it, and the typed field is `None`.
+ if rendered != "nip05.proxy" {
+ issues.push(Issue::new(
+ rendered,
+ format!("Expected {}, got null", js_typeof(schema)),
+ ));
+ }
return;
}
if !matches!(schema, Value::Null) && js_typeof(schema) != js_typeof(candidate) {
diff --git a/crates/nostream-config/tests/defaults_parity.rs b/crates/nostream-config/tests/defaults_parity.rs
index 7cece411b..2f6681aaa 100644
--- a/crates/nostream-config/tests/defaults_parity.rs
+++ b/crates/nostream-config/tests/defaults_parity.rs
@@ -10,6 +10,7 @@ use std::fs;
use nostream_config::load::merge;
use nostream_config::path::get_by_path;
+use nostream_config::settings::{Nip05Proxy, Settings};
use serde_yaml::Value;
fn defaults() -> Value {
@@ -182,3 +183,20 @@ fn a_nip56_user_block_overrides_the_defaults() {
Value::String("a".repeat(64)),
);
}
+
+#[test]
+fn nip05_proxy_defaults_to_disabled() {
+ let defaults = defaults();
+ assert_value(
+ &defaults,
+ "nip05.proxy",
+ Value::String("disabled".to_owned()),
+ );
+
+ let settings: Settings =
+ serde_yaml::from_value(defaults).expect("the defaults fit the typed schema");
+ assert_eq!(
+ settings.nip05.and_then(|nip05| nip05.proxy),
+ Some(Nip05Proxy::Disabled)
+ );
+}
diff --git a/crates/nostream-config/tests/load.rs b/crates/nostream-config/tests/load.rs
index 1baa0af53..9ca9e7cc8 100644
--- a/crates/nostream-config/tests/load.rs
+++ b/crates/nostream-config/tests/load.rs
@@ -12,6 +12,7 @@ use std::path::{Path, PathBuf};
use nostream_config::load::{fit, load, load_user_settings, merge};
use nostream_config::path::get_by_path;
+use nostream_config::settings::Nip05Proxy;
use nostream_config::{ConfigError, SettingsPaths, load_defaults, validate_document};
use serde_yaml::Value;
use tempfile::TempDir;
@@ -498,6 +499,83 @@ fn a_legacy_json_directory_is_reported_the_same_way() {
assert!(matches!(error, ConfigError::NotAFile { .. }));
}
+#[test]
+fn nip05_proxy_pin_loads_and_validates() {
+ let config_dir = TempDir::new().expect("tempdir");
+ write(
+ config_dir.path(),
+ "settings.yaml",
+ "nip05:\n mode: enabled\n proxy: pin\n",
+ );
+ let outcome = load(&paths(config_dir.path())).expect("the settings load");
+
+ assert_eq!(outcome.issues, Vec::new());
+ assert!(!outcome.used_defaults);
+ assert_eq!(
+ outcome.settings.nip05.and_then(|nip05| nip05.proxy),
+ Some(Nip05Proxy::Pin)
+ );
+}
+
+#[test]
+fn nip05_proxy_disabled_loads_and_validates() {
+ let config_dir = TempDir::new().expect("tempdir");
+ write(
+ config_dir.path(),
+ "settings.yaml",
+ "nip05:\n mode: enabled\n proxy: disabled\n",
+ );
+ let outcome = load(&paths(config_dir.path())).expect("the settings load");
+
+ assert_eq!(outcome.issues, Vec::new());
+ assert!(!outcome.used_defaults);
+ assert_eq!(
+ outcome.settings.nip05.and_then(|nip05| nip05.proxy),
+ Some(Nip05Proxy::Disabled)
+ );
+}
+
+#[test]
+fn nip05_proxy_unknown_mode_discards_the_document() {
+ let config_dir = TempDir::new().expect("tempdir");
+ write(
+ config_dir.path(),
+ "settings.yaml",
+ "nip05:\n mode: enabled\n proxy: env\n",
+ );
+ let outcome = load(&paths(config_dir.path())).expect("the settings load");
+
+ assert!(outcome.used_defaults);
+ assert_eq!(
+ outcome
+ .issues
+ .iter()
+ .map(|issue| issue.to_string())
+ .collect::>(),
+ vec!["nip05.proxy: proxy must be disabled or pin"]
+ );
+ assert_eq!(
+ outcome.settings.nip05.and_then(|nip05| nip05.proxy),
+ Some(Nip05Proxy::Disabled),
+ "the fallback is the typed default"
+ );
+}
+
+#[test]
+fn nip05_proxy_null_is_unset() {
+ let config_dir = TempDir::new().expect("tempdir");
+ write(
+ config_dir.path(),
+ "settings.yaml",
+ "nip05:\n mode: enabled\n proxy: null\n",
+ );
+ let outcome = load(&paths(config_dir.path())).expect("the settings load");
+
+ assert_eq!(outcome.issues, Vec::new());
+ assert!(!outcome.used_defaults);
+ assert_eq!(outcome.settings.nip05.expect("the section").proxy, None);
+}
+
#[test]
fn every_float_field_is_declared_to_the_numeric_walk() {
// The walk reads a field's type off the serialized defaults, where `serialize_js_number`
diff --git a/crates/nostream-config/tests/validator.rs b/crates/nostream-config/tests/validator.rs
index 4f890c074..b238c6d6e 100644
--- a/crates/nostream-config/tests/validator.rs
+++ b/crates/nostream-config/tests/validator.rs
@@ -774,6 +774,27 @@ fn accepts_a_well_formed_http_target() {
assert_eq!(issues(&document), Vec::::new());
}
+#[test]
+fn nip05_proxy_rules() {
+ for patch in [
+ "nip05:\n mode: enabled\n proxy: disabled\n",
+ "nip05:\n mode: enabled\n proxy: pin\n",
+ "nip05:\n mode: enabled\n proxy: null\n",
+ "nip05:\n mode: enabled\n",
+ ] {
+ assert_eq!(issues(&patched(patch)), Vec::::new(), "{patch}");
+ }
+
+ assert_eq!(
+ issues(&patched("nip05:\n mode: enabled\n proxy: env\n")),
+ vec!["nip05.proxy: proxy must be disabled or pin"]
+ );
+ assert_eq!(
+ issues(&patched("nip05:\n mode: enabled\n proxy: 5\n")),
+ vec!["nip05.proxy: Expected string, got number"]
+ );
+}
+
#[test]
fn merge_deep_right_replaces_arrays_and_null() {
let defaults: Value =
diff --git a/crates/nostream-relay/tests/handlers.rs b/crates/nostream-relay/tests/handlers.rs
index dbee299e0..78a2dd49f 100644
--- a/crates/nostream-relay/tests/handlers.rs
+++ b/crates/nostream-relay/tests/handlers.rs
@@ -719,6 +719,7 @@ async fn nip05_gates_publication() {
max_consecutive_failures: None,
domain_whitelist: Some(vec!["allowed.example".to_owned()]),
domain_blacklist: None,
+ proxy: None,
});
let server = start(Fixture::new(settings)).await;
@@ -864,6 +865,7 @@ async fn a_nip05_store_error_is_reported_as_a_failure_and_not_as_a_refusal() {
max_consecutive_failures: None,
domain_whitelist: None,
domain_blacklist: None,
+ proxy: None,
});
let fixture = Fixture::new(enabled);
diff --git a/crates/nostream-services/Cargo.toml b/crates/nostream-services/Cargo.toml
index d0c2e46ab..a9819090e 100644
--- a/crates/nostream-services/Cargo.toml
+++ b/crates/nostream-services/Cargo.toml
@@ -13,18 +13,26 @@ nostream-core.workspace = true
nostream-relay.workspace = true
nostream-scan.workspace = true
nostream-storage.workspace = true
+base64.workspace = true
chrono.workspace = true
futures-util.workspace = true
hex.workspace = true
hmac.workspace = true
+http-body-util.workspace = true
+hyper.workspace = true
+hyper-util.workspace = true
+percent-encoding.workspace = true
reqwest.workspace = true
+rustls.workspace = true
serde_json.workspace = true
sha2.workspace = true
thiserror.workspace = true
tokio.workspace = true
+tokio-rustls.workspace = true
tokio-tungstenite.workspace = true
tracing.workspace = true
url.workspace = true
+webpki-roots.workspace = true
[dev-dependencies]
serde_yaml.workspace = true
diff --git a/crates/nostream-services/src/http.rs b/crates/nostream-services/src/http.rs
index fb23ed24c..44f2f1201 100644
--- a/crates/nostream-services/src/http.rs
+++ b/crates/nostream-services/src/http.rs
@@ -15,6 +15,7 @@ use nostream_core::nip05::{FetchOutcome, Nip05Fetch};
use reqwest::dns::{Addrs, Name, Resolve, Resolving};
use crate::error::ServicesError;
+use crate::nip05_egress;
/// What one request answered: the status and the body as text.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -51,12 +52,19 @@ pub trait HttpClient: Send + Sync {
///
/// One client serves the payment processors and the notification channels, whose URLs are the
/// operator's to choose, including a self-hosted processor on a private address. The NIP-05
-/// fetch is the exception: its URL comes from a stored identifier, so it is built on its own
-/// client per request with [`GuardedResolver`] underneath.
+/// fetch has two paths: the direct one builds a per-request client over [`GuardedResolver`];
+/// with `nip05.proxy: pin`, [`nip05_egress`] opens a pinned CONNECT tunnel over the undecorated
+/// resolver and applies the any-private rule itself (ADR 0023, D2).
#[derive(Clone)]
pub struct ReqwestClient {
client: reqwest::Client,
- nip05_resolver: Arc,
+ /// The direct NIP-05 path's resolver: vetted addresses only.
+ nip05_guarded_resolver: Arc,
+ /// The tunnel's resolver, undecorated: [`nip05_egress`] applies the v3 "refuse when any
+ /// address is private" rule itself (ADR 0023, D2).
+ nip05_tunnel_resolver: Arc,
+ /// `Some` when `nip05.proxy: pin` and a proxy URL was resolved at composition.
+ nip05_egress: Option,
}
impl std::fmt::Debug for ReqwestClient {
@@ -80,18 +88,65 @@ impl ReqwestClient {
}
/// A client whose NIP-05 fetch resolves names through `resolver`, guarded by
- /// [`GuardedResolver`].
+ /// [`GuardedResolver`], and connects directly.
pub fn with_nip05_resolver(resolver: Arc) -> Result {
+ Self::with_nip05_proxy(resolver, None)
+ }
+
+ /// A client whose NIP-05 fetch resolves names through `resolver` and, when `proxy` is set,
+ /// reaches them through that proxy with the address it checks.
+ pub fn with_nip05_proxy(
+ resolver: Arc,
+ proxy: Option,
+ ) -> Result {
+ let roots = rustls::RootCertStore {
+ roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
+ };
+ Self::with_nip05_proxy_config(
+ resolver,
+ proxy,
+ Duration::from_millis(nip05_egress::SETUP_TIMEOUT_MS),
+ roots,
+ )
+ }
+
+ fn with_nip05_proxy_config(
+ resolver: Arc,
+ proxy: Option,
+ setup_timeout: Duration,
+ roots: rustls::RootCertStore,
+ ) -> Result {
let client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::limited(MAX_REDIRECTS))
.build()
.map_err(|error| ServicesError::Configuration(format!("http client: {error}")))?;
+ let nip05_egress = match proxy {
+ Some(proxy_url) => Some(nip05_egress::Egress {
+ proxy_url,
+ tls: nip05_egress::client_config(roots)?,
+ setup_timeout,
+ }),
+ None => None,
+ };
Ok(Self {
client,
- nip05_resolver: Arc::new(GuardedResolver::new(resolver)),
+ nip05_guarded_resolver: Arc::new(GuardedResolver::new(Arc::clone(&resolver))),
+ nip05_tunnel_resolver: resolver,
+ nip05_egress,
})
}
+
+ /// The test seam: the same construction with a short setup deadline and the test's roots.
+ #[cfg(test)]
+ pub(crate) fn with_nip05_proxy_test(
+ resolver: Arc,
+ proxy: Option,
+ setup_timeout: Duration,
+ roots: rustls::RootCertStore,
+ ) -> Result {
+ Self::with_nip05_proxy_config(resolver, proxy, setup_timeout, roots)
+ }
}
/// `getaddrinfo`, the resolver a client gets when nothing else is installed.
@@ -165,9 +220,11 @@ impl Resolve for GuardedResolver {
/// Whether `address` may be dialled: public unicast space only.
///
-/// The capture cannot make this check (`src/utils/nip05.ts:59-105` has no resolver either), so
-/// this is a deliberate divergence: a stored NIP-05 domain must not reach the host's own
-/// network.
+/// v3 refuses a name when **any** resolved address is private
+/// (`origin/main:src/utils/safe-lookup.ts:34-47`, `:55-67`, read at `943fd7a2`). The direct
+/// path here drops private addresses and refuses only when none is left, so a stored NIP-05
+/// domain must not reach the host's own network; the tunnel applies v3's any-private rule
+/// instead (AC11).
pub fn is_public_address(address: IpAddr) -> bool {
match address {
IpAddr::V4(address) => is_public_v4(address),
@@ -284,11 +341,11 @@ impl HttpClient for ReqwestClient {
/// A target the NIP-05 fetch may dial: `https` on a host that is not `localhost`, not a
/// private literal, and not an IPv6 literal.
///
-/// The capture's `isRedirectTargetSafe` (`src/utils/nip05.ts:59-105`) is the same predicate
-/// applied to redirect hops. It is applied to the initial URL here as well, and the host's
-/// resolved addresses are filtered by [`GuardedResolver`] — a check the capture cannot make,
-/// because it has no resolver.
-fn is_redirect_target_safe(url: &reqwest::Url) -> bool {
+/// v3's `isRedirectTargetSafe` (`origin/main:src/utils/nip05.ts:139-163`, read at `943fd7a2`)
+/// is the same predicate applied to redirect hops. It is applied to the initial URL here as
+/// well; the direct path's host names are then decided by [`GuardedResolver`], and the
+/// tunnel's by its own any-private check.
+pub(crate) fn is_redirect_target_safe(url: &reqwest::Url) -> bool {
if url.scheme() != "https" {
return false;
}
@@ -313,17 +370,61 @@ fn is_redirect_target_safe(url: &reqwest::Url) -> bool {
}
}
-/// The capture's `beforeRedirect` over `maxRedirects`: each hop is checked before it is
+#[derive(Debug)]
+pub(crate) enum RedirectDecision {
+ /// Not a redirect: the response is the answer, whatever the budget.
+ Answer,
+ /// A redirect inside the budget: follow it once [`is_redirect_target_safe`] allows.
+ Follow,
+}
+
+/// The NIP-05 redirect rule — the statuses followed and the hop budget — in one place, shared
+/// by the direct policy and the tunnel (ADR 0023, D5). `previous` is the number of requests
+/// already made in this fetch, the initial one included, which is what reqwest's
+/// `Attempt::previous()` counts; a fetch that has followed `max_redirects` hops has made
+/// `max_redirects + 1` requests, so the next redirect is refused.
+pub(crate) fn redirect_decision(
+ status: u16,
+ previous: usize,
+ max_redirects: usize,
+) -> Result {
+ if !matches!(status, 301 | 302 | 303 | 307 | 308) {
+ return Ok(RedirectDecision::Answer);
+ }
+
+ if previous > max_redirects {
+ return Err("too many redirects".to_owned());
+ }
+
+ Ok(RedirectDecision::Follow)
+}
+
+/// The refusal text for a redirect target [`is_redirect_target_safe`] rejects.
+pub(crate) fn refused_redirect(target: &reqwest::Url) -> String {
+ format!("refused redirect to unsafe target: {target}")
+}
+
+/// The error text for a response body over the caller's cap.
+pub(crate) fn body_over_cap(max_bytes: usize) -> String {
+ format!("response body exceeds {max_bytes} bytes")
+}
+
+/// v3's `beforeRedirect` over `maxRedirects`: each hop is checked before it is
/// followed, and a refused target aborts the fetch.
fn nip05_redirect_policy(max_redirects: usize) -> reqwest::redirect::Policy {
reqwest::redirect::Policy::custom(move |attempt| {
- if attempt.previous().len() >= max_redirects {
- return attempt.error("too many redirects");
+ match redirect_decision(
+ attempt.status().as_u16(),
+ attempt.previous().len(),
+ max_redirects,
+ ) {
+ Ok(RedirectDecision::Follow) => {}
+ Ok(RedirectDecision::Answer) => return attempt.stop(),
+ Err(reason) => return attempt.error(reason),
}
-
if !is_redirect_target_safe(attempt.url()) {
- let target = attempt.url().to_string();
- return attempt.error(format!("refused redirect to unsafe target: {target}"));
+ let refusal = refused_redirect(attempt.url());
+ return attempt.error(refusal);
}
attempt.follow()
@@ -353,12 +454,30 @@ impl Nip05Fetch for ReqwestClient {
)));
}
+ // With a proxy configured, every hop is a tunnel opened below reqwest: reqwest's
+ // own tunnel would write the host name into the CONNECT line (ADR 0023, D1).
+ if let Some(egress) = &self.nip05_egress {
+ return nip05_egress::fetch(
+ egress,
+ &self.nip05_tunnel_resolver,
+ url,
+ timeout_ms,
+ max_bytes,
+ max_redirects,
+ )
+ .await;
+ }
+
let client = reqwest::Client::builder()
.redirect(nip05_redirect_policy(max_redirects))
.timeout(Duration::from_millis(timeout_ms))
// This client serves only the NIP-05 path; the shared client's processors may
// legitimately point at a private address.
- .dns_resolver(Arc::clone(&self.nip05_resolver))
+ .dns_resolver(Arc::clone(&self.nip05_guarded_resolver))
+ // The proxy is the operator's choice and is honoured only for `nip05.proxy:
+ // pin`; without this reqwest's `auto_sys_proxy` would route every direct
+ // verification through `HTTPS_PROXY`.
+ .no_proxy()
.build()
.map_err(|error| nostream_core::CoreError::Fetch(error.to_string()))?;
@@ -375,9 +494,7 @@ impl Nip05Fetch for ReqwestClient {
.map_err(|error| nostream_core::CoreError::Fetch(error.to_string()))?
{
if body.len() + chunk.len() > max_bytes {
- return Err(nostream_core::CoreError::Fetch(format!(
- "response body exceeds {max_bytes} bytes"
- )));
+ return Err(nostream_core::CoreError::Fetch(body_over_cap(max_bytes)));
}
body.extend_from_slice(&chunk);
@@ -439,18 +556,26 @@ pub fn join_url(base: &str, path: &str) -> String {
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
- use std::collections::HashMap;
+ use std::collections::{HashMap, VecDeque};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
- use std::sync::Arc;
- use std::sync::Mutex;
- use std::time::Duration;
+ use std::pin::Pin;
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+ use std::sync::{Arc, Mutex};
+ use std::time::{Duration, Instant};
- use nostream_core::nip05::Nip05Fetch;
+ use nostream_config::settings::{Nip05Mode, Nip05Proxy, Nip05Settings};
+ use nostream_core::nip05::{FetchOutcome, Nip05Fetch, VerificationOutcome};
use reqwest::dns::{Addrs, Name, Resolve, Resolving};
+ use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
+ use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
+ use tokio::net::TcpStream;
+ use tokio_rustls::TlsAcceptor;
use super::{
- GuardedResolver, HttpClient, ReqwestClient, is_public_address, is_redirect_target_safe,
+ GuardedResolver, HttpClient, RedirectDecision, ReqwestClient, is_public_address,
+ is_redirect_target_safe, redirect_decision,
};
+ use crate::nip05_egress::{authority, parse_proxy, resolve_proxy, target_port};
/// A resolver that answers from a table, so no test needs DNS.
#[derive(Debug, Default)]
@@ -536,6 +661,41 @@ mod tests {
assert_eq!(safe("https://[::1]/nostr.json"), Some(false));
}
+ /// One owner for the redirect budget. `previous` counts the initial request (reqwest's
+ /// `Attempt::previous()`), so `max_redirects` hops are followed and the next is refused.
+ #[test]
+ fn nip05_redirect_decision() {
+ use RedirectDecision::{Answer, Follow};
+
+ // max = 1: the first redirect (one request made) is followed; the second (two) is not.
+ assert!(matches!(redirect_decision(302, 1, 1), Ok(Follow)));
+ assert_eq!(
+ redirect_decision(302, 2, 1).unwrap_err(),
+ "too many redirects"
+ );
+
+ // max = 2: two hops; the third redirect refuses.
+ assert!(matches!(redirect_decision(307, 2, 2), Ok(Follow)));
+ assert_eq!(
+ redirect_decision(307, 3, 2).unwrap_err(),
+ "too many redirects"
+ );
+
+ // max = 0: a fetch may not redirect at all.
+ assert_eq!(
+ redirect_decision(301, 1, 0).unwrap_err(),
+ "too many redirects"
+ );
+
+ // The five followed statuses, and the statuses that are answers whatever the budget.
+ for status in [301, 302, 303, 307, 308] {
+ assert!(matches!(redirect_decision(status, 1, 1), Ok(Follow)));
+ }
+ for status in [200, 204, 300, 304, 400, 500] {
+ assert!(matches!(redirect_decision(status, 9, 1), Ok(Answer)));
+ }
+ }
+
/// A stored NIP-05 domain must not reach the host's own network. The name passes the URL
/// predicate and is refused by its resolved addresses.
#[tokio::test]
@@ -699,4 +859,1454 @@ mod tests {
"the URL is the credential: {error}"
);
}
+
+ // --- the NIP-05 egress harness ------------------------------------------------------
+
+ /// Anything the tunnel wraps: a socket, a TLS stream, a boxed either.
+ trait AsyncStream: AsyncRead + AsyncWrite + Unpin + Send {}
+ impl AsyncStream for T {}
+ type BoxStream = Box;
+
+ type RelayHandler =
+ dyn Fn(BoxStream, usize) -> Pin + Send>> + Send + Sync;
+
+ type Lookup = Box Option>;
+
+ /// A certificate generated with the `openssl` binary at test time (A5), DER-encoded.
+ struct TestCertificate {
+ cert: Vec,
+ key: Vec,
+ }
+
+ fn openssl(args: &[&str]) -> Vec {
+ let output = std::process::Command::new("openssl")
+ .args(args)
+ .output()
+ .expect("openssl runs (A5)");
+ assert!(
+ output.status.success(),
+ "openssl {args:?}: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ output.stdout
+ }
+
+ /// `CA:FALSE` is mandatory: a default `req -x509` writes `CA:TRUE`, which rustls-webpki
+ /// refuses as an end entity (`CaUsedAsEndEntity`).
+ fn certificate(name: &str, san: &str) -> TestCertificate {
+ let dir = tempfile::TempDir::new().expect("tempdir");
+ let cert_pem = dir.path().join("cert.pem");
+ let key_pem = dir.path().join("key.pem");
+ let cert = cert_pem.to_str().expect("a utf-8 path");
+ let key = key_pem.to_str().expect("a utf-8 path");
+ openssl(&[
+ "req",
+ "-x509",
+ "-newkey",
+ "rsa:2048",
+ "-nodes",
+ "-days",
+ "2",
+ "-subj",
+ &format!("/CN={name}"),
+ "-addext",
+ "basicConstraints=critical,CA:FALSE",
+ "-addext",
+ &format!("subjectAltName={san}"),
+ "-keyout",
+ key,
+ "-out",
+ cert,
+ ]);
+
+ TestCertificate {
+ cert: openssl(&["x509", "-in", cert, "-outform", "der"]),
+ key: openssl(&["pkcs8", "-topk8", "-nocrypt", "-in", key, "-outform", "der"]),
+ }
+ }
+
+ fn server_config(certificate: &TestCertificate) -> Arc {
+ let config = rustls::ServerConfig::builder_with_provider(Arc::new(
+ rustls::crypto::ring::default_provider(),
+ ))
+ .with_safe_default_protocol_versions()
+ .expect("protocol versions")
+ .with_no_client_auth()
+ .with_single_cert(
+ vec![CertificateDer::from(certificate.cert.clone())],
+ PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(certificate.key.clone())),
+ )
+ .expect("the test certificate");
+
+ Arc::new(config)
+ }
+
+ /// The test root store: the certificates served, and nothing else.
+ fn roots(certificates: &[&TestCertificate]) -> rustls::RootCertStore {
+ let mut roots = rustls::RootCertStore::empty();
+ for certificate in certificates {
+ roots
+ .add(CertificateDer::from(certificate.cert.clone()))
+ .expect("a test root");
+ }
+
+ roots
+ }
+
+ /// The head as read, terminator included.
+ async fn read_http_head(stream: &mut (impl AsyncRead + Unpin)) -> Result, ()> {
+ let mut head = Vec::new();
+ let mut byte = [0u8; 1];
+
+ loop {
+ if head.ends_with(b"\r\n\r\n") {
+ return Ok(head);
+ }
+ if head.len() > 64 * 1024 {
+ return Err(());
+ }
+ if stream.read(&mut byte).await.map_err(|_| ())? == 0 {
+ return Err(());
+ }
+ head.push(byte[0]);
+ }
+ }
+
+ fn parse_request(head: &[u8]) -> (String, Option) {
+ let text = String::from_utf8_lossy(head);
+ let mut lines = text.split("\r\n");
+ let request_line = lines.next().unwrap_or_default().to_owned();
+ let mut host = None;
+ for line in lines {
+ if let Some((name, value)) = line.split_once(':')
+ && name.eq_ignore_ascii_case("host")
+ {
+ host = Some(value.trim().to_owned());
+ }
+ }
+
+ (request_line, host)
+ }
+
+ fn response(status: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec {
+ let mut bytes = format!("HTTP/1.1 {status}\r\n");
+ for (name, value) in headers {
+ bytes.push_str(&format!("{name}: {value}\r\n"));
+ }
+ bytes.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
+ let mut bytes = bytes.into_bytes();
+ bytes.extend_from_slice(body);
+
+ bytes
+ }
+
+ fn pubkey() -> String {
+ "ab".repeat(32)
+ }
+
+ fn document(name: &str, pubkey: &str) -> Vec {
+ format!(r#"{{"names":{{"{name}":"{pubkey}"}}}}"#).into_bytes()
+ }
+
+ fn nip05_settings(proxy: Option) -> Nip05Settings {
+ Nip05Settings {
+ mode: Nip05Mode::Enabled,
+ verify_expiration: None,
+ verify_update_frequency: None,
+ max_consecutive_failures: None,
+ domain_whitelist: None,
+ domain_blacklist: None,
+ proxy,
+ }
+ }
+
+ fn lookup(pairs: &[(&str, &str)]) -> Lookup {
+ let pairs: HashMap = pairs
+ .iter()
+ .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
+ .collect();
+
+ Box::new(move |key: &str| pairs.get(key).cloned())
+ }
+
+ fn connect_authorities(heads: &[Vec]) -> Vec {
+ heads
+ .iter()
+ .map(|head| {
+ String::from_utf8_lossy(head)
+ .split("\r\n")
+ .next()
+ .unwrap_or_default()
+ .trim_start_matches("CONNECT ")
+ .trim_end_matches(" HTTP/1.1")
+ .to_owned()
+ })
+ .collect()
+ }
+
+ async fn tunnel_head(stream: &mut BoxStream, heads: &Arc>>>) -> Vec {
+ let head = read_http_head(stream).await.expect("a CONNECT head");
+ heads.lock().unwrap().push(head.clone());
+
+ head
+ }
+
+ /// Answers the CONNECT and pipes the tunnel to the origin, as an operator's proxy does.
+ async fn accept_tunnel(stream: &mut BoxStream, origin: SocketAddr) {
+ stream
+ .write_all(b"HTTP/1.1 200 Connection established\r\n\r\n")
+ .await
+ .expect("the CONNECT reply");
+ let mut upstream = TcpStream::connect(origin)
+ .await
+ .expect("the origin answers");
+ let _ = tokio::io::copy_bidirectional(stream, &mut upstream).await;
+ }
+
+ fn bind_listener() -> (std::net::TcpListener, SocketAddr) {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
+ listener.set_nonblocking(true).expect("nonblocking");
+ let addr = listener.local_addr().expect("an address");
+
+ (listener, addr)
+ }
+
+ struct Relay {
+ addr: SocketAddr,
+ connections: Arc,
+ }
+
+ impl Relay {
+ fn port(&self) -> u16 {
+ self.addr.port()
+ }
+
+ fn proxy_url(&self) -> String {
+ format!("http://127.0.0.1:{}", self.addr.port())
+ }
+ }
+
+ /// What the relay handler recorded, in connection order.
+ fn recorded(heads: &Arc>>>) -> Vec> {
+ heads.lock().unwrap().clone()
+ }
+
+ fn spawn_relay(handler: Arc) -> Relay {
+ let (listener, addr) = bind_listener();
+ let connections = Arc::new(AtomicUsize::new(0));
+
+ {
+ let connections = Arc::clone(&connections);
+ tokio::spawn(async move {
+ let listener = tokio::net::TcpListener::from_std(listener).expect("listener");
+ loop {
+ let Ok((stream, _)) = listener.accept().await else {
+ break;
+ };
+ let index = connections.fetch_add(1, Ordering::SeqCst);
+ let handler = Arc::clone(&handler);
+ tokio::spawn(async move { handler(Box::new(stream), index).await });
+ }
+ });
+ }
+
+ Relay { addr, connections }
+ }
+
+ /// A relay reached over TLS, so an `https:` proxy URL has somewhere to land.
+ fn spawn_tls_relay(certificate: &TestCertificate, handler: Arc) -> Relay {
+ let (listener, addr) = bind_listener();
+ let acceptor = TlsAcceptor::from(server_config(certificate));
+ let connections = Arc::new(AtomicUsize::new(0));
+
+ {
+ let connections = Arc::clone(&connections);
+ tokio::spawn(async move {
+ let listener = tokio::net::TcpListener::from_std(listener).expect("listener");
+ loop {
+ let Ok((stream, _)) = listener.accept().await else {
+ break;
+ };
+ let index = connections.fetch_add(1, Ordering::SeqCst);
+ let acceptor = acceptor.clone();
+ let handler = Arc::clone(&handler);
+ tokio::spawn(async move {
+ if let Ok(tls) = acceptor.accept(stream).await {
+ handler(Box::new(tls), index).await;
+ }
+ });
+ }
+ });
+ }
+
+ Relay { addr, connections }
+ }
+
+ #[derive(Clone, Debug)]
+ struct OriginRequest {
+ sni: Option,
+ request_line: String,
+ host: Option,
+ }
+
+ #[derive(Clone)]
+ enum OriginReply {
+ Bytes(Vec),
+ /// Complete the handshake, read the request and never write.
+ Hold,
+ }
+
+ struct Origin {
+ addr: SocketAddr,
+ requests: Arc>>,
+ connections: Arc,
+ }
+
+ fn spawn_origin(certificate: &TestCertificate, respond: F) -> Origin
+ where
+ F: Fn(&OriginRequest) -> OriginReply + Send + Sync + 'static,
+ {
+ let (listener, addr) = bind_listener();
+ let acceptor = TlsAcceptor::from(server_config(certificate));
+ let respond = Arc::new(respond);
+ let requests = Arc::new(Mutex::new(Vec::new()));
+ let connections = Arc::new(AtomicUsize::new(0));
+
+ {
+ let requests = Arc::clone(&requests);
+ let connections = Arc::clone(&connections);
+ tokio::spawn(async move {
+ let listener = tokio::net::TcpListener::from_std(listener).expect("listener");
+ loop {
+ let Ok((stream, _)) = listener.accept().await else {
+ break;
+ };
+ connections.fetch_add(1, Ordering::SeqCst);
+ let acceptor = acceptor.clone();
+ let respond = Arc::clone(&respond);
+ let requests = Arc::clone(&requests);
+ tokio::spawn(async move {
+ let Ok(mut tls) = acceptor.accept(stream).await else {
+ return;
+ };
+ let sni = tls.get_ref().1.server_name().map(str::to_owned);
+ let Ok(head) = read_http_head(&mut tls).await else {
+ return;
+ };
+ let (request_line, host) = parse_request(&head);
+ let request = OriginRequest {
+ sni,
+ request_line,
+ host,
+ };
+ let reply = respond(&request);
+ requests.lock().unwrap().push(request);
+
+ match reply {
+ OriginReply::Bytes(bytes) => {
+ let _ = tls.write_all(&bytes).await;
+ }
+ OriginReply::Hold => {
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ }
+ }
+ });
+ }
+ });
+ }
+
+ Origin {
+ addr,
+ requests,
+ connections,
+ }
+ }
+
+ async fn verify_reason(client: &ReqwestClient, identifier: &str) -> String {
+ let outcome = nostream_core::nip05::verify(client, identifier, &pubkey()).await;
+ assert!(
+ matches!(outcome, VerificationOutcome::Error { .. }),
+ "expected an error, got {outcome:?}"
+ );
+ let VerificationOutcome::Error { reason } = outcome else {
+ unreachable!()
+ };
+
+ reason
+ }
+
+ fn tunnel_client(
+ resolver: Arc,
+ proxy: Option,
+ setup_timeout: Duration,
+ certificates: &[&TestCertificate],
+ ) -> ReqwestClient {
+ ReqwestClient::with_nip05_proxy_test(
+ resolver as Arc,
+ proxy,
+ setup_timeout,
+ roots(certificates),
+ )
+ .expect("client")
+ }
+
+ // --- AC4: selection ----------------------------------------------------------------
+
+ #[test]
+ fn nip05_egress_proxy_selection() {
+ let pin = nip05_settings(Some(Nip05Proxy::Pin));
+ let disabled = nip05_settings(Some(Nip05Proxy::Disabled));
+
+ assert_eq!(
+ resolve_proxy(Some(&pin), &lookup(&[("HTTPS_PROXY", "http://p:1")])),
+ Some("http://p:1".to_owned())
+ );
+ assert_eq!(
+ resolve_proxy(
+ Some(&pin),
+ &lookup(&[
+ ("HTTPS_PROXY", "http://up:1"),
+ ("https_proxy", "http://low:1")
+ ])
+ ),
+ Some("http://up:1".to_owned()),
+ "the uppercase name wins"
+ );
+ assert_eq!(
+ resolve_proxy(
+ Some(&pin),
+ &lookup(&[("HTTPS_PROXY", ""), ("https_proxy", "http://low:1")])
+ ),
+ Some("http://low:1".to_owned()),
+ "an empty value falls through"
+ );
+ assert_eq!(resolve_proxy(Some(&pin), &lookup(&[])), None);
+ assert_eq!(
+ resolve_proxy(Some(&disabled), &lookup(&[("HTTPS_PROXY", "http://p:1")])),
+ None
+ );
+ assert_eq!(
+ resolve_proxy(None, &lookup(&[("HTTPS_PROXY", "http://p:1")])),
+ None
+ );
+ assert_eq!(
+ resolve_proxy(
+ Some(&pin),
+ &lookup(&[("HTTPS_PROXY", "http://p:1"), ("NO_PROXY", "*")])
+ ),
+ Some("http://p:1".to_owned()),
+ "NO_PROXY is never read"
+ );
+ }
+
+ // --- AC5: the CONNECT request ------------------------------------------------------
+
+ #[test]
+ fn nip05_egress_connect_request() {
+ let proxy = parse_proxy("http://127.0.0.1:3128").expect("an http proxy");
+ let v4: IpAddr = "93.184.216.34".parse().expect("an address");
+ let v6: IpAddr = "2606:4700::1".parse().expect("an address");
+
+ assert_eq!(
+ proxy.connect_request(&authority(v4, 443)),
+ b"CONNECT 93.184.216.34:443 HTTP/1.1\r\nHost: 93.184.216.34:443\r\n\r\n".to_vec()
+ );
+ assert_eq!(
+ proxy.connect_request(&authority(v6, 443)),
+ b"CONNECT [2606:4700::1]:443 HTTP/1.1\r\nHost: [2606:4700::1]:443\r\n\r\n".to_vec()
+ );
+
+ let url =
+ reqwest::Url::parse("https://good.example:8443/.well-known/nostr.json?name=alice")
+ .expect("a url");
+ assert_eq!(target_port(&url), 8443);
+ assert_eq!(
+ proxy.connect_request(&authority(v4, target_port(&url))),
+ b"CONNECT 93.184.216.34:8443 HTTP/1.1\r\nHost: 93.184.216.34:8443\r\n\r\n".to_vec()
+ );
+
+ let credentials = parse_proxy("http://relay:p%40ss@127.0.0.1:3128").expect("an http proxy");
+ assert_eq!(
+ credentials.connect_request(&authority(v4, 443)),
+ b"CONNECT 93.184.216.34:443 HTTP/1.1\r\nHost: 93.184.216.34:443\r\nProxy-Authorization: Basic cmVsYXk6cEBzcw==\r\n\r\n".to_vec()
+ );
+
+ let error = parse_proxy("socks5://127.0.0.1:1080").expect_err("socks is refused");
+ assert_eq!(
+ error.to_string(),
+ "unsupported proxy protocol socks5: for NIP-05"
+ );
+ }
+
+ // --- AC6: the pin is used ----------------------------------------------------------
+
+ #[tokio::test]
+ async fn nip05_egress_pin_reaches_the_origin_by_its_address() {
+ let origin_certificate = certificate("good.example", "DNS:good.example");
+ let public_key = pubkey();
+ let body = document("alice", &public_key);
+ let origin = spawn_origin(&origin_certificate, {
+ let body = body.clone();
+ move |_| OriginReply::Bytes(response("200 OK", &[], &body))
+ });
+ let origin_addr = origin.addr;
+
+ let heads = Arc::new(Mutex::new(Vec::new()));
+ let relay = spawn_relay(Arc::new({
+ let heads = Arc::clone(&heads);
+ move |mut stream: BoxStream, _: usize| {
+ let heads = Arc::clone(&heads);
+ Box::pin(async move {
+ tunnel_head(&mut stream, &heads).await;
+ accept_tunnel(&mut stream, origin_addr).await;
+ }) as Pin + Send>>
+ }
+ }));
+
+ let resolver = FakeResolver::new(&[("good.example", &["203.0.113.7"])]);
+ let settings = nip05_settings(Some(Nip05Proxy::Pin));
+ let proxy_url = relay.proxy_url();
+ let proxy = resolve_proxy(Some(&settings), &lookup(&[("HTTPS_PROXY", &proxy_url)]));
+ assert_eq!(proxy, Some(proxy_url));
+
+ let client = tunnel_client(
+ Arc::clone(&resolver),
+ proxy,
+ Duration::from_secs(5),
+ &[&origin_certificate],
+ );
+ let outcome =
+ nostream_core::nip05::verify(&client, "alice@good.example", &public_key).await;
+ assert_eq!(outcome, VerificationOutcome::Verified);
+
+ assert_eq!(relay.connections.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ recorded(&heads),
+ vec![b"CONNECT 203.0.113.7:443 HTTP/1.1\r\nHost: 203.0.113.7:443\r\n\r\n".to_vec()],
+ "the proxy is told the checked address, and nothing else"
+ );
+
+ let requests = origin.requests.lock().unwrap().clone();
+ assert_eq!(requests.len(), 1);
+ assert_eq!(requests[0].sni.as_deref(), Some("good.example"));
+ assert_eq!(
+ requests[0].request_line,
+ "GET /.well-known/nostr.json?name=alice HTTP/1.1"
+ );
+ assert_eq!(requests[0].host.as_deref(), Some("good.example"));
+ }
+
+ // --- AC7: the authority carries the address, and an alien name is refused ----------
+
+ #[tokio::test]
+ async fn nip05_egress_a_misrouted_tunnel_is_refused() {
+ let origin_certificate = certificate("other.example", "DNS:other.example");
+ let origin = spawn_origin(&origin_certificate, |_| {
+ OriginReply::Bytes(response("200 OK", &[], b"{}"))
+ });
+ let origin_addr = origin.addr;
+
+ let heads = Arc::new(Mutex::new(Vec::new()));
+ let relay = spawn_relay(Arc::new({
+ let heads = Arc::clone(&heads);
+ move |mut stream: BoxStream, _: usize| {
+ let heads = Arc::clone(&heads);
+ Box::pin(async move {
+ let head = tunnel_head(&mut stream, &heads).await;
+ let authority = String::from_utf8_lossy(&head)
+ .split("\r\n")
+ .next()
+ .unwrap_or_default()
+ .trim_start_matches("CONNECT ")
+ .trim_end_matches(" HTTP/1.1")
+ .to_owned();
+ if authority == "203.0.113.7:443" {
+ accept_tunnel(&mut stream, origin_addr).await;
+ } else {
+ let _ = stream.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await;
+ }
+ }) as Pin + Send>>
+ }
+ }));
+
+ let resolver = FakeResolver::new(&[("good.example", &["203.0.113.7"])]);
+ let client = tunnel_client(
+ resolver,
+ Some(relay.proxy_url()),
+ Duration::from_secs(5),
+ &[&origin_certificate],
+ );
+
+ let reason = verify_reason(&client, "alice@good.example").await;
+ assert!(
+ reason.contains("NotValidForName") || reason.contains("not valid for name"),
+ "{reason}"
+ );
+
+ assert_eq!(recorded(&heads).len(), 1);
+ assert_eq!(
+ recorded(&heads),
+ vec![b"CONNECT 203.0.113.7:443 HTTP/1.1\r\nHost: 203.0.113.7:443\r\n\r\n".to_vec()]
+ );
+ assert!(
+ origin.requests.lock().unwrap().is_empty(),
+ "no request byte may follow a name mismatch"
+ );
+ }
+
+ // --- AC8: a certificate for another name is refused --------------------------------
+
+ #[tokio::test]
+ async fn nip05_egress_a_certificate_for_another_name_is_refused() {
+ let origin_certificate = certificate("good.example", "DNS:good.example");
+ let origin = spawn_origin(&origin_certificate, |_| {
+ OriginReply::Bytes(response("200 OK", &[], b"{}"))
+ });
+ let origin_addr = origin.addr;
+
+ let heads = Arc::new(Mutex::new(Vec::new()));
+ let relay = spawn_relay(Arc::new({
+ let heads = Arc::clone(&heads);
+ move |mut stream: BoxStream, _: usize| {
+ let heads = Arc::clone(&heads);
+ Box::pin(async move {
+ tunnel_head(&mut stream, &heads).await;
+ accept_tunnel(&mut stream, origin_addr).await;
+ }) as Pin + Send>>
+ }
+ }));
+
+ let resolver = FakeResolver::new(&[("other.example", &["203.0.113.8"])]);
+ let client = tunnel_client(
+ resolver,
+ Some(relay.proxy_url()),
+ Duration::from_secs(5),
+ &[&origin_certificate],
+ );
+
+ let reason = verify_reason(&client, "alice@other.example").await;
+ assert!(
+ reason.contains("NotValidForName") || reason.contains("not valid for name"),
+ "{reason}"
+ );
+
+ assert_eq!(
+ recorded(&heads),
+ vec![b"CONNECT 203.0.113.8:443 HTTP/1.1\r\nHost: 203.0.113.8:443\r\n\r\n".to_vec()]
+ );
+ assert!(origin.requests.lock().unwrap().is_empty());
+ }
+
+ // --- AC9: a refused or unreachable proxy fails closed ------------------------------
+
+ #[tokio::test]
+ async fn nip05_egress_a_refused_or_unreachable_proxy_fails_closed() {
+ let origin_certificate = certificate("good.example", "DNS:good.example");
+ let origin = spawn_origin(&origin_certificate, |_| {
+ OriginReply::Bytes(response("200 OK", &[], b"{}"))
+ });
+
+ let relay = spawn_relay(Arc::new(|mut stream: BoxStream, _: usize| {
+ Box::pin(async move {
+ let _ = read_http_head(&mut stream).await;
+ let _ = stream.write_all(b"HTTP/1.1 403 Forbidden\r\n\r\n").await;
+ }) as Pin + Send>>
+ }));
+
+ let resolver = FakeResolver::new(&[("good.example", &["203.0.113.7"])]);
+ let client = tunnel_client(
+ Arc::clone(&resolver),
+ Some(relay.proxy_url()),
+ Duration::from_secs(5),
+ &[&origin_certificate],
+ );
+ let reason = verify_reason(&client, "alice@good.example").await;
+ assert!(
+ reason.contains(&format!(
+ "proxy 127.0.0.1:{} refused CONNECT to good.example: HTTP/1.1 403 Forbidden",
+ relay.port()
+ )),
+ "{reason}"
+ );
+ assert_eq!(relay.connections.load(Ordering::SeqCst), 1);
+ assert_eq!(resolver.asked(), vec!["good.example".to_owned()]);
+ assert!(origin.requests.lock().unwrap().is_empty());
+ assert_eq!(origin.connections.load(Ordering::SeqCst), 0);
+
+ // (b) no listener at the proxy's address
+ let (listener, addr) = bind_listener();
+ drop(listener);
+ let resolver = FakeResolver::new(&[("good.example", &["203.0.113.7"])]);
+ let client = tunnel_client(
+ resolver,
+ Some(format!("http://{addr}")),
+ Duration::from_secs(5),
+ &[&origin_certificate],
+ );
+ let reason = verify_reason(&client, "alice@good.example").await;
+ assert!(
+ reason.contains(&format!(
+ "could not reach proxy 127.0.0.1:{} for good.example",
+ addr.port()
+ )),
+ "{reason}"
+ );
+ assert!(origin.requests.lock().unwrap().is_empty());
+ assert_eq!(origin.connections.load(Ordering::SeqCst), 0);
+ }
+
+ // --- AC10: a refused address moves on ---------------------------------------------
+
+ #[tokio::test]
+ async fn nip05_egress_a_refused_address_moves_on() {
+ let origin_certificate = certificate("good.example", "DNS:good.example");
+ let public_key = pubkey();
+ let body = document("alice", &public_key);
+ let origin = spawn_origin(&origin_certificate, {
+ let body = body.clone();
+ move |_| OriginReply::Bytes(response("200 OK", &[], &body))
+ });
+ let origin_addr = origin.addr;
+
+ let heads = Arc::new(Mutex::new(Vec::new()));
+ let relay = spawn_relay(Arc::new({
+ let heads = Arc::clone(&heads);
+ move |mut stream: BoxStream, index: usize| {
+ let heads = Arc::clone(&heads);
+ Box::pin(async move {
+ tunnel_head(&mut stream, &heads).await;
+ if index == 0 {
+ let _ = stream.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await;
+ } else {
+ accept_tunnel(&mut stream, origin_addr).await;
+ }
+ }) as Pin + Send>>
+ }
+ }));
+
+ let resolver = FakeResolver::new(&[("good.example", &["203.0.113.7", "203.0.113.9"])]);
+ let client = tunnel_client(
+ resolver,
+ Some(relay.proxy_url()),
+ Duration::from_secs(5),
+ &[&origin_certificate],
+ );
+
+ let outcome =
+ nostream_core::nip05::verify(&client, "alice@good.example", &public_key).await;
+ assert_eq!(outcome, VerificationOutcome::Verified);
+ assert_eq!(
+ connect_authorities(&recorded(&heads)),
+ vec!["203.0.113.7:443".to_owned(), "203.0.113.9:443".to_owned()]
+ );
+ assert_eq!(relay.connections.load(Ordering::SeqCst), 2);
+ }
+
+ // --- AC11: one private address refuses the name before the proxy -------------------
+
+ #[tokio::test]
+ async fn nip05_egress_a_name_with_a_private_address_is_refused() {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind");
+ let addr = listener.local_addr().expect("an address");
+
+ let resolver = FakeResolver::new(&[("rebind.example", &["203.0.113.7", "127.0.0.1"])]);
+ let client = tunnel_client(
+ Arc::clone(&resolver),
+ Some(format!("http://{addr}")),
+ Duration::from_secs(1),
+ &[],
+ );
+
+ let reason = verify_reason(&client, "alice@rebind.example").await;
+ assert_eq!(
+ reason,
+ "refused NIP-05 target rebind.example resolving to a private address"
+ );
+ assert!(
+ tokio::time::timeout(Duration::from_millis(300), listener.accept())
+ .await
+ .is_err(),
+ "the proxy was contacted for a name with a private address"
+ );
+ assert_eq!(resolver.asked(), vec!["rebind.example".to_owned()]);
+ }
+
+ // --- AC12: the setup deadline closes the proxy socket -----------------------------
+
+ #[tokio::test]
+ async fn nip05_egress_setup_deadline_closes_the_proxy_socket() {
+ let closed = Arc::new(AtomicBool::new(false));
+ let relay = spawn_relay(Arc::new({
+ let closed = Arc::clone(&closed);
+ move |mut stream: BoxStream, _: usize| {
+ let closed = Arc::clone(&closed);
+ Box::pin(async move {
+ let _ = read_http_head(&mut stream).await;
+ let mut byte = [0u8; 1];
+ if let Ok(Ok(0)) =
+ tokio::time::timeout(Duration::from_secs(1), stream.read(&mut byte)).await
+ {
+ closed.store(true, Ordering::SeqCst);
+ }
+ }) as Pin + Send>>
+ }
+ }));
+
+ let resolver = FakeResolver::new(&[("good.example", &["203.0.113.7"])]);
+ let client = tunnel_client(
+ resolver,
+ Some(relay.proxy_url()),
+ Duration::from_millis(200),
+ &[],
+ );
+
+ let reason = verify_reason(&client, "alice@good.example").await;
+ assert_eq!(
+ reason,
+ format!(
+ "timed out setting up a tunnel to good.example through proxy 127.0.0.1:{}",
+ relay.port()
+ )
+ );
+ assert_eq!(relay.connections.load(Ordering::SeqCst), 1);
+
+ for _ in 0..50 {
+ if closed.load(Ordering::SeqCst) {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ assert!(closed.load(Ordering::SeqCst), "the proxy saw no EOF");
+ }
+
+ // --- AC13: the CONNECT reply head is capped independently of chunking --------------
+
+ /// A reply whose head is exactly `head_len` bytes before its terminator: the last header
+ /// line's CRLF is the first two bytes of that terminator, as on the wire.
+ fn padded_head(head_len: usize) -> Vec {
+ let status = "HTTP/1.1 200 Connection established\r\n";
+ let prefix = "X-Pad: ";
+ let padding = head_len - status.len() - prefix.len();
+ let head = format!("{status}{prefix}{}", "a".repeat(padding));
+ assert_eq!(head.len(), head_len);
+
+ head.into_bytes()
+ }
+
+ #[tokio::test]
+ async fn nip05_egress_the_connect_reply_head_is_capped() {
+ let origin_certificate = certificate("good.example", "DNS:good.example");
+ let public_key = pubkey();
+ let body = document("alice", &public_key);
+ let origin = spawn_origin(&origin_certificate, {
+ let body = body.clone();
+ move |_| OriginReply::Bytes(response("200 OK", &[], &body))
+ });
+ let origin_addr = origin.addr;
+
+ let plans = Arc::new(Mutex::new(Vec::<(usize, usize)>::new()));
+ let tls_after_refusal = Arc::new(Mutex::new(Vec::::new()));
+ let heads = Arc::new(Mutex::new(Vec::new()));
+ let relay = spawn_relay(Arc::new({
+ let plans = Arc::clone(&plans);
+ let heads = Arc::clone(&heads);
+ let tls_after_refusal = Arc::clone(&tls_after_refusal);
+ move |mut stream: BoxStream, index: usize| {
+ let plans = Arc::clone(&plans);
+ let heads = Arc::clone(&heads);
+ let tls_after_refusal = Arc::clone(&tls_after_refusal);
+ Box::pin(async move {
+ tunnel_head(&mut stream, &heads).await;
+ let (head_len, at) = plans.lock().unwrap()[index];
+ let mut reply = padded_head(head_len);
+ reply.extend_from_slice(b"\r\n\r\n");
+ let (first, second) = reply.split_at(at);
+ let _ = stream.write_all(first).await;
+ tokio::time::sleep(Duration::from_millis(1)).await;
+ let _ = stream.write_all(second).await;
+
+ if head_len <= 8192 {
+ let mut upstream = TcpStream::connect(origin_addr)
+ .await
+ .expect("the origin answers");
+ let _ = tokio::io::copy_bidirectional(&mut stream, &mut upstream).await;
+ } else {
+ let mut byte = [0u8; 1];
+ let saw_tls = matches!(
+ tokio::time::timeout(
+ Duration::from_secs(1),
+ stream.read(&mut byte)
+ )
+ .await,
+ Ok(Ok(read)) if read > 0
+ );
+ tls_after_refusal.lock().unwrap().push(saw_tls);
+ }
+ }) as Pin + Send>>
+ }
+ }));
+
+ let resolver = FakeResolver::new(&[("good.example", &["203.0.113.7"])]);
+ let client = tunnel_client(
+ resolver,
+ Some(relay.proxy_url()),
+ Duration::from_secs(5),
+ &[&origin_certificate],
+ );
+ let url = "https://good.example/.well-known/nostr.json?name=alice";
+
+ for offset in 0..=4 {
+ plans.lock().unwrap().push((8192, 8192 + offset));
+ let outcome = Nip05Fetch::get(&client, url, 2_000, 64 * 1024, 1)
+ .await
+ .map_err(|error| format!("offset {offset}: {error}"))
+ .expect("a head of 8192 is accepted");
+ assert_eq!(
+ outcome,
+ FetchOutcome {
+ status: 200,
+ body: body.clone()
+ },
+ "offset {offset}"
+ );
+ }
+
+ for offset in 0..=4 {
+ plans.lock().unwrap().push((8193, 8193 + offset));
+ let error = Nip05Fetch::get(&client, url, 2_000, 64 * 1024, 1)
+ .await
+ .expect_err("a head of 8193 is refused");
+ assert!(
+ error
+ .to_string()
+ .contains("refused CONNECT to good.example: response too large"),
+ "offset {offset}: {error}"
+ );
+ }
+
+ for _ in 0..100 {
+ if tls_after_refusal.lock().unwrap().len() == 5 {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ assert_eq!(
+ tls_after_refusal.lock().unwrap().clone(),
+ vec![false; 5],
+ "no TLS byte may follow a refused head"
+ );
+ }
+
+ // --- AC14: redirects are checked and pinned again ---------------------------------
+
+ #[tokio::test]
+ async fn nip05_egress_a_redirect_is_checked_and_pinned_again() {
+ let origin_certificate = certificate("good.example", "DNS:good.example,DNS:second.example");
+ let public_key = pubkey();
+ let body = document("alice", &public_key);
+ let script = Arc::new(Mutex::new(VecDeque::::new()));
+ let origin = spawn_origin(&origin_certificate, {
+ let script = Arc::clone(&script);
+ move |_| {
+ script
+ .lock()
+ .unwrap()
+ .pop_front()
+ .expect("a scripted reply")
+ }
+ });
+ let origin_addr = origin.addr;
+
+ let heads = Arc::new(Mutex::new(Vec::new()));
+ let relay = spawn_relay(Arc::new({
+ let heads = Arc::clone(&heads);
+ move |mut stream: BoxStream, _: usize| {
+ let heads = Arc::clone(&heads);
+ Box::pin(async move {
+ tunnel_head(&mut stream, &heads).await;
+ accept_tunnel(&mut stream, origin_addr).await;
+ }) as Pin + Send>>
+ }
+ }));
+
+ let resolver = FakeResolver::new(&[
+ ("good.example", &["203.0.113.7"]),
+ ("second.example", &["203.0.113.9"]),
+ ("private.example", &["203.0.113.10", "127.0.0.1"]),
+ ]);
+ let client = tunnel_client(
+ resolver,
+ Some(relay.proxy_url()),
+ Duration::from_secs(5),
+ &[&origin_certificate],
+ );
+
+ let location = "https://second.example/.well-known/nostr.json?name=alice";
+ let redirect = |location: &str| {
+ OriginReply::Bytes(response("302 Found", &[("Location", location)], b""))
+ };
+
+ // (a) one hop, pinned to the target's own address and name
+ script.lock().unwrap().push_back(redirect(location));
+ script
+ .lock()
+ .unwrap()
+ .push_back(OriginReply::Bytes(response("200 OK", &[], &body)));
+ let before = recorded(&heads).len();
+ let outcome =
+ nostream_core::nip05::verify(&client, "alice@good.example", &public_key).await;
+ assert_eq!(outcome, VerificationOutcome::Verified);
+ assert_eq!(
+ connect_authorities(&recorded(&heads)[before..]),
+ vec!["203.0.113.7:443".to_owned(), "203.0.113.9:443".to_owned()]
+ );
+ let sni: Vec<_> = origin
+ .requests
+ .lock()
+ .unwrap()
+ .iter()
+ .filter_map(|request| request.sni.clone())
+ .collect();
+ assert_eq!(
+ sni,
+ vec!["good.example".to_owned(), "second.example".to_owned()]
+ );
+
+ // (b) a second hop is beyond the budget
+ script.lock().unwrap().push_back(redirect(location));
+ script
+ .lock()
+ .unwrap()
+ .push_back(redirect("https://good.example/again"));
+ let before = recorded(&heads).len();
+ let reason = verify_reason(&client, "alice@good.example").await;
+ assert_eq!(reason, "too many redirects");
+ assert_eq!(recorded(&heads).len() - before, 2);
+
+ // (c) an unsafe target is refused after one CONNECT
+ for target in [
+ "https://localhost/x",
+ "https://[::1]/x",
+ "http://insecure.example/x",
+ ] {
+ script.lock().unwrap().push_back(redirect(target));
+ let before = recorded(&heads).len();
+ let reason = verify_reason(&client, "alice@good.example").await;
+ assert_eq!(
+ reason,
+ format!("refused redirect to unsafe target: {target}")
+ );
+ assert_eq!(recorded(&heads).len() - before, 1, "{target}");
+ }
+
+ // (d) a target whose own addresses include a private one is refused before the proxy
+ script
+ .lock()
+ .unwrap()
+ .push_back(redirect("https://private.example/x"));
+ let before = recorded(&heads).len();
+ let reason = verify_reason(&client, "alice@good.example").await;
+ assert_eq!(
+ reason,
+ "refused NIP-05 target private.example resolving to a private address"
+ );
+ assert!(
+ !connect_authorities(&recorded(&heads)[before..])
+ .iter()
+ .any(|authority| authority.starts_with("203.0.113.10"))
+ );
+
+ // (e) a 3xx without `Location` is a status
+ script
+ .lock()
+ .unwrap()
+ .push_back(OriginReply::Bytes(response("302 Found", &[], b"")));
+ let reason = verify_reason(&client, "alice@good.example").await;
+ assert_eq!(reason, "HTTP status 302");
+ }
+
+ // --- AC15: disabled never opens the proxy, pin does --------------------------------
+
+ #[tokio::test]
+ async fn nip05_egress_disabled_never_opens_the_proxy() {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind");
+ let addr = listener.local_addr().expect("an address");
+ let proxy_url = format!("http://{addr}");
+ let env = lookup(&[("HTTPS_PROXY", &proxy_url)]);
+
+ let disabled = nip05_settings(Some(Nip05Proxy::Disabled));
+ let selection = resolve_proxy(Some(&disabled), &env);
+ assert_eq!(selection, None);
+
+ let resolver = FakeResolver::new(&[("intranet.test", &["127.0.0.1"])]);
+ let client = tunnel_client(resolver, selection, Duration::from_secs(1), &[]);
+ let error = Nip05Fetch::get(
+ &client,
+ "https://intranet.test/.well-known/nostr.json?name=alice",
+ 300,
+ 4_096,
+ 1,
+ )
+ .await
+ .expect_err("a private address is refused");
+ assert!(
+ error
+ .to_string()
+ .contains("refusing to resolve intranet.test"),
+ "{error}"
+ );
+ assert!(
+ tokio::time::timeout(Duration::from_millis(300), listener.accept())
+ .await
+ .is_err(),
+ "the disabled client dialled the proxy"
+ );
+
+ // the control: same listener, same settings, `pin`
+ let pinned = nip05_settings(Some(Nip05Proxy::Pin));
+ let selection = resolve_proxy(Some(&pinned), &env);
+ assert_eq!(selection, Some(proxy_url));
+ let resolver = FakeResolver::new(&[("good.example", &["203.0.113.7"])]);
+ let client = tunnel_client(resolver, selection, Duration::from_secs(1), &[]);
+ let fetch_client = client.clone();
+ let fetch = tokio::spawn(async move {
+ Nip05Fetch::get(
+ &fetch_client,
+ "https://good.example/.well-known/nostr.json?name=alice",
+ 300,
+ 4_096,
+ 1,
+ )
+ .await
+ });
+
+ let (mut stream, _) = tokio::time::timeout(Duration::from_secs(2), listener.accept())
+ .await
+ .expect("the control reaches the proxy")
+ .expect("accept");
+ let head = read_http_head(&mut stream).await.expect("a CONNECT head");
+ assert!(
+ head.starts_with(b"CONNECT 203.0.113.7:443 HTTP/1.1\r\n"),
+ "{}",
+ String::from_utf8_lossy(&head)
+ );
+ assert!(
+ tokio::time::timeout(Duration::from_millis(300), listener.accept())
+ .await
+ .is_err(),
+ "exactly one connection"
+ );
+ let _ = fetch.await;
+ }
+
+ // --- AC16: HTTPS_PROXY is seen and ignored unless the mode is pin ------------------
+
+ /// The proof runs in a child process, so `cargo test --workspace` — which cannot export a
+ /// variable for one test — still runs it. The child is this binary with `--exact` and the
+ /// one test name, a real `HTTPS_PROXY`, and a marker; the marker is a recursion guard only,
+ /// and the branch that sees it runs the assertions (it never spawns). The parent asserts the
+ /// child's stdio names that test as `ok` and reports `1 passed`, because a child whose
+ /// filter matched nothing would exit 0 having proved nothing.
+ #[test]
+ fn nip05_egress_disabled_ignores_https_proxy() {
+ if std::env::var("NIP05_EGRESS_CHILD").is_ok() {
+ prove_disabled_ignores_https_proxy();
+ } else {
+ let binary = std::env::current_exe().expect("the test binary");
+ let output = std::process::Command::new(binary)
+ .args([
+ "--exact",
+ "http::tests::nip05_egress_disabled_ignores_https_proxy",
+ ])
+ .env("NIP05_EGRESS_CHILD", "1")
+ .env("HTTPS_PROXY", "http://192.0.2.1:3128")
+ .env("RUST_BACKTRACE", "1")
+ .env_remove("https_proxy")
+ .output()
+ .expect("spawn the child proof");
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let printed = || format!("--- stdout\n{stdout}\n--- stderr\n{stderr}");
+
+ assert!(
+ output.status.success(),
+ "the child proof failed ({}):\n{}",
+ output.status,
+ printed()
+ );
+ assert!(
+ stdout
+ .contains("test http::tests::nip05_egress_disabled_ignores_https_proxy ... ok"),
+ "the child ran the wrong test ({}):\n{}",
+ output.status,
+ printed()
+ );
+ assert!(
+ stdout.contains("1 passed; 0 failed"),
+ "the child proved nothing ({}):\n{}",
+ output.status,
+ printed()
+ );
+ }
+ }
+
+ fn prove_disabled_ignores_https_proxy() {
+ assert!(
+ std::env::var("HTTPS_PROXY").is_ok_and(|value| !value.is_empty()),
+ "the child runs with HTTPS_PROXY set by its parent"
+ );
+ let configured = std::env::var("HTTPS_PROXY").expect("the variable is set");
+ let proxy_host = reqwest::Url::parse(&configured)
+ .expect("a proxy URL")
+ .host_str()
+ .expect("a host")
+ .to_owned();
+
+ let settings = Nip05Settings {
+ mode: Nip05Mode::Disabled,
+ verify_expiration: None,
+ verify_update_frequency: None,
+ max_consecutive_failures: None,
+ domain_whitelist: None,
+ domain_blacklist: None,
+ proxy: None,
+ };
+ let selection = resolve_proxy(Some(&settings), &|key| std::env::var(key).ok());
+ assert_eq!(selection, None);
+
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("the child runtime");
+ runtime.block_on(async {
+ let resolver = FakeResolver::new(&[("intranet.test", &["127.0.0.1"])]);
+ let client = ReqwestClient::with_nip05_proxy(resolver as Arc, selection)
+ .expect("client");
+ let started = Instant::now();
+ let error = Nip05Fetch::get(
+ &client,
+ "https://intranet.test/.well-known/nostr.json?name=alice",
+ 300,
+ 4_096,
+ 1,
+ )
+ .await
+ .expect_err("a private address is refused");
+ let reason = error.to_string();
+
+ assert!(
+ reason.contains("refusing to resolve intranet.test"),
+ "{reason}"
+ );
+ assert!(
+ !reason.contains(&proxy_host),
+ "the direct path went through {proxy_host}: {reason}"
+ );
+ assert!(started.elapsed() < Duration::from_secs(2), "{reason}");
+ });
+ }
+
+ // --- AC17: an https proxy is reached over TLS -------------------------------------
+
+ #[tokio::test]
+ async fn nip05_egress_an_https_proxy_is_reached_over_tls() {
+ let proxy_certificate = certificate("127.0.0.1", "IP:127.0.0.1");
+ let origin_certificate = certificate("good.example", "DNS:good.example");
+ let public_key = pubkey();
+ let body = document("alice", &public_key);
+ let origin = spawn_origin(&origin_certificate, {
+ let body = body.clone();
+ move |_| OriginReply::Bytes(response("200 OK", &[], &body))
+ });
+ let origin_addr = origin.addr;
+
+ let heads = Arc::new(Mutex::new(Vec::new()));
+ let relay = spawn_tls_relay(
+ &proxy_certificate,
+ Arc::new({
+ let heads = Arc::clone(&heads);
+ move |mut stream: BoxStream, _: usize| {
+ let heads = Arc::clone(&heads);
+ Box::pin(async move {
+ tunnel_head(&mut stream, &heads).await;
+ accept_tunnel(&mut stream, origin_addr).await;
+ }) as Pin + Send>>
+ }
+ }),
+ );
+
+ let resolver = FakeResolver::new(&[("good.example", &["203.0.113.7"])]);
+ let client = tunnel_client(
+ resolver,
+ Some(format!("https://127.0.0.1:{}", relay.port())),
+ Duration::from_secs(5),
+ &[&proxy_certificate, &origin_certificate],
+ );
+
+ let outcome =
+ nostream_core::nip05::verify(&client, "alice@good.example", &public_key).await;
+ assert_eq!(outcome, VerificationOutcome::Verified);
+ assert_eq!(
+ recorded(&heads),
+ vec![b"CONNECT 203.0.113.7:443 HTTP/1.1\r\nHost: 203.0.113.7:443\r\n\r\n".to_vec()]
+ );
+ assert_eq!(
+ origin.requests.lock().unwrap()[0].sni.as_deref(),
+ Some("good.example")
+ );
+ }
+
+ // --- AC18: the body cap and the request deadline ----------------------------------
+
+ #[tokio::test]
+ async fn nip05_egress_the_body_cap_and_the_request_deadline() {
+ let origin_certificate = certificate("good.example", "DNS:good.example");
+ let oversized = response("200 OK", &[], &vec![b'x'; 4_097]);
+ let script = Arc::new(Mutex::new(VecDeque::from([
+ OriginReply::Bytes(oversized),
+ OriginReply::Hold,
+ ])));
+ let origin = spawn_origin(&origin_certificate, {
+ let script = Arc::clone(&script);
+ move |_| {
+ script
+ .lock()
+ .unwrap()
+ .pop_front()
+ .expect("a scripted reply")
+ }
+ });
+ let origin_addr = origin.addr;
+
+ let relay = spawn_relay(Arc::new(move |mut stream: BoxStream, _: usize| {
+ Box::pin(async move {
+ let _ = read_http_head(&mut stream).await;
+ accept_tunnel(&mut stream, origin_addr).await;
+ }) as Pin + Send>>
+ }));
+
+ let resolver = FakeResolver::new(&[("good.example", &["203.0.113.7"])]);
+ let client = tunnel_client(
+ resolver,
+ Some(relay.proxy_url()),
+ Duration::from_secs(5),
+ &[&origin_certificate],
+ );
+ let url = "https://good.example/.well-known/nostr.json?name=alice";
+
+ let error = Nip05Fetch::get(&client, url, 2_000, 4_096, 1)
+ .await
+ .expect_err("a body over the cap");
+ assert_eq!(error.to_string(), "response body exceeds 4096 bytes");
+
+ let started = Instant::now();
+ let error = Nip05Fetch::get(&client, url, 200, 64 * 1024, 1)
+ .await
+ .expect_err("a silent origin times out");
+ assert!(
+ error
+ .to_string()
+ .contains("timed out after 200 ms fetching"),
+ "{error}"
+ );
+ assert!(started.elapsed() < Duration::from_secs(2));
+ }
+
+ // --- AC22: `proxy: null` loads and means disabled ---------------------------------
+
+ #[tokio::test]
+ async fn nip05_egress_null_proxy_never_opens_the_proxy() {
+ let config_dir = tempfile::TempDir::new().expect("tempdir");
+ let settings_file = config_dir.path().join("settings.yaml");
+ std::fs::write(&settings_file, "nip05:\n mode: enabled\n proxy: null\n")
+ .expect("the document");
+ let paths = nostream_config::SettingsPaths::from_config_dir(
+ std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../..")),
+ config_dir.path(),
+ );
+ let outcome = nostream_config::load(&paths).expect("the settings load");
+ assert_eq!(outcome.issues, Vec::new());
+ assert!(!outcome.used_defaults);
+ let settings = outcome.settings;
+ assert_eq!(settings.nip05.as_ref().and_then(|nip05| nip05.proxy), None);
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind");
+ let addr = listener.local_addr().expect("an address");
+ let env = lookup(&[("HTTPS_PROXY", &format!("http://{addr}"))]);
+ let selection = resolve_proxy(settings.nip05.as_ref(), &env);
+ assert_eq!(selection, None);
+
+ let resolver = FakeResolver::new(&[("intranet.test", &["127.0.0.1"])]);
+ let client = tunnel_client(resolver, selection, Duration::from_secs(1), &[]);
+ let error = Nip05Fetch::get(
+ &client,
+ "https://intranet.test/.well-known/nostr.json?name=alice",
+ 300,
+ 4_096,
+ 1,
+ )
+ .await
+ .expect_err("a private address is refused");
+ assert!(
+ error
+ .to_string()
+ .contains("refusing to resolve intranet.test"),
+ "{error}"
+ );
+ assert!(
+ tokio::time::timeout(Duration::from_millis(300), listener.accept())
+ .await
+ .is_err(),
+ "the null proxy dialled the listener"
+ );
+
+ // the control: the same document with `proxy: pin`
+ std::fs::write(&settings_file, "nip05:\n mode: enabled\n proxy: pin\n")
+ .expect("the document");
+ let outcome = nostream_config::load(&paths).expect("the settings load");
+ let settings = outcome.settings;
+ let env = lookup(&[("HTTPS_PROXY", &format!("http://{addr}"))]);
+ let selection = resolve_proxy(settings.nip05.as_ref(), &env);
+ assert!(selection.is_some());
+
+ let resolver = FakeResolver::new(&[("good.example", &["203.0.113.7"])]);
+ let client = tunnel_client(resolver, selection, Duration::from_secs(1), &[]);
+ let fetch_client = client.clone();
+ let fetch = tokio::spawn(async move {
+ Nip05Fetch::get(
+ &fetch_client,
+ "https://good.example/.well-known/nostr.json?name=alice",
+ 300,
+ 4_096,
+ 1,
+ )
+ .await
+ });
+
+ let (mut stream, _) = tokio::time::timeout(Duration::from_secs(2), listener.accept())
+ .await
+ .expect("the control reaches the proxy")
+ .expect("accept");
+ let head = read_http_head(&mut stream).await.expect("a CONNECT head");
+ assert!(
+ head.starts_with(b"CONNECT 203.0.113.7:443 HTTP/1.1\r\n"),
+ "{}",
+ String::from_utf8_lossy(&head)
+ );
+ assert!(
+ tokio::time::timeout(Duration::from_millis(300), listener.accept())
+ .await
+ .is_err(),
+ "exactly one connection"
+ );
+ let _ = fetch.await;
+ }
}
diff --git a/crates/nostream-services/src/lib.rs b/crates/nostream-services/src/lib.rs
index b81d2b56d..9693c1a3d 100644
--- a/crates/nostream-services/src/lib.rs
+++ b/crates/nostream-services/src/lib.rs
@@ -38,6 +38,7 @@ pub mod error;
pub mod http;
pub mod invoice;
pub mod monitor;
+pub mod nip05_egress;
pub mod payments;
pub mod process;
pub mod scheduler;
diff --git a/crates/nostream-services/src/nip05_egress.rs b/crates/nostream-services/src/nip05_egress.rs
new file mode 100644
index 000000000..5456978c1
--- /dev/null
+++ b/crates/nostream-services/src/nip05_egress.rs
@@ -0,0 +1,538 @@
+//! NIP-05 egress through an operator's HTTP or HTTPS proxy with a pinned address.
+//!
+//! This is v3's `PinnedProxyAgent` (`origin/main:src/utils/pinned-proxy-agent.ts:51`, read at
+//! `943fd7a2` — the rewrite's v3 basis, `origin/main`, not the capture commit): the host is
+//! resolved here, every address is checked, and the proxy is asked for `CONNECT :443`
+//! with the address that was checked, so the proxy can only connect where this relay validated.
+//! TLS then runs through the tunnel with the host name as `servername`, so the certificate is
+//! checked against the host and not the address. Every hop — a redirect target's included — is
+//! resolved and pinned afresh.
+//!
+//! reqwest cannot pin a CONNECT authority: its tunnel writes the URI's host name into the
+//! CONNECT line (`reqwest-0.12.28/src/connect.rs:811`, `:856`), so the tunnel below is built on
+//! `hyper`'s client connection. There is no path from a failed CONNECT back to a direct
+//! connection (ADR 0023).
+
+use std::net::IpAddr;
+use std::sync::Arc;
+use std::time::Duration;
+
+use base64::Engine;
+use base64::engine::general_purpose::STANDARD;
+use http_body_util::{BodyExt, Empty};
+use hyper_util::rt::TokioIo;
+use nostream_config::settings::{Nip05Proxy, Nip05Settings};
+use nostream_core::CoreError;
+use nostream_core::nip05::FetchOutcome;
+use percent_encoding::percent_decode_str;
+use reqwest::dns::{Name, Resolve};
+use rustls::pki_types::ServerName;
+use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
+use tokio::net::TcpStream;
+use tokio_rustls::TlsConnector;
+
+use crate::error::ServicesError;
+
+/// v3's `DEFAULT_SETUP_TIMEOUT_MS`: one deadline around resolving the host, reaching
+/// the proxy and the CONNECT (`origin/main:src/utils/pinned-proxy-agent.ts:8-10`, read at
+/// `943fd7a2`). Its separate `CONNECT_TIMEOUT_MS` of the same 10 s is subsumed (ADR 0023, A4).
+pub(crate) const SETUP_TIMEOUT_MS: u64 = 10_000;
+
+/// v3's `MAX_RESPONSE_HEAD_BYTES` (`origin/main:src/utils/pinned-proxy-agent.ts:11`).
+const MAX_RESPONSE_HEAD_BYTES: usize = 8 * 1024;
+
+const HEAD_TERMINATOR: &[u8] = b"\r\n\r\n";
+
+/// What one configured NIP-05 fetch needs besides the resolver: the proxy URL, parsed per
+/// fetch (ADR 0023, D2), the TLS configuration, and the setup deadline.
+#[derive(Clone)]
+pub(crate) struct Egress {
+ pub(crate) proxy_url: String,
+ pub(crate) tls: Arc,
+ pub(crate) setup_timeout: Duration,
+}
+
+/// Whether a verification's requests go through the proxy: only `pin` with a non-empty
+/// `HTTPS_PROXY` (then `https_proxy`) does (`origin/main:src/utils/nip05.ts:45-55`, read at
+/// `943fd7a2`). `NO_PROXY` is never read.
+pub fn resolve_proxy(
+ nip05: Option<&Nip05Settings>,
+ env: &dyn Fn(&str) -> Option,
+) -> Option {
+ let nip05 = nip05?;
+ if nip05.proxy != Some(Nip05Proxy::Pin) {
+ return None;
+ }
+
+ let non_empty = |key: &str| env(key).filter(|value| !value.is_empty());
+ non_empty("HTTPS_PROXY").or_else(|| non_empty("https_proxy"))
+}
+
+/// The client TLS configuration, built from `ring`'s provider explicitly: no process default
+/// provider is installed, so `ClientConfig::builder()` would panic.
+pub(crate) fn client_config(
+ roots: rustls::RootCertStore,
+) -> Result, ServicesError> {
+ let config = rustls::ClientConfig::builder_with_provider(Arc::new(
+ rustls::crypto::ring::default_provider(),
+ ))
+ .with_safe_default_protocol_versions()
+ .map_err(|error| ServicesError::Configuration(format!("NIP-05 tunnel TLS: {error}")))?
+ .with_root_certificates(roots)
+ .with_no_client_auth();
+
+ Ok(Arc::new(config))
+}
+
+/// The authority a CONNECT names: the checked address and the target's port, an IPv6 address in
+/// brackets (`hostForAuthority`, `origin/main:src/utils/pinned-proxy-agent.ts:41`).
+pub(crate) fn authority(address: IpAddr, port: u16) -> String {
+ match address {
+ IpAddr::V4(address) => format!("{address}:{port}"),
+ IpAddr::V6(address) => format!("[{address}]:{port}"),
+ }
+}
+
+/// The port a URL's tunnel is asked for: the URL's own, or 443
+/// (`origin/main:src/utils/pinned-proxy-agent.ts:12`, `:118`).
+pub(crate) fn target_port(url: &reqwest::Url) -> u16 {
+ url.port_or_known_default().unwrap_or(443)
+}
+
+/// A parsed proxy URL. The host name is kept for the proxy's own connection and for the
+/// messages; nothing of it reaches the CONNECT line.
+#[derive(Debug)]
+pub(crate) struct ProxyEndpoint {
+ pub(crate) scheme: String,
+ pub(crate) host: String,
+ pub(crate) port: u16,
+ credentials: Option,
+}
+
+impl ProxyEndpoint {
+ /// `host:port` as v3's `proxy.host` renders it, IPv6 in brackets.
+ pub(crate) fn host_port(&self) -> String {
+ match self.host.parse::() {
+ Ok(IpAddr::V6(_)) => format!("[{}]:{}", self.host, self.port),
+ _ => format!("{}:{}", self.host, self.port),
+ }
+ }
+
+ /// The CONNECT head, exactly: the request line, `Host`, and the credentials when the URL
+ /// carries them (`origin/main:src/utils/pinned-proxy-agent.ts:179-184`).
+ pub(crate) fn connect_request(&self, authority: &str) -> Vec {
+ let mut request = format!("CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n");
+ if let Some(credentials) = &self.credentials {
+ request.push_str("Proxy-Authorization: Basic ");
+ request.push_str(credentials);
+ request.push_str("\r\n");
+ }
+ request.push_str("\r\n");
+ request.into_bytes()
+ }
+}
+
+/// Parses a proxy URL, refusing a scheme v3 refuses
+/// (`origin/main:src/utils/pinned-proxy-agent.ts:65-67`).
+pub(crate) fn parse_proxy(url: &str) -> Result {
+ let parsed = reqwest::Url::parse(url)
+ .map_err(|error| CoreError::Fetch(format!("NIP-05 proxy url: {error}")))?;
+ let scheme = parsed.scheme().to_owned();
+
+ if scheme != "http" && scheme != "https" {
+ return Err(CoreError::Fetch(format!(
+ "unsupported proxy protocol {scheme}: for NIP-05"
+ )));
+ }
+
+ let raw_host = parsed
+ .host_str()
+ .ok_or_else(|| CoreError::Fetch("NIP-05 proxy url has no host".to_owned()))?;
+ let host = raw_host
+ .strip_prefix('[')
+ .and_then(|host| host.strip_suffix(']'))
+ .unwrap_or(raw_host)
+ .to_owned();
+ let port = parsed
+ .port_or_known_default()
+ .unwrap_or(if scheme == "https" { 443 } else { 80 });
+ let credentials = if parsed.username().is_empty() {
+ None
+ } else {
+ let username = percent_decode_str(parsed.username()).decode_utf8_lossy();
+ let password = parsed
+ .password()
+ .map(|password| {
+ percent_decode_str(password)
+ .decode_utf8_lossy()
+ .into_owned()
+ })
+ .unwrap_or_default();
+ Some(STANDARD.encode(format!("{username}:{password}")))
+ };
+
+ Ok(ProxyEndpoint {
+ scheme,
+ host,
+ port,
+ credentials,
+ })
+}
+
+/// One fetched hop: the status, a redirect's `Location` when it is one, and the body.
+struct Hop {
+ status: u16,
+ location: Option,
+ body: Vec,
+}
+
+/// Fetches `url` through the proxy, following at most `max_redirects` redirects, each hop as a
+/// new tunnel resolved and pinned afresh (`origin/main:src/utils/nip05.ts:197`, `:206-211`).
+pub(crate) async fn fetch(
+ egress: &Egress,
+ resolver: &Arc,
+ url: &str,
+ timeout_ms: u64,
+ max_bytes: usize,
+ max_redirects: usize,
+) -> Result {
+ let proxy = parse_proxy(&egress.proxy_url)?;
+ let mut current = reqwest::Url::parse(url)
+ .map_err(|error| CoreError::Fetch(format!("NIP-05 url: {error}")))?;
+ let mut redirects = 0;
+
+ loop {
+ let hop = hop(egress, &proxy, resolver, ¤t, timeout_ms, max_bytes).await?;
+
+ match crate::http::redirect_decision(hop.status, redirects + 1, max_redirects)
+ .map_err(CoreError::Fetch)?
+ {
+ // The status set lives with the shared rule; a non-redirect status is the answer.
+ crate::http::RedirectDecision::Answer => {
+ return Ok(FetchOutcome {
+ status: hop.status,
+ body: hop.body,
+ });
+ }
+ crate::http::RedirectDecision::Follow => {}
+ }
+
+ let Some(location) = hop.location else {
+ return Ok(FetchOutcome {
+ status: hop.status,
+ body: hop.body,
+ });
+ };
+
+ let target = current
+ .join(&location)
+ .map_err(|error| CoreError::Fetch(format!("redirect location: {error}")))?;
+
+ if !crate::http::is_redirect_target_safe(&target) {
+ return Err(CoreError::Fetch(crate::http::refused_redirect(&target)));
+ }
+
+ redirects += 1;
+ current = target;
+ }
+}
+
+/// One hop: set up the tunnel, then TLS, the request and the body under one `timeout_ms`.
+async fn hop(
+ egress: &Egress,
+ proxy: &ProxyEndpoint,
+ resolver: &Arc,
+ url: &reqwest::Url,
+ timeout_ms: u64,
+ max_bytes: usize,
+) -> Result {
+ let host = url
+ .host_str()
+ .ok_or_else(|| CoreError::Fetch("NIP-05 url has no host".to_owned()))?
+ .to_owned();
+ let port = target_port(url);
+
+ let setup = async {
+ let addresses = resolve_checked(resolver, &host).await?;
+ let mut last_refusal = None;
+
+ for address in addresses {
+ match open_tunnel(egress, proxy, &host, address, port).await {
+ Ok(tunnel) => return Ok(tunnel),
+ // v3 fails the whole tunnel when the proxy cannot be reached; only a refused
+ // CONNECT moves on to the next checked address
+ // (`origin/main:src/utils/pinned-proxy-agent.ts:113-150`).
+ Err(TunnelFailure::Unreachable(reason)) => return Err(CoreError::Fetch(reason)),
+ Err(TunnelFailure::Refused(reason)) => last_refusal = Some(reason),
+ }
+ }
+
+ Err(CoreError::Fetch(last_refusal.unwrap_or_else(|| {
+ format!("no address to connect to for {host}")
+ })))
+ };
+
+ let tunnel = match tokio::time::timeout(egress.setup_timeout, setup).await {
+ Ok(tunnel) => tunnel?,
+ Err(_) => {
+ return Err(CoreError::Fetch(format!(
+ "timed out setting up a tunnel to {host} through proxy {}",
+ proxy.host_port()
+ )));
+ }
+ };
+
+ let exchange = async {
+ let name = ServerName::try_from(host.clone())
+ .map_err(|error| CoreError::Fetch(format!("NIP-05 host {host}: {error}")))?;
+ let tls = TlsConnector::from(Arc::clone(&egress.tls))
+ .connect(name, tunnel)
+ .await
+ .map_err(|error| CoreError::Fetch(error.to_string()))?;
+
+ request(tls, url, max_bytes).await
+ };
+
+ match tokio::time::timeout(Duration::from_millis(timeout_ms), exchange).await {
+ Ok(hop) => hop,
+ Err(_) => Err(CoreError::Fetch(format!(
+ "timed out after {timeout_ms} ms fetching {url}"
+ ))),
+ }
+}
+
+/// Whether one tunnel attempt failed because the proxy is unreachable, or because it refused
+/// the CONNECT.
+enum TunnelFailure {
+ Unreachable(String),
+ Refused(String),
+}
+
+/// Resolves `host` and refuses the hop when **any** address is private
+/// (`origin/main:src/utils/safe-lookup.ts:61-63`), unlike
+/// [`crate::http::GuardedResolver`]'s filter-then-connect.
+async fn resolve_checked(
+ resolver: &Arc,
+ host: &str,
+) -> Result, CoreError> {
+ let private = || {
+ CoreError::Fetch(format!(
+ "refused NIP-05 target {host} resolving to a private address"
+ ))
+ };
+
+ if let Ok(address) = host.parse::() {
+ return if crate::http::is_public_address(address) {
+ Ok(vec![address])
+ } else {
+ Err(private())
+ };
+ }
+
+ let name = host
+ .parse::()
+ .map_err(|error| CoreError::Fetch(format!("NIP-05 host {host}: {error}")))?;
+ let resolved = resolver
+ .resolve(name)
+ .await
+ .map_err(|error| CoreError::Fetch(error.to_string()))?;
+ let mut addresses = Vec::new();
+
+ for address in resolved {
+ if !crate::http::is_public_address(address.ip()) {
+ return Err(private());
+ }
+ addresses.push(address.ip());
+ }
+
+ Ok(addresses)
+}
+
+/// Opens the proxy connection, optionally over TLS, sends the CONNECT and reads the reply head.
+async fn open_tunnel(
+ egress: &Egress,
+ proxy: &ProxyEndpoint,
+ host: &str,
+ address: IpAddr,
+ port: u16,
+) -> Result, TunnelFailure> {
+ let unreachable = |error: &dyn std::fmt::Display| {
+ TunnelFailure::Unreachable(format!(
+ "could not reach proxy {} for {host}: {error}",
+ proxy.host_port()
+ ))
+ };
+ let refused = |reason: String| {
+ TunnelFailure::Refused(format!(
+ "proxy {} refused CONNECT to {host}: {reason}",
+ proxy.host_port()
+ ))
+ };
+
+ let socket = TcpStream::connect((proxy.host.as_str(), proxy.port))
+ .await
+ .map_err(|error| unreachable(&error))?;
+
+ let mut stream: Box = if proxy.scheme == "https" {
+ let name = ServerName::try_from(proxy.host.clone()).map_err(|error| unreachable(&error))?;
+ let tls = TlsConnector::from(Arc::clone(&egress.tls))
+ .connect(name, socket)
+ .await
+ .map_err(|error| unreachable(&error))?;
+ Box::new(tls)
+ } else {
+ Box::new(socket)
+ };
+
+ stream
+ .write_all(&proxy.connect_request(&authority(address, port)))
+ .await
+ .map_err(|error| refused(error.to_string()))?;
+
+ let head = match read_head(&mut stream).await {
+ Ok(head) => head,
+ Err(HeadError::TooLarge) => return Err(refused("response too large".to_owned())),
+ Err(HeadError::Closed) => return Err(refused("connection closed".to_owned())),
+ Err(HeadError::Io(error)) => return Err(refused(error.to_string())),
+ };
+
+ let head = String::from_utf8_lossy(&head);
+ let status_line = head.split("\r\n").next().unwrap_or_default();
+
+ match parse_status(status_line) {
+ Some(status) if (200..300).contains(&status) => Ok(stream),
+ _ => {
+ let reason = if status_line.is_empty() {
+ "no status line".to_owned()
+ } else {
+ status_line.chars().take(100).collect()
+ };
+ Err(refused(reason))
+ }
+ }
+}
+
+/// The reply head, without its terminator, capped at [`MAX_RESPONSE_HEAD_BYTES`] measured
+/// without the terminator so the same reply is accepted however it is split (`:190-199`).
+enum HeadError {
+ TooLarge,
+ Closed,
+ Io(std::io::Error),
+}
+
+// shortcut: one byte per socket read, so an over-read can never swallow the first TLS
+// byte; upgrade when a CONNECT reply's head has to be read on a hot path, where the
+// at-most-8-KiB of syscalls per reply matters.
+async fn read_head(stream: &mut (impl AsyncRead + Unpin)) -> Result, HeadError> {
+ let mut head = Vec::new();
+ let mut byte = [0u8; 1];
+
+ loop {
+ if head.ends_with(HEAD_TERMINATOR) {
+ head.truncate(head.len() - HEAD_TERMINATOR.len());
+ if head.len() > MAX_RESPONSE_HEAD_BYTES {
+ return Err(HeadError::TooLarge);
+ }
+ return Ok(head);
+ }
+
+ // No terminator after this many bytes cannot become a head of at most the cap.
+ if head.len() > MAX_RESPONSE_HEAD_BYTES + HEAD_TERMINATOR.len() - 1 {
+ return Err(HeadError::TooLarge);
+ }
+
+ match stream.read(&mut byte).await {
+ Ok(0) => return Err(HeadError::Closed),
+ Ok(_) => head.push(byte[0]),
+ Err(error) => return Err(HeadError::Io(error)),
+ }
+ }
+}
+
+fn parse_status(status_line: &str) -> Option {
+ let mut parts = status_line.split(' ');
+ let version = parts.next()?;
+ if version != "HTTP/1.1" && version != "HTTP/1.0" {
+ return None;
+ }
+ let code = parts.next()?;
+ if code.len() != 3 {
+ return None;
+ }
+
+ code.parse().ok()
+}
+
+/// One `GET ` inside the tunnel: `Host` and `Accept`, nothing else
+/// (`origin/main:src/utils/nip05.ts:193-202`).
+async fn request(stream: T, url: &reqwest::Url, max_bytes: usize) -> Result
+where
+ T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
+{
+ let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
+ .await
+ .map_err(|error| CoreError::Fetch(format!("NIP-05 tunnel handshake: {error}")))?;
+ let connection = tokio::spawn(connection);
+
+ let mut target = url.path().to_owned();
+ if let Some(query) = url.query() {
+ target.push('?');
+ target.push_str(query);
+ }
+
+ let request = hyper::Request::builder()
+ .method(hyper::Method::GET)
+ .uri(&target)
+ .header(hyper::header::HOST, host_header(url))
+ .header(hyper::header::ACCEPT, "application/json")
+ .body(Empty::::new())
+ .map_err(|error| CoreError::Fetch(format!("NIP-05 request: {error}")))?;
+
+ let response = sender
+ .send_request(request)
+ .await
+ .map_err(|error| CoreError::Fetch(format!("NIP-05 tunnel request: {error}")))?;
+ let status = response.status().as_u16();
+ let location = response
+ .headers()
+ .get(hyper::header::LOCATION)
+ .and_then(|value| value.to_str().ok())
+ .map(str::to_owned);
+
+ let mut body = response.into_body();
+ let mut bytes = Vec::new();
+
+ while let Some(frame) = body.frame().await {
+ let frame =
+ frame.map_err(|error| CoreError::Fetch(format!("NIP-05 tunnel response: {error}")))?;
+
+ if let Some(chunk) = frame.data_ref() {
+ if bytes.len() + chunk.len() > max_bytes {
+ return Err(CoreError::Fetch(crate::http::body_over_cap(max_bytes)));
+ }
+
+ bytes.extend_from_slice(chunk);
+ }
+ }
+
+ drop(connection);
+
+ Ok(Hop {
+ status,
+ location,
+ body: bytes,
+ })
+}
+
+fn host_header(url: &reqwest::Url) -> String {
+ let host = url.host_str().unwrap_or_default();
+
+ match url.port() {
+ Some(port) => format!("{host}:{port}"),
+ None => host.to_owned(),
+ }
+}
+
+trait TunnelIo: AsyncRead + AsyncWrite + Unpin + Send {}
+
+impl TunnelIo for T {}
diff --git a/crates/nostream-services/tests/maintenance.rs b/crates/nostream-services/tests/maintenance.rs
index de3c9cc47..4352337e7 100644
--- a/crates/nostream-services/tests/maintenance.rs
+++ b/crates/nostream-services/tests/maintenance.rs
@@ -682,6 +682,7 @@ async fn the_nip05_batch_is_skipped_when_disabled_and_read_with_the_captures_def
max_consecutive_failures: None,
domain_whitelist: None,
domain_blacklist: None,
+ proxy: None,
});
let (runner, repository, _) = self::runner(settings, Arc::clone(&fetch));
runner.reverify_nip05().await.expect("the pass");
@@ -695,6 +696,7 @@ async fn the_nip05_batch_is_skipped_when_disabled_and_read_with_the_captures_def
max_consecutive_failures: None,
domain_whitelist: None,
domain_blacklist: None,
+ proxy: None,
});
let (runner, repository, _) = self::runner(settings, Arc::clone(&fetch));
@@ -736,6 +738,7 @@ async fn the_nip05_batch_is_skipped_when_disabled_and_read_with_the_captures_def
max_consecutive_failures: None,
domain_whitelist: None,
domain_blacklist: None,
+ proxy: None,
});
let (runner, repository, _) = self::runner(settings, Arc::clone(&fetch));
repository.set_pending(vec![verified]);
diff --git a/crates/nostreamd/src/main.rs b/crates/nostreamd/src/main.rs
index 4d216b1fe..10e777cc0 100644
--- a/crates/nostreamd/src/main.rs
+++ b/crates/nostreamd/src/main.rs
@@ -270,8 +270,19 @@ async fn serve(
relay_config,
);
- let client =
- Arc::new(ReqwestClient::new().map_err(|error| DaemonError::Setup(error.to_string()))?);
+ // The NIP-05 proxy mode is read once, with the same environment lookup the stores use:
+ // `pin` is the only mode that honours `HTTPS_PROXY` (ADR 0023, D3).
+ let nip05_proxy =
+ nostream_services::nip05_egress::resolve_proxy(settings.nip05.as_ref(), &|key| {
+ std::env::var(key).ok()
+ });
+ let client = Arc::new(
+ ReqwestClient::with_nip05_proxy(
+ Arc::new(nostream_services::http::SystemResolver),
+ nip05_proxy,
+ )
+ .map_err(|error| DaemonError::Setup(error.to_string()))?,
+ );
let http: Arc = client.clone();
let fetch: Arc = client;
let context = ServiceContext {
diff --git a/crates/nostreamd/src/mcp_stdio.rs b/crates/nostreamd/src/mcp_stdio.rs
index bba853db3..47dc06902 100644
--- a/crates/nostreamd/src/mcp_stdio.rs
+++ b/crates/nostreamd/src/mcp_stdio.rs
@@ -84,9 +84,16 @@ pub async fn serve(
})
.await?;
let stores = Arc::new(nostream_services::ServiceStores::from(&repositories));
+ let nip05_proxy =
+ nostream_services::nip05_egress::resolve_proxy(settings.nip05.as_ref(), &|key| {
+ std::env::var(key).ok()
+ });
let client = Arc::new(
- nostream_services::ReqwestClient::new()
- .map_err(|error| DaemonError::Setup(error.to_string()))?,
+ nostream_services::ReqwestClient::with_nip05_proxy(
+ Arc::new(nostream_services::http::SystemResolver),
+ nip05_proxy,
+ )
+ .map_err(|error| DaemonError::Setup(error.to_string()))?,
);
let http: Arc = client.clone();
let fetch: Arc = client;
diff --git a/docs/rewrite/decisions/0023-nip05-egress-proxy.md b/docs/rewrite/decisions/0023-nip05-egress-proxy.md
new file mode 100644
index 000000000..731e26568
--- /dev/null
+++ b/docs/rewrite/decisions/0023-nip05-egress-proxy.md
@@ -0,0 +1,154 @@
+# ADR 0023: NIP-05 verification reaches an egress proxy with a pinned address
+
+- **Status:** accepted (job 052, issue #1367)
+- **Deciders:** the rewrite team, on the issue's scope and this job's spec
+- **Date:** 2026-12-05
+
+## Context
+
+The v3 NIP-05 verifier (`origin/main` at `943fd7a2`, the rewrite's v3 basis — every `v3`
+citation in this file is read at that commit) can send its `.well-known/nostr.json` request
+through an operator's proxy without letting the proxy resolve the host: the relay resolves the
+host itself, checks every address, and asks the proxy only for `CONNECT :443`; TLS then
+runs through the tunnel with `servername` set to the host name, so the certificate is checked
+against the host and not the address. `origin/main:src/utils/nip05.ts:45-55` selects that path
+with `nip05.proxy: pin` and `HTTPS_PROXY`; `origin/main:src/utils/pinned-proxy-agent.ts:51`
+builds the tunnel; `origin/main:src/utils/safe-lookup.ts:61-63` refuses a name when any resolved
+address is private.
+
+The rewrite had ported neither the behaviour nor the settings key. Its one NIP-05 transport
+(`crates/nostream-services/src/http.rs`) built a per-request reqwest client with
+`GuardedResolver`, and reqwest's `auto_sys_proxy` is on by default
+(`reqwest-0.12.28/src/async_impl/client.rs:309`, `:419`), so `HTTPS_PROXY` in the
+deployment routed the verification through the proxy and the proxy resolved the host — the
+opposite of what the setting means.
+
+Two structural facts constrain the port.
+
+1. **reqwest cannot pin a CONNECT authority.** Its tunnel writes `dst.host()` — the URI's
+ host name — into the CONNECT line (`reqwest-0.12.28/src/connect.rs:811`, `:856`;
+ `hyper-util-0.1.21/src/client/legacy/connect/proxy/tunnel.rs:144`, `:166-173`), and
+ `ClientBuilder::resolve`/`resolve_to_addrs` only pin DNS, not the tunnel's target.
+2. **A direct connection must ignore the environment's proxy.** `no_proxy()` on the
+ per-request client (`async_impl/client.rs:1427-1431`) clears what `build` installed from
+ the environment.
+
+## Decisions
+
+### D1 — The tunnel is hand-built below reqwest, not a loopback CONNECT shim
+
+Option (a): a new `nostream-services` module opens the proxy socket, writes the CONNECT with
+the checked address, runs TLS over that socket with `ServerName` = the host name, and sends
+the request through `hyper::client::conn::http1`.
+Option (b), rejected: a CONNECT shim listening on loopback, with reqwest pointed at it. It
+would put a listener in the relay process on an allocated port, reachable by any local
+process unless authenticated, with a start-up failure mode in two composition sites
+(`crates/nostreamd/src/main.rs`, `crates/nostreamd/src/mcp_stdio.rs`) — and it would still
+hand the host name to the shim, so the pin would rest on the shim's discipline rather than on
+a CONNECT line that never contains the name.
+
+Option (a) adds no listener, reuses `is_redirect_target_safe` and v3's texts, and
+needs one feature (`hyper`'s `client`) plus crates already resolved in `Cargo.lock`:
+`hyper-util` (`TokioIo`), `http-body-util`, `rustls` and `tokio-rustls` (the same `ring`/
+webpki stack reqwest already uses), `webpki-roots`, `percent-encoding` and `base64`. No new
+package enters the lock, and there is no second TLS implementation.
+
+### D2 — The configuration rides a constructor, not the fetch trait
+
+`Nip05Fetch::get` is `nostream-core`'s contract (`crates/nostream-core/src/nip05.rs:146-156`)
+and three test doubles implement it. Widening it would change all three for a configuration
+only the one real transport reads. `ReqwestClient::with_nip05_proxy(resolver, proxy)` mirrors
+the existing `with_nip05_resolver` (`http.rs:84-95`), and both composition sites have the
+settings in scope.
+
+The resolved proxy is stored as `Option` and parsed per fetch, so a bad scheme is a
+verification `Error` naming the scheme (`unsupported proxy protocol socks5: for NIP-05`) rather
+than a daemon that refuses to boot because `HTTPS_PROXY` is set for other tools. The struct
+carries both resolvers by role: `nip05_guarded_resolver` (`GuardedResolver`) for the direct
+path, and `nip05_tunnel_resolver` (the undecorated `Arc`) for the tunnel, which
+must apply v3's "refuse when **any** address is private" rule rather than the guard's
+filter-then-connect.
+
+### D3 — Read once at composition, not per request
+
+v3 re-reads settings and the environment on every request —
+`origin/main:src/utils/settings.ts:108-136` (`watchSettings` hot-reloads the file) and
+`origin/main:src/utils/nip05.ts:45-55` (`getVerificationAgent` re-reads `HTTPS_PROXY` each
+time). This port departs from those lines deliberately: the rewrite loads settings once
+(`crates/nostreamd/src/main.rs:121`) and owns no settings watcher
+(`crates/nostream-config/src/lib.rs:17-19`), and an environment variable cannot change inside a
+running process. `resolve_proxy` is therefore called once per process, at each composition
+site, with the same injected lookup the stores use (`|key| std::env::var(key).ok()`).
+
+Consequence, and the documented one: a change to `nip05.proxy` or `HTTPS_PROXY` takes effect
+after a restart. `CONFIGURATION.md` says so in both rows.
+
+### D4 — `nip05.proxy: null` is unset, the same as `disabled`
+
+v3's type is optional and its rule is nil-tolerant —
+`origin/main:src/utils/settings-config.ts:1430` (`isNil(nip05Proxy) || …`) and
+`origin/main:src/@types/settings.ts:449` (`proxy?: Nip05Proxy`) — so `null` is legal in a v3
+document. If the rewrite's shape walk reported it as an error, `load` would discard the whole
+operator document and run the shipped defaults (`crates/nostream-config/src/load.rs:441-451`),
+and a migrated file that writes `proxy:` would change how verification egresses.
+
+The port therefore carves one exception into the shape walk's null rule
+(`crates/nostream-config/src/validate.rs:601-607`, "Expected …, got null") for the single path
+`nip05.proxy`, on the `admin.passwordHash` precedent (`validate.rs:578-580`): the document
+validates, serde maps `null` to `None`, and `resolve_proxy` treats `None` exactly as
+`disabled`. The exception is one path and null only: every other leaf keeps its null error, and
+a wrong type at this path keeps `Expected string, got number` (the string-only value rule is
+silent for a non-string).
+
+### D5 — One redirect is followed, and the direct path's off-by-one is corrected
+
+`MAX_REDIRECTS` is 1 (`crates/nostream-core/src/nip05.rs:132`), matching v3's
+`maxRedirects: 1` (`origin/main:src/utils/nip05.ts:21`, `:197`). reqwest's
+`attempt.previous()` includes the initial URL (`reqwest-0.12.28/src/redirect.rs:134-137`), so
+the direct path's `len() >= max_redirects` refused the **first** hop: the NIP-05 fetch followed
+no redirect at all. The tunnel follows one hop, each as a new tunnel — fresh resolution, fresh
+pin, fresh TLS name — and the direct path's operator becomes `>` in the same change, so the two
+paths agree.
+
+The rule has one owner: the statuses followed, the hop budget and the `too many redirects` text
+live in `redirect_decision`, and the refusal and body-cap texts in `refused_redirect` and
+`body_over_cap`, next to `is_redirect_target_safe` in `crates/nostream-services/src/http.rs`;
+the direct reqwest policy and the tunnel both call them, and a pure test
+(`http::tests::nip05_redirect_decision`) pins the boundary. The two transports stay two (D1).
+
+The statuses followed are reqwest's five (301/302/303/307/308) with a `Location`, which is what
+the direct path does; a 3xx without `Location`, or any other status, is returned as a status.
+
+### D6 — No connection pooling
+
+v3 keeps one agent per proxy URL alive (`origin/main:src/utils/nip05.ts:36-43`), so
+sequential verifications against one origin reuse DNS, TCP and TLS. The port opens one TCP and
+TLS connection per hop and closes it after the response. A pool would need per-origin lifetime,
+eviction and its own tests, and the load is one GET per verification, batched by maintenance
+(`crates/nostream-services/src/workers/maintenance.rs:373-389`). The cost is one extra
+handshake per verification. A follow-up issue if measurements make it matter.
+
+## Consequences
+
+A deployment that sets `nip05.proxy: pin` and `HTTPS_PROXY` now reaches the proxy with
+`CONNECT :` and no host name in the request, and verifies the origin's
+certificate against the host name; a certificate for another name, a proxy that refuses or
+cannot be reached, a name with any private address, and a setup or request deadline all fail
+the verification closed — `CoreError::Fetch`, hence `VerificationOutcome::Error`, so the row
+keeps its previous verification and the admin answers 502 (R14). There is no path from a failed
+CONNECT back to a direct connection.
+
+A deployment with `disabled` (the default) or no proxy URL now goes direct even when
+`HTTPS_PROXY` is set: the per-request client calls `.no_proxy()`, and the request never touches
+the proxy. That is a behaviour change for anyone who had been relying on the environment
+variable; it is the point of the setting.
+
+The tunnel is bounded like v3's: one 10 s setup deadline around resolve, proxy connect
+and the CONNECT reply (v3's two 10 s deadlines, `CONNECT_TIMEOUT_MS` and
+`DEFAULT_SETUP_TIMEOUT_MS`, are subsumed by one); an 8 KiB reply-head cap measured without the
+terminator; and one `timeout_ms` around TLS, request and body. An `https:` proxy URL wraps the
+proxy socket in the same TLS configuration with `ServerName` = the proxy host.
+
+Out of scope: SOCKS proxies, `NO_PROXY`, proxy client certificates and HTTP/2 CONNECT (v3
+supports none of them), and the shared `HttpClient`'s environment-proxy behaviour,
+which is not NIP-05's.
diff --git a/resources/default-settings.yaml b/resources/default-settings.yaml
index 5f3e25a57..e28661472 100755
--- a/resources/default-settings.yaml
+++ b/resources/default-settings.yaml
@@ -81,6 +81,10 @@ nip05:
domainWhitelist: []
# Block authors with NIP-05 at these domains
domainBlacklist: []
+ # How verification requests reach the internet. 'disabled' connects directly and ignores HTTPS_PROXY.
+ # 'pin' goes through the proxy in HTTPS_PROXY, but the relay resolves the host itself and asks the proxy
+ # to connect to the address it checked, so a proxy cannot send the request to a private address.
+ proxy: disabled
nip42:
# When true, clients must AUTH (NIP-42) as the event author before publishing.
# Advertised in NIP-11 as limitation.restricted_writes (not auth_required).