Returning NULL from willSendRequest should cancel a load from the memory cache
[WebKit-https.git] / Source / WebCore / loader / CrossOriginAccessControl.cpp
1 /*
2  * Copyright (C) 2008 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 COMPUTER, 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 COMPUTER, 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 "CrossOriginAccessControl.h"
29
30 #include "HTTPParsers.h"
31 #include "ResourceRequest.h"
32 #include "ResourceResponse.h"
33 #include "SecurityOrigin.h"
34 #include <wtf/Threading.h>
35 #include <wtf/text/AtomicString.h>
36 #include <wtf/text/StringBuilder.h>
37
38 namespace WebCore {
39
40 bool isOnAccessControlSimpleRequestMethodWhitelist(const String& method)
41 {
42     return method == "GET" || method == "HEAD" || method == "POST";
43 }
44
45 bool isOnAccessControlSimpleRequestHeaderWhitelist(const String& name, const String& value)
46 {
47     if (equalIgnoringCase(name, "accept")
48         || equalIgnoringCase(name, "accept-language")
49         || equalIgnoringCase(name, "content-language")
50         || equalIgnoringCase(name, "origin")
51         || equalIgnoringCase(name, "referer"))
52         return true;
53
54     // Preflight is required for MIME types that can not be sent via form submission.
55     if (equalIgnoringCase(name, "content-type")) {
56         String mimeType = extractMIMETypeFromMediaType(value);
57         return equalIgnoringCase(mimeType, "application/x-www-form-urlencoded")
58             || equalIgnoringCase(mimeType, "multipart/form-data")
59             || equalIgnoringCase(mimeType, "text/plain");
60     }
61
62     return false;
63 }
64
65 bool isSimpleCrossOriginAccessRequest(const String& method, const HTTPHeaderMap& headerMap)
66 {
67     if (!isOnAccessControlSimpleRequestMethodWhitelist(method))
68         return false;
69
70     HTTPHeaderMap::const_iterator end = headerMap.end();
71     for (HTTPHeaderMap::const_iterator it = headerMap.begin(); it != end; ++it) {
72         if (!isOnAccessControlSimpleRequestHeaderWhitelist(it->key, it->value))
73             return false;
74     }
75
76     return true;
77 }
78
79 static PassOwnPtr<HTTPHeaderSet> createAllowedCrossOriginResponseHeadersSet()
80 {
81     OwnPtr<HTTPHeaderSet> headerSet = adoptPtr(new HashSet<String, CaseFoldingHash>);
82     
83     headerSet->add("cache-control");
84     headerSet->add("content-language");
85     headerSet->add("content-type");
86     headerSet->add("expires");
87     headerSet->add("last-modified");
88     headerSet->add("pragma");
89
90     return headerSet.release();
91 }
92
93 bool isOnAccessControlResponseHeaderWhitelist(const String& name)
94 {
95     AtomicallyInitializedStatic(HTTPHeaderSet*, allowedCrossOriginResponseHeaders = createAllowedCrossOriginResponseHeadersSet().leakPtr());
96
97     return allowedCrossOriginResponseHeaders->contains(name);
98 }
99
100 void updateRequestForAccessControl(ResourceRequest& request, SecurityOrigin* securityOrigin, StoredCredentials allowCredentials)
101 {
102     request.removeCredentials();
103     request.setAllowCookies(allowCredentials == AllowStoredCredentials);
104     request.setHTTPOrigin(securityOrigin->toString());
105 }
106
107 ResourceRequest createAccessControlPreflightRequest(const ResourceRequest& request, SecurityOrigin* securityOrigin)
108 {
109     ResourceRequest preflightRequest(request.url());
110     updateRequestForAccessControl(preflightRequest, securityOrigin, DoNotAllowStoredCredentials);
111     preflightRequest.setHTTPMethod("OPTIONS");
112     preflightRequest.setHTTPHeaderField("Access-Control-Request-Method", request.httpMethod());
113     preflightRequest.setPriority(request.priority());
114
115     const HTTPHeaderMap& requestHeaderFields = request.httpHeaderFields();
116
117     if (requestHeaderFields.size() > 0) {
118         StringBuilder headerBuffer;
119         HTTPHeaderMap::const_iterator it = requestHeaderFields.begin();
120         headerBuffer.append(it->key);
121         ++it;
122
123         HTTPHeaderMap::const_iterator end = requestHeaderFields.end();
124         for (; it != end; ++it) {
125             headerBuffer.append(',');
126             headerBuffer.append(' ');
127             headerBuffer.append(it->key);
128         }
129
130         preflightRequest.setHTTPHeaderField("Access-Control-Request-Headers", headerBuffer.toString().lower());
131     }
132
133     return preflightRequest;
134 }
135
136 bool passesAccessControlCheck(const ResourceResponse& response, StoredCredentials includeCredentials, SecurityOrigin* securityOrigin, String& errorDescription)
137 {
138     AtomicallyInitializedStatic(AtomicString&, accessControlAllowOrigin = *new AtomicString("access-control-allow-origin", AtomicString::ConstructFromLiteral));
139     AtomicallyInitializedStatic(AtomicString&, accessControlAllowCredentials = *new AtomicString("access-control-allow-credentials", AtomicString::ConstructFromLiteral));
140
141     // A wildcard Access-Control-Allow-Origin can not be used if credentials are to be sent,
142     // even with Access-Control-Allow-Credentials set to true.
143     const String& accessControlOriginString = response.httpHeaderField(accessControlAllowOrigin);
144     if (accessControlOriginString == "*" && includeCredentials == DoNotAllowStoredCredentials)
145         return true;
146
147     if (securityOrigin->isUnique()) {
148         errorDescription = "Cannot make any requests from " + securityOrigin->toString() + ".";
149         return false;
150     }
151
152     // FIXME: Access-Control-Allow-Origin can contain a list of origins.
153     if (accessControlOriginString != securityOrigin->toString()) {
154         if (accessControlOriginString == "*")
155             errorDescription = "Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.";
156         else
157             errorDescription =  "Origin " + securityOrigin->toString() + " is not allowed by Access-Control-Allow-Origin.";
158         return false;
159     }
160
161     if (includeCredentials == AllowStoredCredentials) {
162         const String& accessControlCredentialsString = response.httpHeaderField(accessControlAllowCredentials);
163         if (accessControlCredentialsString != "true") {
164             errorDescription = "Credentials flag is true, but Access-Control-Allow-Credentials is not \"true\".";
165             return false;
166         }
167     }
168
169     return true;
170 }
171
172 void parseAccessControlExposeHeadersAllowList(const String& headerValue, HTTPHeaderSet& headerSet)
173 {
174     Vector<String> headers;
175     headerValue.split(',', false, headers);
176     for (unsigned headerCount = 0; headerCount < headers.size(); headerCount++) {
177         String strippedHeader = headers[headerCount].stripWhiteSpace();
178         if (!strippedHeader.isEmpty())
179             headerSet.add(strippedHeader);
180     }
181 }
182
183 } // namespace WebCore