File: content_script_utils.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (565 lines) | stat: -rw-r--r-- 21,996 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
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/common/utils/content_script_utils.h"

#include <stddef.h>

#include <algorithm>
#include <memory>
#include <string_view>

#include "base/feature_list.h"
#include "base/files/file_util.h"
#include "base/strings/escape.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/common/url_constants.h"
#include "extensions/common/api/content_scripts.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handlers/permissions_parser.h"
#include "extensions/common/mojom/match_origin_as_fallback.mojom-shared.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/url_pattern.h"
#include "extensions/common/url_pattern_set.h"
#include "extensions/common/user_script.h"
#include "extensions/strings/grit/extensions_strings.h"
#include "net/base/mime_util.h"
#include "third_party/blink/public/common/mime_util/mime_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/gurl.h"

namespace extensions {

namespace errors = manifest_errors;

namespace script_parsing {

namespace {

BASE_FEATURE(kValidateContentScriptMimeType,
             "ValidateContentScriptMimeType",
             base::FEATURE_ENABLED_BY_DEFAULT);

size_t g_max_script_length_in_bytes = 1024u * 1024u * 500u;  // 500 MB.
size_t g_max_scripts_length_per_extension_in_bytes =
    1024u * 1024u * 1024u;  // 1 GB.

const char kEmptyFilesFynamicScriptError[] =
    "Script with ID '*' must specify at least one js or css file.";
constexpr char kEmptyMatchesDynamicScriptError[] =
    "Script with ID '*' must specify at least one match.";
constexpr char kInvalidExcludeMatchDynamicScriptError[] =
    "Script with ID '*' has invalid value for exclude_matches[*]: *";
constexpr char kInvalidMatchDynamicScriptError[] =
    "Script with ID '*' has invalid value for matches[*]: *";
constexpr char kForbiddenInlineCodeScriptError[] =
    "Script with ID '*' has forbidden inline code source";

// Returns true if the given path's mime type can be used for the given content
// script type.
bool IsMimeTypeValid(const base::FilePath& relative_path,
                     ContentScriptType content_script_type) {
  // TODO(https://crbug.com/40059598): Remove this if-check and always validate
  // the mime type in M139.
  if (!base::FeatureList::IsEnabled(kValidateContentScriptMimeType)) {
    return true;
  }

  auto file_extension = relative_path.Extension();
  if (file_extension.empty()) {
    return false;
  }

  // Strip leading ".".
  file_extension = file_extension.substr(1);

  // Allow .user.js files, which normally have no mime type, for JS content
  // scripts.
  if (content_script_type == ContentScriptType::kJs &&
      base::EqualsCaseInsensitiveASCII(file_extension,
                                       UserScript::kFileExtension)) {
    return true;
  }

  // Allow .scss files for CSS content scripts for compatibility with existing
  // extensions that were using such files before the mime type check was
  // introduced.
  if (content_script_type == ContentScriptType::kCss &&
      base::EqualsCaseInsensitiveASCII(file_extension, "scss")) {
    return true;
  }

  std::string mime_type;
  if (!net::GetWellKnownMimeTypeFromExtension(file_extension, &mime_type)) {
    return false;
  }

  switch (content_script_type) {
    case ContentScriptType::kJs:
      return blink::IsSupportedJavascriptMimeType(mime_type);

    case ContentScriptType::kCss:
      return mime_type == "text/css";
  }
}

// Returns false and sets the error if script file can't be loaded, or if it's
// not UTF-8 encoded. If a script file can be loaded but will exceed
// `max_script_length`, return true but add an install warning to `warnings`.
// Otherwise, decrement `remaining_length` by the script file's size.
bool IsScriptValid(const base::FilePath& path,
                   const base::FilePath& relative_path,
                   size_t max_script_length,
                   int file_not_read_error_id,
                   std::string* error,
                   std::vector<InstallWarning>* warnings,
                   size_t& remaining_length) {
  InstallWarning script_file_too_large_warning(
      l10n_util::GetStringFUTF8(IDS_EXTENSION_CONTENT_SCRIPT_FILE_TOO_LARGE,
                                relative_path.LossyDisplayName()),
      api::content_scripts::ManifestKeys::kContentScripts,
      base::UTF16ToUTF8(relative_path.LossyDisplayName()));
  if (remaining_length == 0u) {
    warnings->push_back(std::move(script_file_too_large_warning));
    return true;
  }

  if (!base::PathExists(path)) {
    *error = l10n_util::GetStringFUTF8(file_not_read_error_id,
                                       relative_path.LossyDisplayName());
    return false;
  }

  std::string content;
  bool read_successful =
      base::ReadFileToStringWithMaxSize(path, &content, max_script_length);
  // If the size of the file in `path` exceeds `max_script_length`,
  // ReadFileToStringWithMaxSize will return false but `content` will contain
  // the file's content truncated to `max_script_length`.
  if (!read_successful && content.length() != max_script_length) {
    *error = l10n_util::GetStringFUTF8(file_not_read_error_id,
                                       relative_path.LossyDisplayName());
    return false;
  }

  if (!base::IsStringUTF8(content)) {
    *error = l10n_util::GetStringFUTF8(IDS_EXTENSION_BAD_FILE_ENCODING,
                                       relative_path.LossyDisplayName());
    return false;
  }

  if (read_successful) {
    remaining_length -= content.size();
  } else {
    // Even though the script file is over the max size, we don't throw a hard
    // error so as not to break any existing extensions for which this is the
    // case.
    warnings->push_back(std::move(script_file_too_large_warning));
  }
  return true;
}

// Returns a string error when dynamic script with `script_id` or static script
// at `definition_index` has an empty field error.
std::u16string GetEmptyFieldError(std::string_view static_error,
                                  std::string_view dynamic_error,
                                  const std::string& script_id,
                                  std::optional<int> definition_index) {
  // Static scripts use a manifest error with `definition_index` since the
  // script id is autogenerated and the caller is unaware of it.
  if (definition_index) {
    return ErrorUtils::FormatErrorMessageUTF16(
        static_error, base::NumberToString(*definition_index));
  }

  return ErrorUtils::FormatErrorMessageUTF16(
      dynamic_error, UserScript::TrimPrefixFromScriptID(script_id));
}

// Returns a string error when dynamic script with `dynamic_error` and
// `script_id`, or static script with `static_error` at `definition_index` has
// an invalid exclude matches error.
std::u16string GetInvalidMatchError(std::string_view static_error,
                                    std::string_view dynamic_error,
                                    const std::string& script_id,
                                    std::optional<int> definition_index,
                                    URLPattern::ParseResult parse_result,
                                    int match_index) {
  std::string match_index_string = base::NumberToString(match_index);
  std::string parse_result_string =
      URLPattern::GetParseResultString(parse_result);

  // Static scripts use a manifest error with `definition_index` since the
  // script id is autogenerated and the caller is unaware of it.
  if (definition_index) {
    return ErrorUtils::FormatErrorMessageUTF16(
        static_error, base::NumberToString(*definition_index),
        match_index_string, parse_result_string);
  }

  return ErrorUtils::FormatErrorMessageUTF16(
      dynamic_error, UserScript::TrimPrefixFromScriptID(script_id),
      match_index_string, parse_result_string);
}

// Returns a string error when dynamic script with `script_id` or static script
// at `definition_index` has an empty matches error.
std::u16string GetEmptyMatchesError(const std::string& script_id,
                                    std::optional<int> definition_index) {
  return GetEmptyFieldError(errors::kInvalidMatchCount,
                            kEmptyMatchesDynamicScriptError, script_id,
                            definition_index);
}

// Returns a string error when dynamic script with `script_id` or static script
// at `definition_index` has an empty files error.
std::u16string GetEmptyFilesError(const std::string& script_id,
                                  std::optional<int> definition_index) {
  return GetEmptyFieldError(errors::kMissingFile, kEmptyFilesFynamicScriptError,
                            script_id, definition_index);
}

// Returns a string error when dynamic script with `script_id` or static script
// at `definition_index` has an invalid exclude matches error.
std::u16string GetInvalidExcludeMatchError(const std::string& script_id,
                                           std::optional<int> definition_index,
                                           URLPattern::ParseResult parse_result,
                                           int match_index) {
  return GetInvalidMatchError(errors::kInvalidExcludeMatch,
                              kInvalidExcludeMatchDynamicScriptError, script_id,
                              definition_index, parse_result, match_index);
}

// Returns a string error when dynamic script with `script_id` or static script
// at `definition_index` has an invalid matches error.
std::u16string GetInvalidMatchError(const std::string& script_id,
                                    std::optional<int> definition_index,
                                    URLPattern::ParseResult parse_result,
                                    int match_index) {
  return GetInvalidMatchError(errors::kInvalidMatch,
                              kInvalidMatchDynamicScriptError, script_id,
                              definition_index, parse_result, match_index);
}

}  // namespace

size_t GetMaxScriptLength() {
  return g_max_script_length_in_bytes;
}

size_t GetMaxScriptsLengthPerExtension() {
  return g_max_scripts_length_per_extension_in_bytes;
}

ScopedMaxScriptLengthOverride CreateScopedMaxScriptLengthForTesting(  // IN-TEST
    size_t max) {
  return ScopedMaxScriptLengthOverride(&g_max_script_length_in_bytes, max);
}

ScopedMaxScriptLengthOverride
CreateScopedMaxScriptsLengthPerExtensionForTesting(size_t max) {
  return ScopedMaxScriptLengthOverride(
      &g_max_scripts_length_per_extension_in_bytes, max);
}

bool ParseMatchPatterns(const std::vector<std::string>& matches,
                        const std::vector<std::string>* exclude_matches,
                        int creation_flags,
                        bool can_execute_script_everywhere,
                        bool all_urls_includes_chrome_urls,
                        std::optional<int> definition_index,
                        UserScript* result,
                        std::u16string* error,
                        bool* wants_file_access) {
  if (matches.empty()) {
    *error = GetEmptyMatchesError(result->id(), definition_index);
    return false;
  }

  const int valid_schemes =
      UserScript::ValidUserScriptSchemes(can_execute_script_everywhere);

  for (size_t i = 0; i < matches.size(); ++i) {
    URLPattern pattern(valid_schemes);

    const std::string& match_str = matches[i];
    URLPattern::ParseResult parse_result = pattern.Parse(match_str);
    if (parse_result != URLPattern::ParseResult::kSuccess) {
      *error =
          GetInvalidMatchError(result->id(), definition_index, parse_result, i);
      return false;
    }

    // TODO(aboxhall): check for webstore
    if (!all_urls_includes_chrome_urls &&
        pattern.scheme() != content::kChromeUIScheme) {
      // Exclude SCHEME_CHROMEUI unless it's been explicitly requested or
      // been granted by extension ID.
      // If the --extensions-on-chrome-urls flag has not been passed, requesting
      // a chrome:// url will cause a parse failure above, so there's no need to
      // check the flag here.
      pattern.SetValidSchemes(pattern.valid_schemes() &
                              ~URLPattern::SCHEME_CHROMEUI);
    }

    if (pattern.MatchesScheme(url::kFileScheme) &&
        !can_execute_script_everywhere) {
      if (wants_file_access)
        *wants_file_access = true;
      if (!(creation_flags & Extension::ALLOW_FILE_ACCESS)) {
        pattern.SetValidSchemes(pattern.valid_schemes() &
                                ~URLPattern::SCHEME_FILE);
      }
    }

    result->add_url_pattern(pattern);
  }

  if (exclude_matches) {
    for (size_t i = 0; i < exclude_matches->size(); ++i) {
      const std::string& match_str = exclude_matches->at(i);
      URLPattern pattern(valid_schemes);

      URLPattern::ParseResult parse_result = pattern.Parse(match_str);
      if (parse_result != URLPattern::ParseResult::kSuccess) {
        *error = GetInvalidExcludeMatchError(result->id(), definition_index,
                                             parse_result, i);
        return false;
      }

      result->add_exclude_url_pattern(pattern);
    }
  }

  return true;
}

bool ParseFileSources(
    const Extension* extension,
    const std::vector<api::scripts_internal::ScriptSource>* js,
    const std::vector<api::scripts_internal::ScriptSource>* css,
    std::optional<int> definition_index,
    UserScript* result,
    std::u16string* error) {
  if (js) {
    result->js_scripts().reserve(js->size());
    for (const auto& source : *js) {
      if (source.file) {
        GURL url =
            extension->ResolveExtensionURL(base::EscapePath(*source.file));
        ExtensionResource resource = extension->GetResource(*source.file);
        result->js_scripts().push_back(UserScript::Content::CreateFile(
            resource.extension_root(), resource.relative_path(), url));
      } else if (source.code) {
        // Inline code source is only allowed for user scripts.
        if (result->GetSource() != UserScript::Source::kDynamicUserScript) {
          *error = ErrorUtils::FormatErrorMessageUTF16(
              kForbiddenInlineCodeScriptError,
              UserScript::TrimPrefixFromScriptID(result->id()));
          return false;
        }

        GURL url = extension->ResolveExtensionURL(
            base::Uuid::GenerateRandomV4().AsLowercaseString());
        std::unique_ptr<UserScript::Content> content =
            UserScript::Content::CreateInlineCode(url);
        // TODO(crbug.com/40938420): This creates a copy of a
        // potentially-expensive string. Optimize the usage of inline code.
        content->set_content(*source.code);
        result->js_scripts().push_back(std::move(content));
      }
    }
  }

  if (css) {
    result->css_scripts().reserve(css->size());
    for (const auto& source : *css) {
      if (source.file) {
        GURL url =
            extension->ResolveExtensionURL(base::EscapePath(*source.file));
        ExtensionResource resource = extension->GetResource(*source.file);
        result->css_scripts().push_back(UserScript::Content::CreateFile(
            resource.extension_root(), resource.relative_path(), url));
      }
      // Note: We don't allow `code` in CSS blocks of any user script types yet.
    }
  }

  // The manifest needs to have at least one js or css user script definition.
  if (result->js_scripts().empty() && result->css_scripts().empty()) {
    *error = GetEmptyFilesError(result->id(), definition_index);
    return false;
  }

  return true;
}

void ParseGlobs(const std::vector<std::string>* include_globs,
                const std::vector<std::string>* exclude_globs,
                UserScript* result) {
  if (include_globs) {
    for (const std::string& glob : *include_globs) {
      result->add_glob(glob);
    }
  }

  if (exclude_globs) {
    for (const std::string& glob : *exclude_globs) {
      result->add_exclude_glob(glob);
    }
  }
}

bool ValidateMimeTypeFromFileExtension(const base::FilePath& relative_path,
                                       ContentScriptType content_script_type,
                                       std::string* error) {
  if (!IsMimeTypeValid(relative_path, content_script_type)) {
    switch (content_script_type) {
      case ContentScriptType::kJs:
        *error = l10n_util::GetStringFUTF8(
            IDS_EXTENSION_CONTENT_SCRIPT_FILE_BAD_JS_MIME_TYPE,
            relative_path.LossyDisplayName());
        return false;

      case ContentScriptType::kCss:
        *error = l10n_util::GetStringFUTF8(
            IDS_EXTENSION_CONTENT_SCRIPT_FILE_BAD_CSS_MIME_TYPE,
            relative_path.LossyDisplayName());
        return false;
    }
  }

  return true;
}

bool ValidateFileSources(const UserScriptList& scripts,
                         ExtensionResource::SymlinkPolicy symlink_policy,
                         std::string* error,
                         std::vector<InstallWarning>* warnings) {
  size_t remaining_scripts_length = GetMaxScriptsLengthPerExtension();

  for (const std::unique_ptr<UserScript>& script : scripts) {
    for (const std::unique_ptr<UserScript::Content>& js_script :
         script->js_scripts()) {
      // Don't validate scripts with inline code source, since they don't have
      // file sources.
      if (js_script->source() == UserScript::Content::Source::kInlineCode) {
        continue;
      }

      // Files with invalid mime types will be ignored.
      if (!ValidateMimeTypeFromFileExtension(js_script->relative_path(),
                                             ContentScriptType::kJs, error)) {
        warnings->emplace_back(
            base::StringPrintf(errors::kInvalidUserScriptMimeType,
                               error->c_str()),
            api::content_scripts::ManifestKeys::kContentScripts);
        continue;
      }

      const base::FilePath& path = ExtensionResource::GetFilePath(
          js_script->extension_root(), js_script->relative_path(),
          symlink_policy);
      size_t max_script_length =
          std::min(remaining_scripts_length, GetMaxScriptLength());
      if (!IsScriptValid(path, js_script->relative_path(), max_script_length,
                         IDS_EXTENSION_LOAD_JAVASCRIPT_FAILED, error, warnings,
                         remaining_scripts_length)) {
        return false;
      }
    }

    for (const std::unique_ptr<UserScript::Content>& css_script :
         script->css_scripts()) {
      // Files with invalid mime types will be ignored.
      if (!ValidateMimeTypeFromFileExtension(css_script->relative_path(),
                                             ContentScriptType::kCss, error)) {
        warnings->emplace_back(
            base::StringPrintf(errors::kInvalidUserScriptMimeType,
                               error->c_str()),
            api::content_scripts::ManifestKeys::kContentScripts);
        continue;
      }

      const base::FilePath& path = ExtensionResource::GetFilePath(
          css_script->extension_root(), css_script->relative_path(),
          symlink_policy);
      size_t max_script_length =
          std::min(remaining_scripts_length, GetMaxScriptLength());
      if (!IsScriptValid(path, css_script->relative_path(), max_script_length,
                         IDS_EXTENSION_LOAD_CSS_FAILED, error, warnings,
                         remaining_scripts_length)) {
        return false;
      }
    }
  }

  return true;
}

bool ValidateUserScriptMimeTypesFromFileExtensions(const UserScript& script,
                                                   std::string* error) {
  for (const std::unique_ptr<UserScript::Content>& js_script :
       script.js_scripts()) {
    // Don't validate scripts with inline code source, since they don't have
    // file sources.
    if (js_script->source() == UserScript::Content::Source::kInlineCode) {
      continue;
    }

    if (!ValidateMimeTypeFromFileExtension(js_script->relative_path(),
                                           ContentScriptType::kJs, error)) {
      return false;
    }
  }

  for (const std::unique_ptr<UserScript::Content>& css_script :
       script.css_scripts()) {
    if (!ValidateMimeTypeFromFileExtension(css_script->relative_path(),
                                           ContentScriptType::kCss, error)) {
      return false;
    }
  }

  return true;
}

bool ValidateMatchOriginAsFallback(
    mojom::MatchOriginAsFallbackBehavior match_origin_as_fallback,
    const URLPatternSet& url_patterns,
    std::u16string* error_out) {
  // If the extension is using `match_origin_as_fallback`, we require the
  // pattern to match all paths. This is because origins don't have a path;
  // thus, if an extension specified `"match_origin_as_fallback": true` for
  // a pattern of `"https://google.com/maps/*"`, this script would also run
  // on about:blank, data:, etc frames from https://google.com (because in
  // both cases, the precursor origin is https://google.com).
  if (match_origin_as_fallback ==
      mojom::MatchOriginAsFallbackBehavior::kAlways) {
    for (const auto& pattern : url_patterns) {
      if (pattern.path() != "/*") {
        *error_out = errors::kMatchOriginAsFallbackCantHavePaths;
        return false;
      }
    }
  }

  return true;
}

ExtensionResource::SymlinkPolicy GetSymlinkPolicy(const Extension* extension) {
  if ((extension->creation_flags() & Extension::FOLLOW_SYMLINKS_ANYWHERE) !=
      0) {
    return ExtensionResource::FOLLOW_SYMLINKS_ANYWHERE;
  }

  return ExtensionResource::SYMLINKS_MUST_RESOLVE_WITHIN_ROOT;
}

}  // namespace script_parsing
}  // namespace extensions