Feature Policy

W3C First Public Working Draft,

This version:
https://www.w3.org/TR/2019/WD-feature-policy-1-20190416/
Latest published version:
https://www.w3.org/TR/feature-policy-1/
Editor's Draft:
https://w3c.github.io/webappsec-feature-policy/
Feedback:
public-webappsec@w3.org with subject line “[feature-policy] … message topic …” (archives)
Issue Tracking:
GitHub
Inline In Spec
Editor:
(Google)

Abstract

This specification defines a mechanism that allows developers to selectively enable and disable use of various browser features and APIs.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

This document was published by the Web Application Security Working Group as a Working Draft. This document is intended to become a W3C Recommendation.

The (archived) public mailing list public-webappsec@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “feature-policy” in the subject, preferably like this: “[feature-policy] …summary of comment…

This document is a First Public Working Draft.

Publication as a First Public Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by the Web Application Security Working Group.

This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 1 March 2019 W3C Process Document.

1. Introduction

The web-platform provides an ever-expanding set of features and APIs, offering richer functionality, better developer ergonomics, and improved performance. However, a missing piece is the ability for the developer to selectively enable, disable, or modify the behavior of some of these browser features and APIs within their application:

  1. The developer may want to selectively disable access to certain browser features and APIs to "lock down" their application, as a security or performance precaution, to prevent own and third-party content executing within their application from introducing unwanted or unexpected behaviors within their application.
  2. The developer may want to selectively enable access to certain browser features and APIs which may be disabled by default - e.g. some features may be disabled by default in embedded context unless explicitly enabled; some features may be subject to other policy requirements.
  3. The developer may want to use the policy to assert a promise to a client or an embedder about the use—or lack of thereof—of certain features and APIs. For example, to enable certain types of "fast path" optimizations in the browser, or to assert a promise about conformance with some requirements set by other embedders - e.g. various social networks, search engines, and so on.

This specification defines a feature policy mechanism that addresses the above use cases.

2. Examples

SecureCorp Inc. wants to disable use of Fullscreen and Geolocation APIs within their application. It can do so by delivering the following HTTP response header to define a feature policy:

Feature-Policy: fullscreen 'none'; geolocation 'none'

By specifying the "'none'"keyword for the origin list, the specified features will be disabled for all browsing contexts, regardless of their origin.

SecureCorp Inc. wants to disable use of Geolocation API within all browsing contexts except for its own origin and those whose origin is "https://example.com". It can do so by delivering the following HTTP response header to define a feature policy:

Feature-Policy: geolocation 'self' https://example.com

The allowlist is a list of one or more origins, which can include the application’s origin, optionally with the keyword "'self'", and any third-party origin.

SecureCorp Inc. is hosting an application on "https://example.com" and wants to disable camera and microphone input on its own origin but enable it for a specific embedee ("https://other.com"). It can do so by delivering the following HTTP response header to define a feature policy:

Feature-Policy: camera https://other.com; microphone https://other.com

Some features are disabled by default in embedded contexts. The policy allows the application to selectively enable such features for specified origins.

FastCorp Inc. wants to disable geolocation for all cross-origin child frames, except for a specific iframe. It can do so by delivering the following HTTP response header to define a feature policy:

Feature-Policy: geolocation 'self'

and including an "allow" attribute on the iframe element:

<iframe src="https://other.com/map" allow="geolocation"></iframe>

Iframe attributes can selectively enable features in certain frames, and not in others, even if those contain documents from the same origin.

[HTML5] defines a sandbox attribute for iframe elements that allows developers to reduce the risk of including potentially untrusted content by imposing restrictions on content’s abilities - e.g. prevent it from submitting forms, running scripts and plugins, and more. The sandbox directive defined by [CSP2] extends this capability to any resource, framed or not, to ask for the same set of restrictions - e.g. via an HTTP response header (Content-Security-Policy: sandbox). These mechanisms enable the developer to:

However, there are several limitations to the above mechanism: the developer cannot automatically apply a policy across all contexts, which makes it hard or impossible to enforce consistently in some cases (e.g. due to third-party content injecting frames, which the developer does not control); there is no mechanism to selectively enable features that may be off by default; the sandbox mechanism automatically disables all sandbox features, and requires the developer to opt back in to each of them, so it is impossible to extend the set of sandbox features without significant compatibility risk.

