1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "NotificationUtils.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/Components.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/dom/DOMTypes.h"
#include "mozilla/dom/NotificationBinding.h"
#include "mozilla/glean/DomNotificationMetrics.h"
#include "nsContentUtils.h"
#include "nsIAlertsService.h"
#include "nsINotificationStorage.h"
#include "nsIPermissionManager.h"
#include "nsIPushService.h"
#include "nsServiceManagerUtils.h"
static bool gTriedStorageCleanup = false;
namespace mozilla::dom::notification {
using GleanLabel = glean::web_notification::ShowOriginLabel;
static void ReportTelemetry(GleanLabel aLabel,
PermissionCheckPurpose aPurpose) {
switch (aPurpose) {
case PermissionCheckPurpose::PermissionAttribute:
glean::web_notification::permission_origin
.EnumGet(static_cast<glean::web_notification::PermissionOriginLabel>(
aLabel))
.Add();
return;
case PermissionCheckPurpose::PermissionRequest:
glean::web_notification::request_permission_origin
.EnumGet(static_cast<
glean::web_notification::RequestPermissionOriginLabel>(
aLabel))
.Add();
return;
case PermissionCheckPurpose::NotificationShow:
glean::web_notification::show_origin.EnumGet(aLabel).Add();
return;
default:
MOZ_CRASH("Unknown permission checker");
return;
}
}
bool IsNotificationAllowedFor(nsIPrincipal* aPrincipal) {
if (aPrincipal->IsSystemPrincipal()) {
return true;
}
// Allow files to show notifications by default.
return aPrincipal->SchemeIs("file");
}
bool IsNotificationForbiddenFor(nsIPrincipal* aPrincipal,
nsIPrincipal* aEffectiveStoragePrincipal,
bool isSecureContext,
PermissionCheckPurpose aPurpose,
Document* aRequestorDoc) {
if (aPrincipal->GetIsInPrivateBrowsing() &&
!StaticPrefs::dom_webnotifications_privateBrowsing_enabled()) {
return true;
}
if (!isSecureContext) {
if (aRequestorDoc) {
glean::web_notification::insecure_context_permission_request.Add();
nsContentUtils::ReportToConsole(
nsIScriptError::errorFlag, "DOM"_ns, aRequestorDoc,
nsContentUtils::eDOM_PROPERTIES,
"NotificationsInsecureRequestIsForbidden");
}
return true;
}
const nsString& partitionKey =
aEffectiveStoragePrincipal->OriginAttributesRef().mPartitionKey;
if (aEffectiveStoragePrincipal->OriginAttributesRef()
.mPartitionKey.IsEmpty()) {
// first party
ReportTelemetry(GleanLabel::eFirstParty, aPurpose);
return false;
}
nsString outScheme;
nsString outBaseDomain;
int32_t outPort;
bool outForeignByAncestorContext;
OriginAttributes::ParsePartitionKey(partitionKey, outScheme, outBaseDomain,
outPort, outForeignByAncestorContext);
if (outForeignByAncestorContext) {
// nested first party
ReportTelemetry(GleanLabel::eNestedFirstParty, aPurpose);
return false;
}
// third party
ReportTelemetry(GleanLabel::eThirdParty, aPurpose);
if (aRequestorDoc) {
nsContentUtils::ReportToConsole(
nsIScriptError::errorFlag, "DOM"_ns, aRequestorDoc,
nsContentUtils::eDOM_PROPERTIES,
"NotificationsCrossOriginIframeRequestIsForbidden");
}
return !StaticPrefs::dom_webnotifications_allowcrossoriginiframe();
}
NotificationPermission GetRawNotificationPermission(nsIPrincipal* aPrincipal) {
AssertIsOnMainThread();
uint32_t permission = nsIPermissionManager::UNKNOWN_ACTION;
nsCOMPtr<nsIPermissionManager> permissionManager =
components::PermissionManager::Service();
if (!permissionManager) {
return NotificationPermission::Default;
}
permissionManager->TestExactPermissionFromPrincipal(
aPrincipal, "desktop-notification"_ns, &permission);
// Convert the result to one of the enum types.
switch (permission) {
case nsIPermissionManager::ALLOW_ACTION:
return NotificationPermission::Granted;
case nsIPermissionManager::DENY_ACTION:
return NotificationPermission::Denied;
default:
return NotificationPermission::Default;
}
}
NotificationPermission GetNotificationPermission(
nsIPrincipal* aPrincipal, nsIPrincipal* aEffectiveStoragePrincipal,
bool isSecureContext, PermissionCheckPurpose aPurpose) {
if (IsNotificationAllowedFor(aPrincipal)) {
return NotificationPermission::Granted;
}
if (IsNotificationForbiddenFor(aPrincipal, aEffectiveStoragePrincipal,
isSecureContext, aPurpose)) {
return NotificationPermission::Denied;
}
return GetRawNotificationPermission(aPrincipal);
}
nsresult GetOrigin(nsIPrincipal* aPrincipal, nsString& aOrigin) {
if (!aPrincipal) {
return NS_ERROR_FAILURE;
}
nsAutoCString origin;
MOZ_TRY(aPrincipal->GetOrigin(origin));
CopyUTF8toUTF16(origin, aOrigin);
return NS_OK;
}
nsCOMPtr<nsINotificationStorage> GetNotificationStorage(bool isPrivate) {
return do_GetService(isPrivate ? NS_MEMORY_NOTIFICATION_STORAGE_CONTRACTID
: NS_NOTIFICATION_STORAGE_CONTRACTID);
}
class NotificationsCallback : public nsINotificationStorageCallback {
public:
NS_DECL_ISUPPORTS
already_AddRefed<NotificationsPromise> Promise() {
return mPromiseHolder.Ensure(__func__);
}
NS_IMETHOD Done(
const nsTArray<RefPtr<nsINotificationStorageEntry>>& aEntries) final {
AssertIsOnMainThread();
nsTArray<IPCNotification> notifications(aEntries.Length());
for (const auto& entry : aEntries) {
auto result = NotificationStorageEntry::ToIPC(*entry);
if (result.isErr()) {
continue;
}
MOZ_ASSERT(!result.inspect().id().IsEmpty());
notifications.AppendElement(result.unwrap());
}
mPromiseHolder.Resolve(std::move(notifications), __func__);
return NS_OK;
}
protected:
virtual ~NotificationsCallback() {
// We may be shutting down prematurely without getting the result, so make
// sure to settle the promise.
mPromiseHolder.RejectIfExists(NS_ERROR_DOM_INVALID_STATE_ERR, __func__);
};
MozPromiseHolder<NotificationsPromise> mPromiseHolder;
};
NS_IMPL_ISUPPORTS(NotificationsCallback, nsINotificationStorageCallback)
already_AddRefed<NotificationsPromise> GetStoredNotificationsForScope(
nsIPrincipal* aPrincipal, const nsACString& aScope, const nsAString& aTag) {
nsString origin;
nsresult rv = GetOrigin(aPrincipal, origin);
if (NS_WARN_IF(NS_FAILED(rv))) {
return NotificationsPromise::CreateAndReject(rv, __func__).forget();
}
RefPtr<NotificationsCallback> callback = new NotificationsCallback();
RefPtr<NotificationsPromise> promise = callback->Promise();
nsCOMPtr<nsINotificationStorage> notificationStorage =
GetNotificationStorage(aPrincipal->GetIsInPrivateBrowsing());
if (!notificationStorage) {
return NotificationsPromise::CreateAndReject(NS_ERROR_NOT_AVAILABLE,
__func__)
.forget();
}
rv = notificationStorage->Get(origin, NS_ConvertUTF8toUTF16(aScope), aTag,
callback);
if (NS_WARN_IF(NS_FAILED(rv))) {
return NotificationsPromise::CreateAndReject(rv, __func__).forget();
}
return promise.forget();
}
nsresult PersistNotification(nsIPrincipal* aPrincipal,
const IPCNotification& aNotification,
const nsString& aScope) {
nsCOMPtr<nsINotificationStorage> notificationStorage =
GetNotificationStorage(aPrincipal->GetIsInPrivateBrowsing());
if (NS_WARN_IF(!notificationStorage)) {
return NS_ERROR_UNEXPECTED;
}
nsString origin;
nsresult rv = GetOrigin(aPrincipal, origin);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
RefPtr<NotificationStorageEntry> entry =
new NotificationStorageEntry(aNotification);
rv = notificationStorage->Put(origin, entry, aScope);
if (NS_FAILED(rv)) {
return rv;
}
return NS_OK;
}
nsresult UnpersistNotification(nsIPrincipal* aPrincipal, const nsString& aId) {
if (!aPrincipal) {
return NS_ERROR_FAILURE;
}
if (nsCOMPtr<nsINotificationStorage> notificationStorage =
GetNotificationStorage(aPrincipal->GetIsInPrivateBrowsing())) {
nsString origin;
MOZ_TRY(GetOrigin(aPrincipal, origin));
return notificationStorage->Delete(origin, aId);
}
return NS_ERROR_FAILURE;
}
nsresult UnpersistAllNotificationsExcept(const nsTArray<nsString>& aIds) {
// Cleanup makes only sense for on-disk storage
if (nsCOMPtr<nsINotificationStorage> notificationStorage =
GetNotificationStorage(false)) {
return notificationStorage->DeleteAllExcept(aIds);
}
return NS_ERROR_FAILURE;
}
void UnregisterNotification(nsIPrincipal* aPrincipal, const nsString& aId) {
UnpersistNotification(aPrincipal, aId);
if (nsCOMPtr<nsIAlertsService> alertService = components::Alerts::Service()) {
alertService->CloseAlert(aId, /* aContextClosed */ false);
}
}
nsresult ShowAlertWithCleanup(nsIAlertNotification* aAlert,
nsIObserver* aAlertListener) {
nsCOMPtr<nsIAlertsService> alertService = components::Alerts::Service();
if (!gTriedStorageCleanup ||
StaticPrefs::
dom_webnotifications_testing_force_storage_cleanup_enabled()) {
// The below may fail, but retry probably won't make it work
gTriedStorageCleanup = true;
// Get the list of currently displayed notifications known to the
// notification backend and unpersist all other notifications from
// NotificationDB.
// (This won't affect the following persist call by ShowAlert, as the DB
// maintains a job queue)
nsTArray<nsString> history;
if (NS_SUCCEEDED(alertService->GetHistory(history))) {
UnpersistAllNotificationsExcept(history);
}
}
MOZ_TRY(alertService->ShowAlert(aAlert, aAlertListener));
return NS_OK;
}
nsresult RemovePermission(nsIPrincipal* aPrincipal) {
MOZ_ASSERT(XRE_IsParentProcess());
nsCOMPtr<nsIPermissionManager> permissionManager =
mozilla::components::PermissionManager::Service();
if (!permissionManager) {
return NS_ERROR_FAILURE;
}
permissionManager->RemoveFromPrincipal(aPrincipal, "desktop-notification"_ns);
return NS_OK;
}
nsresult OpenSettings(nsIPrincipal* aPrincipal) {
MOZ_ASSERT(XRE_IsParentProcess());
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (!obs) {
return NS_ERROR_FAILURE;
}
// Notify other observers so they can show settings UI.
obs->NotifyObservers(aPrincipal, "notifications-open-settings", nullptr);
return NS_OK;
}
nsresult AdjustPushQuota(nsIPrincipal* aPrincipal,
NotificationStatusChange aChange) {
MOZ_ASSERT(XRE_IsParentProcess());
nsCOMPtr<nsIPushQuotaManager> pushQuotaManager =
do_GetService("@mozilla.org/push/Service;1");
if (!pushQuotaManager) {
return NS_ERROR_FAILURE;
}
nsAutoCString origin;
MOZ_TRY(aPrincipal->GetOrigin(origin));
if (aChange == NotificationStatusChange::Shown) {
return pushQuotaManager->NotificationForOriginShown(origin.get());
}
return pushQuotaManager->NotificationForOriginClosed(origin.get());
}
NS_IMPL_ISUPPORTS(NotificationActionStorageEntry,
nsINotificationActionStorageEntry)
NS_IMETHODIMP NotificationActionStorageEntry::GetName(nsAString& aName) {
aName = mIPCAction.name();
return NS_OK;
}
NS_IMETHODIMP NotificationActionStorageEntry::GetTitle(nsAString& aTitle) {
aTitle = mIPCAction.title();
return NS_OK;
}
Result<IPCNotificationAction, nsresult> NotificationActionStorageEntry::ToIPC(
nsINotificationActionStorageEntry& aEntry) {
IPCNotificationAction action;
MOZ_TRY(aEntry.GetName(action.name()));
MOZ_TRY(aEntry.GetTitle(action.title()));
return action;
}
NS_IMPL_ISUPPORTS(NotificationStorageEntry, nsINotificationStorageEntry)
NS_IMETHODIMP NotificationStorageEntry::GetId(nsAString& aId) {
aId = mIPCNotification.id();
return NS_OK;
}
NS_IMETHODIMP NotificationStorageEntry::GetTitle(nsAString& aTitle) {
aTitle = mIPCNotification.options().title();
return NS_OK;
}
NS_IMETHODIMP NotificationStorageEntry::GetDir(nsACString& aDir) {
aDir = GetEnumString(mIPCNotification.options().dir());
return NS_OK;
}
NS_IMETHODIMP NotificationStorageEntry::GetLang(nsAString& aLang) {
aLang = mIPCNotification.options().lang();
return NS_OK;
}
NS_IMETHODIMP NotificationStorageEntry::GetBody(nsAString& aBody) {
aBody = mIPCNotification.options().body();
return NS_OK;
}
NS_IMETHODIMP NotificationStorageEntry::GetTag(nsAString& aTag) {
aTag = mIPCNotification.options().tag();
return NS_OK;
}
NS_IMETHODIMP NotificationStorageEntry::GetIcon(nsAString& aIcon) {
aIcon = mIPCNotification.options().icon();
return NS_OK;
}
NS_IMETHODIMP NotificationStorageEntry::GetRequireInteraction(
bool* aRequireInteraction) {
*aRequireInteraction = mIPCNotification.options().requireInteraction();
return NS_OK;
}
NS_IMETHODIMP NotificationStorageEntry::GetSilent(bool* aSilent) {
*aSilent = mIPCNotification.options().silent();
return NS_OK;
}
NS_IMETHODIMP NotificationStorageEntry::GetDataSerialized(
nsAString& aDataSerialized) {
aDataSerialized = mIPCNotification.options().dataSerialized();
return NS_OK;
}
NS_IMETHODIMP NotificationStorageEntry::GetActions(
nsTArray<RefPtr<nsINotificationActionStorageEntry>>& aRetVal) {
nsTArray<RefPtr<nsINotificationActionStorageEntry>> actions(
mIPCNotification.options().actions().Length());
for (const auto& action : mIPCNotification.options().actions()) {
actions.AppendElement(new NotificationActionStorageEntry(action));
}
aRetVal = std::move(actions);
return NS_OK;
}
NS_IMETHODIMP NotificationStorageEntry::GetServiceWorkerRegistrationScope(
nsAString& aScope) {
// Scope is only provided from JS, for now
// TODO(krosylight): Change nsINotificationStorage::Put to provide scope via
// storage entry?
aScope.SetIsVoid(true);
return NS_OK;
}
Result<IPCNotification, nsresult> NotificationStorageEntry::ToIPC(
nsINotificationStorageEntry& aEntry) {
IPCNotification notification;
IPCNotificationOptions& options = notification.options();
MOZ_TRY(aEntry.GetId(notification.id()));
MOZ_TRY(aEntry.GetTitle(options.title()));
nsCString dir;
MOZ_TRY(aEntry.GetDir(dir));
options.dir() = StringToEnum<NotificationDirection>(dir).valueOr(
NotificationDirection::Auto);
MOZ_TRY(aEntry.GetLang(options.lang()));
MOZ_TRY(aEntry.GetBody(options.body()));
MOZ_TRY(aEntry.GetTag(options.tag()));
MOZ_TRY(aEntry.GetIcon(options.icon()));
MOZ_TRY(aEntry.GetRequireInteraction(&options.requireInteraction()));
MOZ_TRY(aEntry.GetSilent(&options.silent()));
MOZ_TRY(aEntry.GetDataSerialized(options.dataSerialized()));
nsTArray<RefPtr<nsINotificationActionStorageEntry>> actionEntries;
MOZ_TRY(aEntry.GetActions(actionEntries));
nsTArray<IPCNotificationAction> actions(actionEntries.Length());
for (const auto& actionEntry : actionEntries) {
IPCNotificationAction action;
MOZ_TRY_VAR(action, NotificationActionStorageEntry::ToIPC(*actionEntry));
actions.AppendElement(std::move(action));
}
options.actions() = std::move(actions);
return notification;
}
} // namespace mozilla::dom::notification
|