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.httpclient;
16  
17  import java.util.ArrayList;
18  import java.util.Date;
19  import java.util.List;
20  import java.util.Locale;
21  
22  import org.apache.http.client.CookieStore;
23  import org.apache.http.cookie.ClientCookie;
24  import org.apache.http.cookie.Cookie;
25  import org.apache.http.impl.cookie.BasicClientCookie;
26  
27  /**
28   * A {@link CookieStore} used for one request; returns only the cookies that are allowed
29   * by their SameSite attribute (all other operations are delegated).
30   * <p>Like the browsers, for a cross-site request</p>
31   * <ul>
32   *   <li>'None' cookies are always sent (they are secure, see {@link HtmlUnitSameSiteHandler})</li>
33   *   <li>'Strict' cookies are never sent</li>
34   *   <li>'Lax' cookies are only sent for top-level navigations with a safe method (e.g. GET)</li>
35   *   <li>cookies without (or with an invalid) SameSite attribute are handled as 'Lax'; additionally
36   *       they are sent for top-level navigations with an unsafe method (e.g. POST) within two minutes
37   *       after they were created (Lax-allowing-unsafe)</li>
38   * </ul>
39   *
40   * @author Ronald Brill
41   * @see <a href="https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#name-samesite-cookies">
42   *     RFC 6265bis - SameSite Cookies</a>
43   */
44  public final class HtmlUnitSameSiteCookieStore implements CookieStore {
45  
46      /** Cookies without SameSite attribute are sent for unsafe top-level navigations for this time. */
47      private static final long LAX_ALLOWING_UNSAFE_MILLIS = 2 * 60 * 1000;
48  
49      private final CookieStore delegate_;
50      private final boolean topLevelNavigation_;
51      private final boolean safeMethod_;
52  
53      /**
54       * Ctor.
55       *
56       * @param delegate the cookie store providing all cookies
57       * @param topLevelNavigation whether the (cross-site) request is a top-level navigation
58       * @param safeMethod whether the request uses a safe method (GET, HEAD, OPTIONS, TRACE)
59       */
60      public HtmlUnitSameSiteCookieStore(final CookieStore delegate,
61              final boolean topLevelNavigation, final boolean safeMethod) {
62          delegate_ = delegate;
63          topLevelNavigation_ = topLevelNavigation;
64          safeMethod_ = safeMethod;
65      }
66  
67      /**
68       * {@inheritDoc}
69       */
70      @Override
71      public void addCookie(final Cookie cookie) {
72          delegate_.addCookie(cookie);
73      }
74  
75      /**
76       * Returns the cookies that are allowed to be sent with this cross-site request.
77       * {@inheritDoc}
78       */
79      @Override
80      public List<Cookie> getCookies() {
81          final long now = System.currentTimeMillis();
82          final List<Cookie> result = new ArrayList<>();
83          for (final Cookie cookie : delegate_.getCookies()) {
84              if (isAllowed(cookie, now)) {
85                  result.add(cookie);
86              }
87          }
88          return result;
89      }
90  
91      private boolean isAllowed(final Cookie cookie, final long now) {
92          String sameSite = null;
93          if (cookie instanceof ClientCookie clientCookie) {
94              sameSite = clientCookie.getAttribute(HtmlUnitSameSiteHandler.SAMESITE_ATTR);
95          }
96          if (sameSite != null) {
97              sameSite = sameSite.toLowerCase(Locale.ROOT);
98          }
99  
100         if ("none".equals(sameSite)) {
101             return true;
102         }
103         if ("strict".equals(sameSite)) {
104             return false;
105         }
106         if (!topLevelNavigation_) {
107             return false;
108         }
109         if (safeMethod_) {
110             return true;
111         }
112         if ("lax".equals(sameSite)) {
113             return false;
114         }
115 
116         // no (or an invalid) SameSite attribute: Lax-allowing-unsafe
117         if (cookie instanceof BasicClientCookie basicClientCookie) {
118             final Date creationDate = basicClientCookie.getCreationDate();
119             return creationDate != null && now - creationDate.getTime() < LAX_ALLOWING_UNSAFE_MILLIS;
120         }
121         return false;
122     }
123 
124     /**
125      * {@inheritDoc}
126      */
127     @Override
128     public boolean clearExpired(final Date date) {
129         return delegate_.clearExpired(date);
130     }
131 
132     /**
133      * {@inheritDoc}
134      */
135     @Override
136     public void clear() {
137         delegate_.clear();
138     }
139 }