Feature Policy is intended to be used in combination with the sandbox mechanism (i.e. it does not duplicate feature controls already covered by sandbox), and provides an extensible mechanism that addresses the above limitations.

4. Framework

4.1. Policy-controlled Features

A policy-controlled feature is an API or behaviour which can be enabled or disabled in a document by referring to it in a feature policy.

For brevity, policy-controlled features will often be referred to in this document simply as "Features". Unless otherwise indicated, the term "feature" refers to policy-controlled features. Other specifications, defining such features, should use the longer term to avoid any ambiguity.
This spec currently only deals with features defined in Documents. We should figure out how to word this to include the possibility of features and feature policies in Workers and Worklets as well.

Policy-controlled features are identified by tokens, which are character strings used in policy directives.

Each policy-controlled feature has a default allowlist, which defines whether that feature is available in documents in top-level browsing contexts, and how access to that feature is inherited in nested browsing contexts.

A user agent has a set of supported features, which is the set of features which it allows to be controlled through policies. User agents are not required to support every feature.

The policy-controlled features themselves are not themselves part of this framework. A non-normative list of currently-defined features is maintained as a companion document alongside this specification.

4.2. Policies

A feature policy is a struct with the following items:

An empty feature policy is a feature policy that has an inherited policy which contains "Enabled" for every supported feature, and a declared policy which is an empty map.

4.3. Inherited policies

An inherited policy is an ordered map from features to either "Enabled" or "Disabled".

The inherited policy for a feature feature is the value in the inherited policy whose key is feature. After a feature policy has been initialized, its inherited policy will contain a value for each supported feature.

Each document in a frame tree inherits a set of policies from its parent frame, or in the case of the top-level document, from the defined defaults for each policy-controlled feature. This inherited policy determines the initial state ("Enabled" or "Disabled") of each feature, and whether it can be controlled by a declared policy in the document.

In a Document in a top-level browsing context, the inherited policy is based on defined defaults for each feature.

In a Document in a nested browsing context, the inherited policy is based on the parent document’s feature policy, as well as the nested browsing context's container policy.

4.4. Declared policies

A declared policy is an ordered map from features to allowlists.

4.5. Header policies

A header policy is a list of policy directives delivered via an HTTP header with a document. This forms the document’s feature policy’s declared policy.

4.6. Container policies

In addition to the header policy, each nested browsing context has a container policy, which is a policy directive, which may be empty. The container policy can set by attributes on the browsing context container.

The container policy for a nested browsing context influences the inherited policy of any document loaded into that context. (See §9.8 Define an inherited policy for feature in document)

Currently, the container policy cannot be set directly, but is indirectly set by iframe "allowfullscreen", "allowpaymentrequest", "and allow" attributes. Future revisions to this spec may introduce a mechanism to explicitly declare the full container policy.

4.7. Policy directives

A policy directive is an ordered map, mapping policy-controlled features to corresponding allowlists of origins.

A policy directive is represented in HTTP headers and HTML attributes as its ASCII serialization.

4.8. Allowlists

A feature policy allowlist is conceptually a set of origins. An allowlist may be either:

The keywords 'self', 'src', and 'none' can appear in the text representation of allowlists in headers and attribute strings. These keywords are always interpreted in context during parsing, and only the origins which they refer to are stored in the allowlist. The keywords themselves are not part of the allowlist.

To determine whether an allowlist matches an origin origin, run these steps:

  1. If the allowlist is the special value *, then return true.
  2. Otherwise, for each item in the allowlist:
    1. If item is same origin-domain with origin, then return true.
  3. return false.

4.9. Default Allowlists

Every policy-controlled feature has a default allowlist. The default allowlist determines whether the feature is allowed in a document with no declared policy in a top-level browsing context, and also whether access to the feature is automatically delegated to documents in nested browsing contexts.

The default allowlist for a feature is one of these values:

*
The feature is allowed in documents in top-level browsing contexts by default, and when allowed, is allowed by default to documents in nested browsing contexts.
'self'
The feature is allowed in documents in top-level browsing contexts by default, and when allowed, is allowed by default to same-origin domain documents in nested browsing contexts, but is disallowed by default in cross-origin documents in nested browsing contexts.
'none'
The feature is disallowed in documents in top-level browsing contexts by default, and is also disallowed by default to documents in nested browsing contexts.

