File: TrustedTypePolicyFactory.cpp

package info (click to toggle)
firefox 147.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,683,484 kB
  • sloc: cpp: 7,607,246; javascript: 6,533,185; ansic: 3,775,227; python: 1,415,393; xml: 634,561; asm: 438,951; java: 186,241; sh: 62,752; makefile: 18,079; objc: 13,092; perl: 12,808; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (368 lines) | stat: -rw-r--r-- 15,174 bytes parent folder | download | duplicates (3)
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
/* -*- 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/TrustedTypePolicyFactory.h"

#include <utility>

#include "mozilla/AlreadyAddRefed.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/RefPtr.h"
#include "mozilla/dom/CSPViolationData.h"
#include "mozilla/dom/PolicyContainer.h"
#include "mozilla/dom/TrustedTypePolicy.h"
#include "mozilla/dom/TrustedTypeUtils.h"
#include "mozilla/dom/WorkerPrivate.h"
#include "mozilla/dom/WorkerRunnable.h"
#include "mozilla/dom/WorkerScope.h"
#include "mozilla/dom/nsCSPUtils.h"
#include "nsLiteralString.h"

using namespace mozilla::dom::TrustedTypeUtils;

namespace mozilla::dom {

NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(TrustedTypePolicyFactory, mGlobalObject,
                                      mDefaultPolicy)

TrustedTypePolicyFactory::TrustedTypePolicyFactory(
    nsIGlobalObject* aGlobalObject)
    : mGlobalObject{aGlobalObject} {}

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

// Default implementation in the .cpp file required because `mDefaultPolicy`
// requires a definition for `TrustedTypePolicy`.
TrustedTypePolicyFactory::~TrustedTypePolicyFactory() = default;

// Implement reporting of violations for policy creation.
// https://w3c.github.io/trusted-types/dist/spec/#should-block-create-policy
static void ReportPolicyCreationViolations(
    nsIContentSecurityPolicy* aCSP, nsICSPEventListener* aCSPEventListener,
    const nsCString& aFileName, uint32_t aLine, uint32_t aColumn,
    const nsTArray<nsString>& aCreatedPolicyNames,
    const nsAString& aPolicyName) {
  MOZ_ASSERT(aCSP);
  uint32_t numPolicies = 0;
  aCSP->GetPolicyCount(&numPolicies);
  for (uint32_t i = 0; i < numPolicies; ++i) {
    const nsCSPPolicy* policy = aCSP->GetPolicy(i);
    if (policy->hasDirective(
            nsIContentSecurityPolicy::TRUSTED_TYPES_DIRECTIVE)) {
      if (policy->ShouldCreateViolationForNewTrustedTypesPolicy(
              aPolicyName, aCreatedPolicyNames)) {
        CSPViolationData cspViolationData{
            i,
            CSPViolationData::Resource{
                CSPViolationData::BlockedContentSource::TrustedTypesPolicy},
            nsIContentSecurityPolicy::TRUSTED_TYPES_DIRECTIVE,
            aFileName,
            aLine,
            aColumn,
            /* aElement */ nullptr,
            CSPViolationData::MaybeTruncateSample(aPolicyName)};
        aCSP->LogTrustedTypesViolationDetailsUnchecked(
            std::move(cspViolationData),
            NS_LITERAL_STRING_FROM_CSTRING(
                TRUSTED_TYPES_VIOLATION_OBSERVER_TOPIC),
            aCSPEventListener);
      }
    }
  }
}

