001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.revetsec;
018
019import com.revetsec.internal.HostClassifier;
020import com.revetsec.internal.HostClassifier.HostClass;
021import org.jspecify.annotations.NonNull;
022import org.jspecify.annotations.Nullable;
023
024import javax.annotation.concurrent.Immutable;
025import java.net.URI;
026import java.util.Collections;
027import java.util.EnumSet;
028import java.util.Set;
029
030import static java.util.Objects.requireNonNull;
031
032/**
033 * Decides which URIs Revetsec may send requests to.
034 * <p>
035 * Revetsec applies the policy to every URI it is about to fetch, such as an issuer, a JSON Web Key Set and every
036 * endpoint named in remote metadata, before any request is sent. There are two presets:
037 * {@link #defaultInstance()}, which rejects the addresses and names it knows to reach a machine's own metadata or
038 * configuration services, and {@link #publicAddressesOnlyInstance()}, which also rejects the local, private-use and
039 * special-use addresses and names it lists. Neither list is exhaustive.
040 * <p>
041 * <strong>Hostnames are never resolved.</strong> The policy looks only at the text of the URI. It classifies IP
042 * address literals, including the all-digit form ({@code https://2852039166/} is 169.254.169.254), and IPv4 addresses
043 * embedded in IPv4-mapped, IPv4-compatible, IPv4-translated and NAT64 IPv6 addresses, and it recognizes special-use
044 * and private-use names by their text, folding ASCII letters only and ignoring one trailing dot. A URI whose host
045 * {@link URI} cannot parse, including the short dotted forms {@code https://127.1/} and
046 * {@code https://169.254.43518/} that {@link java.net.InetAddress} would accept, has no host and is rejected.
047 * <p>
048 * The policy cannot see where a DNS name points, so no policy stops a hostname that resolves to a private or metadata
049 * address, or a name whose DNS answer changes between checks (DNS rebinding). A network-specific NAT64 prefix and an
050 * explicit address mapping (RFC 7757) look like ordinary IPv6 addresses, so the policy cannot tell where they lead
051 * either. When the URIs come from someone you do not control, such as a tenant-supplied issuer, send Revetsec's
052 * traffic through an egress proxy that enforces the destinations you allow, by configuring it on the
053 * {@link java.net.http.HttpClient} you give Revetsec.
054 *
055 * @author <a href="https://www.revetkn.com">Mark Allen</a>
056 * @since 1.0.0
057 */
058@Immutable
059public final class OutboundUriPolicy {
060        private static final OutboundUriPolicy DEFAULT_INSTANCE = new OutboundUriPolicy("default",
061                        EnumSet.of(HostClass.INVALID, HostClass.ANY_LOCAL, HostClass.LINK_LOCAL, HostClass.CLOUD_METADATA,
062                                        HostClass.METADATA_NAME, HostClass.NAT64_LOCAL_USE));
063
064        private static final OutboundUriPolicy PUBLIC_ADDRESSES_ONLY_INSTANCE = new OutboundUriPolicy(
065                        "publicAddressesOnly", EnumSet.complementOf(EnumSet.of(HostClass.HOSTNAME, HostClass.OTHER_ADDRESS)));
066
067        @NonNull
068        private final String name;
069        /**
070         * Never modified after construction and never exposed.
071         */
072        @NonNull
073        private final Set<@NonNull HostClass> rejectedHostClasses;
074
075        /**
076         * Returns the default policy.
077         * <p>
078         * It permits an absolute {@code https} or {@code http} URI whose host is a DNS name or an IP address literal,
079         * except:
080         * <ul>
081         *   <li>a link-local literal: {@code 169.254.0.0/16}, which includes the common cloud metadata address
082         *   {@code 169.254.169.254}, and {@code fe80::/10};</li>
083         *   <li>an any-local literal: {@code 0.0.0.0/8} (so {@code https://0/} is rejected) and {@code ::};</li>
084         *   <li>the known cloud metadata endpoints as of 2026-09-27: the addresses {@code 100.100.100.200} (Alibaba
085         *   Cloud), {@code 168.63.129.16} (Azure WireServer), {@code fd00:ec2::254} (Amazon EC2), {@code fd00:ec2::23}
086         *   (Amazon EKS Pod Identity) and {@code fd20:ce::254} (Google Compute Engine, over IPv6), and Google Compute
087         *   Engine's names {@code metadata.google.internal} and {@code metadata.goog} and every name under them. The list
088         *   is not exhaustive;</li>
089         *   <li>any address in the RFC 8215 local-use NAT64 prefix {@code 64:ff9b:1::/48};</li>
090         *   <li>an IPv4-mapped, IPv4-compatible, IPv4-translated or NAT64 Well-Known Prefix IPv6 literal around one of the
091         *   IPv4 addresses above.</li>
092         * </ul>
093         * It also rejects a URI with no parseable host; a host that looks numeric but is not a well-formed address
094         * literal, such as {@code 0xa9fea9fe} or {@code 0251.254.169.254}, which the JDK refuses by default but passes to
095         * the platform resolver when {@code jdk.net.allowAmbiguousIPAddressLiterals} is {@code true}, and which a proxy or
096         * resolver that uses {@code inet_aton} reads as {@code 169.254.169.254}; and an IPv6 literal with a zone ID.
097         * <p>
098         * Loopback, private, shared (carrier-grade NAT), unique local, 6to4, Teredo, multicast, reserved and other
099         * non-global addresses are permitted, and so are {@code localhost} and other local names. Revetsec's HTTP layer
100         * separately requires {@code https}, except that a builder may explicitly allow plain {@code http} for tests, to a
101         * loopback literal or exactly {@code localhost} only.
102         *
103         * @return the default policy; always the same instance
104         * @since 1.0.0
105         */
106        @NonNull
107        public static OutboundUriPolicy defaultInstance() {
108                return DEFAULT_INSTANCE;
109        }
110
111        /**
112         * Returns the policy that permits only globally reachable destinations, as far as the URI's text shows.
113         * <p>
114         * It permits an absolute {@code https} or {@code http} URI whose host is either:
115         * <ul>
116         *   <li>an IPv4 literal outside the blocks listed below, or an IPv4-mapped ({@code ::ffff:0:0/96}) or NAT64
117         *   Well-Known Prefix ({@code 64:ff9b::/96}) IPv6 literal around one. IPv4 is checked against a list, so a block
118         *   that IANA marks as not globally reachable after 2026-09-27 is permitted until Revetsec lists it;</li>
119         *   <li>an IPv6 literal in the global unicast block {@code 2000::/3}, except {@code 2001::/23} as a whole (which
120         *   includes Teredo, {@code 2001::/32}), 6to4 ({@code 2002::/16}) and the documentation blocks
121         *   {@code 2001:db8::/32} and {@code 3fff::/20}. Everything outside {@code 2000::/3} is rejected, so an IPv6
122         *   block allocated for a special purpose in the future is rejected too;</li>
123         *   <li>a DNS name of at least two labels that is none of the names listed below. Other special-use names, such
124         *   as {@code example.com}, are permitted.</li>
125         * </ul>
126         * On top of everything {@link #defaultInstance()} rejects, it therefore rejects:
127         * <ul>
128         *   <li>loopback, in every form ({@code 127.0.0.0/8}, {@code ::1} and the IPv6 forms around a loopback IPv4
129         *   address);</li>
130         *   <li>the private-use blocks {@code 10.0.0.0/8}, {@code 172.16.0.0/12} and {@code 192.168.0.0/16}, the shared
131         *   address space {@code 100.64.0.0/10} and unique local addresses ({@code fc00::/7});</li>
132         *   <li>the IPv4 blocks that IANA's special-purpose registry marked as not globally reachable as of 2026-09-27,
133         *   such as the documentation and benchmarking blocks, and the deprecated 6to4 relay anycast block
134         *   {@code 192.88.99.0/24};</li>
135         *   <li>multicast and reserved space: {@code 224.0.0.0/4}, {@code 240.0.0.0/4}, {@code 255.255.255.255} and
136         *   {@code ff00::/8};</li>
137         *   <li>6to4 and Teredo as a whole: the IPv4 address inside them is a tunnel endpoint, not the destination;</li>
138         *   <li>IPv4-compatible ({@code ::/96}) and IPv4-translated ({@code ::ffff:0:0:0/96}) literals, whatever the IPv4
139         *   address inside;</li>
140         *   <li>the names {@code localhost} and every name under it, every single-label name (which a resolver may
141         *   complete with its search domains), and {@code local}, {@code internal}, {@code test}, {@code invalid},
142         *   {@code example}, {@code onion} and {@code alt} and every name under them;</li>
143         *   <li>{@code arpa}, the domain reserved for Internet infrastructure (RFC 3172), and every name under it, such as
144         *   {@code home.arpa}, the other special-use names there ({@code service.arpa}, {@code ipv4only.arpa},
145         *   {@code resolver.arpa} and others) and the reverse-mapping zones {@code in-addr.arpa} and
146         *   {@code ip6.arpa}.</li>
147         * </ul>
148         * A name is matched in any ASCII case, with or without one trailing dot, and a suffix only on a label boundary:
149         * {@code idp.internal.} is rejected, {@code idp.evilinternal} is not.
150         * <p>
151         * This policy does not resolve names either, so a public name that points at a private address still passes; see
152         * {@link OutboundUriPolicy}. An identity provider reached through a private DNS zone, such as a name under
153         * {@code .internal}, needs {@link #defaultInstance()} and, where the URIs are not your own, an egress proxy.
154         *
155         * @return the public-addresses-only policy; always the same instance
156         * @since 1.0.0
157         */
158        @NonNull
159        public static OutboundUriPolicy publicAddressesOnlyInstance() {
160                return PUBLIC_ADDRESSES_ONLY_INSTANCE;
161        }
162
163        private OutboundUriPolicy(@NonNull String name,
164                                                                                                                @NonNull Set<@NonNull HostClass> rejectedHostClasses) {
165                this.name = requireNonNull(name);
166                this.rejectedHostClasses = Collections.unmodifiableSet(EnumSet.copyOf(rejectedHostClasses));
167        }
168
169        /**
170         * Returns whether this policy permits a request to {@code uri}.
171         * <p>
172         * The URI must be absolute, with the scheme {@code https} or {@code http} in any case and a host that
173         * {@link URI#getHost()} can parse; a URI without one, such as {@code https://127.1/} (whose host
174         * {@link URI} cannot parse), is rejected. The host is never resolved. The port, path, query and user
175         * information are not examined.
176         *
177         * @param uri the URI Revetsec is about to send a request to
178         * @return {@code true} if the policy permits the request
179         * @throws NullPointerException if {@code uri} is {@code null}
180         * @since 1.0.0
181         */
182        @NonNull
183        public Boolean permits(@NonNull URI uri) {
184                requireNonNull(uri);
185
186                @Nullable String scheme = uri.getScheme();
187
188                if (scheme == null || !(isAsciiCaseInsensitiveMatch(scheme, "https") || isAsciiCaseInsensitiveMatch(scheme,
189                                "http")))
190                        return false;
191
192                @Nullable String host = uri.getHost();
193
194                if (host == null)
195                        return false;
196
197                return !this.rejectedHostClasses.contains(HostClassifier.classify(host));
198        }
199
200        /**
201         * Returns a description of this policy.
202         *
203         * @return a description of this policy
204         * @since 1.0.0
205         */
206        @Override
207        @NonNull
208        public String toString() {
209                return getClass().getSimpleName() + "{name=" + this.name + "}";
210        }
211
212        /**
213         * Compares a URI scheme with a lower-case ASCII expectation, folding ASCII letters only.
214         */
215        private static boolean isAsciiCaseInsensitiveMatch(@NonNull String value,
216                                                                                                                                                                                                                 @NonNull String lowerCaseExpected) {
217                if (value.length() != lowerCaseExpected.length())
218                        return false;
219
220                for (int i = 0; i < value.length(); ++i) {
221                        char c = value.charAt(i);
222                        char lowerCase = c >= 'A' && c <= 'Z' ? (char) (c + ('a' - 'A')) : c;
223                        if (lowerCase != lowerCaseExpected.charAt(i))
224                                return false;
225                }
226
227                return true;
228        }
229}