# UnambitiousFx > A collection of lightweight, modular .NET libraries designed to simplify web API development — with Native AOT support and zero unnecessary overhead. > > Version: Myelin 1.x This file contains all documentation content in a single document following the llmstxt.org standard. ## Myelin UnambitiousFx.Myelin is an outbound HTTP layer for .NET that only reaches the public internet. Use it whenever your server fetches a URL it did not write itself: webhooks, « import from URL », link previews, avatar or icon fetchers, callbacks of third-party services. > *Myelin* is the sheath around a nerve fibre that keeps the signal from leaking. Here, it keeps your server's requests > from leaking into your own network. ### The problem: SSRF A plain `HttpClient` happily connects to `127.0.0.1`, to the cloud metadata endpoint `169.254.169.254`, or to the private network behind your server. If an attacker controls the URL, that is **server-side request forgery** (SSRF): your server becomes their proxy into places they cannot reach. Checking the URL text is not enough: - `0x7f000001`, `2130706433` and `[::ffff:127.0.0.1]` are all `127.0.0.1`; - a public name can resolve to a private address, or resolve to a public one when you check and a private one when you connect (**DNS rebinding**); - a harmless URL can **redirect** to a harmful one; - a proxy hides the real destination. ### What Myelin does - **Resolves the host itself**, refuses it when *any* answer is a special-purpose address, and connects only to the addresses it checked. See [Address policy](address-policy). - **HTTPS only**, no credentials in the URL, optional host allow-list with wildcards. - **Revalidates every redirect** of a GET; never redirects a POST or a request with extra headers. - **Bounds time and size**, declared or streamed. - **Logs each refusal** with its host and reason only. Two ways to use it: [`SafeHttpClient`](safe-http-client), a small client that reads bodies within a limit, or [`UseMyelin()`](http-client-factory) on any `IHttpClientFactory` client. ### Where next - [Getting Started](getting-started) - [Address policy](address-policy): every range Myelin refuses. - [SafeHttpClient](safe-http-client) and [IHttpClientFactory](http-client-factory). --- ## Getting Started ### Install ```bash dotnet add package UnambitiousFx.Myelin ``` Myelin targets `net8.0`, `net9.0`, `net10.0` and `net11.0`. Its only dependencies are `Microsoft.Extensions.Http`, `Microsoft.Extensions.Logging.Abstractions` and `Microsoft.Extensions.Options`. It is trimming- and NativeAOT-compatible. ### Register ```csharp using UnambitiousFx.Myelin; builder.Services.AddMyelin(o => { o.AllowedHosts = ["api.example.com", "*.cdn.example.org"]; // empty: any public host o.UserAgent = "MyApp/1.0 (+https://example.com)"; o.Timeout = TimeSpan.FromSeconds(10); o.MaxRedirects = 3; }); ``` Or bind the options from configuration: ```csharp builder.Services.AddMyelin(); builder.Services.Configure(builder.Configuration.GetSection("Myelin")); ``` ```json title="appsettings.json" { "Myelin": { "AllowedHosts": ["api.example.com", "*.cdn.example.org"], "UserAgent": "MyApp/1.0" } } ``` ### Fetch ```csharp public sealed class IconFetcher(SafeHttpClient http) { public async Task FetchAsync(Uri url, CancellationToken ct) { try { var response = await http.GetAsync(url, maxBytes: 512_000, ct); return response.Status == HttpStatusCode.OK ? response.Body : null; } catch (OutboundRefusedException refused) { // refused.Reason: "address_refused", "not_https", "host_not_allowed", "too_large"... return null; } } } ``` A 4xx or 5xx is returned in `OutboundResponse.Status`, not thrown. Only a refusal throws `OutboundRefusedException`; network failures and the timeout throw as `HttpClient` would. ### Options | Option | Default | Meaning | |---|---|---| | `AllowedHosts` | `[]` | Hosts a request may target. Empty allows any host whose addresses are public. `*.example.com` matches subdomains, not `example.com`. | | `UserAgent` | `null` | Sent on every request. Some servers refuse a request without one. | | `Timeout` | 30 s | The whole call: redirects and body included. | | `MaxRedirects` | 3 | How many redirects a GET may follow. | ### Refusal reasons | `Reason` | When | |---|---| | `not_https` | The URL is relative or not `https`. | | `user_info` | The URL carries credentials. | | `host_not_allowed` | The host is not in `AllowedHosts`. | | `address_refused` | The host resolves to nothing, or to at least one refused address. | | `too_many_redirects` | More redirects than `MaxRedirects`. | | `redirect_without_location` | A 3xx without `Location`. | | `redirect_refused` | A redirect answered a request that is never redirected. | | `too_large` | The body is over the limit of the call. | Constants for all of them are in `RefusalReasons`. --- ## Address policy `AddressPolicy.IsAllowed(IPAddress)` decides whether a connection may reach an address. Myelin calls it on **every** address a host resolves to, before connecting; one refused answer refuses the host. ### Refused ranges Every entry of the IANA [IPv4](https://www.iana.org/assignments/iana-ipv4-special-registry) and [IPv6](https://www.iana.org/assignments/iana-ipv6-special-registry) special-purpose registries that is not globally reachable, plus multicast and broadcast: | IPv4 | What | |---|---| | `0.0.0.0/8` | "This network" | | `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16` | Private | | `100.64.0.0/10` | Carrier-grade NAT | | `127.0.0.0/8` | Loopback | | `169.254.0.0/16` | Link-local, **cloud metadata** (`169.254.169.254`) | | `192.0.0.0/24` | IETF protocol assignments | | `192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24` | Documentation | | `192.88.99.0/24` | Deprecated 6to4 relay | | `198.18.0.0/15` | Benchmarking | | `224.0.0.0/4` | Multicast | | `240.0.0.0/4` | Reserved, and `255.255.255.255` | | IPv6 | What | |---|---| | `::/96` | IPv4-compatible, `::` and `::1` | | `::ffff:0:0:0/96` | SIIT IPv4-translated | | `64:ff9b:1::/48` | Local-use NAT64 | | `100::/64`, `100:0:0:1::/64` | Discard-only, dummy prefix | | `2001::/23` | IETF protocol assignments (Teredo, benchmarking, ORCHID…) | | `2001:db8::/32`, `3fff::/20` | Documentation | | `2002::/16` | 6to4 | | `5f00::/16` | Segment routing SIDs | | `fc00::/7` | Unique local | | `fe80::/10`, `fec0::/10` | Link-local, deprecated site-local | | `ff00::/8` | Multicast | An application that must call a service it registered itself on a private network can opt in to [registered endpoints](./registered-endpoints.mdx): exact `https` host:port pairs allowed to reach private-use, CGNAT and unique-local addresses, and nothing else. `192.0.0.0/24` and `2001::/23` are refused whole, including the few anycast services they hold: an application has no reason to call them. ### Mapped and translated addresses - **IPv4-mapped** (`::ffff:a.b.c.d`) is judged on its IPv4 address: `::ffff:10.0.0.1` is refused, `::ffff:8.8.8.8` allowed. - **Well-known NAT64** (`64:ff9b::/96`) is judged on the IPv4 address it embeds, so a NAT64 network still reaches public IPv4 hosts and still cannot reach `10.0.0.1`. The ranges are checked with `System.Net.IPNetwork` on parsed addresses, never on text: octal, hexadecimal and integer notations (`0x7f000001`, `2130706433`) are already `127.0.0.1` by then. ### DNS rebinding The connection handler (`MyelinHandler.Create`) resolves the host **itself**, checks every answer, then opens the socket on exactly those addresses. The socket layer never resolves the name again, so a server that answers a public address to the check and a private one to the connection gains nothing. Proxies are disabled for the same reason: a proxy would connect to an address this check never sees. ### Custom resolution Register your own `IHostResolver` (before `AddMyelin`, or in place of the default) to resolve through another DNS service, or to make tests deterministic: ```csharp services.AddSingleton(); services.AddMyelin(); ``` --- ## SafeHttpClient `SafeHttpClient` is the small client `AddMyelin()` registers. Each call reads the whole body within a size limit and returns an `OutboundResponse(Status, Body)`. ### GET ```csharp var response = await http.GetAsync(url, maxBytes: 1_000_000, ct); ``` Redirects (301, 302, 303, 307, 308) are followed up to `MaxRedirects`, and **each hop is checked like the first request**: HTTPS, credentials, allow-list, then the addresses of the new host. A redirect from an allowed host to `https://169.254.169.254/` is refused. ### POST a JSON body ```csharp await http.PostJsonAsync(webhookUrl, JsonSerializer.SerializeToUtf8Bytes(payload, AppJsonContext.Default.Payload), 4096, ct); ``` A redirect is **refused, never followed**: a POST must not be replayed to another host, and a webhook URL is a secret. ### Any method, extra headers ```csharp var headers = new Dictionary { ["Authorization"] = $"Bearer {token}" }; await http.SendOnceAsync(HttpMethod.Delete, url, json: null, headers, maxBytes: 4096, ct); ``` Never redirected either: the headers are meant for this host only. ### Size and time - `Content-Length` over `maxBytes` is refused before reading. - Without `Content-Length`, or when it lies, the limit holds on the bytes actually read. - `Timeout` covers the whole call, redirects and body included; it throws `OperationCanceledException`, like the `CancellationToken` you pass. ### Logging Each refusal logs one warning, `Outbound request to {Host} refused: {Reason}`, through `ILogger`. Never the path or the query: they may carry a token. ### Without dependency injection ```csharp var http = new SafeHttpClient( new HttpMessageInvoker(MyelinHandler.Create()), new MyelinOptions { AllowedHosts = ["api.example.com"] }, NullLogger.Instance); ``` Keep one instance for the application's lifetime: it pools connections like `HttpClient`. --- ## IHttpClientFactory When you already use `HttpClient` through `IHttpClientFactory`, add `UseMyelin()` to the client's registration: ```csharp builder.Services .AddHttpClient(client => client.Timeout = TimeSpan.FromSeconds(10)) .UseMyelin(o => o.AllowedHosts = ["hooks.example.com"]); ``` The client then: - uses `MyelinHandler.Create` as its primary handler: public addresses only, checked after resolution, no proxy, no cookies; - checks every request for HTTPS, credentials in the URL and the allow-list; - sends `UserAgent` when the request has none; - throws `OutboundRefusedException` on a refusal, as `SafeHttpClient` does. ### What differs from SafeHttpClient | | `SafeHttpClient` | `UseMyelin()` | |---|---|---| | Redirects | GET follows them, each revalidated | **Not followed**: the 3xx is returned to you | | Body size | `maxBytes` on every call | Up to you (`HttpCompletionOption.ResponseHeadersRead` and a bounded read) | | Timeout | `MyelinOptions.Timeout` | `HttpClient.Timeout` | If you follow a redirect yourself, send the new URL through the same client: the request is checked again. ### Options per client `UseMyelin(configure)` configures the options of **that** client only (named options). Two clients can have different allow-lists: ```csharp services.AddHttpClient("webhooks").UseMyelin(o => o.AllowedHosts = ["hooks.example.com"]); services.AddHttpClient("previews").UseMyelin(); // any public host ``` Both share the registered `IHostResolver`. --- ## Benchmarks `AddressPolicy.IsAllowed` runs once per resolved address of every **new connection** (connections are pooled, so not per request). The suite in `benchmarks/MyelinBenchmark` measures it for each kind of address. ### Results BenchmarkDotNet 0.15.8, `ShortRun` (3 warmups, 3 iterations), .NET 10.0.14, Apple M5 Pro, macOS. | Address | Example | Mean | Allocated | |---|---|---:|---:| | Public IPv4 | `8.8.8.8` | 14.0 ns | - | | Private IPv4 | `10.0.0.1` | 1.9 ns | - | | Public IPv6 | `2606:50c0:8000::154` | 30.3 ns | - | | IPv4-mapped | `::ffff:8.8.8.8` | 17.5 ns | 40 B | | NAT64 | `64:ff9b::808:808` | 27.8 ns | 112 B | A refused address is found early (it matches one of the first ranges); a public one is compared with every range. Either way the check is negligible next to a DNS lookup and a TLS handshake. ### Running the benchmarks ```bash dotnet run --project benchmarks/MyelinBenchmark -c Release # a quick, less precise run dotnet run --project benchmarks/MyelinBenchmark -c Release -- --filter '*' --job short ``` --- ## Registered endpoints By default Myelin refuses every non-global address, private networks included. Some applications must still call a service they registered themselves on a private network: a worker on the same Docker Compose network, a GPU box on the LAN, a host reached over Tailscale. **Registered endpoints** let exactly those calls through Myelin, instead of a second, unguarded `HttpClient`. :::warning A narrow, explicit opt-in Nothing changes unless you call `AllowRegisteredEndpoints`. Even then, only the exact `https` host and port pairs your `IRegisteredEndpoints` answers `true` for gain anything, and they gain only the three private-network ranges below. Never register a host:port that comes from user input. ::: ### Set up Implement `IRegisteredEndpoints` over wherever your application keeps its registrations, and opt in per client. The handler is long-lived and may ask from several connections at once: the implementation must be thread-safe and must not hold a scoped service (an EF Core context) directly. ```csharp public sealed class WorkerRegistry(IDbContextFactory contexts) : IRegisteredEndpoints { public async ValueTask IsRegisteredAsync(string host, int port, CancellationToken ct) { // One context per lookup: connections are opened concurrently. await using var db = await contexts.CreateDbContextAsync(ct); return await db.Workers.AnyAsync(w => w.Host == host && w.Port == port && !w.Revoked, ct); } } services.AddSingleton(); services.AddHttpClient("workers") .UseMyelin(o => o.AllowRegisteredEndpoints(sp => sp.GetRequiredService())); ``` `AddMyelin(o => o.AllowRegisteredEndpoints(...))` does the same for `SafeHttpClient`; a handler built by hand takes the set in `MyelinHandler.Create(resolver, registeredEndpoints)`. The host is passed in its IDN (punycode) form, as the URL gives it; the port is 443 when the URL has none. Match both exactly: no wildcard, no path prefix. ### What a registered endpoint may reach | Range | IANA special-purpose registry entry | |---|---| | `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16` | IPv4 Private-Use (RFC 1918) | | `100.64.0.0/10` | IPv4 Shared Address Space (RFC 6598): carrier-grade NAT, Tailscale | | `fc00::/7` | IPv6 Unique-Local (RFC 4193) | Everything else in the [address policy](./address-policy.mdx) stays refused, registered or not: loopback, link-local (`169.254.0.0/16`, `fe80::/10`), unspecified, multicast, broadcast, documentation, benchmarking, NAT64 of a private address. Two cloud metadata services that sit inside these ranges are refused too: `100.100.100.200` (Alibaba Cloud) and `fd00:ec2::254` (AWS over IPv6). `AddressPolicy.IsAllowedForRegisteredEndpoint(IPAddress)` is the check, if you want it elsewhere. ### How it is checked - **At connect time, on the addresses dialled.** The host is resolved again for every new connection, and **every** answer must be public or in the ranges above: a registered name rebinding to `127.0.0.1` is refused. - **HTTPS only.** An `http` URL never gets the exemption. - **Asked per connection.** `IsRegisteredAsync` is called whenever a new connection resolves to a private address, so registering or revoking an endpoint applies without rebuilding the client. Pooled connections of such a handler live one minute at most, so no new request reaches a revoked endpoint after a minute. A request already in progress (a long upload, a streamed response) is not cancelled by a revocation. - **Redirects are checked again.** A redirect is a new request to a new host:port: if that pair is not registered, a private answer is refused (`address_refused`). A refusal is the usual `OutboundRefusedException` with `RefusalReasons.AddressRefused`, logged with host and reason only. ### Client certificates and pinned keys A registered worker is usually identified by its key rather than its IP. Configure TLS on the primary handler **after** `UseMyelin()`; the Myelin connection check stays in place: ```csharp services.AddHttpClient("workers") .UseMyelin(o => o.AllowRegisteredEndpoints(sp => sp.GetRequiredService())) .ConfigurePrimaryHttpMessageHandler((handler, sp) => { var tls = ((SocketsHttpHandler)handler).SslOptions; tls.ClientCertificates = [clientCertificate]; tls.RemoteCertificateValidationCallback = (_, certificate, _, _) => IsPinned(certificate); }); ``` --- ## Using these docs with AI These docs are built to be consumed by AI coding assistants, not just humans. ### 1. llms.txt (zero setup) Every build publishes machine-readable bundles following the [llmstxt.org](https://llmstxt.org) standard: | File | Contents | |------|----------| | [`/llms.txt`](https://unambitiousfx.com/myelin/llms.txt) | Index of every doc section with links | | [`/llms-full.txt`](https://unambitiousfx.com/myelin/llms-full.txt) | All documentation in one file | ### 2. Context7 MCP [Context7](https://context7.com) indexes these docs and serves them over MCP. Library ID: **`/UnambitiousFx/Myelin`**. ### 3. Agent skill shipped in the package The `UnambitiousFx.Myelin` package ships an [Agent Skill](https://agentskills.io), `unambitiousfx-myelin`: a `SKILL.md` that tells coding agents how to make outbound HTTP calls without opening an SSRF hole. `dotnet restore` places it under `~/.nuget/packages/unambitiousfx.myelin//skills/`, but agents only load skills from their own folders. Set `UnambitiousFxSkillsDestination` to have the package copy its skill there on every build: ```xml title="Directory.Build.props" $(MSBuildThisFileDirectory).claude/skills ``` The copy always matches the referenced package version. Every UnambitiousFx package uses the same property, so one setting copies the skills of all of them.