Bug 1899501 - Part 2: Implement explicit resource management opcodes in Warp. r=arai...
[gecko.git] / dom / midi / MIDIPermissionRequest.cpp
blob5d2581c56b38cebd927d3c820d5233e552b9172f
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sw=2 sts=2 et cindent: */
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 file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/dom/MIDIPermissionRequest.h"
8 #include "mozilla/dom/Document.h"
9 #include "mozilla/dom/MIDIAccessManager.h"
10 #include "mozilla/dom/MIDIOptionsBinding.h"
11 #include "mozilla/ipc/BackgroundChild.h"
12 #include "mozilla/ipc/PBackgroundChild.h"
13 #include "mozilla/BasePrincipal.h"
14 #include "mozilla/RandomNum.h"
15 #include "mozilla/StaticPrefs_dom.h"
16 #include "nsIGlobalObject.h"
17 #include "mozilla/Preferences.h"
18 #include "nsContentUtils.h"
20 //-------------------------------------------------
21 // MIDI Permission Requests
22 //-------------------------------------------------
24 using namespace mozilla::dom;
26 NS_IMPL_CYCLE_COLLECTION_INHERITED(MIDIPermissionRequest,
27 ContentPermissionRequestBase, mPromise)
29 NS_IMPL_QUERY_INTERFACE_CYCLE_COLLECTION_INHERITED(MIDIPermissionRequest,
30 ContentPermissionRequestBase,
31 nsIRunnable)
33 NS_IMPL_ADDREF_INHERITED(MIDIPermissionRequest, ContentPermissionRequestBase)
34 NS_IMPL_RELEASE_INHERITED(MIDIPermissionRequest, ContentPermissionRequestBase)
36 MIDIPermissionRequest::MIDIPermissionRequest(nsPIDOMWindowInner* aWindow,
37 Promise* aPromise,
38 const MIDIOptions& aOptions)
39 : ContentPermissionRequestBase(
40 aWindow->GetDoc()->NodePrincipal(), aWindow,
41 ""_ns, // We check prefs in a custom way here
42 "midi"_ns),
43 mPromise(aPromise),
44 mNeedsSysex(aOptions.mSysex) {
45 MOZ_ASSERT(aWindow);
46 MOZ_ASSERT(aPromise, "aPromise should not be null!");
47 MOZ_ASSERT(aWindow->GetDoc());
48 mPrincipal = aWindow->GetDoc()->NodePrincipal();
49 MOZ_ASSERT(mPrincipal);
52 NS_IMETHODIMP
53 MIDIPermissionRequest::GetTypes(nsIArray** aTypes) {
54 NS_ENSURE_ARG_POINTER(aTypes);
55 nsTArray<nsString> options;
57 // The previous implementation made no differences between midi and
58 // midi-sysex. The check on the SitePermsAddonProvider pref should be removed
59 // at the same time as the old implementation.
60 if (mNeedsSysex || !StaticPrefs::dom_sitepermsaddon_provider_enabled()) {
61 options.AppendElement(u"sysex"_ns);
63 return nsContentPermissionUtils::CreatePermissionArray(mType, options,
64 aTypes);
67 NS_IMETHODIMP
68 MIDIPermissionRequest::Cancel() {
69 mCancelTimer = nullptr;
70 mPromise->MaybeRejectWithSecurityError(
71 "WebMIDI requires a site permission add-on to activate");
72 return NS_OK;
75 NS_IMETHODIMP
76 MIDIPermissionRequest::Allow(JS::Handle<JS::Value> aChoices) {
77 MOZ_ASSERT(aChoices.isUndefined());
78 MIDIAccessManager* mgr = MIDIAccessManager::Get();
79 mgr->CreateMIDIAccess(mWindow, mNeedsSysex, mPromise);
80 return NS_OK;
83 NS_IMETHODIMP
84 MIDIPermissionRequest::Run() {
85 // If the testing flag is true, skip dialog
86 if (Preferences::GetBool("midi.prompt.testing", false)) {
87 bool allow =
88 Preferences::GetBool("media.navigator.permission.disabled", false);
89 if (allow) {
90 Allow(JS::UndefinedHandleValue);
91 } else {
92 Cancel();
94 return NS_OK;
97 nsCString permName = "midi"_ns;
98 // The previous implementation made no differences between midi and
99 // midi-sysex. The check on the SitePermsAddonProvider pref should be removed
100 // at the same time as the old implementation.
101 if (mNeedsSysex || !StaticPrefs::dom_sitepermsaddon_provider_enabled()) {
102 permName.Append("-sysex");
105 // First, check for an explicit allow/deny. Note that we want to support
106 // granting a permission on the base domain and then using it on a subdomain,
107 // which is why we use the non-"Exact" variants of these APIs. See bug
108 // 1757218.
109 if (nsContentUtils::IsSitePermAllow(mPrincipal, permName)) {
110 Allow(JS::UndefinedHandleValue);
111 return NS_OK;
114 if (nsContentUtils::IsSitePermDeny(mPrincipal, permName)) {
115 CancelWithRandomizedDelay();
116 return NS_OK;
119 // If the add-on is not installed, and sitepermsaddon provider not enabled,
120 // auto-deny (except for localhost).
121 if (StaticPrefs::dom_webmidi_gated() &&
122 !StaticPrefs::dom_sitepermsaddon_provider_enabled() &&
123 !nsContentUtils::HasSitePerm(mPrincipal, permName) &&
124 !mPrincipal->GetIsLoopbackHost()) {
125 CancelWithRandomizedDelay();
126 return NS_OK;
129 // If sitepermsaddon provider is enabled and user denied install,
130 // auto-deny (except for localhost, where we use a regular permission flow).
131 if (StaticPrefs::dom_sitepermsaddon_provider_enabled() &&
132 nsContentUtils::IsSitePermDeny(mPrincipal, "install"_ns) &&
133 !mPrincipal->GetIsLoopbackHost()) {
134 CancelWithRandomizedDelay();
135 return NS_OK;
138 // Before we bother the user with a prompt, see if they have any devices. If
139 // they don't, just report denial.
140 MOZ_ASSERT(NS_IsMainThread());
141 mozilla::ipc::PBackgroundChild* actor =
142 mozilla::ipc::BackgroundChild::GetOrCreateForCurrentThread();
143 if (NS_WARN_IF(!actor)) {
144 return NS_ERROR_FAILURE;
146 RefPtr<MIDIPermissionRequest> self = this;
147 actor->SendHasMIDIDevice(
148 [=](bool aHasDevices) {
149 MOZ_ASSERT(NS_IsMainThread());
151 if (aHasDevices) {
152 self->DoPrompt();
153 } else {
154 nsContentUtils::ReportToConsoleNonLocalized(
155 u"Silently denying site request for MIDI access because no devices were detected. You may need to restart your browser after connecting a new device."_ns,
156 nsIScriptError::infoFlag, "WebMIDI"_ns, mWindow->GetDoc());
157 self->CancelWithRandomizedDelay();
160 [=](auto) { self->CancelWithRandomizedDelay(); });
162 return NS_OK;
165 // If the user has no MIDI devices, we automatically deny the request. To
166 // prevent sites from using timing attack to discern the existence of MIDI
167 // devices, we instrument silent denials with a randomized delay between 3
168 // and 13 seconds, which is intended to model the time the user might spend
169 // considering a prompt before denying it.
171 // Note that we set the random component of the delay to zero in automation
172 // to avoid unnecessarily increasing test end-to-end time.
173 void MIDIPermissionRequest::CancelWithRandomizedDelay() {
174 MOZ_ASSERT(NS_IsMainThread());
175 uint32_t baseDelayMS = 3 * 1000;
176 uint32_t randomDelayMS =
177 xpc::IsInAutomation() ? 0 : RandomUint64OrDie() % (10 * 1000);
178 auto delay = TimeDuration::FromMilliseconds(baseDelayMS + randomDelayMS);
179 RefPtr<MIDIPermissionRequest> self = this;
180 NS_NewTimerWithCallback(
181 getter_AddRefs(mCancelTimer), [=](auto) { self->Cancel(); }, delay,
182 nsITimer::TYPE_ONE_SHOT, __func__);
185 nsresult MIDIPermissionRequest::DoPrompt() {
186 if (NS_FAILED(nsContentPermissionUtils::AskPermission(this, mWindow))) {
187 Cancel();
188 return NS_ERROR_FAILURE;
190 return NS_OK;