Changeset 253683 in webkit


Ignore:
Timestamp:
Dec 18, 2019 7:48:59 AM (4 years ago)
Author:
Chris Dumez
Message:

Re-sync web-platform-tests/common from upstream
https://bugs.webkit.org/show_bug.cgi?id=205342

Reviewed by Frédéric Wang.

Re-sync web-platform-tests/common from upstream e9d489f3377139a1d54b.

LayoutTests/imported/w3c:

  • web-platform-tests/common/*: Updated.

LayoutTests:

  • canvas/philip/tests/2d.drawImage.incomplete.emptysrc-expected.txt:
  • canvas/philip/tests/2d.drawImage.incomplete.emptysrc.html:
  • canvas/philip/tests/2d.drawImage.incomplete.nosrc-expected.txt:
  • canvas/philip/tests/2d.drawImage.incomplete.nosrc.html:
  • canvas/philip/tests/2d.drawImage.incomplete.removedsrc-expected.txt:
  • canvas/philip/tests/2d.drawImage.incomplete.removedsrc.html:
  • canvas/philip/tests/2d.pattern.image.incomplete.emptysrc-expected.txt:
  • canvas/philip/tests/2d.pattern.image.incomplete.emptysrc.html:
  • canvas/philip/tests/2d.pattern.image.incomplete.removedsrc-expected.txt:
  • canvas/philip/tests/2d.pattern.image.incomplete.removedsrc.html:
  • http/wpt/2dcontext/imagebitmap/createImageBitmap-sizing.html:
  • http/wpt/2dcontext/imagebitmap/drawImage-ImageBitmap.html:
Location:
trunk/LayoutTests
Files:
6 added
16 deleted
29 edited
1 moved

Legend:

Unmodified
Added
Removed
  • trunk/LayoutTests/ChangeLog

    r253679 r253683  
     12019-12-18  Chris Dumez  <cdumez@apple.com>
     2
     3        Re-sync web-platform-tests/common from upstream
     4        https://bugs.webkit.org/show_bug.cgi?id=205342
     5
     6        Reviewed by Frédéric Wang.
     7
     8        Re-sync web-platform-tests/common from upstream e9d489f3377139a1d54b.
     9
     10        * canvas/philip/tests/2d.drawImage.incomplete.emptysrc-expected.txt:
     11        * canvas/philip/tests/2d.drawImage.incomplete.emptysrc.html:
     12        * canvas/philip/tests/2d.drawImage.incomplete.nosrc-expected.txt:
     13        * canvas/philip/tests/2d.drawImage.incomplete.nosrc.html:
     14        * canvas/philip/tests/2d.drawImage.incomplete.removedsrc-expected.txt:
     15        * canvas/philip/tests/2d.drawImage.incomplete.removedsrc.html:
     16        * canvas/philip/tests/2d.pattern.image.incomplete.emptysrc-expected.txt:
     17        * canvas/philip/tests/2d.pattern.image.incomplete.emptysrc.html:
     18        * canvas/philip/tests/2d.pattern.image.incomplete.removedsrc-expected.txt:
     19        * canvas/philip/tests/2d.pattern.image.incomplete.removedsrc.html:
     20        * http/wpt/2dcontext/imagebitmap/createImageBitmap-sizing.html:
     21        * http/wpt/2dcontext/imagebitmap/drawImage-ImageBitmap.html:
     22
    1232019-12-18  Antoine Quint  <graouts@apple.com>
    224
  • trunk/LayoutTests/canvas/philip/tests/2d.drawImage.incomplete.emptysrc-expected.txt

    r181888 r253683  
    112d.drawImage.incomplete.emptysrc
    2 
    32Actual output:
    4 
    53Expected output:
    6 
    7 
    8 
    94
    105
  • trunk/LayoutTests/canvas/philip/tests/2d.drawImage.incomplete.emptysrc.html

    r181888 r253683  
    44<script src="../../../resources/testharness.js"></script>
    55<script src="../../../resources/testharnessreport.js"></script>
    6 <script src="../../../imported/w3c/web-platform-tests/common/canvas-tests.js"></script>
    7 <link rel="stylesheet" href="/common/canvas-tests.css">
     6<script src="../../../imported/w3c/web-platform-tests/2dcontext/resources/canvas-tests.js"></script>
     7<link rel="stylesheet" href="../../../imported/w3c/web-platform-tests/2dcontext/resources/canvas-tests.css">
    88<body class="show_output">
    99
  • trunk/LayoutTests/canvas/philip/tests/2d.drawImage.incomplete.nosrc-expected.txt

    r181888 r253683  
    112d.drawImage.incomplete.nosrc
    2 
    32Actual output:
    4 
    53Expected output:
    6 
    7 
    84
    95
  • trunk/LayoutTests/canvas/philip/tests/2d.drawImage.incomplete.nosrc.html

    r181888 r253683  
    44<script src="../../../resources/testharness.js"></script>
    55<script src="../../../resources/testharnessreport.js"></script>
    6 <script src="../../../imported/w3c/web-platform-tests/common/canvas-tests.js"></script>
    7 <link rel="stylesheet" href="/common/canvas-tests.css">
     6<script src="../../../imported/w3c/web-platform-tests/2dcontext/resources/canvas-tests.js"></script>
     7<link rel="stylesheet" href="../../../imported/w3c/web-platform-tests/2dcontext/resources/canvas-tests.css">
    88<body class="show_output">
    99
  • trunk/LayoutTests/canvas/philip/tests/2d.drawImage.incomplete.removedsrc-expected.txt

    r181888 r253683  
    112d.drawImage.incomplete.removedsrc
    2 
    32Actual output:
    4 
    53Expected output:
    6 
    7 
    8 
    94
    105
  • trunk/LayoutTests/canvas/philip/tests/2d.drawImage.incomplete.removedsrc.html

    r181888 r253683  
    44<script src="../../../resources/testharness.js"></script>
    55<script src="../../../resources/testharnessreport.js"></script>
    6 <script src="../../../imported/w3c/web-platform-tests/common/canvas-tests.js"></script>
    7 <link rel="stylesheet" href="/common/canvas-tests.css">
     6<script src="../../../imported/w3c/web-platform-tests/2dcontext/resources/canvas-tests.js"></script>
     7<link rel="stylesheet" href="../../../imported/w3c/web-platform-tests/2dcontext/resources/canvas-tests.css">
    88<body class="show_output">
    99
  • trunk/LayoutTests/canvas/philip/tests/2d.pattern.image.incomplete.emptysrc-expected.txt

    r181888 r253683  
    112d.pattern.image.incomplete.emptysrc
    2 
    32Actual output:
    4 
    5  
    63
    74PASS Canvas test: 2d.pattern.image.incomplete.emptysrc
  • trunk/LayoutTests/canvas/philip/tests/2d.pattern.image.incomplete.emptysrc.html

    r181888 r253683  
    44<script src="../../../resources/testharness.js"></script>
    55<script src="../../../resources/testharnessreport.js"></script>
    6 <script src="../../../imported/w3c/web-platform-tests/common/canvas-tests.js"></script>
    7 <link rel="stylesheet" href="/common/canvas-tests.css">
     6<script src="../../../imported/w3c/web-platform-tests/2dcontext/resources/canvas-tests.js"></script>
     7<link rel="stylesheet" href="../../../imported/w3c/web-platform-tests/2dcontext/resources/canvas-tests.css">
    88<body class="show_output">
    99
  • trunk/LayoutTests/canvas/philip/tests/2d.pattern.image.incomplete.removedsrc-expected.txt

    r181888 r253683  
    112d.pattern.image.incomplete.removedsrc
    2 
    32Actual output:
    4 
    5  
    63
    74PASS Canvas test: 2d.pattern.image.incomplete.removedsrc
  • trunk/LayoutTests/canvas/philip/tests/2d.pattern.image.incomplete.removedsrc.html

    r181888 r253683  
    44<script src="../../../resources/testharness.js"></script>
    55<script src="../../../resources/testharnessreport.js"></script>
    6 <script src="../../../imported/w3c/web-platform-tests/common/canvas-tests.js"></script>
    7 <link rel="stylesheet" href="/common/canvas-tests.css">
     6<script src="../../../imported/w3c/web-platform-tests/2dcontext/resources/canvas-tests.js"></script>
     7<link rel="stylesheet" href="../../../imported/w3c/web-platform-tests/2dcontext/resources/canvas-tests.css">
    88<body class="show_output">
    99
  • trunk/LayoutTests/http/wpt/2dcontext/imagebitmap/createImageBitmap-sizing.html

    r224158 r253683  
    44<script src="/resources/testharness.js"></script>
    55<script src="/resources/testharnessreport.js"></script>
    6 <script src="/common/canvas-tests.js"></script>
     6<script src="/2dcontext/resources/canvas-tests.js"></script>
    77<script src="common.js"></script>
    88<link rel="stylesheet" href="/common/canvas-tests.css">
  • trunk/LayoutTests/http/wpt/2dcontext/imagebitmap/drawImage-ImageBitmap.html

    r224158 r253683  
    44<script src="/resources/testharness.js"></script>
    55<script src="/resources/testharnessreport.js"></script>
    6 <script src="/common/canvas-tests.js"></script>
     6<script src="/2dcontext/resources/canvas-tests.js"></script>
    77<script src="common.js"></script>
    88<link rel="stylesheet" href="/common/canvas-tests.css">
  • trunk/LayoutTests/imported/w3c/ChangeLog

    r253668 r253683  
     12019-12-18  Chris Dumez  <cdumez@apple.com>
     2
     3        Re-sync web-platform-tests/common from upstream
     4        https://bugs.webkit.org/show_bug.cgi?id=205342
     5
     6        Reviewed by Frédéric Wang.
     7
     8        Re-sync web-platform-tests/common from upstream e9d489f3377139a1d54b.
     9
     10        * web-platform-tests/common/*: Updated.
     11
    1122019-12-17  Chris Dumez  <cdumez@apple.com>
    213
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/get-host-info.sub.js

    r245004 r253683  
    1313  var REMOTE_HOST = (ORIGINAL_HOST === 'localhost') ? '127.0.0.1' : ('www1.' + ORIGINAL_HOST);
    1414  var OTHER_HOST = '{{domains[www2]}}';
    15   var NOTSAMESITE_HOST = (ORIGINAL_HOST === 'localhost') ? '127.0.0.1' : ('not-' + ORIGINAL_HOST);
     15  var NOTSAMESITE_HOST = (ORIGINAL_HOST === 'localhost') ? '127.0.0.1' : ('{{hosts[alt][]}}');
    1616
    1717  return {
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/security-features/README.md

    r245004 r253683  
    1 This directory contains the common infrastructure for the following tests.
     1
     2
     3This directory contains the common infrastructure for the following tests (also referred below as projects).
     4
    25- referrer-policy/
    36- mixed-content/
     
    58
    69Subdirectories:
     10
     11- `resources`:
     12    Serves JavaScript test helpers.
    713- `subresource`:
    814    Serves subresources, with support for redirects, stash, etc.
     
    1218    Serves nested contexts, such as iframe documents or workers.
    1319    Used from `invokeFrom*()` functions in `resources/common.js`.
     20- `tools`:
     21    Scripts that generate test HTML files. Not used while running tests.
     22- `/referrer-policy/generic/subresource-test`:
     23    Sanity checking tests for subresource invocation
     24    (This is still placed outside common/)
     25
     26# Test generator
     27
     28The test generator (`common/security-features/tools`) generates test HTML files from templates and a seed (`spec.src.json`) that defines all the test scenarios.
     29
     30The project (i.e. a WPT subdirectory, for example `referrer-policy/`) that uses the generator should define per-project data and invoke the common generator logic in `common/security-features/tools`.
     31
     32This is the overview of the project structure:
     33
     34```
     35common/security-features/
     36└── tools/ - the common test generator logic
     37    └── template/ - the test files templates
     38project-directory/ (e.g. referrer-policy/)
     39├── spec.src.json
     40├── generic/
     41│   ├── test-case.sub.js - Per-project test helper
     42│   └── tools/
     43│       └── generator.py - Per-project generator script
     44└── gen/ - generated tests
     45```
     46
     47Invoking `project-directory/generic/tools/generate.py` will parse the spec JSON and determine which tests to generate (or skip) while using templates.
     48
     49## Generating the tests
     50
     51The repository already contains generated tests, so if you're making changes, see the [Removing all generated tests](#removing-all-generated-tests) section below, on how to remove them before you start generating tests which include your changes.
     52
     53```bash
     54# Chdir into the project directory.
     55cd ~/web-platform-tests/project-directory
     56
     57# Generate the test files under gen/ (HTMLs and .headers files).
     58./generic/tools/generate.py
     59
     60# Add all generated tests to the repo.
     61git add gen/ && git commit -m "Add generated tests"
     62```
     63
     64During the generation, the spec is validated by ```common/security-features/tools/spec_validator.py```. This is specially important when you're making changes to  `spec.src.json`. Make sure it's a valid JSON (no comments or trailing commas). The validator reports specific errors (missing keys etc.), if any.
     65
     66### Removing all generated tests
     67
     68Simply remove all files under `project-directory/gen/`.
     69
     70```bash
     71# Chdir into the project directory.
     72cd ~/web-platform-tests/project-directory
     73
     74# Remove all generated tests.
     75rm -r gen/
     76```
     77
     78### Options for generating tests
     79
     80Note: this section is currently obsolete. Only the release template is working.
     81
     82The generator script ```./generic/tools/generate.py``` has two targets: ```release``` and ```debug```.
     83
     84* Using **release** for the target will produce tests using a template for optimizing size and performance. The release template is intended for the official web-platform-tests and possibly other test suites. No sanity checking is done in release mode. Use this option whenever you're checking into web-platform-tests.
     85
     86* When generating for ```debug```, the produced tests will contain more verbosity and sanity checks. Use this target to identify problems with the test suites when making changes locally. Make sure you don't check in tests generated with the debug target.
     87
     88Note that **release** is the default target when invoking ```generate.py```.
     89
     90
     91## Updating the tests
     92
     93The main test logic lives in ```project-directory/generic/test-case.sub.js``` with helper functions defined in ```/common/security-features/resources/common.js``` so you should probably start there.
     94
     95For updating the test suites you will most likely do **a subset** of the following:
     96
     97* Add a new subresource type:
     98
     99  * Add a new sub-resource python script to `/common/security-features/subresource/`.
     100  * Add a sanity check test for a sub-resource to `referrer-policy/generic/subresource-test/`.
     101  * Add a new entry to `subresourceMap` in `/common/security-features/resources/common.js`.
     102  * Add a new entry to `valid_subresource_names` in `/common/security-features/tools/spec_validator.py`.
     103  * Add a new entry to `subresource_schema` in `spec.src.json`.
     104  * Update `source_context_schema` to specify in which source context the subresource can be used.
     105
     106* Add a new subresource redirection type
     107
     108  * TODO: to be documented. Example: [https://github.com/web-platform-tests/wpt/pull/18939](https://github.com/web-platform-tests/wpt/pull/18939)
     109
     110* Add a new subresource origin type
     111
     112  * TODO: to be documented. Example: [https://github.com/web-platform-tests/wpt/pull/18940](https://github.com/web-platform-tests/wpt/pull/18940)
     113
     114* Add a new source context (e.g. "module sharedworker global scope")
     115
     116  * TODO: to be documented. Example: [https://github.com/web-platform-tests/wpt/pull/18904](https://github.com/web-platform-tests/wpt/pull/18904)
     117
     118* Add a new source context list (e.g. "subresource request from a dedicated worker in a `<iframe srcdoc>`")
     119
     120  * TODO: to be documented.
     121
     122* Implement new or update existing assertions in ```project-directory/generic/test-case.sub.js```.
     123
     124* Exclude or add some tests by updating ```spec.src.json``` test expansions.
     125
     126* Implement a new delivery method.
     127
     128  * TODO: to be documented. Currently the support for delivery methods are implemented in many places across `common/security-features/`.
     129
     130* Regenerate the tests and MANIFEST.json
     131
     132
     133## The spec JSON format
     134
     135For examples of spec JSON files, see [referrer-policy/spec.src.json](../../referrer-policy/spec.src.json) or  [mixed-content/spec.src.json](../../mixed-content/spec.src.json).
     136
     137### Main sections
     138
     139* **`specification`**
     140
     141  Top level requirements with description fields and a ```test_expansion``` rule.
     142  This is closely mimicking the [Referrer Policy specification](http://w3c.github.io/webappsec/specs/referrer-policy/) structure.
     143
     144* **`excluded_tests`**
     145
     146  List of ```test_expansion``` patterns expanding into selections which get skipped when generating the tests (aka. blacklisting/suppressing)
     147
     148* **`test_expansion_schema`**
     149
     150  Provides valid values for each field.
     151  Each test expansion can only contain fields and values defined by this schema (or `"*"` values that indicate all the valid values defined this schema).
     152
     153* **`subresource_schema`**
     154
     155  Provides metadata of subresources, e.g. supported delivery types for each subresource.
     156
     157* **`source_context_schema`**
     158
     159  Provides metadata of each single source context, e.g. supported delivery types and subresources that can be sent from the context.
     160
     161* **`source_context_list_schema`**
     162
     163  Provides possible nested combinations of source contexts. See [Source Contexts](#source-contexts) section below for details.
     164
     165### Test Expansion Patterns
     166
     167Each field in a test expansion can be in one of the following formats:
     168
     169* Single match: ```"value"```
     170
     171* Match any of: ```["value1", "value2", ...]```
     172
     173* Match all: ```"*"```
     174
     175
     176**NOTE:** An expansion is always constructive (inclusive), there isn't a negation operator for explicit exclusion. Be aware that using an empty list ```[]``` matches (expands into) exactly nothing. Tests which are to be excluded should be defined in the ```excluded_tests``` section instead.
     177
     178A single test expansion pattern, be it a requirement or a suppressed pattern, gets expanded into a list of **selections** as follows:
     179
     180* Expand each field's pattern (single, any of, or all) to list of allowed values (defined by the ```test_expansion_schema```)
     181
     182* Permute - Recursively enumerate all **selections** across all fields
     183
     184Be aware that if there is more than one pattern expanding into a same selection, the pattern appearing later in the spec JSON will overwrite a previously generated selection. To make sure this is not undetected when generating, set the value of the ```expansion``` field to ```default``` for an expansion appearing earlier and ```override``` for the one appearing later.
     185
     186A **selection** is a single **test instance** (scenario) with explicit values that defines a single test. The scenario is then evaluated by the ```TestCase``` in JS. For the rest of the arranging part, examine ```/common/security-features/tools/generate.py``` to see how the values for the templates are produced.
     187
     188
     189Taking the spec JSON, the generator follows this algorithm:
     190
     191* Expand all ```excluded_tests``` to create a blacklist of selections
     192
     193* For each specification requirement: Expand the ```test_expansion``` pattern into selections and check each against the blacklist, if not marked as suppresed, generate the test resources for the selection
     194
     195
     196### Source Contexts
     197
     198In **`source_context_list_schema`**, we can specify
     199
     200- source contexts from where subresource requests are sent, and
     201- how policies are delivered, by source contexts and/or subresource requests.
     202
     203- `sourceContextList`: an array of `SourceContext` objects, and
     204- `subresourcePolicyDeliveries`: an array of `PolicyDelivery` objects.
     205
     206They have the same object format as described in
     207`common/security-features/resources/common.js` comments, and are directly
     208serialized to generated HTML files and passed to JavaScript test code,
     209except that:
     210
     211- The first entry of `sourceContextList`'s `sourceContextType` should be
     212  always `top`, which represents the top-level generated test HTML.
     213  (This entry is omitted in the JSON passed to JavaScript, but
     214  the policy deliveries specified here are written as e.g.
     215  `<meta>` elements in the generated test HTML or HTTP headers)
     216- Instead of `PolicyDelivery` object (in `sourceContextList` or
     217  `subresourcePolicyDeliveries`), following placeholder strings can be used.
     218
     219The keys of `source_context_list_schema` can be used as the values of
     220`source_context_list` fields, to indicate which source context configuration
     221to be used.
     222
     223### PolicyDelivery placeholders
     224
     225Each test contains
     226
     227- `delivery_key` (derived from the top-level `delivery_key`) and
     228- `delivery_value`, `delivery_type` (derived from `test_expansion`),
     229
     230which represents the **target policy delivery**, the policy delivery to be
     231tested.
     232
     233The following placeholder strings in `source_context_list_schema` can be used:
     234
     235- `"policy"`:
     236    - Replaced with the target policy delivery.
     237    - Can be used to specify where the target policy delivery should be
     238      delivered.
     239- `"policyIfNonNull"`:
     240    - Replaced with the target policy delivery, only if it has non-null value.
     241      If the value is null, then the test file is not generated.
     242- `"anotherPolicy"`:
     243    - Replaced with a `PolicyDelivery` object that has a different value from
     244      the target policy delivery.
     245    - Can be used to specify e.g. a policy that should be overridden by
     246      the target policy delivery.
     247
     248For example, when the target policy delivery is
     249`{deliveryType: "http-rp", key: "referrerPolicy", value: "no-referrer"}`,
     250
     251```json
     252"sourceContextList": [
     253  {
     254    "sourceContextType": "top",
     255    "policyDeliveries": [
     256      "anotherPolicy"
     257    ]
     258  },
     259  {
     260    "sourceContextType": "classic-worker",
     261    "policyDeliveries": [
     262      "policy"
     263    ]
     264  }
     265]
     266```
     267
     268is replaced with
     269
     270```json
     271"sourceContextList": [
     272  {
     273    "sourceContextType": "top",
     274    "policyDeliveries": [
     275      {
     276        "deliveryType": "meta",
     277        "key": "referrerPolicy",
     278        "value": "unsafe-url"
     279      }
     280    ]
     281  },
     282  {
     283    "sourceContextType": "classic-worker",
     284    "policyDeliveries": [
     285      {
     286        "deliveryType": "http-rp",
     287        "key": "referrerPolicy",
     288        "value": "no-referrer"
     289      }
     290    ]
     291  }
     292]
     293```
     294
     295which indicates
     296
     297- The top-level Document has `<meta name="referrer" content="unsafe-url">`.
     298- The classic worker is created with
     299  `Referrer-Policy: no-referrer` HTTP response headers.
     300
     301### `source_context_schema` and `subresource_schema`
     302
     303These represent supported delivery types and subresources
     304for each source context or subresource type. These are used
     305
     306- To filter out test files for unsupported combinations of delivery types,
     307  source contexts and subresources.
     308- To determine what delivery types should be used for `anotherPolicy`
     309  placeholder.
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/security-features/resources/common.sub.js

    r249672 r253683  
    11/**
    2  * @fileoverview Utilities for mixed-content in Web Platform Tests.
     2 * @fileoverview Utilities for mixed-content in web-platform-tests.
    33 * @author burnik@google.com (Kristijan Burnik)
    44 * Disclaimer: Some methods of other authors are annotated in the corresponding
     
    287287  var element = document.createElement(tagName);
    288288
    289   if (doBindEvents)
     289  if (doBindEvents) {
    290290    bindEvents(element);
    291 
     291    if (element.tagName == "IFRAME" && !('srcdoc' in attrs || 'src' in attrs)) {
     292      // If we're loading a frame, ensure we spin the event loop after load to
     293      // paper over the different event timing in Gecko vs Blink/WebKit
     294      // see https://github.com/whatwg/html/issues/4965
     295      element.eventPromise = element.eventPromise.then(() => {
     296        return new Promise(resolve => setTimeout(resolve, 0))
     297      });
     298    }
     299  }
    292300  // We set the attributes after binding to events to catch any
    293301  // event-triggering attribute changes. E.g. form submission.
     
    313321function createRequestViaElement(tagName, attrs, parentNode) {
    314322  return createElement(tagName, attrs, parentNode, true).eventPromise;
    315 }
    316 
    317 /**
    318  * Creates a new empty iframe and appends it to {@code document.body} .
    319  * @param {string} name The name and ID of the new iframe.
    320  * @param {boolean} doBindEvents Whether to bind load and error events.
    321  * @return {DOMElement} The newly created iframe.
    322  */
    323 function createHelperIframe(name, doBindEvents) {
    324   return createElement("iframe",
    325                        {"name": name, "id": name},
    326                        document.body,
    327                        doBindEvents);
    328323}
    329324
     
    395390  requestViaDedicatedWorker        2        Y        Y       Y
    396391  requestViaFetch                  2        Y        Y       -
    397   requestViaForm                   3        -        Y       -
     392  requestViaForm                   2        -        Y       -
    398393  requestViaIframe                 1        Y        Y       -
    399394  requestViaImage                  2        Y        Y       -
     
    584579
    585580/**
    586  * Sets the href attribute on a navigable DOM element and performs a navigation
    587  *     by clicking it. To avoid navigating away from the current execution
    588  *     context, a target attribute is set to point to a new helper iframe.
    589  * @param {DOMElement} navigableElement The navigable DOMElement
    590  * @param {string} url The href for the navigable element.
    591  * @return {Promise} The promise for success/error events.
    592  */
    593 function requestViaNavigable(navigableElement, url) {
    594   var iframe = createHelperIframe(guid(), false);
    595   setAttributes(navigableElement,
    596                 {"href": url,
    597                  "target": iframe.name});
     581 * Creates a navigable element with the name `navigableElementName`
     582 * (<a>, <area>, or <form>) under `parentNode`, and
     583 * performs a navigation by `trigger()` (e.g. clicking <a>).
     584 * To avoid navigating away from the current execution context,
     585 * a target attribute is set to point to a new helper iframe.
     586 * @param {string} navigableElementName
     587 * @param {object} additionalAttributes The attributes of the navigable element.
     588 * @param {DOMElement} parentNode
     589 * @param {function(DOMElement} trigger A callback called after the navigable
     590 * element is inserted and should trigger navigation using the element.
     591 * @return {Promise} The promise for success/error events.
     592 */
     593function requestViaNavigable(navigableElementName, additionalAttributes,
     594                             parentNode, trigger) {
     595  const name = guid();
     596
     597  const iframe =
     598    createElement("iframe", {"name": name, "id": name}, parentNode, false);
     599
     600  const navigable = createElement(
     601      navigableElementName,
     602      Object.assign({"target": name}, additionalAttributes),
     603      parentNode, false);
    598604
    599605  const promise =
     
    604610          return event.data;
    605611        });
    606   navigableElement.click();
     612  trigger(navigable);
    607613  return promise;
    608614}
     
    615621 */
    616622function requestViaAnchor(url, additionalAttributes) {
    617   var a = createElement(
     623  return requestViaNavigable(
    618624      "a",
    619       Object.assign({"innerHTML": "Link to resource"}, additionalAttributes),
    620       document.body);
    621 
    622   return requestViaNavigable(a, url);
     625      Object.assign({"href": url, "innerHTML": "Link to resource"},
     626                    additionalAttributes),
     627      document.body, a => a.click());
    623628}
    624629
     
    630635 */
    631636function requestViaArea(url, additionalAttributes) {
    632   var area = createElement(
     637  // TODO(kristijanburnik): Append to map and add image.
     638  return requestViaNavigable(
    633639      "area",
    634       Object.assign({}, additionalAttributes),
    635       document.body);
    636 
    637   // TODO(kristijanburnik): Append to map and add image.
    638   return requestViaNavigable(area, url);
     640      Object.assign({"href": url}, additionalAttributes),
     641      document.body, area => area.click());
    639642}
    640643
     
    662665 * @return {Promise} The promise for success/error events.
    663666 */
    664 function requestViaForm(url) {
    665   var iframe = createHelperIframe(guid());
    666   var form = createElement("form",
    667                            {"action": url,
    668                             "method": "POST",
    669                             "target": iframe.name},
    670                            document.body);
    671   bindEvents(iframe);
    672   form.submit();
    673 
    674   return iframe.eventPromise;
     667function requestViaForm(url, additionalAttributes) {
     668  return requestViaNavigable(
     669      "form",
     670      Object.assign({"action": url, "method": "POST"}, additionalAttributes),
     671      document.body, form => form.submit());
    675672}
    676673
     
    867864  },
    868865  "form-tag": {
    869     path: "/common/security-features/subresource/empty.py",
     866    path: "/common/security-features/subresource/document.py",
    870867    invoker: requestViaForm,
    871868  },
     
    969966  // These values can evaluate to either empty strings or a ":port" string.
    970967  const httpPort = getNormalizedPort(parseInt("{{ports[http][0]}}", 10));
    971   const httpsPort = getNormalizedPort(parseInt("{{ports[https][0]}}", 10));
     968  const httpsRawPort = parseInt("{{ports[https][0]}}", 10);
     969  const httpsPort = getNormalizedPort(httpsRawPort);
    972970  const wsPort = getNormalizedPort(parseInt("{{ports[ws][0]}}", 10));
    973   const wssPort = getNormalizedPort(parseInt("{{ports[wss][0]}}", 10));
     971  const wssRawPort = parseInt("{{ports[wss][0]}}", 10);
     972  const wssPort = getNormalizedPort(wssRawPort);
    974973
    975974  /**
     
    993992    "cross-wss": wssProtocol + "://" + crossOriginHost + wssPort,
    994993    "cross-ws": wsProtocol + "://" + crossOriginHost + wsPort,
     994
     995    // The following origin types are used for upgrade-insecure-requests tests:
     996    // These rely on some unintuitive cleverness due to WPT's test setup:
     997    // 'Upgrade-Insecure-Requests' does not upgrade the port number,
     998    // so we use URLs in the form `http://[domain]:[https-port]`,
     999    // which will be upgraded to `https://[domain]:[https-port]`.
     1000    // If the upgrade fails, the load will fail, as we don't serve HTTP over
     1001    // the secure port.
     1002    "same-http-downgrade":
     1003        httpProtocol + "://" + sameOriginHost + ":" + httpsRawPort,
     1004    "cross-http-downgrade":
     1005        httpProtocol + "://" + crossOriginHost + ":" + httpsRawPort,
     1006    "same-ws-downgrade":
     1007        wsProtocol + "://" + sameOriginHost + ":" + wssRawPort,
     1008    "cross-ws-downgrade":
     1009        wsProtocol + "://" + crossOriginHost + ":" + wssRawPort,
    9951010  };
    9961011
     
    11011116      invoker: invokeFromIframe,
    11021117    },
     1118    "iframe-blank": { // <iframe></iframe>
     1119      invoker: invokeFromIframe,
     1120    },
    11031121    "worker-classic": {
    11041122      // Classic dedicated worker loaded from same-origin.
     
    11871205        currentSourceContext.policyDeliveries || []));
    11881206
     1207  let iframe;
    11891208  let promise;
    11901209  if (currentSourceContext.sourceContextType === 'srcdoc') {
     
    11921211      .then(r => r.text())
    11931212      .then(srcdoc => {
    1194           return createElement("iframe", {srcdoc: srcdoc}, document.body, true);
     1213          iframe = createElement(
     1214              "iframe", {srcdoc: srcdoc}, document.body, true);
     1215          return iframe.eventPromise;
    11951216        });
    11961217  } else if (currentSourceContext.sourceContextType === 'iframe') {
    1197     promise = Promise.resolve(
    1198         createElement("iframe", {src: frameUrl}, document.body, true));
     1218    iframe = createElement("iframe", {src: frameUrl}, document.body, true);
     1219    promise = iframe.eventPromise;
     1220  } else if (currentSourceContext.sourceContextType === 'iframe-blank') {
     1221    let frameContent;
     1222    promise = fetch(frameUrl)
     1223      .then(r => r.text())
     1224      .then(t => {
     1225          frameContent = t;
     1226          iframe = createElement("iframe", {}, document.body, true);
     1227          return iframe.eventPromise;
     1228        })
     1229      .then(() => {
     1230          // Reinitialize `iframe.eventPromise` with a new promise
     1231          // that catches the load event for the document.write() below.
     1232          bindEvents(iframe);
     1233
     1234          iframe.contentDocument.write(frameContent);
     1235          iframe.contentDocument.close();
     1236          return iframe.eventPromise;
     1237        });
    11991238  }
    12001239
    12011240  return promise
    1202     .then(iframe => {
    1203         return iframe.eventPromise
    1204           .then(() => {
    1205               const promise = bindEvents2(
    1206                   window, "message", iframe, "error", window, "error");
    1207               iframe.contentWindow.postMessage(
    1208                   {subresource: subresource,
    1209                    sourceContextList: sourceContextList.slice(1)},
    1210                   "*");
    1211               return promise;
    1212             })
    1213           .then(event => {
    1214               if (event.data.error)
    1215                 return Promise.reject(event.data.error);
    1216               return event.data;
    1217             });
     1241    .then(() => {
     1242        const promise = bindEvents2(
     1243            window, "message", iframe, "error", window, "error");
     1244        iframe.contentWindow.postMessage(
     1245            {subresource: subresource,
     1246             sourceContextList: sourceContextList.slice(1)},
     1247            "*");
     1248        return promise;
     1249      })
     1250    .then(event => {
     1251        if (event.data.error)
     1252          return Promise.reject(event.data.error);
     1253        return event.data;
    12181254      });
    12191255}
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/security-features/resources/w3c-import.log

    r245004 r253683  
    1515------------------------------------------------------------------------
    1616List of files:
    17 /LayoutTests/imported/w3c/web-platform-tests/common/security-features/resources/common.js
     17/LayoutTests/imported/w3c/web-platform-tests/common/security-features/resources/common.sub.js
     18/LayoutTests/imported/w3c/web-platform-tests/common/security-features/resources/common.sub.js.headers
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/security-features/scope/template/document.html.template

    r245004 r253683  
    33  <head>
    44    %(meta)s
    5     <script src="/common/security-features/resources/common.js"></script>
     5    <script src="/common/security-features/resources/common.sub.js"></script>
    66    <script>
    77    // Receive a message from the parent and start the test.
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/security-features/scope/template/w3c-import.log

    r245004 r253683  
    1616List of files:
    1717/LayoutTests/imported/w3c/web-platform-tests/common/security-features/scope/template/document.html.template
     18/LayoutTests/imported/w3c/web-platform-tests/common/security-features/scope/template/worker.js.template
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/security-features/scope/w3c-import.log

    r245004 r253683  
    1717/LayoutTests/imported/w3c/web-platform-tests/common/security-features/scope/document.py
    1818/LayoutTests/imported/w3c/web-platform-tests/common/security-features/scope/util.py
     19/LayoutTests/imported/w3c/web-platform-tests/common/security-features/scope/worker.py
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/security-features/subresource/subresource.py

    r245004 r253683  
    3333# - When `swap_scheme` or `swap_origin` is True, its scheme/origin is changed
    3434#   to the other one. (http <-> https, ws <-> wss, etc.)
     35# - For `downgrade`, we redirect to a URL that would be successfully loaded
     36#   if and only if upgrade-insecure-request is applied.
    3537# - `query_parameter_to_remove` parameter is removed from query part.
    3638#   Its default is "redirection" to avoid redirect loops.
    37 def create_url(request, swap_scheme = False, swap_origin = False,
    38                query_parameter_to_remove = "redirection"):
     39def create_url(request,
     40               swap_scheme=False,
     41               swap_origin=False,
     42               downgrade=False,
     43               query_parameter_to_remove="redirection"):
    3944    parsed = urlparse.urlsplit(request.url)
    4045    destination_netloc = parsed.netloc
     
    4550        hostname = parsed.netloc.split(':')[0]
    4651        port = request.server.config["ports"][scheme][0]
     52        destination_netloc = ":".join([hostname, str(port)])
     53
     54    if downgrade:
     55        # These rely on some unintuitive cleverness due to WPT's test setup:
     56        # 'Upgrade-Insecure-Requests' does not upgrade the port number,
     57        # so we use URLs in the form `http://[domain]:[https-port]`,
     58        # which will be upgraded to `https://[domain]:[https-port]`.
     59        # If the upgrade fails, the load will fail, as we don't serve HTTP over
     60        # the secure port.
     61        if parsed.scheme == "https":
     62            scheme = "http"
     63        elif parsed.scheme == "wss":
     64            scheme = "ws"
     65        else:
     66            raise ValueError("Downgrade redirection: Invalid scheme '%s'" %
     67                             parsed.scheme)
     68        hostname = parsed.netloc.split(':')[0]
     69        port = request.server.config["ports"][parsed.scheme][0]
    4770        destination_netloc = ":".join([hostname, str(port)])
    4871
     
    7295    if redirection == "no-redirect":
    7396        return False
    74     elif redirection == "keep-scheme-redirect":
     97    elif redirection == "keep-scheme":
    7598        redirect_url = create_url(request, swap_scheme=False)
    76     elif redirection == "swap-scheme-redirect":
     99    elif redirection == "swap-scheme":
    77100        redirect_url = create_url(request, swap_scheme=True)
    78     elif redirection == "keep-origin-redirect":
     101    elif redirection == "downgrade":
     102        redirect_url = create_url(request, downgrade=True)
     103    elif redirection == "keep-origin":
    79104        redirect_url = create_url(request, swap_origin=False)
    80     elif redirection == "swap-origin-redirect":
     105    elif redirection == "swap-origin":
    81106        redirect_url = create_url(request, swap_origin=True)
    82107    else:
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/security-features/tools/generate.py

    r245004 r253683  
    11from __future__ import print_function
    22
     3import argparse
    34import copy
    4 import os, sys, json
     5import json
     6import os
     7import sys
     8
    59import spec_validator
    6 import argparse
    710import util
    811
     
    2932
    3033
    31 def permute_expansion(expansion, artifact_order, selection = {}, artifact_index = 0):
     34def permute_expansion(expansion,
     35                      artifact_order,
     36                      selection={},
     37                      artifact_index=0):
    3238    assert isinstance(artifact_order, list), "artifact_order should be a list"
    3339
     
    4046    for artifact_value in expansion[artifact_key]:
    4147        selection[artifact_key] = artifact_value
    42         for next_selection in permute_expansion(expansion,
    43                                                 artifact_order,
    44                                                 selection,
    45                                                 artifact_index + 1):
     48        for next_selection in permute_expansion(expansion, artifact_order,
     49                                                selection, artifact_index + 1):
    4650            yield next_selection
    4751
    4852
    49 def generate_selection(config, selection, spec, test_html_template_basename):
    50     # TODO: Refactor out this referrer-policy-specific part.
    51     if 'referrer_policy' in spec:
    52       # Oddball: it can be None, so in JS it's null.
    53       selection['referrer_policy'] = spec['referrer_policy']
    54 
    55     test_parameters = json.dumps(selection, indent=2, separators=(',', ':'))
     53# Dumps the test config `selection` into a serialized JSON string.
     54# We omit `name` parameter because it is not used by tests.
     55def dump_test_parameters(selection):
     56    selection = dict(selection)
     57    del selection['name']
     58
     59    return json.dumps(
     60        selection,
     61        indent=2,
     62        separators=(',', ': '),
     63        sort_keys=True,
     64        cls=util.CustomEncoder)
     65
     66
     67def get_test_filename(config, selection):
     68    '''Returns the filname for the main test HTML file'''
     69
     70    selection_for_filename = copy.deepcopy(selection)
     71    # Use 'unset' rather than 'None' in test filenames.
     72    if selection_for_filename['delivery_value'] is None:
     73        selection_for_filename['delivery_value'] = 'unset'
     74
     75    return os.path.join(config.spec_directory,
     76                        config.test_file_path_pattern % selection_for_filename)
     77
     78
     79def handle_deliveries(policy_deliveries):
     80    '''
     81    Generate <meta> elements and HTTP headers for the given list of
     82    PolicyDelivery.
     83    TODO(hiroshige): Merge duplicated code here, scope/document.py, etc.
     84    '''
     85
     86    meta = ''
     87    headers = {}
     88
     89    for delivery in policy_deliveries:
     90        if delivery.value is None:
     91            continue
     92        if delivery.key == 'referrerPolicy':
     93            if delivery.delivery_type == 'meta':
     94                meta += \
     95                    '<meta name="referrer" content="%s">' % delivery.value
     96            elif delivery.delivery_type == 'http-rp':
     97                headers['Referrer-Policy'] = delivery.value
     98                # TODO(kristijanburnik): Limit to WPT origins.
     99                headers['Access-Control-Allow-Origin'] = '*'
     100            else:
     101                raise Exception(
     102                    'Invalid delivery_type: %s' % delivery.delivery_type)
     103        elif delivery.key == 'mixedContent':
     104            assert (delivery.value == 'opt-in')
     105            if delivery.delivery_type == 'meta':
     106                meta += '<meta http-equiv="Content-Security-Policy" ' + \
     107                       'content="block-all-mixed-content">'
     108            elif delivery.delivery_type == 'http-rp':
     109                headers['Content-Security-Policy'] = 'block-all-mixed-content'
     110            else:
     111                raise Exception(
     112                    'Invalid delivery_type: %s' % delivery.delivery_type)
     113        elif delivery.key == 'upgradeInsecureRequests':
     114            # https://w3c.github.io/webappsec-upgrade-insecure-requests/#delivery
     115            assert (delivery.value == 'upgrade')
     116            if delivery.delivery_type == 'meta':
     117                meta += '<meta http-equiv="Content-Security-Policy" ' + \
     118                       'content="upgrade-insecure-requests">'
     119            elif delivery.delivery_type == 'http-rp':
     120                headers[
     121                    'Content-Security-Policy'] = 'upgrade-insecure-requests'
     122            else:
     123                raise Exception(
     124                    'Invalid delivery_type: %s' % delivery.delivery_type)
     125        else:
     126            raise Exception('Invalid delivery_key: %s' % delivery.key)
     127    return {"meta": meta, "headers": headers}
     128
     129
     130def generate_selection(spec_json, config, selection, spec,
     131                       test_html_template_basename):
     132    test_filename = get_test_filename(config, selection)
     133
     134    target_policy_delivery = util.PolicyDelivery(selection['delivery_type'],
     135                                                 selection['delivery_key'],
     136                                                 selection['delivery_value'])
     137    del selection['delivery_type']
     138    del selection['delivery_key']
     139    del selection['delivery_value']
     140
     141    # Parse source context list and policy deliveries of source contexts.
     142    # `util.ShouldSkip()` exceptions are raised if e.g. unsuppported
     143    # combinations of source contexts and policy deliveries are used.
     144    source_context_list_scheme = spec_json['source_context_list_schema'][
     145        selection['source_context_list']]
     146    selection['source_context_list'] = [
     147        util.SourceContext.from_json(source_context, target_policy_delivery,
     148                                     spec_json['source_context_schema'])
     149        for source_context in source_context_list_scheme['sourceContextList']
     150    ]
     151
     152    # Check if the subresource is supported by the innermost source context.
     153    innermost_source_context = selection['source_context_list'][-1]
     154    supported_subresource = spec_json['source_context_schema'][
     155        'supported_subresource'][innermost_source_context.source_context_type]
     156    if supported_subresource != '*':
     157        if selection['subresource'] not in supported_subresource:
     158            raise util.ShouldSkip()
     159
     160    # Parse subresource policy deliveries.
     161    selection[
     162        'subresource_policy_deliveries'] = util.PolicyDelivery.list_from_json(
     163            source_context_list_scheme['subresourcePolicyDeliveries'],
     164            target_policy_delivery, spec_json['subresource_schema']
     165            ['supported_delivery_type'][selection['subresource']])
     166
     167    # We process the top source context below, and do not include it in
     168    # `scenario` field in JavaScript.
     169    top_source_context = selection['source_context_list'].pop(0)
     170    assert (top_source_context.source_context_type == 'top')
     171
    56172    # Adjust the template for the test invoking JS. Indent it to look nice.
    57173    indent = "\n" + " " * 8
    58     test_parameters = test_parameters.replace("\n", indent)
    59 
    60     selection['test_js'] = '''
    61       %s(
    62         %s,
    63         document.querySelector("meta[name=assert]").content,
    64         new SanityChecker()
    65       ).start();
    66       ''' % (config.test_case_name, test_parameters)
     174    selection['scenario'] = dump_test_parameters(selection).replace(
     175        "\n", indent)
    67176
    68177    selection['spec_name'] = spec['name']
    69     selection['test_page_title'] = config.test_page_title_template % spec['title']
     178    selection[
     179        'test_page_title'] = config.test_page_title_template % spec['title']
    70180    selection['spec_description'] = spec['description']
    71181    selection['spec_specification_url'] = spec['specification_url']
     
    74184    selection['spec_json_js'] = config.spec_json_js
    75185
    76     test_filename = os.path.join(config.spec_directory, config.test_file_path_pattern % selection)
    77186    test_headers_filename = test_filename + ".headers"
    78187    test_directory = os.path.dirname(test_filename)
     
    84193                                          test_html_template_basename)
    85194    generated_disclaimer = disclaimer_template \
    86         % {'generating_script_filename': os.path.relpath(__file__,
     195        % {'generating_script_filename': os.path.relpath(sys.argv[0],
    87196                                                         util.test_root_directory),
    88197           'html_template_filename': os.path.relpath(html_template_filename,
     
    91200    # Adjust the template for the test invoking JS. Indent it to look nice.
    92201    selection['generated_disclaimer'] = generated_disclaimer.rstrip()
    93     selection['test_description'] = config.test_description_template % selection
     202    selection[
     203        'test_description'] = config.test_description_template % selection
    94204    selection['test_description'] = \
    95205        selection['test_description'].rstrip().replace("\n", "\n" + " " * 33)
     
    101211        pass
    102212
    103     delivery = config.handleDelivery(selection, spec)
     213    delivery = handle_deliveries(top_source_context.policy_deliveries)
    104214
    105215    if len(delivery['headers']) > 0:
    106216        with open(test_headers_filename, "w") as f:
    107217            for header in delivery['headers']:
    108                 f.write(header)
    109                 f.write('\n')
     218                f.write('%s: %s\n' % (header, delivery['headers'][header]))
    110219
    111220    selection['meta_delivery_method'] = delivery['meta']
     
    124233
    125234    spec_json_js_template = util.get_template('spec_json.js.template')
    126     generated_spec_json_filename = os.path.join(config.spec_directory, "spec_json.js")
    127     util.write_file(generated_spec_json_filename,
    128                spec_json_js_template % {'spec_json': json.dumps(spec_json)})
     235    generated_spec_json_filename = os.path.join(config.spec_directory,
     236                                                "spec_json.js")
     237    util.write_file(
     238        generated_spec_json_filename,
     239        spec_json_js_template % {'spec_json': json.dumps(spec_json)})
    129240
    130241    # Choose a debug/release template depending on the target.
     
    150261
    151262        for expansion_pattern in spec['test_expansion']:
    152             expansion = expand_pattern(expansion_pattern, test_expansion_schema)
     263            expansion = expand_pattern(expansion_pattern,
     264                                       test_expansion_schema)
    153265            for selection in permute_expansion(expansion, artifact_order):
     266                selection['delivery_key'] = spec_json['delivery_key']
    154267                selection_path = config.selection_pattern % selection
    155268                if not selection_path in exclusion_dict:
    156269                    if selection_path in output_dict:
    157270                        if expansion_pattern['expansion'] != 'override':
    158                             print("Error: %s's expansion is default but overrides %s" % (selection['name'], output_dict[selection_path]['name']))
     271                            print(
     272                                "Error: %s's expansion is default but overrides %s"
     273                                % (selection['name'],
     274                                   output_dict[selection_path]['name']))
    159275                            sys.exit(1)
    160276                    output_dict[selection_path] = copy.deepcopy(selection)
     
    164280        for selection_path in output_dict:
    165281            selection = output_dict[selection_path]
    166             generate_selection(config,
    167                                selection,
    168                                spec,
    169                                html_template)
     282            try:
     283                generate_selection(spec_json, config, selection, spec,
     284                                   html_template)
     285            except util.ShouldSkip:
     286                continue
    170287
    171288
    172289def main(config):
    173     parser = argparse.ArgumentParser(description='Test suite generator utility')
    174     parser.add_argument('-t', '--target', type = str,
    175         choices = ("release", "debug"), default = "release",
    176         help = 'Sets the appropriate template for generating tests')
    177     parser.add_argument('-s', '--spec', type = str, default = None,
    178         help = 'Specify a file used for describing and generating the tests')
     290    parser = argparse.ArgumentParser(
     291        description='Test suite generator utility')
     292    parser.add_argument(
     293        '-t',
     294        '--target',
     295        type=str,
     296        choices=("release", "debug"),
     297        default="release",
     298        help='Sets the appropriate template for generating tests')
     299    parser.add_argument(
     300        '-s',
     301        '--spec',
     302        type=str,
     303        default=None,
     304        help='Specify a file used for describing and generating the tests')
    179305    # TODO(kristijanburnik): Add option for the spec_json file.
    180306    args = parser.parse_args()
    181307
    182308    if args.spec:
    183       config.spec_directory = args.spec
     309        config.spec_directory = args.spec
    184310
    185311    spec_filename = os.path.join(config.spec_directory, "spec.src.json")
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/security-features/tools/template/test.debug.html.template

    r245004 r253683  
    1111    <script src="/resources/testharness.js"></script>
    1212    <script src="/resources/testharnessreport.js"></script>
    13     <script src="/common/security-features/resources/common.js"></script>
     13    <script src="/common/security-features/resources/common.sub.js"></script>
    1414    <!-- The original specification JSON for validating the scenario. -->
    1515    <script src="%(spec_json_js)s"></script>
     
    1919  </head>
    2020  <body>
    21     <script>%(test_js)s</script>
     21    <script>
     22      TestCase(
     23        %(scenario)s,
     24        document.querySelector("meta[name=assert]").content,
     25        new SanityChecker()
     26      ).start();
     27      </script>
    2228    <div id="log"></div>
    2329  </body>
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/security-features/tools/template/test.release.html.template

    r245004 r253683  
    1111    <script src="/resources/testharness.js"></script>
    1212    <script src="/resources/testharnessreport.js"></script>
    13     <script src="/common/security-features/resources/common.js"></script>
     13    <script src="/common/security-features/resources/common.sub.js"></script>
    1414    <script src="%(helper_js)s"></script>
    1515  </head>
    1616  <body>
    17     <script>%(test_js)s</script>
     17    <script>
     18      TestCase(
     19        %(scenario)s,
     20        document.querySelector("meta[name=assert]").content,
     21        new SanityChecker()
     22      ).start();
     23      </script>
    1824    <div id="log"></div>
    1925  </body>
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/security-features/tools/util.py

    r245004 r253683  
    44
    55script_directory = os.path.dirname(os.path.abspath(__file__))
    6 template_directory = os.path.abspath(os.path.join(script_directory,
    7                                                   'template'))
    8 test_root_directory = os.path.abspath(os.path.join(script_directory,
    9                                                   '..', '..', '..'))
     6template_directory = os.path.abspath(
     7    os.path.join(script_directory, 'template'))
     8test_root_directory = os.path.abspath(
     9    os.path.join(script_directory, '..', '..', '..'))
    1010
    1111
     
    2121
    2222def read_nth_line(fp, line_number):
    23   fp.seek(0)
    24   for i, line in enumerate(fp):
    25     if (i + 1) == line_number:
    26       return line
     23    fp.seek(0)
     24    for i, line in enumerate(fp):
     25        if (i + 1) == line_number:
     26            return line
    2727
    2828
     
    3131    with open(path_to_spec, "r") as f:
    3232        try:
    33           return json.load(f)
     33            return json.load(f)
    3434        except ValueError as ex:
    35           print(ex.message)
    36           match = re_error_location.search(ex.message)
    37           if match:
    38             line_number, column = int(match.group(1)), int(match.group(2))
    39             print(read_nth_line(f, line_number).rstrip())
    40             print(" " * (column - 1) + "^")
    41           sys.exit(1)
     35            print(ex.message)
     36            match = re_error_location.search(ex.message)
     37            if match:
     38                line_number, column = int(match.group(1)), int(match.group(2))
     39                print(read_nth_line(f, line_number).rstrip())
     40                print(" " * (column - 1) + "^")
     41            sys.exit(1)
     42
     43
     44class ShouldSkip(Exception):
     45    '''
     46    Raised when the given combination of subresource type, source context type,
     47    delivery type etc. are not supported and we should skip that configuration.
     48    ShouldSkip is expected in normal generator execution (and thus subsequent
     49    generation continues), as we first enumerate a broad range of configurations
     50    first, and later raise ShouldSkip to filter out unsupported combinations.
     51
     52    ShouldSkip is distinguished from other general errors that cause immediate
     53    termination of the generator and require fix.
     54    '''
     55    def __init__(self):
     56        pass
     57
     58
     59class PolicyDelivery(object):
     60    '''
     61    See `@typedef PolicyDelivery` comments in
     62    `common/security-features/resources/common.sub.js`.
     63    '''
     64
     65    def __init__(self, delivery_type, key, value):
     66        self.delivery_type = delivery_type
     67        self.key = key
     68        self.value = value
     69
     70    @classmethod
     71    def list_from_json(cls, list, target_policy_delivery,
     72                       supported_delivery_types):
     73        # type: (dict, PolicyDelivery, typing.List[str]) -> typing.List[PolicyDelivery]
     74        '''
     75        Parses a JSON object `list` that represents a list of `PolicyDelivery`
     76        and returns a list of `PolicyDelivery`, plus supporting placeholders
     77        (see `from_json()` comments below or
     78        `common/security-features/README.md`).
     79
     80        Can raise `ShouldSkip`.
     81        '''
     82        if list is None:
     83            return []
     84
     85        out = []
     86        for obj in list:
     87            policy_delivery = PolicyDelivery.from_json(
     88                obj, target_policy_delivery, supported_delivery_types)
     89            # Drop entries with null values.
     90            if policy_delivery.value is None:
     91                continue
     92            out.append(policy_delivery)
     93        return out
     94
     95    @classmethod
     96    def from_json(cls, obj, target_policy_delivery, supported_delivery_types):
     97        # type: (dict, PolicyDelivery, typing.List[str]) -> PolicyDelivery
     98        '''
     99           Parses a JSON object `obj` and returns a `PolicyDelivery` object.
     100           In addition to dicts (in the same format as to_json() outputs),
     101           this method accepts the following placeholders:
     102             "policy":
     103               `target_policy_delivery`
     104             "policyIfNonNull":
     105               `target_policy_delivery` if its value is not None.
     106             "anotherPolicy":
     107               A PolicyDelivery that has the same key as
     108               `target_policy_delivery` but a different value.
     109               The delivery type is selected from `supported_delivery_types`.
     110
     111        Can raise `ShouldSkip`.
     112        '''
     113
     114        if obj == "policy":
     115            policy_delivery = target_policy_delivery
     116        elif obj == "nonNullPolicy":
     117            if target_policy_delivery.value is None:
     118                raise ShouldSkip()
     119            policy_delivery = target_policy_delivery
     120        elif obj == "anotherPolicy":
     121            policy_delivery = target_policy_delivery.get_another_policy(
     122                supported_delivery_types[0])
     123        elif type(obj) == dict:
     124            policy_delivery = PolicyDelivery(obj['deliveryType'], obj['key'],
     125                                             obj['value'])
     126        else:
     127            raise Exception('policy delivery is invalid: ' + obj)
     128
     129        # Omit unsupported combinations of source contexts and delivery type.
     130        if policy_delivery.delivery_type not in supported_delivery_types:
     131            raise ShouldSkip()
     132
     133        return policy_delivery
     134
     135    def to_json(self):
     136        # type: () -> dict
     137        return {
     138            "deliveryType": self.delivery_type,
     139            "key": self.key,
     140            "value": self.value
     141        }
     142
     143    def get_another_policy(self, delivery_type):
     144        # type: (str) -> PolicyDelivery
     145        if self.key == 'referrerPolicy':
     146            if self.value == 'no-referrer':
     147                return PolicyDelivery(delivery_type, self.key, 'unsafe-url')
     148            else:
     149                return PolicyDelivery(delivery_type, self.key, 'no-referrer')
     150        else:
     151            raise Exception('delivery key is invalid: ' + self.key)
     152
     153
     154class SourceContext(object):
     155    def __init__(self, source_context_type, policy_deliveries):
     156        # type: (unicode, typing.List[PolicyDelivery]) -> None
     157        self.source_context_type = source_context_type
     158        self.policy_deliveries = policy_deliveries
     159
     160    @classmethod
     161    def from_json(cls, obj, target_policy_delivery, source_context_schema):
     162        '''
     163        Parses a JSON object `obj` and returns a `SourceContext` object.
     164
     165        `target_policy_delivery` and `source_context_schema` are used for
     166        policy delivery placeholders and filtering out unsupported
     167        delivery types.
     168
     169        Can raise `ShouldSkip`.
     170        '''
     171        source_context_type = obj.get('sourceContextType')
     172        policy_deliveries = PolicyDelivery.list_from_json(
     173            obj.get('policyDeliveries'), target_policy_delivery,
     174            source_context_schema['supported_delivery_type']
     175            [source_context_type])
     176        return SourceContext(source_context_type, policy_deliveries)
     177
     178    def to_json(self):
     179        return {
     180            "sourceContextType": self.source_context_type,
     181            "policyDeliveries": [x.to_json() for x in self.policy_deliveries]
     182        }
     183
     184
     185class CustomEncoder(json.JSONEncoder):
     186    '''
     187    Used to dump dicts containing `SourceContext`/`PolicyDelivery` into JSON.
     188    '''
     189    def default(self, obj):
     190        if isinstance(obj, SourceContext):
     191            return obj.to_json()
     192        if isinstance(obj, PolicyDelivery):
     193            return obj.to_json()
     194        return json.JSONEncoder.default(self, obj)
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/security-features/tools/w3c-import.log

    r245004 r253683  
    1515------------------------------------------------------------------------
    1616List of files:
     17/LayoutTests/imported/w3c/web-platform-tests/common/security-features/tools/format_spec_src_json.py
    1718/LayoutTests/imported/w3c/web-platform-tests/common/security-features/tools/generate.py
     19/LayoutTests/imported/w3c/web-platform-tests/common/security-features/tools/spec_validator.py
    1820/LayoutTests/imported/w3c/web-platform-tests/common/security-features/tools/util.py
  • trunk/LayoutTests/imported/w3c/web-platform-tests/common/w3c-import.log

    r245004 r253683  
    2020/LayoutTests/imported/w3c/web-platform-tests/common/PrefixedPostMessage.js
    2121/LayoutTests/imported/w3c/web-platform-tests/common/PrefixedPostMessage.js.headers
     22/LayoutTests/imported/w3c/web-platform-tests/common/README.md
    2223/LayoutTests/imported/w3c/web-platform-tests/common/arrays.js
    2324/LayoutTests/imported/w3c/web-platform-tests/common/blank.html
    24 /LayoutTests/imported/w3c/web-platform-tests/common/canvas-frame.css
    25 /LayoutTests/imported/w3c/web-platform-tests/common/canvas-frame.css.headers
    26 /LayoutTests/imported/w3c/web-platform-tests/common/canvas-index.css
    27 /LayoutTests/imported/w3c/web-platform-tests/common/canvas-index.css.headers
    28 /LayoutTests/imported/w3c/web-platform-tests/common/canvas-spec.css
    29 /LayoutTests/imported/w3c/web-platform-tests/common/canvas-spec.css.headers
    30 /LayoutTests/imported/w3c/web-platform-tests/common/canvas-tests.css
    31 /LayoutTests/imported/w3c/web-platform-tests/common/canvas-tests.css.headers
    32 /LayoutTests/imported/w3c/web-platform-tests/common/canvas-tests.js
    33 /LayoutTests/imported/w3c/web-platform-tests/common/canvas-tests.js.headers
    34 /LayoutTests/imported/w3c/web-platform-tests/common/css-paint-tests.js.headers
    35 /LayoutTests/imported/w3c/web-platform-tests/common/css-red.txt
    3625/LayoutTests/imported/w3c/web-platform-tests/common/domain-setter.sub.html
    3726/LayoutTests/imported/w3c/web-platform-tests/common/dummy.xhtml
    3827/LayoutTests/imported/w3c/web-platform-tests/common/dummy.xml
    3928/LayoutTests/imported/w3c/web-platform-tests/common/echo.py
    40 /LayoutTests/imported/w3c/web-platform-tests/common/entities.json
    41 /LayoutTests/imported/w3c/web-platform-tests/common/form-submission.py
    4229/LayoutTests/imported/w3c/web-platform-tests/common/get-host-info.sub.js
    4330/LayoutTests/imported/w3c/web-platform-tests/common/get-host-info.sub.js.headers
    4431/LayoutTests/imported/w3c/web-platform-tests/common/media.js
    4532/LayoutTests/imported/w3c/web-platform-tests/common/media.js.headers
    46 /LayoutTests/imported/w3c/web-platform-tests/common/namespaces.js
    4733/LayoutTests/imported/w3c/web-platform-tests/common/object-association.js
    4834/LayoutTests/imported/w3c/web-platform-tests/common/object-association.js.headers
     
    5339/LayoutTests/imported/w3c/web-platform-tests/common/reftest-wait.js
    5440/LayoutTests/imported/w3c/web-platform-tests/common/reftest-wait.js.headers
    55 /LayoutTests/imported/w3c/web-platform-tests/common/sleep.py
    5641/LayoutTests/imported/w3c/web-platform-tests/common/slow.py
    5742/LayoutTests/imported/w3c/web-platform-tests/common/stringifiers.js
     
    6550/LayoutTests/imported/w3c/web-platform-tests/common/utils.js.headers
    6651/LayoutTests/imported/w3c/web-platform-tests/common/worklet-reftest.js
     52/LayoutTests/imported/w3c/web-platform-tests/common/worklet-reftest.js.headers
  • trunk/LayoutTests/imported/w3c/web-platform-tests/html/semantics/document-metadata/the-style-element/style-error-01-expected.txt

    r199225 r253683  
    1 CONSOLE MESSAGE: Did not parse stylesheet at 'http://localhost:8800/common/css-red.txt' because non CSS MIME types are not allowed in strict mode.
    21
    3 Harness Error (TIMEOUT), message = null
     2PASS Should get an error event for a text/plain response.
    43
    5 TIMEOUT Should get an error event for a text/plain response. Test timed out
    6 
Note: See TracChangeset for help on using the changeset viewer.