5. Feature Policy Serialization

5.1. ASCII serialization

Policy Directives are represented in HTTP headers and in HTML attributes as ASCII text.

serialized-feature-policy = serialized-policy-directive *(";" serialized-policy-directive)
serialized-policy-directive = feature-identifier RWS allow-list
feature-identifier = 1*( ALPHA / DIGIT / "-")
allow-list = allow-list-value *(RWS allow-list-value)
allow-list-value = serialized-origin / "*" / "'self'" / "'src'" / "'none'"

serialized-origin is the serialization of an origin. However, the code points U+0027 ('), U+0021 (*), U+002C (,) and U+003B (;) MUST NOT appear in the serialization. If they are required, they must be percent-encoded as "%27", "%2A", "%2C" or "%3B", respectively.

The string "'self'" may be used as an origin in an allowlist. When it is used in this way, it will refer to the origin of the document which contains the feature policy.

6. Delivery

6.1. Feature-Policy HTTP Header Field

The `Feature-Policy` HTTP header field can be used in the response (server to client) to communicate the feature policy that should be enforced by the client.

The header’s value is the §5.1 ASCII serialization of one or more policy directives:.

FeaturePolicy = serialized-feature-policy *("," serialized-feature-policy)

6.2. The allow attribute of the iframe element

iframe elements have an "allow" attribute, which contains an ASCII-serialized policy directive.

The allowlist for the features named in the attribute may be empty; in that case, the default value for the allowlist is 'src', which represents the origin of the URL in the iframe’s src attribute.

When not empty, the "allow" attribute will result in adding an allowlist for each recognized feature to the nested browsing context's container policy, when it is constructed.

6.3. Additional attributes to support legacy features

Some features controlled by Feature Policy have existing iframe attributes defined. This specification redefines these attributes to act as declared policies for the iframe element.

6.3.1. allowfullscreen

The "allowfullscreen" iframe attribute controls access to requestFullscreen().

If the iframe element has an "allow" attribute whose value contains the token "fullscreen", then the "allowfullscreen" attribute must have no effect.

Otherwise, the presence of an "allowfullscreen" attribute on an iframe will result in adding an allowlist of * for the "fullscreen" feature to the nested browsing context's container policy, when it is constructed.

This is different from the behaviour of <iframe allow="fullscreen">, and is for compatibility with existing uses of allowfullscreen. If allow="fullscreen" and allowfullscreen are both present on an iframe element, then the more restrictive allowlist of allow="fullscreen" will be used.

6.3.2. allowpaymentrequest

The "allowpaymentrequest" iframe attribute controls access to PaymentRequest.

If the iframe element has an "allow" attribute whose value contains the token "payment", then the "allowpaymentrequest" attribute must have no effect.

Otherwise, the presence of an "allowpaymentrequest" attribute on an iframe will result in adding an allowlist of * for the "payment" feature to the nested browsing context's container policy, when it is constructed.

This is different from the behaviour of <iframe allow="payment">, and is for compatibility with existing uses of allowpaymentrequest. If allow="payment" and allowpaymentrequest are both present on an iframe element, then the more restrictive allowlist of allow="payment" will be used.

7. Policy Introspection from Scripts

7.1. Overview

The current policy which is in effect in a document can be observed by scripts. This can be used to make decisions, for instance, about what user interface to display, in cases where it is not possible to determine otherwise whether a feature is enabled or not. (Some features may not have any observable failure mode, or may have unwanted side effects to feature detection.)

Documents and iframes both provide a FeaturePolicy object which can be used to inspect the feature policies which apply to them.

7.1.1. Document policies

To retreive the currently effective policy, use document.featurePolicy. This returns a FeaturePolicy object, which can be used to:

  • query the state (allowed or denied) in the current document for a given feature,

  • get a list of all available features (allowed or not) in the current document,

  • get a list of all allowed features in the current document, or

  • get the allowlist for a given feature in the current document.

<!doctype html>
<script>
 const policy = document.featurePolicy;

 // This will be true if this document can use WebUSB.
 const can_use_usb = policy.allowsFeature('usb');

 // True if a new frame at https://example.com will be allowed to use WebVR.
 if (policy.allowsFeature('vr', 'https://example.com')) {
   // Show UI to create frame at https://example.com.
 } else {
   // Show an alternative UI.
 }

 // Get the list of origins which are allowed to request payment. The result
 // will be a list of explicit origins, or the single element ['*'] if all
 // origins are allowed.
 const allowed_payment_origins = policy.getAllowlistForFeature('payment');

 // Get the list of all features supported in this document (even those
 // which are not allowed). The result will be an array of strings, each
 // representing a feature.
 const all_features = policy.features();
 if (all_features.includes('geolocation')) {
   // Append a child frame to a third-party map service.
 }
</script>

7.1.2. Frame policies

It is also possible to inspect the policy on an iframe element, from the document which contains it. The policy object in this case represents the observable policy for the frame, which depends only on the current document and the attributes of the iframe element. It does not reveal whether a feature is actually currently allowed in the frame, as the document in the frame may have applied its own policy via an HTTP header, or may have navigated away from its initial location to a new origin. Revealing the effective policy in the nested browsing context in that case could leak information about the behaviour of a cross-origin document.

<!doctype html>
<iframe id="frame" allow="fullscreen; vr"></iframe>
<script>
 const iframe_element = document.getElementById("frame");
 const iframe_policy = iframe_element.featurePolicy;

 // True if the framed document will be allowed to use WebVR
 if (iframe_policy.allowsFeature('vr')) {
  // display vr controls
 }
</script>

The observable policy on an iframe element is independent of any actual content loaded into the frame (to avoid cross-origin information leakage,) or even whether it is in a document tree.

<!doctype html>
<!-- this frame should not be allowed to use fullscreen when the document
    in its src attribute is loaded in it -->
<iframe id="frame" allow="fullscreen https://example.com" src="https://example.net/" ></iframe>
<script>
 const iframe_element = document.getElementById("frame");
 const iframe_policy = iframe_element.featurePolicy;
 // This will be false, as the URL listed in the src attribute is not allowed
 // by policy to use fullscreen.
 const is_fullscreen_allowed_in_frame = iframe_policy.allowsFeature('fullscreen');

 const new_frame = document.createElement('iframe');
 new_frame.allow = 'syncxhr';
 // This will be true, as the iframe is allowed to use syncxhr at whatever URL is
 // mentioned in its src attribute, even though that attribute is not yet set.
 const is_syncxhr_allowed = new_frame.featurePolicy.allowsFeature('syncxhr');
</script>

7.2. The featurePolicy object

[NoInterfaceObject]
interface FeaturePolicy {
  boolean allowsFeature(DOMString feature, optional DOMString origin);
  sequence<DOMString> features();
  sequence<DOMString> allowedFeatures();
  sequence<DOMString> getAllowlistForFeature(DOMString feature);
};

partial interface Document {
    [SameObject] readonly attribute FeaturePolicy featurePolicy;
};

partial interface HTMLIFrameElement {
    [SameObject] readonly attribute FeaturePolicy featurePolicy;
};

A FeaturePolicy object has an associated node, which is a Node. The associated node is set when the FeaturePolicy object is created.

A FeaturePolicy object has a default origin, which is an origin, whose value depends on the state of the FeaturePolicy object’s associated node:

origin. declared origin.

Each Document has a policy object, which is a FeaturePolicy instance whose associated node is that Document.

A Document's featurePolicy IDL attribute, on getting, must return the Document's policy object.

Each iframe element has a policy object, which is a FeaturePolicy instance whose associated node is that element.

An iframe's featurePolicy IDL attribute, on getting, must return the iframe's policy object.

The allowsFeature(feature, origin) method must run the following steps:

  1. If origin is omitted, set origin to this FeaturePolicy object’s default origin.

  2. Let policy be the observable policy for this FeaturePolicy object’s associated node.

  3. If feature is allowed by policy for origin, return true.

  4. Otherwise, return false.

The features() method must run the following steps:

  1. Set result to an empty ordered set.

  2. For each supported feature feature:

    1. Append feature to result.

  3. return result

The allowedFeatures() method must run the following steps:

  1. Set result to an empty ordered set.

  2. Let origin be this FeaturePolicy object’s default origin.

  3. Let policy be the observable policy for this FeaturePolicy object’s associated node.

  4. For each supported feature feature:

    1. If feature is allowed by policy for origin, append feature to result.

  5. return result

The getAllowlistForFeature(feature) method must run the following steps:

  1. Set result to an empty list

  2. Let origin be this FeaturePolicy object’s default origin.

  3. Let policy be the observable policy for this FeaturePolicy object’s associated node.

  4. If feature is not allowed in policy for origin, return result

  5. Let allowlist be policy’s declared policy[feature]

  6. If allowlist is the special value *, append "*" to result

  7. Otherwise, for each origin in allowlist:

    1. Append the serialization of origin to result

  8. Return result.

The observable policy for any Node is a feature policy, which contains the information about the policy in the browsing context represented by that Node which is visible from the current browsing context.

To get the observable policy for a Document document, return document’s feature policy.

To get the observable policy for an Element node, run the following steps:

  1. Let inherited policy be a new ordered map.

  2. Let declared policy be a new ordered map.

  3. For each supported feature feature:

    1. Let isInherited be the result of running §9.9 Define an inherited policy for feature in container at origin on feature, node and node’s declared origin.

    2. Set inherited policy[feature] to isInherited.

  4. Return a new feature policy with inherited policy inherited policy and declared policy declared policy.

To get the declared origin for an Element node, run the following steps:

  1. If node’s node document’s sandboxed origin browsing context flag is set, then return a unique opaque origin.

  2. If node’s sandbox attribute is set, and does not contain the allow-same-origin keyword, then return a unique opaque origin.

  3. If node’s srcdoc attribute is set, then return node’s node document’s origin.

  4. If node’s src attribute is set:

    1. Let url be the result of parsing node’s src attribute, relative to node’s node document.

    2. If url is not failure, return url’s origin.

  5. Return node’s node document’s origin.

The declared origin concept is intended to represent the origin of the document which the embedding page intends to load into a frame. This means, for instance, that if the browser does not support the sandbox or srcdoc attributes, it should not take those attributes into account when computing the declared origin.

8. Reporting

Feature policy violation reports indicate that some behavior of the Document has violated a feature policy. It is up to each individual feature policy to define/determine when a violation of that policy has occurred.

Feature policy violation reports have the report type "feature-policy-violation".

Feature policy violation reports are visible to ReportingObservers.

interface FeaturePolicyViolationReportBody : ReportBody {
  readonly attribute DOMString featureId;
  readonly attribute DOMString? sourceFile;
  readonly attribute long? lineNumber;
  readonly attribute long? columnNumber;
  readonly attribute DOMString disposition;
};

A feature policy violation report’s body, represented in JavaScript by FeaturePolicyViolationReportBody, contains the following fields:

9. Algorithms

9.1. Process response policy

Given a response (response) and an origin (origin), this algorithm returns a declared feature policy.

  1. Abort these steps if the response’s header list does not contain a header whose name is "Feature-Policy".
  2. Let header be the concatenation of the values of all header fields in response’s header list whose name is "Feature-Policy", separated by U+002C (,) (according to [RFC7230, 3.2.2]).
  3. Let feature policy be the result of executing §9.2 Parse header from value and origin on header and origin.
  4. Return feature policy.

9.2. Parse header from value and origin

Given a string (value) and an origin (origin) this algorithm will return a declared feature policy.

  1. Let policy be an empty ordered map.
  2. For each element returned by splitting value on commas:
    1. Let directive be the result of executing §9.3 Parse policy directive on element with container origin set to origin.
    2. Run §9.4 Merge directive with declared policy on directive and policy.
  3. Return policy.

9.3. Parse policy directive

Given a string (value), an origin (container origin), and an optional origin (target origin), this algorithm returns a policy directive.

  1. Let directive be an empty ordered map.
  2. For each serialized-declaration returned by strictly splitting value on the delimiter U+003B (;):
    1. Let tokens be the result of splitting serialized-declaration on ASCII whitespace.
    2. If tokens is an empty list, then continue.
    3. Let feature-name be the first element of tokens.
    4. If feature-name does not identify any recognized policy-controlled feature, then continue.
    5. Let feature be the policy-controlled feature identified by feature-name.
    6. Let targetlist be the remaining elements, if any, of tokens.
    7. Let allowlist be a new allowlist.
    8. If any element of targetlist is the string "*", set allowlist to the special value *.
    9. Otherwise:
      1. Set allowlist to an new ordered set.
      2. If targetlist is empty and target origin is given, append target origin to allowlist.
      3. For each element in targetlist:
        1. If element is an ASCII case-insensitive match for "'self'", let result be container origin.
        2. If target origin is given, and element is an ASCII case-insensitive match for "'src'", let result be target origin.
        3. Otherwise, let result be the result of executing the URL parser on element.
        4. If result is not failure:
          1. Let target be the origin of result.
          2. If target is not an opaque origin, append target to allowlist.
    10. Set directive[feature] to allowlist.
  3. Return directive

9.4. Merge directive with declared policy

Given a policy directive (directive) and a declared policy (policy), this algorithm will modify policy to account for the new directive.

  1. For each featureallowlist of directive:
    1. If policy does not contain an allowlist for feature, then set policy[feature] to allowlist.

9.5. Process feature policy attributes

Given an element (element), this algorithm returns a container policy, which may be empty.

  1. Let policy be a new policy directive.
  2. Let container policy be the result of running Parse policy directive on the value of element’s allow attribute, with container origin set to the origin of element’s node document, and target origin set to element’s declared origin.
  3. If element is an iframe element:
    1. If element’s allowfullscreen attribute is specified, and container policy does not contain an allowlist for fullscreen,
      1. Construct a new declaration for fullscreen, whose allowlist is the special value *.
      2. Add declaration to container policy.
    2. If element’s allowpaymentrequest attribute is specified, and container policy does not contain an allowlist for payment,
      1. Construct a new declaration for payment, whose allowlist is the special value *.
      2. Add declaration to container policy.
  4. Return container policy.

9.6. Initialize document’s Feature Policy

Given a Document object (document), this algorithm initialises document’s Feature Policy

  1. Let inherited policy be a new ordered map.
  2. Let declared policy be a new ordered map.
  3. For each feature supported,
    1. Let isInherited be the result of running §9.8 Define an inherited policy for feature in document on feature and document.
    2. Set inherited policy[feature] to isInherited.
  4. Let policy be a new feature policy, with inherited policy inherited policy and declared policy declared policy.
  5. Enforce the policy policy on document.

9.7. Initialize document’s Feature Policy from response

Given a response (response) and a Document (document), this algorithm populates document’s Feature Policy

  1. Initialize document’s Feature Policy
  2. Let inherited policy be document’s Feature Policy’s inherited policy.
  3. Let declared policy be a new ordered map.
  4. Let d be the result of running Process response policy on response and document’s origin.
  5. For each featureallowlist of d:
    1. If inherited policy[feature] is true, then set declared policy[feature] to allowlist.
  6. Let policy be a new feature policy, with inherited policy inherited policy and declared policy declared policy.
  7. Enforce the policy policy on document.

9.8. Define an inherited policy for feature in document

Given a feature (feature) and a Document (document), this algorithm returns the inherited policy for that feature.

  1. Let context be document’s browsing context.
  2. If context is a nested browsing context, return the result of executing §9.9 Define an inherited policy for feature in container at origin for feature in context’s browsing context container at document’s origin.
  3. Otherwise, return "Enabled".

9.9. Define an inherited policy for feature in container at origin

Given a feature (feature) a browsing context container (container), and an origin for a document in that container (origin), this algorithm returns the inherited policy for that feature.

  1. Let parent be container’s node document.
  2. Let container policy be the result of running §9.5 Process feature policy attributes on container.
  3. If feature is a key in container policy:
    1. If the allowlist for feature in container policy does not match origin, return "Disabled".
    2. If feature is enabled in parent for parent’s origin, return "Enabled".
  4. If feature is enabled in parent for origin, return "Enabled".
  5. Otherwise return "Disabled".

9.10. Is feature enabled in document for origin?

Given a feature (feature), a Document object (document), and an origin (origin), this algorithm returns "Disabled" if feature should be considered disabled, and "Enabled" otherwise.

  1. Let policy be document’s Feature Policy
  2. If policy’s inherited policy for feature is Disabled, return "Disabled".
  3. If feature is present in policy’s declared policy:
    1. If the allowlist for feature in policy’s declared policy matches origin, then return "Enabled".
    2. Otherwise return "Disabled".
  4. If feature’s default allowlist is *, return "Enabled".
  5. If feature’s default allowlist is 'self', and origin is same origin-domain with document’s origin, return "Enabled".
  6. Return "Disabled".

9.11. Generate report for violation of feature policy on settings

Given a feature (feature), an environment settings object (settings), and an optional string (group), this algorithm generates a report about the violation of the policy for feature.

  1. Let body be a new FeaturePolicyViolationReportBody, initialized as follows:

    featureId

    feature’s string representation.

    sourceFile

    null

    lineNumber

    null

    columnNumber

    null

    disposition

    "enforce"

  2. If the user agent is currently executing script, and can extract the source file’s URL, line number, and column number from settings, then set body’s sourceFile, lineNumber, and columnNumber accordingly.

  3. If group is omitted, set group to "default".

  4. Execute Reporting API §#queue-report with body, "feature-policy-violation", group, and settings.

Note: This algorithm should be called when a feature policy has been violated.

9.12. Should request be allowed to use feature?

Given a feature (feature) and a request (request), this algorithm returns true if the request should be allowed to use feature, and false otherwise.

  1. Set window to request’s window.
  2. If window is not a Window, return false.
    Feature Policy within no-window contexts (WorkerGlobalScope or WorkletGlobalScope) is being figured out in issue #207. After that’s resolved, update this algorithm to allow fetches initiated within these contexts to use policy-controlled features. Until that’s resolved, disallow all policy-controlled features (e.g., sending Client Hints to third parties) in these contexts.
  3. Set document to window’s associated Document.
  4. Let origin be request’s origin.
  5. Let result be the result of executing Is feature enabled in document for origin? on feature, document, and origin.
  6. If result is "Enabled", return true.
  7. Otherwise, return false.

10. IANA Considerations

The permanent message header field registry should be updated with the following registration [RFC3864]:

Header field name
Feature-Policy
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
Feature Policy API

11. Privacy and Security

This specification standardizes a mechanism for an embedding page to set a policy which will be enforced on an embedded page. Similar to iframe sandbox, this can be done without the express permission of the embedded page, which means that behaviors of existing features can be changed in published web sites, by embedding them in another document with an appropriate container policy.

As such, the biggest privacy and security concerns are:

To a degree, these concerns are already present in the web platform, and this specification attempts to at least not make them needlessly worse.

Security and privacy issues may also be caused by the design of individual features, so care must be taken when integrating with this specification. This section attempts to provide some guidance as to what kinds of behaviors could cause such issues.

11.1. Exposure of cross-origin behavior

Features should be designed such that a violation of the policy in a framed document is not observable by documents in other frames. For instance, a hypothetical feature which caused a event to be fired in the embedding document if it is used while disabled by policy, could be used to extract information about the state of an embedded document. If the feature is known only to be used while a user is logged in to the site, for instance, then the embedder could disable that feature for the frame, and then listen for the resulting events to determine whether or not the user is logged in.

The introspection API is designed to only show information about a subframe’s policy which could already be deduced by the embedding document. This observable policy is not affected by any HTTP headers delivered with the framed document, and does not change when the frame navigates itself, even if such navigation is to a different origin, where a different policy applies. Only navigations caused by setting the src attribute of the <iframe> element will cause the observable policy to be updated.

11.2. Unanticipated behavior changes

Feature policy grants a document the ability to control which features will and will not be availble in a subframe at the time it is loaded. When a feature represents an existing, long-standing behavior of the web platform, this may mean that existing published content on the web was not written with the expectation that a particular API could fail.

As a practical (though contrived) example, consider a document which uses synchronous XMLHttpRequest to determine whether a user has sufficient privileges to access the page:

<!DOCTYPE html>
<h1>Welcome to SecureCorp!</h1>
<script>
  var req = new XMLHttpRequest();
  req.open("GET", "/api/security_check.json", false);
  req.send();
  if (req.response == "untrusted user") {
    // User is not logged in; redirect to a safe page
    location.href = "/security_check_failed.html";
  }
</script>
<!-- Page continues with assumption that user is logged in -->

If this document is embedded by a page which disables the "sync-xhr" feature, the call to XMLHttpRequest.open() would fail, and the security check would be bypassed.

Note that this sort of behavior forcing is already possible on the web: some features are only allowed in top-level documents, and not in any iframes, and iframe sandboxing can be used in a similar way to embed a frame without access to features which it may be depending on.

In general, this concern is mitigated in two ways:

Authors integrating their features with Feature Policy can decide when and how the feature will fail when a document attempts to use it while it is disabled. Authors should attempt to make use of existing failure modes, when they exist, to increase the chance that existing content will already be correctly handling such failures.

11.3. Exposure of embedding policy

Care has been taken to limit the information which an page can infer about the behavior of cross-origin pages which it embeds. It may be possible in some scenarios however, for the embedded page to infer information about its embedder, by examining the policy which the embedder has enforced on it.

This is similar to the existing document.fullscreenEnabled property, which can be used by the embedded document to infer whether its embedder has granted it the ability to use the Fullscreen API. If this is only granted in certain cases — when the user is logged in to the embedding site, for instance — then the embedded site can learn something about the state of its embedder.

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Conformant Algorithms

Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.

Conformance requirements phrased as algorithms or specific steps can be implemented in any manner, so long as the end result is equivalent. In particular, the algorithms defined in this specification are intended to be easy to understand and are not intended to be performant. Implementers are encouraged to optimize.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSP-3]
Content Security Policy Level 3 URL: https://www.w3.org/TR/CSP3/
[DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[FETCH]
Anne van Kesteren. Fetch Standard. Living Standard. URL: https://fetch.spec.whatwg.org/
[FULLSCREEN]
Philip Jägenstedt. Fullscreen API Standard. Living Standard. URL: https://fullscreen.spec.whatwg.org/
[HTML]
Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[INFRA]
Anne van Kesteren; Domenic Denicola. Infra Standard. Living Standard. URL: https://infra.spec.whatwg.org/
[PAYMENT-REQUEST]
Adrian Bateman; et al. Payment Request API. 30 August 2018. CR. URL: https://www.w3.org/TR/payment-request/
[REPORTING]
Reporting API. Living Standard. URL: https://wicg.github.io/reporting/
[REPORTING-1]
Douglas Creager; et al. Reporting API. 25 September 2018. WD. URL: https://www.w3.org/TR/reporting-1/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[RFC3864]
G. Klyne; M. Nottingham; J. Mogul. Registration Procedures for Message Header Fields. September 2004. Best Current Practice. URL: https://tools.ietf.org/html/rfc3864
[URL]
Anne van Kesteren. URL Standard. Living Standard. URL: https://url.spec.whatwg.org/
[WebIDL]
Boris Zbarsky. Web IDL. 15 December 2016. ED. URL: https://heycam.github.io/webidl/
[WORKLETS-1]
Ian Kilpatrick. Worklets Level 1. 7 June 2016. WD. URL: https://www.w3.org/TR/worklets-1/

Informative References

[CSP2]
Mike West; Adam Barth; Daniel Veditz. Content Security Policy Level 2. 15 December 2016. REC. URL: https://www.w3.org/TR/CSP2/
[HTML5]
Ian Hickson; et al. HTML5. 27 March 2018. REC. URL: https://www.w3.org/TR/html5/

IDL Index

[NoInterfaceObject]
interface FeaturePolicy {
  boolean allowsFeature(DOMString feature, optional DOMString origin);
  sequence<DOMString> features();
  sequence<DOMString> allowedFeatures();
  sequence<DOMString> getAllowlistForFeature(DOMString feature);
};

partial interface Document {
    [SameObject] readonly attribute FeaturePolicy featurePolicy;
};

partial interface HTMLIFrameElement {
    [SameObject] readonly attribute FeaturePolicy featurePolicy;
};
interface FeaturePolicyViolationReportBody : ReportBody {
  readonly attribute DOMString featureId;
  readonly attribute DOMString? sourceFile;
  readonly attribute long? lineNumber;
  readonly attribute long? columnNumber;
  readonly attribute DOMString disposition;
};

Issues Index

This spec currently only deals with features defined in Documents. We should figure out how to word this to include the possibility of features and feature policies in Workers and Worklets as well.
Feature Policy within no-window contexts (WorkerGlobalScope or WorkletGlobalScope) is being figured out in issue #207. After that’s resolved, update this algorithm to allow fetches initiated within these contexts to use policy-controlled features. Until that’s resolved, disallow all policy-controlled features (e.g., sending Client Hints to third parties) in these contexts.