Backed out changeset 2450366cf7ca (bug 1891629) for causing win msix mochitest failures
[gecko.git] / dom / base / PostMessageEvent.cpp
blobf1ede5dc6f7e2eceab708b71c4ba12c35261bed6
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "PostMessageEvent.h"
9 #include "MessageEvent.h"
10 #include "mozilla/dom/BrowsingContext.h"
11 #include "mozilla/dom/BrowsingContextGroup.h"
12 #include "mozilla/dom/DocGroup.h"
13 #include "mozilla/dom/DocumentInlines.h"
14 #include "mozilla/dom/MessageEventBinding.h"
15 #include "mozilla/dom/MessagePort.h"
16 #include "mozilla/dom/RootedDictionary.h"
17 #include "mozilla/BasePrincipal.h"
18 #include "mozilla/EventDispatcher.h"
19 #include "mozilla/StaticPrefs_dom.h"
20 #include "nsDocShell.h"
21 #include "nsGlobalWindowInner.h"
22 #include "nsGlobalWindowOuter.h"
23 #include "nsIConsoleService.h"
24 #include "nsIPrincipal.h"
25 #include "nsIScriptError.h"
26 #include "nsPresContext.h"
27 #include "nsQueryObject.h"
28 #include "nsServiceManagerUtils.h"
30 namespace mozilla::dom {
32 PostMessageEvent::PostMessageEvent(BrowsingContext* aSource,
33 const nsAString& aCallerOrigin,
34 nsGlobalWindowOuter* aTargetWindow,
35 nsIPrincipal* aProvidedPrincipal,
36 uint64_t aCallerWindowID, nsIURI* aCallerURI,
37 const nsCString& aScriptLocation,
38 bool aIsFromPrivateWindow,
39 const Maybe<nsID>& aCallerAgentClusterId)
40 : Runnable("dom::PostMessageEvent"),
41 mSource(aSource),
42 mCallerOrigin(aCallerOrigin),
43 mTargetWindow(aTargetWindow),
44 mProvidedPrincipal(aProvidedPrincipal),
45 mCallerWindowID(aCallerWindowID),
46 mCallerAgentClusterId(aCallerAgentClusterId),
47 mCallerURI(aCallerURI),
48 mScriptLocation(Some(aScriptLocation)),
49 mIsFromPrivateWindow(aIsFromPrivateWindow) {}
51 PostMessageEvent::~PostMessageEvent() = default;
53 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230, bug 1535398)
54 MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMP PostMessageEvent::Run() {
55 // Note: We don't init this AutoJSAPI with targetWindow, because we do not
56 // want exceptions during message deserialization to trigger error events on
57 // targetWindow.
58 AutoJSAPI jsapi;
59 jsapi.Init();
60 JSContext* cx = jsapi.cx();
62 // The document URI is just used for the principal mismatch error message
63 // below. Use a stack variable so mCallerURI is not held onto after
64 // this method finishes, regardless of the method outcome.
65 nsCOMPtr<nsIURI> callerURI = std::move(mCallerURI);
67 // If we bailed before this point we're going to leak mMessage, but
68 // that's probably better than crashing.
70 RefPtr<nsGlobalWindowInner> targetWindow;
71 if (mTargetWindow->IsClosedOrClosing() ||
72 !(targetWindow = nsGlobalWindowInner::Cast(
73 mTargetWindow->GetCurrentInnerWindow())) ||
74 targetWindow->IsDying())
75 return NS_OK;
77 // If the window's document has suppressed event handling, hand off this event
78 // for running later. We check the top window's document so that when multiple
79 // same-origin windows exist in the same top window, postMessage events will
80 // be delivered in the same order they were posted, regardless of which window
81 // they were posted to.
82 if (nsCOMPtr<nsPIDOMWindowOuter> topWindow =
83 targetWindow->GetOuterWindow()->GetInProcessTop()) {
84 if (nsCOMPtr<nsPIDOMWindowInner> topInner =
85 topWindow->GetCurrentInnerWindow()) {
86 if (topInner->GetExtantDoc() &&
87 topInner->GetExtantDoc()->SuspendPostMessageEvent(this)) {
88 return NS_OK;
93 JSAutoRealm ar(cx, targetWindow->GetWrapper());
95 // Ensure that any origin which might have been provided is the origin of this
96 // window's document. Note that we do this *now* instead of when postMessage
97 // is called because the target window might have been navigated to a
98 // different location between then and now. If this check happened when
99 // postMessage was called, it would be fairly easy for a malicious webpage to
100 // intercept messages intended for another site by carefully timing navigation
101 // of the target window so it changed location after postMessage but before
102 // now.
103 if (mProvidedPrincipal) {
104 // Get the target's origin either from its principal or, in the case the
105 // principal doesn't carry a URI (e.g. the system principal), the target's
106 // document.
107 nsIPrincipal* targetPrin = targetWindow->GetPrincipal();
108 if (NS_WARN_IF(!targetPrin)) return NS_OK;
110 // Note: This is contrary to the spec with respect to file: URLs, which
111 // the spec groups into a single origin, but given we intentionally
112 // don't do that in other places it seems better to hold the line for
113 // now. Long-term, we want HTML5 to address this so that we can
114 // be compliant while being safer.
115 if (!targetPrin->Equals(mProvidedPrincipal)) {
116 OriginAttributes sourceAttrs = mProvidedPrincipal->OriginAttributesRef();
117 OriginAttributes targetAttrs = targetPrin->OriginAttributesRef();
119 MOZ_DIAGNOSTIC_ASSERT(
120 sourceAttrs.mUserContextId == targetAttrs.mUserContextId,
121 "Target and source should have the same userContextId attribute.");
123 nsAutoString providedOrigin, targetOrigin;
124 nsresult rv = nsContentUtils::GetWebExposedOriginSerialization(
125 targetPrin, targetOrigin);
126 NS_ENSURE_SUCCESS(rv, rv);
127 rv = nsContentUtils::GetWebExposedOriginSerialization(mProvidedPrincipal,
128 providedOrigin);
129 NS_ENSURE_SUCCESS(rv, rv);
131 nsAutoString errorText;
132 nsContentUtils::FormatLocalizedString(
133 errorText, nsContentUtils::eDOM_PROPERTIES,
134 "TargetPrincipalDoesNotMatch", providedOrigin, targetOrigin);
136 nsCOMPtr<nsIScriptError> errorObject =
137 do_CreateInstance(NS_SCRIPTERROR_CONTRACTID, &rv);
138 NS_ENSURE_SUCCESS(rv, rv);
140 if (mCallerWindowID == 0) {
141 rv = errorObject->Init(
142 errorText, NS_ConvertUTF8toUTF16(mScriptLocation.value()), u""_ns,
143 0, 0, nsIScriptError::errorFlag, "DOM Window"_ns,
144 mIsFromPrivateWindow, mProvidedPrincipal->IsSystemPrincipal());
145 } else if (callerURI) {
146 rv = errorObject->InitWithSourceURI(errorText, callerURI, u""_ns, 0, 0,
147 nsIScriptError::errorFlag,
148 "DOM Window"_ns, mCallerWindowID);
149 } else {
150 rv = errorObject->InitWithWindowID(
151 errorText, NS_ConvertUTF8toUTF16(mScriptLocation.value()), u""_ns,
152 0, 0, nsIScriptError::errorFlag, "DOM Window"_ns, mCallerWindowID);
154 NS_ENSURE_SUCCESS(rv, rv);
156 nsCOMPtr<nsIConsoleService> consoleService =
157 do_GetService(NS_CONSOLESERVICE_CONTRACTID, &rv);
158 NS_ENSURE_SUCCESS(rv, rv);
160 return consoleService->LogMessage(errorObject);
164 IgnoredErrorResult rv;
165 JS::Rooted<JS::Value> messageData(cx);
166 nsCOMPtr<mozilla::dom::EventTarget> eventTarget =
167 do_QueryObject(targetWindow);
169 JS::CloneDataPolicy cloneDataPolicy;
171 MOZ_DIAGNOSTIC_ASSERT(targetWindow);
172 if (mCallerAgentClusterId.isSome() && targetWindow->GetDocGroup() &&
173 targetWindow->GetDocGroup()->AgentClusterId().Equals(
174 mCallerAgentClusterId.ref())) {
175 cloneDataPolicy.allowIntraClusterClonableSharedObjects();
178 if (targetWindow->IsSharedMemoryAllowed()) {
179 cloneDataPolicy.allowSharedMemoryObjects();
182 if (mHolder.empty()) {
183 DispatchError(cx, targetWindow, eventTarget);
184 return NS_OK;
187 StructuredCloneHolder* holder;
188 if (mHolder.constructed<StructuredCloneHolder>()) {
189 mHolder.ref<StructuredCloneHolder>().Read(
190 targetWindow->AsGlobal(), cx, &messageData, cloneDataPolicy, rv);
191 holder = &mHolder.ref<StructuredCloneHolder>();
192 } else {
193 MOZ_ASSERT(mHolder.constructed<ipc::StructuredCloneData>());
194 mHolder.ref<ipc::StructuredCloneData>().Read(cx, &messageData, rv);
195 holder = &mHolder.ref<ipc::StructuredCloneData>();
197 if (NS_WARN_IF(rv.Failed())) {
198 JS_ClearPendingException(cx);
199 DispatchError(cx, targetWindow, eventTarget);
200 return NS_OK;
203 // Create the event
204 RefPtr<MessageEvent> event = new MessageEvent(eventTarget, nullptr, nullptr);
206 Nullable<WindowProxyOrMessagePortOrServiceWorker> source;
207 if (mSource) {
208 source.SetValue().SetAsWindowProxy() = mSource;
211 Sequence<OwningNonNull<MessagePort>> ports;
212 if (!holder->TakeTransferredPortsAsSequence(ports)) {
213 DispatchError(cx, targetWindow, eventTarget);
214 return NS_OK;
217 event->InitMessageEvent(nullptr, u"message"_ns, CanBubble::eNo,
218 Cancelable::eNo, messageData, mCallerOrigin, u""_ns,
219 source, ports);
221 Dispatch(targetWindow, event);
222 return NS_OK;
225 void PostMessageEvent::DispatchError(JSContext* aCx,
226 nsGlobalWindowInner* aTargetWindow,
227 mozilla::dom::EventTarget* aEventTarget) {
228 RootedDictionary<MessageEventInit> init(aCx);
229 init.mBubbles = false;
230 init.mCancelable = false;
231 init.mOrigin = mCallerOrigin;
233 if (mSource) {
234 init.mSource.SetValue().SetAsWindowProxy() = mSource;
237 RefPtr<Event> event =
238 MessageEvent::Constructor(aEventTarget, u"messageerror"_ns, init);
239 Dispatch(aTargetWindow, event);
242 void PostMessageEvent::Dispatch(nsGlobalWindowInner* aTargetWindow,
243 Event* aEvent) {
244 // We can't simply call dispatchEvent on the window because doing so ends
245 // up flipping the trusted bit on the event, and we don't want that to
246 // happen because then untrusted content can call postMessage on a chrome
247 // window if it can get a reference to it.
249 RefPtr<nsPresContext> presContext =
250 aTargetWindow->GetExtantDoc()->GetPresContext();
252 aEvent->SetTrusted(true);
253 WidgetEvent* internalEvent = aEvent->WidgetEventPtr();
255 nsEventStatus status = nsEventStatus_eIgnore;
256 EventDispatcher::Dispatch(aTargetWindow, presContext, internalEvent, aEvent,
257 &status);
260 static nsresult MaybeThrottle(nsGlobalWindowOuter* aTargetWindow,
261 PostMessageEvent* aEvent) {
262 BrowsingContext* bc = aTargetWindow->GetBrowsingContext();
263 if (!bc) {
264 return NS_ERROR_FAILURE;
266 bc = bc->Top();
267 if (!bc->IsLoading()) {
268 return NS_ERROR_FAILURE;
270 if (nsContentUtils::IsPDFJS(aTargetWindow->GetPrincipal())) {
271 // pdf.js is known to block the load event on a worker's postMessage event.
272 // Avoid throttling postMessage for pdf.js to avoid pathological wait times,
273 // see bug 1840762.
274 return NS_ERROR_FAILURE;
276 if (!StaticPrefs::dom_separate_event_queue_for_post_message_enabled()) {
277 return NS_ERROR_FAILURE;
279 return bc->Group()->QueuePostMessageEvent(aEvent);
282 void PostMessageEvent::DispatchToTargetThread(ErrorResult& aError) {
283 if (NS_SUCCEEDED(MaybeThrottle(mTargetWindow, this))) {
284 return;
286 aError = mTargetWindow->Dispatch(do_AddRef(this));
289 } // namespace mozilla::dom