summaryrefslogtreecommitdiffstats
path: root/dom/serviceworkers/ServiceWorkerUtils.cpp
blob: 630d667c6e43ed56f702c31e7449448ddc3d1aec (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
/* -*- 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 "ServiceWorkerUtils.h"

#include "mozilla/BasePrincipal.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_extensions.h"
#include "mozilla/dom/BrowsingContext.h"
#include "mozilla/dom/ClientInfo.h"
#include "mozilla/dom/Navigator.h"
#include "mozilla/dom/ServiceWorkerGlobalScopeBinding.h"
#include "mozilla/dom/ServiceWorkerRegistrarTypes.h"
#include "nsCOMPtr.h"
#include "nsIPrincipal.h"
#include "nsIURL.h"
#include "nsPrintfCString.h"

namespace mozilla::dom {

static bool IsServiceWorkersTestingEnabledInWindow(JSObject* const aGlobal) {
  if (const nsCOMPtr<nsPIDOMWindowInner> innerWindow =
          Navigator::GetWindowFromGlobal(aGlobal)) {
    if (auto* bc = innerWindow->GetBrowsingContext()) {
      return bc->Top()->ServiceWorkersTestingEnabled();
    }
  }
  return false;
}

static bool IsInPrivateBrowsing(JSContext* const aCx) {
  if (const nsCOMPtr<nsIGlobalObject> global = xpc::CurrentNativeGlobal(aCx)) {
    if (const nsCOMPtr<nsIPrincipal> principal = global->PrincipalOrNull()) {
      return principal->GetPrivateBrowsingId() > 0;
    }
  }
  return false;
}

bool ServiceWorkersEnabled(JSContext* aCx, JSObject* aGlobal) {
  MOZ_ASSERT(NS_IsMainThread());

  if (!StaticPrefs::dom_serviceWorkers_enabled()) {
    return false;
  }

  // xpc::CurrentNativeGlobal below requires rooting
  JS::Rooted<JSObject*> global(aCx, aGlobal);

  if (IsInPrivateBrowsing(aCx)) {
    return false;
  }

  // Allow a webextension principal to register a service worker script with
  // a moz-extension url only if 'extensions.service_worker_register.allowed'
  // is true.
  if (!StaticPrefs::extensions_serviceWorkerRegister_allowed()) {
    nsIPrincipal* principal = nsContentUtils::SubjectPrincipal(aCx);
    if (principal && BasePrincipal::Cast(principal)->AddonPolicy()) {
      return false;
    }
  }

  if (IsSecureContextOrObjectIsFromSecureContext(aCx, global)) {
    return true;
  }

  return StaticPrefs::dom_serviceWorkers_testing_enabled() ||
         IsServiceWorkersTestingEnabledInWindow(global);
}

bool ServiceWorkerVisible(JSContext* aCx, JSObject* aGlobal) {
  if (NS_IsMainThread()) {
    // We want to expose ServiceWorker interface only when
    // navigator.serviceWorker is available. Currently it may not be available
    // with some reasons:
    // 1. navigator.serviceWorker is not supported in workers. (bug 1131324)
    return ServiceWorkersEnabled(aCx, aGlobal);
  }

  // We are already in ServiceWorker and interfaces need to be exposed for e.g.
  // globalThis.registration.serviceWorker. Note that navigator.serviceWorker
  // is still not supported. (bug 1131324)
  return IS_INSTANCE_OF(ServiceWorkerGlobalScope, aGlobal);
}

bool ServiceWorkerRegistrationDataIsValid(
    const ServiceWorkerRegistrationData& aData) {
  return !aData.scope().IsEmpty() && !aData.currentWorkerURL().IsEmpty() &&
         !aData.cacheName().IsEmpty();
}

namespace {

void CheckForSlashEscapedCharsInPath(nsIURI* aURI, const char* aURLDescription,
                                     ErrorResult& aRv) {
  MOZ_ASSERT(aURI);

  // A URL that can't be downcast to a standard URL is an invalid URL and should
  // be treated as such and fail with SecurityError.
  nsCOMPtr<nsIURL> url(do_QueryInterface(aURI));
  if (NS_WARN_IF(!url)) {
    // This really should not happen, since the caller checks that we
    // have an http: or https: URL!
    aRv.ThrowInvalidStateError("http: or https: URL without a concept of path");
    return;
  }

  nsAutoCString path;
  nsresult rv = url->GetFilePath(path);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    // Again, should not happen.
    aRv.ThrowInvalidStateError("http: or https: URL without a concept of path");
    return;
  }

  ToLowerCase(path);
  if (path.Find("%2f") != kNotFound || path.Find("%5c") != kNotFound) {
    nsPrintfCString err("%s contains %%2f or %%5c", aURLDescription);
    aRv.ThrowTypeError(err);
  }
}

}  // anonymous namespace

void ServiceWorkerScopeAndScriptAreValid(const ClientInfo& aClientInfo,
                                         nsIURI* aScopeURI, nsIURI* aScriptURI,
                                         ErrorResult& aRv) {
  MOZ_DIAGNOSTIC_ASSERT(aScopeURI);
  MOZ_DIAGNOSTIC_ASSERT(aScriptURI);

  auto principalOrErr = aClientInfo.GetPrincipal();
  if (NS_WARN_IF(principalOrErr.isErr())) {
    aRv.ThrowInvalidStateError("Can't make security decisions about Client");
    return;
  }

  auto hasHTTPScheme = [](nsIURI* aURI) -> bool {
    return aURI->SchemeIs("http") || aURI->SchemeIs("https");
  };
  auto hasMozExtScheme = [](nsIURI* aURI) -> bool {
    return aURI->SchemeIs("moz-extension");
  };

  nsCOMPtr<nsIPrincipal> principal = principalOrErr.unwrap();

  auto isExtension = !!BasePrincipal::Cast(principal)->AddonPolicy();
  auto hasValidURISchemes = !isExtension ? hasHTTPScheme : hasMozExtScheme;

  // https://w3c.github.io/ServiceWorker/#start-register-algorithm step 3.
  if (!hasValidURISchemes(aScriptURI)) {
    auto message = !isExtension
                       ? "Script URL's scheme is not 'http' or 'https'"_ns
                       : "Script URL's scheme is not 'moz-extension'"_ns;
    aRv.ThrowTypeError(message);
    return;
  }

  // https://w3c.github.io/ServiceWorker/#start-register-algorithm step 4.
  CheckForSlashEscapedCharsInPath(aScriptURI, "script URL", aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return;
  }

  // https://w3c.github.io/ServiceWorker/#start-register-algorithm step 8.
  if (!hasValidURISchemes(aScopeURI)) {
    auto message = !isExtension
                       ? "Scope URL's scheme is not 'http' or 'https'"_ns
                       : "Scope URL's scheme is not 'moz-extension'"_ns;
    aRv.ThrowTypeError(message);
    return;
  }

  // https://w3c.github.io/ServiceWorker/#start-register-algorithm step 9.
  CheckForSlashEscapedCharsInPath(aScopeURI, "scope URL", aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return;
  }

  // The refs should really be empty coming in here, but if someone
  // injects bad data into IPC, who knows.  So let's revalidate that.
  nsAutoCString ref;
  Unused << aScopeURI->GetRef(ref);
  if (NS_WARN_IF(!ref.IsEmpty())) {
    aRv.ThrowSecurityError("Non-empty fragment on scope URL");
    return;
  }

  Unused << aScriptURI->GetRef(ref);
  if (NS_WARN_IF(!ref.IsEmpty())) {
    aRv.ThrowSecurityError("Non-empty fragment on script URL");
    return;
  }

  // Unfortunately we don't seem to have an obvious window id here; in
  // particular ClientInfo does not have one.
  nsresult rv = principal->CheckMayLoadWithReporting(
      aScopeURI, false /* allowIfInheritsPrincipal */, 0 /* innerWindowID */);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    aRv.ThrowSecurityError("Scope URL is not same-origin with Client");
    return;
  }

  rv = principal->CheckMayLoadWithReporting(
      aScriptURI, false /* allowIfInheritsPrincipal */, 0 /* innerWindowID */);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    aRv.ThrowSecurityError("Script URL is not same-origin with Client");
    return;
  }
}

}  // namespace mozilla::dom