class LogPolicyCreationViolationsRunnable final
    : public WorkerMainThreadRunnable {
 public:
  LogPolicyCreationViolationsRunnable(
      WorkerPrivate* aWorker, const nsCString& aFileName, uint32_t aLine,
      uint32_t aColumn, const nsTArray<nsString>& aCreatedPolicyNames,
      const nsAString& aPolicyName)
      : WorkerMainThreadRunnable(
            aWorker,
            "RuntimeService :: LogPolicyCreationViolationsRunnable"_ns),
        mFileName(aFileName),
        mLine(aLine),
        mColumn(aColumn),
        mCreatedPolicyNames(aCreatedPolicyNames),
        mPolicyName(aPolicyName) {
    MOZ_ASSERT(aWorker);
  }

  virtual bool MainThreadRun() override {
    AssertIsOnMainThread();
    MOZ_ASSERT(mWorkerRef);
    if (nsIContentSecurityPolicy* csp = mWorkerRef->Private()->GetCsp()) {
      ReportPolicyCreationViolations(
          csp, mWorkerRef->Private()->CSPEventListener(), mFileName, mLine,
          mColumn, mCreatedPolicyNames, mPolicyName);
    }
    return true;
  }

 private:
  ~LogPolicyCreationViolationsRunnable() = default;
  const nsCString& mFileName;
  uint32_t mLine;
  uint32_t mColumn;
  const nsTArray<nsString>& mCreatedPolicyNames;
  const nsString mPolicyName;
};

auto TrustedTypePolicyFactory::ShouldTrustedTypePolicyCreationBeBlockedByCSP(
    JSContext* aJSContext, const nsAString& aPolicyName) const
    -> PolicyCreation {
  auto shouldBlock = [this, &aPolicyName](const nsCSPPolicy* aPolicy) {
    return aPolicy->hasDirective(
               nsIContentSecurityPolicy::TRUSTED_TYPES_DIRECTIVE) &&
           aPolicy->getDisposition() == nsCSPPolicy::Disposition::Enforce &&
           aPolicy->ShouldCreateViolationForNewTrustedTypesPolicy(
               aPolicyName, mCreatedPolicyNames);
  };

  auto result = PolicyCreation::Allowed;
  auto location = JSCallingLocation::Get(aJSContext);
  if (auto* piDOMWindowInner = mGlobalObject->GetAsInnerWindow()) {
    if (auto* csp =
            PolicyContainer::GetCSP(piDOMWindowInner->GetPolicyContainer())) {
      ReportPolicyCreationViolations(
          csp, nullptr /* aCSPEventListener */, location.FileName(),
          location.mLine, location.mColumn, mCreatedPolicyNames, aPolicyName);
      uint32_t numPolicies = 0;
      csp->GetPolicyCount(&numPolicies);
      for (uint64_t i = 0; i < numPolicies; ++i) {
        const nsCSPPolicy* policy = csp->GetPolicy(i);
        if (shouldBlock(policy)) {
          result = PolicyCreation::Blocked;
          break;
        }
      }
    }
  } else {
    MOZ_ASSERT(IsWorkerGlobal(mGlobalObject->GetGlobalJSObject()));
    MOZ_ASSERT(!NS_IsMainThread());
    WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
    RefPtr<LogPolicyCreationViolationsRunnable> runnable =
        new LogPolicyCreationViolationsRunnable(
            workerPrivate, location.FileName(), location.mLine,
            location.mColumn, mCreatedPolicyNames, aPolicyName);
    ErrorResult rv;
    runnable->Dispatch(workerPrivate, Killing, rv);
    if (NS_WARN_IF(rv.Failed())) {
      rv.SuppressException();
    }
    if (WorkerCSPContext* ctx = workerPrivate->GetCSPContext()) {
      for (const UniquePtr<const nsCSPPolicy>& policy : ctx->Policies()) {
        if (shouldBlock(policy.get())) {
          result = PolicyCreation::Blocked;
          break;
        }
      }
    }
  }

  return result;
}

constexpr nsLiteralString kDefaultPolicyName = u"default"_ns;

