summaryrefslogtreecommitdiffstats
path: root/dom/push/PushManager.cpp
blob: 426f965f0f5dabe1829d7e475059393fe6d3a96c (plain)
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
/* -*- 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 "mozilla/dom/PushManager.h"

#include "mozilla/Base64.h"
#include "mozilla/Preferences.h"
#include "mozilla/Components.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/PermissionStatusBinding.h"
#include "mozilla/dom/PushManagerBinding.h"
#include "mozilla/dom/PushSubscription.h"
#include "mozilla/dom/PushSubscriptionOptionsBinding.h"
#include "mozilla/dom/PushUtil.h"
#include "mozilla/dom/RootedDictionary.h"
#include "mozilla/dom/ServiceWorker.h"
#include "mozilla/dom/WorkerRunnable.h"
#include "mozilla/dom/WorkerScope.h"

#include "mozilla/dom/Promise.h"
#include "mozilla/dom/PromiseWorkerProxy.h"

#include "nsIGlobalObject.h"
#include "nsIPermissionManager.h"
#include "nsIPrincipal.h"
#include "nsIPushService.h"

#include "nsComponentManagerUtils.h"
#include "nsContentUtils.h"
#include "nsServiceManagerUtils.h"

namespace mozilla::dom {

namespace {

nsresult GetPermissionState(nsIPrincipal* aPrincipal, PermissionState& aState) {
  nsCOMPtr<nsIPermissionManager> permManager =
      mozilla::components::PermissionManager::Service();

  if (!permManager) {
    return NS_ERROR_FAILURE;
  }
  uint32_t permission = nsIPermissionManager::UNKNOWN_ACTION;
  nsresult rv = permManager->TestExactPermissionFromPrincipal(
      aPrincipal, "desktop-notification"_ns, &permission);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  if (permission == nsIPermissionManager::ALLOW_ACTION ||
      Preferences::GetBool("dom.push.testing.ignorePermission", false)) {
    aState = PermissionState::Granted;
  } else if (permission == nsIPermissionManager::DENY_ACTION) {
    aState = PermissionState::Denied;
  } else {
    aState = PermissionState::Prompt;
  }

  return NS_OK;
}

nsresult GetSubscriptionParams(nsIPushSubscription* aSubscription,
                               nsAString& aEndpoint,
                               nsTArray<uint8_t>& aRawP256dhKey,
                               nsTArray<uint8_t>& aAuthSecret,
                               nsTArray<uint8_t>& aAppServerKey) {
  if (!aSubscription) {
    return NS_OK;
  }

  nsresult rv = aSubscription->GetEndpoint(aEndpoint);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = aSubscription->GetKey(u"p256dh"_ns, aRawP256dhKey);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }
  rv = aSubscription->GetKey(u"auth"_ns, aAuthSecret);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }
  rv = aSubscription->GetKey(u"appServer"_ns, aAppServerKey);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  return NS_OK;
}

class GetSubscriptionResultRunnable final : public WorkerRunnable {
 public:
  GetSubscriptionResultRunnable(WorkerPrivate* aWorkerPrivate,
                                RefPtr<PromiseWorkerProxy>&& aProxy,
                                nsresult aStatus, const nsAString& aEndpoint,
                                const nsAString& aScope,
                                Nullable<EpochTimeStamp>&& aExpirationTime,
                                nsTArray<uint8_t>&& aRawP256dhKey,
                                nsTArray<uint8_t>&& aAuthSecret,
                                nsTArray<uint8_t>&& aAppServerKey)
      : WorkerRunnable(aWorkerPrivate),
        mProxy(std::move(aProxy)),
        mStatus(aStatus),
        mEndpoint(aEndpoint),
        mScope(aScope),
        mExpirationTime(std::move(aExpirationTime)),
        mRawP256dhKey(std::move(aRawP256dhKey)),
        mAuthSecret(std::move(aAuthSecret)),
        mAppServerKey(std::move(aAppServerKey)) {}

  bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override {
    RefPtr<Promise> promise = mProxy->WorkerPromise();
    if (NS_SUCCEEDED(mStatus)) {
      if (mEndpoint.IsEmpty()) {
        promise->MaybeResolve(JS::NullHandleValue);
      } else {
        RefPtr<PushSubscription> sub = new PushSubscription(
            nullptr, mEndpoint, mScope, std::move(mExpirationTime),
            std::move(mRawP256dhKey), std::move(mAuthSecret),
            std::move(mAppServerKey));
        promise->MaybeResolve(sub);
      }
    } else if (NS_ERROR_GET_MODULE(mStatus) == NS_ERROR_MODULE_DOM_PUSH) {
      promise->MaybeReject(mStatus);
    } else {
      promise->MaybeReject(NS_ERROR_DOM_PUSH_ABORT_ERR);
    }

    mProxy->CleanUp();

    return true;
  }

 private:
  ~GetSubscriptionResultRunnable() = default;

  RefPtr<PromiseWorkerProxy> mProxy;
  nsresult mStatus;
  nsString mEndpoint;
  nsString mScope;
  Nullable<EpochTimeStamp> mExpirationTime;
  nsTArray<uint8_t> mRawP256dhKey;
  nsTArray<uint8_t> mAuthSecret;
  nsTArray<uint8_t> mAppServerKey;
};

class GetSubscriptionCallback final : public nsIPushSubscriptionCallback {
 public:
  NS_DECL_ISUPPORTS

  explicit GetSubscriptionCallback(PromiseWorkerProxy* aProxy,
                                   const nsAString& aScope)
      : mProxy(aProxy), mScope(aScope) {}

  NS_IMETHOD
  OnPushSubscription(nsresult aStatus,
                     nsIPushSubscription* aSubscription) override {
    AssertIsOnMainThread();
    MOZ_ASSERT(mProxy, "OnPushSubscription() called twice?");

    MutexAutoLock lock(mProxy->Lock());
    if (mProxy->CleanedUp()) {
      return NS_OK;
    }

    nsAutoString endpoint;
    nsTArray<uint8_t> rawP256dhKey, authSecret, appServerKey;
    if (NS_SUCCEEDED(aStatus)) {
      aStatus = GetSubscriptionParams(aSubscription, endpoint, rawP256dhKey,
                                      authSecret, appServerKey);
    }

    WorkerPrivate* worker = mProxy->GetWorkerPrivate();
    RefPtr<GetSubscriptionResultRunnable> r = new GetSubscriptionResultRunnable(
        worker, std::move(mProxy), aStatus, endpoint, mScope,
        std::move(mExpirationTime), std::move(rawP256dhKey),
        std::move(authSecret), std::move(appServerKey));
    if (!r->Dispatch()) {
      return NS_ERROR_UNEXPECTED;
    }

    return NS_OK;
  }

  // Convenience method for use in this file.
  void OnPushSubscriptionError(nsresult aStatus) {
    Unused << NS_WARN_IF(NS_FAILED(OnPushSubscription(aStatus, nullptr)));
  }

 protected:
  ~GetSubscriptionCallback() = default;

 private:
  RefPtr<PromiseWorkerProxy> mProxy;
  nsString mScope;
  Nullable<EpochTimeStamp> mExpirationTime;
};

NS_IMPL_ISUPPORTS(GetSubscriptionCallback, nsIPushSubscriptionCallback)

class GetSubscriptionRunnable final : public Runnable {
 public:
  GetSubscriptionRunnable(PromiseWorkerProxy* aProxy, const nsAString& aScope,
                          PushManager::SubscriptionAction aAction,
                          nsTArray<uint8_t>&& aAppServerKey)
      : Runnable("dom::GetSubscriptionRunnable"),
        mProxy(aProxy),
        mScope(aScope),
        mAction(aAction),
        mAppServerKey(std::move(aAppServerKey)) {}

  NS_IMETHOD
  Run() override {
    AssertIsOnMainThread();

    nsCOMPtr<nsIPrincipal> principal;

    {
      // Bug 1228723: If permission is revoked or an error occurs, the
      // subscription callback will be called synchronously. This causes
      // `GetSubscriptionCallback::OnPushSubscription` to deadlock when
      // it tries to acquire the lock.
      MutexAutoLock lock(mProxy->Lock());
      if (mProxy->CleanedUp()) {
        return NS_OK;
      }
      principal = mProxy->GetWorkerPrivate()->GetPrincipal();
    }

    MOZ_ASSERT(principal);

    RefPtr<GetSubscriptionCallback> callback =
        new GetSubscriptionCallback(mProxy, mScope);

    PermissionState state;
    nsresult rv = GetPermissionState(principal, state);
    if (NS_FAILED(rv)) {
      callback->OnPushSubscriptionError(NS_ERROR_FAILURE);
      return NS_OK;
    }

    if (state != PermissionState::Granted) {
      if (mAction == PushManager::GetSubscriptionAction) {
        callback->OnPushSubscriptionError(NS_OK);
        return NS_OK;
      }
      callback->OnPushSubscriptionError(NS_ERROR_DOM_PUSH_DENIED_ERR);
      return NS_OK;
    }

    nsCOMPtr<nsIPushService> service =
        do_GetService("@mozilla.org/push/Service;1");
    if (NS_WARN_IF(!service)) {
      callback->OnPushSubscriptionError(NS_ERROR_FAILURE);
      return NS_OK;
    }

    if (mAction == PushManager::SubscribeAction) {
      if (mAppServerKey.IsEmpty()) {
        rv = service->Subscribe(mScope, principal, callback);
      } else {
        rv = service->SubscribeWithKey(mScope, principal, mAppServerKey,
                                       callback);
      }
    } else {
      MOZ_ASSERT(mAction == PushManager::GetSubscriptionAction);
      rv = service->GetSubscription(mScope, principal, callback);
    }

    if (NS_WARN_IF(NS_FAILED(rv))) {
      callback->OnPushSubscriptionError(NS_ERROR_FAILURE);
      return NS_OK;
    }

    return NS_OK;
  }

 private:
  ~GetSubscriptionRunnable() = default;

  RefPtr<PromiseWorkerProxy> mProxy;
  nsString mScope;
  PushManager::SubscriptionAction mAction;
  nsTArray<uint8_t> mAppServerKey;
};

class PermissionResultRunnable final : public WorkerRunnable {
 public:
  PermissionResultRunnable(PromiseWorkerProxy* aProxy, nsresult aStatus,
                           PermissionState aState)
      : WorkerRunnable(aProxy->GetWorkerPrivate()),
        mProxy(aProxy),
        mStatus(aStatus),
        mState(aState) {
    AssertIsOnMainThread();
  }

  bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override {
    MOZ_ASSERT(aWorkerPrivate);
    aWorkerPrivate->AssertIsOnWorkerThread();

    RefPtr<Promise> promise = mProxy->WorkerPromise();
    if (NS_SUCCEEDED(mStatus)) {
      promise->MaybeResolve(mState);
    } else {
      promise->MaybeRejectWithUndefined();
    }

    mProxy->CleanUp();

    return true;
  }

 private:
  ~PermissionResultRunnable() = default;

  RefPtr<PromiseWorkerProxy> mProxy;
  nsresult mStatus;
  PermissionState mState;
};

class PermissionStateRunnable final : public Runnable {
 public:
  explicit PermissionStateRunnable(PromiseWorkerProxy* aProxy)
      : Runnable("dom::PermissionStateRunnable"), mProxy(aProxy) {}

  NS_IMETHOD
  Run() override {
    AssertIsOnMainThread();
    MutexAutoLock lock(mProxy->Lock());
    if (mProxy->CleanedUp()) {
      return NS_OK;
    }

    PermissionState state;
    nsresult rv =
        GetPermissionState(mProxy->GetWorkerPrivate()->GetPrincipal(), state);

    RefPtr<PermissionResultRunnable> r =
        new PermissionResultRunnable(mProxy, rv, state);

    // This can fail if the worker thread is already shutting down, but there's
    // nothing we can do in that case.
    Unused << NS_WARN_IF(!r->Dispatch());

    return NS_OK;
  }

 private:
  ~PermissionStateRunnable() = default;

  RefPtr<PromiseWorkerProxy> mProxy;
};

}  // anonymous namespace

PushManager::PushManager(nsIGlobalObject* aGlobal, PushManagerImpl* aImpl)
    : mGlobal(aGlobal), mImpl(aImpl) {
  AssertIsOnMainThread();
  MOZ_ASSERT(aImpl);
}

PushManager::PushManager(const nsAString& aScope) : mScope(aScope) {
#ifdef DEBUG
  // There's only one global on a worker, so we don't need to pass a global
  // object to the constructor.
  WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
  MOZ_ASSERT(worker);
  worker->AssertIsOnWorkerThread();
#endif
}

PushManager::~PushManager() = default;

NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(PushManager, mGlobal, mImpl)
NS_IMPL_CYCLE_COLLECTING_ADDREF(PushManager)
NS_IMPL_CYCLE_COLLECTING_RELEASE(PushManager)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(PushManager)
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

JSObject* PushManager::WrapObject(JSContext* aCx,
                                  JS::Handle<JSObject*> aGivenProto) {
  return PushManager_Binding::Wrap(aCx, this, aGivenProto);
}

// static
already_AddRefed<PushManager> PushManager::Constructor(GlobalObject& aGlobal,
                                                       const nsAString& aScope,
                                                       ErrorResult& aRv) {
  if (!NS_IsMainThread()) {
    RefPtr<PushManager> ret = new PushManager(aScope);
    return ret.forget();
  }

  RefPtr<PushManagerImpl> impl =
      PushManagerImpl::Constructor(aGlobal, aGlobal.Context(), aScope, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
  RefPtr<PushManager> ret = new PushManager(global, impl);

  return ret.forget();
}

bool PushManager::IsEnabled(JSContext* aCx, JSObject* aGlobal) {
  return StaticPrefs::dom_push_enabled() && ServiceWorkerVisible(aCx, aGlobal);
}

already_AddRefed<Promise> PushManager::Subscribe(
    const PushSubscriptionOptionsInit& aOptions, ErrorResult& aRv) {
  if (mImpl) {
    MOZ_ASSERT(NS_IsMainThread());
    return mImpl->Subscribe(aOptions, aRv);
  }

  return PerformSubscriptionActionFromWorker(SubscribeAction, aOptions, aRv);
}

already_AddRefed<Promise> PushManager::GetSubscription(ErrorResult& aRv) {
  if (mImpl) {
    MOZ_ASSERT(NS_IsMainThread());
    return mImpl->GetSubscription(aRv);
  }

  return PerformSubscriptionActionFromWorker(GetSubscriptionAction, aRv);
}

already_AddRefed<Promise> PushManager::PermissionState(
    const PushSubscriptionOptionsInit& aOptions, ErrorResult& aRv) {
  if (mImpl) {
    MOZ_ASSERT(NS_IsMainThread());
    return mImpl->PermissionState(aOptions, aRv);
  }

  WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
  MOZ_ASSERT(worker);
  worker->AssertIsOnWorkerThread();

  nsCOMPtr<nsIGlobalObject> global = worker->GlobalScope();
  RefPtr<Promise> p = Promise::Create(global, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  RefPtr<PromiseWorkerProxy> proxy = PromiseWorkerProxy::Create(worker, p);
  if (!proxy) {
    p->MaybeRejectWithUndefined();
    return p.forget();
  }

  RefPtr<PermissionStateRunnable> r = new PermissionStateRunnable(proxy);
  NS_DispatchToMainThread(r);

  return p.forget();
}

already_AddRefed<Promise> PushManager::PerformSubscriptionActionFromWorker(
    SubscriptionAction aAction, ErrorResult& aRv) {
  RootedDictionary<PushSubscriptionOptionsInit> options(RootingCx());
  return PerformSubscriptionActionFromWorker(aAction, options, aRv);
}

already_AddRefed<Promise> PushManager::PerformSubscriptionActionFromWorker(
    SubscriptionAction aAction, const PushSubscriptionOptionsInit& aOptions,
    ErrorResult& aRv) {
  WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
  MOZ_ASSERT(worker);
  worker->AssertIsOnWorkerThread();

  nsCOMPtr<nsIGlobalObject> global = worker->GlobalScope();
  RefPtr<Promise> p = Promise::Create(global, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  RefPtr<PromiseWorkerProxy> proxy = PromiseWorkerProxy::Create(worker, p);
  if (!proxy) {
    p->MaybeReject(NS_ERROR_DOM_PUSH_ABORT_ERR);
    return p.forget();
  }

  nsTArray<uint8_t> appServerKey;
  if (!aOptions.mApplicationServerKey.IsNull()) {
    nsresult rv = NormalizeAppServerKey(aOptions.mApplicationServerKey.Value(),
                                        appServerKey);
    if (NS_FAILED(rv)) {
      p->MaybeReject(rv);
      return p.forget();
    }
  }

  RefPtr<GetSubscriptionRunnable> r = new GetSubscriptionRunnable(
      proxy, mScope, aAction, std::move(appServerKey));
  MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(r));

  return p.forget();
}

nsresult PushManager::NormalizeAppServerKey(
    const OwningArrayBufferViewOrArrayBufferOrString& aSource,
    nsTArray<uint8_t>& aAppServerKey) {
  if (aSource.IsString()) {
    NS_ConvertUTF16toUTF8 base64Key(aSource.GetAsString());
    FallibleTArray<uint8_t> decodedKey;
    nsresult rv = Base64URLDecode(
        base64Key, Base64URLDecodePaddingPolicy::Reject, decodedKey);
    if (NS_FAILED(rv)) {
      return NS_ERROR_DOM_INVALID_CHARACTER_ERR;
    }
    aAppServerKey = decodedKey;
  } else if (aSource.IsArrayBuffer()) {
    if (!PushUtil::CopyArrayBufferToArray(aSource.GetAsArrayBuffer(),
                                          aAppServerKey)) {
      return NS_ERROR_DOM_PUSH_INVALID_KEY_ERR;
    }
  } else if (aSource.IsArrayBufferView()) {
    if (!PushUtil::CopyArrayBufferViewToArray(aSource.GetAsArrayBufferView(),
                                              aAppServerKey)) {
      return NS_ERROR_DOM_PUSH_INVALID_KEY_ERR;
    }
  } else {
    MOZ_CRASH("Uninitialized union: expected string, buffer, or view");
  }
  if (aAppServerKey.IsEmpty()) {
    return NS_ERROR_DOM_PUSH_INVALID_KEY_ERR;
  }
  return NS_OK;
}

}  // namespace mozilla::dom