diff --git a/.github/workflows/wpt.yml b/.github/workflows/wpt.yml new file mode 100644 index 00000000..d4545a19 --- /dev/null +++ b/.github/workflows/wpt.yml @@ -0,0 +1,40 @@ +name: WPT + +# Runs web-platform-tests' url/resources/urltestdata.json, toascii.json and +# setters_tests.json, fetched from WPT master, against URI::WHATWG_PARSER +# (rake test:wpt). The same task runs Unicode's IdnaTestV2.txt for the +# Unicode version of the generated IDNA data and NormalizationTest.txt for +# that of Ruby, and fails when Unicode has released a newer version than +# the generated data. +# +# The URL Standard is a living standard and WPT follows its changes, so the +# scheduled run is how a change in the standard is noticed: it fails when a +# case newer than test/wpt/*_exclusions.json fails, or when an excluded case +# passes or disappears. On push and pull requests a failure is reported +# without failing the checks, since it can come from WPT rather than from +# the change being tested. (GitHub runs scheduled workflows on the +# default branch only, and notifies of a failed scheduled run.) + +on: + push: + pull_request: + schedule: + - cron: '17 3 * * 1' + workflow_dispatch: + +permissions: + contents: read + +jobs: + wpt: + runs-on: ubuntu-latest + continue-on-error: ${{ github.event_name == 'push' || github.event_name == 'pull_request' }} + steps: + - uses: actions/checkout@v7.0.1 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ruby + - run: bundle install --jobs 4 --retry 3 + - name: Run WPT urltestdata + run: bundle exec rake test:wpt diff --git a/README.md b/README.md index 5c7c0dd3..641b2c7e 100644 --- a/README.md +++ b/README.md @@ -44,10 +44,62 @@ uri.fragment #=> "time=1305298413" uri.to_s #=> "http://foo.com/posts?id=30&limit=5#time=1305298413" ``` +### WHATWG URL Standard + +The default parser follows RFC 3986. `URI::WHATWG_PARSER` parses URLs as web browsers do, following the [WHATWG URL Standard](https://url.spec.whatwg.org/), including domain to ASCII (IDNA, [UTS #46](https://www.unicode.org/reports/tr46/)) for non-ASCII domains. IDNA uses the Unicode data of the running Ruby, so a domain with a character added in a later version of Unicode than `RbConfig::CONFIG["UNICODE_VERSION"]`, or than that of the data bundled for IDNA (18.0.0), is invalid: + +```ruby +URI::WHATWG_PARSER.parse("HTTP://EXAMPLE.com:80/a/../b c") +#=> # +URI::WHATWG_PARSER.parse("http://0x7f.1/") +#=> # +URI::WHATWG_PARSER.parse("http://日本語.jp/").host +#=> "xn--wgv71a119e.jp" + +# A relative reference is resolved against a base URL. +URI::WHATWG_PARSER.join("http://example.com/a/b", "../c") +#=> # +``` + +It can also replace the default parser for the whole process: + +```ruby +URI.parser = URI::WHATWG_PARSER +URI("http://EXAMPLE.com/") +#=> # +URI.parser = URI::RFC3986_PARSER +``` + +Only http, https, ws, wss and file URLs become instances of their scheme's class. Other schemes, ftp, mailto and ldap among them, become `URI::Generic`, since `URI::FTP`, `URI::MailTo` and `URI::LDAP` interpret their components by their own RFCs. With `URI.parser = URI::WHATWG_PARSER`, code that relies on those classes no longer works for such URLs: for example, `URI.open("ftp://...")` of open-uri, which opens a `URI::FTP` only, tries to open a local file instead and raises `Errno::ENOENT`. + +The setters of a URI built by `URI::WHATWG_PARSER` follow the setters of the URL Standard. A value that the URL Standard ignores raises `URI::InvalidComponentError`: + +```ruby +uri = URI::WHATWG_PARSER.parse("http://example.com/") +uri.host = "日本語.jp" +uri.port = "8080abc" +uri.to_s #=> "http://xn--wgv71a119e.jp:8080/" +uri.port = "abc" +# raises URI::InvalidComponentError +``` + +As for any URI, `scheme=` does not change the class of the object. Parse the URI again to get the class of its new scheme, before handing it to code that checks the class, such as open-uri, which uses TLS for a `URI::HTTPS` only: + +```ruby +uri = URI::WHATWG_PARSER.parse("http://example.com/") +uri.scheme = "https" +uri #=> # +URI::WHATWG_PARSER.parse(uri.to_s) #=> # +``` + ## Development After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. +`rake test:wpt` runs the conformance tests of `URI::WHATWG_PARSER`: web-platform-tests' `urltestdata.json`, `toascii.json` and `setters_tests.json`, and Unicode's `IdnaTestV2.txt` and `NormalizationTest.txt` (the latter for the Unicode version of the running Ruby; the cases of the former that succeed with a character unknown to it are not run). It fetches them over the network, unless `WPT_URLTESTDATA`, `WPT_TOASCII`, `WPT_SETTERS`, `IDNA_TEST_V2` and `NORMALIZATION_TEST` name local files. The cases that are known to fail are listed in `test/wpt/urltestdata_exclusions.json` and `test/wpt/setters_tests_exclusions.json`; regenerate them with `rake test:wpt:update_exclusions`. + +The Unicode data that IDNA needs and Ruby has not, the Bidi_Class and Joining_Type values in `lib/uri/whatwg_parser/idna_data.rb`, is generated by `rake idna:generate`. Set `UNICODE_VERSION` (for example `UNICODE_VERSION=18.0.0`) to generate it for another version of Unicode. + To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). ## Contributing diff --git a/Rakefile b/Rakefile index 3935fdf2..65d25b97 100644 --- a/Rakefile +++ b/Rakefile @@ -4,7 +4,9 @@ require "rake/testtask" Rake::TestTask.new(:test) do |t| t.libs << "test/lib" t.ruby_opts << "-rhelper" - t.test_files = FileList["test/**/test_*.rb"] + # The WPT and Unicode data tests need the network and run in rake + # test:wpt; the tests of their harness do not. + t.test_files = FileList["test/**/test_*.rb"].exclude(%r{\Atest/wpt/(?!test_\w+_harness\.rb\z)}) end require "rdoc/task" diff --git a/lib/uri/common.rb b/lib/uri/common.rb index 971a684b..45a23a73 100644 --- a/lib/uri/common.rb +++ b/lib/uri/common.rb @@ -11,6 +11,7 @@ require_relative "rfc2396_parser" require_relative "rfc3986_parser" +require_relative "whatwg_parser" module URI # The default parser instance for RFC 2396. @@ -21,6 +22,62 @@ module URI RFC3986_PARSER = RFC3986_Parser.new Ractor.make_shareable(RFC3986_PARSER) if defined?(Ractor) + # The parser instance for the WHATWG URL Standard + # (https://url.spec.whatwg.org/), which browsers follow. It is not the + # default; use it directly, or switch to it with + # URI.parser = URI::WHATWG_PARSER. + # + # URI::WHATWG_PARSER.parse("HTTP://EXAMPLE.com:80/a/../b c") + # # => # + # URI::WHATWG_PARSER.parse("http://0x7f.1/") + # # => # + # + # A relative reference is only meaningful against a base URL, so it is + # resolved with #join or URI::Generic#merge rather than parsed alone: + # + # URI::WHATWG_PARSER.join("http://example.com/a/b", "../c") + # # => # + # URI::WHATWG_PARSER.parse("http://example.com/a") + "b" + # # => # + # URI::WHATWG_PARSER.parse("/relative") + # # raises URI::InvalidURIError + # + # Only http, https, ws, wss and file URLs become instances of their + # scheme's class; other schemes become URI::Generic. A non-ASCII domain + # is converted to ASCII (IDNA, UTS #46): + # + # URI::WHATWG_PARSER.parse("http://\u{65E5}\u{672C}\u{8A9E}.jp/").host + # # => "xn--wgv71a119e.jp" + # + # IDNA uses the Unicode data of the running Ruby, as String#upcase + # does, so a domain with a character added in a later version of + # Unicode than RbConfig::CONFIG["UNICODE_VERSION"], or than that of the + # data bundled for IDNA, is invalid. + # + # As ftp, mailto and ldap URLs become URI::Generic, code that relies on + # URI::FTP, URI::MailTo or URI::LDAP, such as URI.open of open-uri for + # ftp, does not work for them. + # + # The setters of a URI it builds follow the setters of the URL + # Standard, and raise URI::InvalidComponentError for a value that the + # URL Standard ignores: + # + # uri = URI::WHATWG_PARSER.parse("http://example.com/") + # uri.port = "8080abc" + # uri.to_s + # # => "http://example.com:8080/" + # + # As for any URI, scheme= does not change the class of the object. + # Parse the URI again to get the class of its new scheme: + # + # uri.scheme = "https" + # uri + # # => # + # URI::WHATWG_PARSER.parse(uri.to_s) + # # => # + WHATWG_PARSER = WHATWG_Parser.new + Ractor.make_shareable(WHATWG_PARSER) if defined?(Ractor) + # The default parser instance. DEFAULT_PARSER = RFC3986_PARSER Ractor.make_shareable(DEFAULT_PARSER) if defined?(Ractor) diff --git a/lib/uri/generic.rb b/lib/uri/generic.rb index fce8a8a5..eab95ef6 100644 --- a/lib/uri/generic.rb +++ b/lib/uri/generic.rb @@ -866,6 +866,24 @@ def query=(v) @query = v end + # + # == Args + # + # +v+:: + # String + # + # == Description + # + # Protected setter for the query component +v+, without the escaping + # done by #query=. + # + # See also URI::Generic.query=. + # + def set_query(v) + @query = v + end + protected :set_query + # # Checks the opaque +v+ component for RFC2396 compliance and # against the +parser+ Regexp for :OPAQUE. @@ -1215,6 +1233,7 @@ def route_from_path(src, dst) # :startdoc: # :stopdoc: + def route_from0(oth) oth = parser.__send__(:convert_to_uri, oth) if self.relative? @@ -1602,3 +1621,5 @@ def self.use_proxy?(hostname, addr, port, no_proxy) # :nodoc: end end end + +require_relative "whatwg_parser/setters" diff --git a/lib/uri/whatwg_parser.rb b/lib/uri/whatwg_parser.rb new file mode 100644 index 00000000..0526e35b --- /dev/null +++ b/lib/uri/whatwg_parser.rb @@ -0,0 +1,874 @@ +# frozen_string_literal: true +require_relative "whatwg_parser/punycode" +require_relative "whatwg_parser/nfc" +require_relative "whatwg_parser/idna" + +# A require in a non-main Ractor is not safe before Ruby 4.0, which runs +# it in the main Ractor. Where Ractors are available before that, the +# Unicode data, otherwise loaded on first use, is loaded here. +if defined?(Ractor) && (RUBY_VERSION.split(".").map(&:to_i) <=> [4, 0]) < 0 + URI::WHATWG_Parser::IDNA.load_data + URI::WHATWG_Parser::NFC.load_tables +end + +module URI + # A parser for the WHATWG URL Standard (https://url.spec.whatwg.org/). + # + # It is not the default parser. Use it explicitly with + # URI::WHATWG_PARSER.parse, or switch to it with + # URI.parser = URI::WHATWG_PARSER. + class WHATWG_Parser # :nodoc: + # A URL record (https://url.spec.whatwg.org/#concept-url). +path+ is an + # Array of segments, or a String for an opaque path. +port+ is an + # Integer, or nil when it is empty or the scheme's default port. + URLRecord = Struct.new(:scheme, :username, :password, :host, :port, :path, :query, :fragment) # :nodoc: + + # Returns [scheme, userinfo, host, port, registry, path, opaque, query, + # fragment], the same contract as URI::RFC3986_Parser#split. + def split(uri) # :nodoc: + begin + uri = uri.to_str + rescue NoMethodError + raise InvalidURIError, "bad URI (is not URI?): #{uri.inspect}" + end + to_components(basic_parse(uri)) + end + + def parse(uri) # :nodoc: + build(split(uri)) + end + + # Resolves each of +uris+ after the first against the result so far, + # as the URL Standard's basic URL parser does with a base URL. + def join(*uris) # :nodoc: + uris[1..-1].inject(convert_to_uri(uris[0])) do |base, uri| + reference = uri.is_a?(URI::Generic) ? uri.to_s : String.try_convert(uri) + raise ArgumentError, "bad argument (expected URI object or URI string)" unless reference + build(to_components(basic_parse(reference, url_record(base)))) + end + end + + # Component syntax used by URI::Generic's setters is shared with + # URI::RFC3986_Parser. + def regexp # :nodoc: + RFC3986_PARSER.regexp + end + + # Compatibility for RFC2396 parser + def extract(str, schemes = nil, &block) # :nodoc: + warn "URI::WHATWG_PARSER.extract is obsolete. Use URI::RFC2396_PARSER.extract explicitly.", uplevel: 1 if $VERBOSE + RFC2396_PARSER.extract(str, schemes, &block) + end + + # Compatibility for RFC2396 parser + def make_regexp(schemes = nil) # :nodoc: + warn "URI::WHATWG_PARSER.make_regexp is obsolete. Use URI::RFC2396_PARSER.make_regexp explicitly.", uplevel: 1 if $VERBOSE + RFC2396_PARSER.make_regexp(schemes) + end + + # Compatibility for RFC2396 parser + def escape(str, unsafe = nil) # :nodoc: + warn "URI::WHATWG_PARSER.escape is obsolete. Use URI::RFC2396_PARSER.escape explicitly.", uplevel: 1 if $VERBOSE + unsafe ? RFC2396_PARSER.escape(str, unsafe) : RFC2396_PARSER.escape(str) + end + + # Compatibility for RFC2396 parser + def unescape(str, escaped = nil) # :nodoc: + warn "URI::WHATWG_PARSER.unescape is obsolete. Use URI::RFC2396_PARSER.unescape explicitly.", uplevel: 1 if $VERBOSE + escaped ? RFC2396_PARSER.unescape(str, escaped) : RFC2396_PARSER.unescape(str) + end + + private + + # basic URL parser, with an optional +base+ URL record. + def basic_parse(input, base = nil) + input = preprocess(to_utf8(input)) + + scheme, rest = parse_scheme(input) + relative = scheme.nil? + if relative + # no scheme state + raise InvalidURIError, "missing scheme: #{input.dump}" unless base + if base.path.is_a?(String) && !rest.start_with?("#") + raise InvalidURIError, "relative reference to a URL with an opaque path: #{input.dump}" + end + scheme = base.scheme + # The file state handles a reference relative to a file URL. + relative = false if scheme == "file" + elsif base && scheme == base.scheme && scheme != "file" && SPECIAL_SCHEMES.key?(scheme) + # special relative or authority state: two slashes start an + # authority; anything else is relative to the base. + relative = !rest.match?(TWO_SLASHES) + end + + # Every state before the fragment state ends at the first "#", and + # every state before the query state at the first "?" before it. + rest, query, fragment = split_query_and_fragment(rest) + + url = URLRecord.new(scheme, "", "", nil, nil, [], nil, nil) + special = SPECIAL_SCHEMES.key?(scheme) + # query state and fragment state + url.query = query && utf8_percent_encode(query, special ? SPECIAL_QUERY_PERCENT_ENCODE_SET : QUERY_PERCENT_ENCODE_SET) + url.fragment = fragment && utf8_percent_encode(fragment, FRAGMENT_PERCENT_ENCODE_SET) + + if relative + parse_relative(url, rest, base, special) + elsif scheme == "file" + parse_file(url, rest, base&.scheme == "file" ? base : nil) + elsif special + # special authority slashes state and special authority ignore + # slashes state: skip any run of "/" or "\\". + parse_authority(url, rest.sub(SPECIAL_AUTHORITY_SLASHES, ""), true) + elsif rest.start_with?("/") + # path or authority state + if rest.start_with?("//") + parse_authority(url, rest[2..-1], false) + else + url.path = parse_path(rest, false) + end + else + url.path = parse_opaque_path(rest, query || fragment) + end + url + end + + # relative state and relative slash state. +rest+ is the input after + # any scheme, without query and fragment, which +url+ already has. + def parse_relative(url, rest, base, special) + if base.path.is_a?(String) + # no scheme state, for a base with an opaque path: only a + # fragment may be given. + url.path = base.path + url.query = base.query + return + end + + if rest.start_with?("/") || (special && rest.start_with?("\\")) + # relative slash state + if special && rest.match?(TWO_SLASHES) + return parse_authority(url, rest.sub(SPECIAL_AUTHORITY_SLASHES, ""), true) + elsif !special && rest.start_with?("//") + return parse_authority(url, rest[2..-1], false) + end + copy_authority(url, base) + url.path = parse_path(rest, special) + else + copy_authority(url, base) + if rest.empty? + # c is EOF, "?" or "#": the base path, and the base query unless + # a query is given. + url.path = base.path.dup + url.query = base.query if url.query.nil? + else + path = base.path.dup + shorten(path, false) + url.path = parse_path(rest, special, path) + end + end + end + + # file state, file slash state and file host state. +base+ is the + # base URL if it is a file URL. +rest+ is the input after any scheme, + # without query and fragment, which +url+ already has. + def parse_file(url, rest, base) + url.host = "" + if rest.start_with?("/", "\\") + rest = rest[1..-1] + # file slash state + return parse_file_host(url, rest[1..-1]) if rest.start_with?("/", "\\") + if base + url.host = base.host + if !starts_with_windows_drive_letter?(rest) && normalized_windows_drive_letter?(base.path[0]) + url.path = [base.path[0]] + end + end + url.path = parse_path(rest, true, url.path, file: true, start: false) + elsif base + url.host = base.host + url.path = base.path.dup + if rest.empty? + # c is EOF, "?" or "#": the base query too, unless a query is given. + url.query = base.query if url.query.nil? + else + if starts_with_windows_drive_letter?(rest) + url.path = [] + else + shorten(url.path, true) + end + url.path = parse_path(rest, true, url.path, file: true, start: false) + end + else + url.path = parse_path(rest, true, [], file: true, start: false) + end + end + + # file host state. +rest+ starts after the two slashes. + def parse_file_host(url, rest) + host_end = rest.index(SPECIAL_PATH_SEPARATOR) || rest.size + buffer = rest[0, host_end] + if windows_drive_letter?(buffer) + # The buffer is not a host but the start of the path. + url.path = parse_path(rest, true, [], file: true, start: false) + return + end + url.host = file_host(buffer) + url.path = parse_path(rest[host_end..-1], true, [], file: true) + end + + # The host of a file URL, which is empty for an empty +buffer+ or + # localhost. + def file_host(buffer) + return "" if buffer.empty? + host = parse_host(buffer, true) + host == "localhost" ? "" : host + end + + # https://url.spec.whatwg.org/#windows-drive-letter + def windows_drive_letter?(string) + string.match?(WINDOWS_DRIVE_LETTER) + end + + def normalized_windows_drive_letter?(string) + string.to_s.match?(NORMALIZED_WINDOWS_DRIVE_LETTER) + end + + # https://url.spec.whatwg.org/#start-with-a-windows-drive-letter + def starts_with_windows_drive_letter?(string) + string.match?(STARTS_WITH_WINDOWS_DRIVE_LETTER) + end + + # shorten a URL's path: a file URL's path that is only a normalized + # Windows drive letter is kept. + def shorten(path, file) + return if file && path.size == 1 && normalized_windows_drive_letter?(path[0]) + path.pop + end + + def copy_authority(url, base) + url.username = base.username + url.password = base.password + url.host = base.host + url.port = base.port + end + + # Creates the URI object for +components+. + # + # Scheme-specific classes are used only for the schemes in + # SCHEMES_WITH_CLASS, whose rules agree with the URL Standard; any + # other scheme gets URI::Generic. (URI::FTP rewrites the path by RFC + # 1738 rules, URI::MailTo validates the opaque part, and URI::LDAP + # omits its default port.) + # + # The query is set afterwards with URI::Generic#set_query, as the + # constructor would re-escape it by RFC 3986 rules with + # URI::Generic#query=. + def build(components) + *components, query, fragment = components + arguments = [*components, nil, fragment, self] + uri = SCHEMES_WITH_CLASS.include?(components[0]) ? URI.for(*arguments) : Generic.new(*arguments) + uri.__send__(:set_query, query) if query + uri.__send__(:whatwg_url!) + uri + end + + # The URL record as the components of URI::RFC3986_Parser#split. + def to_components(url) + userinfo = + if url.password.empty? + url.username.empty? ? nil : url.username + else + "#{url.username}:#{url.password}" + end + port = url.port&.to_s + + if url.path.is_a?(String) + # The query is kept inside opaque, as URI::RFC3986_Parser does, + # since URI::Generic does not serialize the query of an opaque URI. + opaque = url.query ? "#{url.path}?#{url.query}" : url.path + [url.scheme, userinfo, url.host, port, nil, nil, opaque, nil, url.fragment] + else + path = serialize_path(url.path) + # The URL serializer writes "/." before a hostless path that would + # otherwise start with "//", so it is not mistaken for an + # authority when reparsed. + path = "/.#{path}" if url.host.nil? && url.path.size > 1 && url.path[0].empty? + [url.scheme, userinfo, url.host, port, nil, path, nil, url.query, url.fragment] + end + end + + # The URL record of +uri+. The components of a URI that this parser + # built are those of a URL record, already serialized, so the record + # is rebuilt from them, the reverse of #to_components; any other URI + # is parsed. The strings are copied, as a URI built from the record + # must not share them with +uri+. + def url_record(uri) + return basic_parse(uri.to_s) unless uri.__send__(:whatwg_url?) + + scheme = uri.scheme.dup + port = uri.port == SPECIAL_SCHEMES[scheme] ? nil : uri.port + url = URLRecord.new(scheme, uri.user.to_s.dup, uri.password.to_s.dup, uri.host&.dup, port, nil, + uri.query&.dup, uri.fragment&.dup) + if uri.opaque + path, question, query = uri.opaque.partition("?") + url.path = path + url.query = question.empty? ? nil : query + else + path = uri.path + path = path[2..-1] if url.host.nil? && path.start_with?("/.//") + # Each segment follows a "/". + url.path = path.split("/", -1).drop(1) + end + url + end + + def split_query_and_fragment(rest) + rest, hash, fragment = rest.partition("#") + fragment = nil if hash.empty? + rest, question, query = rest.partition("?") + query = nil if question.empty? + [rest, query, fragment] + end + + # opaque path state: code points in the C0 control percent-encode set + # are percent-encoded, and a space right before "?" or "#" (when + # +followed+ by a query or fragment) is written as "%20". + def parse_opaque_path(input, followed) + opaque = utf8_percent_encode(input, C0_CONTROL_PERCENT_ENCODE_SET) + followed ? opaque.sub(TRAILING_SPACE, "%20") : opaque + end + + # https://url.spec.whatwg.org/#special-scheme + SPECIAL_SCHEMES = { + "ftp" => 21, + "file" => nil, + "http" => 80, + "https" => 443, + "ws" => 80, + "wss" => 443, + }.freeze # :nodoc: + + SCHEMES_WITH_CLASS = %w[http https ws wss file].freeze # :nodoc: + + # scheme start state and scheme state: an ASCII alpha followed by + # ASCII alphanumerics, "+", "-" or ".", up to the first ":". + SCHEME = /\A[A-Za-z][A-Za-z0-9+\-.]*:/ # :nodoc: + + SPECIAL_AUTHORITY_SLASHES = %r{\A[/\\]*} # :nodoc: + # Two of "/" or "\\", which start an authority in a special URL. + TWO_SLASHES = %r{\A[/\\]{2}} # :nodoc: + WINDOWS_DRIVE_LETTER = /\A[A-Za-z][:|]\z/ # :nodoc: + NORMALIZED_WINDOWS_DRIVE_LETTER = /\A[A-Za-z]:\z/ # :nodoc: + STARTS_WITH_WINDOWS_DRIVE_LETTER = %r{\A[A-Za-z][:|](?:\z|[/\\?#])} # :nodoc: + AUTHORITY_END = %r{[/?#]} # :nodoc: + SPECIAL_AUTHORITY_END = %r{[/?#\\]} # :nodoc: + + # https://url.spec.whatwg.org/#forbidden-host-code-point + FORBIDDEN_HOST_CODE_POINT = %r{[\x00\t\n\r #/:<>?@\[\\\]^|]} # :nodoc: + # https://url.spec.whatwg.org/#forbidden-domain-code-point + # (forbidden host code points, C0 controls, "%" and U+007F DELETE) + FORBIDDEN_DOMAIN_CODE_POINT = %r{[\x00-\x20#/:<>?@\[\\\]^|%\x7F]} # :nodoc: + # Percent-encode sets, https://url.spec.whatwg.org/#percent-encoded-bytes. + # Each one adds to the previous one; [^\x00-\x7E] is every code point + # greater than U+007E. + # + # C0 controls and code points greater than U+007E + C0_CONTROL_PERCENT_ENCODE_SET = /[\x00-\x1F]|[^\x00-\x7E]/ # :nodoc: + # + U+0020 SPACE, U+0022 ("), U+003C (<), U+003E (>), U+0060 (`) + FRAGMENT_PERCENT_ENCODE_SET = /[\x00-\x20"<>`]|[^\x00-\x7E]/ # :nodoc: + # C0 control set + U+0020 SPACE, U+0022 ("), U+0023 (#), U+003C (<), U+003E (>) + QUERY_PERCENT_ENCODE_SET = /[\x00-\x20"#<>]|[^\x00-\x7E]/ # :nodoc: + # query set + U+0027 (') + SPECIAL_QUERY_PERCENT_ENCODE_SET = /[\x00-\x20"#<>']|[^\x00-\x7E]/ # :nodoc: + # query set + U+003F (?), U+005E (^), U+0060 (`), U+007B ({), U+007D (}) + PATH_PERCENT_ENCODE_SET = /[\x00-\x20"#<>?^`{}]|[^\x00-\x7E]/ # :nodoc: + # path set + U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+0040 (@), + # U+005B ([) to U+005E (^), U+007C (|) + USERINFO_PERCENT_ENCODE_SET = %r{[\x00-\x20"#<>?^`{}/:;=@\[\\\]|]|[^\x00-\x7E]} # :nodoc: + PERCENT_ENCODED_BYTE = /%[0-9A-Fa-f]{2}/ # :nodoc: + + ASCII_DIGITS = /\A[0-9]+\z/ # :nodoc: + ASCII_DIGIT = /\A[0-9]\z/ # :nodoc: + ASCII_HEX_DIGIT = /\A[0-9A-Fa-f]\z/ # :nodoc: + IPV4_NUMBER_DIGITS = { + 8 => /\A[0-7]+\z/, + 10 => /\A[0-9]+\z/, + 16 => /\A[0-9A-Fa-f]+\z/, + }.freeze # :nodoc: + LEADING_ZEROS = /\A0+/ # :nodoc: + # 2**32 - 1 has 11 digits in octal, 10 in decimal and 8 in hex. + IPV4_NUMBER_MAX_DIGITS = 11 # :nodoc: + + MAX_PORT = 2**16 - 1 # :nodoc: + PORT_MAX_DIGITS = MAX_PORT.to_s.size # :nodoc: + + TRAILING_SPACE = / \z/ # :nodoc: + SPECIAL_PATH_SEPARATOR = %r{[/\\]} # :nodoc: + DOUBLE_DOT_SEGMENTS = ["..", ".%2e", "%2e.", "%2e%2e"].freeze # :nodoc: + + NOT_C0_CONTROL_OR_SPACE = /[^\x00-\x20]/ # :nodoc: + ASCII_TAB_OR_NEWLINE = "\t\n\r" # :nodoc: + + # The URL Standard parses a string of Unicode scalar values. + def to_utf8(input) + raise InvalidURIError, "invalid byte sequence: #{input.dump}" unless input.valid_encoding? + input.encode(Encoding::UTF_8) + rescue EncodingError + raise InvalidURIError, "cannot be converted to UTF-8: #{input.dump}" + end + + # basic URL parser, steps 1-3: strip leading and trailing C0 control + # or space, then remove all ASCII tab or newline. + # + # The ends are found with index/rindex rather than an anchored + # regexp such as /[\x00-\x20]+\z/, which backtracks quadratically on + # long inner runs of spaces. + def preprocess(input) + first = input.index(NOT_C0_CONTROL_OR_SPACE) or return +"" + last = input.rindex(NOT_C0_CONTROL_OR_SPACE) + input[first..last].delete(ASCII_TAB_OR_NEWLINE) + end + + # scheme start state and scheme state. Returns the ASCII-lowercased + # scheme and the rest of +input+ after the ":", or nil and +input+ + # when there is no scheme. + def parse_scheme(input) + scheme = input[SCHEME] or return [nil, input] + [scheme.chop.downcase, input[scheme.size..-1]] + end + + # authority state, host state, port state and the path after them. + # +rest+ starts right after the slashes preceding the authority. + def parse_authority(url, rest, special) + authority_end = rest.index(special ? SPECIAL_AUTHORITY_END : AUTHORITY_END) || rest.size + authority = rest[0, authority_end] + remainder = rest[authority_end..-1] + + url.username, url.password, host_and_port = split_userinfo(authority) + host, port = split_host_and_port(host_and_port) + raise InvalidURIError, "missing host: #{rest.dump}" if host.empty? && (special || port) + url.host = host.empty? ? host : parse_host(host, special) + url.port = parse_port(port, url.scheme) if port + url.path = parse_path(remainder, special) + end + + # path start state (unless +start+ is false) and path state. Returns + # the list of path segments, appended to +path+ (the shortened base + # path of a relative reference). +file+ applies the Windows drive + # letter rules of file URLs. + def parse_path(input, special, path = [], file: false, start: true) + separator = special ? SPECIAL_PATH_SEPARATOR : "/" + if start + # path start state: a special URL always has a path, even an + # empty one; another URL has one only if anything follows the + # authority. + return path if input.empty? && !special + input = input[1..-1] if input.start_with?("/") || (special && input.start_with?("\\")) + end + + buffers = input.split(separator, -1) + buffers = [""] if buffers.empty? + buffers.each_with_index.with_object(path) do |(buffer, i), segments| + buffer = utf8_percent_encode(buffer, PATH_PERCENT_ENCODE_SET) + # Whether this segment is ended by the end of the path rather + # than by a separator. + last = i == buffers.size - 1 + if double_dot_segment?(buffer) + shorten(segments, file) + segments << "" if last + elsif single_dot_segment?(buffer) + segments << "" if last + else + if file && segments.empty? && windows_drive_letter?(buffer) + buffer = "#{buffer[0]}:" + end + segments << buffer + end + end + end + + def serialize_path(segments) + segments.map { |segment| "/#{segment}" }.join + end + + # https://url.spec.whatwg.org/#single-dot-path-segment + def single_dot_segment?(buffer) + buffer == "." || buffer.downcase == "%2e" + end + + # https://url.spec.whatwg.org/#double-dot-path-segment + def double_dot_segment?(buffer) + DOUBLE_DOT_SEGMENTS.include?(buffer.downcase) + end + + # authority state, on "@": the last "@" ends the userinfo, and every + # earlier one is part of it, as "%40". The first ":" separates the + # username from the password. Returns the percent-encoded username + # and password, and the rest. + def split_userinfo(authority) + at = authority.rindex("@") or return ["", "", authority] + host_and_port = authority[at + 1..-1] + raise InvalidURIError, "missing host after userinfo: #{authority.dump}" if host_and_port.empty? + + username, _, password = authority[0, at].gsub("@", "%40").partition(":") + [utf8_percent_encode(username, USERINFO_PERCENT_ENCODE_SET), + utf8_percent_encode(password, USERINFO_PERCENT_ENCODE_SET), + host_and_port] + end + + # host state: the first ":" outside "[...]" starts the port. + def split_host_and_port(host_and_port) + inside_brackets = false + host_and_port.each_char.with_index do |c, i| + case c + when "[" then inside_brackets = true + when "]" then inside_brackets = false + when ":" + return [host_and_port[0, i], host_and_port[i + 1..-1]] unless inside_brackets + end + end + [host_and_port, nil] + end + + # port state. +input+ is everything between the ":" and the end of + # the authority. Returns the port, or nil when it is empty or the + # scheme's default port. + # + # A port with more significant digits than 65535 has is rejected + # without converting it. + def parse_port(input, scheme) + return nil if input.empty? + raise InvalidURIError, "invalid port: #{input.dump}" unless input.match?(ASCII_DIGITS) + + port = port_number(input) + raise InvalidURIError, "port out of range: #{input.dump}" if port > MAX_PORT + port == SPECIAL_SCHEMES[scheme] ? nil : port + end + + # The number that +digits+, ASCII digits, represent. A number with + # more significant digits than MAX_PORT is MAX_PORT + 1 instead of + # being converted. + def port_number(digits) + digits = digits.sub(LEADING_ZEROS, "") + digits.size > PORT_MAX_DIGITS ? MAX_PORT + 1 : digits.to_i + end + + # host parser + def parse_host(input, special) + if input.start_with?("[") + raise InvalidURIError, "unterminated IPv6 address: #{input.dump}" unless input.end_with?("]") + return "[#{serialize_ipv6(parse_ipv6(input[1..-2]))}]" + end + return parse_opaque_host(input) unless special + + ascii_domain = domain_to_ascii(percent_decode(input)) + raise InvalidURIError, "invalid host: #{input.dump}" unless ascii_domain + return serialize_ipv4(parse_ipv4(ascii_domain)) if ends_in_a_number?(ascii_domain) + ascii_domain + end + + # domain to ASCII (the domain parser) with beStrict false. Returns nil + # on failure. + # + # An ASCII domain is lowercased without Unicode ToASCII, so an "xn--" + # label in it is not validated. + def domain_to_ascii(domain) + result = domain.ascii_only? ? domain.downcase : IDNA.to_ascii(domain) + return nil if result.nil? || result.empty? || result.match?(FORBIDDEN_DOMAIN_CODE_POINT) + result + end + + # ends in a number checker + def ends_in_a_number?(input) + parts = input.split(".", -1) + if parts.last.empty? + return false if parts.size == 1 + parts.pop + end + last = parts.last + return true if last.match?(ASCII_DIGITS) + !parse_ipv4_number(last).nil? + end + + # IPv4 parser + def parse_ipv4(input) + parts = input.split(".", -1) + parts.pop if parts.last.empty? && parts.size > 1 + raise InvalidURIError, "invalid IPv4 address: #{input.dump}" if parts.size > 4 + + numbers = parts.map do |part| + parse_ipv4_number(part) or raise InvalidURIError, "invalid IPv4 address: #{input.dump}" + end + last = numbers.pop + if numbers.any? { |n| n > 255 } || last >= 256**(4 - numbers.size) + raise InvalidURIError, "invalid IPv4 address: #{input.dump}" + end + + numbers.each_with_index.inject(last) { |ipv4, (n, i)| ipv4 + n * 256**(3 - i) } + end + + # IPv4 number parser. Returns nil on failure. + # + # Any value of 2**32 or more makes the IPv4 parser fail, so a number + # with more significant digits than 2**32 - 1 has in any radix is + # returned as 2**32 instead of being converted. + def parse_ipv4_number(input) + return nil if input.empty? + + radix = 10 + if input.size >= 2 && input.start_with?("0x", "0X") + input = input[2..-1] + radix = 16 + elsif input.size >= 2 && input.start_with?("0") + input = input[1..-1] + radix = 8 + end + return 0 if input.empty? + return nil unless input.match?(IPV4_NUMBER_DIGITS.fetch(radix)) + + digits = input.sub(LEADING_ZEROS, "") + return 2**32 if digits.size > IPV4_NUMBER_MAX_DIGITS + digits.to_i(radix) + end + + # IPv6 parser. Follows the standard's algorithm step by step, reading + # +input+ one code point at a time with +pointer+. + def parse_ipv6(input) + failure = -> { raise InvalidURIError, "invalid IPv6 address: #{"[#{input}]".dump}" } + failure.() unless input.ascii_only? + + address = [0] * 8 + piece_index = 0 + compress = nil + pointer = 0 + c = -> { input[pointer] } + + if c.() == ":" + failure.() unless input[pointer + 1] == ":" + pointer += 2 + piece_index += 1 + compress = piece_index + end + + while c.() + failure.() if piece_index == 8 + + if c.() == ":" + failure.() if compress + pointer += 1 + piece_index += 1 + compress = piece_index + next + end + + value = length = 0 + while length < 4 && c.()&.match?(ASCII_HEX_DIGIT) + value = value * 0x10 + c.().hex + pointer += 1 + length += 1 + end + + if c.() == "." + failure.() if length == 0 + pointer -= length + failure.() if piece_index > 6 + + numbers_seen = 0 + while c.() + ipv4_piece = nil + if numbers_seen > 0 + failure.() unless c.() == "." && numbers_seen < 4 + pointer += 1 + end + failure.() unless c.()&.match?(ASCII_DIGIT) + while c.()&.match?(ASCII_DIGIT) + number = c.().to_i + if ipv4_piece.nil? + ipv4_piece = number + elsif ipv4_piece == 0 + failure.() + else + ipv4_piece = ipv4_piece * 10 + number + end + failure.() if ipv4_piece > 255 + pointer += 1 + end + address[piece_index] = address[piece_index] * 0x100 + ipv4_piece + numbers_seen += 1 + piece_index += 1 if numbers_seen == 2 || numbers_seen == 4 + end + failure.() unless numbers_seen == 4 + break + elsif c.() == ":" + pointer += 1 + failure.() unless c.() + elsif c.() + failure.() + end + + address[piece_index] = value + piece_index += 1 + end + + if compress + swaps = piece_index - compress + piece_index = 7 + while piece_index != 0 && swaps > 0 + address[piece_index], address[compress + swaps - 1] = address[compress + swaps - 1], address[piece_index] + piece_index -= 1 + swaps -= 1 + end + elsif piece_index != 8 + failure.() + end + + address + end + + # IPv6 serializer (without the surrounding brackets): the first + # longest run of two or more zero pieces is written as "::". + def serialize_ipv6(address) + compress = longest_zero_run(address) + output = +"" + ignore0 = false + address.each_with_index do |piece, piece_index| + next if ignore0 && piece == 0 + ignore0 = false + if compress == piece_index + output << (piece_index == 0 ? "::" : ":") + ignore0 = true + next + end + output << piece.to_s(16) + output << ":" unless piece_index == 7 + end + output + end + + # Index of the first longest run of two or more zero pieces, or nil. + def longest_zero_run(address) + best = nil + best_length = 1 + run_start = nil + (address + [nil]).each_with_index do |piece, i| + if piece == 0 + run_start ||= i + elsif run_start + if i - run_start > best_length + best = run_start + best_length = i - run_start + end + run_start = nil + end + end + best + end + + # IPv4 serializer + def serialize_ipv4(address) + [24, 16, 8, 0].map { |shift| (address >> shift) & 0xFF }.join(".") + end + + # opaque-host parser + def parse_opaque_host(input) + raise InvalidURIError, "invalid host: #{input.dump}" if input.match?(FORBIDDEN_HOST_CODE_POINT) + utf8_percent_encode(input, C0_CONTROL_PERCENT_ENCODE_SET) + end + + # percent-decode, then UTF-8 decode without BOM (invalid sequences + # become U+FFFD). + def percent_decode(input) + input.b.gsub(PERCENT_ENCODED_BYTE) { $&[1, 2].hex.chr }.force_encoding(Encoding::UTF_8).scrub + end + + def utf8_percent_encode(input, encode_set) + input.gsub(encode_set) { |c| c.unpack("C*").map { |b| format("%%%02X", b) }.join } + end + + # Generic#merge. The URL Standard resolves a reference while parsing + # it against a base. A relative +base+, which Generic#route_to can + # return, is merged with an absolute URI only, as in Generic#merge. + def merge(base, reference) + return join(base, reference) if base.absolute? + absolute_uri(reference) or raise BadURIError, "both URI are relative" + end + + # Generic#route_from: the first of the references from #route_candidates + # that resolves to +target+ against +base+, or a copy of +target+. + def route(base, target) + expected = target.to_s + route_candidates(base, target).each do |reference| + return reference if resolves_to?(base, reference, expected) + end + target.dup + end + + # The references that may resolve to +target+ against +base+, shortest + # first: the fragment, the query, the path relative to the path of + # +base+, the path, and the authority with the path. A URL with an + # opaque path is the base of a fragment only. + # + # The relative path is empty for the path of +base+, which keeps the + # query of +base+, so its last segment is tried too. + def route_candidates(base, target) + return [] unless base.scheme == target.scheme + + query = target.query + fragment = target.fragment + candidates = [relative_reference(fragment: fragment)] + return candidates if base.opaque || target.opaque + + candidates << relative_reference(query: query, fragment: fragment) if query + path = target.path + relative_path = target.__send__(:route_from_path, base.path, path) + candidates << relative_reference(path: relative_path, query: query, fragment: fragment) + if relative_path.empty? + segment = path[%r{[^/]*\z}] + segment = "./#{segment}" if segment.empty? || segment.include?(":") + candidates << relative_reference(path: segment, query: query, fragment: fragment) + end + candidates << relative_reference(path: path, query: query, fragment: fragment) + port = target.port == SPECIAL_SCHEMES[target.scheme] ? nil : target.port + candidates << relative_reference(userinfo: target.userinfo, host: target.host, port: port, + path: path, query: query, fragment: fragment) + end + + def resolves_to?(base, reference, expected) + join(base, reference).to_s == expected + rescue InvalidURIError + false + end + + # A relative URI bound to this parser. The query, which may hold + # characters that Generic#query= would escape, is set as it is. + def relative_reference(userinfo: nil, host: nil, port: nil, path: "", query: nil, fragment: nil) + uri = Generic.new(nil, userinfo, host, port, nil, path, nil, nil, fragment, self) + uri.__send__(:set_query, query) if query + uri + end + + # Returns +uri+ converted to a URI if it is absolute, or nil if it is + # a relative reference. + def absolute_uri(uri) + return (uri.absolute? ? uri : nil) if uri.is_a?(URI::Generic) + + str = String.try_convert(uri) + raise ArgumentError, "bad argument (expected URI object or URI string)" unless str + scheme, = parse_scheme(preprocess(to_utf8(str))) + scheme ? parse(str) : nil + end + + # A URI that this parser built, or the relative URI that + # Generic#route_to returned for one, is returned as it is; a URI that + # another parser built is parsed, as its string would be. + def convert_to_uri(uri) + if uri.is_a?(URI::Generic) + uri.parser.is_a?(WHATWG_Parser) ? uri : parse(uri.to_s) + elsif uri = String.try_convert(uri) + parse(uri) + else + raise ArgumentError, + "bad argument (expected URI object or URI string)" + end + end + end +end diff --git a/lib/uri/whatwg_parser/idna.rb b/lib/uri/whatwg_parser/idna.rb new file mode 100644 index 00000000..c2355373 --- /dev/null +++ b/lib/uri/whatwg_parser/idna.rb @@ -0,0 +1,270 @@ +# frozen_string_literal: true +module URI + class WHATWG_Parser + # Domain to ASCII (https://url.spec.whatwg.org/#concept-domain-to-ascii) + # for a domain that is not ASCII: Unicode ToASCII (UTS #46, + # https://www.unicode.org/reports/tr46/) with CheckHyphens=false, + # CheckBidi=true, CheckJoiners=true, UseSTD3ASCIIRules=false, + # Transitional_Processing=false, VerifyDnsLength=false and + # IgnoreInvalidPunycode=false. + # + # The IDNA Mapping Table is not stored: the status and the mapping of + # each code point are derived as UTS #46 section 6 does, from the + # Unicode data of the running Ruby (its character properties, case + # folding and the tables of NFC and NFKC), so a code point added in a + # later Unicode version is disallowed. Only the Bidi_Class and + # Joining_Type values that the Bidi Rule and CONTEXTJ need, which Ruby + # has not, are generated (idna_data.rb). + # + # The data is loaded on first use, or with whatwg_parser.rb where a + # Ractor cannot require it safely. + module IDNA # :nodoc: + ACE_PREFIX = "xn--" + LABEL_SEPARATOR = "." + ZWNJ = 0x200C.chr(Encoding::UTF_8).freeze + ZWJ = 0x200D.chr(Encoding::UTF_8).freeze + + # Every code point the IDNA Mapping Table leaves unchanged is + # matched out; ASCII code points other than A-Z are among them. + MAPPING_CANDIDATE = /[A-Z]|[^\x00-\x7F]/ + UPPERCASE_ASCII = /\A[A-Z]\z/ + + # The Bidi Rule (RFC 5893 section 2), over a label whose code points + # are replaced by their Bidi_Class: L, R (R or AL), A (AN), E (EN), + # N (ES, CS, ET, ON or BN), M (NSM), or X (anything else). + BIDI_RTL = /[RA]/ + BIDI_FIRST = /\A[LR]/ + BIDI_RTL_ALLOWED = /\A[RAENM]*\z/ + BIDI_RTL_END = /[RAE]M*\z/ + BIDI_LTR_ALLOWED = /\A[LENM]*\z/ + BIDI_LTR_END = /[LE]M*\z/ + + # The sets of the Mapping Table Derivation (UTS #46 section 6). + LABEL_SEPARATORS = ["\u{FF0E}", "\u{3002}", "\u{FF61}"].freeze + CAPITAL_SHARP_S = "\u{1E9E}" + SHARP_S = "\u{DF}" + BIDI_CONTROL = /\p{Bidi_Control}/ + DEFAULT_IGNORABLE = /\p{Default_Ignorable_Code_Point}/ + OTHER_OR_SEPARATOR = /[\p{C}\p{Z}]/ + IDS_OPERATOR = + begin + # Regexp.new, unlike a literal, is not frozen. + Regexp.new("[\\p{IDS_Unary_Operator}\\p{IDS_Binary_Operator}\\p{IDS_Trinary_Operator}]").freeze + rescue RegexpError + # IDS_Unary_Operator is new in Unicode 15.1, with U+2FFE and U+2FFF. + /[\u{2FFE}\u{2FFF}\p{IDS_Binary_Operator}\p{IDS_Trinary_Operator}]/ + end + EXCLUDED = /[\u{FFFC}\u{FFFD}\u{E0001}-\u{E007F}]/ + UNASSIGNED = /\p{Cn}/ + DEVIATIONS = [ZWNJ, ZWJ, SHARP_S, "\u{3C2}"].freeze + + # General_Category=Mark. + MARK = /\p{M}/ + # Canonical_Combining_Class=Virama. + VIRAMA_CLASS = 9 + # The ASCII code points whose Bidi_Class (B, S or WS) is none that + # the Bidi Rule names. Every other valid code point not listed in + # idna_data.rb has Bidi_Class L. + BIDI_OTHER = /[\t\n\v\f\r\x1C-\x20]/ + + module_function + + # Returns the ASCII form of +domain+, or nil on failure. + def to_ascii(domain) + labels = process(domain) + return nil unless labels + labels.map { |label| label.ascii_only? ? label : ACE_PREFIX + Punycode.encode(label) }.join(LABEL_SEPARATOR) + end + + # UTS #46 Processing. Returns the labels in Unicode, or nil if an + # error is recorded. + def process(domain) + return nil unless domain.valid_encoding? + load_data + + # Deriving the status of a code point takes several + # normalizations, so each one is derived once per domain. + statuses = {} + mapped = domain.gsub(MAPPING_CANDIDATE) do |c| + st = status(c, statuses) + st.is_a?(String) ? st : c + end + labels = NFC.normalize(mapped).split(LABEL_SEPARATOR, -1) + labels.map! do |label| + label = decode_label(label) if label.start_with?(ACE_PREFIX) + return nil unless label && valid_label?(label, statuses) + label + end + return nil if bidi_domain?(labels) && !labels.all? { |label| satisfies_bidi_rule?(label) } + labels + end + + def load_data + require_relative "idna_data" unless const_defined?(:BIDI_NSM, false) + NFC.load_tables + end + + # Steps 6 and 7 of the Mapping Table Derivation for +c+: true if its + # status is valid or deviation, its mapping (an empty string if it + # is ignored) if it is mapped, or false if it is disallowed. + # +statuses+ caches the result by code point. + def status(c, statuses = {}) + statuses.fetch(c) { statuses[c] = derive_status(c, statuses) } + end + + def derive_status(c, statuses) + return c.downcase if UPPERCASE_ASCII.match?(c) + return c != LABEL_SEPARATOR if c.ord < 0x80 + return true if DEVIATIONS.include?(c) + return false if c.match?(EXCLUDED) || unknown?(c) + mapping = base_mapping(c) + return base_valid?(c) if mapping == c + return false unless LABEL_SEPARATORS.include?(c) || mapping.each_char.all? { |m| base_valid?(m) } + # Step 7: a mapping that is not wholly valid is disallowed, such + # as the U+3002 of U+FE12, which is mapped itself. A mapping is + # stable under NFKC_Casefold, so this needs no repeating. + return false unless mapping.each_char.all? { |m| m == LABEL_SEPARATOR || status(m, statuses) == true } + mapping + end + + # Whether +c+ is unassigned in the Unicode version of the running + # Ruby, or assigned after that of the generated data, whose + # Bidi_Class and Joining_Type values it does not have. + def unknown?(c) + c.match?(UNASSIGNED) || (!NEWER_THAN_DATA.nil? && c.match?(NEWER_THAN_DATA)) + end + + # A pattern of the code points assigned after Unicode +version+, or + # nil when the running Ruby does not know +version+, so knows no + # later one either. + def newer_than(version) + Regexp.new("(?!\\p{Age=#{version[/\A\d+\.\d+/]}})\\P{Cn}").freeze + rescue RegexpError + nil + end + + # Step 1: the base mapping of +c+. + def base_mapping(c) + return LABEL_SEPARATOR if LABEL_SEPARATORS.include?(c) + return c if c.match?(BIDI_CONTROL) + return SHARP_S if c == CAPITAL_SHARP_S + nfkc_casefold(c) + end + + # Step 2: whether +c+ is in the base valid set. + def base_valid?(c) + return c != LABEL_SEPARATOR if c.ord < 0x80 + return true if c == SHARP_S + return false if c.match?(OTHER_OR_SEPARATOR) || c.match?(IDS_OPERATOR) + nfkc_casefold(c) == c + end + + # NFKC_Casefold: the closure of NFKC(toCasefold(NFKC(X))) with the + # default ignorable code points removed. + def nfkc_casefold(s) + # Most code points have no decomposition, which NFKC keeps as they + # are, and fold to themselves. + return s if s.size == 1 && stable_code_point?(s) + loop do + t = NFC.normalize_kc(NFC.normalize_kc(s).downcase(:fold)).gsub(DEFAULT_IGNORABLE, "") + return t if t == s + s = t + end + end + + # Whether NFKC and case folding leave the code point +c+ unchanged, + # and it is not default ignorable, so NFKC_Casefold does. + def stable_code_point?(c) + code_point = c.ord + !NFC::DECOMPOSITION.key?(code_point) && !NFC::COMPATIBILITY_DECOMPOSITION.key?(code_point) && + c.downcase(:fold) == c && !c.match?(DEFAULT_IGNORABLE) + end + + # Processing step 4 for a label that starts with "xn--". Returns the + # decoded label, or nil. + def decode_label(label) + return nil unless label.ascii_only? + decoded = Punycode.decode(label[ACE_PREFIX.size..-1]) + return nil if decoded.nil? || decoded.empty? || decoded.ascii_only? + return nil unless NFC.normalized?(decoded) + decoded + end + + # Validity Criteria (UTS #46 section 4.1) for Nontransitional + # Processing, except the Bidi Rule, which needs the whole domain. + # Criterion 1 (NFC) holds for a label that was not decoded. + # + # +statuses+ caches #status by code point. + def valid_label?(label, statuses = {}) + return true if label.empty? + !label.start_with?(ACE_PREFIX) && + !label.include?(LABEL_SEPARATOR) && + !MARK.match?(label[0]) && + label.each_char.all? { |c| status(c, statuses) == true } && + valid_joiners?(label) + end + + # CONTEXTJ rules (RFC 5892 Appendix A.1 and A.2). + def valid_joiners?(label) + return true unless label.include?(ZWNJ) || label.include?(ZWJ) + chars = label.chars + chars.each_with_index.all? do |char, i| + case char + when ZWJ + i > 0 && virama?(chars[i - 1]) + when ZWNJ + (i > 0 && virama?(chars[i - 1])) || joining_context?(chars, i) + else + true + end + end + end + + def virama?(c) + NFC::COMBINING_CLASS[c.ord] == VIRAMA_CLASS + end + + # Whether the ZWNJ at +i+ is preceded by Joining_Type L or D and + # followed by Joining_Type R or D, with only Joining_Type T between. + def joining_context?(chars, i) + before = i - 1 + before -= 1 while before >= 0 && JOINING_TYPE_T.match?(chars[before]) + return false unless before >= 0 && JOINING_TYPE_L_OR_D.match?(chars[before]) + + after = i + 1 + after += 1 while after < chars.size && JOINING_TYPE_T.match?(chars[after]) + after < chars.size && JOINING_TYPE_R_OR_D.match?(chars[after]) + end + + # A Bidi domain name contains a code point with Bidi_Class R, AL or AN. + def bidi_domain?(labels) + labels.any? { |label| BIDI_RTL.match?(bidi_classes(label)) } + end + + def satisfies_bidi_rule?(label) + return true if label.empty? + classes = bidi_classes(label) + return false unless BIDI_FIRST.match?(classes) + if BIDI_RTL.match?(classes) + BIDI_RTL_ALLOWED.match?(classes) && BIDI_RTL_END.match?(classes) && + !(classes.include?("A") && classes.include?("E")) + else + BIDI_LTR_ALLOWED.match?(classes) && BIDI_LTR_END.match?(classes) + end + end + + def bidi_classes(label) + label.each_char.map do |char| + if BIDI_R_OR_AL.match?(char) then "R" + elsif BIDI_AN.match?(char) then "A" + elsif BIDI_EN.match?(char) then "E" + elsif BIDI_ES_CS_ET_ON_BN.match?(char) then "N" + elsif BIDI_NSM.match?(char) then "M" + elsif BIDI_OTHER.match?(char) then "X" + else "L" + end + end.join + end + end + end +end diff --git a/lib/uri/whatwg_parser/idna_data.rb b/lib/uri/whatwg_parser/idna_data.rb new file mode 100644 index 00000000..5ba896b7 --- /dev/null +++ b/lib/uri/whatwg_parser/idna_data.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +# This file is generated by `rake idna:generate` from Unicode 18.0.0: +# https://www.unicode.org/Public/18.0.0/idna/IdnaMappingTable.txt +# https://www.unicode.org/Public/18.0.0/ucd/extracted/DerivedBidiClass.txt +# https://www.unicode.org/Public/18.0.0/ucd/extracted/DerivedJoiningType.txt +# Do not edit it by hand. + +module URI + class WHATWG_Parser + module IDNA # :nodoc: + UNICODE_VERSION = "18.0.0" + + # Joining_Type, among the valid code points. + JOINING_TYPE_L_OR_D = /[\u{620}\u{626}\u{628}\u{62A}-\u{62E}\u{633}-\u{63F}\u{641}-\u{647}\u{649}-\u{64A}\u{66E}-\u{66F}\u{679}-\u{687}\u{69A}-\u{6BF}\u{6C1}-\u{6C2}\u{6CC}\u{6CE}\u{6D0}-\u{6D1}\u{6FA}-\u{6FC}\u{6FF}\u{712}-\u{714}\u{71A}-\u{71D}\u{71F}-\u{727}\u{729}\u{72B}\u{72D}-\u{72E}\u{74E}-\u{758}\u{75C}-\u{76A}\u{76D}-\u{770}\u{772}\u{775}-\u{777}\u{77A}-\u{77F}\u{7CA}-\u{7EA}\u{841}-\u{845}\u{848}\u{84A}-\u{853}\u{855}\u{860}\u{862}-\u{865}\u{868}\u{886}\u{889}-\u{88D}\u{88F}\u{8A0}-\u{8A9}\u{8AF}-\u{8B0}\u{8B3}-\u{8B8}\u{8BA}-\u{8C8}\u{1807}\u{1820}-\u{1878}\u{1887}-\u{18A8}\u{18AA}\u{A840}-\u{A872}\u{10AC0}-\u{10AC4}\u{10ACD}\u{10AD3}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}-\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}-\u{10BAE}\u{10D00}-\u{10D21}\u{10D23}\u{10EC3}-\u{10EC4}\u{10EC6}-\u{10EC7}\u{10ED9}-\u{10EEE}\u{10F30}-\u{10F32}\u{10F34}-\u{10F44}\u{10F51}-\u{10F53}\u{10F70}-\u{10F73}\u{10F76}-\u{10F81}\u{10FB0}\u{10FB2}-\u{10FB3}\u{10FB8}\u{10FBB}-\u{10FBC}\u{10FBE}-\u{10FBF}\u{10FC1}\u{10FC4}\u{10FCA}-\u{10FCB}\u{1E922}-\u{1E943}]/ + JOINING_TYPE_R_OR_D = /[\u{620}\u{622}-\u{63F}\u{641}-\u{64A}\u{66E}-\u{66F}\u{671}-\u{673}\u{679}-\u{6D3}\u{6D5}\u{6EE}-\u{6EF}\u{6FA}-\u{6FC}\u{6FF}\u{710}\u{712}-\u{72F}\u{74D}-\u{77F}\u{7CA}-\u{7EA}\u{840}-\u{858}\u{860}\u{862}-\u{865}\u{867}-\u{86A}\u{870}-\u{882}\u{886}\u{889}-\u{88F}\u{8A0}-\u{8AC}\u{8AE}-\u{8C8}\u{1807}\u{1820}-\u{1878}\u{1887}-\u{18A8}\u{18AA}\u{A840}-\u{A871}\u{10AC0}-\u{10AC5}\u{10AC7}\u{10AC9}-\u{10ACA}\u{10ACE}-\u{10AD6}\u{10AD8}-\u{10AE1}\u{10AE4}\u{10AEB}-\u{10AEF}\u{10B80}-\u{10B91}\u{10BA9}-\u{10BAE}\u{10D01}-\u{10D23}\u{10EC2}-\u{10EC4}\u{10EC6}-\u{10EC7}\u{10F30}-\u{10F44}\u{10F51}-\u{10F54}\u{10F70}-\u{10F81}\u{10FB0}\u{10FB2}-\u{10FB6}\u{10FB8}-\u{10FBF}\u{10FC1}-\u{10FC4}\u{10FC9}-\u{10FCA}\u{1E922}-\u{1E943}]/ + JOINING_TYPE_T = /[\u{300}-\u{33F}\u{342}\u{346}-\u{34E}\u{350}-\u{36F}\u{483}-\u{489}\u{591}-\u{5BD}\u{5BF}\u{5C1}-\u{5C2}\u{5C4}-\u{5C5}\u{5C7}-\u{5C9}\u{610}-\u{61A}\u{64B}-\u{65F}\u{670}\u{6D6}-\u{6DC}\u{6DF}-\u{6E4}\u{6E7}-\u{6E8}\u{6EA}-\u{6ED}\u{711}\u{730}-\u{74A}\u{7A6}-\u{7B0}\u{7EB}-\u{7F3}\u{7FD}\u{816}-\u{819}\u{81B}-\u{823}\u{825}-\u{827}\u{829}-\u{82D}\u{859}-\u{85B}\u{897}-\u{89F}\u{8CA}-\u{8E1}\u{8E3}-\u{902}\u{93A}\u{93C}\u{941}-\u{948}\u{94D}\u{951}-\u{957}\u{962}-\u{963}\u{981}\u{9BC}\u{9C1}-\u{9C4}\u{9CD}\u{9E2}-\u{9E3}\u{9FE}\u{A01}-\u{A02}\u{A3C}\u{A41}-\u{A42}\u{A47}-\u{A48}\u{A4B}-\u{A4D}\u{A51}\u{A70}-\u{A71}\u{A75}\u{A81}-\u{A82}\u{ABC}\u{AC1}-\u{AC5}\u{AC7}-\u{AC8}\u{ACD}\u{AE2}-\u{AE3}\u{AFA}-\u{AFF}\u{B01}\u{B3C}\u{B3F}\u{B41}-\u{B44}\u{B4D}\u{B53}-\u{B56}\u{B62}-\u{B63}\u{B82}\u{BC0}\u{BCD}\u{C00}\u{C04}\u{C3C}\u{C3E}-\u{C40}\u{C46}-\u{C48}\u{C4A}-\u{C4D}\u{C55}-\u{C56}\u{C62}-\u{C63}\u{C81}\u{CBC}\u{CBF}\u{CC6}\u{CCC}-\u{CCD}\u{CE2}-\u{CE3}\u{D00}-\u{D01}\u{D3B}-\u{D3C}\u{D41}-\u{D44}\u{D4D}\u{D62}-\u{D63}\u{D81}\u{DCA}\u{DD2}-\u{DD4}\u{DD6}\u{E31}\u{E34}-\u{E3A}\u{E47}-\u{E4E}\u{EB1}\u{EB4}-\u{EBC}\u{EC8}-\u{ECE}\u{F18}-\u{F19}\u{F35}\u{F37}\u{F39}\u{F71}-\u{F72}\u{F74}\u{F7A}-\u{F7E}\u{F80}\u{F82}-\u{F84}\u{F86}-\u{F87}\u{F8D}-\u{F92}\u{F94}-\u{F97}\u{F99}-\u{F9C}\u{F9E}-\u{FA1}\u{FA3}-\u{FA6}\u{FA8}-\u{FAB}\u{FAD}-\u{FB8}\u{FBA}-\u{FBC}\u{FC6}\u{102D}-\u{1030}\u{1032}-\u{1037}\u{1039}-\u{103A}\u{103D}-\u{103E}\u{1058}-\u{1059}\u{105E}-\u{1060}\u{1071}-\u{1074}\u{1082}\u{1085}-\u{1086}\u{108D}\u{109D}\u{135D}-\u{135F}\u{1712}-\u{1714}\u{1732}-\u{1733}\u{1752}-\u{1753}\u{1772}-\u{1773}\u{17B7}-\u{17BD}\u{17C6}\u{17C9}-\u{17D3}\u{17DD}\u{1885}-\u{1886}\u{18A9}\u{1920}-\u{1922}\u{1927}-\u{1928}\u{1932}\u{1939}-\u{193B}\u{1A17}-\u{1A18}\u{1A1B}\u{1A56}\u{1A58}-\u{1A5E}\u{1A60}\u{1A62}\u{1A65}-\u{1A6C}\u{1A73}-\u{1A7C}\u{1A7F}\u{1AB0}-\u{1AF0}\u{1B00}-\u{1B03}\u{1B34}\u{1B36}-\u{1B3A}\u{1B3C}\u{1B42}\u{1B6B}-\u{1B73}\u{1B80}-\u{1B81}\u{1BA2}-\u{1BA5}\u{1BA8}-\u{1BA9}\u{1BAB}-\u{1BAD}\u{1BE6}\u{1BE8}-\u{1BE9}\u{1BED}\u{1BEF}-\u{1BF1}\u{1C2C}-\u{1C33}\u{1C36}-\u{1C37}\u{1CD0}-\u{1CD2}\u{1CD4}-\u{1CE0}\u{1CE2}-\u{1CE8}\u{1CED}\u{1CF4}\u{1CF8}-\u{1CF9}\u{1DC0}-\u{1DFF}\u{20D0}-\u{20F0}\u{2CEF}-\u{2CF1}\u{2D7F}\u{2DE0}-\u{2DFF}\u{302A}-\u{302D}\u{3099}-\u{309A}\u{A66F}-\u{A672}\u{A674}-\u{A67D}\u{A69E}-\u{A69F}\u{A6F0}-\u{A6F1}\u{A802}\u{A806}\u{A80B}\u{A825}-\u{A826}\u{A82C}\u{A8C4}-\u{A8C5}\u{A8E0}-\u{A8F1}\u{A8FF}\u{A926}-\u{A92D}\u{A947}-\u{A951}\u{A980}-\u{A982}\u{A9B3}\u{A9B6}-\u{A9B9}\u{A9BC}-\u{A9BD}\u{A9E5}\u{AA29}-\u{AA2E}\u{AA31}-\u{AA32}\u{AA35}-\u{AA36}\u{AA43}\u{AA4C}\u{AA7C}\u{AAB0}\u{AAB2}-\u{AAB4}\u{AAB7}-\u{AAB8}\u{AABE}-\u{AABF}\u{AAC1}\u{AAEC}-\u{AAED}\u{AAF6}\u{ABE5}\u{ABE8}\u{ABED}\u{FB1E}\u{FE20}-\u{FE2F}\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}-\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}-\u{10AE6}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6D}\u{10EAB}-\u{10EAC}\u{10ECB}-\u{10ECF}\u{10EF0}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}-\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}-\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}-\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}-\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}-\u{11301}\u{1133B}-\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113BB}-\u{113C0}\u{113CE}\u{113D0}\u{113D2}\u{113E1}-\u{113E2}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}-\u{114C0}\u{114C2}-\u{114C3}\u{115B2}-\u{115B5}\u{115BC}-\u{115BD}\u{115BF}-\u{115C0}\u{115DC}-\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}-\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}-\u{1183A}\u{1193B}-\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}-\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}-\u{11A99}\u{11B60}\u{11B62}-\u{11B64}\u{11B66}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}-\u{11CB3}\u{11CB5}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}-\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}-\u{11D91}\u{11D95}\u{11D97}\u{11DF0}\u{11EF3}-\u{11EF4}\u{11F00}-\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11F5A}\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{16129}\u{1612D}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}-\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D127}-\u{1D128}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1D25B}-\u{1D25C}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}-\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}-\u{1E5EF}\u{1E6E3}\u{1E6E6}\u{1E6EE}-\u{1E6EF}\u{1E6F5}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}]/ + + # Bidi_Class, among the valid code points, but L, which is the + # class of the others. The values that the Bidi Rule (RFC 5893) + # always treats alike are grouped. + BIDI_R_OR_AL = /[\u{5BE}\u{5C0}\u{5C3}\u{5C6}\u{5D0}-\u{5EA}\u{5EF}-\u{5F4}\u{608}\u{60B}\u{60D}\u{61B}\u{61D}-\u{64A}\u{66D}-\u{66F}\u{671}-\u{674}\u{679}-\u{6D5}\u{6E5}-\u{6E6}\u{6EE}-\u{6EF}\u{6FA}-\u{70D}\u{710}\u{712}-\u{72F}\u{74D}-\u{7A5}\u{7B1}\u{7C0}-\u{7EA}\u{7F4}-\u{7F5}\u{7FA}\u{7FE}-\u{815}\u{81A}\u{824}\u{828}\u{830}-\u{83E}\u{840}-\u{858}\u{85E}\u{860}-\u{86A}\u{870}-\u{88F}\u{8A0}-\u{8C9}\u{FBB2}-\u{FBC2}\u{FE73}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}-\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}-\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}-\u{10959}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D4A}-\u{10D4F}\u{10D6F}-\u{10D85}\u{10D8E}-\u{10D8F}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}-\u{10EB1}\u{10EC2}-\u{10EC7}\u{10EC9}-\u{10ECA}\u{10ED9}-\u{10EEE}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E922}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}-\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}]/ + BIDI_AN = /[\u{660}-\u{669}\u{66B}-\u{66C}\u{10D30}-\u{10D39}\u{10D40}-\u{10D49}\u{10E60}-\u{10E7E}]/ + BIDI_EN = /[\u{30}-\u{39}\u{6F0}-\u{6F9}\u{102E1}-\u{102FB}]/ + BIDI_ES_CS_ET_ON_BN = /[\u{0}-\u{8}\u{E}-\u{1B}\u{21}-\u{2F}\u{3A}-\u{40}\u{5B}-\u{60}\u{7B}-\u{7F}\u{A1}-\u{A7}\u{A9}\u{AB}-\u{AC}\u{AE}\u{B0}-\u{B1}\u{B6}-\u{B7}\u{BB}\u{BF}\u{D7}\u{F7}\u{2B9}-\u{2BA}\u{2C2}-\u{2CF}\u{2D2}-\u{2D7}\u{2DE}-\u{2DF}\u{2E5}-\u{2ED}\u{2EF}-\u{2FF}\u{375}\u{3F6}\u{58A}\u{58D}-\u{58F}\u{606}-\u{607}\u{609}-\u{60A}\u{60C}\u{60E}-\u{60F}\u{66A}\u{6DE}\u{6E9}\u{7F6}-\u{7F9}\u{9F2}-\u{9F3}\u{9FB}\u{AF1}\u{BF3}-\u{BFA}\u{C78}-\u{C7E}\u{E3F}\u{F3A}-\u{F3D}\u{1390}-\u{1399}\u{1400}\u{169B}-\u{169C}\u{17DB}\u{17F0}-\u{17F9}\u{1800}-\u{180A}\u{1940}\u{1944}-\u{1945}\u{19DE}-\u{19FF}\u{200C}-\u{200D}\u{2010}\u{2012}-\u{2016}\u{2018}-\u{2023}\u{2027}\u{2030}-\u{2032}\u{2035}\u{2038}-\u{203B}\u{203D}\u{203F}-\u{2046}\u{204A}-\u{2056}\u{2058}-\u{205E}\u{208F}\u{20A0}-\u{20A7}\u{20A9}-\u{20C4}\u{2104}\u{2108}\u{2114}\u{2117}-\u{2118}\u{211E}-\u{211F}\u{2123}\u{2125}\u{2127}\u{2129}\u{212E}\u{213A}\u{2141}-\u{2144}\u{214A}-\u{214D}\u{218A}-\u{218B}\u{2190}-\u{222B}\u{222E}\u{2231}-\u{2328}\u{232B}-\u{2335}\u{237B}-\u{2394}\u{2396}-\u{2429}\u{2440}-\u{244A}\u{24EB}-\u{26AB}\u{26AD}-\u{27FF}\u{2900}-\u{2A0B}\u{2A0D}-\u{2A73}\u{2A77}-\u{2ADB}\u{2ADD}-\u{2B73}\u{2B76}-\u{2BFF}\u{2CE5}-\u{2CEA}\u{2CF9}-\u{2CFF}\u{2E00}-\u{2E5D}\u{2E60}-\u{2E63}\u{2E80}-\u{2E99}\u{2E9B}-\u{2E9E}\u{2EA0}-\u{2EF2}\u{3001}\u{3003}-\u{3004}\u{3008}-\u{3020}\u{3030}\u{3037}\u{303D}-\u{303F}\u{30A0}\u{30FB}\u{31C0}-\u{31E5}\u{4DC0}-\u{4DFF}\u{A490}-\u{A4C6}\u{A60D}-\u{A60F}\u{A673}\u{A67E}-\u{A67F}\u{A700}-\u{A721}\u{A788}\u{A828}-\u{A82B}\u{A838}-\u{A839}\u{A874}-\u{A877}\u{AB6A}-\u{AB6B}\u{FBC3}-\u{FBD2}\u{FD3E}-\u{FD4F}\u{FD90}-\u{FD91}\u{FDC8}-\u{FDCF}\u{FDFD}-\u{FDFF}\u{FE45}-\u{FE46}\u{10101}\u{10140}-\u{1018C}\u{10190}-\u{1019C}\u{101A0}\u{1091F}\u{10B39}-\u{10B3F}\u{10D6E}\u{10ED0}-\u{10ED8}\u{11052}-\u{11065}\u{11660}-\u{1166C}\u{11FD5}-\u{11FF1}\u{16FE2}\u{1CC00}-\u{1CCD5}\u{1CCFA}-\u{1CCFC}\u{1CD00}-\u{1CEB3}\u{1CEBA}-\u{1CED0}\u{1CED2}-\u{1CED4}\u{1CEDD}-\u{1CEFD}\u{1D1E9}-\u{1D1EA}\u{1D200}-\u{1D241}\u{1D245}\u{1D300}-\u{1D356}\u{1DB00}-\u{1DB1C}\u{1E2FF}\u{1EEF0}-\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F10B}-\u{1F10F}\u{1F12F}\u{1F16D}-\u{1F16F}\u{1F1AD}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D9}\u{1F6DC}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F7D9}\u{1F7DB}\u{1F7E0}-\u{1F7EB}\u{1F7F0}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}-\u{1F8BB}\u{1F8C0}-\u{1F8C1}\u{1F8D0}-\u{1F8D8}\u{1F900}-\u{1FA57}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA7C}\u{1FA80}-\u{1FAC6}\u{1FAC8}\u{1FACC}-\u{1FADD}\u{1FADF}-\u{1FAEB}\u{1FAEF}-\u{1FAFA}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBEF}\u{1FBFA}]/ + BIDI_NSM = /[\u{300}-\u{33F}\u{342}\u{346}-\u{34E}\u{350}-\u{36F}\u{483}-\u{489}\u{591}-\u{5BD}\u{5BF}\u{5C1}-\u{5C2}\u{5C4}-\u{5C5}\u{5C7}-\u{5C9}\u{610}-\u{61A}\u{64B}-\u{65F}\u{670}\u{6D6}-\u{6DC}\u{6DF}-\u{6E4}\u{6E7}-\u{6E8}\u{6EA}-\u{6ED}\u{711}\u{730}-\u{74A}\u{7A6}-\u{7B0}\u{7EB}-\u{7F3}\u{7FD}\u{816}-\u{819}\u{81B}-\u{823}\u{825}-\u{827}\u{829}-\u{82D}\u{859}-\u{85B}\u{897}-\u{89F}\u{8CA}-\u{8E1}\u{8E3}-\u{902}\u{93A}\u{93C}\u{941}-\u{948}\u{94D}\u{951}-\u{957}\u{962}-\u{963}\u{981}\u{9BC}\u{9C1}-\u{9C4}\u{9CD}\u{9E2}-\u{9E3}\u{9FE}\u{A01}-\u{A02}\u{A3C}\u{A41}-\u{A42}\u{A47}-\u{A48}\u{A4B}-\u{A4D}\u{A51}\u{A70}-\u{A71}\u{A75}\u{A81}-\u{A82}\u{ABC}\u{AC1}-\u{AC5}\u{AC7}-\u{AC8}\u{ACD}\u{AE2}-\u{AE3}\u{AFA}-\u{AFF}\u{B01}\u{B3C}\u{B3F}\u{B41}-\u{B44}\u{B4D}\u{B53}-\u{B56}\u{B62}-\u{B63}\u{B82}\u{BC0}\u{BCD}\u{C00}\u{C04}\u{C3C}\u{C3E}-\u{C40}\u{C46}-\u{C48}\u{C4A}-\u{C4D}\u{C55}-\u{C56}\u{C62}-\u{C63}\u{C81}\u{CBC}\u{CCC}-\u{CCD}\u{CE2}-\u{CE3}\u{D00}-\u{D01}\u{D3B}-\u{D3C}\u{D41}-\u{D44}\u{D4D}\u{D62}-\u{D63}\u{D81}\u{DCA}\u{DD2}-\u{DD4}\u{DD6}\u{E31}\u{E34}-\u{E3A}\u{E47}-\u{E4E}\u{EB1}\u{EB4}-\u{EBC}\u{EC8}-\u{ECE}\u{F18}-\u{F19}\u{F35}\u{F37}\u{F39}\u{F71}-\u{F72}\u{F74}\u{F7A}-\u{F7E}\u{F80}\u{F82}-\u{F84}\u{F86}-\u{F87}\u{F8D}-\u{F92}\u{F94}-\u{F97}\u{F99}-\u{F9C}\u{F9E}-\u{FA1}\u{FA3}-\u{FA6}\u{FA8}-\u{FAB}\u{FAD}-\u{FB8}\u{FBA}-\u{FBC}\u{FC6}\u{102D}-\u{1030}\u{1032}-\u{1037}\u{1039}-\u{103A}\u{103D}-\u{103E}\u{1058}-\u{1059}\u{105E}-\u{1060}\u{1071}-\u{1074}\u{1082}\u{1085}-\u{1086}\u{108D}\u{109D}\u{135D}-\u{135F}\u{1712}-\u{1714}\u{1732}-\u{1733}\u{1752}-\u{1753}\u{1772}-\u{1773}\u{17B7}-\u{17BD}\u{17C6}\u{17C9}-\u{17D3}\u{17DD}\u{1885}-\u{1886}\u{18A9}\u{1920}-\u{1922}\u{1927}-\u{1928}\u{1932}\u{1939}-\u{193B}\u{1A17}-\u{1A18}\u{1A1B}\u{1A56}\u{1A58}-\u{1A5E}\u{1A60}\u{1A62}\u{1A65}-\u{1A6C}\u{1A73}-\u{1A7C}\u{1A7F}\u{1AB0}-\u{1AF0}\u{1B00}-\u{1B03}\u{1B34}\u{1B36}-\u{1B39}\u{1B6B}-\u{1B73}\u{1B80}-\u{1B81}\u{1BA2}-\u{1BA5}\u{1BA8}-\u{1BA9}\u{1BAB}-\u{1BAD}\u{1BE6}\u{1BE8}-\u{1BE9}\u{1BED}\u{1BEF}-\u{1BF1}\u{1C2C}-\u{1C33}\u{1C36}-\u{1C37}\u{1CD0}-\u{1CD2}\u{1CD4}-\u{1CE0}\u{1CE2}-\u{1CE8}\u{1CED}\u{1CF4}\u{1CF8}-\u{1CF9}\u{1DC0}-\u{1DFF}\u{20D0}-\u{20F0}\u{2CEF}-\u{2CF1}\u{2D7F}\u{2DE0}-\u{2DFF}\u{302A}-\u{302D}\u{3099}-\u{309A}\u{A66F}-\u{A672}\u{A674}-\u{A67D}\u{A69E}-\u{A69F}\u{A6F0}-\u{A6F1}\u{A802}\u{A806}\u{A80B}\u{A825}-\u{A826}\u{A82C}\u{A8C4}-\u{A8C5}\u{A8E0}-\u{A8F1}\u{A8FF}\u{A926}-\u{A92D}\u{A947}-\u{A951}\u{A980}-\u{A982}\u{A9B3}\u{A9B6}-\u{A9B9}\u{A9BC}-\u{A9BD}\u{A9E5}\u{AA29}-\u{AA2E}\u{AA31}-\u{AA32}\u{AA35}-\u{AA36}\u{AA43}\u{AA4C}\u{AA7C}\u{AAB0}\u{AAB2}-\u{AAB4}\u{AAB7}-\u{AAB8}\u{AABE}-\u{AABF}\u{AAC1}\u{AAEC}-\u{AAED}\u{AAF6}\u{ABE5}\u{ABE8}\u{ABED}\u{FB1E}\u{FE20}-\u{FE2F}\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}-\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}-\u{10AE6}\u{10D24}-\u{10D27}\u{10D69}-\u{10D6D}\u{10EAB}-\u{10EAC}\u{10ECB}-\u{10ECF}\u{10EF0}-\u{10EFF}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}-\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}-\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}-\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}-\u{11237}\u{1123E}\u{11241}\u{112DF}\u{112E3}-\u{112EA}\u{11300}-\u{11301}\u{1133B}-\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{113BB}-\u{113C0}\u{113CE}\u{113D0}\u{113D2}\u{113E1}-\u{113E2}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}-\u{114C0}\u{114C2}-\u{114C3}\u{115B2}-\u{115B5}\u{115BC}-\u{115BD}\u{115BF}-\u{115C0}\u{115DC}-\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}-\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}-\u{1183A}\u{1193B}-\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}-\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}-\u{11A99}\u{11B60}\u{11B62}-\u{11B64}\u{11B66}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}-\u{11CB3}\u{11CB5}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}-\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}-\u{11D91}\u{11D95}\u{11D97}\u{11DF0}\u{11EF3}-\u{11EF4}\u{11F00}-\u{11F01}\u{11F36}-\u{11F3A}\u{11F40}\u{11F42}\u{11F5A}\u{13440}\u{13447}-\u{13455}\u{1611E}-\u{16129}\u{1612D}-\u{1612F}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}-\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D127}-\u{1D128}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1D25B}-\u{1D25C}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}-\u{1E024}\u{1E026}-\u{1E02A}\u{1E08F}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E4EC}-\u{1E4EF}\u{1E5EE}-\u{1E5EF}\u{1E6E3}\u{1E6E6}\u{1E6EE}-\u{1E6EF}\u{1E6F5}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}]/ + + # The code points that a Ruby of a later Unicode version knows, + # but these values do not cover, or nil. + NEWER_THAN_DATA = newer_than(UNICODE_VERSION) + end + end +end diff --git a/lib/uri/whatwg_parser/nfc.rb b/lib/uri/whatwg_parser/nfc.rb new file mode 100644 index 00000000..e87eb5e7 --- /dev/null +++ b/lib/uri/whatwg_parser/nfc.rb @@ -0,0 +1,142 @@ +# frozen_string_literal: true +module URI + class WHATWG_Parser + # Unicode Normalization Forms C and KC (UAX #15, + # https://www.unicode.org/reports/tr15/) with the tables of + # String#unicode_normalize, so with the Unicode version of the running + # Ruby. String#unicode_normalize itself cannot run in a non-main + # Ractor. + # + # The tables (nfc_tables.rb) are loaded on first use, or with + # whatwg_parser.rb where a Ractor cannot require them safely. + module NFC # :nodoc: + # Hangul syllable composition (Unicode Standard, section 3.12). + S_BASE = 0xAC00 + L_BASE = 0x1100 + V_BASE = 0x1161 + T_BASE = 0x11A7 + L_COUNT = 19 + V_COUNT = 21 + T_COUNT = 28 + N_COUNT = V_COUNT * T_COUNT + S_COUNT = L_COUNT * N_COUNT + + CODE_SPACE = 0x110000 + + module_function + + # Returns +input+, a UTF-8 String, in NFC. + def normalize(input) + recompose(input) { |code_points| decompose(code_points) } + end + + # Returns +input+, a UTF-8 String, in NFKC. + def normalize_kc(input) + recompose(input) { |code_points| decompose(code_points, COMPATIBILITY_DECOMPOSITION) } + end + + # Composes +input+ decomposed by the block. + def recompose(input) + return input.dup if input.ascii_only? + load_tables + code_points = yield input.codepoints + reorder!(code_points) + compose(code_points).pack("U*") + end + + def normalized?(input) + normalize(input) == input + end + + def load_tables + require_relative "nfc_tables" unless const_defined?(:COMPOSITION, false) + end + + def pair_key(first, second) + first * CODE_SPACE + second + end + + # The full canonical decomposition of +code_points+, or the full + # compatibility decomposition with COMPATIBILITY_DECOMPOSITION as + # +compatibility+. + def decompose(code_points, compatibility = nil) + code_points.each_with_object([]) do |c, result| + s_index = c - S_BASE + if s_index >= 0 && s_index < S_COUNT + result << L_BASE + s_index / N_COUNT << V_BASE + (s_index % N_COUNT) / T_COUNT + t = s_index % T_COUNT + result << T_BASE + t if t > 0 + elsif (decomposition = (compatibility && compatibility[c]) || DECOMPOSITION[c]) + result.concat(decomposition) + else + result << c + end + end + end + + # The Canonical Ordering Algorithm: sorts each run of code points + # whose combining class is not 0 by class, keeping the order of + # equal classes. + def reorder!(code_points) + i = 0 + while i < code_points.size + if COMBINING_CLASS.key?(code_points[i]) + run_end = i + run_end += 1 while run_end < code_points.size && COMBINING_CLASS.key?(code_points[run_end]) + if run_end - i > 1 + run = code_points[i...run_end].each_with_index.sort_by { |c, index| [COMBINING_CLASS[c], index] } + code_points[i...run_end] = run.map(&:first) + end + i = run_end + else + i += 1 + end + end + code_points + end + + # The Canonical Composition Algorithm. + def compose(code_points) + result = [] + starter = nil + # The combining class of the last code point kept since the + # starter, or nil when the starter is the last one. + last_class = nil + code_points.each do |c| + ccc = COMBINING_CLASS.fetch(c, 0) + if starter && (last_class.nil? || last_class < ccc) + composite = compose_pair(result[starter], c) + if composite + result[starter] = composite + next + end + end + if ccc == 0 + starter = result.size + last_class = nil + else + last_class = ccc + end + result << c + end + result + end + + def compose_pair(first, second) + l_index = first - L_BASE + v_index = second - V_BASE + if l_index >= 0 && l_index < L_COUNT && v_index >= 0 && v_index < V_COUNT + return S_BASE + (l_index * V_COUNT + v_index) * T_COUNT + end + + s_index = first - S_BASE + t_index = second - T_BASE + if s_index >= 0 && s_index < S_COUNT && s_index % T_COUNT == 0 && t_index > 0 && t_index < T_COUNT + return first + t_index + end + + COMPOSITION[pair_key(first, second)] + end + end + end +end diff --git a/lib/uri/whatwg_parser/nfc_tables.rb b/lib/uri/whatwg_parser/nfc_tables.rb new file mode 100644 index 00000000..e382d3fc --- /dev/null +++ b/lib/uri/whatwg_parser/nfc_tables.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true +require "unicode_normalize/tables" + +module URI + class WHATWG_Parser + # The tables of NFC and NFKC, built from those of + # String#unicode_normalize, which are shareable between Ractors. + module NFC # :nodoc: + # Canonical_Combining_Class by code point, for classes other than 0. + COMBINING_CLASS = UnicodeNormalize::CLASS_TABLE.each_with_object({}) do |(char, ccc), classes| + classes[char.ord] = ccc + end.freeze + + # The full canonical decomposition by code point, except Hangul + # syllables. + DECOMPOSITION = UnicodeNormalize::DECOMPOSITION_TABLE.each_with_object({}) do |(char, target), decompositions| + decompositions[char.ord] = target.codepoints.freeze + end.freeze + + # The full compatibility decomposition by code point, for the code + # points whose compatibility decomposition differs from their + # canonical one. The targets in UnicodeNormalize::KOMPATIBLE_TABLE + # may still have canonical decompositions, such as U+0F81 in that of + # U+0F77. + COMPATIBILITY_DECOMPOSITION = UnicodeNormalize::KOMPATIBLE_TABLE.each_with_object({}) do |(char, target), decompositions| + decompositions[char.ord] = decompose(target.codepoints).freeze + end.freeze + + # The primary composite by pair of code points (see pair_key), + # except Hangul syllables. + COMPOSITION = UnicodeNormalize::COMPOSITION_TABLE.each_with_object({}) do |(pair, char), compositions| + first, second = pair.codepoints + compositions[pair_key(first, second)] = char.ord + end.freeze + + Ractor.make_shareable(DECOMPOSITION) if defined?(Ractor) + Ractor.make_shareable(COMPATIBILITY_DECOMPOSITION) if defined?(Ractor) + end + end +end diff --git a/lib/uri/whatwg_parser/punycode.rb b/lib/uri/whatwg_parser/punycode.rb new file mode 100644 index 00000000..13bf3368 --- /dev/null +++ b/lib/uri/whatwg_parser/punycode.rb @@ -0,0 +1,252 @@ +# frozen_string_literal: true +module URI + class WHATWG_Parser + # Punycode (RFC 3492), the encoding of a domain label's code points + # in ASCII that follows "xn--" in an A-label. + module Punycode # :nodoc: + BASE = 36 + TMIN = 1 + TMAX = 26 + SKEW = 38 + DAMP = 700 + INITIAL_BIAS = 72 + INITIAL_N = 0x80 + DELIMITER = "-" + + # The largest value an intermediate integer may take while + # decoding. Ruby's integers do not overflow, but a value this large + # can only produce a code point beyond Unicode, so decoding stops + # there instead of computing with ever larger integers. + MAXINT = 0x7FFF_FFFF + MAX_CODE_POINT = 0x10FFFF + SURROGATES = (0xD800..0xDFFF).freeze + + # Up to this many insertions, inserting into an array is faster + # than placing them with a Fenwick tree, and takes little time even + # when each one goes to the start. + ARRAY_INSERTION_LIMIT = 1024 + + module_function + + # Encodes +input+, a String of Unicode code points, as Punycode. + # + # RFC 3492 scans the whole input once for each distinct non-basic + # code point, which takes time proportional to the length times the + # number of distinct code points. Instead, the positions of each + # code point are visited in order, and the code points smaller than + # it between two positions are counted with a Fenwick tree, which + # gives the same deltas. + def encode(input) + code_points = input.codepoints + output = code_points.select { |c| c < INITIAL_N }.pack("U*") + basic_count = handled = output.size + output << DELIMITER if basic_count > 0 + + smaller = FenwickTree.new(code_points.size) + positions = Hash.new { |hash, c| hash[c] = [] } + code_points.each_with_index do |c, i| + c < INITIAL_N ? smaller.add(i) : positions[c] << i + end + + n = INITIAL_N + delta = 0 + bias = INITIAL_BIAS + positions.keys.sort.each do |m| + delta += (m - n) * (handled + 1) + n = m + previous = -1 + positions[m].each do |i| + delta += smaller.count(previous + 1, i) + previous = i + encode_delta(output, delta, bias) + bias = adapt(delta, handled + 1, handled == basic_count) + delta = 0 + handled += 1 + end + delta += smaller.count(previous + 1, code_points.size) + positions[m].each { |i| smaller.add(i) } + delta += 1 + n += 1 + end + output + end + + # Appends +delta+ as a variable-length integer. + def encode_delta(output, delta, bias) + q = delta + k = BASE + loop do + t = threshold(k, bias) + break if q < t + output << digit(t + (q - t) % (BASE - t)) + q = (q - t) / (BASE - t) + k += BASE + end + output << digit(q) + end + + # Counts marked positions. + class FenwickTree # :nodoc: + # A tree of +size+ positions, all of them marked if +marked+. + def initialize(size, marked: false) + @tree = Array.new(size + 1) { |i| marked ? i & -i : 0 } + end + + # Marks position +i+, or unmarks it if +value+ is -1. + def add(i, value = 1) + i += 1 + while i < @tree.size + @tree[i] += value + i += i & -i + end + end + + # The number of marked positions in first...last. + def count(first, last) + prefix(last) - prefix(first) + end + + # The position of the marked position that has +k+ marked + # positions before it. + def find(k) + position = 0 + step = 1 + step <<= 1 while step * 2 < @tree.size + while step > 0 + if position + step < @tree.size && @tree[position + step] <= k + position += step + k -= @tree[position] + end + step >>= 1 + end + position + end + + private + + # The number of marked positions in 0...i. + def prefix(i) + sum = 0 + while i > 0 + sum += @tree[i] + i -= i & -i + end + sum + end + end + private_constant :FenwickTree + + # Decodes +input+, a Punycode String. Returns nil when +input+ is + # not valid Punycode or decodes to something that is not a sequence + # of Unicode scalar values. + # + # RFC 3492 inserts each decoded code point into the output, which + # takes time proportional to the square of the length when each one + # goes to the start. Instead, the insertions are recorded, and then + # placed by #place, which inserts only a few into an array. + def decode(input) + return nil unless input.ascii_only? + + delimiter = input.rindex(DELIMITER) + basic = delimiter ? input[0, delimiter].codepoints : [] + rest = delimiter ? input[delimiter + 1..-1] : input + indices = [] + inserted = [] + + n = INITIAL_N + i = 0 + bias = INITIAL_BIAS + position = 0 + while position < rest.size + old_i = i + w = 1 + k = BASE + loop do + return nil if position >= rest.size + d = digit_value(rest[position]) + position += 1 + return nil unless d + i += d * w + return nil if i > MAXINT + t = threshold(k, bias) + break if d < t + w *= BASE - t + return nil if w > MAXINT + k += BASE + end + length = basic.size + indices.size + 1 + bias = adapt(i - old_i, length, old_i == 0) + n += i / length + return nil if n > MAX_CODE_POINT || SURROGATES.cover?(n) + i %= length + indices << i + inserted << n + i += 1 + end + place(basic, indices, inserted).pack("U*") + end + + # The code points of +basic+ followed by those of +inserted+, each + # inserted at the index of the same place in +indices+, in order. + # Going back from the last insertion, each code point takes the free + # position that has as many free positions before it as its index, + # since the positions after it are those of later insertions. + def place(basic, indices, inserted) + if indices.size <= ARRAY_INSERTION_LIMIT + indices.each_with_index { |index, j| basic.insert(index, inserted[j]) } + return basic + end + + output = Array.new(basic.size + indices.size) + free = FenwickTree.new(output.size, marked: true) + (indices.size - 1).downto(0) do |j| + position = free.find(indices[j]) + output[position] = inserted[j] + free.add(position, -1) + end + # The basic code points take the positions left, in order. + basic_index = 0 + output.map! do |c| + next c if c + basic_index += 1 + basic[basic_index - 1] + end + end + + def threshold(k, bias) + if k <= bias + TMIN + elsif k >= bias + TMAX + TMAX + else + k - bias + end + end + + def adapt(delta, num_points, first_time) + delta = first_time ? delta / DAMP : delta / 2 + delta += delta / num_points + k = 0 + while delta > ((BASE - TMIN) * TMAX) / 2 + delta /= BASE - TMIN + k += BASE + end + k + (BASE - TMIN + 1) * delta / (delta + SKEW) + end + + # The basic code point for the digit +d+ (0..35): "a".."z", "0".."9". + def digit(d) + (d < 26 ? d + 0x61 : d + 0x16).chr + end + + # The value of the basic code point +char+ as a digit, or nil. + def digit_value(char) + case char + when "a".."z" then char.ord - 0x61 + when "A".."Z" then char.ord - 0x41 + when "0".."9" then char.ord - 0x16 + end + end + end + end +end diff --git a/lib/uri/whatwg_parser/setters.rb b/lib/uri/whatwg_parser/setters.rb new file mode 100644 index 00000000..3e48fb0f --- /dev/null +++ b/lib/uri/whatwg_parser/setters.rb @@ -0,0 +1,363 @@ +# frozen_string_literal: true +module URI + class WHATWG_Parser + # The setters of the URL Standard (https://url.spec.whatwg.org/#api) + # on a URL record. Each returns false when the URL Standard leaves the + # URL unchanged because the value is rejected, and true otherwise, + # including when only a part of the value is applied. + + private + + # The protocol setter: the scheme state with a state override. + def set_url_scheme(url, value) + match = SCHEME.match(remove_tab_and_newline(value) + ":") + return false unless match + + scheme = match[0].chop.downcase + return false if special?(url.scheme) != special?(scheme) + return false if scheme == "file" && (includes_credentials?(url) || url.port) + return false if url.scheme == "file" && url.host == "" + + url.scheme = scheme + url.port = nil if url.port == SPECIAL_SCHEMES[scheme] + true + end + + # The username setter. The value is not stripped of tabs and newlines. + def set_url_username(url, value) + return false if cannot_have_credentials_or_port?(url) + url.username = utf8_percent_encode(value, USERINFO_PERCENT_ENCODE_SET) + true + end + + # The password setter. + def set_url_password(url, value) + return false if cannot_have_credentials_or_port?(url) + url.password = utf8_percent_encode(value, USERINFO_PERCENT_ENCODE_SET) + true + end + + # The username and password setters together, for a userinfo that + # the basic URL parser would split at its first ":". + # Both reject the same URLs, so either both are applied or neither. + def set_url_userinfo(url, username, password) + set_url_username(url, username) && set_url_password(url, password) + end + + # The hostname setter: the hostname state with a state override, or + # the file host state for a file URL. + def set_url_hostname(url, value) + return false if url.path.is_a?(String) + + input = remove_tab_and_newline(value) + return set_url_file_host(url, input) if url.scheme == "file" + + special = special?(url.scheme) + authority_end = input.index(special ? SPECIAL_AUTHORITY_END : AUTHORITY_END) || input.size + buffer, port = split_host_and_port(input[0, authority_end]) + # A ":" outside brackets starts the port, which the hostname setter + # does not set. + return false if port + return false if special && buffer.empty? + return false if buffer.empty? && (includes_credentials?(url) || url.port) + + host = try_parse_host(buffer, special) + return false unless host + url.host = host + true + end + + # The file host state with a state override. + def set_url_file_host(url, input) + url.host = file_host(input[0, input.index(SPECIAL_AUTHORITY_END) || input.size]) + true + rescue InvalidURIError + false + end + + def try_parse_host(buffer, special) + parse_host(buffer, special) + rescue InvalidURIError + nil + end + + # The port setter: the port state with a state override, which takes + # the leading digits. + def set_url_port(url, value) + return false if cannot_have_credentials_or_port?(url) + + # Only the empty string removes the port, before tabs and newlines + # are removed. + if value.to_s.empty? + url.port = nil + return true + end + + digits = remove_tab_and_newline(value)[/\A[0-9]*/] + return false if digits.empty? + port = port_number(digits) + return false if port > MAX_PORT + url.port = port == SPECIAL_SCHEMES[url.scheme] ? nil : port + true + end + + # The pathname setter: the path start state with a state override, + # in which "?" and "#" are part of the path. + def set_url_path(url, value) + return false if url.path.is_a?(String) + + input = remove_tab_and_newline(value) + special = special?(url.scheme) + url.path = + if input.empty? && !special + url.host.nil? ? [""] : [] + else + parse_path(input, special, [], file: url.scheme == "file") + end + true + end + + # The search setter, given the query without a leading "?", or nil + # to remove it. + def set_url_query(url, value) + if value.nil? + url.query = nil + else + encode_set = special?(url.scheme) ? SPECIAL_QUERY_PERCENT_ENCODE_SET : QUERY_PERCENT_ENCODE_SET + url.query = utf8_percent_encode(remove_tab_and_newline(value), encode_set) + end + true + end + + # The hash setter, given the fragment without a leading "#", or nil + # to remove it. + def set_url_fragment(url, value) + if value.nil? + url.fragment = nil + else + url.fragment = utf8_percent_encode(remove_tab_and_newline(value), FRAGMENT_PERCENT_ENCODE_SET) + end + true + end + + def remove_tab_and_newline(value) + value.to_s.delete(ASCII_TAB_OR_NEWLINE) + end + + def special?(scheme) + SPECIAL_SCHEMES.key?(scheme) + end + + def includes_credentials?(url) + !url.username.empty? || !url.password.empty? + end + + def cannot_have_credentials_or_port?(url) + url.host.nil? || url.host == "" || url.scheme == "file" + end + + # Makes a URI built by WHATWG_Parser follow the URL Standard in its + # setters, equality, normalization, merge and routes. Prepended to + # URI::Generic; a URI that WHATWG_Parser did not build, or one that is + # still being initialized, keeps the methods of URI::Generic. + # + # A value that the URL Standard ignores raises InvalidComponentError. + module URLMethods # :nodoc: + def scheme=(v) + return super unless whatwg_url? + update_whatwg_url(:scheme, v) { |parser, url, value| parser.__send__(:set_url_scheme, url, value) } + end + + def user=(v) + return super unless whatwg_url? + update_whatwg_url(:user, v) { |parser, url, value| parser.__send__(:set_url_username, url, value.to_s) } + end + + def password=(v) + return super unless whatwg_url? + update_whatwg_url(:password, v) { |parser, url, value| parser.__send__(:set_url_password, url, value.to_s) } + end + + # Sets the username and the password from "user:password", split at + # the first ":", or from [user, password]. Empty or nil credentials + # are removed. + def userinfo=(v) + return super unless whatwg_url? + update_whatwg_url(:userinfo, v) do |parser, url, value| + username, password = value.is_a?(Array) ? value : value.to_s.split(":", 2) + parser.__send__(:set_url_userinfo, url, username.to_s, password.to_s) + end + end + + def host=(v) + return super unless whatwg_url? + update_whatwg_url(:host, v) { |parser, url, value| parser.__send__(:set_url_hostname, url, value) } + end + + def port=(v) + return super unless whatwg_url? + update_whatwg_url(:port, v) { |parser, url, value| parser.__send__(:set_url_port, url, value) } + end + + def path=(v) + return super unless whatwg_url? + update_whatwg_url(:path, v) { |parser, url, value| parser.__send__(:set_url_path, url, value) } + end + + # The URL Standard has no setter for an opaque path, and a URL with + # a host cannot get one, so any value is rejected. + def opaque=(v) + return super unless whatwg_url? + raise InvalidComponentError, "bad component(expected opaque component): #{v.inspect}" + end + + def query=(v) + return super unless whatwg_url? + update_whatwg_url(:query, v) { |parser, url, value| parser.__send__(:set_url_query, url, value) } + end + + def fragment=(v) + return super unless whatwg_url? + update_whatwg_url(:fragment, v) { |parser, url, value| parser.__send__(:set_url_fragment, url, value) } + end + + # The default port of the scheme, which can change with #scheme= + # while the class stays. + def default_port + return super unless whatwg_url? + SPECIAL_SCHEMES[@scheme] + end + + # Two URIs built by WHATWG_Parser are equal when their + # serializations are (URL equivalence), whatever their classes. One + # built by WHATWG_Parser is not equal to one that is not. + def ==(oth) + oth_whatwg_url = oth.is_a?(Generic) && oth.whatwg_url? + return super unless whatwg_url? || oth_whatwg_url + whatwg_url? && oth_whatwg_url && to_s == oth.to_s + end + + # The URL serializer writes "//" only for a URL with a host, while + # Generic#to_s writes it for any file or postgres URI. (A file URL + # always has a host.) + def to_s + str = super + return str unless whatwg_url? && @host.nil? + + prefix = "#{@scheme}://" + str.start_with?(prefix) ? "#{@scheme}:#{str[prefix.size..-1]}" : str + end + alias to_str to_s + + # The URL Standard resolves a reference while parsing it against a + # base, so WHATWG_Parser does the whole merge. + def merge(oth) + return super unless whatwg_parser? + parser.__send__(:merge, self, oth) + end + alias + merge + + def route_to(oth) + return super unless whatwg_parser? + parser.__send__(:convert_to_uri, route_uri(oth)).route_from(self) + end + + # The shortest reference that resolves to this URL against +oth+ by + # the URL Standard, as WHATWG_Parser finds it. + def route_from(oth) + return super unless whatwg_parser? + base = parser.__send__(:convert_to_uri, route_uri(oth)) + raise BadURIError, "relative URI: #{self}" if relative? + parser.__send__(:route, base, self) + end + alias - route_from + + # A URL is already normalized by the URL Standard, which the + # normalization of RFC 3986 would make another URL of. + def normalize! + return super unless whatwg_url? + nil + end + + protected + + def whatwg_url? + defined?(@whatwg_url) ? @whatwg_url : false + end + + # Marks a URI that WHATWG_Parser has finished building. + def whatwg_url! + @whatwg_url = true + set_port(default_port) if @port.nil? && default_port + end + + private + + COMPONENT_VARIABLES = %i[@scheme @user @password @host @port @path @query @opaque @fragment].freeze + private_constant :COMPONENT_VARIABLES + + # Generic#merge! replaces the components through the setters, which + # for a URL would apply the setters of the URL Standard to values + # that are already serialized, and would also set the registry, + # which always fails. The components are copied as they are. + def replace!(oth) + return super unless whatwg_url? + raise ArgumentError, "expected #{self.class} object" if self.class != oth.class + + COMPONENT_VARIABLES.each do |name| + instance_variable_set(name, oth.instance_variable_get(name)) + end + end + + # Whether WHATWG_Parser built this URI, or the relative URI that + # #route_to returned for one. + def whatwg_parser? + parser.is_a?(WHATWG_Parser) + end + + # Converts +oth+ to a URI for a route. WHATWG_Parser builds absolute + # URIs only, so a relative reference is rejected here as + # Generic#route_from rejects a relative URI. + def route_uri(oth) + parser.__send__(:absolute_uri, oth) or raise BadURIError, "relative URI: #{oth}" + end + + # Applies a setter to the URL record of this URI, and replaces the + # components with the result. The setter is given +value+ with its + # strings converted to UTF-8. + def update_whatwg_url(component, value) + parser = self.parser + url = parser.__send__(:url_record, self) + unless yield(parser, url, utf8_value(parser, component, value)) + raise InvalidComponentError, "bad component(expected #{component} component): #{value.inspect}" + end + + scheme, userinfo, host, port, _registry, path, opaque, query, fragment = parser.__send__(:to_components, url) + @scheme = scheme.freeze + @user, @password = userinfo ? userinfo.split(":", 2) : [nil, nil] + @host = host + @path = path + @opaque = opaque + @query = query + @fragment = fragment + @port = port ? port.to_i : default_port + value + end + + def utf8_value(parser, component, value) + case value + when String + parser.__send__(:to_utf8, value) + when Array + value.map { |v| utf8_value(parser, component, v) } + else + value + end + rescue InvalidURIError + raise InvalidComponentError, "bad component(expected #{component} component): #{value.inspect}" + end + end + + Generic.prepend(URLMethods) + end +end diff --git a/rakelib/idna.rake b/rakelib/idna.rake new file mode 100644 index 00000000..73974b07 --- /dev/null +++ b/rakelib/idna.rake @@ -0,0 +1,29 @@ +namespace :idna do + desc "Generate lib/uri/whatwg_parser/idna_data.rb from Unicode data (UNICODE_VERSION=x.y.z, default: the version of the current data)" + task :generate do + require_relative "idna_data_generator" + require "net/http" + require "fileutils" + + data_path = "lib/uri/whatwg_parser/idna_data.rb" + version = ENV["UNICODE_VERSION"] || File.read(data_path)[/UNICODE_VERSION = "([\d.]+)"/, 1] + abort "set UNICODE_VERSION" unless version + + cache_dir = File.join("tmp", "unicode", version) + FileUtils.mkdir_p(cache_dir) + sources = IDNADataGenerator::FILES.to_h do |key, file| + path = File.join(cache_dir, File.basename(file)) + unless File.exist?(path) + url = IDNADataGenerator.url(version, file) + puts "fetching #{url}" + response = Net::HTTP.get_response(URI(url)) + abort "failed to fetch #{url}: HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess) + File.binwrite(path, response.body) + end + [key, File.read(path, encoding: "UTF-8")] + end + + File.write(data_path, IDNADataGenerator.new(version, sources).generate) + puts "wrote #{data_path} (Unicode #{version})" + end +end diff --git a/rakelib/idna_data_generator.rb b/rakelib/idna_data_generator.rb new file mode 100644 index 00000000..3dacc0d7 --- /dev/null +++ b/rakelib/idna_data_generator.rb @@ -0,0 +1,126 @@ +# frozen_string_literal: true + +# Generates lib/uri/whatwg_parser/idna_data.rb, the Unicode data that +# URI::WHATWG_Parser::IDNA needs for domain to ASCII (UTS #46 ToASCII +# with the settings of the URL Standard) and that Ruby has not: the +# Bidi_Class and Joining_Type values of the valid code points, from the +# Unicode Character Database files of one Unicode version. +class IDNADataGenerator + FILES = { + mapping: "idna/IdnaMappingTable.txt", + bidi_class: "ucd/extracted/DerivedBidiClass.txt", + joining_type: "ucd/extracted/DerivedJoiningType.txt", + }.freeze + + def self.url(version, file) + "https://www.unicode.org/Public/#{version}/#{file}" + end + + # +sources+ maps each key of FILES to the content of that file. + def initialize(version, sources) + @version = version + @sources = sources + end + + def generate + valid = valid_code_points + <<~RUBY + # frozen_string_literal: true + + # This file is generated by `rake idna:generate` from Unicode #{@version}: + #{FILES.values.map { |f| "# #{self.class.url(@version, f)}" }.join("\n")} + # Do not edit it by hand. + + module URI + class WHATWG_Parser + module IDNA # :nodoc: + UNICODE_VERSION = #{@version.dump} + + # Joining_Type, among the valid code points. + JOINING_TYPE_L_OR_D = #{char_class(intersect(property("joining_type") { |v| %w[L D].include?(v) }, valid))} + JOINING_TYPE_R_OR_D = #{char_class(intersect(property("joining_type") { |v| %w[R D].include?(v) }, valid))} + JOINING_TYPE_T = #{char_class(intersect(property("joining_type") { |v| v == "T" }, valid))} + + # Bidi_Class, among the valid code points, but L, which is the + # class of the others. The values that the Bidi Rule (RFC 5893) + # always treats alike are grouped. + BIDI_R_OR_AL = #{char_class(intersect(bidi_class("R", "AL"), valid))} + BIDI_AN = #{char_class(intersect(bidi_class("AN"), valid))} + BIDI_EN = #{char_class(intersect(bidi_class("EN"), valid))} + BIDI_ES_CS_ET_ON_BN = #{char_class(intersect(bidi_class("ES", "CS", "ET", "ON", "BN"), valid))} + BIDI_NSM = #{char_class(intersect(bidi_class("NSM"), valid))} + + # The code points that a Ruby of a later Unicode version knows, + # but these values do not cover, or nil. + NEWER_THAN_DATA = newer_than(UNICODE_VERSION) + end + end + end + RUBY + end + + private + + # The ranges of the code points whose status is valid or deviation in + # the IDNA Mapping Table: the others are never checked for Bidi_Class + # or Joining_Type. + def valid_code_points + valid = [] + each_line(:mapping) do |range, fields| + valid << range if %w[valid deviation].include?(fields[0]) + end + merge(valid) + end + + def property(key) + ranges = [] + each_line(key.to_sym) do |range, fields| + ranges << range if yield fields[0] + end + merge(ranges) + end + + def bidi_class(*values) + property("bidi_class") { |v| values.include?(v) } + end + + # Yields each data line of a UCD file as a code point range and the + # remaining fields, without comments. "@missing" lines are comments. + def each_line(key) + @sources.fetch(key).each_line do |line| + line = line.sub(/#.*/, "").strip + next if line.empty? + code_points, *fields = line.split(";").map(&:strip) + first, last = code_points.split("..").map(&:hex) + yield first..(last || first), fields + end + end + + def merge(ranges) + ranges.sort_by(&:first).each_with_object([]) do |range, merged| + if merged.last && merged.last.last + 1 >= range.first + merged[-1] = merged.last.first..[merged.last.last, range.last].max + else + merged << range + end + end + end + + def intersect(ranges, others) + ranges.flat_map do |range| + others.filter_map do |other| + first = [range.first, other.first].max + last = [range.last, other.last].min + first..last if first <= last + end + end + end + + def char_class(ranges) + body = ranges.map do |range| + first = format("\\u{%X}", range.first) + range.size == 1 ? first : "#{first}-#{format("\\u{%X}", range.last)}" + end + "/[#{body.join}]/" + end +end diff --git a/rakelib/wpt.rake b/rakelib/wpt.rake new file mode 100644 index 00000000..aa1bab82 --- /dev/null +++ b/rakelib/wpt.rake @@ -0,0 +1,16 @@ +require "rake/testtask" + +namespace :test do + Rake::TestTask.new(:wpt) do |t| + t.description = "Run WPT urltestdata.json, toascii.json and setters_tests.json and Unicode IdnaTestV2.txt and NormalizationTest.txt against URI::WHATWG_PARSER (needs network unless WPT_URLTESTDATA, WPT_TOASCII, WPT_SETTERS, IDNA_TEST_V2 and NORMALIZATION_TEST are local files)" + t.libs << "lib" + t.test_files = FileList["test/wpt/test_*.rb"] + end + + namespace :wpt do + desc "Regenerate test/wpt/urltestdata_exclusions.json and setters_tests_exclusions.json from the currently failing cases" + task :update_exclusions do + ruby "-Ilib", "test/wpt/update_exclusions.rb" + end + end +end diff --git a/test/uri/test_whatwg_idna.rb b/test/uri/test_whatwg_idna.rb new file mode 100644 index 00000000..67df94d4 --- /dev/null +++ b/test/uri/test_whatwg_idna.rb @@ -0,0 +1,380 @@ +# frozen_string_literal: false +require 'test/unit' +require 'uri' + +# Domain to ASCII: UTS #46 ToASCII with the settings of the URL Standard +# (CheckHyphens=false, CheckBidi=true, CheckJoiners=true, +# UseSTD3ASCIIRules=false, Transitional_Processing=false, +# VerifyDnsLength=false, IgnoreInvalidPunycode=false). +class URI::TestWHATWGIDNA < Test::Unit::TestCase + IDNA = URI::WHATWG_Parser::IDNA + + def assert_to_ascii(expected, domain) + assert_equal(expected, IDNA.to_ascii(domain), "to_ascii(#{domain.dump})") + end + + def assert_failure(domain) + assert_nil(IDNA.to_ascii(domain), "to_ascii(#{domain.dump})") + end + + # --- ASCII --------------------------------------------------------- + + def test_ascii_is_lowercased + assert_to_ascii("example.com", "EXAMPLE.com") + end + + def test_ascii_without_std3_rules + assert_to_ascii("a_b.com", "a_b.com") + assert_to_ascii("a b", "a b") + end + + def test_hyphens_are_not_checked + assert_to_ascii("-a-.com", "-a-.com") + assert_to_ascii("ab--c.com", "ab--c.com") + end + + def test_dns_length_is_not_verified + assert_to_ascii("", "") + assert_to_ascii("a..b", "a..b") + assert_to_ascii("a.", "a.") + assert_to_ascii("a" * 64, "a" * 64) + end + + # --- Map ----------------------------------------------------------- + + def test_mapped + assert_to_ascii("example.com", "\uFF25\uFF38\uFF21\uFF2D\uFF30\uFF2C\uFF25.com") + assert_to_ascii("a.com", "\u24D0.com") + end + + def test_mapped_to_several_code_points + assert_to_ascii("tm.com", "\u2122.com") + end + + def test_ignored + assert_to_ascii("example.com", "ex\u00ADample.com") + end + + def test_ideographic_full_stop_separates_labels + assert_to_ascii("xn--wgv71a119e.jp", "\u65E5\u672C\u8A9E\u3002jp") + assert_to_ascii("xn--wgv71a119e.jp", "\u65E5\u672C\u8A9E\uFF0Ejp") + assert_to_ascii("xn--wgv71a119e.jp", "\u65E5\u672C\u8A9E\uFF61jp") + end + + def test_deviation_is_kept + assert_to_ascii("xn--fa-hia.de", "fa\u00DF.de") + assert_to_ascii("xn--fa-hia.de", "FA\u1E9E.de") + end + + # --- Mapping table derivation (UTS #46 section 6) ----------------- + # The IDNA Mapping Table is derived from the Unicode data of the + # running Ruby. + + # Step 1: the label separators map to ".", Bidi_Control characters + # to themselves (so step 6 disallows them), and U+1E9E to U+00DF. + def test_derivation_base_mapping_exceptions + assert_to_ascii("a.b", "a\u{FF0E}b") + assert_to_ascii("a.b", "a\u{FF61}b") + assert_to_ascii(".", "\u{3002}") + assert_failure("a\u{200E}b") + assert_failure("a\u{202A}b") + assert_to_ascii("xn--zca", "\u{1E9E}") + end + + # Step 1 otherwise: NFKC_Casefold, which removes default ignorable + # code points. + def test_derivation_nfkc_casefold + assert_to_ascii("viii", "\u{2167}") + assert_to_ascii("ffi", "\u{FB03}") + assert_to_ascii("xn--bya", "\u{2126}") + assert_to_ascii("ab", "a\u{AD}b") + assert_to_ascii("ab", "a\u{200B}b") + assert_to_ascii("ab", "a\u{180E}b") + assert_to_ascii("ab", "a\u{FE0F}b") + assert_to_ascii("ab", "a\u{E0100}b") + end + + # Step 2: the base valid set has the ASCII code points but ".", and no + # other control, format, private use, unassigned or separator code + # point, nor IDS operator. + def test_derivation_base_valid_set + assert_to_ascii("a\u{0}b", "a\u{0}b") + assert_to_ascii("a b", "a\u{A0}b") + assert_to_ascii("a b", "a\u{3000}b") + assert_failure("a\u{2028}b") + assert_failure("a\u{E000}") + assert_failure("a\u{FDD0}") + assert_failure("a\u{2FF0}b") + assert_failure("a\u{2FFE}b") + assert_to_ascii("xn--a-jv3s", "a\u{1F600}") + assert_to_ascii("xn--o39a", "\u{AC00}") + end + + # Step 3: the base exclusion set. + def test_derivation_base_exclusion_set + assert_failure("a\u{FFFC}") + assert_failure("a\u{FFFD}") + assert_failure("a\u{E0001}") + assert_failure("a\u{E007F}") + end + + # Step 4: the deviations are valid in Nontransitional Processing. + def test_derivation_deviations + assert_to_ascii("xn--a-ymb", "a\u{3C2}") + assert_to_ascii("xn--fa-hia.de", "fa\u{DF}.de") + end + + # Step 6: an unassigned code point is disallowed, as is one whose + # mapping has a code point outside the base valid set, such as the + # "." of U+2488 DIGIT ONE FULL STOP. + def test_derivation_disallowed + assert_failure("a\u{378}") + assert_failure("a\u{2488}b") + end + + # Step 7: a mapping must be wholly valid. U+FE12 maps to U+3002, which + # is mapped itself. + def test_derivation_mapping_to_a_mapped_code_point + assert_failure("a\u{FE12}b") + end + + # A code point added in a later Unicode version than the running + # Ruby's is unassigned, so disallowed. + def test_code_point_unknown_to_ruby_is_disallowed + unknown = (0x30000..0x3FFFD).find { |c| c.chr(Encoding::UTF_8).match?(/\p{Cn}/) } + assert_failure("a" + unknown.chr(Encoding::UTF_8)) + end + + # NFKC_Casefold of one code point, computed with String#unicode_normalize + # instead of URI::WHATWG_Parser::NFC. + def reference_nfkc_casefold(s) + loop do + t = s.unicode_normalize(:nfkc).downcase(:fold).unicode_normalize(:nfkc).gsub(/\p{Default_Ignorable_Code_Point}/, "") + return t if t == s + s = t + end + end + + # Every code point with a decomposition or a combining class, and a + # sample of the others. + def test_nfkc_casefold + require "unicode_normalize/tables" + IDNA.load_data + chars = UnicodeNormalize::KOMPATIBLE_TABLE.keys + UnicodeNormalize::DECOMPOSITION_TABLE.keys + + UnicodeNormalize::CLASS_TABLE.keys + chars += (0x80..0x10FFFF).step(97).reject { |c| (0xD800..0xDFFF).cover?(c) }.map { |c| c.chr(Encoding::UTF_8) } + chars += ["A", "\u{DF}", "\u{1E9E}", "\u{130}", "\u{FB03}", "\u{AD}", "\u{AC00}", "\u{2126}", "\u{1F600}"] + wrong = chars.uniq.reject { |c| IDNA.nfkc_casefold(c) == reference_nfkc_casefold(c) } + assert_equal([], wrong.map(&:dump)) + end + + # The Bidi_Class and Joining_Type values come from generated data, so + # a code point that Ruby knows but the data does not, on a Ruby whose + # Unicode version is newer, is disallowed. + def test_newer_than_matches_code_points_assigned_after_a_version + newer = IDNA.newer_than("6.0.0") + assert_match(newer, "\u{1F600}") # Unicode 6.1 + assert_no_match(newer, "\u{263A}") # Unicode 1.1 + assert_no_match(newer, "a") + assert_no_match(newer, "\u{378}") # unassigned + assert_no_match(newer, "\u{FDD0}") # noncharacter + assert_predicate(newer, :frozen?) + end + + def test_newer_than_a_version_that_ruby_does_not_know_is_nil + assert_nil(IDNA.newer_than("999.0.0")) + end + + def test_code_point_newer_than_the_data_is_disallowed + assert_separately([], <<~'RUBY') + require "uri" + idna = URI::WHATWG_Parser::IDNA + idna.load_data + idna.send(:remove_const, :NEWER_THAN_DATA) + idna.const_set(:NEWER_THAN_DATA, idna.newer_than("6.0.0")) + assert_nil(idna.to_ascii("a\u{1F600}")) + assert_nil(idna.to_ascii("xn--a-jv3s")) + assert_equal("xn--a-60p", idna.to_ascii("a\u{263A}")) + RUBY + end + + # --- Normalize ----------------------------------------------------- + + def test_normalized_to_nfc + assert_to_ascii("xn--9ca.com", "e\u0301.com") + end + + # --- Convert ------------------------------------------------------- + + def test_non_ascii_labels_are_converted + assert_to_ascii("xn--wgv71a119e.jp", "\u65E5\u672C\u8A9E.jp") + assert_to_ascii("xn--tda.xn--tda", "\u00FC.\u00DC") + end + + def test_result_is_ascii + assert_predicate(IDNA.to_ascii("\u65E5\u672C\u8A9E.jp"), :ascii_only?) + end + + def test_empty_labels_around_non_ascii + assert_to_ascii("xn--tda..com", "\u00FC..com") + assert_to_ascii("xn--tda.", "\u00FC.") + assert_to_ascii(".xn--tda", ".\u00FC") + end + + # --- Validity criteria --------------------------------------------- + + def test_disallowed + assert_failure("\uFFFD.com") + assert_failure("a\u2028b.com") + assert_failure("\uE000.com") + assert_failure("\u{E0001}.com") + end + + def test_leading_combining_mark + assert_failure("\u0301a.com") + assert_to_ascii("xn--9ca.com", "e\u0301.com") + end + + def test_label_starting_with_xn_dash_dash_and_non_ascii + assert_failure("xn--\u00FC.com") + end + + # --- Punycode labels ----------------------------------------------- + + def test_valid_punycode_label_is_kept + assert_to_ascii("xn--tda.xn--tda", "xn--tda.\u00FC") + assert_to_ascii("xn--tda.xn--tda", "XN--TDA.\u00FC") + end + + def test_invalid_punycode + assert_failure("xn--a-!.\u00FC") + assert_failure("xn--a-9.\u00FC") + end + + def test_empty_punycode + assert_failure("xn--.\u00FC") + assert_failure("xn---.\u00FC") + end + + def test_ascii_only_punycode + assert_failure("xn--ascii-.\u00FC") + end + + def test_punycode_decoding_to_disallowed + assert_failure("xn--a.\u00FC") # U+0080 + end + + def test_punycode_decoding_to_mapped + # U+24D0 is mapped; a decoded label is validated, not mapped. + assert_failure("xn--vuh.\u00FC") + end + + def test_punycode_decoding_to_non_nfc + assert_failure("xn--e-xbb.\u00FC") # "e\u0301" + end + + # --- CheckJoiners -------------------------------------------------- + + def test_zwnj_after_virama + assert_to_ascii("xn--11b2ezcs70k", "\u0915\u094D\u200C\u0937") + end + + def test_zwnj_in_joining_context + assert_to_ascii("xn--ngba799q", "\u0628\u200C\u0628") + end + + def test_zwnj_in_joining_context_with_transparent + assert_equal( + IDNA.to_ascii("\u0628\u064B\u200C\u064B\u0628"), + "xn--" + URI::WHATWG_Parser::Punycode.encode("\u0628\u064B\u200C\u064B\u0628") + ) + end + + def test_zwnj_without_context + assert_failure("a\u200Cb") + assert_failure("\u200Cb") + assert_failure("\u0628\u200C") + assert_failure("\u200C\u0628") + end + + def test_zwj_after_virama + assert_to_ascii("xn--11b2ezcw70k", "\u0915\u094D\u200D\u0937") + end + + def test_zwj_without_virama + assert_failure("a\u200Db") + assert_failure("\u200Db") + assert_failure("\u0628\u200D\u0628") + end + + # --- CheckBidi ----------------------------------------------------- + + def test_rtl_label + assert_to_ascii("xn--4dbc.com", "\u05D0\u05D1.com") + end + + def test_rtl_label_ending_with_nsm + assert_to_ascii("xn--7cb7d", "\u05D0\u05B0") + end + + def test_rtl_label_with_an + assert_to_ascii("xn--mgb0j", "\u0627\u0661") + end + + def test_rtl_label_with_en_at_the_end + assert_to_ascii("xn--1-zhc", "\u05D01") + end + + def test_rtl_label_with_l + assert_failure("\u05D0a") + end + + def test_rtl_label_starting_with_an + assert_failure("\u0661\u0627") + end + + def test_rtl_label_mixing_an_and_en + assert_failure("\u0627\u0661\u06F1") + end + + def test_rtl_label_ending_with_on + assert_failure("\u05D0!") + end + + def test_ltr_label_with_r + assert_failure("a\u05D0") + end + + def test_ltr_label_in_a_bidi_domain_starting_with_en + assert_failure("1a.\u05D0") + end + + def test_ltr_label_in_a_bidi_domain_ending_with_on + assert_failure("a!.\u05D0") + end + + def test_ltr_label_outside_a_bidi_domain_is_not_checked + assert_to_ascii("1a.xn--tda", "1a.\u00FC") + end + + # --- Input --------------------------------------------------------- + + # A non-main Ractor can read only shareable constants. + def test_constants_are_shareable + omit "Ractor is not available" unless defined?(Ractor) + IDNA.load_data + [IDNA, URI::WHATWG_Parser::NFC].each do |mod| + assert_equal([], mod.constants.reject { |c| Ractor.shareable?(mod.const_get(c)) }, mod.name) + end + end + + def test_invalid_utf8 + assert_failure("\xFF.com".dup.force_encoding(Encoding::UTF_8)) + end + + def test_input_is_not_modified + domain = "\u00DC.com" + IDNA.to_ascii(domain) + assert_equal("\u00DC.com", domain) + end +end diff --git a/test/uri/test_whatwg_nfc.rb b/test/uri/test_whatwg_nfc.rb new file mode 100644 index 00000000..08f2b382 --- /dev/null +++ b/test/uri/test_whatwg_nfc.rb @@ -0,0 +1,197 @@ +# frozen_string_literal: false +require 'test/unit' +require 'uri' + +# Unicode Normalization Forms C and KC (UAX #15) with the Unicode data of +# the running Ruby. +class URI::TestWHATWGNFC < Test::Unit::TestCase + NFC = URI::WHATWG_Parser::NFC + + def assert_nfc(expected, input) + assert_equal(expected, NFC.normalize(input), "NFC(#{input.dump})") + end + + def assert_nfkc(expected, input) + assert_equal(expected, NFC.normalize_kc(input), "NFKC(#{input.dump})") + end + + def test_ascii_and_empty + assert_nfc("", "") + assert_nfc("example.com", "example.com") + end + + def test_already_composed + assert_nfc("\u{E9}", "\u{E9}") + assert_nfc("\u{1EBE}", "\u{1EBE}") + assert_nfc("\u{65E5}\u{672C}", "\u{65E5}\u{672C}") + end + + def test_composes + assert_nfc("\u{E9}", "e\u{301}") + assert_nfc("\u{C5}", "A\u{30A}") + assert_nfc("\u{1EBE}", "\u{CA}\u{301}") + end + + def test_decomposes_singletons + assert_nfc("\u{C5}", "\u{212B}") + assert_nfc("\u{3A9}", "\u{2126}") + assert_nfc("\u{8C48}", "\u{F900}") + end + + def test_composition_exclusions_stay_decomposed + assert_nfc("\u{915}\u{93C}", "\u{958}") + assert_nfc("\u{915}\u{93C}", "\u{915}\u{93C}") + end + + def test_non_starter_decomposition + assert_nfc("\u{308}\u{301}", "\u{344}") + end + + def test_canonical_ordering + assert_nfc("\u{1EA1}\u{301}", "a\u{301}\u{323}") + assert_nfc("\u{1E0D}\u{307}", "\u{1E0B}\u{323}") + end + + def test_composes_across_a_mark_of_another_class + assert_nfc("\u{1EAD}", "a\u{323}\u{302}") + end + + def test_blocked_by_a_mark_of_the_same_class + assert_nfc("\u{E4}\u{308}", "a\u{308}\u{308}") + assert_nfc("\u{E9}\u{301}", "e\u{301}\u{301}") + end + + def test_blocked_by_a_starter + assert_nfc("\u{1100}\u{301}\u{1161}", "\u{1100}\u{301}\u{1161}") + end + + def test_leading_combining_mark + assert_nfc("\u{301}e", "\u{301}e") + end + + def test_hangul_composes + assert_nfc("\u{AC00}", "\u{1100}\u{1161}") + assert_nfc("\u{AC01}", "\u{1100}\u{1161}\u{11A8}") + assert_nfc("\u{AC01}", "\u{AC00}\u{11A8}") + assert_nfc("\u{D7A3}", "\u{1112}\u{1175}\u{11C2}") + end + + def test_hangul_syllables_stay_composed + assert_nfc("\u{AC01}", "\u{AC01}") + assert_nfc("\u{D7A3}", "\u{D7A3}") + end + + def test_hangul_boundaries + # U+11A7 is just below the trailing consonants (U+11A8..U+11C2). + assert_nfc("\u{AC00}\u{11A7}", "\u{AC00}\u{11A7}") + # U+11C3 is just above them. + assert_nfc("\u{AC00}\u{11C3}", "\u{AC00}\u{11C3}") + # An LVT syllable takes no further trailing consonant. + assert_nfc("\u{AC01}\u{11A8}", "\u{AC01}\u{11A8}") + # U+1113 is just above the leading consonants (U+1100..U+1112). + assert_nfc("\u{1113}\u{1161}", "\u{1113}\u{1161}") + # U+1176 is just above the vowels (U+1161..U+1175). + assert_nfc("\u{1100}\u{1176}", "\u{1100}\u{1176}") + end + + def test_supplementary_planes + # U+1D15E MUSICAL SYMBOL HALF NOTE is excluded from composition. + assert_nfc("\u{1D157}\u{1D165}", "\u{1D15E}") + assert_nfc("\u{1F600}", "\u{1F600}") + end + + def test_input_is_not_modified + input = "e\u{301}" + NFC.normalize(input) + assert_equal("e\u{301}", input) + end + + def test_result_is_utf8 + assert_equal(Encoding::UTF_8, NFC.normalize("e\u{301}").encoding) + assert_equal(Encoding::UTF_8, NFC.normalize("a").encoding) + end + + def test_normalized + assert_true(NFC.normalized?("")) + assert_true(NFC.normalized?("\u{E9}")) + assert_false(NFC.normalized?("e\u{301}")) + assert_false(NFC.normalized?("\u{212B}")) + assert_false(NFC.normalized?("a\u{301}\u{323}")) + assert_true(NFC.normalized?("\u{1EA1}\u{301}")) + end + + def test_nfkc_ascii_and_empty + assert_nfkc("", "") + assert_nfkc("Example.COM", "Example.COM") + end + + def test_nfkc_decomposes_compatibility_characters + assert_nfkc("ffi", "\u{FB03}") + assert_nfkc("A", "\u{FF21}") + assert_nfkc("1", "\u{2460}") + assert_nfkc("A", "\u{1D400}") + assert_nfkc("\u{30A2}\u{30D1}\u{30FC}\u{30C8}", "\u{3300}") + end + + # Each step of a compatibility decomposition is applied: U+FFA1 is + # U+3131, which is U+1100. + def test_nfkc_decomposes_fully + assert_nfkc("\u{1100}", "\u{FFA1}") + end + + def test_nfkc_composes + assert_nfkc("\u{30AC}", "\u{FF76}\u{FF9E}") + assert_nfkc("\u{1E69}", "\u{1E9B}\u{323}") + assert_nfkc("\u{E9}", "e\u{301}") + end + + def test_nfkc_keeps_what_nfc_keeps + assert_nfkc("\u{AC00}", "\u{AC00}") + assert_nfkc("\u{3A9}", "\u{2126}") + assert_nfkc("\u{8C48}", "\u{F900}") + assert_nfkc("\u{915}\u{93C}", "\u{958}") + end + + def test_nfkc_input_is_not_modified_and_result_is_utf8 + input = "\u{FB03}" + result = NFC.normalize_kc(input) + assert_equal("\u{FB03}", input) + assert_equal(Encoding::UTF_8, result.encoding) + assert_equal(Encoding::UTF_8, NFC.normalize_kc("a").encoding) + end + + # The tables are those of String#unicode_normalize, so both agree on + # every code point that has a decomposition or a combining class. + def test_agrees_with_unicode_normalize + require "unicode_normalize/tables" + chars = UnicodeNormalize::KOMPATIBLE_TABLE.keys + UnicodeNormalize::DECOMPOSITION_TABLE.keys + + UnicodeNormalize::CLASS_TABLE.keys + ["\u{AC00}", "\u{D7A3}", "\u{1100}\u{1161}\u{11A8}"] + nfc = chars.reject { |c| NFC.normalize(c) == c.unicode_normalize(:nfc) } + nfkc = chars.reject { |c| NFC.normalize_kc(c) == c.unicode_normalize(:nfkc) } + assert_equal([[], []], [nfc.map(&:dump), nfkc.map(&:dump)]) + end + + def test_works_in_a_ractor + omit "Ractor is not available" unless defined?(Ractor) + assert_separately(%w[-W0], <<~'RUBY') + require "uri" + r = Ractor.new { [URI::WHATWG_Parser::NFC.normalize("e\u{301}"), URI::WHATWG_Parser::NFC.normalize_kc("\u{FB03}")] } + assert_equal(["\u{E9}", "ffi"], r.respond_to?(:value) ? r.value : r.take) + RUBY + end + + def test_normalize_in_linear_time + marks = ->(n) { "a" + "\u{301}\u{323}" * n } + assert_linear_performance([300, 1_000, 3_000, 10_000], pre: marks) do |input| + NFC.normalize(input) + end + hangul = ->(n) { "\u{1100}\u{1161}\u{11A8}" * n } + assert_linear_performance([300, 1_000, 3_000, 10_000], pre: hangul) do |input| + NFC.normalize(input) + end + compatibility = ->(n) { "\u{FDFA}\u{301}" * n } + assert_linear_performance([300, 1_000, 3_000, 10_000], pre: compatibility) do |input| + NFC.normalize_kc(input) + end + end +end diff --git a/test/uri/test_whatwg_parser.rb b/test/uri/test_whatwg_parser.rb new file mode 100644 index 00000000..a297b388 --- /dev/null +++ b/test/uri/test_whatwg_parser.rb @@ -0,0 +1,2521 @@ +# frozen_string_literal: true +require 'test/unit' +require 'envutil' +require 'stringio' +require 'uri' + +class URI::TestWHATWGParser < Test::Unit::TestCase + def teardown + URI.parser = URI::RFC3986_PARSER + end + + # --- constant / default parser ------------------------------------- + + def test_whatwg_parser_is_defined_by_requiring_uri + assert_kind_of(URI::WHATWG_Parser, URI::WHATWG_PARSER) + end + + def test_default_parser_stays_rfc3986 + assert_same(URI::RFC3986_PARSER, URI::DEFAULT_PARSER) + assert_same(URI::RFC3986_PARSER, URI::PARSER) + assert_equal(URI::RFC3986_Parser, URI::Parser) + end + + def test_whatwg_parser_is_ractor_shareable + omit "Ractor is not available" unless defined?(Ractor) + assert(Ractor.shareable?(URI::WHATWG_PARSER)) + end + + def test_whatwg_parser_can_be_instantiated_without_arguments + # URI.parser= calls Parser.new with no arguments. + assert_kind_of(URI::WHATWG_Parser, URI::WHATWG_Parser.new) + end + + # --- URI.parser= switching ----------------------------------------- + + def test_parser_switch_to_whatwg + URI.parser = URI::WHATWG_PARSER + + assert_same(URI::WHATWG_PARSER, URI::PARSER) + assert_equal(URI::WHATWG_Parser, URI::Parser) + refute defined?(URI::REGEXP) + refute defined?(URI::PATTERN) + end + + def test_parser_switch_does_not_change_default_parser + URI.parser = URI::WHATWG_PARSER + + assert_same(URI::RFC3986_PARSER, URI::DEFAULT_PARSER) + end + + def test_parser_switch_back_to_rfc3986 + URI.parser = URI::WHATWG_PARSER + URI.parser = URI::RFC3986_PARSER + + assert_same(URI::RFC3986_PARSER, URI::PARSER) + assert_equal(URI::RFC3986_Parser, URI::Parser) + end + + def test_parser_switch_back_with_default_argument + URI.parser = URI::WHATWG_PARSER + URI.parser = URI::RFC2396_PARSER + URI.parser = URI::WHATWG_PARSER + URI.send(:parser=) + + assert_same(URI::RFC3986_PARSER, URI::PARSER) + end + + def test_parser_switch_defines_regexp_constants + URI.parser = URI::WHATWG_PARSER + + URI::WHATWG_PARSER.regexp.each_pair do |name, re| + assert_same(re, URI.const_get(name, false), name.to_s) + end + end + + def test_uri_parse_uses_whatwg_parser_after_switch + URI.parser = URI::WHATWG_PARSER + + assert_same(URI::WHATWG_PARSER, URI.parse("http://example.com/").parser) + assert_same(URI::WHATWG_PARSER, URI("http://example.com/").parser) + end + + def test_uri_parse_uses_default_parser_without_switch + assert_same(URI::RFC3986_PARSER, URI.parse("http://example.com/").parser) + end + + # --- regexp -------------------------------------------------------- + + def test_regexp_has_keys_used_by_generic_setters + %i[SCHEME USERINFO HOST PORT ABS_PATH REL_PATH QUERY FRAGMENT OPAQUE].each do |key| + assert_kind_of(Regexp, URI::WHATWG_PARSER.regexp[key], key.to_s) + end + end + + # --- split / parse / join ------------------------------------------ + + def test_split_returns_nine_components + assert_equal( + ["http", nil, "example.com", nil, nil, "/", nil, nil, nil], + URI::WHATWG_PARSER.split("http://example.com/") + ) + end + + def test_split_rejects_non_string + assert_raise(URI::InvalidURIError) { URI::WHATWG_PARSER.split(nil) } + assert_raise(URI::InvalidURIError) { URI::WHATWG_PARSER.split(1) } + end + + def test_split_accepts_object_responding_to_to_str + str = Object.new + def str.to_str; "http://example.com/"; end + assert_equal("example.com", URI::WHATWG_PARSER.split(str)[2]) + end + + def test_parse_returns_scheme_class_bound_to_whatwg_parser + uri = URI::WHATWG_PARSER.parse("http://example.com/") + + assert_kind_of(URI::HTTP, uri) + assert_equal("http://example.com/", uri.to_s) + assert_same(URI::WHATWG_PARSER, uri.parser) + end + + def test_join_with_single_argument + uri = URI::WHATWG_PARSER.join("http://example.com/") + + assert_equal("http://example.com/", uri.to_s) + assert_same(URI::WHATWG_PARSER, uri.parser) + end + + def test_join_with_absolute_second_argument + assert_equal( + "http://b.example/y", + URI::WHATWG_PARSER.join("http://a.example/x", "http://b.example/y").to_s + ) + end + + def test_join_does_not_share_strings_with_the_base + base = URI::WHATWG_PARSER.parse("http://u:p@h/a?q#f") + joined = URI::WHATWG_PARSER.join(base, "#g") + %i[scheme user password host path query].each do |component| + value = base.public_send(component) + value << "x" unless value.frozen? + end + assert_equal("http://u:p@h/a?q#g", joined.to_s) + end + + def test_join_returns_given_uri_object_unchanged + uri = URI::WHATWG_PARSER.parse("http://example.com/") + + assert_same(uri, URI::WHATWG_PARSER.join(uri)) + end + + # A URI that another parser built is parsed by the URL Standard, as + # its string would be. + def test_join_with_single_rfc3986_uri + rfc3986 = URI::RFC3986_PARSER.parse("HTTP://A/b/../c") + uri = URI::WHATWG_PARSER.join(rfc3986) + + assert_equal("http://a/c", uri.to_s) + assert_same(URI::WHATWG_PARSER, uri.parser) + assert_equal(URI::WHATWG_PARSER.parse("http://a/c"), uri) + uri.host = "\u{E9}" + assert_equal("http://xn--9ca/c", uri.to_s) + assert_equal("http://A/b/../c", rfc3986.to_s) + end + + def test_join_with_single_relative_rfc3986_uri + assert_raise(URI::InvalidURIError) { URI::WHATWG_PARSER.join(URI::RFC3986_PARSER.parse("/a")) } + end + + def test_join_with_rfc3986_uris + uri = URI::WHATWG_PARSER.join(URI::RFC3986_PARSER.parse("HTTP://A/b/"), URI::RFC3986_PARSER.parse("../c")) + assert_equal("http://a/c", uri.to_s) + assert_same(URI::WHATWG_PARSER, uri.parser) + end + + # --- convert_to_uri (used by Generic#merge / #route_to) ------------ + + def test_convert_to_uri_returns_uri_as_is + uri = URI::WHATWG_PARSER.parse("http://example.com/") + + assert_same(uri, URI::WHATWG_PARSER.__send__(:convert_to_uri, uri)) + end + + def test_convert_to_uri_parses_uri_of_another_parser + rfc3986 = URI::RFC3986_PARSER.parse("HTTP://A/b/../c") + uri = URI::WHATWG_PARSER.__send__(:convert_to_uri, rfc3986) + + assert_equal("http://a/c", uri.to_s) + assert_same(URI::WHATWG_PARSER, uri.parser) + end + + def test_convert_to_uri_returns_relative_uri_of_this_parser_as_is + uri = URI::WHATWG_PARSER.parse("http://h/a/b").route_to("http://h/a/c") + + assert_same(uri, URI::WHATWG_PARSER.__send__(:convert_to_uri, uri)) + end + + def test_convert_to_uri_parses_string + uri = URI::WHATWG_PARSER.__send__(:convert_to_uri, "http://example.com/") + + assert_equal("http://example.com/", uri.to_s) + assert_same(URI::WHATWG_PARSER, uri.parser) + end + + def test_convert_to_uri_rejects_other_objects + assert_raise(ArgumentError) { URI::WHATWG_PARSER.__send__(:convert_to_uri, nil) } + assert_raise(ArgumentError) { URI::WHATWG_PARSER.__send__(:convert_to_uri, 1) } + end + + # --- Generic#merge of a relative URI ------------------------------- + + # Generic#route_to can return a relative URI bound to WHATWG_PARSER. + # Merging into it behaves as for an RFC 3986 URI: an absolute URI is + # returned, and a relative reference raises BadURIError. + def relative_whatwg_uri + uri = URI::WHATWG_PARSER.parse("http://h/a/b").route_to("http://h/a/c") + assert_predicate(uri, :relative?) + assert_same(URI::WHATWG_PARSER, uri.parser) + uri + end + + def test_merge_relative_reference_into_relative_uri + ["x", "", "#f", "?q", "/x", "//h/x", "../x"].each do |reference| + assert_raise(URI::BadURIError, reference.dump) { relative_whatwg_uri.merge(reference) } + end + end + + def test_merge_relative_uri_object_into_relative_uri + assert_raise(URI::BadURIError) { relative_whatwg_uri.merge(relative_whatwg_uri) } + end + + def test_merge_absolute_string_into_relative_uri + uri = relative_whatwg_uri.merge("HTTP://H/x") + assert_equal("http://h/x", uri.to_s) + assert_same(URI::WHATWG_PARSER, uri.parser) + assert_equal("http://h/x", relative_whatwg_uri.merge(" \thttp://h/x ").to_s) + end + + def test_merge_absolute_uri_object_into_relative_uri + absolute = URI::WHATWG_PARSER.parse("http://h/x") + assert_same(absolute, relative_whatwg_uri.merge(absolute)) + end + + def test_merge_invalid_absolute_string_into_relative_uri + assert_raise(URI::InvalidURIError) { relative_whatwg_uri.merge("http://[/") } + end + + def test_merge_other_object_into_relative_uri + assert_raise(ArgumentError) { relative_whatwg_uri.merge(1) } + assert_raise(ArgumentError) { relative_whatwg_uri.merge(nil) } + end + + def test_plus_relative_reference_into_relative_uri + assert_raise(URI::BadURIError) { relative_whatwg_uri + "x" } + end + + # --- Generic#route_to / #route_from with a relative URI ------------ + + # As for RFC 3986 URIs, a route needs two absolute URIs, and a relative + # one raises BadURIError. + def test_route_to_relative_reference + uri = URI::WHATWG_PARSER.parse("http://h/a") + ["x", "", "#f", "?q", "/x", "//h/x"].each do |reference| + error = assert_raise(URI::BadURIError, reference.dump) { uri.route_to(reference) } + assert_equal("relative URI: #{reference}", error.message) + end + end + + def test_route_from_relative_reference + uri = URI::WHATWG_PARSER.parse("http://h/a") + ["x", "", "#f", "?q", "/x", "//h/x"].each do |reference| + assert_raise(URI::BadURIError, reference.dump) { uri.route_from(reference) } + end + end + + def test_route_to_and_from_relative_uri_object + uri = URI::WHATWG_PARSER.parse("http://h/a") + assert_raise(URI::BadURIError) { uri.route_to(relative_whatwg_uri) } + assert_raise(URI::BadURIError) { uri.route_from(relative_whatwg_uri) } + end + + def test_route_of_relative_uri + assert_raise(URI::BadURIError) { relative_whatwg_uri.route_to("http://h/a") } + assert_raise(URI::BadURIError) { relative_whatwg_uri.route_from("http://h/a") } + assert_raise(URI::BadURIError) { relative_whatwg_uri.route_to("x") } + assert_raise(URI::BadURIError) { relative_whatwg_uri.route_from("x") } + end + + def test_route_to_and_from_absolute_string + uri = URI::WHATWG_PARSER.parse("http://h/a/b") + assert_equal("c", uri.route_to("http://h/a/c").to_s) + assert_equal("c", uri.route_to(" HTTP://H/a/c ").to_s) + assert_equal("b", uri.route_from("http://h/a/c").to_s) + end + + def test_route_to_and_from_invalid_absolute_string + uri = URI::WHATWG_PARSER.parse("http://h/a") + assert_raise(URI::InvalidURIError) { uri.route_to("http://[/") } + assert_raise(URI::InvalidURIError) { uri.route_from("http://[/") } + end + + def test_route_to_and_from_other_object + uri = URI::WHATWG_PARSER.parse("http://h/a") + assert_raise(ArgumentError) { uri.route_to(1) } + assert_raise(ArgumentError) { uri.route_from(nil) } + end + + def test_minus_relative_reference + assert_raise(URI::BadURIError) { URI::WHATWG_PARSER.parse("http://h/a") - "x" } + end + + # --- Generic#route_to / #route_from between URLs ------------------- + + # The route from +base+ to +target+ is the shortest reference that + # resolves to +target+ against +base+ by the URL Standard. + def assert_route(expected, base, target) + base_uri = URI::WHATWG_PARSER.parse(base) + target_uri = URI::WHATWG_PARSER.parse(target) + route = base_uri.route_to(target) + message = "#{base} -> #{target}" + assert_equal(expected, route.to_s, message) + assert_equal(target_uri.to_s, (base_uri + route).to_s, message) + assert_equal(expected, target_uri.route_from(base).to_s, message) + assert_equal(expected, (target_uri - base_uri).to_s, message) + end + + def test_route_to_the_same_url + assert_route("", "http://a/b", "http://a/b") + assert_route("", "http://a/b?q", "http://a/b?q") + assert_route("#f", "http://a/b#f", "http://a/b#f") + end + + def test_route_to_a_fragment + assert_route("#f", "http://a/b", "http://a/b#f") + assert_route("", "http://a/b#f", "http://a/b") + assert_route("#", "http://a/b", "http://a/b#") + end + + def test_route_to_a_query + assert_route("?r", "http://a/b?q", "http://a/b?r") + assert_route("?r#f", "http://a/b", "http://a/b?r#f") + assert_route("?", "http://a/b", "http://a/b?") + assert_route("?%27%zz{|}", "http://a/b", "http://a/b?'%zz{|}") + assert_route("?'%zz{|}", "foo://a/b", "foo://a/b?'%zz{|}") + end + + def test_route_to_a_url_without_the_query_of_the_base + assert_route("c", "http://a/b/c?x", "http://a/b/c") + assert_route("./", "http://a/b/?x", "http://a/b/") + assert_route("./a:b", "http://a/a:b?x", "http://a/a:b") + end + + def test_route_to_a_path + assert_route("d", "http://a/b/c", "http://a/b/d") + assert_route("../x", "http://a/b/c", "http://a/x") + assert_route("c/d", "http://a/b/", "http://a/b/c/d") + assert_route("d?q#f", "http://a/b/c", "http://a/b/d?q#f") + assert_route("./a:b", "http://a/", "http://a/a:b") + end + + def test_route_to_a_path_with_empty_segments + assert_route("//a//x", "http://a/", "http://a//x") + assert_route("x//y", "http://a/b/", "http://a/b/x//y") + end + + def test_route_to_another_authority + assert_route("//b/c", "http://a/c", "http://b/c") + assert_route("//a/", "http://u@a/", "http://a/") + assert_route("//u:p@a/", "http://a/", "http://u:p@a/") + assert_route("//a/", "http://a:81/", "http://a/") + assert_route("//a:81/x", "http://a/", "http://a:81/x") + end + + def test_route_to_another_scheme + assert_route("https://a/b", "http://a/b", "https://a/b") + assert_route("foo://a/b", "http://a/b", "foo://a/b") + end + + def test_route_to_a_non_special_url_with_an_empty_path + assert_route("//h", "foo://h/a", "foo://h") + assert_route("/", "foo://h", "foo://h/") + assert_route("?q", "foo://h", "foo://h?q") + end + + def test_route_between_hostless_urls + assert_route("c", "foo:/a/b", "foo:/a/c") + assert_route("/.//b", "foo:/a", "foo:/.//b") + end + + def test_route_between_opaque_paths + assert_route("mailto:a?y", "mailto:a?x", "mailto:a?y") + assert_route("mailto:b", "mailto:a", "mailto:b") + assert_route("#f", "mailto:a", "mailto:a#f") + # Only a fragment resolves against an opaque path. + assert_route("mailto:a", "mailto:a#f", "mailto:a") + end + + def test_route_between_file_urls + assert_route("b", "file:///C:/a", "file:///C:/b") + assert_route("//h/a", "file:///a", "file://h/a") + end + + def test_route_is_bound_to_whatwg_parser + route = URI::WHATWG_PARSER.parse("http://a/b/c").route_to("http://a/b/d") + assert_predicate(route, :relative?) + assert_same(URI::WHATWG_PARSER, route.parser) + end + + def test_route_to_another_scheme_is_an_absolute_url + route = URI::WHATWG_PARSER.parse("http://a/b").route_to("https://a/b") + assert_predicate(route, :absolute?) + route.host = "\u{E9}" + assert_equal("https://xn--9ca/b", route.to_s) + end + + def test_route_to_an_rfc3986_uri + route = URI::WHATWG_PARSER.parse("http://a/b/c").route_to(URI::RFC3986_PARSER.parse("HTTP://A/b/d")) + assert_equal("d", route.to_s) + end + + # --- serialization ------------------------------------------------- + + # The URL serializer writes "//" only for a URL with a host, which + # Generic#to_s writes for any file or postgres URI. + def test_to_s_of_a_postgres_url_without_a_host + { + "postgres:/x" => "postgres:/x", + "postgres:/.//x" => "postgres:/.//x", + "postgres:/" => "postgres:/", + "postgres:" => "postgres:", + "postgres:?q#f" => "postgres:?q#f", + "postgres:/x?q#f" => "postgres:/x?q#f", + }.each do |input, expected| + uri = URI::WHATWG_PARSER.parse(input) + assert_equal(expected, uri.to_s, input) + assert_equal(expected, uri.to_str, input) + end + end + + def test_to_s_of_a_postgres_url_with_a_host + assert_equal("postgres://h/x", URI::WHATWG_PARSER.parse("postgres://h/x").to_s) + assert_equal("postgres:///x", URI::WHATWG_PARSER.parse("postgres:///x").to_s) + assert_equal("postgres://", URI::WHATWG_PARSER.parse("postgres://").to_s) + end + + def test_postgres_url_without_a_host + uri = URI::WHATWG_PARSER.parse("postgres:/x") + assert_not_equal(URI::WHATWG_PARSER.parse("postgres:///x"), uri) + assert_equal("postgres:/a/c", URI::WHATWG_PARSER.join("postgres:/a/b", "c").to_s) + assert_equal("postgres:/a/c", (URI::WHATWG_PARSER.parse("postgres:/a/b") + "c").to_s) + assert_equal("#", uri.inspect) + uri.path = "y" + assert_equal("postgres:/y", uri.to_s) + end + + def test_to_s_of_an_rfc3986_postgres_uri_without_a_host + assert_equal("postgres:///x", URI::RFC3986_PARSER.parse("postgres:/x").to_s) + end + + # --- normalize ----------------------------------------------------- + + # A URI built by WHATWG_PARSER is already normalized by the URL + # Standard. The normalization of RFC 3986 URIs would make another URL + # of it, such as by adding a path to a non-special URL or by changing + # the case of an opaque host. + def test_normalize_keeps_the_url + [ + "foo://h", + "foo://H/", + "foo://H%c3%a9/", + "foo:", + "foo:/a", + "mailto:X", + "http://h/", + "http://h/a%c3%a9?Q#F", + "file:///C:/a", + ].each do |str| + uri = URI::WHATWG_PARSER.parse(str) + assert_equal(uri.to_s, uri.normalize.to_s, str) + end + end + + def test_normalize_bang_keeps_the_url + uri = URI::WHATWG_PARSER.parse("foo://H") + uri.normalize! + assert_equal("foo://H", uri.to_s) + end + + def test_normalized_uri_keeps_the_setters + uri = URI::WHATWG_PARSER.parse("http://h/").normalize + uri.host = "\u{E9}" + assert_equal("http://xn--9ca/", uri.to_s) + end + + def test_rfc3986_uris_keep_their_normalization + assert_equal("foo://h/", URI::RFC3986_PARSER.parse("foo://H").normalize.to_s) + assert_equal("http://h/", URI::RFC3986_PARSER.parse("HTTP://H").normalize.to_s) + end + + # --- equality (URL equivalence) ------------------------------------ + + # Two URIs built by WHATWG_PARSER are equal when their serializations + # are (https://url.spec.whatwg.org/#url-equivalence); the URIs are not + # normalized as RFC 3986 URIs are. + def test_equal_uris + assert_equal(URI::WHATWG_PARSER.parse("http://h/a?q#f"), URI::WHATWG_PARSER.parse("http://h/a?q#f")) + assert_equal(URI::WHATWG_PARSER.parse("HTTP://H"), URI::WHATWG_PARSER.parse("http://h/")) + assert_equal(URI::WHATWG_PARSER.parse("http://h:80/"), URI::WHATWG_PARSER.parse("http://h/")) + assert_equal(URI::WHATWG_PARSER.parse("mailto:x"), URI::WHATWG_PARSER.parse("mailto:x")) + end + + def test_non_special_uris_with_and_without_an_empty_path_differ + assert_not_equal(URI::WHATWG_PARSER.parse("foo://h"), URI::WHATWG_PARSER.parse("foo://h/")) + assert_not_equal(URI::WHATWG_PARSER.parse("foo://h/"), URI::WHATWG_PARSER.parse("foo://h")) + end + + def test_opaque_hosts_differing_in_case_differ + assert_not_equal(URI::WHATWG_PARSER.parse("foo://H/"), URI::WHATWG_PARSER.parse("foo://h/")) + end + + def test_uris_differing_in_a_component_differ + base = URI::WHATWG_PARSER.parse("http://u:p@h:8080/a?q#f") + [ + "https://u:p@h:8080/a?q#f", + "http://x:p@h:8080/a?q#f", + "http://u:x@h:8080/a?q#f", + "http://u:p@x:8080/a?q#f", + "http://u:p@h:8081/a?q#f", + "http://u:p@h:8080/x?q#f", + "http://u:p@h:8080/a?x#f", + "http://u:p@h:8080/a?q#x", + "http://u:p@h:8080/a?q", + "http://u:p@h:8080/a#f", + "http://u:p@h:8080/a?q#", + ].each do |str| + assert_not_equal(base, URI::WHATWG_PARSER.parse(str), str) + end + end + + def test_equality_after_a_setter + uri = URI::WHATWG_PARSER.parse("http://h/") + uri.path = "a" + assert_equal(URI::WHATWG_PARSER.parse("http://h/a"), uri) + end + + # scheme= keeps the class, which the URL Standard does not have. + def test_equality_ignores_the_class + uri = URI::WHATWG_PARSER.parse("http://h/") + uri.scheme = "https" + assert_instance_of(URI::HTTP, uri) + assert_equal(URI::WHATWG_PARSER.parse("https://h/"), uri) + assert_equal(uri, URI::WHATWG_PARSER.parse("https://h/")) + end + + def test_whatwg_and_rfc3986_uris_differ + assert_not_equal(URI::WHATWG_PARSER.parse("http://h/"), URI::RFC3986_PARSER.parse("http://h/")) + assert_not_equal(URI::RFC3986_PARSER.parse("http://h/"), URI::WHATWG_PARSER.parse("http://h/")) + end + + def test_rfc3986_uris_keep_their_equality + assert_equal(URI::RFC3986_PARSER.parse("http://h"), URI::RFC3986_PARSER.parse("http://h/")) + assert_equal(URI::RFC3986_PARSER.parse("foo://H/"), URI::RFC3986_PARSER.parse("foo://h/")) + end + + def test_equality_returns_true_or_false + whatwg = URI::WHATWG_PARSER.parse("http://h/") + rfc3986 = URI::RFC3986_PARSER.parse("http://h/") + assert_same(true, whatwg == URI::WHATWG_PARSER.parse("http://h/")) + assert_same(false, whatwg == URI::WHATWG_PARSER.parse("http://x/")) + assert_same(false, whatwg == rfc3986) + assert_same(false, rfc3986 == whatwg) + assert_same(false, whatwg == "http://h/") + assert_same(false, whatwg == nil) + assert_same(true, rfc3986 == URI::RFC3986_PARSER.parse("http://h/")) + end + + def test_uri_is_not_equal_to_a_string + assert_not_equal(URI::WHATWG_PARSER.parse("http://h/"), "http://h/") + assert_not_equal(URI::WHATWG_PARSER.parse("http://h/"), nil) + end + + # --- RFC2396-compatible methods (obsolete, delegated) -------------- + + def test_extract_delegates_to_rfc2396 + EnvUtil.suppress_warning do + assert_equal(["http://example.com"], URI::WHATWG_PARSER.extract("x http://example.com y")) + assert_equal([], URI::WHATWG_PARSER.extract("x http://example.com y", ["ftp"])) + assert_equal(["http://example.com"], URI::WHATWG_PARSER.extract("http://example.com", ["http"])) + end + end + + def test_extract_with_block + EnvUtil.suppress_warning do + found = [] + URI::WHATWG_PARSER.extract("http://example.com") { |u| found << u } + assert_equal(["http://example.com"], found) + end + end + + def test_make_regexp_delegates_to_rfc2396 + EnvUtil.suppress_warning do + assert_match(URI::WHATWG_PARSER.make_regexp, "http://example.com") + assert_match(URI::WHATWG_PARSER.make_regexp(["http"]), "http://example.com") + assert_no_match(URI::WHATWG_PARSER.make_regexp(["ftp"]), "http://example.com") + end + end + + def test_escape_delegates_to_rfc2396 + EnvUtil.suppress_warning do + assert_equal("a%20b", URI::WHATWG_PARSER.escape("a b")) + assert_equal("%61b", URI::WHATWG_PARSER.escape("ab", /a/)) + end + end + + def test_unescape_delegates_to_rfc2396 + EnvUtil.suppress_warning do + assert_equal("a b", URI::WHATWG_PARSER.unescape("a%20b")) + assert_equal("a%20b", URI::WHATWG_PARSER.unescape("a%20b", /%41/)) + end + end + + def test_uri_extract_and_regexp_work_after_switch + URI.parser = URI::WHATWG_PARSER + + EnvUtil.suppress_warning do + assert_equal(["http://example.com"], URI.extract("http://example.com")) + assert_match(URI.regexp, "http://example.com") + end + end + + def test_obsolete_methods_warn_when_verbose + assert_warning(/URI::WHATWG_PARSER\.extract is obsolete/) { URI::WHATWG_PARSER.extract("") } + assert_warning(/URI::WHATWG_PARSER\.make_regexp is obsolete/) { URI::WHATWG_PARSER.make_regexp } + assert_warning(/URI::WHATWG_PARSER\.escape is obsolete/) { URI::WHATWG_PARSER.escape("") } + assert_warning(/URI::WHATWG_PARSER\.unescape is obsolete/) { URI::WHATWG_PARSER.unescape("") } + end + + def test_obsolete_methods_do_not_warn_when_not_verbose + verbose, $VERBOSE = $VERBOSE, false + stderr, $stderr = $stderr, StringIO.new + URI::WHATWG_PARSER.extract("") + URI::WHATWG_PARSER.make_regexp + URI::WHATWG_PARSER.escape("") + URI::WHATWG_PARSER.unescape("") + assert_equal("", $stderr.string) + ensure + $stderr = stderr + $VERBOSE = verbose + end + + # --- preprocessing ------------------------------------------------- + # https://url.spec.whatwg.org/#concept-basic-url-parser (steps 1-3) + + SIMPLE = ["http", nil, "example.com", nil, nil, "/", nil, nil, nil].freeze + + def split(str) + URI::WHATWG_PARSER.split(str) + end + + def test_split_strips_leading_and_trailing_spaces + assert_equal(SIMPLE, split(" http://example.com/ ")) + end + + def test_split_strips_leading_and_trailing_c0_controls + assert_equal(SIMPLE, split("\x00\x01\x1Fhttp://example.com/\x1F\x0B\x00")) + end + + def test_split_strips_every_c0_control_and_space_at_both_ends + all = (0x00..0x20).map(&:chr).join + assert_equal(SIMPLE, split("#{all}http://example.com/#{all}")) + end + + def test_split_does_not_strip_just_outside_c0_control_or_space_range + # U+0021 "!" and U+007F DELETE are not C0 control or space. + assert_equal("/!", split("http://example.com/!")[5]) + assert_not_equal(SIMPLE, split("http://example.com/\x7F")) + end + + def test_split_does_not_strip_non_ascii_whitespace + # U+00A0 NO-BREAK SPACE and U+3000 IDEOGRAPHIC SPACE are kept. + assert_not_equal(SIMPLE, split("http://example.com/\u00A0")) + assert_not_equal(SIMPLE, split("http://example.com/\u3000")) + end + + def test_split_removes_tab_and_newlines_anywhere + assert_equal(SIMPLE, split("ht\ttp://exa\nmple.com\r/")) + assert_equal(SIMPLE, split("\r\nhttp://example.com/\t")) + end + + def test_split_keeps_other_inner_c0_controls_and_spaces + # Only tab, LF and CR are removed from the inside of the input. + assert_not_equal(SIMPLE, split("http://example.com/a\x0Bb")) + assert_not_equal(SIMPLE, split("http://example.com/a\x0Cb")) + assert_not_equal(SIMPLE, split("http://example.com/a b")) + end + + def test_split_does_not_modify_its_argument + str = +" ht\ttp://example.com/ " + split(str) + assert_equal(" ht\ttp://example.com/ ", str) + end + + def test_split_accepts_frozen_string + assert_equal(SIMPLE, split(" http://example.com/ ".freeze)) + end + + def test_split_strips_in_linear_time + # Inner runs of C0 control or space must not cause backtracking. + pre = ->(n) { "http://example.com/" + " " * n + "a" } + assert_linear_performance((1..5).map { |i| 10**i }, pre: pre) do |uri| + split(uri) + end + end + + # --- input encoding ------------------------------------------------ + + def test_split_accepts_us_ascii_and_binary_ascii_only_input + assert_equal(SIMPLE, split("http://example.com/".encode("US-ASCII"))) + assert_equal(SIMPLE, split("http://example.com/".b)) + end + + def test_split_converts_other_encodings_to_utf8 + assert_equal(SIMPLE, split("http://example.com/".encode("UTF-16LE"))) + assert_equal(SIMPLE, split(" http://example.com/ ".encode("UTF-16BE"))) + end + + def test_split_returns_utf8_components + split("http://example.com/".encode("UTF-16LE")).compact.each do |component| + assert_equal(Encoding::UTF_8, component.encoding, component) + end + end + + def test_split_rejects_invalid_byte_sequence + assert_raise(URI::InvalidURIError) { split("http://example.com/\xFF") } + assert_raise(URI::InvalidURIError) { split("http://example.com/\xE3\x81") } + end + + def test_split_rejects_binary_input_with_non_ascii_bytes + assert_raise(URI::InvalidURIError) { split("http://example.com/\xE3\x81\x82".b) } + end + + def test_split_rejects_invalid_utf16_input + # An unpaired high surrogate (U+D800) is not a valid UTF-16 sequence. + lone_surrogate = ("http://example.com/".encode("UTF-16LE").b + "\x00\xD8".b).force_encoding("UTF-16LE") + assert_raise(URI::InvalidURIError) { split(lone_surrogate) } + end + + # --- scheme -------------------------------------------------------- + # https://url.spec.whatwg.org/#scheme-start-state + # https://url.spec.whatwg.org/#scheme-state + # https://url.spec.whatwg.org/#no-scheme-state + + def test_split_lowercases_scheme + assert_equal("http", split("HTTP://example.com/")[0]) + assert_equal("https", split("HtTpS://example.com/")[0]) + assert_equal("foo", split("FOO:bar")[0]) + end + + def test_split_scheme_may_contain_digits_plus_hyphen_and_dot + assert_equal("a+b-c.d0", split("a+b-c.d0:x")[0]) + assert_equal("a9", split("a9:x")[0]) + end + + def test_split_single_letter_scheme + assert_equal("a", split("a:x")[0]) + assert_equal("z", split("Z:x")[0]) + end + + def test_split_scheme_letter_boundaries + # "A", "Z", "a", "z" start a scheme; "@", "[", "`", "{" (their + # neighbours in ASCII) do not. + %w[A Z a z].each { |c| assert_equal(c.downcase, split("#{c}:x")[0], c) } + ["@", "[", "`", "{"].each { |c| assert_raise(URI::InvalidURIError, c) { split("#{c}a:x") } } + end + + def test_split_scheme_digit_boundaries + # "0" and "9" may follow the first letter; "/" (before "0") may not. + assert_equal("a0", split("a0:x")[0]) + assert_equal("a9", split("a9:x")[0]) + assert_raise(URI::InvalidURIError) { split("a/:x") } + end + + def test_split_scheme_must_start_with_letter + %w[1a:x +a:x -a:x .a:x].each do |input| + assert_raise(URI::InvalidURIError, input) { split(input) } + end + end + + def test_split_scheme_rejects_other_characters + ["a_b:x", "a b:x", "a%62:x", "a!b:x"].each do |input| + assert_raise(URI::InvalidURIError, input) { split(input) } + end + end + + def test_split_scheme_rejects_non_ascii_letters + # U+212A KELVIN SIGN lowercases to "k" with Unicode case mapping, but + # it is not an ASCII alpha. + ["\u00E9:x", "a\u00E9:x", "\u212A:x", "\u212Ahttp:x"].each do |input| + assert_raise(URI::InvalidURIError, input) { split(input) } + end + end + + def test_split_without_scheme_fails_without_base + ["example.com", "/path", "//example.com/", "?q", "#f", "", " ", ":", ":foo"].each do |input| + assert_raise(URI::InvalidURIError, input.inspect) { split(input) } + end + end + + def test_parse_without_scheme_fails + assert_raise(URI::InvalidURIError) { URI::WHATWG_PARSER.parse("example.com") } + end + + def test_split_uses_first_colon_as_scheme_delimiter + assert_equal(["foo", "bar:baz"], split("foo:bar:baz").values_at(0, 6)) + end + + def test_split_special_schemes_are_hierarchical + %w[http https ws wss ftp].each do |scheme| + assert_equal( + [scheme, nil, "example.com", nil, nil, "/", nil, nil, nil], + split("#{scheme}://example.com/"), + scheme + ) + end + end + + def test_split_file_scheme_is_hierarchical + # file is a special scheme. Its own states (file state, file host + # state, ...) are not implemented yet. + assert_equal(["file", nil], split("FILE:///tmp/a").values_at(0, 6)) + end + + def test_split_non_special_scheme_with_opaque_path + assert_equal(["foo", nil, nil, nil, nil, nil, "bar", nil, nil], split("foo:bar")) + end + + def test_split_non_special_scheme_with_empty_opaque_path + assert_equal(["foo", nil, nil, nil, nil, nil, "", nil, nil], split("foo:")) + end + + def test_split_non_special_scheme_with_path + assert_equal(["foo", nil, nil, nil, nil, "/bar", nil, nil, nil], split("foo:/bar")) + end + + def test_split_non_special_scheme_with_authority + assert_equal(["foo", nil, "host", nil, nil, "/bar", nil, nil, nil], split("foo://host/bar")) + end + + def test_split_scheme_that_only_resembles_a_special_one_is_non_special + # "http" is special only as the whole scheme. + assert_equal("httpx", split("httpx:bar")[0]) + assert_equal("bar", split("httpx:bar")[6]) + assert_equal("bar", split("htt:bar")[6]) + end + + def test_parse_non_special_opaque_round_trip + assert_equal("foo:bar", URI::WHATWG_PARSER.parse("foo:bar").to_s) + assert_equal("foo:", URI::WHATWG_PARSER.parse("foo:").to_s) + end + + # --- authority ----------------------------------------------------- + # https://url.spec.whatwg.org/#special-authority-slashes-state + # https://url.spec.whatwg.org/#special-authority-ignore-slashes-state + # https://url.spec.whatwg.org/#path-or-authority-state + # https://url.spec.whatwg.org/#authority-state + # https://url.spec.whatwg.org/#host-state + + USERINFO, HOST, PORT, PATH, OPAQUE = 1, 2, 3, 5, 6 + + def test_split_special_authority_ignores_any_number_of_slashes + ["http:example.com/", "http:/example.com/", "http://example.com/", + "http:///example.com/", "http:////example.com/"].each do |input| + assert_equal("example.com", split(input)[HOST], input) + end + end + + def test_split_special_authority_treats_backslash_as_slash + ["http:\\\\example.com/", "http:/\\example.com/", "http:\\/example.com/", + "http:\\example.com/"].each do |input| + assert_equal("example.com", split(input)[HOST], input) + end + end + + def test_split_ignoring_slashes_applies_to_every_special_scheme + %w[https ws wss ftp].each do |scheme| + assert_equal("example.com", split("#{scheme}:example.com/")[HOST], scheme) + assert_equal("example.com", split("#{scheme}:\\\\example.com/")[HOST], scheme) + end + end + + def test_split_non_special_needs_exactly_two_slashes_for_authority + assert_equal([nil, "/host/x"], split("foo:/host/x").values_at(HOST, PATH)) + assert_equal(["", "/x"], split("foo:///x").values_at(HOST, PATH)) + assert_equal(["host", "/x"], split("foo://host/x").values_at(HOST, PATH)) + end + + def test_split_non_special_does_not_treat_backslash_as_slash + assert_equal([nil, "\\\\host"], split("foo:\\\\host").values_at(HOST, OPAQUE)) + assert_equal([nil, "/\\host"], split("foo:/\\host").values_at(HOST, PATH)) + end + + def test_split_special_authority_ends_at_slash_question_hash_or_backslash + %w[/ ? # \\].each do |c| + assert_equal("host", split("http://host#{c}x")[HOST], c) + end + end + + def test_split_non_special_authority_ends_at_slash_question_or_hash + %w[/ ? #].each do |c| + assert_equal("host", split("foo://host#{c}x")[HOST], c) + end + end + + def test_split_authority_at_end_of_input + assert_equal("host", split("http://host")[HOST]) + assert_equal("host", split("foo://host")[HOST]) + end + + def test_split_userinfo + assert_equal(["user:pass", "host"], split("http://user:pass@host/").values_at(USERINFO, HOST)) + end + + def test_split_userinfo_username_only + assert_equal("user", split("http://user@host/")[USERINFO]) + end + + def test_split_userinfo_empty_password_is_dropped + assert_equal("user", split("http://user:@host/")[USERINFO]) + end + + def test_split_userinfo_password_only + assert_equal(":pass", split("http://:pass@host/")[USERINFO]) + end + + def test_split_userinfo_empty_is_nil + assert_nil(split("http://@host/")[USERINFO]) + assert_nil(split("http://:@host/")[USERINFO]) + end + + def test_split_userinfo_splits_at_last_at_sign + # Every "@" but the last one belongs to the userinfo, as "%40". + assert_equal(["a%40b", "host"], split("http://a@b@host/").values_at(USERINFO, HOST)) + assert_equal("a%40b%40c", split("http://a@b@c@host/")[USERINFO]) + end + + def test_split_userinfo_splits_password_at_first_colon + assert_equal("a%40b:c", split("http://a@b:c@host/")[USERINFO]) + end + + def test_split_userinfo_in_non_special_url + assert_equal(["user:pass", "host"], split("foo://user:pass@host/").values_at(USERINFO, HOST)) + end + + def test_split_at_sign_after_authority_is_not_userinfo + ["http://host/a@b", "http://host?a@b", "http://host#a@b"].each do |input| + assert_equal([nil, "host"], split(input).values_at(USERINFO, HOST), input) + end + end + + def test_split_backslash_ends_special_authority_before_at_sign + assert_equal([nil, "user"], split("http://user\\@host/").values_at(USERINFO, HOST)) + end + + def test_split_host_and_port + assert_equal(["host", "8080"], split("http://host:8080/").values_at(HOST, PORT)) + assert_equal(["host", "8080"], split("http://u:p@host:8080/").values_at(HOST, PORT)) + end + + def test_split_without_port + assert_nil(split("http://host/")[PORT]) + end + + def test_split_colon_inside_brackets_is_not_port_delimiter + assert_equal(["[::1]", "8080"], split("http://[::1]:8080/").values_at(HOST, PORT)) + assert_equal(["[::1]", nil], split("http://[::1]/").values_at(HOST, PORT)) + end + + def test_split_brackets_in_userinfo_do_not_affect_port + assert_equal(["u%5B", "host", "8080"], split("http://u[@host:8080/").values_at(USERINFO, HOST, PORT)) + end + + def test_split_special_url_needs_host + ["http://", "http:///", "http:", "http:/", "http://?q", "http://#f", "http:\\\\"].each do |input| + assert_raise(URI::InvalidURIError, input) { split(input) } + end + end + + def test_split_userinfo_without_host_fails + ["http://user@/", "http://@/", "http://user@", "http://u:p@", "foo://@", "foo://user@/"].each do |input| + assert_raise(URI::InvalidURIError, input) { split(input) } + end + end + + def test_split_port_without_host_fails + ["http://:80/", "foo://:80/", "http://u@:80/"].each do |input| + assert_raise(URI::InvalidURIError, input) { split(input) } + end + end + + def test_split_non_special_url_may_have_empty_host + assert_equal("", split("foo://")[HOST]) + assert_equal("", split("foo:///")[HOST]) + assert_equal("", split("foo://?q")[HOST]) + end + + def test_split_file_host_may_be_empty + assert_equal(["", "/tmp/a"], split("file:///tmp/a").values_at(HOST, PATH)) + assert_equal(["host", "/a"], split("file://host/a").values_at(HOST, PATH)) + assert_equal(["host", "/a"], split("file:\\\\host/a").values_at(HOST, PATH)) + assert_equal(["", "/a"], split("file:/a").values_at(HOST, PATH)) + end + + # --- host: domain ------------------------------------------------- + # https://url.spec.whatwg.org/#concept-host-parser + # https://url.spec.whatwg.org/#concept-domain-to-ascii + + def test_split_domain_is_ascii_lowercased + assert_equal("example.com", split("http://EXAMPLE.COM/")[HOST]) + assert_equal("example.com", split("http://ExAmPlE.cOm/")[HOST]) + end + + def test_split_domain_is_percent_decoded + assert_equal("example.com", split("http://ex%61mple.com/")[HOST]) + assert_equal("example.com", split("http://ex%41mple.com/")[HOST]) + assert_equal("example.com", split("http://example%2ecom/")[HOST]) + assert_equal("example.com", split("http://example%2Ecom/")[HOST]) + end + + def test_split_domain_percent_decoded_to_forbidden_code_point_fails + %w[%25 %2F %20 %00 %3A %40 %3C %7C %7F %01].each do |encoded| + assert_raise(URI::InvalidURIError, encoded) { split("http://a#{encoded}b/") } + end + end + + def test_split_domain_with_invalid_percent_sequence_fails + # "%" not followed by two hex digits is left alone, and "%" is a + # forbidden domain code point. + ["http://a%zzb/", "http://a%/", "http://a%4/", "http://a%4g/"].each do |input| + assert_raise(URI::InvalidURIError, input) { split(input) } + end + end + + def test_split_domain_with_forbidden_code_point_fails + ["\x00", " ", "<", ">", "[", "]", "^", "|", "%", "\x01", "\x1F", "\x7F"].each do |c| + assert_raise(URI::InvalidURIError, c.dump) { split("http://a#{c}b/") } + end + end + + def test_split_domain_code_point_boundaries + # U+0020 SPACE and U+007F DELETE are forbidden; U+0021 "!" and U+007E + # "~" next to them are not. + assert_equal("a!b", split("http://a!b/")[HOST]) + assert_equal("a~b", split("http://a~b/")[HOST]) + end + + def test_split_domain_allows_other_ascii_punctuation + assert_equal("a$&'()*+,;=_-b", split("http://a$&'()*+,;=_-b/")[HOST]) + end + + def test_split_domain_with_empty_labels + assert_equal(".", split("http://./")[HOST]) + assert_equal("..", split("http://../")[HOST]) + assert_equal("a..b", split("http://a..b/")[HOST]) + assert_equal("example.com.", split("http://example.com./")[HOST]) + end + + def test_split_domain_rules_apply_to_every_special_scheme + %w[https ws wss ftp].each do |scheme| + assert_equal("example.com", split("#{scheme}://EX%41MPLE.com/")[HOST], scheme) + assert_raise(URI::InvalidURIError, scheme) { split("#{scheme}://a b/") } + end + end + + def test_split_ascii_xn_label_is_lowercased_without_validation + # The domain parser returns an ASCII domain lowercased (beStrict is + # false), even when an "xn--" label is not valid Punycode. + assert_equal("xn--9ca.example", split("http://XN--9CA.example/")[HOST]) + assert_equal("xn--", split("http://xn--/")[HOST]) + assert_equal("a.xn--pokxncvks", split("http://a.XN--pokxncvks/")[HOST]) + end + + # https://url.spec.whatwg.org/#concept-domain-to-ascii + + def test_split_non_ascii_domain_to_ascii + assert_equal("xn--9ca.example", split("http://\u{E9}.example/")[HOST]) + assert_equal("xn--wgv71a119e.jp", split("http://\u{65E5}\u{672C}\u{8A9E}.jp/")[HOST]) + end + + def test_split_percent_encoded_non_ascii_domain_to_ascii + assert_equal("xn--9ca.example", split("http://%C3%A9.example/")[HOST]) + assert_equal("xn--9ca.example", split("http://%c3%a9.example/")[HOST]) + end + + def test_split_non_ascii_domain_mapped_to_ascii + assert_equal("example.com", split("http://\u{FF25}\u{FF38}\u{FF21}\u{FF2D}\u{FF30}\u{FF2C}\u{FF25}.com/")[HOST]) + assert_equal("example.com", split("http://ex\u{AD}ample.com/")[HOST]) + assert_equal("example.com", split("http://ex%C2%ADample.com/")[HOST]) + assert_equal("example.com", split("http://example\u{3002}com/")[HOST]) + end + + def test_split_non_ascii_domain_failure + [ + "http://\u{FFFD}/", # disallowed + "http://a\u{200C}b/", # ZWNJ without context + "http://\u{301}a/", # leading combining mark + "http://a\u{5D0}/", # Bidi Rule + "http://xn--a.\u{E9}/", # "xn--" label decoding to U+0080 + "http://xn--a-!.\u{E9}/", # invalid Punycode + ].each do |input| + assert_raise(URI::InvalidURIError, input.dump) { split(input) } + end + end + + def test_split_domain_not_valid_utf8_fails + ["http://%FF/", "http://a%C3/", "http://%C3%28/"].each do |input| + assert_raise(URI::InvalidURIError, input) { split(input) } + end + end + + def test_split_non_ascii_domain_mapped_to_empty_fails + assert_raise(URI::InvalidURIError) { split("http://\u{AD}/") } + assert_raise(URI::InvalidURIError) { split("http://%C2%AD/") } + end + + def test_split_non_ascii_domain_mapped_to_forbidden_code_point_fails + # U+FF05 FULLWIDTH PERCENT SIGN maps to "%". + assert_raise(URI::InvalidURIError) { split("http://a\u{FF05}b/") } + end + + def test_split_non_ascii_domain_ending_in_a_number_is_ipv4 + assert_equal("127.0.0.1", split("http://\u{FF11}\u{FF12}\u{FF17}.0.0.1/")[HOST]) + assert_equal("127.0.0.1", split("http://127\u{3002}0.0.1/")[HOST]) + end + + def test_split_non_ascii_domain_in_a_ractor + omit "Ractor is not available" unless defined?(Ractor) + assert_separately(%w[-W0], <<~'RUBY') + require "uri" + r = Ractor.new { URI::WHATWG_PARSER.parse("http://e\u{301}.example/").host } + assert_equal("xn--9ca.example", r.respond_to?(:value) ? r.value : r.take) + RUBY + end + + # Before Ruby 4.0, concurrent Ractors processing non-ASCII strings can + # corrupt memory even without uri (URI.encode_www_form_component of a + # non-ASCII string crashes as well), so this runs on Ruby 4.0 or later. + def test_split_non_ascii_domain_in_concurrent_ractors + omit "Ractor is not available" unless defined?(Ractor) + omit "Ractors before Ruby 4.0 are not stable enough" if (RUBY_VERSION.split(".").map(&:to_i) <=> [4, 0]) < 0 + assert_separately(%w[-W0], <<~'RUBY') + require "uri" + ractors = 8.times.map { Ractor.new { URI::WHATWG_PARSER.parse("http://e\u{301}.example/").host } } + hosts = ractors.map { |r| r.respond_to?(:value) ? r.value : r.take } + assert_equal(["xn--9ca.example"] * 8, hosts) + RUBY + end + + # A require in a non-main Ractor is not safe before Ruby 4.0, which + # runs it in the main Ractor, so the Unicode data, which is otherwise + # loaded on first use, is loaded with uri where Ractors are available. + def test_unicode_data_is_loaded_with_uri_only_where_ractors_cannot_require + assert_separately([], <<~'RUBY') + require "uri" + version = RUBY_VERSION.split(".").map(&:to_i) + eager = !!defined?(Ractor) && (version <=> [3, 0]) >= 0 && (version <=> [4, 0]) < 0 + assert_equal(eager, URI::WHATWG_Parser::IDNA.const_defined?(:BIDI_NSM, false), "IDNA data") + assert_equal(eager, URI::WHATWG_Parser::NFC.const_defined?(:COMPOSITION, false), "NFC tables") + RUBY + end + + def test_split_non_ascii_domain_in_linear_time + distinct = ->(n) { "http://" + (0x4E00...0x4E00 + n).map { |c| c.chr(Encoding::UTF_8) }.join + "/" } + assert_linear_performance([300, 1_000, 3_000, 10_000], pre: distinct) do |uri| + split(uri) + end + # Bidi Rule and CONTEXTJ (ZWNJ between transparent marks). + rtl = ->(n) { "http://" + "\u{5D0}\u{5B0}" * n + "." + "\u{628}\u{64B}\u{200C}\u{64B}\u{628}" * n + "/" } + assert_linear_performance([300, 1_000, 3_000, 10_000], pre: rtl) do |uri| + split(uri) + end + end + + def test_split_non_ascii_domain_rules_apply_to_every_special_scheme + %w[https ws wss ftp].each do |scheme| + assert_equal("xn--9ca", split("#{scheme}://\u{E9}/")[HOST], scheme) + end + assert_equal("xn--9ca", split("file://\u{E9}/p")[HOST]) + end + + def test_split_bracketed_host_must_end_with_bracket + ["http://[::1/", "http://[/", "http://[::1]x/", "foo://[::1/"].each do |input| + assert_raise(URI::InvalidURIError, input) { split(input) } + end + end + + # --- host: IPv4 --------------------------------------------------- + # https://url.spec.whatwg.org/#ends-in-a-number-checker + # https://url.spec.whatwg.org/#concept-ipv4-parser + # https://url.spec.whatwg.org/#ipv4-number-parser + # https://url.spec.whatwg.org/#concept-ipv4-serializer + + def host(input) + split(input)[HOST] + end + + def assert_ipv4_failure(*inputs) + inputs.each do |input| + assert_raise(URI::InvalidURIError, input) { split(input) } + end + end + + def test_split_ipv4_dotted_decimal + assert_equal("192.168.0.1", host("http://192.168.0.1/")) + assert_equal("0.0.0.0", host("http://0.0.0.0/")) + assert_equal("255.255.255.255", host("http://255.255.255.255/")) + end + + def test_split_ipv4_octal_and_hex_parts + assert_equal("192.168.0.1", host("http://0300.0250.0.01/")) + assert_equal("192.168.0.1", host("http://0xc0.0xA8.0X0.0x1/")) + assert_equal("192.168.0.1", host("http://0xC0.0250.0.1/")) + end + + def test_split_ipv4_number_prefix_only + # "0x" alone is 0; "0" and "00" are 0. + assert_equal("0.0.0.0", host("http://0x/")) + assert_equal("0.0.0.0", host("http://0X/")) + assert_equal("0.0.0.0", host("http://0/")) + assert_equal("0.0.0.0", host("http://00/")) + assert_equal("1.0.0.0", host("http://1.0x.0.00/")) + end + + def test_split_ipv4_one_part + assert_equal("192.168.0.1", host("http://3232235521/")) + assert_equal("192.168.0.1", host("http://0xc0a80001/")) + end + + def test_split_ipv4_two_parts + # The last part fills the remaining three bytes. + assert_equal("192.168.0.1", host("http://192.11010049/")) + end + + def test_split_ipv4_three_parts + # The last part fills the remaining two bytes. + assert_equal("192.168.0.1", host("http://192.168.1/")) + end + + def test_split_ipv4_trailing_dot_is_ignored_once + assert_equal("1.2.3.4", host("http://1.2.3.4./")) + assert_equal("0.0.0.1", host("http://1./")) + # With two trailing dots the last label is still empty, so it does not + # end in a number and is a domain. + assert_equal("1.2.3.4..", host("http://1.2.3.4../")) + end + + def test_split_ipv4_more_than_four_parts_fails + assert_ipv4_failure("http://1.2.3.4.5/", "http://1.2.3.4.5./", "http://0.0.0.0.0/") + end + + def test_split_ipv4_empty_part_fails + assert_ipv4_failure("http://1..2/", "http://.1/", "http://1.2..3/") + end + + def test_split_ipv4_non_last_part_boundaries + assert_equal("255.0.0.0", host("http://255.0.0.0/")) + assert_ipv4_failure("http://256.0.0.0/", "http://0.256.0.0/", "http://0.0.256.0/") + assert_ipv4_failure("http://0x100.0.0.0/", "http://0400.0.0.0/") + end + + def test_split_ipv4_last_part_boundaries + assert_equal("0.0.0.255", host("http://0.0.0.255/")) + assert_ipv4_failure("http://0.0.0.256/") + + assert_equal("1.2.255.255", host("http://1.2.65535/")) + assert_ipv4_failure("http://1.2.65536/") + + assert_equal("1.255.255.255", host("http://1.16777215/")) + assert_ipv4_failure("http://1.16777216/") + + assert_equal("255.255.255.255", host("http://4294967295/")) + assert_equal("255.255.255.255", host("http://0xffffffff/")) + assert_equal("255.255.255.255", host("http://037777777777/")) + assert_ipv4_failure("http://4294967296/", "http://0x100000000/", "http://040000000000/") + end + + def test_split_ipv4_huge_numbers_fail + assert_ipv4_failure("http://99999999999999999999999999/", "http://1.2.3.99999999999999999999/", + "http://0x#{"f" * 100}/") + end + + def test_split_ipv4_leading_zeros + assert_equal("0.0.0.1", host("http://#{"0" * 1000}1/")) + assert_equal("0.0.0.1", host("http://0x#{"0" * 1000}1/")) + end + + def test_split_ipv4_invalid_digits_fail + # "08" and "09" are octal; "+", "-", "_" and spaces are not digits. + assert_ipv4_failure("http://08/", "http://09/", "http://1.08/", "http://0xg.1/", "http://0x0x1.1/", + "http://+1.2.3.4/", "http://-1.2.3.4/", "http://1_0.1/", "http://1e1.1/") + end + + def test_split_ends_in_a_number_but_not_ipv4_fails + assert_ipv4_failure("http://example.1/", "http://foo.09/", "http://foo.0x/", "http://example.1./", + "http://foo.0x1f/") + end + + def test_split_not_ending_in_a_number_is_a_domain + assert_equal("1.example", host("http://1.example/")) + assert_equal("foo.0xg", host("http://foo.0xg/")) + assert_equal("1.2.3.4a", host("http://1.2.3.4a/")) + assert_equal("1..", host("http://1../")) + assert_equal("0x1.example", host("http://0x1.example/")) + end + + def test_split_ipv4_after_percent_decoding + assert_equal("1.2.3.4", host("http://%31.%32.%33.%34/")) + assert_equal("127.0.0.1", host("http://%30x7f.1/")) + end + + def test_split_ipv4_for_every_special_scheme + %w[https ws wss ftp].each do |scheme| + assert_equal("127.0.0.1", host("#{scheme}://0x7f.1/"), scheme) + end + end + + def test_split_opaque_host_is_not_parsed_as_ipv4 + assert_equal("0x7f.1", host("foo://0x7f.1/")) + assert_equal("1.2.3.08", host("foo://1.2.3.08/")) + end + + def test_parse_serializes_ipv4_host + assert_equal("http://127.0.0.1/", URI::WHATWG_PARSER.parse("http://0x7f.1/").to_s) + end + + def test_split_ipv4_in_linear_time + pre = ->(n) { "http://1.2.3." + "9" * n + "/" } + assert_linear_performance((2..5).map { |i| 10**i }, pre: pre) do |uri| + assert_raise(URI::InvalidURIError) { split(uri) } + end + end + + # --- host: IPv6 --------------------------------------------------- + # https://url.spec.whatwg.org/#concept-ipv6-parser + # https://url.spec.whatwg.org/#concept-ipv6-serializer + + def ipv6(address, scheme = "http") + host("#{scheme}://[#{address}]/") + end + + def assert_ipv6_failure(*addresses) + addresses.each do |address| + assert_raise(URI::InvalidURIError, address) { split("http://[#{address}]/") } + end + end + + def test_split_ipv6_loopback_and_unspecified + assert_equal("[::1]", ipv6("::1")) + assert_equal("[::1]", ipv6("0:0:0:0:0:0:0:1")) + assert_equal("[::]", ipv6("::")) + assert_equal("[::]", ipv6("0:0:0:0:0:0:0:0")) + end + + def test_split_ipv6_full_address_is_kept + assert_equal("[2001:db8:85a3:8d3:1319:8a2e:370:7348]", ipv6("2001:db8:85a3:8d3:1319:8a2e:370:7348")) + end + + def test_split_ipv6_is_lowercased_without_leading_zeros + assert_equal("[abcd::ef]", ipv6("ABCD::EF")) + assert_equal("[1:db8::]", ipv6("0001:0db8::")) + assert_equal("[ffff::]", ipv6("FFFF::")) + end + + def test_split_ipv6_compression_position + assert_equal("[1::]", ipv6("1::")) + assert_equal("[::1:2]", ipv6("::1:2")) + assert_equal("[1:2::3:4]", ipv6("1:2::3:4")) + assert_equal("[::1:2:3:4:5:6]", ipv6("0:0:1:2:3:4:5:6")) + assert_equal("[1:2:3:4:5:6::]", ipv6("1:2:3:4:5:6:0:0")) + end + + def test_split_ipv6_compresses_longest_zero_run + assert_equal("[1:0:0:2::3]", ipv6("1:0:0:2:0:0:0:3")) + assert_equal("[1::2:0:0:3]", ipv6("1:0:0:0:2:0:0:3")) + end + + def test_split_ipv6_compresses_first_of_equally_long_zero_runs + assert_equal("[1::2:0:0:3:4]", ipv6("1:0:0:2:0:0:3:4")) + end + + def test_split_ipv6_does_not_compress_single_zero + assert_equal("[1:0:2:3:4:5:6:7]", ipv6("1:0:2:3:4:5:6:7")) + assert_equal("[1:2:3:4:5:6:7:0]", ipv6("1:2:3:4:5:6:7::")) + assert_equal("[0:1:2:3:4:5:6:7]", ipv6("::1:2:3:4:5:6:7")) + end + + def test_split_ipv6_piece_boundaries + assert_equal("[1:2:3:4:5:6:7:ffff]", ipv6("1:2:3:4:5:6:7:ffff")) + assert_ipv6_failure("10000::", "1:2:3:4:5:6:7:10000", "00000::") + end + + def test_split_ipv6_piece_count_boundaries + # 8 pieces, or fewer with "::". + assert_ipv6_failure("1:2:3:4:5:6:7", "1:2:3:4:5:6:7:8:9", "1:2:3:4:5:6:7:8::", "::1:2:3:4:5:6:7:8") + end + + def test_split_ipv6_invalid_colons_fail + assert_ipv6_failure("", ":", ":1", "1:", "1::2::3", ":::", "::1::", "1:::2", "1:2:3:4:5:6:7:8:") + end + + def test_split_ipv6_invalid_characters_fail + assert_ipv6_failure("g::", "::1 ", "::1%25eth0", "%3A%3A1", "::-1", "\u00E9::") + end + + def test_split_ipv6_embedded_ipv4 + assert_equal("[::ffff:102:304]", ipv6("::ffff:1.2.3.4")) + assert_equal("[::102:304]", ipv6("::1.2.3.4")) + assert_equal("[1:2:3:4:5:6:102:304]", ipv6("1:2:3:4:5:6:1.2.3.4")) + assert_equal("[::]", ipv6("::0.0.0.0")) + end + + def test_split_ipv6_embedded_ipv4_number_boundaries + assert_equal("[::102:3ff]", ipv6("::1.2.3.255")) + assert_equal("[::102:300]", ipv6("::1.2.3.0")) + assert_ipv6_failure("::1.2.3.256", "::256.1.2.3") + end + + def test_split_ipv6_embedded_ipv4_must_have_four_decimal_parts + assert_ipv6_failure("::1.2.3", "::1.2.3.4.5", "::1.2..3", "::.1.2.3", "::1.2.3.", "::1.2.3.4x", + "::a.b.c.d", "::0x1.2.3.4", "::1.2.3.4:5") + end + + def test_split_ipv6_embedded_ipv4_rejects_leading_zero + assert_ipv6_failure("::1.2.3.04", "::01.2.3.4", "::1.2.3.00") + end + + def test_split_ipv6_embedded_ipv4_position + # The IPv4 address takes the last two pieces. + assert_ipv6_failure("1:2:3:4:5:6:7:1.2.3.4", "1.2.3.4", "1.2.3.4::") + end + + def test_split_ipv6_embedded_ipv4_number_too_long_fails + # The leading hex piece is re-read as decimal. + assert_ipv6_failure("::1234.1.2.3", "::12345.1.2.3") + end + + def test_split_ipv6_in_non_special_url + assert_equal("[::1]", ipv6("0:0::1", "foo")) + assert_raise(URI::InvalidURIError) { split("foo://[x]/") } + end + + def test_split_ipv6_with_port + assert_equal(["[::1]", "8080"], split("http://[0::1]:8080/").values_at(HOST, PORT)) + end + + def test_parse_serializes_ipv6_host + uri = URI::WHATWG_PARSER.parse("http://[0:0::1]/") + assert_equal("http://[::1]/", uri.to_s) + assert_equal("::1", uri.hostname) + end + + # --- port --------------------------------------------------------- + # https://url.spec.whatwg.org/#port-state + + def port(input) + split(input)[PORT] + end + + def assert_port_failure(*inputs) + inputs.each do |input| + assert_raise(URI::InvalidURIError, input) { split(input) } + end + end + + def test_split_port + assert_equal("8080", port("http://h:8080/")) + assert_equal("8080", port("http://u:p@h:8080/")) + end + + def test_split_empty_port_is_nil + assert_nil(port("http://h:/")) + assert_nil(port("http://h:")) + assert_nil(port("http://h:?q")) + assert_nil(port("foo://h:/")) + end + + def test_split_default_port_is_nil + { "http" => 80, "https" => 443, "ws" => 80, "wss" => 443, "ftp" => 21 }.each do |scheme, default| + assert_nil(port("#{scheme}://h:#{default}/"), scheme) + end + end + + def test_split_default_port_of_another_scheme_is_kept + assert_equal("443", port("http://h:443/")) + assert_equal("80", port("https://h:80/")) + assert_equal("80", port("ftp://h:80/")) + assert_equal("21", port("http://h:21/")) + end + + def test_split_non_special_scheme_has_no_default_port + assert_equal("80", port("foo://h:80/")) + assert_equal("443", port("foo://h:443/")) + end + + def test_split_port_leading_zeros_are_removed + assert_equal("8080", port("http://h:0008080/")) + assert_equal("80", port("foo://h:0080/")) + assert_nil(port("http://h:00080/")) + assert_equal("1", port("http://h:#{"0" * 1000}1/")) + assert_equal("0", port("http://h:000/")) + end + + def test_split_port_boundaries + assert_equal("0", port("http://h:0/")) + assert_equal("1", port("http://h:1/")) + assert_equal("65535", port("http://h:65535/")) + assert_port_failure("http://h:65536/", "http://h:99999/", "http://h:100000/", "foo://h:65536/") + end + + def test_split_huge_port_fails + assert_port_failure("http://h:#{"9" * 100}/", "http://h:1#{"0" * 100}/") + end + + def test_split_port_must_be_digits + assert_port_failure("http://h:8a/", "http://h:a/", "http://h:-1/", "http://h:+1/", "http://h: 1/", + "http://h:1 /", "http://h:1_0/", "http://h:0x10/", "http://h:1:2/", "http://h:1.0/", + "http://h:\uFF11/", "foo://h:8a/") + end + + def test_split_port_ends_at_authority_end + %w[/ ? #].each do |c| + assert_equal("8080", port("http://h:8080#{c}x"), c) + assert_equal("8080", port("foo://h:8080#{c}x"), c) + end + assert_equal("8080", port("http://h:8080\\x")) + end + + def test_split_non_special_port_does_not_end_at_backslash + assert_port_failure("foo://h:8080\\x") + end + + def test_split_port_with_ipv6_host + assert_equal("8080", port("http://[::1]:8080/")) + assert_nil(port("http://[::1]:80/")) + end + + def test_parse_port + assert_equal(8080, URI::WHATWG_PARSER.parse("http://h:8080/").port) + assert_equal("http://h:8080/", URI::WHATWG_PARSER.parse("http://h:08080/").to_s) + end + + def test_parse_default_port_is_omitted + uri = URI::WHATWG_PARSER.parse("http://h:80/") + assert_equal("http://h/", uri.to_s) + assert_equal(80, uri.port) + end + + def test_split_port_in_linear_time + pre = ->(n) { "http://h:" + "9" * n + "/" } + assert_linear_performance((2..5).map { |i| 10**i }, pre: pre) do |uri| + assert_raise(URI::InvalidURIError) { split(uri) } + end + end + + # --- query and fragment ------------------------------------------- + # https://url.spec.whatwg.org/#path-state + # https://url.spec.whatwg.org/#query-state + # https://url.spec.whatwg.org/#fragment-state + # https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state + + QUERY, FRAGMENT = 7, 8 + + def test_split_query_and_fragment + assert_equal(["/p", "q", "f"], split("http://h/p?q#f").values_at(PATH, QUERY, FRAGMENT)) + end + + def test_split_query_only + assert_equal(["/p", "q", nil], split("http://h/p?q").values_at(PATH, QUERY, FRAGMENT)) + end + + def test_split_fragment_only + assert_equal(["/p", nil, "f"], split("http://h/p#f").values_at(PATH, QUERY, FRAGMENT)) + end + + def test_split_empty_query_and_fragment_are_kept + assert_equal(["", nil], split("http://h/p?").values_at(QUERY, FRAGMENT)) + assert_equal([nil, ""], split("http://h/p#").values_at(QUERY, FRAGMENT)) + assert_equal(["", ""], split("http://h/p?#").values_at(QUERY, FRAGMENT)) + end + + def test_split_question_mark_after_hash_is_part_of_fragment + assert_equal([nil, "f?q"], split("http://h/p#f?q").values_at(QUERY, FRAGMENT)) + end + + def test_split_query_and_fragment_split_at_first_delimiter + assert_equal("a?b", split("http://h/p?a?b")[QUERY]) + assert_equal("a#b", split("http://h/p#a#b")[FRAGMENT]) + assert_equal(["a?b", "c#d?e"], split("http://h/p?a?b#c#d?e").values_at(QUERY, FRAGMENT)) + end + + def test_split_query_and_fragment_right_after_host + assert_equal(["h", "q", nil], split("http://h?q").values_at(HOST, QUERY, FRAGMENT)) + assert_equal(["h", nil, "f"], split("http://h#f").values_at(HOST, QUERY, FRAGMENT)) + assert_equal(["h", "8080", "q"], split("http://h:8080?q").values_at(HOST, PORT, QUERY)) + end + + def test_split_hash_ends_authority_before_at_sign + assert_equal([nil, "u", "@host/"], split('http://u#@host/').values_at(USERINFO, HOST, FRAGMENT)) + end + + def test_split_backslash_in_query_and_fragment_is_kept + assert_equal(["a\\b", "c\\d"], split("http://h/?a\\b#c\\d").values_at(QUERY, FRAGMENT)) + end + + def test_split_query_and_fragment_in_non_special_url + assert_equal(["h", "/p", "q", "f"], split("foo://h/p?q#f").values_at(HOST, PATH, QUERY, FRAGMENT)) + assert_equal([nil, "/p", "q", "f"], split("foo:/p?q#f").values_at(HOST, PATH, QUERY, FRAGMENT)) + assert_equal(["", "q"], split("foo://?q").values_at(HOST, QUERY)) + end + + def test_split_query_and_fragment_in_file_url + assert_equal(["/a", "q", "f"], split("file:///a?q#f").values_at(PATH, QUERY, FRAGMENT)) + end + + # An opaque URI keeps its query inside opaque, as URI::RFC3986_Parser + # does, since URI::Generic does not serialize the query of an opaque URI. + + def test_split_opaque_path_with_query_and_fragment + assert_equal(["bar?q", nil, "f"], split("foo:bar?q#f").values_at(OPAQUE, QUERY, FRAGMENT)) + end + + def test_split_opaque_path_with_fragment_containing_question_mark + assert_equal(["bar", nil, "f?q"], split("foo:bar#f?q").values_at(OPAQUE, QUERY, FRAGMENT)) + end + + def test_split_opaque_path_with_empty_query_and_fragment + assert_equal(["bar?", nil, ""], split("foo:bar?#").values_at(OPAQUE, QUERY, FRAGMENT)) + end + + def test_split_empty_opaque_path_with_query_or_fragment + assert_equal(["?q", nil], split("foo:?q").values_at(OPAQUE, FRAGMENT)) + assert_equal(["", "f"], split("foo:#f").values_at(OPAQUE, FRAGMENT)) + end + + def test_split_opaque_path_space_before_query_or_fragment_is_encoded + # Only the space right before "?" or "#" is encoded, so it survives + # the stripping of trailing spaces when the URL is reparsed. + assert_equal("a%20?q", split("foo:a ?q")[OPAQUE]) + assert_equal("a %20", split("foo:a #f")[OPAQUE]) + assert_equal("a %20?", split("foo:a ?")[OPAQUE]) + end + + def test_split_opaque_path_other_spaces_are_kept + assert_equal("a b?q", split("foo:a b?q")[OPAQUE]) + assert_equal("a b", split("foo:a b")[OPAQUE]) + end + + def test_split_opaque_path_trailing_spaces_are_stripped + # by the preprocessing, as they are at the end of the input. + assert_equal("a", split("foo:a ")[OPAQUE]) + end + + def test_split_space_in_query_or_fragment_of_opaque_url_uses_their_encode_sets + # The "%20" rule for the opaque path does not apply; the query and + # fragment percent-encode sets do. + assert_equal("a?%20b", split("foo:a? b")[OPAQUE]) + assert_equal("%20b", split("foo:a# b")[FRAGMENT]) + end + + def test_parse_round_trip_with_query_and_fragment + %w[http://h/p?q#f http://h/p?# foo:bar?q#f foo:bar?# foo://h/p?q#f].each do |input| + assert_equal(input, URI::WHATWG_PARSER.parse(input).to_s, input) + end + end + + def test_parse_query_and_fragment + uri = URI::WHATWG_PARSER.parse("http://h/p?q#f") + assert_equal(["q", "f"], [uri.query, uri.fragment]) + end + + # --- path --------------------------------------------------------- + # https://url.spec.whatwg.org/#path-start-state + # https://url.spec.whatwg.org/#path-state + # https://url.spec.whatwg.org/#single-dot-path-segment + # https://url.spec.whatwg.org/#double-dot-path-segment + # https://url.spec.whatwg.org/#url-serializing (the "/." prefix) + + def path(input) + split(input)[PATH] + end + + def test_split_special_empty_path_is_slash + assert_equal("/", path("http://h")) + assert_equal("/", path("http://h?q")) + assert_equal("/", path("http://h#f")) + assert_equal("/", path("http://h:8080")) + end + + def test_split_special_path + assert_equal("/", path("http://h/")) + assert_equal("/a/b", path("http://h/a/b")) + assert_equal("/a/b/", path("http://h/a/b/")) + end + + def test_split_special_path_treats_backslash_as_slash + assert_equal("/a/b", path("http://h\\a\\b")) + assert_equal("/a/b/c", path("http://h/a\\b/c")) + assert_equal("/", path("http://h\\")) + end + + def test_split_path_keeps_empty_segments + assert_equal("//a//b", path("http://h//a//b")) + assert_equal("///", path("http://h///")) + end + + def test_split_single_dot_segments_are_removed + assert_equal("/a/b", path("http://h/a/./b")) + assert_equal("/a", path("http://h/./a")) + assert_equal("/a/", path("http://h/a/./")) + assert_equal("/a/b", path("http://h/a/././b")) + end + + def test_split_trailing_single_dot_keeps_slash + assert_equal("/a/", path("http://h/a/.")) + assert_equal("/", path("http://h/.")) + end + + def test_split_double_dot_segments_remove_previous_segment + assert_equal("/a/c", path("http://h/a/b/../c")) + assert_equal("/", path("http://h/a/../")) + assert_equal("/c", path("http://h/a/b/../../c")) + end + + def test_split_trailing_double_dot_keeps_slash + assert_equal("/a/", path("http://h/a/b/..")) + assert_equal("/", path("http://h/a/..")) + assert_equal("/", path("http://h/..")) + end + + def test_split_double_dot_does_not_go_above_root + assert_equal("/a", path("http://h/../a")) + assert_equal("/a", path("http://h/../../a")) + assert_equal("/", path("http://h/a/../../..")) + end + + def test_split_double_dot_removes_empty_segment + assert_equal("/a/", path("http://h/a//..")) + assert_equal("//b", path("http://h//a/../b")) + end + + def test_split_percent_encoded_single_dot + assert_equal("/a/b", path("http://h/a/%2e/b")) + assert_equal("/a/b", path("http://h/a/%2E/b")) + assert_equal("/a/", path("http://h/a/%2e")) + end + + def test_split_percent_encoded_double_dot + [".%2e", "%2e.", "%2e%2e", ".%2E", "%2E.", "%2E%2E", "%2e%2E"].each do |dots| + assert_equal("/a/c", path("http://h/a/b/#{dots}/c"), dots) + assert_equal("/a/", path("http://h/a/b/#{dots}"), dots) + end + end + + def test_split_segments_that_only_resemble_dots_are_kept + ["...", "a.", ".a", "..a", "a..", "%2e%2e%2e", "%2", "%2ex", "%2f", "%252e"].each do |segment| + assert_equal("/#{segment}/b", path("http://h/#{segment}/b"), segment) + end + end + + def test_split_dot_segments_with_backslash_in_special_url + assert_equal("/b", path("http://h/a\\..\\b")) + assert_equal("/a/", path("http://h/a\\.")) + end + + def test_split_dot_segments_before_query_and_fragment + assert_equal(["/", "q"], split("http://h/a/..?q").values_at(PATH, QUERY)) + assert_equal(["/a/", "f"], split("http://h/a/.#f").values_at(PATH, FRAGMENT)) + assert_equal(["/a/", "q"], split("http://h/a/%2e?q").values_at(PATH, QUERY)) + end + + def test_split_dot_segments_in_every_special_scheme + %w[https ws wss ftp].each do |scheme| + assert_equal("/b", path("#{scheme}://h/a/../b"), scheme) + assert_equal("/", path("#{scheme}://h"), scheme) + end + end + + def test_split_non_special_empty_path_stays_empty + assert_equal("", path("foo://h")) + assert_equal("", path("foo://h?q")) + assert_equal("/", path("foo://h/")) + end + + def test_split_non_special_dot_segments + assert_equal("/b", path("foo://h/a/../b")) + assert_equal("/a/b", path("foo:/a/./b")) + assert_equal("/", path("foo:/a/..")) + assert_equal("/a/", path("foo:/a/.")) + assert_equal("/b", path("foo:/%2e%2e/b")) + end + + def test_split_non_special_does_not_treat_backslash_as_separator + assert_equal("/a\\..\\b", path("foo://h/a\\..\\b")) + assert_equal("/a/..\\b", path("foo://h/a/..\\b")) + end + + def test_split_hostless_path_starting_with_two_slashes_gets_dot_prefix + assert_equal("/.//p", path("foo:/..//p")) + assert_equal("/.//p", path("foo:/.//p")) + assert_equal("/.//p", path("foo:/a/..//p")) + assert_equal("/.//", path("foo:/.//")) + end + + def test_split_no_dot_prefix_when_not_needed + assert_equal("/", path("foo:/./")) + assert_equal("/p", path("foo:/./p")) + assert_equal("//p", path("foo://h/..//p")) + assert_equal("//p", path("foo:///..//p")) + end + + def test_parse_dot_prefix_round_trips + uri = URI::WHATWG_PARSER.parse("foo:/..//p") + assert_equal("foo:/.//p", uri.to_s) + assert_equal("foo:/.//p", URI::WHATWG_PARSER.parse(uri.to_s).to_s) + end + + def test_split_file_path_dot_segments + assert_equal("/b", path("file:///a/../b")) + assert_equal("/b", path("file:/a/../b")) + end + + def test_split_path_in_linear_time + pre = ->(n) { "http://h" + "/a/.." * n + "/b" } + assert_linear_performance((1..4).map { |i| 10**i }, pre: pre) do |uri| + split(uri) + end + end + + # --- percent-encoding --------------------------------------------- + # https://url.spec.whatwg.org/#percent-encoded-bytes + + # Printable ASCII other than alphanumerics, including the space. + PUNCTUATION = (0x20..0x7E).map(&:chr).grep(/[^A-Za-z0-9]/).freeze + + # Returns the punctuation characters that the block, given "ab", + # percent-encodes, checking that each one comes back as "a%XXb". + def encoded_characters(component) + PUNCTUATION.reject { |c| yield(c) == "a#{c}b" }.each do |c| + assert_equal("a%%%02Xb" % c.ord, yield(c), "#{component} #{c.inspect}") + end + end + + def test_split_fragment_percent_encode_set + encoded = encoded_characters("fragment") { |c| split("http://h/#a#{c}b")[FRAGMENT] } + assert_equal([" ", '"', "<", ">", "`"], encoded) + end + + def test_split_special_query_percent_encode_set + # "#" never reaches the query; it starts the fragment. + encoded = encoded_characters("query") { |c| c == "#" ? "a#b" : split("http://h/?a#{c}b")[QUERY] } + assert_equal([" ", '"', "'", "<", ">"], encoded) + end + + def test_split_non_special_query_percent_encode_set + encoded = encoded_characters("query") { |c| c == "#" ? "a#b" : split("foo://h/?a#{c}b")[QUERY] } + assert_equal([" ", '"', "<", ">"], encoded) + end + + def test_split_path_percent_encode_set + # "/" separates segments, "?" and "#" end the path; "." and "%" are + # never encoded. + encoded = encoded_characters("path") do |c| + %w[/ ? #].include?(c) ? "a#{c}b" : split("foo://h/a#{c}b")[PATH].delete_prefix("/") + end + assert_equal([" ", '"', "<", ">", "^", "`", "{", "}"], encoded) + end + + def test_split_userinfo_percent_encode_set + # "/", "?", "#" end the authority; "@" and ":" are delimiters here. + encoded = encoded_characters("userinfo") do |c| + %w[/ ? # @ :].include?(c) ? "a#{c}b" : split("foo://a#{c}b@h/")[USERINFO] + end + assert_equal([" ", '"', ";", "<", "=", ">", "[", "\\", "]", "^", "`", "{", "|", "}"], encoded) + end + + def test_split_opaque_path_keeps_printable_ascii + PUNCTUATION.each do |c| + next if %w[? #].include?(c) + opaque = split("foo:a#{c}b")[OPAQUE] + assert_equal("a#{c}b", opaque, c.inspect) + end + end + + def test_split_percent_encodes_c0_controls_and_delete + ["\x01", "\x1F", "\x7F"].each do |c| + expected = "a%%%02Xb" % c.ord + assert_equal("/#{expected}", split("http://h/a#{c}b")[PATH], c.dump) + assert_equal(expected, split("http://h/?a#{c}b")[QUERY], c.dump) + assert_equal(expected, split("http://h/#a#{c}b")[FRAGMENT], c.dump) + assert_equal(expected, split("http://a#{c}b@h/")[USERINFO], c.dump) + assert_equal(expected, split("foo:a#{c}b")[OPAQUE], c.dump) + end + end + + def test_split_percent_encodes_null + assert_equal("/a%00b", split("http://h/a\x00b")[PATH]) + assert_equal("a%00b", split("foo:a\x00b")[OPAQUE]) + end + + def test_split_percent_encodes_non_ascii_as_utf8 + { + "\u0080" => "%C2%80", + "\u00E9" => "%C3%A9", + "\u3042" => "%E3%81%82", + "\u{1F600}" => "%F0%9F%98%80", + }.each do |c, encoded| + assert_equal("/#{encoded}", split("http://h/#{c}")[PATH], c) + assert_equal(encoded, split("http://h/?#{c}")[QUERY], c) + assert_equal(encoded, split("http://h/##{c}")[FRAGMENT], c) + assert_equal(encoded, split("http://#{c}@h/")[USERINFO], c) + assert_equal(encoded, split("foo:#{c}")[OPAQUE], c) + end + end + + def test_split_keeps_percent_encoded_and_stray_percent_signs + ["%41", "%zz", "%", "%4"].each do |s| + assert_equal("/#{s}", split("http://h/#{s}")[PATH], s) + assert_equal(s, split("http://h/?#{s}")[QUERY], s) + assert_equal(s, split("http://h/##{s}")[FRAGMENT], s) + assert_equal(s, split("http://#{s}@h/")[USERINFO], s) + assert_equal(s, split("foo:#{s}")[OPAQUE], s) + end + end + + def test_split_encodes_username_and_password_separately + # Only the first ":" separates them; later ones are encoded. + assert_equal("u:a%3Ab", split("http://u:a:b@h/")[USERINFO]) + assert_equal("a%20b:c%20d", split("http://a b:c d@h/")[USERINFO]) + end + + def test_split_encodes_userinfo_with_at_sign_kept_as_percent_40 + assert_equal("a%40b%20c", split("http://a@b c@h/")[USERINFO]) + end + + def test_split_encoded_path_is_not_a_dot_segment + assert_equal("/a/.%20/b", path("http://h/a/.%20/b")) + assert_equal("/a/.%20/b", path("http://h/a/. /b")) + assert_equal("/a/%E3%80%82/b", path("http://h/a/\u3002/b")) + end + + def test_split_special_query_quote_differs_from_non_special + assert_equal("%27", split("ws://h/?'")[QUERY]) + assert_equal("'", split("foo:/?'")[QUERY]) + end + + def test_parse_percent_encoded_round_trip + uri = URI::WHATWG_PARSER.parse("http://u s@h/a b?c d#e f") + assert_equal("http://u%20s@h/a%20b?c%20d#e%20f", uri.to_s) + assert_equal(uri.to_s, URI::WHATWG_PARSER.parse(uri.to_s).to_s) + end + + def test_split_percent_encode_in_linear_time + pre = ->(n) { "http://h/" + "\u00E9" * n + "?" + "\u00E9" * n + "#" + "\u00E9" * n } + assert_linear_performance((1..4).map { |i| 10**i }, pre: pre) do |uri| + split(uri) + end + end + + # --- relative references ------------------------------------------ + # https://url.spec.whatwg.org/#no-scheme-state + # https://url.spec.whatwg.org/#special-relative-or-authority-state + # https://url.spec.whatwg.org/#relative-state + # https://url.spec.whatwg.org/#relative-slash-state + + RFC3986_BASE = "http://a/b/c/d;p?q" + + def join(*uris) + URI::WHATWG_PARSER.join(*uris).to_s + end + + def test_join_rfc3986_normal_examples + # RFC 3986, 5.4.1, except that "g:h" is left out (another scheme). + { + "g" => "http://a/b/c/g", + "./g" => "http://a/b/c/g", + "g/" => "http://a/b/c/g/", + "/g" => "http://a/g", + "//g" => "http://g/", + "?y" => "http://a/b/c/d;p?y", + "g?y" => "http://a/b/c/g?y", + "#s" => "http://a/b/c/d;p?q#s", + "g#s" => "http://a/b/c/g#s", + "g?y#s" => "http://a/b/c/g?y#s", + ";x" => "http://a/b/c/;x", + "g;x" => "http://a/b/c/g;x", + "g;x?y#s" => "http://a/b/c/g;x?y#s", + "" => "http://a/b/c/d;p?q", + "." => "http://a/b/c/", + "./" => "http://a/b/c/", + ".." => "http://a/b/", + "../" => "http://a/b/", + "../g" => "http://a/b/g", + "../.." => "http://a/", + "../../" => "http://a/", + "../../g" => "http://a/g", + }.each do |rel, expected| + assert_equal(expected, join(RFC3986_BASE, rel), rel) + end + end + + def test_join_rfc3986_abnormal_examples + # RFC 3986, 5.4.2. "http:g" differs: the URL Standard resolves a + # special scheme equal to the base's as a relative reference. + { + "../../../g" => "http://a/g", + "../../../../g" => "http://a/g", + "/./g" => "http://a/g", + "/../g" => "http://a/g", + "g." => "http://a/b/c/g.", + ".g" => "http://a/b/c/.g", + "g.." => "http://a/b/c/g..", + "..g" => "http://a/b/c/..g", + "./../g" => "http://a/b/g", + "./g/." => "http://a/b/c/g/", + "g/./h" => "http://a/b/c/g/h", + "g/../h" => "http://a/b/c/h", + "g;x=1/./y" => "http://a/b/c/g;x=1/y", + "g;x=1/../y" => "http://a/b/c/y", + "g?y/./x" => "http://a/b/c/g?y/./x", + "g?y/../x" => "http://a/b/c/g?y/../x", + "g#s/./x" => "http://a/b/c/g#s/./x", + "g#s/../x" => "http://a/b/c/g#s/../x", + "http:g" => "http://a/b/c/g", + }.each do |rel, expected| + assert_equal(expected, join(RFC3986_BASE, rel), rel) + end + end + + def test_join_same_special_scheme_is_relative + assert_equal("http://a/b/c/g", join(RFC3986_BASE, "HTTP:g")) + assert_equal("http://a/g", join(RFC3986_BASE, "http:/g")) + assert_equal("http://g/", join(RFC3986_BASE, "http://g")) + assert_equal("http://g/", join(RFC3986_BASE, "http:\\\\g")) + assert_equal("http://a/b/c/d;p?y", join(RFC3986_BASE, "http:?y")) + end + + def test_join_other_special_scheme_is_absolute + assert_equal("https://g/", join(RFC3986_BASE, "https:g")) + assert_equal("ws://g/", join(RFC3986_BASE, "ws:/g")) + end + + def test_join_non_special_scheme_is_absolute + assert_equal("g:h", join(RFC3986_BASE, "g:h")) + assert_equal("c:/foo", join(RFC3986_BASE, "c:/foo")) + end + + def test_join_backslash_in_special_relative_reference + assert_equal("http://a/g", join(RFC3986_BASE, "\\g")) + assert_equal("http://g/", join(RFC3986_BASE, "\\\\g")) + assert_equal("http://g/", join(RFC3986_BASE, "/\\g")) + assert_equal("http://g/", join(RFC3986_BASE, "\\/g")) + assert_equal("http://a/b/c/g/h", join(RFC3986_BASE, "g\\h")) + end + + def test_join_network_path_skips_extra_slashes_for_special + assert_equal("http://g/", join(RFC3986_BASE, "///g")) + assert_equal("http://u@g:8080/x", join(RFC3986_BASE, "//u@g:8080/x")) + end + + def test_join_network_path_without_host_fails_for_special + ["//", "///", "\\\\"].each do |rel| + assert_raise(URI::InvalidURIError, rel) { join(RFC3986_BASE, rel) } + end + end + + def test_join_keeps_base_userinfo_and_port + assert_equal("http://u:p@a:8080/c", join("http://u:p@a:8080/b", "c")) + assert_equal("http://u:p@a:8080/c", join("http://u:p@a:8080/b", "/c")) + end + + def test_join_does_not_keep_base_fragment + assert_equal("http://a/b", join("http://a/b#f", "")) + assert_equal("http://a/b?x", join("http://a/b#f", "?x")) + assert_equal("http://a/c", join("http://a/b#f", "c")) + end + + def test_join_keeps_base_query_only_without_path_or_query + assert_equal("http://a/b?q", join("http://a/b?q", "")) + assert_equal("http://a/b?q#f", join("http://a/b?q", "#f")) + assert_equal("http://a/b?", join("http://a/b?q", "?")) + assert_equal("http://a/c", join("http://a/b?q", "c")) + assert_equal("http://a/c", join("http://a/b?q", "/c")) + end + + def test_join_empty_query_and_fragment + assert_equal("http://a/b/c/d;p?", join(RFC3986_BASE, "?")) + assert_equal("http://a/b/c/d;p?q#", join(RFC3986_BASE, "#")) + end + + def test_join_preprocesses_relative_reference + assert_equal("http://a/b/c/g", join(RFC3986_BASE, " \tg\n ")) + end + + def test_join_percent_encodes_relative_reference + assert_equal("http://a/b/c/a%20b?c%20d#e%20f", join(RFC3986_BASE, "a b?c d#e f")) + assert_equal("http://a/b/c/d;p?%27", join(RFC3986_BASE, "?'")) + end + + def test_join_non_special_base + base = "foo://h/a/b" + assert_equal("foo://h/a/c", join(base, "c")) + assert_equal("foo://x/y", join(base, "//x/y")) + assert_equal("foo://h/c", join(base, "/c")) + assert_equal("foo://h/a/", join(base, ".")) + assert_equal("foo://h/", join(base, "../..")) + end + + def test_join_non_special_base_does_not_treat_backslash_as_slash + assert_equal("foo://h/\\x", join("foo://h/a/b", "/\\x")) + assert_equal("foo://h/a/\\x", join("foo://h/a/b", "\\x")) + end + + def test_join_non_special_base_with_empty_host + assert_equal("foo:///a/c", join("foo:///a/b", "c")) + assert_equal("foo://", join("foo://", "")) + end + + def test_join_hostless_base + assert_equal("foo:/a/c", join("foo:/a/b", "c")) + assert_equal("foo:/.//c", join("foo:/a/b", "..//c")) + assert_equal("foo:/c", join("foo:/a/b", "/c")) + end + + def test_join_base_with_opaque_path_accepts_only_fragment + assert_equal("foo:bar#f", join("foo:bar", "#f")) + assert_equal("foo:bar?q#f", join("foo:bar?q", "#f")) + assert_equal("foo:bar#", join("foo:bar#x", "#")) + end + + def test_join_base_with_opaque_path_rejects_anything_else + ["", "x", "?q", "/x", "//x"].each do |rel| + assert_raise(URI::InvalidURIError, rel) { join("foo:bar", rel) } + end + end + + def test_join_with_multiple_references + assert_equal("http://a/b/d/e", join("http://a/b/c", "d/", "e")) + assert_equal("http://x/z", join("http://a/b", "http://x/y", "z")) + end + + def test_join_with_uri_objects + base = URI::WHATWG_PARSER.parse("http://a/b/c") + assert_equal("http://a/b/d", join(base, "d")) + assert_equal("http://x/", join("http://a/", URI::WHATWG_PARSER.parse("http://x/"))) + end + + def test_join_result_is_bound_to_whatwg_parser + assert_same(URI::WHATWG_PARSER, URI::WHATWG_PARSER.join("http://a/b", "c").parser) + end + + def test_join_fails_without_absolute_base + assert_raise(URI::InvalidURIError) { join("g", "h") } + assert_raise(URI::InvalidURIError) { join(URI::RFC3986_PARSER.parse("g"), "h") } + end + + def test_join_rejects_non_string_reference + assert_raise(ArgumentError) { join("http://a/", nil) } + assert_raise(ArgumentError) { join("http://a/", 1) } + end + + def test_uri_join_uses_whatwg_parser_after_switch + URI.parser = URI::WHATWG_PARSER + assert_equal("http://a/b/c/g", URI.join(RFC3986_BASE, "http:g").to_s) + end + + def test_merge_resolves_with_whatwg_rules + uri = URI::WHATWG_PARSER.parse("http://a/b/c") + { + "d" => "http://a/b/d", + "../x" => "http://a/x", + "//h/p" => "http://h/p", + "?y" => "http://a/b/c?y", + "#f" => "http://a/b/c#f", + "http:g" => "http://a/b/g", + "\\g" => "http://a/g", + "http://q/" => "http://q/", + }.each do |rel, expected| + assert_equal(expected, uri.merge(rel).to_s, rel) + assert_equal(expected, (uri + rel).to_s, rel) + end + end + + def test_merge_result_is_bound_to_whatwg_parser + uri = URI::WHATWG_PARSER.parse("http://a/b/c") + "d" + assert_same(URI::WHATWG_PARSER, uri.parser) + assert_equal("http://a/b/e", (uri + "e").to_s) + end + + def test_merge_with_uri_object + uri = URI::WHATWG_PARSER.parse("http://a/b/c") + assert_equal("http://a/b/d", uri.merge(URI::RFC3986_PARSER.parse("d")).to_s) + end + + def test_merge_bang + uri = URI::WHATWG_PARSER.parse("http://a/b/c") + assert_same(uri, uri.merge!("d")) + assert_equal("http://a/b/d", uri.to_s) + assert_nil(uri.merge!("")) + end + + def test_merge_does_not_modify_receiver + uri = URI::WHATWG_PARSER.parse("http://a/b/c?q#f") + assert_equal("http://a/b/d", uri.merge("d").to_s) + assert_equal("http://a/b/c?q#f", uri.to_s) + end + + def test_merge_rejects_non_string + assert_raise(ArgumentError) { URI::WHATWG_PARSER.parse("http://a/") + 1 } + end + + def test_merge_after_parser_switch + URI.parser = URI::WHATWG_PARSER + assert_equal("http://a/b/g", (URI("http://a/b/c") + "http:g").to_s) + end + + def test_rfc3986_merge_is_unchanged + assert_equal("http:g", (URI::RFC3986_PARSER.parse("http://a/b/c") + "http:g").to_s) + end + + def test_split_without_base_still_fails_for_relative_reference + assert_raise(URI::InvalidURIError) { split("g") } + end + + # --- file --------------------------------------------------------- + # https://url.spec.whatwg.org/#file-state + # https://url.spec.whatwg.org/#file-slash-state + # https://url.spec.whatwg.org/#file-host-state + # https://url.spec.whatwg.org/#windows-drive-letter + # https://url.spec.whatwg.org/#shorten-a-urls-path + + def file(input, base = nil) + base ? join(base, input) : URI::WHATWG_PARSER.parse(input).to_s + end + + def test_file_with_empty_host + assert_equal("file:///tmp/a", file("file:///tmp/a")) + assert_equal(["", "/tmp/a"], split("file:///tmp/a").values_at(HOST, PATH)) + end + + def test_file_with_host + assert_equal(["host", "/a"], split("file://host/a").values_at(HOST, PATH)) + assert_equal("file://host/a", file("FILE://HOST/a")) + end + + def test_file_without_slashes_has_empty_host + assert_equal(["", "/a"], split("file:a").values_at(HOST, PATH)) + assert_equal(["", "/a"], split("file:/a").values_at(HOST, PATH)) + assert_equal(["", "/"], split("file:").values_at(HOST, PATH)) + end + + def test_file_backslashes_are_slashes + assert_equal("file://host/a/b", file("file:\\\\host\\a\\b")) + assert_equal("file:///a", file("file:\\a")) + end + + def test_file_more_than_two_slashes_keep_empty_host + assert_equal("file:////a", file("file:////a")) + assert_equal("file:///localhost//cat", file("file:///localhost//cat")) + assert_equal("file:////localhost//cat", file("file://\\/localhost//cat")) + end + + def test_file_localhost_is_empty_host + assert_equal("file:///a", file("file://localhost/a")) + assert_equal("file:///a", file("file://LOCALHOST/a")) + assert_equal("file:///", file("file://localhost")) + assert_equal("file://localhost.example/a", file("file://localhost.example/a")) + end + + def test_file_host_is_a_domain + assert_equal("file://example.com/", file("file://EX%41MPLE.com/")) + assert_equal("file://127.0.0.1/", file("file://0x7f.1/")) + assert_equal("file://[::1]/", file("file://[0::1]/")) + end + + def test_file_host_has_no_port_or_userinfo + ["file://example:1/", "file://example:/", "file://u@host/", "file://u:p@host/", "file://ho st/"].each do |input| + assert_raise(URI::InvalidURIError, input) { split(input) } + end + end + + def test_file_query_and_fragment + assert_equal("file:///a?q#f", file("file:///a?q#f")) + assert_equal("file://host/?q", file("file://host?q")) + end + + def test_file_drive_letter_is_normalized_in_first_segment + assert_equal("file:///C:/m/", file("file:C|/m/")) + assert_equal("file:///c:/foo/bar.html", file("file:c:\\foo\\bar.html")) + assert_equal("file:///C:/", file("file:///C|/")) + assert_equal("file:///C:", file("file:///C|")) + end + + def test_file_drive_letter_only_in_first_segment + assert_equal("file:///a/C|/", file("file:///a/C|/")) + end + + def test_file_not_a_drive_letter + assert_equal("file:///C||/m/", file("file:C||/m/")) + assert_equal("file:///1:/", file("file:///1:/")) + assert_equal("file:///C%3A/", file("file:///C%3A/")) + assert_equal("file:///C%7C/", file("file:///C%7C/")) + assert_equal("file:///CC:/", file("file:///CC:/")) + end + + def test_file_drive_letter_in_host_position_is_a_path + assert_equal("file:///C:/", file("file://C:/")) + assert_equal("file:///C:/", file("file://C|/")) + assert_equal("file:///d:", file("//d:", "file:///C:/a/b")) + end + + def test_file_double_dot_does_not_remove_drive_letter + assert_equal("file:///C:/", file("file:///C:/..")) + assert_equal("file:///C:/", file("file:///C:/a/../..")) + assert_equal("file:///C:/", file("..", "file:///C:/")) + assert_equal("file:///d:/", file("//d:/..", "file:///C:/a/b")) + end + + def test_file_double_dot_removes_other_first_segments + assert_equal("file:///", file("file:///a/..")) + assert_equal("file:///", file("file:///C|a/..")) + end + + def test_file_drive_letter_with_host_keeps_host + assert_equal("file://host/C:/", file("file://host/C|/")) + assert_equal("file://host/C:", file("C|", "file://host/dir/file")) + end + + def test_file_relative_to_file_base + base = "file:///tmp/mock/path" + assert_equal("file:///tmp/mock/a", file("a", base)) + assert_equal("file:///tmp/mock/a", file("file:a", base)) + assert_equal("file:///a", file("/a", base)) + assert_equal("file:///a", file("file:/a", base)) + assert_equal("file://h/a", file("//h/a", base)) + assert_equal("file:///", file("//", base)) + assert_equal("file:///", file("///", base)) + assert_equal("file:///test", file("///test", base)) + end + + def test_file_relative_keeps_base_host + base = "file://host/dir/file" + assert_equal("file://host/dir/a", file("a", base)) + assert_equal("file://host/a", file("/a", base)) + assert_equal("file://host/dir/C|a", file("C|a", base)) + end + + def test_file_relative_keeps_base_query_only_when_empty + base = "file:///test?test#test" + assert_equal("file:///test?test", file("file:", base)) + assert_equal("file:///test?x", file("file:?x", base)) + assert_equal("file:///test?test#x", file("file:#x", base)) + assert_equal("file:///a", file("a", base)) + end + + def test_file_relative_drive_letter_replaces_base_path + base = "file:///tmp/mock/path" + assert_equal("file:///C:/foo/bar", file("C|/foo/bar", base)) + assert_equal("file:///C:/foo/bar", file("/C|\\foo\\bar", base)) + assert_equal("file:///C:/foo/bar", file("//C|/foo/bar", base)) + assert_equal("file://host/C:", file("C|", "file://host/D:/dir1/dir2/file")) + end + + def test_file_absolute_path_keeps_base_drive_letter + assert_equal("file:///C:/", file("/", "file:///C:/a/b")) + assert_equal("file://h/C:/", file("/", "file://h/C:/a/b")) + assert_equal("file:///C:/x", file("/x", "file:///C:/a/b")) + end + + def test_file_absolute_path_with_own_drive_letter + assert_equal("file:///c:/foo/bar", file("/c|/foo/bar", "file:///c:/baz/qux")) + end + + def test_file_relative_to_non_file_base_is_not_file + assert_equal("http://a/C|/x", file("C|/x", "http://a/b")) + end + + def test_file_scheme_from_non_file_base + assert_equal("file:///a", file("file:/a", "http://a/b")) + assert_equal("file:///C:/", file("file:C|/", "http://a/b")) + end + + def test_file_dot_prefix_is_never_needed + # A file URL always has a host (possibly empty), so a path starting + # with "//" needs no "/." prefix. + assert_equal("file:////p", file("file:.//p")) + assert_equal("file:////p", file("file:/.//p")) + end + + # --- building URI objects ----------------------------------------- + # URI::Generic#query= re-escapes the query by RFC 3986 rules; the URL + # Standard's query must reach the URI object unchanged. + + def test_parse_keeps_query_characters_rfc3986_would_escape + assert_equal("'", URI::WHATWG_PARSER.parse("foo://h/?'").query) + assert_equal("`{}", URI::WHATWG_PARSER.parse("http://h/?`{}").query) + assert_equal("http://h/?`{}|^", URI::WHATWG_PARSER.parse("http://h/?`{}|^").to_s) + end + + def test_parse_keeps_stray_percent_sign_in_query + assert_equal("%GH", URI::WHATWG_PARSER.parse("http://h/?%GH").query) + assert_equal("a%", URI::WHATWG_PARSER.parse("http://h/?a%").query) + assert_equal("http://h/?%zz", URI::WHATWG_PARSER.parse("http://h/?%zz").to_s) + end + + def test_join_keeps_query_unchanged + assert_equal("%GH'", URI::WHATWG_PARSER.join("foo://h/", "?%GH'").query) + end + + def test_parse_without_query_has_nil_query + assert_nil(URI::WHATWG_PARSER.parse("http://h/").query) + assert_equal("", URI::WHATWG_PARSER.parse("http://h/?").query) + end + + # Scheme-specific classes are used only where their rules agree with + # the URL Standard. URI::FTP rewrites the path by RFC 1738 rules, + # URI::MailTo validates the opaque part, and URI::LDAP drops its + # default port, so those schemes get URI::Generic. + + def test_parse_uses_scheme_classes_for_http_https_ws_wss_and_file + { + "http://h/" => URI::HTTP, + "https://h/" => URI::HTTPS, + "ws://h/" => URI::WS, + "wss://h/" => URI::WSS, + "file:///a" => URI::File, + }.each do |input, klass| + assert_instance_of(klass, URI::WHATWG_PARSER.parse(input), input) + end + end + + def test_parse_uses_generic_for_other_schemes + %w[ftp://h/ mailto:a@example.com ldap://h/ ldaps://h/ foo:bar].each do |input| + assert_instance_of(URI::Generic, URI::WHATWG_PARSER.parse(input), input) + end + end + + def test_parse_ftp_path_is_not_rewritten + assert_equal("ftp://h//a", URI::WHATWG_PARSER.parse("ftp://h//a").to_s) + uri = URI::WHATWG_PARSER.parse("ftp://h/a;type=x") + assert_equal(["ftp://h/a;type=x", "/a;type=x"], [uri.to_s, uri.path]) + end + + def test_parse_ftp_default_port_is_omitted + assert_equal("ftp://h/", URI::WHATWG_PARSER.parse("ftp://h:21/").to_s) + assert_equal("ftp://h:80/", URI::WHATWG_PARSER.parse("ftp://h:80/").to_s) + end + + def test_parse_mailto_is_not_validated_by_mailto_rules + assert_equal("mailto:/example.com/", URI::WHATWG_PARSER.parse("mailto:/example.com/").to_s) + assert_equal("mailto:a@example.com?subject=x", URI::WHATWG_PARSER.parse("mailto:a@example.com?subject=x").to_s) + assert_equal("mailto://h:8080/p?q#f", URI::WHATWG_PARSER.parse("mailto://h:8080/p?q#f").to_s) + end + + def test_parse_ldap_keeps_port_389 + uri = URI::WHATWG_PARSER.parse("ldap://h:389/x") + assert_equal(["ldap://h:389/x", 389], [uri.to_s, uri.port]) + end + + def test_join_uses_the_same_classes + assert_instance_of(URI::Generic, URI::WHATWG_PARSER.join("http://a/", "mailto:x")) + assert_instance_of(URI::HTTPS, URI::WHATWG_PARSER.join("http://a/", "https://b/")) + end + + def test_rfc3986_parser_still_uses_scheme_classes + assert_instance_of(URI::MailTo, URI::RFC3986_PARSER.parse("mailto:a@example.com")) + assert_instance_of(URI::FTP, URI::RFC3986_PARSER.parse("ftp://h/")) + end + + def test_rfc3986_parser_still_rejects_stray_percent_in_query + assert_raise(URI::InvalidURIError) { URI::RFC3986_PARSER.parse("http://h/?%GH") } + end + + # --- host: opaque host --------------------------------------------- + # https://url.spec.whatwg.org/#concept-opaque-host-parser + + def test_split_opaque_host_is_not_lowercased + assert_equal("EXAMPLE.com", split("foo://EXAMPLE.com/")[HOST]) + end + + def test_split_opaque_host_is_not_percent_decoded + assert_equal("ex%61mple", split("foo://ex%61mple/")[HOST]) + assert_equal("a%zzb", split("foo://a%zzb/")[HOST]) + assert_equal("a%", split("foo://a%/")[HOST]) + end + + def test_split_opaque_host_with_forbidden_host_code_point_fails + ["\x00", " ", "<", ">", "[", "]", "^", "|"].each do |c| + assert_raise(URI::InvalidURIError, c.dump) { split("foo://a#{c}b/") } + end + end + + def test_split_opaque_host_percent_encodes_c0_controls_and_non_ascii + assert_equal("a%01b", split("foo://a\x01b/")[HOST]) + assert_equal("a%1Fb", split("foo://a\x1Fb/")[HOST]) + assert_equal("a%7Fb", split("foo://a\x7Fb/")[HOST]) + assert_equal("a%C2%80b", split("foo://a\u0080b/")[HOST]) + assert_equal("%C3%A9", split("foo://\u00E9/")[HOST]) + assert_equal("%F0%9F%98%80", split("foo://\u{1F600}/")[HOST]) + end + + def test_split_opaque_host_keeps_printable_ascii + assert_equal("a!~%$b", split("foo://a!~%$b/")[HOST]) + end + + def test_split_authority_in_linear_time + pre = ->(n) { "http:" + "/" * n + "a@" * n + "host/" } + assert_linear_performance((1..4).map { |i| 10**i }, pre: pre) do |uri| + split(uri) + end + end +end diff --git a/test/uri/test_whatwg_punycode.rb b/test/uri/test_whatwg_punycode.rb new file mode 100644 index 00000000..31e233c6 --- /dev/null +++ b/test/uri/test_whatwg_punycode.rb @@ -0,0 +1,173 @@ +# frozen_string_literal: false +require 'test/unit' +require 'uri' + +class URI::TestWHATWGPunycode < Test::Unit::TestCase + Punycode = URI::WHATWG_Parser::Punycode + + # [Unicode, Punycode] + ROUND_TRIPS = [ + ["", ""], + ["a", "a-"], + ["abc", "abc-"], + ["-> $1.00 <-", "-> $1.00 <--"], + ["\u00FC", "tda"], + ["b\u00FCcher", "bcher-kva"], + ["fa\u00DF", "fa-hia"], + ["\u2615", "53h"], + ["\u65E5\u672C\u8A9E", "wgv71a119e"], + ["\u30CF\u30ED\u30FC\u30FB\u30EF\u30FC\u30EB\u30C9", "gdkl8fhk5egc"], + ["3\u5E74B\u7D44\u91D1\u516B\u5148\u751F", "3B-ww4c5e180e575a65lsy2b"], + # RFC 3492 7.1 (A) Arabic (Egyptian) + ["\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F", + "egbpdaj6bu4bxfgehfvwxn"], + # RFC 3492 7.1 (B) Chinese (simplified) + ["\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587", "ihqwcrb4cv8a8dqg056pqjye"], + ["\u00E9-", "--9fa"], + ["-\u00E9", "--bga"], + # boundaries of the code space + ["\u0080", "a"], + ["\u007F\u0080", "\u007F-ba"], + ["\u{1F600}", "e28h"], + ["\u{10FFFF}", "dn32g"], + ["\u{E000}", "0y0c"], + ] + + ROUND_TRIPS.each_with_index do |(unicode, punycode), i| + define_method("test_encode_#{i}") do + assert_equal(punycode, Punycode.encode(unicode)) + end + + define_method("test_decode_#{i}") do + assert_equal(unicode, Punycode.decode(punycode)) + end + end + + def test_encode_returns_ascii + assert_predicate(Punycode.encode("\u65E5\u672C\u8A9E"), :ascii_only?) + end + + def test_decode_returns_utf8 + assert_equal(Encoding::UTF_8, Punycode.decode("tda").encoding) + assert_equal(Encoding::UTF_8, Punycode.decode("a-").encoding) + end + + def test_decode_digits_are_case_insensitive + assert_equal("b\u00FCcher", Punycode.decode("bcher-KVA")) + end + + def test_decode_keeps_the_case_of_basic_code_points + assert_equal("B\u00FCCHER", Punycode.decode("BCHER-KVA")) + end + + def test_decode_lone_delimiter + assert_equal("", Punycode.decode("-")) + end + + def test_decode_splits_at_the_last_delimiter + assert_equal("a-b", Punycode.decode("a-b-")) + end + + def test_decode_rejects_non_ascii + assert_nil(Punycode.decode("\u00FC")) + assert_nil(Punycode.decode("\u00FC-tda")) + end + + def test_decode_rejects_invalid_digits + assert_nil(Punycode.decode("a-!")) + assert_nil(Punycode.decode("a-_")) + assert_nil(Punycode.decode("a- ")) + end + + def test_decode_rejects_truncated_input + # "9" is a digit that does not end the variable-length integer. + assert_nil(Punycode.decode("a-9")) + assert_nil(Punycode.decode("z" * 50)) + end + + def test_decode_rejects_code_points_beyond_unicode + assert_nil(Punycode.decode("en32g")) # U+110000 + end + + def test_decode_rejects_surrogates + assert_nil(Punycode.decode("ib9b")) # U+D800 + assert_nil(Punycode.decode("zy0c")) # U+DFFF + end + + def test_decode_rejects_overflow + assert_nil(Punycode.decode("9" * 10 + "a")) + assert_nil(Punycode.decode("a-" + "9" * 10 + "a")) + end + + def test_encode_with_repeated_and_interleaved_code_points + # Each occurrence of a code point is counted against the code points + # smaller than it on both sides. + assert_equal("a\u{E9}b\u{E9}\u{FC}c\u{E9}", Punycode.decode(Punycode.encode("a\u{E9}b\u{E9}\u{FC}c\u{E9}"))) + assert_equal("ab-9iab8gc", Punycode.encode("\u{E9}a\u{FC}\u{E9}b\u{FC}")) + end + + def test_encode_in_linear_time + # The number of distinct code points must not multiply the time. + pre = ->(n) { (0x4E00...0x4E00 + n).map { |c| c.chr(Encoding::UTF_8) }.join } + assert_linear_performance([300, 1_000, 3_000, 10_000], pre: pre) do |label| + Punycode.encode(label) + end + end + + def test_decode_in_linear_time + pre = ->(n) { Punycode.encode((0x4E00...0x4E00 + n).map { |c| c.chr(Encoding::UTF_8) }.join) } + assert_linear_performance([300, 1_000, 3_000, 10_000], pre: pre) do |punycode| + Punycode.decode(punycode) + end + end + + # Code points in descending order are each inserted at the start of + # the decoded output, the worst case for inserting into an array. + def test_decode_in_linear_time_with_insertions_at_the_start + pre = ->(n) { Punycode.encode((0x10000...0x10000 + n).map { |c| c.chr(Encoding::UTF_8) }.join.reverse) } + assert_linear_performance([3_000, 10_000, 30_000, 100_000], pre: pre) do |punycode| + Punycode.decode(punycode) + end + end + + def test_decode_inverts_encode + [ + "", + "a", + "abc", + "\u{E9}", + "\u{E9}\u{E9}\u{E9}", + "\u{FC}\u{E9}", + "\u{E9}a", + "a\u{E9}", + "a\u{E9}b", + "\u{E9}ab\u{FC}", + "\u{3042}a\u{E9}b\u{3042}c\u{E9}", + "\u{10FFFF}\u{80}\u{10000}", + (0x4E00...0x4E40).map { |c| c.chr(Encoding::UTF_8) }.join.reverse, + (0x4E00...0x4E40).map { |c| c.chr(Encoding::UTF_8) }.each_slice(2).map(&:reverse).join, + "ab" + (0x4E00...0x4E20).map { |c| c.chr(Encoding::UTF_8) }.join("x").reverse, + ].each do |label| + assert_equal(label, Punycode.decode(Punycode.encode(label)), label.dump) + end + end + + # Many insertions are placed otherwise than a few. + def test_decode_inverts_encode_with_many_insertions + code_points = (0x4E00...0x4E00 + 3000).map { |c| c.chr(Encoding::UTF_8) } + [ + code_points.first(1024).reverse.join, + code_points.first(1025).reverse.join, + code_points.reverse.join, + code_points.shuffle(random: Random.new(1)).join, + code_points.shuffle(random: Random.new(2)).each_slice(3).map { |s| s.join + "a-" }.join, + code_points.first(1500).zip(code_points.last(1500)).flatten.join, + ].each_with_index do |label, i| + assert_equal(label, Punycode.decode(Punycode.encode(label)), "label #{i}") + end + end + + def test_decode_of_a_non_string + assert_raise(NoMethodError, TypeError) { Punycode.decode(nil) } + end +end diff --git a/test/uri/test_whatwg_setters.rb b/test/uri/test_whatwg_setters.rb new file mode 100644 index 00000000..b2b8cdfb --- /dev/null +++ b/test/uri/test_whatwg_setters.rb @@ -0,0 +1,679 @@ +# frozen_string_literal: false +require 'test/unit' +require 'uri' + +# Setters of URIs built by URI::WHATWG_PARSER follow the setters of the +# URL Standard (https://url.spec.whatwg.org/#api), except that a value +# the URL Standard ignores raises URI::InvalidComponentError instead of +# leaving the URI silently unchanged. +class URI::TestWHATWGSetters < Test::Unit::TestCase + def url(str) + URI::WHATWG_PARSER.parse(str) + end + + def assert_set(expected, str, attribute, value) + uri = url(str) + uri.public_send("#{attribute}=", value) + assert_equal(expected, uri.to_s, "#{str.dump}.#{attribute} = #{value.inspect}") + end + + def assert_rejected(str, attribute, value) + uri = url(str) + assert_raise(URI::InvalidComponentError, "#{str.dump}.#{attribute} = #{value.inspect}") do + uri.public_send("#{attribute}=", value) + end + assert_equal(url(str).to_s, uri.to_s, "unchanged after #{attribute} = #{value.inspect}") + end + + # --- which URIs ---------------------------------------------------- + + def test_rfc3986_uris_keep_their_setters + uri = URI::RFC3986_PARSER.parse("http://example.com/") + assert_raise(URI::InvalidComponentError) { uri.host = "\u{65E5}\u{672C}\u{8A9E}.jp" } + assert_raise(URI::InvalidComponentError) { uri.port = "8080abc" } + end + + def test_dup_keeps_the_setters + uri = url("http://example.com/").dup + uri.host = "\u{E9}" + assert_equal("http://xn--9ca/", uri.to_s) + end + + def test_marshal_keeps_the_setters + uri = Marshal.load(Marshal.dump(url("http://example.com/"))) + uri.host = "\u{E9}" + assert_equal("http://xn--9ca/", uri.to_s) + end + + def test_merged_uri_keeps_the_setters + uri = url("http://example.com/a") + "b" + uri.host = "\u{E9}" + assert_equal("http://xn--9ca/b", uri.to_s) + end + + def test_merge_bang + uri = url("http://example.com/a/b") + uri.merge!("../c?q#f") + assert_equal("http://example.com/c?q#f", uri.to_s) + end + + def test_merge_bang_on_an_opaque_path + uri = url("mailto:x") + uri.merge!("#f") + assert_equal("mailto:x#f", uri.to_s) + end + + def test_merge_bang_on_a_non_special_uri + uri = url("foo://h/a/b") + uri.merge!("c") + assert_equal("foo://h/a/c", uri.to_s) + end + + def test_the_value_is_returned + uri = url("http://example.com/") + assert_equal(8080, (uri.port = 8080)) + end + + # --- encodings of the values --------------------------------------- + + # A value is converted to UTF-8 before it is percent-encoded, as the + # input of the parser is. + def test_values_are_converted_to_utf8 + latin1 = "\u{E9}".encode("ISO-8859-1") + assert_set("http://%C3%A9@example.com/", "http://example.com/", :user, latin1) + assert_set("http://:%C3%A9@example.com/", "http://example.com/", :password, latin1) + assert_set("http://xn--9ca/", "http://example.com/", :host, latin1) + assert_set("http://example.com/%C3%A9", "http://example.com/", :path, latin1) + assert_set("http://example.com/?%C3%A9", "http://example.com/", :query, latin1) + assert_set("http://example.com/#%C3%A9", "http://example.com/", :fragment, latin1) + end + + def test_userinfo_is_converted_to_utf8 + latin1 = "\u{E9}:\u{E9}".encode("ISO-8859-1") + assert_set("http://%C3%A9:%C3%A9@example.com/", "http://example.com/", :userinfo, latin1) + assert_set("http://%C3%A9:%C3%A9@example.com/", "http://example.com/", :userinfo, + ["\u{E9}".encode("ISO-8859-1"), "\u{E9}".encode("ISO-8859-1")]) + end + + def test_ascii_incompatible_values + assert_set("https://example.com/", "http://example.com/", :scheme, "https".encode("UTF-16LE")) + assert_set("http://u@example.com/", "http://example.com/", :user, "u".encode("UTF-16LE")) + assert_set("http://h/", "http://example.com/", :host, "h".encode("UTF-16BE")) + assert_set("http://example.com:8080/", "http://example.com/", :port, "8080".encode("UTF-16LE")) + assert_set("http://example.com/a%09b", "http://example.com/", :path, "a%09b".encode("UTF-16LE")) + assert_set("http://example.com/?a%20%C3%A9", "http://example.com/", :query, "a \u{E9}".encode("UTF-16LE")) + assert_set("http://example.com/#x", "http://example.com/", :fragment, "x".encode("UTF-32LE")) + end + + def test_ascii_only_binary_values + assert_set("http://example.com/?abc", "http://example.com/", :query, "abc".b) + end + + def test_values_with_invalid_byte_sequences + invalid = "\xFF".dup.force_encoding("UTF-8") + %i[scheme user password userinfo host port path query fragment].each do |attribute| + assert_rejected("http://example.com/", attribute, invalid) + end + assert_rejected("http://example.com/", :userinfo, ["u", invalid]) + end + + def test_values_that_cannot_be_converted_to_utf8 + assert_rejected("http://example.com/", :query, "\xE9".b) + assert_rejected("http://example.com/", :host, "\xE9".b) + end + + def test_the_value_is_returned_as_given + uri = url("http://example.com/") + latin1 = "\u{E9}".encode("ISO-8859-1") + assert_same(latin1, (uri.query = latin1)) + end + + # --- scheme= (protocol setter) ------------------------------------- + + def test_scheme + assert_set("https://example.com/", "http://example.com/", :scheme, "https") + assert_set("https://example.com/", "http://example.com/", :scheme, "HTTPS") + assert_set("wss://example.com/", "http://example.com/", :scheme, "wss") + assert_set("bar://h/", "foo://h/", :scheme, "bar") + end + + def test_scheme_up_to_a_colon + assert_set("https://example.com/", "http://example.com/", :scheme, "https:foo") + end + + def test_scheme_strips_tabs_and_newlines + assert_set("https://example.com/", "http://example.com/", :scheme, "ht\ttp\ns") + end + + def test_scheme_with_invalid_code_points + assert_rejected("http://example.com/", :scheme, "") + assert_rejected("http://example.com/", :scheme, "ht tp") + assert_rejected("http://example.com/", :scheme, "1http") + assert_rejected("http://example.com/", :scheme, "\u{E9}") + end + + def test_scheme_between_special_and_not_special + assert_rejected("http://example.com/", :scheme, "foo") + assert_rejected("foo://example.com/", :scheme, "http") + end + + def test_scheme_file_with_credentials_or_port + assert_rejected("http://u@example.com/", :scheme, "file") + assert_rejected("http://example.com:8080/", :scheme, "file") + assert_set("file://example.com/", "http://example.com/", :scheme, "file") + end + + def test_scheme_from_file_with_an_empty_host + assert_rejected("file:///p", :scheme, "http") + assert_set("http://h/p", "file://h/p", :scheme, "http") + end + + def test_scheme_drops_the_new_default_port + uri = url("http://example.com:443/") + uri.scheme = "https" + assert_equal("https://example.com/", uri.to_s) + assert_equal(443, uri.port) + assert_equal(443, uri.default_port) + end + + def test_scheme_keeps_another_port + assert_set("https://example.com:8080/", "http://example.com:8080/", :scheme, "https") + # http://example.com/ has no port, not port 80. + assert_set("https://example.com/", "http://example.com/", :scheme, "https") + end + + # The class of an object cannot change, as for RFC 3986 URIs; parsing + # the URI again gives the class of its new scheme. + def test_scheme_keeps_the_class + uri = url("http://example.com/") + uri.scheme = "https" + assert_instance_of(URI::HTTP, uri) + assert_equal("https://example.com/", uri.to_s) + assert_equal(443, uri.port) + assert_instance_of(URI::HTTPS, URI::WHATWG_PARSER.parse(uri.to_s)) + + uri = url("https://example.com/") + uri.scheme = "http" + assert_instance_of(URI::HTTPS, uri) + assert_instance_of(URI::HTTP, URI::WHATWG_PARSER.parse(uri.to_s)) + + uri = url("foo://example.com/") + uri.scheme = "bar" + assert_instance_of(URI::Generic, uri) + end + + # --- user= and password= ------------------------------------------- + + def test_user + assert_set("http://me@example.com/", "http://example.com/", :user, "me") + assert_set("http://me:p@example.com/", "http://u:p@example.com/", :user, "me") + end + + def test_user_is_percent_encoded + assert_set("http://a%20b%40c%3A@example.com/", "http://example.com/", :user, "a b@c:") + assert_set("http://%C3%A9@example.com/", "http://example.com/", :user, "\u{E9}") + end + + def test_user_keeps_tabs + assert_set("http://a%09b@example.com/", "http://example.com/", :user, "a\tb") + end + + def test_empty_user + assert_set("http://example.com/", "http://u@example.com/", :user, "") + assert_set("http://:p@example.com/", "http://u:p@example.com/", :user, "") + assert_set("http://example.com/", "http://u@example.com/", :user, nil) + end + + def test_password + assert_set("http://u:p@example.com/", "http://u@example.com/", :password, "p") + assert_set("http://:p@example.com/", "http://example.com/", :password, "p") + assert_set("http://u:a%20b%40%3A@example.com/", "http://u@example.com/", :password, "a b@:") + end + + def test_empty_password + assert_set("http://u@example.com/", "http://u:p@example.com/", :password, "") + assert_set("http://example.com/", "http://:p@example.com/", :password, nil) + end + + def test_credentials_without_a_host + assert_rejected("file:///p", :user, "u") + assert_rejected("file://h/p", :password, "p") + assert_rejected("foo:///p", :user, "u") + assert_rejected("foo:/p", :password, "p") + assert_rejected("mailto:x", :user, "u") + end + + # --- userinfo= (username and password setters) --------------------- + + def test_userinfo + assert_set("http://u:p@example.com/", "http://example.com/", :userinfo, "u:p") + assert_set("http://me:pw@example.com/", "http://u:p@example.com/", :userinfo, "me:pw") + end + + def test_userinfo_without_a_colon_clears_the_password + assert_set("http://u@example.com/", "http://x:y@example.com/", :userinfo, "u") + end + + def test_userinfo_is_split_at_the_first_colon + assert_set("http://u:a%3Ab@example.com/", "http://example.com/", :userinfo, "u:a:b") + assert_set("http://:p@example.com/", "http://u@example.com/", :userinfo, ":p") + assert_set("http://u@example.com/", "http://example.com/", :userinfo, "u:") + end + + def test_userinfo_is_percent_encoded + assert_set("http://a%20b%40c:d%20e@example.com/", "http://example.com/", :userinfo, "a b@c:d e") + assert_set("http://%C3%A9:%C3%A9@example.com/", "http://example.com/", :userinfo, "\u{E9}:\u{E9}") + end + + def test_userinfo_keeps_tabs + assert_set("http://a%09b:c%0Ad@example.com/", "http://example.com/", :userinfo, "a\tb:c\nd") + end + + def test_userinfo_as_an_array + assert_set("http://u:a%3Ab@example.com/", "http://example.com/", :userinfo, ["u", "a:b"]) + assert_set("http://u@example.com/", "http://x:y@example.com/", :userinfo, ["u"]) + assert_set("http://u@example.com/", "http://x:y@example.com/", :userinfo, ["u", nil]) + end + + def test_empty_userinfo_clears_the_credentials + assert_set("http://example.com/", "http://u:p@example.com/", :userinfo, "") + assert_set("http://example.com/", "http://u:p@example.com/", :userinfo, ":") + assert_set("http://example.com/", "http://u:p@example.com/", :userinfo, nil) + end + + def test_userinfo_without_a_host + assert_rejected("file:///p", :userinfo, "u:p") + assert_rejected("file://h/p", :userinfo, "u:p") + assert_rejected("foo:///p", :userinfo, "u:p") + assert_rejected("foo:/p", :userinfo, "u:p") + assert_rejected("mailto:x", :userinfo, "u:p") + assert_rejected("foo:///p", :userinfo, nil) + end + + def test_userinfo_value_is_returned + uri = url("http://example.com/") + assert_equal("u:p", (uri.userinfo = "u:p")) + end + + def test_userinfo_keeps_the_uri_reparsable + uri = url("foo://h/x") + uri.userinfo = "a b" + uri.path = "y" + assert_equal("foo://a%20b@h/y", uri.to_s) + end + + # --- opaque= ------------------------------------------------------- + + # The URL Standard has no setter for an opaque path, and a URL with a + # host cannot get one. + def test_opaque_is_rejected + assert_rejected("mailto:x", :opaque, "y") + assert_rejected("http://example.com/", :opaque, "zz") + assert_rejected("foo:///x", :opaque, "zz") + assert_rejected("mailto:x", :opaque, "") + assert_rejected("mailto:x", :opaque, nil) + assert_rejected("http://example.com/", :opaque, nil) + end + + # --- host= (hostname setter) --------------------------------------- + + def test_host + assert_set("http://example.org/p", "http://example.com/p", :host, "example.org") + assert_set("http://example.org/p", "http://example.com/p", :host, "EXAMPLE.org") + assert_set("http://127.0.0.1/", "http://example.com/", :host, "0x7f.1") + assert_set("http://[::1]/", "http://example.com/", :host, "[0:0::1]") + end + + def test_host_to_ascii + assert_set("http://xn--wgv71a119e.jp/", "http://example.com/", :host, "\u{65E5}\u{672C}\u{8A9E}.jp") + end + + def test_host_keeps_the_port + assert_set("http://example.org:8080/", "http://example.com:8080/", :host, "example.org") + end + + def test_host_with_a_port + assert_rejected("http://example.com/", :host, "example.org:8080") + end + + # A ":" inside brackets is part of an IPv6 address, and one outside + # them starts the port, which the hostname setter does not set. + def test_host_with_colons_and_brackets + assert_set("http://[::1]/", "http://example.com/", :host, "[::1]") + assert_set("http://[::1]/", "http://example.com/", :host, "[::1]/x") + assert_set("http://[::1]/", "http://example.com/", :host, "[::1]?x") + assert_rejected("http://example.com/", :host, "[::1]:8080") + assert_rejected("http://example.com/", :host, ":") + assert_rejected("http://example.com/", :host, ":8080") + assert_rejected("http://example.com/", :host, "a:") + assert_rejected("http://example.com/", :host, "a]:b") + assert_rejected("http://example.com/", :host, "[a]b:c") + assert_rejected("http://example.com/", :host, "[::1/]") + assert_rejected("foo://example.com/", :host, "[::1]:1") + assert_set("foo://[::1]/", "foo://example.com/", :host, "[::1]") + end + + def test_host_up_to_a_path_query_or_fragment + assert_set("http://a/p", "http://example.com/p", :host, "a/b") + assert_set("http://a/p", "http://example.com/p", :host, "a?b") + assert_set("http://a/p", "http://example.com/p", :host, "a#b") + assert_set("http://a/p", "http://example.com/p", :host, "a\\b") + end + + def test_host_strips_tabs_and_newlines + assert_set("http://example.org/", "http://example.com/", :host, "exa\tmple.o\nrg") + end + + def test_invalid_host + assert_rejected("http://example.com/", :host, "a b") + assert_rejected("http://example.com/", :host, "a%") + assert_rejected("http://example.com/", :host, "[::1") + assert_rejected("http://example.com/", :host, "a\u{200C}b") + end + + def test_empty_host_of_a_special_uri + assert_rejected("http://example.com/", :host, "") + assert_rejected("http://example.com/", :host, nil) + assert_rejected("http://example.com/", :host, "/a") + end + + def test_host_of_a_non_special_uri + assert_set("foo://example.org/p", "foo://example.com/p", :host, "example.org") + assert_set("foo://%C3%A9/p", "foo://example.com/p", :host, "\u{E9}") + assert_rejected("foo://example.com/p", :host, "a\\b") + end + + def test_empty_host_of_a_non_special_uri + assert_set("foo:///p", "foo://example.com/p", :host, "") + assert_rejected("foo://u@example.com/p", :host, "") + assert_rejected("foo://example.com:8080/p", :host, "") + end + + def test_host_of_an_opaque_path + assert_rejected("mailto:x", :host, "example.com") + end + + def test_host_of_a_file_uri + assert_set("file://example.com/p", "file:///p", :host, "example.com") + assert_set("file:///p", "file://example.com/p", :host, "localhost") + assert_set("file:///p", "file://example.com/p", :host, "") + assert_rejected("file:///p", :host, "example.com:8080") + end + + def test_host_of_a_file_uri_is_parsed_as_a_special_host + assert_set("file:///p", "file://example.com/p", :host, "LOCALHOST") + assert_set("file:///p", "file://example.com/p", :host, "loc%41lhost") + assert_set("file://xn--9ca/p", "file:///p", :host, "\u{E9}") + assert_set("file://127.0.0.1/p", "file:///p", :host, "0x7f.1") + assert_set("file://[::1]/p", "file:///p", :host, "[::1]") + assert_rejected("file:///p", :host, "a b") + assert_rejected("file:///p", :host, "C:") + assert_rejected("file:///p", :host, "[::1") + end + + def test_host_of_a_file_uri_up_to_a_path_query_or_fragment + assert_set("file://a/p", "file:///p", :host, "a/b") + assert_set("file://a/p", "file:///p", :host, "a\\b") + assert_set("file://a/p", "file:///p", :host, "a?b") + assert_set("file://a/p", "file:///p", :host, "a#b") + assert_set("file:///p", "file://example.com/p", :host, "/a") + end + + def test_hostname_wraps_ipv6 + uri = url("http://example.com/") + uri.hostname = "::1" + assert_equal("http://[::1]/", uri.to_s) + end + + # --- port= --------------------------------------------------------- + + def test_port + assert_set("http://example.com:8080/", "http://example.com/", :port, 8080) + assert_set("http://example.com:8080/", "http://example.com/", :port, "8080") + assert_set("http://example.com:0/", "http://example.com/", :port, 0) + end + + def test_port_boundaries + assert_set("http://example.com:65535/", "http://example.com/", :port, 65535) + assert_rejected("http://example.com/", :port, 65536) + assert_rejected("http://example.com/", :port, "99999999999999999999") + end + + def test_port_with_leading_zeros + assert_set("http://example.com:65535/", "http://example.com/", :port, "0" * 100 + "65535") + assert_rejected("http://example.com/", :port, "0" * 100 + "65536") + assert_set("http://example.com:0/", "http://example.com/", :port, "0" * 100) + assert_set("http://example.com/", "http://example.com:8080/", :port, "0" * 100 + "80") + assert_set("http://example.com:8080/", "http://example.com/", :port, "0" * 100 + "8080abc") + end + + def test_port_with_many_digits + assert_rejected("http://example.com/", :port, "1" + "0" * 5) + assert_rejected("http://example.com/", :port, "1" * 100) + assert_rejected("http://example.com/", :port, "1" * 100 + "abc") + end + + def test_port_in_linear_time + pre = ->(n) { [url("http://example.com/"), "1" * n] } + assert_linear_performance([10_000, 100_000, 1_000_000], pre: pre) do |uri, digits| + uri.port = digits + rescue URI::InvalidComponentError + end + end + + def test_port_up_to_a_non_digit + assert_set("http://example.com:8080/", "http://example.com/", :port, "8080abc") + assert_set("http://example.com:8080/", "http://example.com/", :port, "8080/x") + end + + def test_port_strips_tabs_and_newlines + assert_set("http://example.com:8080/", "http://example.com/", :port, "80\t8\n0") + end + + def test_port_without_digits + assert_rejected("http://example.com/", :port, "abc") + assert_rejected("http://example.com/", :port, " 8080") + assert_rejected("http://example.com/", :port, -1) + end + + def test_default_port + uri = url("http://example.com:8080/") + uri.port = 80 + assert_equal("http://example.com/", uri.to_s) + assert_equal(80, uri.port) + end + + def test_empty_port + assert_set("http://example.com/", "http://example.com:8080/", :port, "") + assert_set("http://example.com/", "http://example.com:8080/", :port, nil) + assert_set("foo://example.com/", "foo://example.com:8080/", :port, nil) + end + + def test_port_of_only_tabs_and_newlines + # Only the empty string removes the port; tabs and newlines are + # removed afterwards and leave no digits. + assert_rejected("http://example.com:8080/", :port, "\n\t") + end + + def test_port_without_a_host + assert_rejected("file://example.com/", :port, 8080) + assert_rejected("foo:///p", :port, 8080) + assert_rejected("foo:/p", :port, 8080) + end + + # --- path= (pathname setter) --------------------------------------- + + def test_path + assert_set("http://example.com/a/b", "http://example.com/x", :path, "/a/b") + assert_set("http://example.com/a", "http://example.com/x", :path, "a") + assert_set("http://example.com/", "http://example.com/x", :path, "") + end + + def test_path_is_normalized_and_percent_encoded + assert_set("http://example.com/b", "http://example.com/x", :path, "/a/../b") + assert_set("http://example.com/a%20b", "http://example.com/x", :path, "a b") + assert_set("http://example.com/a%3Fb%23c", "http://example.com/x", :path, "a?b#c") + end + + def test_path_keeps_query_and_fragment + assert_set("http://example.com/a?q#f", "http://example.com/x?q#f", :path, "a") + end + + def test_path_backslashes + assert_set("http://example.com/a/b", "http://example.com/x", :path, "\\a\\b") + assert_set("foo://h/\\a", "foo://h/x", :path, "\\a") + end + + def test_path_of_a_non_special_uri + assert_set("foo://h/a", "foo://h/x", :path, "a") + assert_set("foo://h", "foo://h/x", :path, "") + assert_set("foo:/", "foo:/x", :path, "") + assert_set("foo:/.//a", "foo:/x", :path, "//a") + end + + def test_path_of_a_file_uri + assert_set("file:///C:/a", "file:///x", :path, "C|/a") + end + + def test_path_of_an_opaque_path + assert_rejected("mailto:x", :path, "y") + end + + # --- query= (search setter) ---------------------------------------- + + def test_query + assert_set("http://example.com/?a=b", "http://example.com/", :query, "a=b") + assert_set("http://example.com/?a%20b", "http://example.com/?x", :query, "a b") + assert_set("http://example.com/?", "http://example.com/?x", :query, "") + end + + def test_query_keeps_a_leading_question_mark + assert_set("http://example.com/??a", "http://example.com/", :query, "?a") + end + + def test_query_percent_encoding + assert_set("http://example.com/?%27%23", "http://example.com/", :query, "'#") + assert_set("foo://h/?'%23", "foo://h/", :query, "'#") + assert_set("http://example.com/?%C3%A9", "http://example.com/", :query, "\u{E9}") + end + + def test_query_strips_tabs_and_newlines + assert_set("http://example.com/?ab", "http://example.com/", :query, "a\tb\n") + end + + def test_query_removed + assert_set("http://example.com/#f", "http://example.com/?q#f", :query, nil) + end + + def test_query_of_an_opaque_path + assert_set("mailto:x?a", "mailto:x", :query, "a") + assert_set("mailto:x", "mailto:x?q", :query, nil) + end + + def test_query_removed_from_an_opaque_path_ending_with_a_space + # The space before "?" was encoded when parsed, so it stays. + assert_set("sc:a%20", "sc:a ?q", :query, nil) + end + + # --- fragment= (hash setter) --------------------------------------- + + def test_fragment + assert_set("http://example.com/#a", "http://example.com/", :fragment, "a") + assert_set("http://example.com/#a%20b%60", "http://example.com/#x", :fragment, "a b`") + assert_set("http://example.com/#a#b", "http://example.com/", :fragment, "a#b") + assert_set("http://example.com/#", "http://example.com/#x", :fragment, "") + end + + def test_fragment_strips_tabs_and_newlines + assert_set("http://example.com/#ab", "http://example.com/", :fragment, "a\tb\n") + end + + def test_fragment_removed + assert_set("http://example.com/?q", "http://example.com/?q#f", :fragment, nil) + end + + def test_fragment_removed_from_an_opaque_path_ending_with_a_space + assert_set("sc:a%20", "sc:a #f", :fragment, nil) + end + # --- the URL record behind a URI ----------------------------------- + + # A setter applies to the URL record that the URI serializes, so + # every other part is kept as it is. + URLS_KEPT_BY_SETTERS = [ + "http://example.com/", + "http://u:p@example.com:8080/a/b?q#f", + "http://u@example.com/", + "http://:p@example.com/", + "http://example.com/?#", + "http://example.com/a/", + "http://example.com//a//b", + "http://192.168.0.1/", + "http://[::1]:8080/", + "http://xn--9ca/", + "https://example.com:443/", + "ws://example.com:80/", + "file:///", + "file:///C:/a", + "file://host/a", + "foo://", + "foo:///", + "foo://h", + "foo://h/", + "foo://H/%C3%A9", + "foo://h:1/a", + "foo:", + "foo:/", + "foo:/a/b", + "foo:/.//a/b", + "foo:/..//a", + "foo:/a/..//b", + "mailto:x", + "mailto:x?q", + "mailto:x?", + "sc:a%20", + "sc:a%20?q", + "sc:", + "sc:?q", + ].freeze + + def test_setters_keep_the_other_parts + URLS_KEPT_BY_SETTERS.each do |str| + expected = url(str).to_s + uri = url(str) + uri.fragment = "f2" + assert_equal(expected.sub(/#.*\z/, "") + "#f2", uri.to_s, str) + uri.fragment = nil + assert_equal(expected.sub(/#.*\z/, ""), uri.to_s, str) + end + end + + def test_setters_keep_the_components + URLS_KEPT_BY_SETTERS.each do |str| + uri = url(str) + uri.fragment = uri.fragment + fresh = url(str) + %i[scheme user password host port path opaque query fragment].each do |component| + assert_equal(fresh.public_send(component), uri.public_send(component), "#{str}: #{component}") + end + end + end + + def test_setters_apply_to_the_hostless_path_written_with_a_dot + assert_set("foo:/.//a/c", "foo:/.//a/b", :path, "//a/c") + assert_set("foo:/.//a/b?q", "foo:/.//a/b", :query, "q") + assert_set("foo:/a", "foo:/.//a/b", :path, "a") + end + + def test_setters_apply_to_an_opaque_path_with_a_query + assert_set("mailto:x?r", "mailto:x?q", :query, "r") + assert_set("mailto:x", "mailto:x?q", :query, nil) + assert_set("mailto:x?q#f", "mailto:x?q", :fragment, "f") + end + + def test_setters_after_normalize + uri = url("foo://H/") + uri.normalize! + uri.fragment = "f" + assert_equal("foo://H/#f", uri.to_s) + end +end diff --git a/test/uri/test_whatwg_setters_stripping.rb b/test/uri/test_whatwg_setters_stripping.rb new file mode 100644 index 00000000..1253bfcd --- /dev/null +++ b/test/uri/test_whatwg_setters_stripping.rb @@ -0,0 +1,95 @@ +# frozen_string_literal: false +require 'test/unit' +require 'uri' + +# A port of WPT url/url-setters-stripping.any.js: which C0 controls the +# setters of a WHATWG URI strip (tab, LF and CR) and which they keep or +# reject, at the start, in the middle and at the end of the value. +# +# The cases of the host setter (URI has no setter for a host with a +# port) and of searchParams (URI has no equivalent) are not ported. A +# value rejected with URI::InvalidComponentError leaves the URI +# unchanged, as the URL Standard does. +class URI::TestWHATWGSettersStripping < Test::Unit::TestCase + SCHEMES = ["https", "wpt++"].freeze + # As in WPT, only these C0 controls are tested: user agents treat the + # others like U+0000 or U+001F. + CODE_POINTS = [0x00, 0x09, 0x0A, 0x0D, 0x1F].freeze + STRIPPED = [0x09, 0x0A, 0x0D].freeze + + def self.url_string(scheme: "https", username: "username", password: "password", host: "host", + port: "8000", pathname: "path", search: "query", hash: "fragment") + "#{scheme}://#{username}:#{password}@#{host}:#{port}/#{pathname}?#{search}##{hash}" + end + + # encodeURIComponent of a C0 control. + def self.encode(char) + format("%%%02X", char.ord) + end + + def self.reference(code_point) + format("U+%04X", code_point) + end + + def self.affixed(char) + [["leading", char + "test"], ["middle", "te" + char + "st"], ["trailing", "test" + char]] + end + + # Defines a test that sets +attribute+ to +value+ on the URL of + # +scheme+, expecting the URL of +expected_parts+ afterwards. + def self.define_case(name, scheme, attribute, value, expected_parts) + define_method("test_#{name} (#{scheme}:)") do + uri = URI::WHATWG_PARSER.parse(self.class.url_string(scheme: scheme)) + begin + uri.public_send("#{attribute}=", value) + rescue URI::InvalidComponentError + # Left unchanged. + end + assert_equal(self.class.url_string(scheme: scheme, **expected_parts), uri.to_s) + end + end + + SCHEMES.each do |scheme| + CODE_POINTS.each do |code_point| + char = code_point.chr + stripped = STRIPPED.include?(code_point) + ref = reference(code_point) + new_scheme = scheme == "https" ? "http" : "wpt--" + expected_scheme = stripped ? new_scheme : scheme + + define_case("scheme with leading #{ref}", scheme, :scheme, char + new_scheme, scheme: expected_scheme) + define_case("scheme with #{ref} before inserted colon", scheme, :scheme, new_scheme + char, scheme: expected_scheme) + + # No stripping. + [[:user, :username], [:password, :password]].each do |attribute, part| + affixed(char).each do |type, value| + expected = value.sub(char, encode(char)) + define_case("#{attribute} with #{type} #{ref}", scheme, attribute, value, part => expected) + end + end + + affixed(char).each do |type, value| + expected = + if code_point == 0x00 || (scheme == "https" && code_point == 0x1F) + "host" + elsif stripped + "test" + else + value.sub(char, scheme == "https" ? char : encode(char)) + end + define_case("host with #{type} #{ref}", scheme, :host, value, host: expected) + end + + define_case("port with leading #{ref}", scheme, :port, char + "9000", port: stripped ? "9000" : "8000") + define_case("port with middle #{ref}", scheme, :port, "90" + char + "00", port: stripped ? "9000" : "90") + define_case("port with trailing #{ref}", scheme, :port, "9000" + char, port: "9000") + + [[:path, :pathname], [:query, :search], [:fragment, :hash]].each do |attribute, part| + affixed(char).each do |type, value| + expected = stripped ? "test" : value.sub(char, encode(char)) + define_case("#{attribute} with #{type} #{ref}", scheme, attribute, value, part => expected) + end + end + end + end +end diff --git a/test/wpt/idna_test_v2.rb b/test/wpt/idna_test_v2.rb new file mode 100644 index 00000000..d0a0e4ab --- /dev/null +++ b/test/wpt/idna_test_v2.rb @@ -0,0 +1,141 @@ +# frozen_string_literal: true +require 'uri' +require 'rbconfig' +require_relative 'wpt_url_test_data' + +# Harness for running Unicode's IdnaTestV2.txt, the conformance test of +# UTS #46, against URI::WHATWG_Parser::IDNA.to_ascii. +# +# Each case is a Hash of :source, :to_ascii (the toAsciiN column: ToASCII +# with Nontransitional Processing), :status (the status codes of +# toAsciiN) and :line. :source and :to_ascii are nil when the column +# holds a surrogate, which a UTF-8 String cannot. +module IDNATestV2 + # Status codes of the checks that domain to ASCII turns off: + # CheckHyphens (V2, V3), UseSTD3ASCIIRules (U1) and VerifyDnsLength + # (A4_1, A4_2, and X4_2, which IdnaTestV2.txt reports for an empty + # label). + IGNORED_STATUSES = %w[V2 V3 U1 A4_1 A4_2 X4_2].freeze + + # The ReadMe of the latest version of the Unicode Character Database. + LATEST_README = "https://www.unicode.org/Public/UCD/latest/ReadMe.txt" + + ESCAPE = /\\u(\h{4})|\\x\{(\h+)\}/ + SURROGATES = (0xD800..0xDFFF).freeze + UNKNOWN_TO_RUBY = /(?!\p{Noncharacter_Code_Point})\p{Cn}/ + + module_function + + def unicode_version + URI::WHATWG_Parser::IDNA.load_data + URI::WHATWG_Parser::IDNA::UNICODE_VERSION + end + + # IdnaTestV2.txt of the Unicode version of URI::WHATWG_Parser's data. + def default_source + "https://www.unicode.org/Public/#{unicode_version}/idna/IdnaTestV2.txt" + end + + # IDNA_TEST_V2 (a local path or an https URL) if set, otherwise + # default_source. + def source + ENV["IDNA_TEST_V2"] || default_source + end + + # The Unicode version that +readme+ (LATEST_README) is for. + def latest_unicode_version(readme) + readme[/data files and charts for version (\d+\.\d+\.\d+)/, 1] or + raise "no Unicode version in #{LATEST_README}" + end + + def newer?(version, other) + Gem::Version.new(version) > Gem::Version.new(other) + end + + def load(source) + text = source.match?(%r{\A[A-Za-z][A-Za-z0-9+.-]*://}) ? WPT::URLTestData.fetch(source) : File.read(source) + parse(text.dup.force_encoding(Encoding::UTF_8)) + end + + def parse(text) + cases = [] + text.each_line.with_index(1) do |line, number| + line = line.sub(/#.*/, "").strip + next if line.empty? + + columns = line.split(";", -1).map(&:strip) + source = value(columns[0]) + to_unicode = columns[1].empty? ? source : value(columns[1]) + to_unicode_status = statuses(columns[2]) + to_ascii = columns[3].empty? ? to_unicode : value(columns[3]) + status = columns[4].empty? ? to_unicode_status : statuses(columns[4]) + cases << { source: source, to_ascii: to_ascii, status: status, line: number } + end + cases + end + + def value(column) + column == '""' ? "" : unescape(column) + end + + def statuses(column) + column.delete("[]").split(",").map(&:strip) + end + + # Replaces \uXXXX and \x{X...} escapes. Returns nil if one of them is a + # surrogate. + def unescape(str) + code_points = [] + result = str.gsub(ESCAPE) do + code_point = ($1 || $2).hex + code_points << code_point + SURROGATES.cover?(code_point) ? "" : code_point.chr(Encoding::UTF_8) + end + code_points.any? { |c| SURROGATES.cover?(c) } ? nil : result + end + + # {failure: true}, {value: expected ASCII}, or nil when the case cannot + # be checked: it holds a surrogate, it has only ignored errors and the + # file gives no ASCII result for it, or it succeeds with a code point + # that the running Ruby, whose Unicode data IDNA uses, does not know. + def expectation(test_case) + return nil if test_case[:source].nil? || test_case[:to_ascii].nil? + return { failure: true } unless (test_case[:status] - IGNORED_STATUSES).empty? + return nil unless test_case[:to_ascii].ascii_only? + return nil if unknown_to_ruby?(test_case) + { value: test_case[:to_ascii] } + end + + # Whether +test_case+ holds a code point that is unassigned in the + # Unicode version of the running Ruby, in its source or in its ASCII + # result decoded. Noncharacters are unassigned in every version. + def unknown_to_ruby?(test_case) + [test_case[:source], test_case[:to_ascii]].compact.any? do |domain| + domain.split(".", -1).any? do |label| + decoded = URI::WHATWG_Parser::Punycode.decode(label[4..-1]) if label.start_with?("xn--") && label.ascii_only? + [label, decoded].compact.any? { |s| s.match?(UNKNOWN_TO_RUBY) } + end + end + end + + # Runs +test_case+ with +to_ascii+, a callable that returns the ASCII + # domain or nil on failure. Returns nil when it passes, or a message. + def run(test_case, to_ascii) + expected = expectation(test_case) + return nil unless expected + + begin + actual = to_ascii.call(test_case[:source]) + rescue StandardError => e + return "#{e.class}: #{e.message}" + end + + if expected[:failure] + actual.nil? ? nil : "expected failure (#{test_case[:status].join(", ")}), got #{actual.inspect}" + elsif actual.nil? + "unexpected failure, expected #{expected[:value].inspect}" + elsif actual != expected[:value] + "expected #{expected[:value].inspect}, got #{actual.inspect}" + end + end +end diff --git a/test/wpt/normalization_test.rb b/test/wpt/normalization_test.rb new file mode 100644 index 00000000..9fff9ca0 --- /dev/null +++ b/test/wpt/normalization_test.rb @@ -0,0 +1,77 @@ +# frozen_string_literal: true +require 'uri' +require 'rbconfig' +require_relative 'wpt_url_test_data' + +# Harness for running Unicode's NormalizationTest.txt against +# URI::WHATWG_Parser::NFC.normalize and normalize_kc. +# +# Each case is a Hash of :columns (c1..c5), :line and :part. For NFC, the +# file requires c2 == NFC(c1) == NFC(c2) == NFC(c3) and +# c4 == NFC(c4) == NFC(c5); for NFKC, c4 == NFKC(c1) == ... == NFKC(c5). +# Every code point that Part 1 does not list is unchanged by both. +module NormalizationTest + module_function + + # NormalizationTest.txt of the Unicode version of the running Ruby, + # whose tables URI::WHATWG_Parser::NFC uses. + def default_source + "https://www.unicode.org/Public/#{RbConfig::CONFIG["UNICODE_VERSION"]}/ucd/NormalizationTest.txt" + end + + # NORMALIZATION_TEST (a local path or an https URL) if set, otherwise + # default_source. + def source + ENV["NORMALIZATION_TEST"] || default_source + end + + def load(source) + text = source.match?(%r{\A[A-Za-z][A-Za-z0-9+.-]*://}) ? WPT::URLTestData.fetch(source) : File.read(source) + parse(text.dup.force_encoding(Encoding::UTF_8)) + end + + def parse(text) + part = nil + cases = [] + text.each_line.with_index(1) do |line, number| + line = line.sub(/#.*/, "").strip + next if line.empty? + if line.start_with?("@") + part = line[1..-1].strip + next + end + columns = line.split(";").first(5).map { |column| column.split.map(&:hex).pack("U*") } + cases << { columns: columns, line: number, part: part } + end + cases + end + + def part1_code_points(cases) + cases.select { |c| c[:part] == "Part1" }.map { |c| c[:columns][0].ord } + end + + NFC_CHECKS = [[0, 1], [1, 1], [2, 1], [3, 3], [4, 3]].freeze + NFKC_CHECKS = [[0, 3], [1, 3], [2, 3], [3, 3], [4, 3]].freeze + + # Runs +test_case+ with +nfc+, and +nfkc+ if given, callables. Returns + # nil when it passes, or a message. + def run(test_case, nfc, nfkc = nil) + c = test_case[:columns] + checks = NFC_CHECKS.map { |source, expected| ["NFC", nfc, source, expected] } + checks += NFKC_CHECKS.map { |source, expected| ["NFKC", nfkc, source, expected] } if nfkc + # Array#filter_map needs Ruby 2.7, and rake test runs the harness on + # older versions too. + failures = checks.map do |form, normalize, source, expected| + actual = normalize.call(c[source]) + next if actual == c[expected] + "#{form}(c#{source + 1}) = #{dump(actual)}, expected c#{expected + 1} = #{dump(c[expected])}" + end.compact + failures.empty? ? nil : failures.join("\n") + rescue StandardError => e + "#{e.class}: #{e.message}" + end + + def dump(str) + str.codepoints.map { |cp| format("%04X", cp) }.join(" ") + end +end diff --git a/test/wpt/setters_tests_exclusions.json b/test/wpt/setters_tests_exclusions.json new file mode 100644 index 00000000..fe51488c --- /dev/null +++ b/test/wpt/setters_tests_exclusions.json @@ -0,0 +1 @@ +[] diff --git a/test/wpt/test_idna_test_v2.rb b/test/wpt/test_idna_test_v2.rb new file mode 100644 index 00000000..48d5bea5 --- /dev/null +++ b/test/wpt/test_idna_test_v2.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true +require 'test/unit' +require 'uri' +require_relative 'idna_test_v2' + +# Runs Unicode's IdnaTestV2.txt against URI::WHATWG_Parser::IDNA.to_ascii. +# +# The data is fetched for the Unicode version of the generated data +# (lib/uri/whatwg_parser/idna_data.rb), unless IDNA_TEST_V2 names a +# local file or another https URL. The cases that succeed with a code +# point that the running Ruby does not know are not run. +class IDNATestV2::TestConformance < Test::Unit::TestCase + SOURCE = IDNATestV2.source + CASES = IDNATestV2.load(SOURCE) + + CASES.each do |test_case| + next unless IDNATestV2.expectation(test_case) + data("line #{test_case[:line]} #{test_case[:source].dump}", test_case) + end + + def test_case(test_case) + message = IDNATestV2.run(test_case, URI::WHATWG_Parser::IDNA.method(:to_ascii)) + flunk(message) if message + end + + def test_source + assert_not_empty(CASES, "no cases in #{SOURCE}") + unknown = CASES.count { |c| IDNATestV2.unknown_to_ruby?(c) && IDNATestV2.expectation(c).nil? } + notify("IdnaTestV2: #{CASES.size} cases, #{unknown} not run for code points unknown to " \ + "Ruby #{RUBY_VERSION} (Unicode #{RbConfig::CONFIG["UNICODE_VERSION"]}) (source: #{SOURCE})") + end + + # Fails when Unicode has released a newer version than the generated + # data, so that the scheduled run reports it. + def test_idna_data_is_the_latest_unicode_version + current = IDNATestV2.unicode_version + latest = IDNATestV2.latest_unicode_version(WPT::URLTestData.fetch(IDNATestV2::LATEST_README)) + assert( + !IDNATestV2.newer?(latest, current), + "Unicode #{latest} is out; the IDNA data is #{current}. " \ + "Regenerate it with `UNICODE_VERSION=#{latest} rake idna:generate`." + ) + end +end diff --git a/test/wpt/test_idna_test_v2_harness.rb b/test/wpt/test_idna_test_v2_harness.rb new file mode 100644 index 00000000..8ed9d05e --- /dev/null +++ b/test/wpt/test_idna_test_v2_harness.rb @@ -0,0 +1,182 @@ +# frozen_string_literal: true +require 'test/unit' +require 'uri' +require_relative 'idna_test_v2' + +# Tests for the harness that runs Unicode's IdnaTestV2.txt. These never +# touch the network. +class IDNATestV2::TestHarness < Test::Unit::TestCase + def parse(text) + IDNATestV2.parse(text) + end + + def test_parse_skips_comments_and_blank_lines + cases = parse(<<~'TXT') + # comment + + fass.de; ; ; ; ; ; # fass.de + TXT + assert_equal(1, cases.size) + assert_equal("fass.de", cases[0][:source]) + assert_equal(3, cases[0][:line]) + end + + def test_parse_blank_columns_inherit + c = parse("Fa\\u00DF.de; fa\\u00DF.de; ; ; ; ; # x\n")[0] + # toAsciiN is the toUnicode value; its status is the toUnicode status. + assert_equal("fa\u00DF.de", c[:to_ascii]) + assert_equal([], c[:status]) + end + + def test_parse_blank_to_unicode_is_the_source + c = parse("fass.de; ; ; ; ; ;\n")[0] + assert_equal("fass.de", c[:to_ascii]) + end + + def test_parse_explicit_values + c = parse("fa\\u00DF.de; ; ; xn--fa-hia.de; ; fass.de; # x\n")[0] + assert_equal("xn--fa-hia.de", c[:to_ascii]) + assert_equal([], c[:status]) + end + + def test_parse_status_inherits_from_to_unicode + c = parse("a.-b.; ; [V3]; ; ; ;\n")[0] + assert_equal(%w[V3], c[:status]) + end + + def test_parse_status_of_to_ascii + c = parse("a.-b.; ; [V3]; ; [V3, A4_2]; ;\n")[0] + assert_equal(%w[V3 A4_2], c[:status]) + end + + def test_parse_explicit_empty_status + c = parse("a; ; [X4_2]; ; []; ;\n")[0] + assert_equal([], c[:status]) + end + + def test_parse_empty_string + c = parse("\"\"; ; [X4_2]; ; [A4_1, A4_2]; ; #\n")[0] + assert_equal("", c[:source]) + assert_equal("", c[:to_ascii]) + end + + def test_unescape + assert_equal("a\u0308b", IDNATestV2.unescape("a\\u0308b")) + assert_equal("\u{1F600}", IDNATestV2.unescape("\\x{1F600}")) + assert_equal("\u00E4", IDNATestV2.unescape("\u00E4")) + end + + def test_unescape_surrogate_is_nil + assert_nil(IDNATestV2.unescape("a\\uD800b")) + end + + def test_expectation_success + c = { source: "fa\u00DF.de", to_ascii: "xn--fa-hia.de", status: [] } + assert_equal({ value: "xn--fa-hia.de" }, IDNATestV2.expectation(c)) + end + + def test_expectation_failure + c = { source: "a\u05D0", to_ascii: "xn--a-0hc", status: %w[B5 B6] } + assert_equal({ failure: true }, IDNATestV2.expectation(c)) + end + + def test_expectation_ignores_statuses_of_disabled_checks + c = { source: "a.-b.", to_ascii: "a.-b.", status: %w[V2 V3 U1 A4_1 A4_2 X4_2] } + assert_equal({ value: "a.-b." }, IDNATestV2.expectation(c)) + end + + def test_expectation_is_nil_for_a_surrogate + assert_nil(IDNATestV2.expectation({ source: nil, to_ascii: nil, status: %w[A3] })) + end + + def test_expectation_is_nil_without_an_ascii_result + # Only ignored errors, but the file has no ToASCII value to compare. + c = { source: "\u00E4-.de", to_ascii: "\u00E4-.de", status: %w[V3] } + assert_nil(IDNATestV2.expectation(c)) + end + + # U+0378 is unassigned in every Unicode version so far. + def test_unknown_to_ruby_for_a_code_point_unassigned_in_ruby + assert_true(IDNATestV2.unknown_to_ruby?({ source: "a\u{378}", to_ascii: "xn--a-qib", status: [] })) + end + + def test_unknown_to_ruby_decodes_the_ascii_result + assert_true(IDNATestV2.unknown_to_ruby?({ source: "xn--a-qib", to_ascii: "xn--a-qib", status: [] })) + end + + def test_unknown_to_ruby_for_known_code_points + assert_false(IDNATestV2.unknown_to_ruby?({ source: "fa\u00DF.de", to_ascii: "xn--fa-hia.de", status: [] })) + assert_false(IDNATestV2.unknown_to_ruby?({ source: "xn--zz", to_ascii: "xn--zz", status: %w[P4] })) + assert_false(IDNATestV2.unknown_to_ruby?({ source: nil, to_ascii: nil, status: %w[A3] })) + end + + # A noncharacter is unassigned, but every Unicode version knows it. + def test_unknown_to_ruby_for_a_noncharacter + assert_false(IDNATestV2.unknown_to_ruby?({ source: "\u{FDD0}", to_ascii: "\u{FDD0}", status: %w[V7] })) + end + + # The Unicode data of IDNA is the running Ruby's, which does not know + # the code points added since its Unicode version. + def test_expectation_is_nil_for_a_success_with_a_code_point_unknown_to_ruby + assert_nil(IDNATestV2.expectation({ source: "a\u{378}", to_ascii: "xn--a-qib", status: [] })) + end + + def test_expectation_keeps_a_failure_with_a_code_point_unknown_to_ruby + c = { source: "a\u{378}", to_ascii: "xn--a-qib", status: %w[V7] } + assert_equal({ failure: true }, IDNATestV2.expectation(c)) + end + + def test_run_passes + c = { source: "fa\u00DF.de", to_ascii: "xn--fa-hia.de", status: [] } + assert_nil(IDNATestV2.run(c, ->(d) { "xn--fa-hia.de" })) + end + + def test_run_reports_a_wrong_value + c = { source: "fa\u00DF.de", to_ascii: "xn--fa-hia.de", status: [] } + assert_match(/expected "xn--fa-hia.de", got "fass.de"/, IDNATestV2.run(c, ->(d) { "fass.de" })) + end + + def test_run_reports_an_unexpected_failure + c = { source: "fa\u00DF.de", to_ascii: "xn--fa-hia.de", status: [] } + assert_match(/unexpected failure/, IDNATestV2.run(c, ->(d) { nil })) + end + + def test_run_reports_an_unexpected_success + c = { source: "a\u05D0", to_ascii: "xn--a-0hc", status: %w[B5] } + assert_match(/expected failure/, IDNATestV2.run(c, ->(d) { "xn--a-0hc" })) + end + + def test_run_reports_exceptions + c = { source: "a", to_ascii: "a", status: [] } + assert_match(/RuntimeError: boom/, IDNATestV2.run(c, ->(d) { raise "boom" })) + end + + def test_latest_unicode_version_from_readme + readme = <<~TXT + # Unicode Standard Data Files & Charts + + This directory contains final data files and charts for version 18.0.0 of the + Unicode Character Database and for the synchronized Unicode Technical Standards. + TXT + assert_equal("18.0.0", IDNATestV2.latest_unicode_version(readme)) + end + + def test_latest_unicode_version_without_a_version + assert_raise(RuntimeError) { IDNATestV2.latest_unicode_version("no version here") } + end + + def test_newer_unicode_version + assert_equal(true, IDNATestV2.newer?("18.1.0", "18.0.0")) + assert_equal(true, IDNATestV2.newer?("19.0.0", "18.0.0")) + assert_equal(true, IDNATestV2.newer?("18.0.10", "18.0.9")) + assert_equal(false, IDNATestV2.newer?("18.0.0", "18.0.0")) + assert_equal(false, IDNATestV2.newer?("17.0.0", "18.0.0")) + end + + def test_source_defaults_to_the_version_of_the_data + assert_equal( + "https://www.unicode.org/Public/#{IDNATestV2.unicode_version}/idna/IdnaTestV2.txt", + IDNATestV2.default_source + ) + end +end diff --git a/test/wpt/test_normalization_test.rb b/test/wpt/test_normalization_test.rb new file mode 100644 index 00000000..ea701f31 --- /dev/null +++ b/test/wpt/test_normalization_test.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true +require 'test/unit' +require 'uri' +require_relative 'normalization_test' + +# Runs Unicode's NormalizationTest.txt against +# URI::WHATWG_Parser::NFC.normalize and normalize_kc. +# +# The data is fetched for the Unicode version of the running Ruby, whose +# tables NFC uses, unless NORMALIZATION_TEST names a local file or +# another https URL. +class NormalizationTest::TestConformance < Test::Unit::TestCase + SOURCE = NormalizationTest.source + CASES = NormalizationTest.load(SOURCE) + NFC = URI::WHATWG_Parser::NFC.method(:normalize) + NFKC = URI::WHATWG_Parser::NFC.method(:normalize_kc) + + # One test per part: a test per line would make test-unit spend most + # of the time on its own bookkeeping. + CASES.group_by { |c| c[:part] }.each do |part, cases| + data(part, cases) + end + + def test_part(cases) + # Array#filter_map needs Ruby 2.7. + failures = cases.map do |test_case| + message = NormalizationTest.run(test_case, NFC, NFKC) + "line #{test_case[:line]}: #{message}" if message + end.compact + assert_empty(failures, "#{failures.size} of #{cases.size} cases failed") + end + + def test_code_points_outside_part1_are_unchanged + listed = NormalizationTest.part1_code_points(CASES).each_with_object({}) { |c, h| h[c] = true } + changed = (0..0x10FFFF).reject do |c| + (0xD800..0xDFFF).cover?(c) || listed[c] || (NFC.call(s = [c].pack("U")) == s && NFKC.call(s) == s) + end + assert_empty(changed.map { |c| format("U+%04X", c) }) + end + + def test_source + assert_not_empty(CASES, "no cases in #{SOURCE}") + notify("NormalizationTest: #{CASES.size} cases (source: #{SOURCE})") + end +end diff --git a/test/wpt/test_normalization_test_harness.rb b/test/wpt/test_normalization_test_harness.rb new file mode 100644 index 00000000..bf686ddc --- /dev/null +++ b/test/wpt/test_normalization_test_harness.rb @@ -0,0 +1,69 @@ +# frozen_string_literal: true +require 'test/unit' +require 'uri' +require_relative 'normalization_test' + +# Tests for the harness that runs Unicode's NormalizationTest.txt. These +# never touch the network. +class NormalizationTest::TestHarness < Test::Unit::TestCase + TEXT = <<~TXT + # comment + @Part0 # Specific cases + 1E0A;1E0A;0044 0307;1E0A;0044 0307; # comment + @Part1 # Character by character test + 00C5;00C5;0041 030A;00C5;0041 030A; + TXT + + def test_parse + cases = NormalizationTest.parse(TEXT) + assert_equal(2, cases.size) + assert_equal(["\u{1E0A}", "\u{1E0A}", "D\u{307}", "\u{1E0A}", "D\u{307}"], cases[0][:columns]) + assert_equal(3, cases[0][:line]) + assert_equal("Part0", cases[0][:part]) + assert_equal("Part1", cases[1][:part]) + end + + def test_part1_code_points + cases = NormalizationTest.parse(TEXT) + assert_equal([0xC5], NormalizationTest.part1_code_points(cases)) + end + + def test_run_passes + c = NormalizationTest.parse(TEXT)[0] + nfc = ->(s) { s == "D\u{307}" ? "\u{1E0A}" : s } + assert_nil(NormalizationTest.run(c, nfc)) + end + + def test_run_reports_c2_mismatch + c = NormalizationTest.parse(TEXT)[0] + message = NormalizationTest.run(c, ->(s) { s }) + assert_match(/NFC\(c3\)/, message) + assert_match(/expected c2/, message) + end + + def test_run_reports_c4_mismatch + c = { columns: ["a", "a", "a", "b", "c"], line: 1, part: "Part0" } + assert_match(/NFC\(c5\).*expected c4/, NormalizationTest.run(c, ->(s) { s })) + end + + def test_run_checks_nfkc_when_given + c = { columns: ["\u{FB03}", "\u{FB03}", "\u{FB03}", "ffi", "ffi"], line: 1, part: "Part1" } + nfc = ->(s) { s } + assert_nil(NormalizationTest.run(c, nfc)) + assert_match(/NFKC\(c1\) = FB03, expected c4 = 0066 0066 0069/, NormalizationTest.run(c, nfc, nfc)) + assert_nil(NormalizationTest.run(c, nfc, ->(s) { s == "ffi" ? s : "ffi" })) + end + + def test_run_reports_exceptions + c = NormalizationTest.parse(TEXT)[0] + assert_match(/RuntimeError: boom/, NormalizationTest.run(c, ->(s) { raise "boom" })) + end + + # The tables of NFC are those of the running Ruby. + def test_source_defaults_to_the_unicode_version_of_ruby + assert_equal( + "https://www.unicode.org/Public/#{RbConfig::CONFIG["UNICODE_VERSION"]}/ucd/NormalizationTest.txt", + NormalizationTest.default_source + ) + end +end diff --git a/test/wpt/test_wpt_harness.rb b/test/wpt/test_wpt_harness.rb new file mode 100644 index 00000000..fa0b15b0 --- /dev/null +++ b/test/wpt/test_wpt_harness.rb @@ -0,0 +1,501 @@ +# frozen_string_literal: true +require 'test/unit' +require 'json' +require 'tmpdir' +require 'uri' +require_relative 'wpt_url_test_data' + +# Tests for the harness that runs WPT url/resources/urltestdata.json. +# These never touch the network. +class WPT::TestHarness < Test::Unit::TestCase + # A parser stand-in that records how it was called and returns (or + # raises) whatever the given block produces. + class FakeParser + attr_reader :calls + + def initialize(&block) + @block = block + @calls = [] + end + + def parse(input) + @calls << [:parse, input] + @block.call(input, nil) + end + + def join(base, input) + @calls << [:join, base, input] + @block.call(input, base) + end + end + + def rfc3986(str) + URI::RFC3986_PARSER.parse(str) + end + + def passing_case(input, base, uri_str) + expected = WPT::URLTestData.components(rfc3986(uri_str)) + { "input" => input, "base" => base }.merge(expected) + end + + # --- components ---------------------------------------------------- + + def test_components_of_simple_http_url + assert_equal( + { + "href" => "http://example.com/a", + "protocol" => "http:", + "username" => "", + "password" => "", + "host" => "example.com", + "hostname" => "example.com", + "port" => "", + "pathname" => "/a", + "search" => "", + "hash" => "", + }, + WPT::URLTestData.components(rfc3986("http://example.com/a")) + ) + end + + def test_components_with_userinfo + c = WPT::URLTestData.components(rfc3986("http://user:pass@example.com/")) + assert_equal("user", c["username"]) + assert_equal("pass", c["password"]) + end + + def test_components_with_user_only + c = WPT::URLTestData.components(rfc3986("http://user@example.com/")) + assert_equal("user", c["username"]) + assert_equal("", c["password"]) + end + + def test_components_omit_default_port + c = WPT::URLTestData.components(rfc3986("http://example.com:80/")) + assert_equal("", c["port"]) + assert_equal("example.com", c["host"]) + end + + def test_components_keep_non_default_port + c = WPT::URLTestData.components(rfc3986("http://example.com:8080/")) + assert_equal("8080", c["port"]) + assert_equal("example.com:8080", c["host"]) + end + + def test_components_keep_port_zero + c = WPT::URLTestData.components(rfc3986("http://example.com:0/")) + assert_equal("0", c["port"]) + end + + def test_components_keep_port_for_scheme_without_default_port + c = WPT::URLTestData.components(rfc3986("foo://example.com:80/")) + assert_equal("80", c["port"]) + end + + def test_components_keep_ipv6_brackets_in_hostname + c = WPT::URLTestData.components(rfc3986("http://[::1]:8080/")) + assert_equal("[::1]", c["hostname"]) + assert_equal("[::1]:8080", c["host"]) + end + + def test_components_without_host + c = WPT::URLTestData.components(rfc3986("foo:/a")) + assert_equal("", c["host"]) + assert_equal("", c["hostname"]) + end + + def test_components_query_and_fragment + c = WPT::URLTestData.components(rfc3986("http://example.com/?q#f")) + assert_equal("?q", c["search"]) + assert_equal("#f", c["hash"]) + end + + def test_components_empty_query_and_fragment_are_empty_strings + # WHATWG's search/hash getters return "" for both null and "". + c = WPT::URLTestData.components(rfc3986("http://example.com/?#")) + assert_equal("", c["search"]) + assert_equal("", c["hash"]) + assert_equal("http://example.com/?#", c["href"]) + end + + def test_components_opaque_is_pathname + c = WPT::URLTestData.components(rfc3986("mailto:a@example.com")) + assert_equal("mailto:", c["protocol"]) + assert_equal("a@example.com", c["pathname"]) + end + + def opaque_uri(opaque, fragment = nil) + # URI::Generic keeps the query of an opaque URI inside opaque. + URI::Generic.new("foo", nil, nil, nil, nil, nil, opaque, nil, fragment) + end + + def test_components_query_inside_opaque_is_search + c = WPT::URLTestData.components(opaque_uri("bar?q", "f")) + assert_equal("bar", c["pathname"]) + assert_equal("?q", c["search"]) + assert_equal("#f", c["hash"]) + assert_equal("foo:bar?q#f", c["href"]) + end + + def test_components_empty_query_inside_opaque + c = WPT::URLTestData.components(opaque_uri("bar?")) + assert_equal("bar", c["pathname"]) + assert_equal("", c["search"]) + end + + def test_components_opaque_query_containing_question_mark + c = WPT::URLTestData.components(opaque_uri("bar?a?b")) + assert_equal("bar", c["pathname"]) + assert_equal("?a?b", c["search"]) + end + + def hostless_uri(path) + URI::Generic.new("foo", nil, nil, nil, nil, path, nil, nil, nil) + end + + def test_components_drops_dot_prefix_of_hostless_path + # The URL serializer writes "/." before a hostless path starting with + # "//"; pathname does not include it. + c = WPT::URLTestData.components(hostless_uri("/.//p")) + assert_equal("//p", c["pathname"]) + assert_equal("foo:/.//p", c["href"]) + end + + def test_components_keeps_other_dot_paths + assert_equal("/./p", WPT::URLTestData.components(hostless_uri("/./p"))["pathname"]) + assert_equal("/.", WPT::URLTestData.components(hostless_uri("/."))["pathname"]) + end + + def test_components_keeps_dot_prefix_when_host_is_present + uri = URI::Generic.new("foo", nil, "", nil, nil, "/.//p", nil, nil, nil) + assert_equal("/.//p", WPT::URLTestData.components(uri)["pathname"]) + end + + def test_components_empty_opaque + c = WPT::URLTestData.components(opaque_uri("")) + assert_equal("", c["pathname"]) + assert_equal("", c["search"]) + end + + # --- run ----------------------------------------------------------- + + def test_run_without_base_uses_parse + parser = FakeParser.new { rfc3986("http://example.com/") } + tc = passing_case("http://example.com/", nil, "http://example.com/") + + assert_nil(WPT::URLTestData.run(tc, parser)) + assert_equal([[:parse, "http://example.com/"]], parser.calls) + end + + def test_run_with_base_uses_join + parser = FakeParser.new { rfc3986("http://example.com/b") } + tc = passing_case("b", "http://example.com/a", "http://example.com/b") + + assert_nil(WPT::URLTestData.run(tc, parser)) + assert_equal([[:join, "http://example.com/a", "b"]], parser.calls) + end + + def test_run_reports_mismatched_components + parser = FakeParser.new { rfc3986("http://example.com/x") } + tc = passing_case("http://example.com/", nil, "http://example.com/") + + message = WPT::URLTestData.run(tc, parser) + assert_match(/pathname/, message) + assert_match(/href/, message) + assert_no_match(/hostname/, message) + end + + def test_run_ignores_keys_it_does_not_compare + parser = FakeParser.new { rfc3986("http://example.com/") } + tc = passing_case("http://example.com/", nil, "http://example.com/") + tc = tc.merge("origin" => "http://example.com", "searchParams" => "", "comment" => "c") + + assert_nil(WPT::URLTestData.run(tc, parser)) + end + + def test_run_expected_failure_raising_uri_error_passes + [URI::InvalidURIError, URI::InvalidComponentError].each do |error| + parser = FakeParser.new { raise error, "bad" } + tc = { "input" => "http://[/", "base" => nil, "failure" => true } + + assert_nil(WPT::URLTestData.run(tc, parser), error.name) + end + end + + def test_run_expected_failure_not_raising_is_reported + parser = FakeParser.new { rfc3986("http://example.com/") } + tc = { "input" => "http://[/", "base" => nil, "failure" => true } + + assert_match(/expected failure/, WPT::URLTestData.run(tc, parser)) + end + + def test_run_expected_failure_with_non_uri_error_is_reported + parser = FakeParser.new { raise NoMethodError, "oops" } + tc = { "input" => "http://[/", "base" => nil, "failure" => true } + + assert_match(/NoMethodError: oops/, WPT::URLTestData.run(tc, parser)) + end + + def test_run_unexpected_error_is_reported_not_raised + [URI::InvalidURIError, NoMethodError, ArgumentError].each do |error| + parser = FakeParser.new { raise error, "boom" } + tc = passing_case("http://example.com/", nil, "http://example.com/") + + assert_match(/#{error.name}: boom/, WPT::URLTestData.run(tc, parser), error.name) + end + end + + # --- load ---------------------------------------------------------- + + def with_json_file(content) + Dir.mktmpdir do |dir| + path = File.join(dir, "urltestdata.json") + File.write(path, content) + yield path + end + end + + def test_load_from_file_drops_comments + data = ["comment", { "input" => "a", "base" => nil, "failure" => true }, "another"] + with_json_file(JSON.generate(data)) do |path| + assert_equal([data[1]], WPT::URLTestData.load(path)) + end + end + + def test_load_from_empty_array + with_json_file("[]") do |path| + assert_equal([], WPT::URLTestData.load(path)) + end + end + + def test_load_rejects_non_array + with_json_file("{}") do |path| + assert_raise(ArgumentError) { WPT::URLTestData.load(path) } + end + end + + def test_load_rejects_invalid_json + with_json_file("[") do |path| + assert_raise(JSON::ParserError) { WPT::URLTestData.load(path) } + end + end + + def test_load_rejects_non_https_url + assert_raise(ArgumentError) { WPT::URLTestData.load("http://example.com/urltestdata.json") } + end + + def test_load_rejects_missing_file + assert_raise(Errno::ENOENT) { WPT::URLTestData.load("/nonexistent/urltestdata.json") } + end + + def test_default_source_is_wpt_master + assert_equal( + "https://raw.githubusercontent.com/web-platform-tests/wpt/master/url/resources/urltestdata.json", + WPT::URLTestData::DEFAULT_SOURCE + ) + end + + def test_source_defaults_to_wpt_master + env, ENV["WPT_URLTESTDATA"] = ENV["WPT_URLTESTDATA"], nil + assert_equal(WPT::URLTestData::DEFAULT_SOURCE, WPT::URLTestData.source) + ensure + ENV["WPT_URLTESTDATA"] = env + end + + def test_source_can_be_overridden_by_env + env, ENV["WPT_URLTESTDATA"] = ENV["WPT_URLTESTDATA"], "/tmp/local.json" + assert_equal("/tmp/local.json", WPT::URLTestData.source) + ensure + ENV["WPT_URLTESTDATA"] = env + end + + def test_exclusions_path_is_next_to_the_harness + assert_equal(File.expand_path("urltestdata_exclusions.json", __dir__), WPT::Exclusions::PATH) + end + + def test_key_identifies_case_by_input_and_base + assert_equal(["a", nil], WPT::URLTestData.key("input" => "a", "base" => nil, "href" => "x")) + assert_equal(["a", "b"], WPT::URLTestData.key("input" => "a", "base" => "b")) + end + + # --- exclusions ---------------------------------------------------- + + def test_exclusions_round_trip + entries = { ["a\t", nil] => "reason 1", ["b", "http://x/"] => "reason 2" } + Dir.mktmpdir do |dir| + path = File.join(dir, "exclusions.json") + WPT::Exclusions.save(path, entries) + assert_equal(entries, WPT::Exclusions.load(path)) + end + end + + def test_exclusions_save_writes_reviewable_json + Dir.mktmpdir do |dir| + path = File.join(dir, "exclusions.json") + WPT::Exclusions.save(path, { ["a", nil] => "r" }) + assert_equal( + [{ "input" => "a", "base" => nil, "reason" => "r" }], + JSON.parse(File.read(path)) + ) + assert_operator(File.read(path).lines.size, :>, 1, "pretty-printed") + assert(File.read(path).end_with?("\n")) + end + end + + def test_exclusions_load_empty_list + Dir.mktmpdir do |dir| + path = File.join(dir, "exclusions.json") + File.write(path, "[]") + assert_equal({}, WPT::Exclusions.load(path)) + end + end + + def test_exclusions_load_rejects_duplicates + Dir.mktmpdir do |dir| + path = File.join(dir, "exclusions.json") + entry = { "input" => "a", "base" => nil, "reason" => "r" } + File.write(path, JSON.generate([entry, entry])) + assert_raise(ArgumentError) { WPT::Exclusions.load(path) } + end + end + + def test_exclusions_load_rejects_missing_reason + Dir.mktmpdir do |dir| + path = File.join(dir, "exclusions.json") + [nil, ""].each do |reason| + File.write(path, JSON.generate([{ "input" => "a", "base" => nil, "reason" => reason }])) + assert_raise(ArgumentError, reason.inspect) { WPT::Exclusions.load(path) } + end + end + end + + def test_exclusions_stale_lists_entries_not_in_data + cases = [{ "input" => "a", "base" => nil }] + exclusions = { ["a", nil] => "r", ["a", "http://x/"] => "r", ["gone", nil] => "r" } + + assert_equal([["a", "http://x/"], ["gone", nil]], WPT::Exclusions.stale(exclusions, cases)) + end + + def test_exclusions_stale_is_empty_when_all_present + cases = [{ "input" => "a", "base" => nil }] + assert_equal([], WPT::Exclusions.stale({ ["a", nil] => "r" }, cases)) + assert_equal([], WPT::Exclusions.stale({}, cases)) + end + + def test_exclusions_update + cases = %w[pass keep new gone_from_list].map { |i| { "input" => i, "base" => nil } } + failing = [["keep", nil], ["new", nil]] + current = { ["keep", nil] => "known reason", ["pass", nil] => "fixed now", ["stale", nil] => "old" } + + updated = WPT::Exclusions.update(current, cases, failing) + + assert_equal( + { ["keep", nil] => "known reason", ["new", nil] => WPT::Exclusions::UNCLASSIFIED }, + updated + ) + end + + def test_exclusions_update_follows_data_order + cases = %w[c a b].map { |i| { "input" => i, "base" => nil } } + failing = [["a", nil], ["b", nil], ["c", nil]] + + assert_equal( + [["c", nil], ["a", nil], ["b", nil]], + WPT::Exclusions.update({}, cases, failing).keys + ) + end + + def test_exclusions_with_other_fields + fields = %w[setter href new_value] + entries = { ["port", "http://x/", "1"] => "r" } + Dir.mktmpdir do |dir| + path = File.join(dir, "exclusions.json") + WPT::Exclusions.save(path, entries, fields: fields) + assert_equal([{ "setter" => "port", "href" => "http://x/", "new_value" => "1", "reason" => "r" }], + JSON.parse(File.read(path))) + assert_equal(entries, WPT::Exclusions.load(path, fields: fields)) + end + end + + def test_exclusions_stale_and_update_with_another_key + key = ->(c) { [c["setter"], c["href"]] } + cases = [{ "setter" => "port", "href" => "a" }, { "setter" => "hash", "href" => "b" }] + assert_equal([["port", "gone"]], WPT::Exclusions.stale({ ["port", "gone"] => "r", ["port", "a"] => "r" }, cases, key: key)) + assert_equal({ ["hash", "b"] => WPT::Exclusions::UNCLASSIFIED }, + WPT::Exclusions.update({}, cases, [["hash", "b"]], key: key)) + end + # --- run_route ----------------------------------------------------- + + # URIs of a parser stand-in for routes: the route from a base to a + # target is what +route+ returns, and a base plus a route resolves to + # what +resolve+ returns. + class FakeRouteParser + FakeURI = Struct.new(:str, :parser) do + def to_s + str + end + + def route_to(target) + parser.route.call(str, target.to_s) + end + + def +(route) + FakeURI.new(parser.resolve.call(str, route), parser) + end + end + + attr_reader :route, :resolve + + def initialize(route:, resolve:, bad: []) + @route = route + @resolve = resolve + @bad = bad + end + + def parse(input) + raise URI::InvalidURIError, "fake failure" if @bad.include?(input) + FakeURI.new(input, self) + end + + def join(base, input) + raise URI::InvalidURIError, "fake failure" if @bad.include?(input) + FakeURI.new("#{base}|#{input}", self) + end + end + + def route_parser(**options) + FakeRouteParser.new(**{ route: ->(_base, target) { target }, resolve: ->(_base, route) { route } }.merge(options)) + end + + def test_run_route_passes_when_the_route_resolves_to_the_target + assert_nil(WPT::URLTestData.run_route({ "input" => "x", "base" => "b" }, route_parser)) + end + + def test_run_route_reports_a_route_resolving_elsewhere + parser = route_parser(route: ->(_base, _target) { "r" }, resolve: ->(_base, _route) { "elsewhere" }) + message = WPT::URLTestData.run_route({ "input" => "x", "base" => "b" }, parser) + assert_equal('route: "r" from "b" resolves to "elsewhere", expected "b|x"', message) + end + + def test_run_route_skips_cases_without_a_base + parser = route_parser(resolve: ->(_base, _route) { raise "not run" }) + assert_nil(WPT::URLTestData.run_route({ "input" => "x", "base" => nil }, parser)) + end + + def test_run_route_skips_expected_failures + parser = route_parser(resolve: ->(_base, _route) { raise "not run" }) + assert_nil(WPT::URLTestData.run_route({ "input" => "x", "base" => "b", "failure" => true }, parser)) + end + + def test_run_route_skips_a_base_or_an_input_that_fails + parser = route_parser(resolve: ->(_base, _route) { raise "not run" }, bad: ["b", "x"]) + assert_nil(WPT::URLTestData.run_route({ "input" => "y", "base" => "b" }, parser)) + assert_nil(WPT::URLTestData.run_route({ "input" => "x", "base" => "c" }, parser)) + end + + def test_run_route_reports_exceptions + parser = route_parser(route: ->(_base, _target) { raise URI::BadURIError, "boom" }) + message = WPT::URLTestData.run_route({ "input" => "x", "base" => "b" }, parser) + assert_equal('route: unexpected URI::BadURIError: boom', message) + end +end diff --git a/test/wpt/test_wpt_setters.rb b/test/wpt/test_wpt_setters.rb new file mode 100644 index 00000000..e2c41805 --- /dev/null +++ b/test/wpt/test_wpt_setters.rb @@ -0,0 +1,58 @@ +# frozen_string_literal: true +require 'test/unit' +require 'uri' +require_relative 'wpt_setters_test_data' + +# Runs WPT url/resources/setters_tests.json against the setters of URIs +# built by URI::WHATWG_PARSER. +# +# The data is fetched from WPT master on every run, unless WPT_SETTERS +# names a local file or another https URL. The cases of setters that URI +# has no counterpart for (WPT::SettersTestData::UNSUPPORTED) are not +# run. Cases listed in setters_tests_exclusions.json are known to fail; +# as for urltestdata.json, the test fails if one of them passes or no +# longer exists. Regenerate the list with +# `rake test:wpt:update_exclusions`. +class WPT::TestSetters < Test::Unit::TestCase + Setters = WPT::SettersTestData + + SOURCE = Setters.source + CASES = Setters.load(SOURCE) + EXCLUSIONS = WPT::Exclusions.load(Setters::EXCLUSIONS_PATH, fields: Setters::EXCLUSION_FIELDS) + KEY = Setters.method(:key) + + CASES.each_with_index do |test_case, index| + next unless Setters.supported?(test_case) + next if EXCLUSIONS.key?(Setters.key(test_case)) + label = "##{index + 1} #{test_case["setter"]} #{test_case["href"].inspect} = #{test_case["new_value"].inspect}" + data(label, test_case) + end + + def test_case(test_case) + message = Setters.run(test_case, URI::WHATWG_PARSER) + flunk(message) if message + end + + def test_excluded_cases_still_fail + passing = CASES.select do |test_case| + EXCLUSIONS.key?(Setters.key(test_case)) && Setters.run(test_case, URI::WHATWG_PARSER).nil? + end + + assert_empty( + passing.map { |c| Setters.key(c) }, + "these excluded cases pass now; remove them from #{Setters::EXCLUSIONS_PATH} " \ + "(rake test:wpt:update_exclusions)" + ) + unsupported = CASES.count { |c| !Setters.supported?(c) } + notify("setters_tests: #{CASES.size} cases, #{unsupported} of unsupported setters, " \ + "#{EXCLUSIONS.size} excluded (source: #{SOURCE})") + end + + def test_no_stale_exclusions + assert_empty( + WPT::Exclusions.stale(EXCLUSIONS, CASES, key: KEY), + "these exclusions match no case in #{SOURCE}; " \ + "remove them from #{Setters::EXCLUSIONS_PATH} (rake test:wpt:update_exclusions)" + ) + end +end diff --git a/test/wpt/test_wpt_setters_harness.rb b/test/wpt/test_wpt_setters_harness.rb new file mode 100644 index 00000000..e8fa1d61 --- /dev/null +++ b/test/wpt/test_wpt_setters_harness.rb @@ -0,0 +1,103 @@ +# frozen_string_literal: true +require 'test/unit' +require 'uri' +require_relative 'wpt_setters_test_data' + +# Tests for the harness that runs WPT url/resources/setters_tests.json. +# These never touch the network. +class WPT::TestSettersHarness < Test::Unit::TestCase + Setters = WPT::SettersTestData + + def setter_case(setter, href, new_value, expected) + { "setter" => setter, "href" => href, "new_value" => new_value, "expected" => expected } + end + + def test_flatten + data = { + "comment" => ["a", "b"], + "port" => [{ "href" => "http://x/", "new_value" => "1", "expected" => { "port" => "1" } }], + "hash" => [{ "comment" => "c", "href" => "http://x/", "new_value" => "", "expected" => {} }], + } + cases = Setters.flatten(data) + assert_equal(%w[port hash], cases.map { |c| c["setter"] }) + assert_equal("http://x/", cases[0]["href"]) + assert_equal("c", cases[1]["comment"]) + end + + def test_key + assert_equal(["port", "http://x/", "1"], Setters.key(setter_case("port", "http://x/", "1", {}))) + end + + def test_supported + %w[protocol username password hostname port pathname search hash].each do |setter| + assert_true(Setters.supported?(setter_case(setter, "http://x/", "", {})), setter) + end + assert_false(Setters.supported?(setter_case("host", "http://x/", "", {}))) + assert_false(Setters.supported?(setter_case("href", "http://x/", "", {}))) + end + + def apply(setter, href, value) + uri = URI::WHATWG_PARSER.parse(href) + Setters.apply(uri, setter, value) + uri.to_s + end + + def test_apply_maps_the_setters + assert_equal("https://x/", apply("protocol", "http://x/", "https")) + assert_equal("http://u@x/", apply("username", "http://x/", "u")) + assert_equal("http://:p@x/", apply("password", "http://x/", "p")) + assert_equal("http://y/", apply("hostname", "http://x/", "y")) + assert_equal("http://x:1/", apply("port", "http://x/", "1")) + assert_equal("http://x/p", apply("pathname", "http://x/", "p")) + end + + def test_apply_search + assert_equal("http://x/?a", apply("search", "http://x/", "?a")) + assert_equal("http://x/?a", apply("search", "http://x/", "a")) + assert_equal("http://x/??a", apply("search", "http://x/", "??a")) + assert_equal("http://x/?", apply("search", "http://x/?q", "?")) + assert_equal("http://x/", apply("search", "http://x/?q", "")) + end + + def test_apply_hash + assert_equal("http://x/#a", apply("hash", "http://x/", "#a")) + assert_equal("http://x/#a", apply("hash", "http://x/", "a")) + assert_equal("http://x/##a", apply("hash", "http://x/", "##a")) + assert_equal("http://x/#", apply("hash", "http://x/#f", "#")) + assert_equal("http://x/", apply("hash", "http://x/#f", "")) + end + + def test_apply_unsupported + assert_raise(ArgumentError) { apply("host", "http://x/", "y") } + end + + def test_run_passes + c = setter_case("port", "http://x/", "8080", { "href" => "http://x:8080/", "port" => "8080" }) + assert_nil(Setters.run(c, URI::WHATWG_PARSER)) + end + + def test_run_reports_differences + c = setter_case("port", "http://x/", "8080", { "href" => "http://x:9090/", "port" => "9090" }) + message = Setters.run(c, URI::WHATWG_PARSER) + assert_match(/href: expected "http:\/\/x:9090\/", got "http:\/\/x:8080\/"/, message) + assert_match(/port: expected "9090", got "8080"/, message) + end + + def test_run_treats_a_rejected_value_as_unchanged + c = setter_case("port", "http://x/", "abc", { "href" => "http://x/", "port" => "" }) + assert_nil(Setters.run(c, URI::WHATWG_PARSER)) + end + + def test_run_reports_other_exceptions + parser = Object.new + def parser.parse(_) + raise ArgumentError, "boom" + end + c = setter_case("port", "http://x/", "1", {}) + assert_match(/ArgumentError: boom/, Setters.run(c, parser)) + end + + def test_exclusions_path + assert_equal(File.expand_path("setters_tests_exclusions.json", __dir__), Setters::EXCLUSIONS_PATH) + end +end diff --git a/test/wpt/test_wpt_toascii.rb b/test/wpt/test_wpt_toascii.rb new file mode 100644 index 00000000..90306231 --- /dev/null +++ b/test/wpt/test_wpt_toascii.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true +require 'test/unit' +require 'uri' +require_relative 'wpt_url_test_data' + +# Runs WPT url/resources/toascii.json against URI::WHATWG_PARSER and the +# host= of the URIs it builds. +# +# The data is fetched from WPT master on every run, unless WPT_TOASCII +# names a local file or another https URL. +class WPT::TestToASCII < Test::Unit::TestCase + SOURCE = WPT::ToASCIIData.source + CASES = WPT::URLTestData.load(SOURCE) + + CASES.each_with_index do |test_case, index| + data("##{index + 1} #{test_case["input"].dump}", test_case) + end + + def test_case(test_case) + message = WPT::ToASCIIData.run(test_case, URI::WHATWG_PARSER) + flunk(message) if message + end + + CASES.each_with_index do |test_case, index| + data("##{index + 1} #{test_case["input"].dump}", test_case) + end + + def test_setter(test_case) + message = WPT::ToASCIIData.run_setter(test_case, URI::WHATWG_PARSER) + flunk(message) if message + end + + def test_source + assert_not_empty(CASES, "no cases in #{SOURCE}") + notify("toascii: #{CASES.size} cases (source: #{SOURCE})") + end +end diff --git a/test/wpt/test_wpt_toascii_harness.rb b/test/wpt/test_wpt_toascii_harness.rb new file mode 100644 index 00000000..c2bccab2 --- /dev/null +++ b/test/wpt/test_wpt_toascii_harness.rb @@ -0,0 +1,143 @@ +# frozen_string_literal: true +require 'test/unit' +require 'uri' +require_relative 'wpt_url_test_data' + +# Tests for the harness that runs WPT url/resources/toascii.json. These +# never touch the network. +class WPT::TestToASCIIHarness < Test::Unit::TestCase + ToASCII = WPT::ToASCIIData + + # A parser stand-in that parses with RFC3986_PARSER after replacing the + # host as the block says, or raises when the block returns nil. + class FakeParser + attr_reader :inputs + + def initialize(&block) + @block = block + @inputs = [] + end + + def parse(input) + @inputs << input + host = @block.call(input[%r{\Ahttps://(.*)/x\z}m, 1]) + raise URI::InvalidURIError, "fake failure" unless host + URI::RFC3986_PARSER.parse("https://#{host}/x") + end + end + + def test_run_parses_the_input_as_the_host_of_an_https_url + parser = FakeParser.new { |host| host } + ToASCII.run({ "input" => "example.com", "output" => "example.com" }, parser) + assert_equal(["https://example.com/x"], parser.inputs) + end + + def test_run_passes + parser = FakeParser.new { "xn--fa-hia.de" } + assert_nil(ToASCII.run({ "input" => "fa\u{DF}.de", "output" => "xn--fa-hia.de" }, parser)) + end + + def test_run_reports_a_wrong_host + parser = FakeParser.new { "fass.de" } + message = ToASCII.run({ "input" => "fa\u{DF}.de", "output" => "xn--fa-hia.de" }, parser) + assert_match(/host: expected "xn--fa-hia.de", got "fass.de"/, message) + assert_match(%r{href: expected "https://xn--fa-hia.de/x", got "https://fass.de/x"}, message) + end + + def test_run_reports_an_unexpected_failure + parser = FakeParser.new { nil } + message = ToASCII.run({ "input" => "a", "output" => "a" }, parser) + assert_match(/unexpected URI::InvalidURIError/, message) + end + + def test_run_passes_an_expected_failure + parser = FakeParser.new { nil } + assert_nil(ToASCII.run({ "input" => "a\u{200C}b", "output" => nil }, parser)) + end + + def test_run_reports_an_unexpected_success + parser = FakeParser.new { |host| host } + message = ToASCII.run({ "input" => "a", "output" => nil }, parser) + assert_match(%r{expected failure, but parsed as "https://a/x"}, message) + end + + def test_run_reports_other_exceptions + parser = Object.new + def parser.parse(_) + raise ArgumentError, "boom" + end + assert_match(/ArgumentError: boom/, ToASCII.run({ "input" => "a", "output" => "a" }, parser)) + end + + # A parser stand-in whose URIs set the host as the block says, or + # raise InvalidComponentError when the block returns nil. + class FakeSetterParser + FakeURI = Struct.new(:host, :setter) do + def host=(value) + host = setter.call(value) + raise URI::InvalidComponentError, "fake rejection" unless host + self[:host] = host + end + end + + attr_reader :inputs + + def initialize(&block) + @block = block + @inputs = [] + end + + def parse(input) + @inputs << input + FakeURI.new(input[%r{\Ahttps://(.*)/x\z}, 1], @block) + end + end + + def test_run_setter_sets_the_input_as_the_host_of_an_https_url + values = [] + parser = FakeSetterParser.new { |value| values << value; value } + ToASCII.run_setter({ "input" => "example.com", "output" => "example.com" }, parser) + assert_equal(["https://x/x"], parser.inputs) + assert_equal(["example.com"], values) + end + + def test_run_setter_passes + parser = FakeSetterParser.new { "xn--fa-hia.de" } + assert_nil(ToASCII.run_setter({ "input" => "fa\u{DF}.de", "output" => "xn--fa-hia.de" }, parser)) + end + + def test_run_setter_reports_a_wrong_host + parser = FakeSetterParser.new { "fass.de" } + message = ToASCII.run_setter({ "input" => "fa\u{DF}.de", "output" => "xn--fa-hia.de" }, parser) + assert_equal('hostname setter: expected "xn--fa-hia.de", got "fass.de"', message) + end + + def test_run_setter_reports_an_unexpected_rejection + parser = FakeSetterParser.new { nil } + message = ToASCII.run_setter({ "input" => "a", "output" => "a" }, parser) + assert_equal('hostname setter: expected "a", got "x"', message) + end + + # The setter ignores a host that fails to parse, so the host stays "x". + def test_run_setter_passes_an_expected_failure + parser = FakeSetterParser.new { nil } + assert_nil(ToASCII.run_setter({ "input" => "a\u{200C}b", "output" => nil }, parser)) + end + + def test_run_setter_reports_an_unexpected_success + parser = FakeSetterParser.new { |value| value } + message = ToASCII.run_setter({ "input" => "a", "output" => nil }, parser) + assert_equal('hostname setter: expected "x", got "a"', message) + end + + def test_run_setter_reports_other_exceptions + parser = FakeSetterParser.new { raise ArgumentError, "boom" } + message = ToASCII.run_setter({ "input" => "a", "output" => "a" }, parser) + assert_equal("hostname setter: unexpected ArgumentError: boom", message) + end + + def test_source + assert_equal(ToASCII::DEFAULT_SOURCE, ToASCII.source) unless ENV["WPT_TOASCII"] + assert_match(%r{\Ahttps://.*/url/resources/toascii\.json\z}, ToASCII::DEFAULT_SOURCE) + end +end diff --git a/test/wpt/test_wpt_urltestdata.rb b/test/wpt/test_wpt_urltestdata.rb new file mode 100644 index 00000000..c18f2f6a --- /dev/null +++ b/test/wpt/test_wpt_urltestdata.rb @@ -0,0 +1,68 @@ +# frozen_string_literal: true +require 'test/unit' +require 'uri' +require_relative 'wpt_url_test_data' + +# Runs WPT url/resources/urltestdata.json against URI::WHATWG_PARSER. +# +# The data is fetched from WPT master on every run, unless +# WPT_URLTESTDATA names a local file or another https URL. +# +# Cases listed in urltestdata_exclusions.json are known to fail. They are +# not run as individual tests; instead test_excluded_cases_still_fail +# fails if any of them passes, so the list never claims more than is +# true. Regenerate the list with `rake test:wpt:update_exclusions`. +class WPT::TestURLTestData < Test::Unit::TestCase + SOURCE = WPT::URLTestData.source + EXCLUSIONS_PATH = WPT::Exclusions::PATH + CASES = WPT::URLTestData.load(SOURCE) + EXCLUSIONS = WPT::Exclusions.load(EXCLUSIONS_PATH) + + def self.label(index, test_case) + "##{index + 1} #{test_case["input"].inspect} base=#{test_case["base"].inspect}" + end + + CASES.each_with_index do |test_case, index| + next if EXCLUSIONS.key?(WPT::URLTestData.key(test_case)) + data(label(index, test_case), test_case) + end + + def test_case(test_case) + message = WPT::URLTestData.run(test_case, URI::WHATWG_PARSER) + flunk(message) if message + end + + CASES.each_with_index do |test_case, index| + next unless test_case["base"] && !test_case["failure"] + data(label(index, test_case), test_case) + end + + # The route from the base of each case to the URL it parses to resolves + # back to that URL. + def test_route(test_case) + message = WPT::URLTestData.run_route(test_case, URI::WHATWG_PARSER) + flunk(message) if message + end + + def test_excluded_cases_still_fail + passing = CASES.select do |test_case| + EXCLUSIONS.key?(WPT::URLTestData.key(test_case)) && + WPT::URLTestData.run(test_case, URI::WHATWG_PARSER).nil? + end + + assert_empty( + passing.map { |c| WPT::URLTestData.key(c) }, + "these excluded cases pass now; remove them from #{EXCLUSIONS_PATH} " \ + "(rake test:wpt:update_exclusions)" + ) + notify("urltestdata: #{CASES.size} cases, #{EXCLUSIONS.size} excluded (source: #{SOURCE})") + end + + def test_no_stale_exclusions + assert_empty( + WPT::Exclusions.stale(EXCLUSIONS, CASES), + "these exclusions match no case in #{SOURCE}; " \ + "remove them from #{EXCLUSIONS_PATH} (rake test:wpt:update_exclusions)" + ) + end +end diff --git a/test/wpt/update_exclusions.rb b/test/wpt/update_exclusions.rb new file mode 100644 index 00000000..e605265c --- /dev/null +++ b/test/wpt/update_exclusions.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true +# Regenerates urltestdata_exclusions.json and setters_tests_exclusions.json +# from the cases that currently fail with URI::WHATWG_PARSER. Known +# reasons are kept, new failures are marked "unclassified", and cases +# that pass now or no longer exist in the data are dropped. +# +# Usage: ruby -Ilib test/wpt/update_exclusions.rb +# (or rake test:wpt:update_exclusions) +require 'uri' +require_relative 'wpt_url_test_data' +require_relative 'wpt_setters_test_data' + +def update_exclusions(source:, path:, cases:, key:, fields:) + current = File.exist?(path) ? WPT::Exclusions.load(path, fields: fields) : {} + failing = cases.reject { |c| yield(c).nil? }.map(&key) + updated = WPT::Exclusions.update(current, cases, failing, key: key) + WPT::Exclusions.save(path, updated, fields: fields) + + added = (updated.keys - current.keys).size + removed = (current.keys - updated.keys).size + puts "#{source}: #{cases.size} cases, #{cases.size - updated.size} passing, #{updated.size} excluded (+#{added}, -#{removed})" +end + +source = WPT::URLTestData.source +update_exclusions( + source: source, path: WPT::Exclusions::PATH, cases: WPT::URLTestData.load(source), + key: WPT::URLTestData.method(:key), fields: WPT::Exclusions::FIELDS +) { |c| WPT::URLTestData.run(c, URI::WHATWG_PARSER) } + +setters = WPT::SettersTestData +source = setters.source +update_exclusions( + source: source, path: setters::EXCLUSIONS_PATH, cases: setters.load(source).select { |c| setters.supported?(c) }, + key: setters.method(:key), fields: setters::EXCLUSION_FIELDS +) { |c| setters.run(c, URI::WHATWG_PARSER) } diff --git a/test/wpt/urltestdata_exclusions.json b/test/wpt/urltestdata_exclusions.json new file mode 100644 index 00000000..fe51488c --- /dev/null +++ b/test/wpt/urltestdata_exclusions.json @@ -0,0 +1 @@ +[] diff --git a/test/wpt/wpt_setters_test_data.rb b/test/wpt/wpt_setters_test_data.rb new file mode 100644 index 00000000..888f4994 --- /dev/null +++ b/test/wpt/wpt_setters_test_data.rb @@ -0,0 +1,92 @@ +# frozen_string_literal: true +require 'json' +require 'uri' +require_relative 'wpt_url_test_data' + +module WPT + # Harness for url/resources/setters_tests.json, which sets one + # attribute of the URL API on a parsed URL and lists the attributes + # expected afterwards. + # + # The setters map to those of URI: protocol to scheme=, username to + # user=, password to password=, hostname to host=, port to port=, + # pathname to path=, search to query= and hash to fragment=. query= and + # fragment= take the value without the leading "?" or "#" that search + # and hash strip, and nil for the empty string that removes the + # component. A value that URI rejects with InvalidComponentError is + # one that the URL Standard ignores, so the attributes are compared + # as they are after it. + module SettersTestData + DEFAULT_SOURCE = "https://raw.githubusercontent.com/web-platform-tests/wpt/master/url/resources/setters_tests.json" + EXCLUSIONS_PATH = File.expand_path("setters_tests_exclusions.json", __dir__) + EXCLUSION_FIELDS = %w[setter href new_value].freeze + + # Setters of the URL API that URI has no counterpart for. + UNSUPPORTED = { + "host" => "URI has no setter for a host and a port together", + "href" => "URI has no setter for the whole URL", + }.freeze + + module_function + + # WPT_SETTERS (a local path or an https URL) if set, otherwise WPT + # master. + def source + ENV["WPT_SETTERS"] || DEFAULT_SOURCE + end + + def load(source) + json = source.match?(%r{\A[A-Za-z][A-Za-z0-9+.-]*://}) ? URLTestData.fetch(source) : File.read(source) + flatten(JSON.parse(json)) + end + + # The cases of every setter, each with its "setter". + def flatten(data) + data.flat_map do |setter, cases| + next [] if setter == "comment" + cases.map { |c| c.merge("setter" => setter) } + end + end + + def key(test_case) + test_case.values_at(*EXCLUSION_FIELDS) + end + + def supported?(test_case) + !UNSUPPORTED.key?(test_case["setter"]) + end + + def apply(uri, setter, value) + case setter + when "protocol" then uri.scheme = value + when "username" then uri.user = value + when "password" then uri.password = value + when "hostname" then uri.host = value + when "port" then uri.port = value + when "pathname" then uri.path = value + when "search" then uri.query = value.empty? ? nil : value.sub(/\A\?/, "") + when "hash" then uri.fragment = value.empty? ? nil : value.sub(/\A#/, "") + else raise ArgumentError, "unsupported setter: #{setter}" + end + end + + # Runs +test_case+ with +parser+. Returns nil when it passes, or a + # message. + def run(test_case, parser) + uri = parser.parse(test_case["href"]) + begin + apply(uri, test_case["setter"], test_case["new_value"]) + rescue URI::InvalidComponentError + # The URL Standard leaves the URL unchanged. + end + + actual = URLTestData.components(uri) + expected = test_case["expected"] + diffs = expected.keys.select { |k| actual.key?(k) && expected[k] != actual[k] } + return nil if diffs.empty? + diffs.map { |k| "#{k}: expected #{expected[k].inspect}, got #{actual[k].inspect}" }.join("\n") + rescue StandardError => e + "#{e.class}: #{e.message}" + end + end +end diff --git a/test/wpt/wpt_url_test_data.rb b/test/wpt/wpt_url_test_data.rb new file mode 100644 index 00000000..bf2a0ba6 --- /dev/null +++ b/test/wpt/wpt_url_test_data.rb @@ -0,0 +1,221 @@ +# frozen_string_literal: true +require 'json' +require 'uri' + +# Harness for running web-platform-tests' url/resources/urltestdata.json +# (https://github.com/web-platform-tests/wpt) against a URI parser. +module WPT + module URLTestData + DEFAULT_SOURCE = "https://raw.githubusercontent.com/web-platform-tests/wpt/master/url/resources/urltestdata.json" + + # URL attributes compared against the expectations. "origin" and + # "searchParams" are not compared: URI has no equivalent of either. + COMPARED_KEYS = %w[href protocol username password host hostname port pathname search hash].freeze + + module_function + + # The data source: WPT_URLTESTDATA (a local path or an https URL) if + # set, otherwise WPT master. + def source + ENV["WPT_URLTESTDATA"] || DEFAULT_SOURCE + end + + # Loads the test cases from +source+, a local path or an https URL, + # dropping the comment strings interleaved in the data. + def load(source = DEFAULT_SOURCE) + json = source.match?(%r{\A[A-Za-z][A-Za-z0-9+.-]*://}) ? fetch(source) : File.read(source) + data = JSON.parse(json) + raise ArgumentError, "urltestdata must be a JSON array: #{source}" unless data.is_a?(Array) + data.grep(Hash) + end + + def fetch(url) + uri = URI::RFC3986_PARSER.parse(url) + raise ArgumentError, "urltestdata must be fetched over https: #{url}" unless uri.is_a?(URI::HTTPS) + + require 'net/http' + response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30) do |http| + http.get(uri.request_uri) + end + raise "failed to fetch #{url}: HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess) + response.body + end + + # A test case is identified by its input and base; the pair is unique + # in urltestdata.json. + def key(test_case) + [test_case["input"], test_case["base"]] + end + + # The URL attributes (as the WHATWG URL API exposes them) of +uri+. + # + # URI::Generic keeps the query of an opaque URI inside opaque, after + # the first "?" (an opaque path cannot contain "?"). + def components(uri) + port = uri.port && uri.port != uri.default_port ? uri.port.to_s : "" + hostname = uri.host.to_s + if uri.opaque + pathname, question, query = uri.opaque.partition("?") + query = nil if question.empty? + else + pathname = uri.path.to_s + # The "/." the URL serializer writes before a hostless path that + # starts with "//" is not part of pathname. + pathname = pathname[2..-1] if uri.host.nil? && pathname.start_with?("/.//") + query = uri.query + end + { + "href" => uri.to_s, + "protocol" => "#{uri.scheme}:", + "username" => uri.user.to_s, + "password" => uri.password.to_s, + "host" => port.empty? ? hostname : "#{hostname}:#{port}", + "hostname" => hostname, + "port" => port, + "pathname" => pathname, + "search" => query.to_s.empty? ? "" : "?#{query}", + "hash" => uri.fragment.to_s.empty? ? "" : "##{uri.fragment}", + } + end + + # Runs +test_case+ with +parser+. Returns nil when it passes, or a + # message describing how it failed. Exceptions are reported in the + # message rather than raised, so one case cannot abort the others. + def run(test_case, parser) + input = test_case["input"] + base = test_case["base"] + begin + uri = base ? parser.join(base, input) : parser.parse(input) + rescue URI::Error => e + return nil if test_case["failure"] + return "unexpected #{e.class}: #{e.message}" + rescue StandardError => e + return "#{e.class}: #{e.message}" + end + + return "expected failure, but parsed as #{uri.to_s.inspect}" if test_case["failure"] + + actual = components(uri) + diffs = COMPARED_KEYS.select { |k| test_case.key?(k) && test_case[k] != actual[k] } + return nil if diffs.empty? + + diffs.map { |k| "#{k}: expected #{test_case[k].inspect}, got #{actual[k].inspect}" }.join("\n") + end + + # Checks the route from the base of +test_case+ to the URL it parses + # to: the route must resolve back to that URL. Returns nil when it + # does, or when the case has no base or fails to parse, which #run + # checks; otherwise a message. + def run_route(test_case, parser) + base = test_case["base"] + return nil if base.nil? || test_case["failure"] + + begin + base_uri = parser.parse(base) + target = parser.join(base, test_case["input"]) + rescue URI::Error + return nil + end + route = base_uri.route_to(target) + resolved = base_uri + route + return nil if resolved.to_s == target.to_s + "route: #{route.to_s.inspect} from #{base.inspect} resolves to #{resolved.to_s.inspect}, expected #{target.to_s.inspect}" + rescue StandardError => e + "route: unexpected #{e.class}: #{e.message}" + end + end + + # Harness for url/resources/toascii.json: each case is a host "input" + # and its expected ASCII "output", or null when parsing fails. As in + # WPT's toascii.window.js, the input is parsed as the host of + # "https:///x" (run), and set with the hostname setter, which + # is URI's host=, on "https://x/x" (run_setter). The host setter check + # of that file is not run, as URI has no setter that takes a port; + # without a port in any input, it would give the same result. + module ToASCIIData + DEFAULT_SOURCE = "https://raw.githubusercontent.com/web-platform-tests/wpt/master/url/resources/toascii.json" + + module_function + + # WPT_TOASCII (a local path or an https URL) if set, otherwise WPT + # master. + def source + ENV["WPT_TOASCII"] || DEFAULT_SOURCE + end + + # Runs +test_case+ with +parser+. Returns nil when it passes, or a + # message. + def run(test_case, parser) + output = test_case["output"] + url_test_case = { "input" => "https://#{test_case["input"]}/x", "base" => nil } + if output.nil? + url_test_case["failure"] = true + else + url_test_case.merge!("host" => output, "hostname" => output, "pathname" => "/x", "href" => "https://#{output}/x") + end + URLTestData.run(url_test_case, parser) + end + + # Runs the hostname setter check of +test_case+ with +parser+. A host + # that fails to parse is ignored, which keeps the host "x". Returns + # nil when it passes, or a message. + def run_setter(test_case, parser) + uri = parser.parse("https://x/x") + begin + uri.host = test_case["input"] + rescue URI::InvalidComponentError + # The setter ignores the value. + end + expected = test_case["output"] || "x" + return nil if uri.host == expected + "hostname setter: expected #{expected.inspect}, got #{uri.host.inspect}" + rescue StandardError => e + "hostname setter: unexpected #{e.class}: #{e.message}" + end + end + + # The list of urltestdata cases that are known to fail, each with the + # reason, stored as a JSON array of {"input", "base", "reason"}. + module Exclusions + UNCLASSIFIED = "unclassified" + PATH = File.expand_path("urltestdata_exclusions.json", __dir__) + # The fields of an entry that identify a case of urltestdata.json. + FIELDS = %w[input base].freeze + + module_function + + # Returns a Hash of key => reason, where the key is the values of + # +fields+ in each entry. + def load(path, fields: FIELDS) + JSON.parse(File.read(path)).each_with_object({}) do |entry, result| + key = entry.values_at(*fields) + reason = entry["reason"] + raise ArgumentError, "duplicate exclusion: #{key.inspect}" if result.key?(key) + raise ArgumentError, "exclusion without reason: #{key.inspect}" if reason.nil? || reason.empty? + result[key] = reason + end + end + + def save(path, exclusions, fields: FIELDS) + entries = exclusions.map { |key, reason| fields.zip(key).to_h.merge("reason" => reason) } + File.write(path, JSON.pretty_generate(entries) + "\n") + end + + # Keys of +exclusions+ that no longer match any case in +cases+, with + # +key+ giving the key of a case. + def stale(exclusions, cases, key: URLTestData.method(:key)) + exclusions.keys - cases.map(&key) + end + + # Rebuilds the exclusions from the keys of the currently +failing+ + # cases, keeping known reasons and marking new ones UNCLASSIFIED. + # Cases that pass now, or that are gone from +cases+, are dropped. + # The result follows the order of +cases+. + def update(exclusions, cases, failing, key: URLTestData.method(:key)) + failing = failing.to_a + cases.map(&key).select { |k| failing.include?(k) }.each_with_object({}) do |k, result| + result[k] = exclusions.fetch(k, UNCLASSIFIED) + end + end + end +end