already_AddRefed<TrustedTypePolicy> TrustedTypePolicyFactory::CreatePolicy(
    JSContext* aJSContext, const nsAString& aPolicyName,
    const TrustedTypePolicyOptions& aPolicyOptions, ErrorResult& aRv) {
  if (PolicyCreation::Blocked ==
      ShouldTrustedTypePolicyCreationBeBlockedByCSP(aJSContext, aPolicyName)) {
    nsCString errorMessage =
        "Content-Security-Policy blocked creating policy named '"_ns +
        NS_ConvertUTF16toUTF8(aPolicyName) + "'"_ns;

    // TODO: perhaps throw different TypeError messages,
    //       https://github.com/w3c/trusted-types/issues/511.
    aRv.ThrowTypeError(errorMessage);
    return nullptr;
  }

  if (aPolicyName.Equals(kDefaultPolicyName) && mDefaultPolicy) {
    aRv.ThrowTypeError("Tried to create a second default policy"_ns);
    return nullptr;
  }

  TrustedTypePolicy::Options options;

  if (aPolicyOptions.mCreateHTML.WasPassed()) {
    options.mCreateHTMLCallback = &aPolicyOptions.mCreateHTML.Value();
  }

  if (aPolicyOptions.mCreateScript.WasPassed()) {
    options.mCreateScriptCallback = &aPolicyOptions.mCreateScript.Value();
  }

  if (aPolicyOptions.mCreateScriptURL.WasPassed()) {
    options.mCreateScriptURLCallback = &aPolicyOptions.mCreateScriptURL.Value();
  }

  RefPtr<TrustedTypePolicy> policy =
      MakeRefPtr<TrustedTypePolicy>(this, aPolicyName, std::move(options));

  if (aPolicyName.Equals(kDefaultPolicyName)) {
    mDefaultPolicy = policy;
  }

  mCreatedPolicyNames.AppendElement(aPolicyName);

  return policy.forget();
}

