WebKit.WebsitePoliciesAutoplayQuirks API test times out with async policy delegates
[WebKit-https.git] / Source / WebCore / loader / PolicyChecker.cpp
1 /*
2  * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
4  * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer. 
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution. 
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission. 
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "PolicyChecker.h"
33
34 #include "ContentFilter.h"
35 #include "ContentSecurityPolicy.h"
36 #include "DOMWindow.h"
37 #include "DocumentLoader.h"
38 #include "Event.h"
39 #include "EventNames.h"
40 #include "FormState.h"
41 #include "Frame.h"
42 #include "FrameLoader.h"
43 #include "FrameLoaderClient.h"
44 #include "HTMLFormElement.h"
45 #include "HTMLFrameOwnerElement.h"
46 #include "HTMLPlugInElement.h"
47 #include <wtf/CompletionHandler.h>
48
49 #if USE(QUICK_LOOK)
50 #include "QuickLook.h"
51 #endif
52
53 namespace WebCore {
54
55 static bool isAllowedByContentSecurityPolicy(const URL& url, const Element* ownerElement, bool didReceiveRedirectResponse)
56 {
57     if (!ownerElement)
58         return true;
59     // Elements in user agent show tree should load whatever the embedding document policy is.
60     if (ownerElement->isInUserAgentShadowTree())
61         return true;
62
63     auto redirectResponseReceived = didReceiveRedirectResponse ? ContentSecurityPolicy::RedirectResponseReceived::Yes : ContentSecurityPolicy::RedirectResponseReceived::No;
64
65     ASSERT(ownerElement->document().contentSecurityPolicy());
66     if (is<HTMLPlugInElement>(ownerElement))
67         return ownerElement->document().contentSecurityPolicy()->allowObjectFromSource(url, redirectResponseReceived);
68     return ownerElement->document().contentSecurityPolicy()->allowChildFrameFromSource(url, redirectResponseReceived);
69 }
70
71 PolicyChecker::PolicyChecker(Frame& frame)
72     : m_frame(frame)
73     , m_delegateIsDecidingNavigationPolicy(false)
74     , m_delegateIsHandlingUnimplementablePolicy(false)
75     , m_loadType(FrameLoadType::Standard)
76 {
77 }
78
79 void PolicyChecker::checkNavigationPolicy(ResourceRequest&& newRequest, bool didReceiveRedirectResponse, NavigationPolicyDecisionFunction&& function)
80 {
81     checkNavigationPolicy(WTFMove(newRequest), didReceiveRedirectResponse, m_frame.loader().activeDocumentLoader(), nullptr, WTFMove(function));
82 }
83
84 void PolicyChecker::checkNavigationPolicy(ResourceRequest&& request, bool didReceiveRedirectResponse, DocumentLoader* loader, FormState* formState, NavigationPolicyDecisionFunction&& function)
85 {
86     NavigationAction action = loader->triggeringAction();
87     if (action.isEmpty()) {
88         action = NavigationAction { *m_frame.document(), request, InitiatedByMainFrame::Unknown, NavigationType::Other, loader->shouldOpenExternalURLsPolicyToPropagate() };
89         loader->setTriggeringAction(action);
90     }
91
92     // Don't ask more than once for the same request or if we are loading an empty URL.
93     // This avoids confusion on the part of the client.
94     if (equalIgnoringHeaderFields(request, loader->lastCheckedRequest()) || (!request.isNull() && request.url().isEmpty())) {
95         function(ResourceRequest(request), nullptr, true);
96         loader->setLastCheckedRequest(WTFMove(request));
97         return;
98     }
99
100     // We are always willing to show alternate content for unreachable URLs;
101     // treat it like a reload so it maintains the right state for b/f list.
102     auto& substituteData = loader->substituteData();
103     if (substituteData.isValid() && !substituteData.failingURL().isEmpty()) {
104         bool shouldContinue = true;
105 #if ENABLE(CONTENT_FILTERING)
106         shouldContinue = ContentFilter::continueAfterSubstituteDataRequest(*m_frame.loader().activeDocumentLoader(), substituteData);
107 #endif
108         if (isBackForwardLoadType(m_loadType))
109             m_loadType = FrameLoadType::Reload;
110         function(WTFMove(request), nullptr, shouldContinue);
111         return;
112     }
113
114     if (!isAllowedByContentSecurityPolicy(request.url(), m_frame.ownerElement(), didReceiveRedirectResponse)) {
115         if (m_frame.ownerElement()) {
116             // Fire a load event (even though we were blocked by CSP) as timing attacks would otherwise
117             // reveal that the frame was blocked. This way, it looks like any other cross-origin page load.
118             m_frame.ownerElement()->dispatchEvent(Event::create(eventNames().loadEvent, false, false));
119         }
120         function(WTFMove(request), nullptr, false);
121         return;
122     }
123
124     loader->setLastCheckedRequest(ResourceRequest(request));
125
126     if (request.url() == blankURL())
127         return function(WTFMove(request), formState, true);
128
129 #if USE(QUICK_LOOK)
130     // Always allow QuickLook-generated URLs based on the protocol scheme.
131     if (!request.isNull() && isQuickLookPreviewURL(request.url()))
132         return function(WTFMove(request), formState, true);
133 #endif
134
135 #if ENABLE(CONTENT_FILTERING)
136     if (m_contentFilterUnblockHandler.canHandleRequest(request)) {
137         RefPtr<Frame> frame { &m_frame };
138         m_contentFilterUnblockHandler.requestUnblockAsync([frame](bool unblocked) {
139             if (unblocked)
140                 frame->loader().reload();
141         });
142         return function({ }, nullptr, false);
143     }
144     m_contentFilterUnblockHandler = { };
145 #endif
146
147     m_frame.loader().clearProvisionalLoadForPolicyCheck();
148
149     m_delegateIsDecidingNavigationPolicy = true;
150     String suggestedFilename = action.downloadAttribute().isEmpty() ? nullAtom() : action.downloadAttribute();
151     ResourceRequest requestCopy = request;
152     m_frame.loader().client().dispatchDecidePolicyForNavigationAction(action, request, didReceiveRedirectResponse, formState, [this, function = WTFMove(function), request = WTFMove(requestCopy), formState = makeRefPtr(formState), suggestedFilename = WTFMove(suggestedFilename)](PolicyAction policyAction) mutable {
153         m_delegateIsDecidingNavigationPolicy = false;
154
155         switch (policyAction) {
156         case PolicyAction::Download:
157             m_frame.loader().setOriginalURLForDownloadRequest(request);
158             m_frame.loader().client().startDownload(request, suggestedFilename);
159             FALLTHROUGH;
160         case PolicyAction::Ignore:
161             return function({ }, nullptr, false);
162         case PolicyAction::Use:
163             if (!m_frame.loader().client().canHandleRequest(request)) {
164                 handleUnimplementablePolicy(m_frame.loader().client().cannotShowURLError(request));
165                 return function({ }, nullptr, false);
166             }
167             return function(WTFMove(request), formState.get(), true);
168         }
169         ASSERT_NOT_REACHED();
170     });
171 }
172
173 void PolicyChecker::checkNewWindowPolicy(NavigationAction&& navigationAction, const ResourceRequest& request, FormState* formState, const String& frameName, NewWindowPolicyDecisionFunction&& function)
174 {
175     if (m_frame.document() && m_frame.document()->isSandboxed(SandboxPopups))
176         return function({ }, nullptr, { }, { }, false);
177
178     if (!DOMWindow::allowPopUp(m_frame))
179         return function({ }, nullptr, { }, { }, false);
180
181     m_frame.loader().client().dispatchDecidePolicyForNewWindowAction(navigationAction, request, formState, frameName, [frame = makeRef(m_frame), request, formState = makeRefPtr(formState), frameName, navigationAction, function = WTFMove(function)](PolicyAction policyAction) mutable {
182         switch (policyAction) {
183         case PolicyAction::Download:
184             frame->loader().client().startDownload(request);
185             FALLTHROUGH;
186         case PolicyAction::Ignore:
187             function({ }, nullptr, { }, { }, false);
188             return;
189         case PolicyAction::Use:
190             function(request, formState.get(), frameName, navigationAction, true);
191             return;
192         }
193         ASSERT_NOT_REACHED();
194     });
195 }
196
197 void PolicyChecker::stopCheck()
198 {
199     m_frame.loader().client().cancelPolicyCheck();
200 }
201
202 void PolicyChecker::cannotShowMIMEType(const ResourceResponse& response)
203 {
204     handleUnimplementablePolicy(m_frame.loader().client().cannotShowMIMETypeError(response));
205 }
206
207 void PolicyChecker::handleUnimplementablePolicy(const ResourceError& error)
208 {
209     m_delegateIsHandlingUnimplementablePolicy = true;
210     m_frame.loader().client().dispatchUnableToImplementPolicy(error);
211     m_delegateIsHandlingUnimplementablePolicy = false;
212 }
213
214 } // namespace WebCore