1/*
2 * Copyright (C) 2008, 2009 Apple Inc. All Rights Reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 *
25 */
26
27#include "config.h"
28#include "CrossOriginPreflightResultCache.h"
29
30#include "CrossOriginAccessControl.h"
31#include "HTTPHeaderNames.h"
32#include "HTTPParsers.h"
33#include "ResourceResponse.h"
34#include <wtf/MainThread.h>
35#include <wtf/NeverDestroyed.h>
36
37namespace WebCore {
38
39// These values are at the discretion of the user agent.
40static const auto defaultPreflightCacheTimeout = 5_s;
41static const auto maxPreflightCacheTimeout = 600_s; // Should be short enough to minimize the risk of using a poisoned cache after switching to a secure network.
42
43CrossOriginPreflightResultCache::CrossOriginPreflightResultCache()
44{
45}
46
47static bool parseAccessControlMaxAge(const String& string, Seconds& expiryDelta)
48{
49 // FIXME: this will not do the correct thing for a number starting with a '+'
50 bool ok = false;
51 expiryDelta = Seconds(static_cast<double>(string.toUIntStrict(&ok)));
52 return ok;
53}
54
55bool CrossOriginPreflightResultCacheItem::parse(const ResourceResponse& response)
56{
57 m_methods = parseAccessControlAllowList(response.httpHeaderField(HTTPHeaderName::AccessControlAllowMethods));
58 m_headers = parseAccessControlAllowList<ASCIICaseInsensitiveHash>(response.httpHeaderField(HTTPHeaderName::AccessControlAllowHeaders));
59
60 Seconds expiryDelta = 0_s;
61 if (parseAccessControlMaxAge(response.httpHeaderField(HTTPHeaderName::AccessControlMaxAge), expiryDelta)) {
62 if (expiryDelta > maxPreflightCacheTimeout)
63 expiryDelta = maxPreflightCacheTimeout;
64 } else
65 expiryDelta = defaultPreflightCacheTimeout;
66
67 m_absoluteExpiryTime = MonotonicTime::now() + expiryDelta;
68 return true;
69}
70
71bool CrossOriginPreflightResultCacheItem::allowsCrossOriginMethod(const String& method, String& errorDescription) const
72{
73 if (m_methods.contains(method) || isOnAccessControlSimpleRequestMethodWhitelist(method))
74 return true;
75
76 errorDescription = "Method " + method + " is not allowed by Access-Control-Allow-Methods.";
77 return false;
78}
79
80bool CrossOriginPreflightResultCacheItem::allowsCrossOriginHeaders(const HTTPHeaderMap& requestHeaders, String& errorDescription) const
81{
82 for (const auto& header : requestHeaders) {
83 if (header.keyAsHTTPHeaderName && isCrossOriginSafeRequestHeader(header.keyAsHTTPHeaderName.value(), header.value))
84 continue;
85 if (!m_headers.contains(header.key)) {
86 errorDescription = "Request header field " + header.key + " is not allowed by Access-Control-Allow-Headers.";
87 return false;
88 }
89 }
90 return true;
91}
92
93bool CrossOriginPreflightResultCacheItem::allowsRequest(StoredCredentialsPolicy storedCredentialsPolicy, const String& method, const HTTPHeaderMap& requestHeaders) const
94{
95 String ignoredExplanation;
96 if (m_absoluteExpiryTime < MonotonicTime::now())
97 return false;
98 if (storedCredentialsPolicy == StoredCredentialsPolicy::Use && m_storedCredentialsPolicy == StoredCredentialsPolicy::DoNotUse)
99 return false;
100 if (!allowsCrossOriginMethod(method, ignoredExplanation))
101 return false;
102 if (!allowsCrossOriginHeaders(requestHeaders, ignoredExplanation))
103 return false;
104 return true;
105}
106
107CrossOriginPreflightResultCache& CrossOriginPreflightResultCache::singleton()
108{
109 ASSERT(isMainThread());
110
111 static NeverDestroyed<CrossOriginPreflightResultCache> cache;
112 return cache;
113}
114
115void CrossOriginPreflightResultCache::appendEntry(const String& origin, const URL& url, std::unique_ptr<CrossOriginPreflightResultCacheItem> preflightResult)
116{
117 ASSERT(isMainThread());
118 m_preflightHashMap.set(std::make_pair(origin, url), WTFMove(preflightResult));
119}
120
121bool CrossOriginPreflightResultCache::canSkipPreflight(const String& origin, const URL& url, StoredCredentialsPolicy storedCredentialsPolicy, const String& method, const HTTPHeaderMap& requestHeaders)
122{
123 ASSERT(isMainThread());
124 auto it = m_preflightHashMap.find(std::make_pair(origin, url));
125 if (it == m_preflightHashMap.end())
126 return false;
127
128 if (it->value->allowsRequest(storedCredentialsPolicy, method, requestHeaders))
129 return true;
130
131 m_preflightHashMap.remove(it);
132 return false;
133}
134
135void CrossOriginPreflightResultCache::clear()
136{
137 ASSERT(isMainThread());
138 m_preflightHashMap.clear();
139}
140
141} // namespace WebCore
142