View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.javascript.host.fetch;
16  
17  import static java.nio.charset.StandardCharsets.ISO_8859_1;
18  import static java.nio.charset.StandardCharsets.UTF_8;
19  import static org.htmlunit.BrowserVersionFeatures.XHR_PREFLIGHT_CORS;
20  
21  import java.io.IOException;
22  import java.net.MalformedURLException;
23  import java.net.URL;
24  import java.util.HashSet;
25  import java.util.Locale;
26  import java.util.Map.Entry;
27  import java.util.Set;
28  import java.util.TreeMap;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.htmlunit.HttpHeader;
33  import org.htmlunit.HttpMethod;
34  import org.htmlunit.WebClient;
35  import org.htmlunit.WebRequest;
36  import org.htmlunit.WebRequest.HttpHint;
37  import org.htmlunit.WebResponse;
38  import org.htmlunit.WebWindow;
39  import org.htmlunit.html.HtmlPage;
40  import org.htmlunit.html.csp.ContentSecurityPolicy;
41  import org.htmlunit.util.NameValuePair;
42  import org.htmlunit.util.StringUtils;
43  import org.htmlunit.util.UrlUtils;
44  
45  /**
46   * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
47   *
48   * The network part of {@code fetch()} and {@code XMLHttpRequest} for requests in 'cors' mode:
49   * the CORS checks, the preflight requests and the redirect handling of the fetch standard.
50   *
51   * @see <a href="https://fetch.spec.whatwg.org/#http-fetch">Fetch Standard - HTTP fetch</a>
52   * @author Ronald Brill
53   */
54  public final class CorsLoader {
55  
56      private static final Log LOG = LogFactory.getLog(CorsLoader.class);
57  
58      // https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name
59      private static final Set<String> CORS_SAFELISTED_RESPONSE_HEADERS = Set.of(
60              "cache-control", "content-language", "content-length", "content-type",
61              "expires", "last-modified", "pragma");
62  
63      private static final String ALLOW_ORIGIN_ALL = "*";
64  
65      private static final int MAX_REDIRECTS = 20;
66  
67      /**
68       * The credentials mode of the request.
69       */
70      public enum CredentialsMode {
71          /** Never send credentials (cookies). */
72          OMIT,
73          /** Send credentials only to the origin of the page. */
74          SAME_ORIGIN,
75          /** Always send credentials; responses of other origins have to allow this. */
76          INCLUDE
77      }
78  
79      /**
80       * The mode of the request (the modes 'navigate' and 'websocket' are not supported here).
81       */
82      public enum RequestMode {
83          /** Requests to other origins have to pass the CORS checks. */
84          CORS,
85          /** Only requests to the origin of the page are allowed (also after redirects). */
86          SAME_ORIGIN,
87          /** Requests to other origins are not checked; their responses are opaque. */
88          NO_CORS
89      }
90  
91      /**
92       * The redirect mode of the request.
93       */
94      public enum RedirectMode {
95          /** Follow the redirects. */
96          FOLLOW,
97          /** A redirect is a network error. */
98          ERROR,
99          /** The redirect response is returned (as opaque redirect). */
100         MANUAL
101     }
102 
103     /**
104      * The result of {@link CorsLoader#load(WebRequest, boolean)}.
105      *
106      * @param response the response
107      * @param url the url of the response
108      * @param redirected whether a redirect was followed
109      * @param corsTainting whether an url of another origin was involved (response tainting 'cors' or,
110      *        for the request mode 'no-cors', 'opaque')
111      * @param opaqueRedirect whether the response is a redirect returned because of {@link RedirectMode#MANUAL}
112      */
113     public record Result(WebResponse response, URL url, boolean redirected,
114             boolean corsTainting, boolean opaqueRedirect) {
115     }
116 
117     /**
118      * Thrown if the CORS check fails.
119      */
120     public static final class NoPermittedHeaderException extends IOException {
121         /**
122          * Ctor.
123          * @param msg the message
124          */
125         public NoPermittedHeaderException(final String msg) {
126             super(msg);
127         }
128     }
129 
130     /**
131      * A redirect that is not allowed (or not possible); this is a network error.
132      */
133     public static final class RedirectException extends IOException {
134         /**
135          * Ctor.
136          * @param msg the message
137          */
138         public RedirectException(final String msg) {
139             super(msg);
140         }
141 
142         /**
143          * Ctor.
144          * @param msg the message
145          * @param cause the cause
146          */
147         public RedirectException(final String msg, final Throwable cause) {
148             super(msg, cause);
149         }
150     }
151 
152     private final WebWindow webWindow_;
153     private final CredentialsMode credentialsMode_;
154     private final RedirectMode redirectMode_;
155     private final int timeout_;
156     private final RequestMode requestMode_;
157 
158     /**
159      * Ctor.
160      *
161      * @param webWindow the window of the page that sends the request
162      * @param credentialsMode the credentials mode
163      * @param redirectMode the redirect mode
164      * @param timeout the timeout for the preflight requests (0 means no timeout)
165      */
166     public CorsLoader(final WebWindow webWindow, final CredentialsMode credentialsMode,
167             final RedirectMode redirectMode, final int timeout) {
168         this(webWindow, credentialsMode, redirectMode, timeout, RequestMode.CORS);
169     }
170 
171     /**
172      * Ctor.
173      *
174      * @param webWindow the window of the page that sends the request
175      * @param credentialsMode the credentials mode
176      * @param redirectMode the redirect mode
177      * @param timeout the timeout for the preflight requests (0 means no timeout)
178      * @param requestMode the request mode
179      */
180     public CorsLoader(final WebWindow webWindow, final CredentialsMode credentialsMode,
181             final RedirectMode redirectMode, final int timeout, final RequestMode requestMode) {
182         webWindow_ = webWindow;
183         credentialsMode_ = credentialsMode;
184         redirectMode_ = redirectMode;
185         timeout_ = timeout;
186         requestMode_ = requestMode;
187     }
188 
189     private boolean isIncludeCredentials() {
190         return credentialsMode_ == CredentialsMode.INCLUDE;
191     }
192 
193     /**
194      * Checks the connect-src directive of the Content-Security-Policy of the page.
195      *
196      * @param url the url to connect to (the request url or a redirect target)
197      * @param reportedUrl the url reported in case of a violation (the url of the request)
198      * @throws IOException if the connection is not allowed
199      */
200     public void ensureConnectionAllowed(final URL url, final URL reportedUrl) throws IOException {
201         if (webWindow_ != null
202                 && webWindow_.getEnclosedPage() instanceof HtmlPage page
203                 && !ContentSecurityPolicy.allowsConnection(page, url, reportedUrl)) {
204             throw new IOException("Refused to connect to '" + url
205                     + "' because it violates the Content Security Policy of the page.");
206         }
207     }
208 
209     /**
210      * Loads the response of the request and follows the redirects the way the
211      * <a href="https://fetch.spec.whatwg.org/#http-redirect-fetch">fetch standard</a> describes it for a
212      * request in cors mode.
213      * <ul>
214      *   <li>only http and https locations are followed, not more than {@value #MAX_REDIRECTS} times</li>
215      *   <li>as soon as a url of another origin is involved, all responses (also the ones that redirect)
216      *       have to pass the CORS check and cookies are only sent if credentials are included</li>
217      *   <li>the Origin header is the one of the page; after a redirect from one foreign origin to another
218      *       one it is 'null'</li>
219      *   <li>a redirect to a foreign url with credentials is a network error</li>
220      *   <li>301/302 (for POST) and 303 switch to GET and drop the body; 307/308 keep method and body</li>
221      *   <li>the Authorization header and the credentials of the request are dropped if the redirect
222      *       leaves the origin</li>
223      * </ul>
224      * The preflight of the (first) request has to be done by the caller.
225      *
226      * @param webRequest the request
227      * @param sameOrigin whether the url of the request has the origin of the page
228      * @return the result
229      * @throws IOException in case of a network error
230      */
231     public Result load(final WebRequest webRequest, final boolean sameOrigin) throws IOException {
232         final WebClient wc = webWindow_.getWebClient();
233         final URL pageUrl = webRequest.getRequestingUrl();
234         final String pageOrigin = serializeOrigin(pageUrl);
235 
236         WebRequest request = webRequest;
237         // the response tainting 'cors' of the fetch standard: as soon as an url of another origin is involved
238         boolean corsTainting = !sameOrigin;
239         // the origin of the request is 'null' after a redirect from one foreign origin to another one
240         boolean taintedOrigin = false;
241 
242         for (int redirects = 0;; redirects++) {
243             // the redirects are handled here, the web client has to return the response as it is
244             request.addHint(HttpHint.DoNotFollowRedirects);
245             if (credentialsMode_ == CredentialsMode.OMIT
246                     || corsTainting && credentialsMode_ == CredentialsMode.SAME_ORIGIN) {
247                 request.addHint(HttpHint.BlockCookies);
248             }
249 
250             final WebResponse response = wc.loadWebResponse(request);
251             final String originHeader = request.getAdditionalHeaders().get(HttpHeader.ORIGIN);
252             final URL currentUrl = request.getUrl();
253 
254             URL nextUrl = wc.getOptions().isRedirectEnabled() ? getRedirectUrl(response, currentUrl) : null;
255             // upgrade-insecure-requests of the Content-Security-Policy
256             if (nextUrl != null && webWindow_.getEnclosedPage() instanceof HtmlPage page) {
257                 nextUrl = ContentSecurityPolicy.upgradeInsecureRequest(page, nextUrl);
258             }
259 
260             // each response of a cors request has to pass the check, also the one that redirects
261             // (in mode 'no-cors' the response is opaque instead)
262             if (corsTainting && requestMode_ != RequestMode.NO_CORS && !isCorsAllowed(response, originHeader)) {
263                 if (LOG.isDebugEnabled()) {
264                     LOG.debug("No permitted \"Access-Control-Allow-Origin\" header for URL " + currentUrl);
265                 }
266                 throw new NoPermittedHeaderException("No permitted \"Access-Control-Allow-Origin\" header.");
267             }
268 
269             if (nextUrl == null) {
270                 return new Result(response, currentUrl, redirects > 0, corsTainting, false);
271             }
272 
273             if (redirectMode_ == RedirectMode.ERROR) {
274                 throw new RedirectException("Redirect for '" + currentUrl + "' with redirect mode 'error'.");
275             }
276             if (redirectMode_ == RedirectMode.MANUAL) {
277                 return new Result(response, currentUrl, redirects > 0, corsTainting, true);
278             }
279 
280             if (redirects >= MAX_REDIRECTS) {
281                 throw new RedirectException("Too many redirects for " + webRequest.getUrl());
282             }
283 
284             ensureConnectionAllowed(nextUrl, webRequest.getUrl());
285 
286             final boolean crossOriginRedirect = !UrlUtils.isSameOrigin(currentUrl, nextUrl);
287             final boolean foreignTarget = !UrlUtils.isSameOrigin(pageUrl, nextUrl);
288             if (requestMode_ == RequestMode.SAME_ORIGIN && foreignTarget) {
289                 throw new RedirectException("Redirect to another origin with request mode 'same-origin': "
290                         + nextUrl);
291             }
292             if (requestMode_ == RequestMode.CORS && nextUrl.getUserInfo() != null
293                     && (corsTainting || foreignTarget)) {
294                 throw new RedirectException("Redirect to a URL with credentials is not allowed: " + currentUrl);
295             }
296 
297             if (crossOriginRedirect && !UrlUtils.isSameOrigin(pageUrl, currentUrl)) {
298                 taintedOrigin = true;
299             }
300             corsTainting = corsTainting || foreignTarget;
301 
302             request = createRedirectRequest(request, response.getStatusCode(), nextUrl, crossOriginRedirect);
303             setOriginHeader(request, corsTainting && requestMode_ != RequestMode.NO_CORS, taintedOrigin, pageOrigin);
304 
305             if (corsTainting && requestMode_ != RequestMode.NO_CORS && isPreflight(request)) {
306                 final WebResponse preflightResponse = sendPreflight(request);
307                 if (!preflightResponse.isSuccessOrUseProxyOrNotModified()
308                         || !isPreflightAuthorized(request, preflightResponse)) {
309                     throw new NoPermittedHeaderException("No permitted \"Access-Control-Allow-Origin\" header.");
310                 }
311             }
312         }
313     }
314 
315     /**
316      * Returns the url a response redirects to.
317      *
318      * @param response the response
319      * @param currentUrl the url the response was loaded from
320      * @return the url or {@code null} if the response is not a redirect (or has no location)
321      * @throws IOException if the location is invalid or not a http(s) url
322      */
323     private static URL getRedirectUrl(final WebResponse response, final URL currentUrl) throws IOException {
324         final int status = response.getStatusCode();
325         if (status != 301 && status != 302 && status != 303 && status != 307 && status != 308) {
326             return null;
327         }
328 
329         String location = response.getResponseHeaderValue("Location");
330         if (location == null) {
331             return null;
332         }
333         location = new String(location.getBytes(ISO_8859_1), UTF_8);
334 
335         final URL url;
336         try {
337             url = WebClient.expandUrl(currentUrl, location);
338         }
339         catch (final MalformedURLException e) {
340             throw new RedirectException("Invalid redirect location '" + location + "'", e);
341         }
342 
343         final String protocol = url.getProtocol();
344         if (!"http".equals(protocol) && !"https".equals(protocol)) {
345             throw new RedirectException("Redirect to the unsupported scheme '" + protocol + "' is not allowed.");
346         }
347         return url;
348     }
349 
350     /**
351      * Creates the request for the target of a redirect.
352      *
353      * @param request the request that was redirected
354      * @param status the status of the redirect response
355      * @param url the target of the redirect
356      * @param crossOriginRedirect whether the redirect leaves the origin of the request
357      * @return the new request
358      */
359     private static WebRequest createRedirectRequest(final WebRequest request, final int status,
360             final URL url, final boolean crossOriginRedirect) {
361         final HttpMethod method = request.getHttpMethod();
362         final boolean toGet = ((status == 301 || status == 302) && method == HttpMethod.POST)
363                 || (status == 303 && method != HttpMethod.GET && method != HttpMethod.HEAD);
364 
365         final WebRequest next = new WebRequest(url, toGet ? HttpMethod.GET : method);
366         next.setCharset(request.getCharset());
367         next.setDefaultResponseContentCharset(request.getDefaultResponseContentCharset());
368         next.setFetchDestination(request.getFetchDestination());
369         next.setFetchModeOverride(request.getFetchModeOverride());
370         next.setRequestingUrl(request.getRequestingUrl());
371         next.setSiteForCookies(request.getSiteForCookies());
372         next.setTimeout(request.getTimeout());
373         next.setCacheMode(request.getCacheMode());
374         if (request.hasHint(HttpHint.IncludeCharsetInContentTypeHeader)) {
375             next.addHint(HttpHint.IncludeCharsetInContentTypeHeader);
376         }
377 
378         for (final Entry<String, String> header : request.getAdditionalHeaders().entrySet()) {
379             next.setAdditionalHeader(header.getKey(), header.getValue());
380         }
381 
382         if (toGet) {
383             // the body is gone, and the headers that describe it
384             next.removeAdditionalHeader(HttpHeader.CONTENT_TYPE);
385             next.removeAdditionalHeader("Content-Length");
386             next.removeAdditionalHeader("Content-Encoding");
387             next.removeAdditionalHeader("Content-Language");
388             next.removeAdditionalHeader("Content-Location");
389         }
390         else if (request.getRequestBody() != null) {
391             next.setRequestBody(request.getRequestBody());
392             next.setEncodingType(request.getEncodingType());
393         }
394         else if (!request.getRequestParameters().isEmpty()) {
395             next.setRequestParameters(request.getRequestParameters());
396         }
397 
398         if (crossOriginRedirect) {
399             // credentials are not forwarded to another origin
400             next.removeAdditionalHeader("Authorization");
401         }
402         else {
403             next.setCredentials(request.getCredentials());
404         }
405         return next;
406     }
407 
408     /**
409      * The Origin header is sent for requests of another origin and for all methods but GET and HEAD.
410      */
411     private static void setOriginHeader(final WebRequest request, final boolean corsTainting,
412             final boolean taintedOrigin, final String pageOrigin) {
413         final HttpMethod method = request.getHttpMethod();
414         if (corsTainting || (method != HttpMethod.GET && method != HttpMethod.HEAD)) {
415             request.setAdditionalHeader(HttpHeader.ORIGIN, taintedOrigin ? "null" : pageOrigin);
416         }
417         else {
418             request.removeAdditionalHeader(HttpHeader.ORIGIN);
419         }
420     }
421 
422     /**
423      * Serializes the origin of the url (scheme, host and port).
424      *
425      * @param url the url
426      * @return the origin
427      */
428     public static String serializeOrigin(final URL url) {
429         final StringBuilder origin = new StringBuilder().append(url.getProtocol()).append("://")
430                 .append(url.getHost());
431         if (url.getPort() != -1) {
432             origin.append(':').append(url.getPort());
433         }
434         return origin.toString();
435     }
436 
437     /**
438      * The CORS check of the fetch standard.
439      *
440      * @param response the response
441      * @param origin the origin sent with the request
442      * @return whether the response passes the check
443      */
444     public boolean isCorsAllowed(final WebResponse response, final String origin) {
445         String value = response.getResponseHeaderValue(HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN);
446         final boolean allowed = origin != null && origin.equals(value);
447         if (isIncludeCredentials()) {
448             // second step: check the allow-credentials header for true
449             value = response.getResponseHeaderValue(HttpHeader.ACCESS_CONTROL_ALLOW_CREDENTIALS);
450             return allowed && Boolean.parseBoolean(value);
451         }
452         return allowed || ALLOW_ORIGIN_ALL.equals(value);
453     }
454 
455     /**
456      * Sends the preflight request for the given request.
457      *
458      * @param request the request
459      * @return the response of the preflight request
460      * @throws IOException in case of a network error
461      */
462     public WebResponse sendPreflight(final WebRequest request) throws IOException {
463         final WebRequest preflightRequest = new WebRequest(request.getUrl(), HttpMethod.OPTIONS);
464         preflightRequest.setEncodingType(null);
465 
466         // preflight request shouldn't have cookies
467         preflightRequest.addHint(HttpHint.BlockCookies);
468 
469         // header origin
470         final String originHeaderValue = request.getAdditionalHeaders().get(HttpHeader.ORIGIN);
471         preflightRequest.setAdditionalHeader(HttpHeader.ORIGIN, originHeaderValue);
472 
473         // header request-method
474         preflightRequest.setAdditionalHeader(
475                 HttpHeader.ACCESS_CONTROL_REQUEST_METHOD,
476                 request.getHttpMethod().name());
477 
478         // header request-headers
479         final StringBuilder builder = new StringBuilder();
480         for (final Entry<String, String> header
481                 : new TreeMap<>(request.getAdditionalHeaders()).entrySet()) {
482             final String name = StringUtils.toRootLowerCase(header.getKey());
483             if (isPreflightHeader(name, header.getValue())) {
484                 if (builder.length() != 0) {
485                     builder.append(',');
486                 }
487                 builder.append(name);
488             }
489         }
490         preflightRequest.setAdditionalHeader(HttpHeader.ACCESS_CONTROL_REQUEST_HEADERS, builder.toString());
491         if (timeout_ > 0) {
492             preflightRequest.setTimeout(timeout_);
493         }
494 
495         final WebClient wc = webWindow_.getWebClient();
496         if (wc.getBrowserVersion().hasFeature(XHR_PREFLIGHT_CORS)) {
497             // preflightRequest.setFetchModeOverride(FetchMode.CORS);
498             preflightRequest.setAdditionalHeader(HttpHeader.SEC_FETCH_MODE, "cors");
499         }
500 
501         if (webWindow_.getEnclosedPage() instanceof HtmlPage containingPage) {
502             preflightRequest.setRefererHeader(containingPage.getUrl());
503             preflightRequest.setReferrerPolicy(containingPage.getReferrerPolicy());
504         }
505 
506         // do the preflight request
507         return wc.loadWebResponse(preflightRequest);
508     }
509 
510     /**
511      * Returns whether the request requires a preflight request (if it is a request to another origin).
512      *
513      * @param request the request
514      * @return whether the request requires a preflight request
515      */
516     public static boolean isPreflight(final WebRequest request) {
517         final HttpMethod method = request.getHttpMethod();
518         if (method != HttpMethod.GET && method != HttpMethod.HEAD && method != HttpMethod.POST) {
519             return true;
520         }
521         for (final Entry<String, String> header : request.getAdditionalHeaders().entrySet()) {
522             if (isPreflightHeader(header.getKey().toLowerCase(Locale.ROOT), header.getValue())) {
523                 return true;
524             }
525         }
526         return false;
527     }
528 
529     /**
530      * Checks the response of the preflight request.
531      *
532      * @param request the request
533      * @param preflightResponse the response of the preflight request
534      * @return whether the request is allowed
535      */
536     public boolean isPreflightAuthorized(final WebRequest request, final WebResponse preflightResponse) {
537         // the preflight response has to pass the CORS check too; for a request with credentials
538         // this requires the exact origin and Access-Control-Allow-Credentials
539         if (!isCorsAllowed(preflightResponse, request.getAdditionalHeaders().get(HttpHeader.ORIGIN))) {
540             return false;
541         }
542 
543         // the wildcard is not supported for requests with credentials
544         final boolean wildcard = !isIncludeCredentials();
545 
546         final HttpMethod method = request.getHttpMethod();
547         if (method != HttpMethod.GET && method != HttpMethod.HEAD && method != HttpMethod.POST
548                 && !isPreflightMethodAllowed(method.name(), preflightResponse, wildcard)) {
549             return false;
550         }
551 
552         // there is no test case for this because the servlet API has no support
553         // for adding the same header twice
554         final HashSet<String> accessControlValues = new HashSet<>();
555         for (final NameValuePair pair : preflightResponse.getResponseHeaders()) {
556             if (HttpHeader.ACCESS_CONTROL_ALLOW_HEADERS.equalsIgnoreCase(pair.getName())) {
557                 String value = pair.getValue();
558                 if (value != null) {
559                     if (wildcard && ALLOW_ORIGIN_ALL.equals(value)) {
560                         // all headers are allowed
561                         return true;
562                     }
563                     value = StringUtils.toRootLowerCase(value);
564                     final String[] values = StringUtils.splitAtComma(value);
565                     for (String part : values) {
566                         part = part.trim();
567                         if (!StringUtils.isEmptyOrNull(part)) {
568                             accessControlValues.add(part);
569                         }
570                     }
571                 }
572             }
573         }
574 
575         for (final Entry<String, String> header : request.getAdditionalHeaders().entrySet()) {
576             final String key = StringUtils.toRootLowerCase(header.getKey());
577             if (isPreflightHeader(key, header.getValue())
578                     && !accessControlValues.contains(key)) {
579                 return false;
580             }
581         }
582         return true;
583     }
584 
585     /**
586      * Checks whether the given method is listed in the Access-Control-Allow-Methods header
587      * of the preflight response (the method names are case-sensitive).
588      *
589      * @param method the method name
590      * @param preflightResponse the preflight response
591      * @param wildcard whether the wildcard '*' allows all methods
592      * @return {@code true} if the method is allowed
593      */
594     private static boolean isPreflightMethodAllowed(final String method, final WebResponse preflightResponse,
595             final boolean wildcard) {
596         for (final NameValuePair pair : preflightResponse.getResponseHeaders()) {
597             if (HttpHeader.ACCESS_CONTROL_ALLOW_METHODS.equalsIgnoreCase(pair.getName())
598                     && pair.getValue() != null) {
599                 for (final String part : StringUtils.splitAtComma(pair.getValue())) {
600                     final String allowed = part.trim();
601                     if (method.equals(allowed) || (wildcard && ALLOW_ORIGIN_ALL.equals(allowed))) {
602                         return true;
603                     }
604                 }
605             }
606         }
607         return false;
608     }
609 
610     /**
611      * Checks whether the given header requires a preflight request. Accept, Accept-Language,
612      * Content-Language and Content-Type need no preflight only if the value is CORS-safelisted.
613      *
614      * @param name the header name (MUST be lower-case for performance reasons)
615      * @param value the header value
616      * @return {@code true} if this header requires a preflight
617      * @see <a href="https://fetch.spec.whatwg.org/#cors-safelisted-request-header">Fetch Standard -
618      *     CORS-safelisted request-header</a>
619      */
620     private static boolean isPreflightHeader(final String name, final String value) {
621         if (HttpHeader.REFERER_LC.equals(name)
622                 || "accept-encoding".equals(name)
623                 || HttpHeader.ORIGIN_LC.equals(name)) {
624             return false;
625         }
626         return !Headers.isCorsSafelistedRequestHeader(name, value);
627     }
628 
629     /**
630      * Set-Cookie and Set-Cookie2 are never exposed to scripts, otherwise HttpOnly cookies are readable.
631      *
632      * @see <a href="https://fetch.spec.whatwg.org/#forbidden-response-header-name">Fetch Standard</a>
633      * @param name the header name
634      * @return {@code true} if the header is a forbidden response header
635      */
636     public static boolean isForbiddenResponseHeader(final String name) {
637         return "set-cookie".equalsIgnoreCase(name) || "set-cookie2".equalsIgnoreCase(name);
638     }
639 
640     /**
641      * Returns whether the response header is visible for scripts. Forbidden response headers are never
642      * visible; for a response of a cross-origin request (response tainting 'cors') only the CORS-safelisted
643      * response headers and the headers listed in Access-Control-Expose-Headers are visible.
644      *
645      * @param response the response
646      * @param name the header name
647      * @param corsTainting whether the response has the response tainting 'cors'
648      * @param includeCredentials whether the request included credentials (the wildcard is not supported then)
649      * @return {@code true} if the header is visible
650      * @see <a href="https://fetch.spec.whatwg.org/#concept-filtered-response-cors">Fetch Standard - CORS filtered
651      *     response</a>
652      */
653     public static boolean isExposedResponseHeader(final WebResponse response, final String name,
654             final boolean corsTainting, final boolean includeCredentials) {
655         if (isForbiddenResponseHeader(name)) {
656             return false;
657         }
658         if (!corsTainting) {
659             return true;
660         }
661 
662         if (name == null) {
663             return false;
664         }
665         final String nameLC = name.toLowerCase(Locale.ROOT);
666         if (CORS_SAFELISTED_RESPONSE_HEADERS.contains(nameLC)) {
667             return true;
668         }
669 
670         for (final NameValuePair header : response.getResponseHeaders()) {
671             if (HttpHeader.ACCESS_CONTROL_EXPOSE_HEADERS.equalsIgnoreCase(header.getName())) {
672                 for (final String token : StringUtils.splitAtComma(header.getValue())) {
673                     final String exposed = token.trim();
674                     // the wildcard is a header name for requests with credentials
675                     if (exposed.equalsIgnoreCase(name) || ("*".equals(exposed) && !includeCredentials)) {
676                         return true;
677                     }
678                 }
679             }
680         }
681         return false;
682     }
683 }