Bug 1700051: part 26) Correct typo in comment of `mozInlineSpellWordUtil::BuildSoftTe...
[gecko.git] / dom / canvas / CanvasUtils.cpp
blob0cbcfea2697068eedd78ea693dfe8ad9919f01b7
1 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include <stdlib.h>
7 #include <stdarg.h>
9 #include "nsICanvasRenderingContextInternal.h"
10 #include "nsIHTMLCollection.h"
11 #include "mozilla/dom/BrowserChild.h"
12 #include "mozilla/dom/Document.h"
13 #include "mozilla/dom/HTMLCanvasElement.h"
14 #include "mozilla/dom/UserActivation.h"
15 #include "mozilla/BasePrincipal.h"
16 #include "mozilla/StaticPrefs_dom.h"
17 #include "mozilla/StaticPrefs_privacy.h"
18 #include "mozilla/StaticPrefs_webgl.h"
19 #include "nsIPrincipal.h"
21 #include "nsGfxCIID.h"
23 #include "nsTArray.h"
25 #include "CanvasUtils.h"
26 #include "mozilla/gfx/Matrix.h"
27 #include "WebGL2Context.h"
29 #include "nsIScriptError.h"
30 #include "nsIScriptObjectPrincipal.h"
31 #include "nsIPermissionManager.h"
32 #include "nsIObserverService.h"
33 #include "mozilla/Services.h"
34 #include "mozIThirdPartyUtil.h"
35 #include "nsContentUtils.h"
36 #include "nsUnicharUtils.h"
37 #include "nsPrintfCString.h"
38 #include "jsapi.h"
40 #define TOPIC_CANVAS_PERMISSIONS_PROMPT "canvas-permissions-prompt"
41 #define TOPIC_CANVAS_PERMISSIONS_PROMPT_HIDE_DOORHANGER \
42 "canvas-permissions-prompt-hide-doorhanger"
43 #define PERMISSION_CANVAS_EXTRACT_DATA "canvas"_ns
45 using namespace mozilla::gfx;
47 namespace mozilla::CanvasUtils {
49 bool IsImageExtractionAllowed(dom::Document* aDocument, JSContext* aCx,
50 nsIPrincipal& aPrincipal) {
51 // Do the rest of the checks only if privacy.resistFingerprinting is on.
52 if (!nsContentUtils::ShouldResistFingerprinting(aDocument)) {
53 return true;
56 // Don't proceed if we don't have a document or JavaScript context.
57 if (!aDocument || !aCx) {
58 return false;
61 // The system principal can always extract canvas data.
62 if (aPrincipal.IsSystemPrincipal()) {
63 return true;
66 // Allow extension principals.
67 auto principal = BasePrincipal::Cast(&aPrincipal);
68 if (principal->AddonPolicy() || principal->ContentScriptAddonPolicy()) {
69 return true;
72 // Get the document URI and its spec.
73 nsIURI* docURI = aDocument->GetDocumentURI();
74 nsCString docURISpec;
75 docURI->GetSpec(docURISpec);
77 // Allow local files to extract canvas data.
78 if (docURI->SchemeIs("file")) {
79 return true;
82 // Don't show canvas prompt for PDF.js
83 JS::AutoFilename scriptFile;
84 if (JS::DescribeScriptedCaller(aCx, &scriptFile) && scriptFile.get() &&
85 strcmp(scriptFile.get(), "resource://pdf.js/build/pdf.js") == 0) {
86 return true;
89 dom::Document* topLevelDocument = aDocument->GetTopLevelContentDocument();
90 nsIURI* topLevelDocURI =
91 topLevelDocument ? topLevelDocument->GetDocumentURI() : nullptr;
92 nsCString topLevelDocURISpec;
93 if (topLevelDocURI) {
94 topLevelDocURI->GetSpec(topLevelDocURISpec);
97 // Load Third Party Util service.
98 nsresult rv;
99 nsCOMPtr<mozIThirdPartyUtil> thirdPartyUtil =
100 do_GetService(THIRDPARTYUTIL_CONTRACTID, &rv);
101 NS_ENSURE_SUCCESS(rv, false);
103 // Block all third-party attempts to extract canvas.
104 bool isThirdParty = true;
105 rv = thirdPartyUtil->IsThirdPartyURI(topLevelDocURI, docURI, &isThirdParty);
106 NS_ENSURE_SUCCESS(rv, false);
107 if (isThirdParty) {
108 nsAutoString message;
109 message.AppendPrintf("Blocked third party %s from extracting canvas data.",
110 docURISpec.get());
111 nsContentUtils::ReportToConsoleNonLocalized(
112 message, nsIScriptError::warningFlag, "Security"_ns, aDocument);
113 return false;
116 // Load Permission Manager service.
117 nsCOMPtr<nsIPermissionManager> permissionManager =
118 do_GetService(NS_PERMISSIONMANAGER_CONTRACTID, &rv);
119 NS_ENSURE_SUCCESS(rv, false);
121 // Check if the site has permission to extract canvas data.
122 // Either permit or block extraction if a stored permission setting exists.
123 uint32_t permission;
124 rv = permissionManager->TestPermissionFromPrincipal(
125 principal, PERMISSION_CANVAS_EXTRACT_DATA, &permission);
126 NS_ENSURE_SUCCESS(rv, false);
127 switch (permission) {
128 case nsIPermissionManager::ALLOW_ACTION:
129 return true;
130 case nsIPermissionManager::DENY_ACTION:
131 return false;
132 default:
133 break;
136 // At this point, permission is unknown
137 // (nsIPermissionManager::UNKNOWN_ACTION).
139 // Check if the request is in response to user input
140 bool isAutoBlockCanvas =
141 StaticPrefs::
142 privacy_resistFingerprinting_autoDeclineNoUserInputCanvasPrompts() &&
143 !dom::UserActivation::IsHandlingUserInput();
145 if (isAutoBlockCanvas) {
146 nsAutoString message;
147 message.AppendPrintf(
148 "Blocked %s from extracting canvas data because no user input was "
149 "detected.",
150 docURISpec.get());
151 nsContentUtils::ReportToConsoleNonLocalized(
152 message, nsIScriptError::warningFlag, "Security"_ns, aDocument);
153 } else {
154 // It was in response to user input, so log and display the prompt.
155 nsAutoString message;
156 message.AppendPrintf(
157 "Blocked %s from extracting canvas data, but prompting the user.",
158 docURISpec.get());
159 nsContentUtils::ReportToConsoleNonLocalized(
160 message, nsIScriptError::warningFlag, "Security"_ns, aDocument);
163 // Prompt the user (asynchronous).
164 nsPIDOMWindowOuter* win = aDocument->GetWindow();
165 nsAutoCString origin;
166 rv = principal->GetOrigin(origin);
167 NS_ENSURE_SUCCESS(rv, false);
169 if (XRE_IsContentProcess()) {
170 dom::BrowserChild* browserChild = dom::BrowserChild::GetFrom(win);
171 if (browserChild) {
172 browserChild->SendShowCanvasPermissionPrompt(origin, isAutoBlockCanvas);
174 } else {
175 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
176 if (obs) {
177 obs->NotifyObservers(win,
178 isAutoBlockCanvas
179 ? TOPIC_CANVAS_PERMISSIONS_PROMPT_HIDE_DOORHANGER
180 : TOPIC_CANVAS_PERMISSIONS_PROMPT,
181 NS_ConvertUTF8toUTF16(origin).get());
185 // We don't extract the image for now -- user may override at prompt.
186 return false;
189 bool GetCanvasContextType(const nsAString& str,
190 dom::CanvasContextType* const out_type) {
191 if (str.EqualsLiteral("2d")) {
192 *out_type = dom::CanvasContextType::Canvas2D;
193 return true;
196 if (str.EqualsLiteral("webgl") || str.EqualsLiteral("experimental-webgl")) {
197 *out_type = dom::CanvasContextType::WebGL1;
198 return true;
201 if (StaticPrefs::webgl_enable_webgl2()) {
202 if (str.EqualsLiteral("webgl2")) {
203 *out_type = dom::CanvasContextType::WebGL2;
204 return true;
208 if (StaticPrefs::dom_webgpu_enabled()) {
209 if (str.EqualsLiteral("gpupresent")) {
210 *out_type = dom::CanvasContextType::WebGPU;
211 return true;
215 if (str.EqualsLiteral("bitmaprenderer")) {
216 *out_type = dom::CanvasContextType::ImageBitmap;
217 return true;
220 return false;
224 * This security check utility might be called from an source that never taints
225 * others. For example, while painting a CanvasPattern, which is created from an
226 * ImageBitmap, onto a canvas. In this case, the caller could set the CORSUsed
227 * true in order to pass this check and leave the aPrincipal to be a nullptr
228 * since the aPrincipal is not going to be used.
230 void DoDrawImageSecurityCheck(dom::HTMLCanvasElement* aCanvasElement,
231 nsIPrincipal* aPrincipal, bool forceWriteOnly,
232 bool CORSUsed) {
233 // Callers should ensure that mCanvasElement is non-null before calling this
234 if (!aCanvasElement) {
235 NS_WARNING("DoDrawImageSecurityCheck called without canvas element!");
236 return;
239 if (aCanvasElement->IsWriteOnly() && !aCanvasElement->mExpandedReader) {
240 return;
243 // If we explicitly set WriteOnly just do it and get out
244 if (forceWriteOnly) {
245 aCanvasElement->SetWriteOnly();
246 return;
249 // No need to do a security check if the image used CORS for the load
250 if (CORSUsed) return;
252 MOZ_ASSERT(aPrincipal, "Must have a principal here");
254 if (aCanvasElement->NodePrincipal()->Subsumes(aPrincipal)) {
255 // This canvas has access to that image anyway
256 return;
259 if (BasePrincipal::Cast(aPrincipal)->AddonPolicy()) {
260 // This is a resource from an extension content script principal.
262 if (aCanvasElement->mExpandedReader &&
263 aCanvasElement->mExpandedReader->Subsumes(aPrincipal)) {
264 // This canvas already allows reading from this principal.
265 return;
268 if (!aCanvasElement->mExpandedReader) {
269 // Allow future reads from this same princial only.
270 aCanvasElement->SetWriteOnly(aPrincipal);
271 return;
274 // If we got here, this must be the *second* extension tainting
275 // the canvas. Fall through to mark it WriteOnly for everyone.
278 aCanvasElement->SetWriteOnly();
281 bool CoerceDouble(const JS::Value& v, double* d) {
282 if (v.isDouble()) {
283 *d = v.toDouble();
284 } else if (v.isInt32()) {
285 *d = double(v.toInt32());
286 } else if (v.isUndefined()) {
287 *d = 0.0;
288 } else {
289 return false;
291 return true;
294 bool HasDrawWindowPrivilege(JSContext* aCx, JSObject* /* unused */) {
295 return nsContentUtils::CallerHasPermission(aCx,
296 nsGkAtoms::all_urlsPermission);
299 bool CheckWriteOnlySecurity(bool aCORSUsed, nsIPrincipal* aPrincipal,
300 bool aHadCrossOriginRedirects) {
301 if (!aPrincipal) {
302 return true;
305 if (!aCORSUsed) {
306 if (aHadCrossOriginRedirects) {
307 return true;
310 nsIGlobalObject* incumbentSettingsObject = dom::GetIncumbentGlobal();
311 if (!incumbentSettingsObject) {
312 return true;
315 nsIPrincipal* principal = incumbentSettingsObject->PrincipalOrNull();
316 if (NS_WARN_IF(!principal) || !(principal->Subsumes(aPrincipal))) {
317 return true;
321 return false;
324 } // namespace mozilla::CanvasUtils