Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / fetch / infrastructure / http / cors.lucb

#==============================================================================================
#
#   cors - CORS-safelisted and CORS-unsafe request headers, safelisted response header names
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/Fetch/Infrastructure/HTTP/CORS.cpp (lines 17-195) with
#       CORS.h.
#
#       Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
#       Copyright (c) 2022, Kenneth Myhra <kennethmyhra@serenityos.org>
#       Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

## Whether `value` holds a CORS-unsafe request-header byte (`any_of(value, is_cors_unsafe_request_header_byte)`).
func fetch_contains_cors_unsafe_request_header_byte(value: ak.StringView) -> bool:
    for byte in ak.string_view_bytes(&value):
        if fetch_is_cors_unsafe_request_header_byte(byte):
            return true
    return false

## Ported from Libraries/LibWeb/Fetch/Infrastructure/HTTP/CORS.cpp:19 Web::Fetch::Infrastructure::is_cors_safelisted_request_header.
# https://fetch.spec.whatwg.org/#cors-safelisted-request-header
pub func fetch_is_cors_safelisted_request_header(header: const HttpHeader*) -> bool:
    let name = ak.byte_string_view(&header.name)
    let value = ak.byte_string_view(&header.value)

    # 1. If value’s length is greater than 128, then return false.
    if ak.string_view_length(&value) > 128:
        return false

    # 2. Byte-lowercase name and switch on the result:
    # `accept`
    if ak.string_view_equals_ignoring_ascii_case(&name, ak.sv("accept")):
        # If value contains a CORS-unsafe request-header byte, then return false.
        if fetch_contains_cors_unsafe_request_header_byte(value):
            return false
    # `accept-language`
    # `content-language`
    elif ak.string_view_is_one_of_ignoring_ascii_case(&name, ["accept-language", "content-language"]):
        # If value contains a byte that is not in the range 0x30 (0) to 0x39 (9), inclusive, is not in the range 0x41 (A) to 0x5A (Z), inclusive, is not in the range 0x61 (a) to 0x7A (z), inclusive, and is not 0x20 (SP), 0x2A (*), 0x2C (,), 0x2D (-), 0x2E (.), 0x3B (;), or 0x3D (=), then return false.
        let allowed_punctuation = ak.sv(" *,-.;=")
        for byte in ak.string_view_bytes(&value):
            if not (ak.is_ascii_digit(byte) or ak.is_ascii_alpha(byte) or ak.string_view_contains_u8(&allowed_punctuation, byte)):
                return false
    # `content-type`
    elif ak.string_view_equals_ignoring_ascii_case(&name, ak.sv("content-type")):
        # 1. If value contains a CORS-unsafe request-header byte, then return false.
        if fetch_contains_cors_unsafe_request_header_byte(value):
            return false

        # 2. Let mimeType be the result of parsing the result of isomorphic decoding value.
        let decoded = text_codec.isomorphic_decode(value)
        let mime_type = mime_type_parse(ak.string_bytes_as_string_view(&decoded))

        # 3. If mimeType is failure, then return false.
        let parsed = mime_type else return false

        # 4. If mimeType’s essence is not "application/x-www-form-urlencoded", "multipart/form-data", or "text/plain", then return false.
        let essence = mime_type_essence(&parsed)
        let essence_view = ak.string_bytes_as_string_view(&essence)
        if not (ak.string_view_equals(&essence_view, "application/x-www-form-urlencoded") or ak.string_view_equals(&essence_view, "multipart/form-data") or ak.string_view_equals(&essence_view, "text/plain")):
            return false
    # `range`
    elif ak.string_view_equals_ignoring_ascii_case(&name, ak.sv("range")):
        # 1. Let rangeValue be the result of parsing a single range header value given value and false.
        let range_value = http_parse_single_range_header_value(value, false)

        # 2. If rangeValue is failure, then return false.
        let parsed_range = range_value else return false

        # 3. If rangeValue[0] is null, then return false.
        # NOTE: As web browsers have historically not emitted ranges such as `bytes=-500` this algorithm does not safelist them.
        if parsed_range.start == none:
            return false
    # Otherwise
    else:
        # Return false.
        return false

    # 3. Return true.
    return true

## Ported from Libraries/LibWeb/Fetch/Infrastructure/HTTP/CORS.cpp:86 Web::Fetch::Infrastructure::is_cors_unsafe_request_header_byte.
# https://fetch.spec.whatwg.org/#cors-unsafe-request-header-byte
pub func fetch_is_cors_unsafe_request_header_byte(byte: u8) -> bool:
    # A CORS-unsafe request-header byte is a byte byte for which one of the following is true:
    # - byte is less than 0x20 and is not 0x09 HT
    # - byte is 0x22 ("), 0x28 (left parenthesis), 0x29 (right parenthesis), 0x3A (:), 0x3C (<), 0x3E (>), 0x3F (?), 0x40 (@), 0x5B ([), 0x5C (\), 0x5D (]), 0x7B ({), 0x7D (}), or 0x7F DEL.
    let unsafe_bytes: u8[14] = [0x22, 0x28, 0x29, 0x3a, 0x3c, 0x3e, 0x3f, 0x40, 0x5b, 0x5c, 0x5d, 0x7b, 0x7d, 0x7f]
    if byte < 0x20 and byte != 0x09:
        return true
    for unsafe_byte in unsafe_bytes:
        if byte == unsafe_byte:
            return true
    return false