#define IS_TRUSTED_TYPE_IMPL(_trustedTypeSuffix)                                                                                                                         \
  bool TrustedTypePolicyFactory::Is##_trustedTypeSuffix(                                                                                                                 \
      JSContext*, const JS::Handle<JS::Value>& aValue) const {                                                                                                           \
    /**                                                                                                                                                                  \
     * No need to check the internal slot.                                                                                                                               \
     * Ensured by the corresponding test:                                                                                                                                \
     * <https://searchfox.org/mozilla-central/rev/b60cb73160843adb5a5a3ec8058e75a69b46acf7/testing/web-platform/tests/trusted-types/TrustedTypePolicyFactory-isXXX.html> \
     */                                                                                                                                                                  \
    return aValue.isObject() &&                                                                                                                                          \
           IS_INSTANCE_OF(Trusted##_trustedTypeSuffix, &aValue.toObject());                                                                                              \
  }

IS_TRUSTED_TYPE_IMPL(HTML);
IS_TRUSTED_TYPE_IMPL(Script);
IS_TRUSTED_TYPE_IMPL(ScriptURL);

already_AddRefed<TrustedHTML> TrustedTypePolicyFactory::EmptyHTML() {
  // Preserving the wrapper ensures:
  // ```
  //  const e = trustedTypes.emptyHTML;
  //  e === trustedTypes.emptyHTML;
  // ```
  // which comes with the cost of keeping the factory, one per global, alive.
  // An additional benefit is it saves the cost of re-instantiating potentially
  // multiple emptyHML objects. Both, the JS- and the C++-objects.
  dom::PreserveWrapper(this);

  RefPtr<TrustedHTML> result = new TrustedHTML(EmptyString());
  return result.forget();
}

already_AddRefed<TrustedScript> TrustedTypePolicyFactory::EmptyScript() {
  // See the explanation in `EmptyHTML()`.
  dom::PreserveWrapper(this);

  RefPtr<TrustedScript> result = new TrustedScript(EmptyString());
  return result.forget();
}

// TODO(fwang): Improve this API:
// - Rename aTagName parameter to use aLocalName instead
//   (https://github.com/w3c/trusted-types/issues/496)
// - Remove ASCII-case-insensitivity for aTagName and aAttribute
//  (https://github.com/w3c/trusted-types/issues/424)
// - Make aElementNs default to HTML namespace, so special handling for an empty
//   string is not needed (https://github.com/w3c/trusted-types/issues/381).
void TrustedTypePolicyFactory::GetAttributeType(const nsAString& aTagName,
                                                const nsAString& aAttribute,
                                                const nsAString& aElementNs,
                                                const nsAString& aAttrNs,
                                                DOMString& aResult) {
  // We first determine the namespace IDs for the element and attribute.
  // Currently, GetTrustedTypeDataForAttribute() only test a few of them so use
  // direct string comparisons instead of relying on
  // nsNameSpaceManager::GetNameSpaceID().

  // GetTrustedTypeDataForAttribute() can only return true for empty or XLink
  // attribute namespaces, so don't bother calling it for other namespaces.
  int32_t attributeNamespaceID = kNameSpaceID_Unknown;
  if (aAttrNs.IsEmpty()) {
    attributeNamespaceID = kNameSpaceID_None;
  } else if (nsGkAtoms::nsuri_xlink->Equals(aAttrNs)) {
    attributeNamespaceID = kNameSpaceID_XLink;
  } else {
    aResult.SetNull();
    return;
  }

  // GetTrustedTypeDataForAttribute() only return true for HTML, SVG or MathML
  // element namespaces, so don't bother calling it for other namespaces.
  int32_t elementNamespaceID = kNameSpaceID_Unknown;
  if (aElementNs.IsEmpty() || nsGkAtoms::nsuri_xhtml->Equals(aElementNs)) {
    elementNamespaceID = kNameSpaceID_XHTML;
  } else if (nsGkAtoms::nsuri_svg->Equals(aElementNs)) {
    elementNamespaceID = kNameSpaceID_SVG;
  } else if (nsGkAtoms::nsuri_mathml->Equals(aElementNs)) {
    elementNamespaceID = kNameSpaceID_MathML;
  } else {
    aResult.SetNull();
    return;
  }

  nsAutoString attribute;
  nsContentUtils::ASCIIToLower(aAttribute, attribute);
  RefPtr<nsAtom> attributeAtom = NS_Atomize(attribute);

  nsAutoString localName;
  nsContentUtils::ASCIIToLower(aTagName, localName);
  RefPtr<nsAtom> elementAtom = NS_Atomize(localName);

  TrustedType trustedType;
  nsAutoString unusedSink;
  if (GetTrustedTypeDataForAttribute(elementAtom, elementNamespaceID,
                                     attributeAtom, attributeNamespaceID,
                                     trustedType, unusedSink)) {
    aResult.SetKnownLiveString(GetTrustedTypeName(trustedType));
    return;
  }

  aResult.SetNull();
}

// TODO(fwang): Improve this API:
// - Rename aTagName parameter to use aLocalName instead
//   (https://github.com/w3c/trusted-types/issues/496)
// - Remove ASCII-case-insensitivity for aTagName
//  (https://github.com/w3c/trusted-types/issues/424)
// - Make aElementNs default to HTML namespace, so special handling for an empty
//   string is not needed (https://github.com/w3c/trusted-types/issues/381).
void TrustedTypePolicyFactory::GetPropertyType(const nsAString& aTagName,
                                               const nsAString& aProperty,
                                               const nsAString& aElementNs,
                                               DOMString& aResult) {
  RefPtr<nsAtom> propertyAtom = NS_Atomize(aProperty);
  if (aElementNs.IsEmpty() || nsGkAtoms::nsuri_xhtml->Equals(aElementNs)) {
    if (nsContentUtils::EqualsIgnoreASCIICase(
            aTagName, nsDependentAtomString(nsGkAtoms::iframe))) {
      // HTMLIFrameElement
      if (propertyAtom == nsGkAtoms::srcdoc) {
        aResult.SetKnownLiveString(GetTrustedTypeName<TrustedHTML>());
        return;
      }
    } else if (nsContentUtils::EqualsIgnoreASCIICase(
                   aTagName, nsDependentAtomString(nsGkAtoms::script))) {
      // HTMLScriptElement
      if (propertyAtom == nsGkAtoms::innerText ||
          propertyAtom == nsGkAtoms::text ||
          propertyAtom == nsGkAtoms::textContent) {
        aResult.SetKnownLiveString(GetTrustedTypeName<TrustedScript>());
        return;
      }
      if (propertyAtom == nsGkAtoms::src) {
        aResult.SetKnownLiveString(GetTrustedTypeName<TrustedScriptURL>());
        return;
      }
    }
  }
  // *
  if (propertyAtom == nsGkAtoms::innerHTML ||
      propertyAtom == nsGkAtoms::outerHTML) {
    aResult.SetKnownLiveString(GetTrustedTypeName<TrustedHTML>());
    return;
  }

  aResult.SetNull();
}

}  // namespace mozilla::dom