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;
16  
17  import static org.htmlunit.BrowserVersionFeatures.REFERRER_POLICY_IGNORE_CROSS_SITE_RELAXING;
18  
19  import java.net.MalformedURLException;
20  import java.net.URL;
21  import java.util.Locale;
22  
23  import org.htmlunit.util.StringUtils;
24  import org.htmlunit.util.UrlUtils;
25  
26  /**
27   * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
28   *
29   * The referrer policies; a referrer policy determines the referrer (the Referer header)
30   * of a request.
31   *
32   * @author Ronald Brill
33   * @see <a href="https://w3c.github.io/webappsec-referrer-policy/">Referrer Policy</a>
34   */
35  public enum ReferrerPolicy {
36  
37      /** No referrer at all. */
38      NO_REFERRER("no-referrer"),
39  
40      /** The full url, but no referrer from https to http. */
41      NO_REFERRER_WHEN_DOWNGRADE("no-referrer-when-downgrade"),
42  
43      /** The full url for same-origin requests, no referrer for cross-origin requests. */
44      SAME_ORIGIN("same-origin"),
45  
46      /** Only the origin. */
47      ORIGIN("origin"),
48  
49      /** Only the origin, but no referrer from https to http. */
50      STRICT_ORIGIN("strict-origin"),
51  
52      /** The full url for same-origin requests, only the origin for cross-origin requests. */
53      ORIGIN_WHEN_CROSS_ORIGIN("origin-when-cross-origin"),
54  
55      /**
56       * The full url for same-origin requests, only the origin for cross-origin requests,
57       * no referrer from https to http; this is the default.
58       */
59      STRICT_ORIGIN_WHEN_CROSS_ORIGIN("strict-origin-when-cross-origin"),
60  
61      /** Always the full url. */
62      UNSAFE_URL("unsafe-url");
63  
64      /** The default policy. */
65      public static final ReferrerPolicy DEFAULT = STRICT_ORIGIN_WHEN_CROSS_ORIGIN;
66  
67      // the referrer url is limited to 4096 chars, longer urls are replaced by the origin
68      private static final int MAX_REFERRER_LENGTH = 4096;
69  
70      private final String token_;
71  
72      ReferrerPolicy(final String token) {
73          token_ = token;
74      }
75  
76      /**
77       * Returns the token of this policy (e.g. 'no-referrer').
78       *
79       * @return the token
80       */
81      public String getToken() {
82          return token_;
83      }
84  
85      /**
86       * Returns the policy for the given token (case-insensitive); used for the referrerpolicy
87       * attribute.
88       *
89       * @param token the token
90       * @return the policy or {@code null} if the token is not a known policy
91       */
92      public static ReferrerPolicy fromToken(final String token) {
93          if (token == null) {
94              return null;
95          }
96          final String normalized = token.trim().toLowerCase(Locale.ROOT);
97          for (final ReferrerPolicy policy : values()) {
98              if (policy.token_.equals(normalized)) {
99                  return policy;
100             }
101         }
102         return null;
103     }
104 
105     /**
106      * Returns the policy for the content of a meta element with the name 'referrer';
107      * the legacy values ('never', 'default', 'always' and 'origin-when-crossorigin') are supported.
108      *
109      * @param content the content
110      * @return the policy or {@code null} if the content is not a known policy
111      * @see <a href="https://html.spec.whatwg.org/multipage/semantics.html#meta-referrer">meta referrer</a>
112      */
113     public static ReferrerPolicy fromMetaContent(final String content) {
114         if (content == null) {
115             return null;
116         }
117         switch (content.trim().toLowerCase(Locale.ROOT)) {
118             case "never":
119                 return NO_REFERRER;
120             case "default":
121                 return DEFAULT;
122             case "always":
123                 return UNSAFE_URL;
124             case "origin-when-crossorigin":
125                 return ORIGIN_WHEN_CROSS_ORIGIN;
126             default:
127                 return fromToken(content);
128         }
129     }
130 
131     /**
132      * Returns the policy of the value of the Referrer-Policy header: the last known token of the
133      * comma separated list.
134      *
135      * @param headerValue the header value
136      * @return the policy or {@code null} if the value contains no known token
137      * @see <a href="https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header">
138      *     Parse a referrer policy from a Referrer-Policy header</a>
139      */
140     public static ReferrerPolicy fromHeader(final String headerValue) {
141         if (StringUtils.isEmptyOrNull(headerValue)) {
142             return null;
143         }
144         ReferrerPolicy result = null;
145         for (final String token : StringUtils.splitAtComma(headerValue)) {
146             final ReferrerPolicy policy = fromToken(token);
147             if (policy != null) {
148                 result = policy;
149             }
150         }
151         return result;
152     }
153 
154     /**
155      * Determines the referrer for a request to the target url.
156      *
157      * @param referrerUrl the url of the referrer (without user info and ref)
158      * @param targetUrl the url of the request
159      * @param browserVersion the browser version
160      * @return the referrer (the value of the Referer header) or {@code null} if there is no referrer
161      * @see <a href="https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer">
162      *     Determine request's Referrer</a>
163      */
164     public String getReferrer(final URL referrerUrl, final URL targetUrl, final BrowserVersion browserVersion) {
165         final String full = referrerUrl.toExternalForm();
166         final String origin;
167         try {
168             origin = UrlUtils.getUrlWithProtocolAndAuthority(referrerUrl).toExternalForm() + "/";
169         }
170         catch (final MalformedURLException e) {
171             return null;
172         }
173         final String referrer = full.length() > MAX_REFERRER_LENGTH ? origin : full;
174 
175         final boolean sameOrigin = UrlUtils.isSameOrigin(referrerUrl, targetUrl);
176         final boolean downgrade = isTlsProtected(referrerUrl) && !UrlUtils.isPotentiallyTrustworthy(targetUrl);
177 
178         ReferrerPolicy policy = this;
179         if ((policy == UNSAFE_URL || policy == NO_REFERRER_WHEN_DOWNGRADE)
180                 && browserVersion.hasFeature(REFERRER_POLICY_IGNORE_CROSS_SITE_RELAXING)
181                 && !WebClient.isSameSite(referrerUrl, targetUrl)) {
182             // Firefox ignores the less restrictive policies for cross-site requests
183             policy = DEFAULT;
184         }
185 
186         switch (policy) {
187             case NO_REFERRER:
188                 return null;
189             case NO_REFERRER_WHEN_DOWNGRADE:
190                 return downgrade ? null : referrer;
191             case SAME_ORIGIN:
192                 return sameOrigin ? referrer : null;
193             case ORIGIN:
194                 return origin;
195             case STRICT_ORIGIN:
196                 return downgrade ? null : origin;
197             case ORIGIN_WHEN_CROSS_ORIGIN:
198                 return sameOrigin ? referrer : origin;
199             case UNSAFE_URL:
200                 return referrer;
201             case STRICT_ORIGIN_WHEN_CROSS_ORIGIN:
202             default:
203                 if (sameOrigin) {
204                     return referrer;
205                 }
206                 return downgrade ? null : origin;
207         }
208     }
209 
210     private static boolean isTlsProtected(final URL url) {
211         return "https".equals(url.getProtocol()) || "wss".equals(url.getProtocol());
212     }
213 }