## Ported from Libraries/LibWeb/Fetch/Infrastructure/HTTP/CORS.cpp:96 Web::Fetch::Infrastructure::get_cors_unsafe_header_names.
# https://fetch.spec.whatwg.org/#cors-unsafe-request-header-names
pub func fetch_get_cors_unsafe_header_names(headers: const HttpHeaderList*) -> ak.Vector[ak.ByteString]:
    # 1. Let unsafeNames be a new list.
    var unsafe_names = ak.Vector[ak.ByteString]()

    # 2. Let potentiallyUnsafeNames be a new list.
    var potentially_unsafe_names = ak.Vector[ak.ByteString]()

    # 3. Let safelistValueSize be 0.
    # (Checked<size_t>: an overflow is remembered.)
    var safelist_value_size: usize = 0
    var safelist_value_size_overflowed = false

    # 4. For each header of headers:
    for header in &ak.vector_span_const(http_header_list_headers(headers)):
        # 1. If header is not a CORS-safelisted request-header, then append header’s name to unsafeNames.
        if not fetch_is_cors_safelisted_request_header(header):
            ak.vector_append_t(&unsafe_names, header.name)
        # 2. Otherwise, append header’s name to potentiallyUnsafeNames and increase safelistValueSize by header’s
        #    value’s length.
        else:
            ak.vector_append_t(&potentially_unsafe_names, header.name)
            if let sum = safelist_value_size +? ak.byte_string_length(&header.value):
                safelist_value_size = sum
            else:
                safelist_value_size = safelist_value_size +% ak.byte_string_length(&header.value)
                safelist_value_size_overflowed = true

    # 5. If safelistValueSize is greater than 1024, then for each name of potentiallyUnsafeNames, append name to
    #    unsafeNames.
    if safelist_value_size_overflowed or safelist_value_size > 1024:
        ak.vector_extend(&unsafe_names, &potentially_unsafe_names)

    # 6. Return the result of convert header names to a sorted-lowercase set with unsafeNames.
    return http_convert_header_names_to_a_sorted_lowercase_set(ak.vector_span_const(&unsafe_names))

## Ported from Libraries/LibWeb/Fetch/Infrastructure/HTTP/CORS.cpp:131 Web::Fetch::Infrastructure::is_cors_non_wildcard_request_header_name.
# https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
pub func fetch_is_cors_non_wildcard_request_header_name(header_name: ak.StringView) -> bool:
    # A CORS non-wildcard request-header name is a header name that is a byte-case-insensitive match for `Authorization`.
    return ak.string_view_equals_ignoring_ascii_case(&header_name, ak.sv("Authorization"))

## Ported from Libraries/LibWeb/Fetch/Infrastructure/HTTP/CORS.cpp:138 Web::Fetch::Infrastructure::is_privileged_no_cors_request_header_name.
# https://fetch.spec.whatwg.org/#privileged-no-cors-request-header-name
pub func fetch_is_privileged_no_cors_request_header_name(header_name: ak.StringView) -> bool:
    # A privileged no-CORS request-header name is a header name that is a byte-case-insensitive match for one of
    # - `Range`.
    return ak.string_view_equals_ignoring_ascii_case(&header_name, ak.sv("Range"))

## Ported from Libraries/LibWeb/Fetch/Infrastructure/HTTP/CORS.cpp:146 Web::Fetch::Infrastructure::is_cors_safelisted_response_header_name.
# https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name
pub func fetch_is_cors_safelisted_response_header_name(header_name: ak.StringView, list: const ak.StringView[]) -> bool:
    # A CORS-safelisted response-header name, given a list of header names list, is a header name that is a byte-case-insensitive match for one of
    # - `Cache-Control`
    # - `Content-Language`
    # - `Content-Length`
    # - `Content-Type`
    # - `Expires`
    # - `Last-Modified`
    # - `Pragma`
    # - Any item in list that is not a forbidden response-header name.
    if ak.string_view_is_one_of_ignoring_ascii_case(&header_name, ["Cache-Control", "Content-Language", "Content-Length", "Content-Type", "Expires", "Last-Modified", "Pragma"]):
        return true
    for list_header_name in list:
        if ak.string_view_equals_ignoring_ascii_case(&header_name, list_header_name) and not http_is_forbidden_response_header_name(list_header_name):
            return true
    return false

## Ported from Libraries/LibWeb/Fetch/Infrastructure/HTTP/CORS.cpp:172 Web::Fetch::Infrastructure::is_no_cors_safelisted_request_header_name.
# https://fetch.spec.whatwg.org/#no-cors-safelisted-request-header-name
pub func fetch_is_no_cors_safelisted_request_header_name(header_name: ak.StringView) -> bool:
    # A no-CORS-safelisted request-header name is a header name that is a byte-case-insensitive match for one of
    # - `Accept`
    # - `Accept-Language`
    # - `Content-Language`
    # - `Content-Type`
    return ak.string_view_is_one_of_ignoring_ascii_case(&header_name, ["Accept", "Accept-Language", "Content-Language", "Content-Type"])

## Ported from Libraries/LibWeb/Fetch/Infrastructure/HTTP/CORS.cpp:187 Web::Fetch::Infrastructure::is_no_cors_safelisted_request_header.
# https://fetch.spec.whatwg.org/#no-cors-safelisted-request-header
pub func fetch_is_no_cors_safelisted_request_header(header: const HttpHeader*) -> bool:
    # 1. If name is not a no-CORS-safelisted request-header name, then return false.
    if not fetch_is_no_cors_safelisted_request_header_name(ak.byte_string_view(&header.name)):
        return false

    # 2. Return whether (name, value) is a CORS-safelisted request-header.
    return fetch_is_cors_safelisted_request_header(header)