dymokomi/luce-browser-engine
Source of release 0.6.0
0.6.0 / src / web / content_security_policy / directives / directive_operations_1.lucb
#==============================================================================================
#
# directive_operations_1 - ContentSecurityPolicy::Directives operations: effective
# directives, the fetch directive fallback list, and the scheme-, host-, port- and path-part
# matching of source expressions
#
# DESCRIPTION:
# Port of Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp
# (lines 1-445): fetch_directive_fallback_list through path_part_matches.
#
# Copyright (c) 2025, Luke Wilde <luke@ladybird.org>
# SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================
# mark: Effective directives and the fallback list ==============================================
## Whether content_security_policy_directives_fetch_directive_fallback_list has been filled.
var content_security_policy_directives_fetch_directive_fallback_list_initialized: bool
## One entry of fetch_directive_fallback_list's initializer: `{ name, { fallbacks... } }`.
func content_security_policy_directives_add_fallback_list(name: str, fallbacks: const str[]):
var list = ak.Vector[ak.StringView]()
for fallback in fallbacks:
ak.vector_append_t(&list, ak.sv(fallback))
_ = ak.hash_map_set(&content_security_policy_directives_fetch_directive_fallback_list, ak.sv(name), list)
## Ported from Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp:35 the initializer of
## Web::ContentSecurityPolicy::Directives::fetch_directive_fallback_list (a static HashMap, filled when first
## needed; it outlives every VM, so it is made in the C heap, DESIGN.md §3.3 rule 7).
# https://w3c.github.io/webappsec-csp/#directive-fallback-list
# Will return an ordered set of the fallback directives for a specific directive.
# The returned ordered set is sorted from most relevant to least relevant and it includes the effective directive
# itself.
func content_security_policy_directives_initialize_fetch_directive_fallback_list():
if content_security_policy_directives_fetch_directive_fallback_list_initialized:
return
let saved_atomic_allocator = ak.atomic_allocator
ak.atomic_allocator = none
defer ak.atomic_allocator = saved_atomic_allocator
with memory.heap:
# "script-src-elem"
# 1. Return << "script-src-elem", "script-src", "default-src" >>.
content_security_policy_directives_add_fallback_list("script-src-elem", ["script-src-elem", "script-src", "default-src"])
# "script-src-attr"
# 1. Return << "script-src-attr", "script-src", "default-src" >>.
content_security_policy_directives_add_fallback_list("script-src-attr", ["script-src-attr", "script-src", "default-src"])
# "style-src-elem"
# 1. Return << "style-src-elem", "style-src", "default-src" >>.
content_security_policy_directives_add_fallback_list("style-src-elem", ["style-src-elem", "style-src", "default-src"])
# "style-src-attr"
# 1. Return << "style-src-attr", "style-src", "default-src" >>.
content_security_policy_directives_add_fallback_list("style-src-attr", ["style-src-attr", "style-src", "default-src"])
# "worker-src"
# 1. Return << "worker-src", "child-src", "script-src", "default-src" >>.
content_security_policy_directives_add_fallback_list("worker-src", ["worker-src", "child-src", "script-src", "default-src"])
# "connect-src"
# 1. Return << "connect-src", "default-src" >>.
content_security_policy_directives_add_fallback_list("connect-src", ["connect-src", "default-src"])
# "manifest-src"
# 1. Return << "manifest-src", "default-src" >>.
content_security_policy_directives_add_fallback_list("manifest-src", ["manifest-src", "default-src"])
# "object-src"
# 1. Return << "object-src", "default-src" >>.
content_security_policy_directives_add_fallback_list("object-src", ["object-src", "default-src"])
# "frame-src"
# 1. Return << "frame-src", "child-src", "default-src" >>.
content_security_policy_directives_add_fallback_list("frame-src", ["frame-src", "child-src", "default-src"])
# "media-src"
# 1. Return << "media-src", "default-src" >>.
content_security_policy_directives_add_fallback_list("media-src", ["media-src", "default-src"])
# "font-src"
# 1. Return << "font-src", "default-src" >>.
content_security_policy_directives_add_fallback_list("font-src", ["font-src", "default-src"])
# "img-src"
# 1. Return << "img-src", "default-src" >>.
content_security_policy_directives_add_fallback_list("img-src", ["img-src", "default-src"])
content_security_policy_directives_fetch_directive_fallback_list_initialized = true
## Ported from Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp:87 Web::ContentSecurityPolicy::Directives::get_the_effective_directive_for_request.
# https://w3c.github.io/webappsec-csp/#effective-directive-for-a-request
pub func content_security_policy_directives_get_the_effective_directive_for_request(request: FetchRequest*) -> ak.FlyString?:
# Each fetch directive controls a specific destination of request. Given a request request, the following algorithm
# returns either null or the name of the request’s effective directive:
# 1. If request’s initiator is "prefetch" or "prerender", return default-src.
let initiator = fetch_request_initiator(request)
if initiator == FetchRequestInitiator.prefetch or initiator == FetchRequestInitiator.prerender:
return content_security_policy_directives_names_default_src
# 2. Switch on request’s destination, and execute the associated steps:
# the empty string
# 1. Return connect-src.
let destination = fetch_request_destination(request) else return content_security_policy_directives_names_connect_src
match destination:
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#process-a-navigate-fetch
# destination
# "document" (NOTE: The destination is updated below when navigable has a container.)
# If navigable's container is non-null:
# 2. Set request's destination to navigable's container's local name.
# AD-HOC: CSP's effective directive algorithm does not have a "document" case, but falling through to connect-src
# applies fetch directives to top-level document navigations. Treat these navigation requests as not having
# a fetch directive.
.document:
return none
# "manifest"
# 1. Return manifest-src.
.manifest:
return content_security_policy_directives_names_manifest_src
# "object"
# "embed"
# 1. Return object-src.
.object, .embed:
return content_security_policy_directives_names_object_src
# "frame"
# "iframe"
# 1. Return frame-src.
.frame, .i_frame:
return content_security_policy_directives_names_frame_src
# "audio"
# "track"
# "video"
# 1. Return media-src.
.audio, .track, .video:
return content_security_policy_directives_names_media_src
# "font"
# 1. Return font-src.
.font:
return content_security_policy_directives_names_font_src
# "image"
# 1. Return img-src.
.image:
return content_security_policy_directives_names_img_src
# "style"
# 1. Return style-src-elem.
.style:
return content_security_policy_directives_names_style_src_elem
# "script"
# "xslt"
# "audioworklet"
# "paintworklet"
# 1. Return script-src-elem.
.script, .xslt, .audio_worklet, .paint_worklet:
return content_security_policy_directives_names_script_src_elem
# "serviceworker"
# "sharedworker"
# "worker"
# 1. Return worker-src.
.service_worker, .shared_worker, .worker:
return content_security_policy_directives_names_worker_src
# "json"
# "webidentity"
# 1. Return connect-src.
.json, .web_identity:
return content_security_policy_directives_names_connect_src
# "report"
# 1. Return null.
.report:
return none
# 3. Return connect-src.
# Spec Note: The algorithm returns connect-src as a default fallback. This is intended for new fetch destinations
# that are added and which don’t explicitly fall into one of the other categories.
_:
return content_security_policy_directives_names_connect_src
## Ported from Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp:182 Web::ContentSecurityPolicy::Directives::get_fetch_directive_fallback_list.
# https://w3c.github.io/webappsec-csp/#directive-fallback-list
pub func content_security_policy_directives_get_fetch_directive_fallback_list(directive_name: ak.FlyString?) -> ak.Vector[ak.StringView]:
let name = directive_name else return ak.Vector[ak.StringView]()
content_security_policy_directives_initialize_fetch_directive_fallback_list()
let list = ak.hash_map_get_k(&content_security_policy_directives_fetch_directive_fallback_list, ak.fly_string_bytes_as_string_view(&name)) else return ak.Vector[ak.StringView]()
return ak.vector_clone(list)
## Ported from Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp:195 Web::ContentSecurityPolicy::Directives::should_fetch_directive_execute.
# https://w3c.github.io/webappsec-csp/#should-directive-execute
pub func content_security_policy_directives_should_fetch_directive_execute(effective_directive_name: ak.FlyString?, directive_name: ak.FlyString, policy: ContentSecurityPolicyPolicy*) -> ContentSecurityPolicyShouldExecute:
# 1. Let directive fallback list be the result of executing § 6.8.3 Get fetch directive fallback list on effective
# directive name.
var directive_fallback_list = content_security_policy_directives_get_fetch_directive_fallback_list(effective_directive_name)
# 2. For each fallback directive of directive fallback list:
for fallback_directive in ak.vector_span(&directive_fallback_list):
# 1. If directive name is fallback directive, Return "Yes".
if ak.fly_string_eq_string_view(&directive_name, fallback_directive):
return ContentSecurityPolicyShouldExecute.yes
# 2. If policy contains a directive whose name is fallback directive, Return "No".
if content_security_policy_policy_contains_directive_with_name(policy, fallback_directive):
return ContentSecurityPolicyShouldExecute.no
# 3. Return "No".
return ContentSecurityPolicyShouldExecute.no
## Ported from Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp:217 Web::ContentSecurityPolicy::Directives::get_the_effective_directive_for_inline_checks.
# https://w3c.github.io/webappsec-csp/#effective-directive-for-inline-check
pub func content_security_policy_directives_get_the_effective_directive_for_inline_checks(type_: ContentSecurityPolicyInlineType) -> ak.FlyString:
# Spec Note: While the effective directive is only defined for requests, in this algorithm it is used similarly to
# mean the directive that is most relevant to a particular type of inline check.
# Switch on type:
match type_:
# "script"
# "navigation"
# Return script-src-elem.
.script, .navigation:
return content_security_policy_directives_names_script_src_elem
# "script attribute"
# Return script-src-attr.
.script_attribute:
return content_security_policy_directives_names_script_src_attr
# "style"
# Return style-src-elem.
.style:
return content_security_policy_directives_names_style_src_elem
# "style attribute"
# Return style-src-attr.
.style_attribute:
return content_security_policy_directives_names_style_src_attr
_:
# 2. Return null.
# FIXME: File spec issue that this should be invalid, as the result of this algorithm ends up being piped into
# Violation's effective directive, which is defined to be a non-empty string.
trap("VERIFY_NOT_REACHED")
# mark: Part matching ===========================================================================
## Ported from Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp:263 Web::ContentSecurityPolicy::Directives::scheme_part_matches.
# https://w3c.github.io/webappsec-csp/#scheme-part-match
# An ASCII string scheme-part matches another ASCII string if a CSP source expression that contained the first as a
# scheme-part could potentially match a URL containing the latter as a scheme. For example, we say that "http"
# scheme-part matches "https".
# More formally, two ASCII strings A and B are said to scheme-part match if the following algorithm returns "Matches":
# Spec Note: The matching relation is asymmetric. For example, the source expressions https: and https://example.com/
# do not match the URL http://example.com/. We always allow a secure upgrade from an explicitly insecure
# expression. script-src http: is treated as equivalent to script-src http: https:,
# script-src http://example.com to script-src http://example.com https://example.com,
# and connect-src ws: to connect-src ws: wss:.
func content_security_policy_directives_scheme_part_matches(a: ak.StringView, b: ak.StringView) -> ContentSecurityPolicyDirectivesMatchResult:
# 1. If one of the following is true, return "Matches":
# 1. A is an ASCII case-insensitive match for B.
if ak.string_view_equals_ignoring_ascii_case(&a, b):
return ContentSecurityPolicyDirectivesMatchResult.matches
# 2. A is an ASCII case-insensitive match for "http", and B is an ASCII case-insensitive match for "https".
if ak.string_view_equals_ignoring_ascii_case(&a, ak.sv("http")) and ak.string_view_equals_ignoring_ascii_case(&b, ak.sv("https")):
return ContentSecurityPolicyDirectivesMatchResult.matches
# 3. A is an ASCII case-insensitive match for "ws", and B is an ASCII case-insensitive match for "wss", "http", or "https".
if (ak.string_view_equals_ignoring_ascii_case(&a, ak.sv("ws")) and (ak.string_view_equals_ignoring_ascii_case(&b, ak.sv("wss")) or ak.string_view_equals_ignoring_ascii_case(&b, ak.sv("http")) or ak.string_view_equals_ignoring_ascii_case(&b, ak.sv("https")))):
return ContentSecurityPolicyDirectivesMatchResult.matches
# 4. A is an ASCII case-insensitive match for "wss", and B is an ASCII case-insensitive match for "https".
if ak.string_view_equals_ignoring_ascii_case(&a, ak.sv("wss")) and ak.string_view_equals_ignoring_ascii_case(&b, ak.sv("https")):
return ContentSecurityPolicyDirectivesMatchResult.matches
# 2. Return "Does Not Match".
return ContentSecurityPolicyDirectivesMatchResult.does_not_match
## Ported from Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp:298 Web::ContentSecurityPolicy::Directives::host_part_matches.
# https://w3c.github.io/webappsec-csp/#host-part-match
# An ASCII string host-part matches a host if a CSP source expression that contained the first as a host-part could
# potentially match the latter. For example, we say that "www.example.com" host-part matches "www.example.com".
# More formally, ASCII string pattern and host host are said to host-part match if the following algorithm returns "Matches":
# Spec Note: The matching relation is asymmetric. That is, pattern matching host does not mean that host will match pattern.
# For example, *.example.com host-part matches www.example.com, but www.example.com does not host-part match *.example.com.
func content_security_policy_directives_host_part_matches(pattern: ak.StringView, maybe_host: web_url.Host?) -> ContentSecurityPolicyDirectivesMatchResult:
# 1. If host is not a domain, return "Does Not Match".
# Spec Note: A future version of this specification may allow literal IPv6 and IPv4 addresses, depending on usage and demand.
# Given the weak security properties of IP addresses in relation to named hosts, however, authors are encouraged
# to prefer the latter whenever possible.
let host = maybe_host else return ContentSecurityPolicyDirectivesMatchResult.does_not_match
if not web_url.host_is_domain(&host):
return ContentSecurityPolicyDirectivesMatchResult.does_not_match
# 2. If pattern is "*", return "Matches".
if ak.string_view_eq_string_view(&pattern, ak.sv("*")):
return ContentSecurityPolicyDirectivesMatchResult.matches
assert(web_url.host_has_string(&host))
let host_string = web_url.host_get_string(&host)
# 3. If pattern starts with "*.":
if ak.string_view_starts_with_string_view(&pattern, ak.sv("*.")):
# 1. Let remaining be pattern with the leading U+002A (*) removed and ASCII lowercased.
let remaining_without_asterisk = ak.string_view_substring_view(&pattern, 1)
let remaining = ak.string_view_to_ascii_lowercase_string(&remaining_without_asterisk)
# 2. If host to ASCII lowercase ends with remaining, then return "Matches".
let lowercase_host = ak.string_to_ascii_lowercase(&host_string)
if ak.string_ends_with_bytes(&lowercase_host, ak.string_bytes_as_string_view(&remaining)):
return ContentSecurityPolicyDirectivesMatchResult.matches
# 3. Return "Does Not Match".
return ContentSecurityPolicyDirectivesMatchResult.does_not_match
# 4. If pattern is not an ASCII case-insensitive match for host, return "Does Not Match".
if not ak.string_view_equals_ignoring_ascii_case(&pattern, ak.string_bytes_as_string_view(&host_string)):
return ContentSecurityPolicyDirectivesMatchResult.does_not_match
# 5. Return "Matches".
return ContentSecurityPolicyDirectivesMatchResult.matches
## Ported from Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp:349 Web::ContentSecurityPolicy::Directives::port_part_matches.
# https://w3c.github.io/webappsec-csp/#port-part-matches
# An ASCII string input port-part matches URL url if a CSP source expression that contained the first as a port-part
# could potentially match a URL containing the latter’s port and scheme. For example, "80" port-part matches
# matches http://example.com.
func content_security_policy_directives_port_part_matches(input: ak.StringView?, url: web_url.Url) -> ContentSecurityPolicyDirectivesMatchResult:
# FIXME: 1. Assert: input is the empty string, "*", or a sequence of ASCII digits.
# 2. If input is equal to "*", return "Matches".
if let input_value = input:
if ak.string_view_eq_string_view(&input_value, ak.sv("*")):
return ContentSecurityPolicyDirectivesMatchResult.matches
# 3. Let normalizedInput be null if input is the empty string; otherwise input interpreted as decimal number.
var normalized_input: u16? = none
if let input_value = input:
assert(not ak.string_view_is_empty(&input_value))
let maybe_port = ak.string_view_to_number_u16(&input_value, ak.TrimWhitespace.no)
# If the port is empty here, then it's because the input overflowed the u16. Since this means it's bigger than
# a u16, it can never match the URL's port, which is only within the u16 range.
let port = maybe_port else return ContentSecurityPolicyDirectivesMatchResult.does_not_match
normalized_input = port
# 4. If normalizedInput equals url’s port, return "Matches".
if normalized_input == web_url.url_port(&url):
return ContentSecurityPolicyDirectivesMatchResult.matches
# 5. If url’s port is null:
if web_url.url_port(&url) == none:
# 1. Let defaultPort be the default port for url’s scheme.
let scheme = web_url.url_scheme(&url)
let default_port = web_url.default_port_for_scheme(ak.string_bytes_as_string_view(&scheme))
# 2. If normalizedInput equals defaultPort, return "Matches".
if normalized_input == default_port:
return ContentSecurityPolicyDirectivesMatchResult.matches
# 6. Return "Does Not Match".
return ContentSecurityPolicyDirectivesMatchResult.does_not_match
## Ported from Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp:392 Web::ContentSecurityPolicy::Directives::path_part_matches.
# https://w3c.github.io/webappsec-csp/#path-part-match
# An ASCII string path A path-part matches another ASCII string path B if a CSP source expression that contained the
# first as a path-part could potentially match a URL containing the latter as a path. For example, we say that
# "/subdirectory/" path-part matches "/subdirectory/file".
# Spec Note: The matching relation is asymmetric. That is, path A matching path B does not mean that path B will
# match path A.
func content_security_policy_directives_path_part_matches(a: ak.StringView, b: ak.StringView) -> ContentSecurityPolicyDirectivesMatchResult:
# 1. If path A is the empty string, return "Matches".
if ak.string_view_is_empty(&a):
return ContentSecurityPolicyDirectivesMatchResult.matches
# 2. If path A consists of one character that is equal to the U+002F SOLIDUS character (/) and path B is the empty
# string, return "Matches".
if ak.string_view_eq_string_view(&a, ak.sv("/")) and ak.string_view_is_empty(&b):
return ContentSecurityPolicyDirectivesMatchResult.matches
# 3. Let exact match be false if the final character of path A is the U+002F SOLIDUS character (/), and true
# otherwise.
let exact_match = not ak.string_view_ends_with_u8(&a, '/')
# 4. Let path list A and path list B be the result of strictly splitting path A and path B respectively on the
# U+002F SOLIDUS character (/).
var path_list_a = ak.string_view_split_view_u8(&a, '/', ak.SplitBehavior.keep_empty)
var path_list_b = ak.string_view_split_view_u8(&b, '/', ak.SplitBehavior.keep_empty)
# 5. If path list A has more items than path list B, return "Does Not Match".
if ak.vector_size(&path_list_a) > ak.vector_size(&path_list_b):
return ContentSecurityPolicyDirectivesMatchResult.does_not_match
# 6. If exact match is true, and path list A does not have the same number of items as path list B,
# return "Does Not Match".
if exact_match and ak.vector_size(&path_list_a) != ak.vector_size(&path_list_b):
return ContentSecurityPolicyDirectivesMatchResult.does_not_match
# 7. If exact match is false:
if not exact_match:
# 1. Assert: the final item in path list A is the empty string.
assert(ak.string_view_is_empty(ak.vector_last(&path_list_a)))
# 2. Remove the final item from path list A.
_ = ak.vector_take_last(&path_list_a)
# 8. For each piece A of path list A:
for path_set_a_index in 0..<ak.vector_size(&path_list_a):
let piece_a = *ak.vector_at(&path_list_a, path_set_a_index)
# 1. Let piece B be the next item in path list B.
let piece_b = *ak.vector_at(&path_list_b, path_set_a_index)
# 2. Let decoded piece A be the percent-decoding of piece A.
let decoded_piece_a = web_url.percent_decode(piece_a)
# 3. Let decoded piece B be the percent-decoding of piece B.
let decoded_piece_b = web_url.percent_decode(piece_b)
# 4. If decoded piece A is not decoded piece B, return "Does Not Match".
if not ak.byte_string_eq_byte_string(&decoded_piece_a, &decoded_piece_b):
return ContentSecurityPolicyDirectivesMatchResult.does_not_match
# 9. Return "Matches".
return ContentSecurityPolicyDirectivesMatchResult.matches