diff --git a/CHANGELOG.md b/CHANGELOG.md index c450578..b381659 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,408 @@ mistaken for a safe patch upgrade. ## [Unreleased] +### Breaking + +- `marker`, `requirement`, `reqtxt`: **a marker with more than 100 nested + parentheses is now a syntax error.** Before, the parser recursed once for + each `(` with no limit. +- `reqtxt`: **`Flatten` now stops at 100 nested includes, 10,000 opened + files, 64 MiB of files read in total, and 100,000 entries in the result.** + Before, a chain of includes, or two includes in each file, could open an + excessive number of files. A file that is included more than once counts + each time, so a small file that includes one file many times cannot make a + very large result: before, 32 KB of files could give 10 million entries. + `Flatten` stops parsing a file at the entry limit, so a 64 MiB file of + requirements allocates about 100 MB before the error, not 18 GB. It also + stops at an include that is over the file limit, and then the error names + the file that has the include, not the file that it includes. +- `reqtxt`: **`Parse` now returns an error for a file of more than 100,000 + entries, or a line of more than 100,000 options.** Every kind of entry + counts. The options of a line are the options of an option line, or the + per-requirement options of a requirement. Before, `Parse` had no limit, and + 8 MiB of requirements allocated 2.2 GB. `Parse` stops at the limit, so + that file now allocates about 50 MB before the error. `Flatten` uses its + own limits in place of the entry limit. +- `reqtxt`: **lines now end at every line break matching the behavior of pip:** `\v`, `\f`, `\x1c` to `\x1e`, + U+0085, U+2028 and U+2029, as well as `\n` and `\r`. This can change the + entries of a file and their line numbers. For example, `-e\v .` is now an + error. +- `reqtxt`: **`Parse` now returns an error when it joins bytes that are not + valid UTF-8 into the line break U+0085, U+2028 or U+2029.** The error wraps + `ErrInvalidRequirementsFile`. `Parse` reads the file as bytes, so three + steps could join the bytes `\xc2` and `\x85` into U+0085: + - removing quotes or a backslash from a word of an option line, or of the + options after a requirement, as in `-0\xc2""\x85`; + - a backslash continuation, as in `-0\xc2\` and then `\x85x` on the next + line; + - with `WithEnv`, a `${NAME}` value and the text or value next to it, as in + `-0${A}\x85x` with `A="\xc2"`. + + Before, these parsed, and the result held a line break. `String()` then + wrote, for example, `-"0\u0085"`, which does not parse, because the line + ends before the closing quote. pip decodes the file, and gets each value as + decoded text, before it joins lines, expands values or splits words, so it + never joins bytes. A `WithEnv` value that holds a whole line break still + puts it in the line, as in pip. +- `reqtxt`: **U+001F (unit separator) is now whitespace when `Parse` finds + comments and trims a line, as in pip.** pip uses Python's whitespace there, + which also includes U+001C to U+001F. A `#` after U+001F now starts a + comment, so `--index-url=a\x1f#b` now gives the index URL `a`. U+001F at the + start or end of a line is now removed. `File.String()` now quotes or + escapes a value with U+001F the same way, so that it reads back the same. +- `reqtxt`: **with `WithEnv`, `${NAME}` references are now replaced in pip's + order.** pip finds the references of a line first, then replaces all copies + of each one in turn, so a reference that a value adds can be expanded too. + With `NESTED=${TOKEN}` and `TOKEN=t`, `${NESTED} ${TOKEN}` now gives `t t`. + Before, it gave `${TOKEN} t`. A line that does not need pip's order (no + value makes a new reference) gives the same result as before, in linear + time. A line that needs pip's order and has more than 100 references, or + that grows by more than 1 MiB, is now an error that wraps + `ErrInvalidRequirementsFile`. So is a line that needs pip's order and is + too long for it: pip's order reads the line once for each reference, and + it may read at most 16 MiB in all. pip has no such limit, and such a line + can make it run for a very long time. +- `reqtxt`: **with `WithEnv`, `${NAME}` expansion may now add at most 16 MiB + to one file, in all its lines.** Over that, `Parse` returns an error that + wraps `ErrInvalidRequirementsFile`, before it builds the expanded line. + Before, there was no limit: a 256 KB line of `${A}` with a 4 KB value made a + 256 MB line and allocated 1.4 GB. `Flatten` now counts the 64 MiB limit on + included files after expansion, also for each later include of a file. +- `reqtxt`: **an empty `-r` or `-c` path, such as `--requirement=`, is now an + error.** pip fails on it too. As in pip, only the include that the line uses + is checked, so `-r a.txt -r ''` is not an error (see the next entry). +- `reqtxt`: **an option line with `-e`, `-r` or `-c` now gives only one entry, + as in pip.** pip reads all of the options of the line, then uses only one: + the editable requirement of `-e`, or else the first `-r` include, or else + the first `-c` include. pip ignores the other options of the line. Before, + each option gave an entry. For example, `-r a.txt -i URL` gave an include + and an index URL, and now gives only the include. `-r a.txt -r b.txt` now + includes only `a.txt`, `-c a.txt -r b.txt` now includes only `b.txt`, and + `--pre -e ./pkg` now gives only the editable requirement. `Flatten` opens + only the include that the line uses. An invalid option is still an error + anywhere on the line, as in pip. +- `reqtxt`: **on an option line, a token that does not start with `-` is now + ignored, as pip ignores it.** Before, `--pre foo` also gave a requirement + entry for `foo`. Options after such a token are still read, but a line + with `-e`, `-r` or `-c` gives only one entry (see above). +- `reqtxt`: **a lone `-` is no longer an option.** pip's `optparse` reads it + as an argument. On an option line it is now ignored, as pip ignores it, so + `-` and `- foo` give no entries. After a requirement, it is now an + "unexpected token" error, like any other word there, so `foo -` is now an + error. pip ignores it there too. Before, both gave an `OptionEntry` named + `-`. +- `reqtxt`: **a token that is only `--` now ends the options of a line, and + the rest of the line is ignored, as in pip.** pip reads a line with Python's + `optparse`, which reads `--` as the end of the options. Before, `--` was an + `OptionEntry` named `--`, and the options after it were read. For example, + `--pre -- --index-url x` gave three entries and now gives only `--pre`, and + `foo -- --hash=sha256:x` now gives `foo` with no hash. An option that takes + a value still takes `--` as its value, as in `--index-url --`. `--=x` is + now an "ambiguous option" error, as in pip, because `optparse` reads `--` as + a prefix of every long option. Before, it was an `OptionEntry` named `--`. +- `reqtxt`: **a short option with an attached value, such as `-rother.txt`, + is now read as the option with that value, as pip reads it.** This applies + to `-r`, `-c`, `-e`, `-i` and `-f`. Before, `-rother.txt` was an unknown + `OptionEntry` named `-rother.txt`, so the include was lost with no error. + Now `-rother.txt` is an include, and `Flatten` opens `other.txt`. An + attached editable target that is not a VCS reference, URL or path, such as + `-efoo`, is now an error, as in pip. `-r=other.txt` still reads as + `other.txt`, but pip reads it as the path `=other.txt`. +- `reqtxt`: **a unique prefix of a long option is now read as that option, + and a prefix of two or more options is now an error, as in pip.** pip + reads an option line with Python's `optparse`, which accepts + abbreviations. Before, `--index https://x` was an unknown option + `--index`, and the index URL was lost with no error. Now it is + `--index-url`. A prefix such as `--req` matches `--requirement` and + `--require-hashes`, so it now fails with an "ambiguous option" error. + Before, it was an unknown option. A full option name, such as `--pre`, is + never read as a prefix. The older `--global-option` and `--install-option` + options still work when written in full, but they have no prefix, because + pip does not have them now. +- `reqtxt`: **`--pypi-url`, pip's second long name of `--index-url`, now + gives an `OptionEntry` named `--index-url`.** `--no-require-hashes` is now + a known option. Before, both were unknown options, and `--pypi-url` + did not take its value. +- `reqtxt`: **on a line that is not a URL, only the text before the first + `;` now decides whether the line is a local path, as in pip.** pip removes + the marker at the first `;`, also when no whitespace comes before it. + `foo.tar.gz;os_name=="x"` and `./pkg;os_name=="x"` are now errors, because + an archive or a path cannot have a marker. Before, the archive was a + requirement named `foo.tar.gz`, and the path kept the marker in its `Raw` + text. `foo;os_name=="a/b"` is now a requirement `foo` with a marker. Before, + the `/` in the marker made it a local path. A URL is not changed: + `https://example.com/a.whl;os_name=="x"` is still one URL, as in pip. +- `reqtxt`: **a line is now an archive when its whole text before the marker + ends with an archive extension, after non-empty extras at its end are + removed, as in pip.** Before, only the first token counted. Now: + - `foo.whl[x]` and `foo.zip[x,y]` are archives (`UnnamedEntry`). Before, + they were requirements named `foo.whl` and `foo.zip`. + - `foo ===x.whl` is now an error, because an archive cannot have other + text. Before, it was a requirement. Write the version in parentheses, + as in `foo (===x.whl )`. + - `foo.whl [x]`, `foo.whl >=1` and `foo.whl[]` are requirements named + `foo.whl`. Before, the first two were errors. + + A line whose first token contains `/` is still a local path. +- `reqtxt`: **the archive extensions are now pip's, and pip's rule finds the + extension.** `.tbz`, `.tar.xz`, `.txz`, `.tlz`, `.tar.lz` and `.tar.lzma` + are now archive extensions, so `foo-1.0.tar.xz` is now an archive. Before, + it was a requirement. The extension now starts at the last `.`, with a + `.tar` before it added, as in pip's `splitext`. So `foo.tar.zip` (extension + `.tar.zip`) and `.zip` (no extension) are no longer archives. Before, any + text that ended with `.zip` was one. This also applies to `-e` targets. +- `tags`, `wheelname`: **a tag that expands to more than 10,000 tags is now + an error** that wraps `tags.ErrInvalidTag`. Before, a 1.2 KB tag expanded + to 8 million tags. +- `wheelname`: **a filename with an empty project name, such as + `-1.0-py3-none-any.whl`, is now an error** that wraps + `ErrInvalidWheelFilename`. +- `wheelname`: **`Parse` and `ParseTags` now check the project name as + packaging's `parse_wheel_filename` does.** It may have only Unicode letters + and numbers, `_` and `.`, and no `__`, because PEP 427 escapes each run of + other characters to one `_`. A name with any other character, such as a + space, `+`, `~`, a control character or U+00A0, is now an error that wraps + `ErrInvalidWheelFilename`. So are `foo__bar` and a name that is not valid + UTF-8. Before, any non-empty name was accepted. +- `distribution`: **parsing a wheel or sdist now fails when a METADATA or + PKG-INFO candidate is over 64 MiB uncompressed.** Before, the whole entry + was read into memory, so a small archive that decompresses to many GB could + use all memory. +- `version`, `requirement`, `reqtxt`: **a number in a version with more than + 4,300 digits is now an error,** the same default limit as Python's `int()`, + so packaging on Python 3.11 and later rejects it too. This covers the + release, epoch, pre, post and dev numbers and all-digit local segments. + Before, `math/big` used quadratic memory: a 400,000-digit number allocated + 350 MB. +- `version`: **`Specifiers.And` now returns an error that wraps the new + `ErrTooManyOrGroups` when both sets have more than one OR group and the + result would have more than 10,000.** `And` makes one group for each pair + of groups, so two sets of 1,200 groups made 1.4 million groups and + allocated 3.4 GB. A set with one group, or an empty set, does not make the + count grow, so `And` with it has no limit, even for a set of more than + 10,000 groups. +- `version`: **`Specifiers.And` now returns an error that wraps the new + `ErrTooManySpecifiers` when the result would have more than 100,000 + specifiers and more specifiers than the two sets together.** `And` copies + all the specifiers of both groups into each result group. The OR group + limit does not see the size of each group, and a set with one group has no + OR group limit. So 2 groups of 2,000 specifiers and 5,000 groups of 1 made + 20 million specifiers and allocated about 20 GB. `And` of two sets with one + group each, or with an empty set, makes no more specifiers than the two + sets together, so it never returns this error. +- `distribution`: **a GPG signature file over 1 MiB is now an error** that + wraps `ErrTooLarge`. Before, the whole file was read into memory. A + signature is about 1 KB. +- `version`: **a `===` value now ends at any Python whitespace, as in + packaging.** Before, it ended only at Go's whitespace, so `===x\vy` was the + value `x\vy`. It is now an error. +- `requirement`, `reqtxt`: **after a version in a requirement, only space and + tab are allowed, as in packaging.** Before, `foo>=1.0` followed by `\v`, + U+00A0, U+2028 or other Unicode whitespace parsed as `foo>=1.0`. It is now + an error. +- `requirement`, `reqtxt`: **`||` in a version specifier is now an error, + except in the value of `===`, as in packaging.** `||` is an OR in package + `version`, but it is not PEP 508. Before, `Parse` accepted some such + requirements, such as `foo>1.0||*`, and `String()` could write one that did + not parse back, such as `foo>1.0||>=0.0.0`. A `===` value can now contain + `||`: `foo===a||b` is one `===` specifier with the value `a||b`. Before, it + was an error. `version.NewSpecifiers` still reads `||` as an OR. +- `marker`: **in a version comparison, `Evaluate` now lets the specifier + decide when the value is not a version, as packaging does.** When the + operator and the literal form a valid specifier, a value that is not a + version matches nothing, and `===` compares the value as written, ignoring + case. Before, such a value fell back to the string operators, so + `python_version != "3.11"` was true for the value `garbage`, and + `===` compared the normalized version, so + `python_full_version === "3.11.4"` matched `3.11.04`. Each is now as in + packaging 26.2 and 26.3. This matters for a target that + `EnvironmentFromTarget` builds, whose `platform_release` is empty: + `platform_release != "5.0"` was true and is now false. `EvaluateUndecidable` + still reports the empty variable, so a caller that must keep the edge can. +- `marker`: **`Evaluate` now reads a comma or `||` in the literal of a + version comparison as packaging does.** It builds one specifier from the + operator and the literal, as packaging's `Specifier(f"{op}{rhs}")` does. + Before, it built a specifier set, which read `python_version >= "3.8,<4"` + as two constraints. Now the specifier is invalid, and the comparison falls + back to the string operators, as in packaging 26.2 and 26.3. Most such + markers stop matching: `python_version >= "3.8,<4"` was true and is now + false. A `!=` marker can start to match: `python_version != "3.8,!=3.11"` + was false for Python 3.11 and is now true. + +### Added + +- `distribution`: when `Parse` cannot read a wheel or sdist, its error now + wraps the cause, so `errors.Is` and `errors.As` can match it (for example + `zip.ErrChecksum` for a corrupt wheel). The message text does not change. +- `distribution`: new `ErrTooLarge` and `ErrUnknownArchiveFormat`, which the + error from `Parse` wraps when an archive entry is over 64 MiB, when a GPG + signature file is over 1 MiB, or when a file is not a zip or a gzipped tar + archive. Match them with `errors.Is`. Before, the unknown-format error was + in an internal package, so other modules could not match it. Its message + text does not change. + +### Fixed + +- `marker`: **`String()` now writes every literal so that it parses again.** + A backslash is written as `\\`. A value with both quote characters is + written with each `"` as `\x22`. A line break is written as an escape, such + as `\n`. Other characters, such as `#` and `-`, are written unchanged. + Before, `os_name == "C:\\U"` was written as `os_name == "C:\U"`, which does + not parse. +- `marker`, `requirement`, `reqtxt`: **`String()` now writes a byte in a + marker literal that is not valid UTF-8 unchanged,** so the literal parses + back to the same value. Before, each such byte was written as U+FFFD, so + `os_name == "a\xffb"` (with the raw byte `0xFF`) parsed back with a + different value. +- `requirement`: **`String()` now writes an extra that normalizes to a + trailing `-` with a trailing `_`,** so `foo[a_]` parses again. `Extras` + still holds the normalized `a-`. Before, `String()` wrote `foo[a-]`, which + does not parse. +- `requirement`: **`String()` now writes a URL that starts with `#` or `-` + directly after `@`,** as in `foo @#frag`, so a requirements file does not + read it as a comment or as options. +- `reqtxt`: **`File.String()` now writes every value so that it parses back + to the same value.** Include paths and `-e` targets are quoted when they + have whitespace, quotes or a backslash. A `#` after whitespace in a quoted + value is written as `"\#"`. A `#` or `-` after whitespace in a marker + literal is written as `\x23` or `\x2d`, because pip reads ` #` as a comment + and ` -` as the start of the options, also inside quotes. `marker.String()` + and `requirement.String()` do not write these escapes, so their output stays + readable by tools that do not decode escapes, such as `packaging` before + 22.0. pip decodes these escapes only from pip 24.1, the first release that + bundles `packaging` 22.0 or later. Older pip reads `\x23` as four + characters, but it cannot read a ` #` or ` -` in a literal at all. In an + option name, the part after the `-` is quoted, as in `-" 0"`. Before, + `-r a\ b.txt` was written as `-r a b.txt`, which reads as two entries. +- `reqtxt`: **`Parse` and `File.String()` now keep a byte that is not valid + UTF-8 in an option value, an include path, or an `-e` target.** Before, + `Parse` changed each such byte to U+FFFD when it split an option line, and + `String()` did the same when it quoted a value. So + `--index-url="a \xffb"` (with the raw byte `0xFF`) read back with a + different value. +- `reqtxt`: **`File.String()` now writes an option named `-` with no value as + `-=""`.** `Parse` gives this option for the token `-=`. Before, `String()` + wrote a bare `-`, which reads back as no entry, or as an "unexpected + token" error after a requirement. +- `reqtxt`: **`File.String()` now writes a requirement that would read back + as a local path in a form that reads back as the same requirement,** in + `Parse` and in pip 21.2.4: + - A version with `/`, such as `0===a/b`, gets a space before it: + `0 ===a/b`. Before, it read back as a local path, and + `0 ===a/b ; os_name == "x"` did not parse again. + - A version with an archive extension, such as `===x.whl` or + `==1.0+a.zip`, is written in parentheses with a space before `)`: + `foo (===x.whl )`. pip 21.2.4 reads a `)` just after a `===` version as + part of the version. + - A project name with an archive extension and no version gets empty + extras, `foo.whl[]`, or a space before its extras, `foo.whl [x]`. pip + reads `foo.whl` and `foo.whl[x]` as files. Before, `foo.whl` read back as + a local path, and `foo.tar.gz; python_version > "3"` did not parse again. +- `reqtxt`: **`-C`, pip's short form of `--config-settings`, is now read as + `--config-settings`.** `foo -C x=y` and `foo -Cx=y` now give `foo` the + option `--config-settings` with the value `x=y`. Before, `-C` was an + unknown option, so `foo -C x=y` failed with "unexpected token". `-C=x=y` + gives the value `x=y`, but pip reads it as `=x=y`. +- `reqtxt`: **after a requirement or an `-e` target, an option that takes a + value now takes the next token as its value, as in pip.** This includes + the file options, such as `--index-url`, and `-r`, `-c` and `-e`. So + `foo --index-url https://x` now gives `foo` the option `--index-url` with + the value `https://x`, the same as `foo --index-url=https://x`. And + `-e ./a -e ./b` now gives the editable requirement `./a` with the option + `-e` and the value `./b`. pip ignores these options on a requirement line, + but this package keeps them. A value attached to a short option, as in + `foo -rother.txt`, is now read as on an option line. Before, each of these + lines failed with "unexpected token", and `foo -rother.txt` gave an + unknown option named `-rother.txt`. +- `reqtxt`: **a line such as `foo.zip @ https://example.com/foo.zip` is now a + named URL requirement, as in pip.** When a line looks like an archive but + the text before `@` does not look like a path, pip reads it as + `name @ url`. Before, it was an error. An `@` in the marker does not count, + because pip removes the marker first, so `foo.tar.gz ; os_name == "a@b"` + is still an error. +- `reqtxt`: **whitespace in a requirement line is now kept as written,** as + pip keeps it. Before, a tab or two spaces inside a quoted marker literal or + a quoted option value became one space. +- `reqtxt`: **with `WithEnv`, whitespace that a value adds at the start or end + of a requirement line is now removed,** as pip removes it. The line is + trimmed before the expansion, so with `A=" ./pkg"`, the line `${A}` was an + `UnnamedEntry` with the `Raw` text ` ./pkg`, which did not read back the + same after `File.String()`. Now `Raw` is `./pkg`. +- `wheelname`: **`CompareBuildTags` now compares build numbers of any size.** + Before, numbers too large for `int` compared wrongly. +- `marker`, `requirement`, `reqtxt`: **syntax error text for a long input is + now short.** When the input is longer than 1024 bytes, the error shows only + 80 bytes on each side of the error, with `...` where text is cut, and marks + at most 80 bytes of the error span. Before, the error included the whole + input, so a 2 MB input made an error of more than 2 MB. +- `version`, `requirement`, `reqtxt`, `distribution`: **errors that show + input text now show at most 200 bytes of it,** then `...` and the full + length in bytes. Shorter text is shown as before. This applies to + `version.Parse`, `NewSpecifier` and `NewSpecifiers` errors, the version + specifier error from `requirement.Parse`, and the `reqtxt` errors for + editable targets, direct references, unexpected tokens, `--hash` values, and + `Flatten` include paths. Before, a 2 MB version specifier made an error of + about 4 MB. In `distribution.Parse` errors, the name of an archive entry and + a `Metadata-Version` value are now also quoted, as with `%q`, so a line break + or an escape sequence in them is not written as it is. Before, a 64 KB sdist + with a 500 KB entry name made an error of 1 MB. The error for a malformed + header line in a METADATA or PKG-INFO file now also shows at most 200 bytes, + and `errors.Unwrap` still gives the error of `net/mail`. Before, a 500 KB + line made an error of 500 KB. +- `version`: **the error for an operand that a `NewSpecifiersWithSanitizer` + sanitizer makes invalid no longer has empty parentheses.** It was + `version parse error (): malformed version: X` and is now + `version parse error: malformed version: X`. +- `distribution`: `Parse` no longer panics on a `.tar.gz` file that is empty + or is not gzip. It now returns an error. +- `version`: **`Parse`, `NewSpecifier` and `NewSpecifiers` now allow all of + Python's whitespace where packaging allows whitespace:** around a version, + around a specifier, between an operator and its version, and around each + comma-separated part. packaging's patterns run on a Python str, where `\s` + also matches U+001C to U+001F and Unicode whitespace such as U+00A0 (no-break + space) and U+3000. Before, only `[\t\n\v\f\r ]` was allowed, so `1.0` + followed by U+00A0 was an error. Whitespace inside a version is still an + error. +- `requirement`, `reqtxt`: **U+001C to U+001F between an operator and its + version are now allowed, as in packaging,** like the other whitespace + there. For example, `foo>=\x1f1.0` is now `foo>=1.0`. Before, it was an + error. + +### Notes + +- `version`, `marker`: **checking a version against a specifier, and + `Marker.Evaluate`, allocate much less.** A `Specifier` now keeps its + operand parsed, so `Check` does not parse it on each call, and a parsed + version no longer builds comparison-key parts that it then discards. + `Specifiers.Check` is about 75% faster, `version.Parse` about 10% faster, + and `python_version >= "3.8"` evaluates with 36 allocations instead of 108. + A marker with no version or `extra` comparison evaluates with none. The + cost is memory: a parsed `Specifier` now holds about 650 bytes, not 72. +- `distribution`: **a `.tar.gz` sdist is now read in one pass.** Before, + `Parse` decompressed it once to list the entries and again for each + PKG-INFO candidate. It picks the same PKG-INFO, with two exceptions that + were not predictable before: among candidates of the same depth, archive + order now always decides (before, with more than 12 candidates, the order + could change), and when two tar entries have the same name, each one is + now read (before, the first one was read for both). The pass reads a + candidate only if it can replace the one found so far, and at most 1 MiB + of candidates in all. A larger candidate that can be the result is read + after the pass, as before, so an sdist with a PKG-INFO over 1 MiB can take + more than one pass. +- `reqtxt`: **`Flatten` now calls `open` and parses each file only once,** + also when the file is included more than once. Each include still gives + its own copy of the entries, and the limits still count each include. +- `reqtxt`: **`File.String()` cannot write two kinds of value, and its + output then does not read back as the same file.** `Parse` gives either + kind only with `WithEnv`, when an environment variable's value adds the + text, as in pip: + - A value that holds a line break. A requirements file has no escape for a + line break, so a quoted value no longer parses, and a URL reads back as + two lines. Marker literals are not affected. + - A target (not `-e`) that starts with `-`, or has a `#` at its start or + after whitespace. pip reads a target with no quotes or escapes, so + `#/` reads back as a comment, and `-/` as an option. + ## [0.13.0] - 2026-10-19 ### Breaking diff --git a/CLAUDE.md b/CLAUDE.md index dde96da..60f0a93 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -63,6 +63,43 @@ Keep the random seed. `rapid.Check` takes no seed option by design; a fixed seed degenerates into a slow, unreadable table test. Name every `Draw` so failures are reproducible from the printed output. +## Performance + +Each package with a hot path (`version`, `requirement`, `marker`, `reqtxt`, +`wheelname`, `tags`, `distribution`) has a `bench_test.go` with benchmarks and +`TestAllocBudget_*` tests over the same inputs. + +**Allocation budgets run in CI.** An allocation count does not depend on the machine, +so `internal/allocbudget.Check` fails when a call allocates more *or fewer* times than +its budget, within 0.1% (so a budget under 1,000 is exact). Each slowdown found while +reviewing PR #71 also added allocations, and these tests catch them. + +- **Over budget:** find the new allocation. If the change needs it, raise the budget to + the count the failure prints, and say why in the PR. +- **Under budget:** lower the budget to the printed count, so the next regression is + caught. +- The tests skip under `-race`, which adds allocations; CI's plain `go test ./...` runs + them. Counts are the same on arm64 and amd64. +- Code that uses a `sync.Pool` (such as `archive/zip`) or builds maps can move by an + allocation or two between runs. Use `allocbudget.CheckWithin` with a small tolerance, + and say why at the call. +- A new Go release can change the counts. Update the budgets in that PR. +- Each budget test checks first that its input parses, so a budget does not measure an + error path by accident. A row that measures one on purpose says so. + +**Benchmarks do not run in CI**, because timing on shared runners is too noisy to gate +on. Before you merge a change to a hot path, compare it with `main`: + +```bash +git worktree add /tmp/gpp-main main +(cd /tmp/gpp-main && go test -run '^$' -bench . -count 10 ./reqtxt) > /tmp/old.txt +go test -run '^$' -bench . -count 10 ./reqtxt > /tmp/new.txt +go run golang.org/x/perf/cmd/benchstat@latest /tmp/old.txt /tmp/new.txt +git worktree remove /tmp/gpp-main +``` + +Explain any change that `benchstat` marks as significant. + ## Code Style - Follow standard Go conventions. diff --git a/distribution/bench_test.go b/distribution/bench_test.go new file mode 100644 index 0000000..8cbe237 --- /dev/null +++ b/distribution/bench_test.go @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package distribution_test + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "fmt" + "math/rand/v2" + "os" + "path/filepath" + "testing" + + distribution "github.com/posit-dev/go-python-packaging/distribution" + "github.com/posit-dev/go-python-packaging/internal/allocbudget" + "github.com/stretchr/testify/require" +) + +// Benchmarks and allocation budgets for Parse. The budget tests run in CI +// and fail on any change in allocations; the benchmarks are for comparing a +// branch with main (see CLAUDE.md, "Performance"). + +const benchMetadata = "Metadata-Version: 2.1\nName: example\nVersion: 1.0\nSummary: An example\n" + + "Requires-Dist: requests>=2.8.1\nRequires-Dist: numpy; python_version >= \"3.8\"\n" + +// benchSource is the random contents of n source files of size bytes each. +// Random bytes do not compress, so the archive is as large as a real one. +func benchSource(n, size int) [][]byte { + rng := rand.NewChaCha8([32]byte{7}) + files := make([][]byte, n) + for i := range files { + files[i] = make([]byte, size) + _, _ = rng.Read(files[i]) + } + return files +} + +// writeBenchSDist writes a 3 MB .tar.gz sdist whose PKG-INFO comes after +// its 200 source files, as some build tools write it. +func writeBenchSDist(tb testing.TB) string { + tb.Helper() + var buf bytes.Buffer + gzw := gzip.NewWriter(&buf) + tw := tar.NewWriter(gzw) + add := func(name string, data []byte) { + require.NoError(tb, tw.WriteHeader(&tar.Header{Name: name, Mode: 0o644, Size: int64(len(data))})) + _, err := tw.Write(data) + require.NoError(tb, err) + } + for i, data := range benchSource(200, 16<<10) { + add(fmt.Sprintf("example-1.0/src/mod%d.py", i), data) + } + add("example-1.0/PKG-INFO", []byte(benchMetadata)) + require.NoError(tb, tw.Close()) + require.NoError(tb, gzw.Close()) + path := filepath.Join(tb.TempDir(), "example-1.0.tar.gz") + require.NoError(tb, os.WriteFile(path, buf.Bytes(), 0o600)) + return path +} + +// writeBenchWheel writes a 3 MB wheel with 200 source files. +func writeBenchWheel(tb testing.TB) string { + tb.Helper() + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + add := func(name string, data []byte) { + w, err := zw.Create(name) + require.NoError(tb, err) + _, err = w.Write(data) + require.NoError(tb, err) + } + for i, data := range benchSource(200, 16<<10) { + add(fmt.Sprintf("example/mod%d.py", i), data) + } + add("example-1.0.dist-info/METADATA", []byte(benchMetadata)) + add("example-1.0.dist-info/WHEEL", []byte("Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n")) + require.NoError(tb, zw.Close()) + path := filepath.Join(tb.TempDir(), "example-1.0-py3-none-any.whl") + require.NoError(tb, os.WriteFile(path, buf.Bytes(), 0o600)) + return path +} + +// benchPackages are the files that Parse reads. budget is its allocation +// budget for each. +var benchPackages = []struct { + name string + write func(testing.TB) string + budget float64 +}{ + {name: "sdist", write: writeBenchSDist, budget: 2778}, + {name: "wheel", write: writeBenchWheel, budget: 955}, +} + +func BenchmarkParse(b *testing.B) { + for _, p := range benchPackages { + b.Run(p.name, func(b *testing.B) { + path := p.write(b) + b.ReportAllocs() + for b.Loop() { + if _, err := distribution.Parse(path); err != nil { + b.Fatal(err) + } + } + }) + } +} + +func TestAllocBudget_Parse(t *testing.T) { + for _, p := range benchPackages { + t.Run(p.name, func(t *testing.T) { + path := p.write(t) + _, err := distribution.Parse(path) + require.NoError(t, err, "the budget must not be an error path") + // archive/zip and compress/flate keep decompressors in a + // sync.Pool, so a garbage collection can add or save an + // allocation: the count moves by up to 1 or 2. + allocbudget.CheckWithin(t, p.budget, 2, func() { _, _ = distribution.Parse(path) }) + }) + } +} diff --git a/distribution/errors.go b/distribution/errors.go new file mode 100644 index 0000000..eab5b4f --- /dev/null +++ b/distribution/errors.go @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package distribution + +import "github.com/posit-dev/go-python-packaging/distribution/internal/archiver" + +// Errors that Parse can wrap. Match them with errors.Is. +var ( + // ErrTooLarge means that a METADATA or PKG-INFO candidate is larger than + // 64 MiB, or that a GPG signature file is larger than 1 MiB. + ErrTooLarge = archiver.ErrTooLarge + + // ErrUnknownArchiveFormat means that a file is not a zip archive or a + // gzipped tar archive. + ErrUnknownArchiveFormat = archiver.ErrUnknownFormat +) diff --git a/distribution/fuzz_test.go b/distribution/fuzz_test.go new file mode 100644 index 0000000..5937bd0 --- /dev/null +++ b/distribution/fuzz_test.go @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package distribution_test + +import ( + "path/filepath" + "strings" + "testing" + "time" + + distribution "github.com/posit-dev/go-python-packaging/distribution" + "github.com/posit-dev/go-python-packaging/internal/fuzzseed" +) + +// FuzzParseWheelMetadata puts the fuzzed bytes in a wheel's METADATA file +// and parses the wheel through the public entry point. +func FuzzParseWheelMetadata(f *testing.F) { + fuzzseed.Add(f, + "Metadata-Version: 2.4\nName: fz\nVersion: 1.0\nRequires-Dist: a>=1; python_version >= \"3.8\"\n\nbody\n", + "Metadata-Version: 2.1\r\nName: fz\r\nVersion: 1.0\r\n\r\n", + "Metadata-Version: 1.0\nName: fz\nVersion: 1\nAuthor: J\xf6rg\n", + "Metadata-Version: 9.9\nName: fz\n\n", + ) + f.Add("Metadata-Version: 2.1\nName: fz\n" + strings.Repeat("Classifier: x\n", 5000) + "\n") + + f.Fuzz(func(t *testing.T, metadata string) { + path := filepath.Join(t.TempDir(), "fz-1.0-py3-none-any.whl") + writeWheelFixture(t, path, []fixtureEntry{ + {name: "fz-1.0.dist-info/METADATA", contents: metadata}, + {name: "fz-1.0.dist-info/WHEEL", contents: "Wheel-Version: 1.0\nTag: py3-none-any\n"}, + }) + start := time.Now() + pkgs, err := distribution.Parse(path) + fuzzseed.Within(t, start, metadata) + if err != nil { + if pkgs != nil { + t.Fatalf("Parse returned packages and an error: %v", err) + } + return + } + if len(pkgs) != 1 || pkgs[0] == nil { + t.Fatalf("Parse of one wheel returned %d packages and no error", len(pkgs)) + } + _ = pkgs[0].MetadataMap() + }) +} diff --git a/distribution/internal/archiver/archive_limit_test.go b/distribution/internal/archiver/archive_limit_test.go new file mode 100644 index 0000000..4d0a00a --- /dev/null +++ b/distribution/internal/archiver/archive_limit_test.go @@ -0,0 +1,268 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package archiver_test + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/flate" + "compress/gzip" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/posit-dev/go-python-packaging/distribution/internal/archiver" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// zeroReader gives an endless stream of zero bytes. +type zeroReader struct{} + +func (zeroReader) Read(p []byte) (int, error) { + clear(p) + return len(p), nil +} + +// newGzipWriter compresses at BestSpeed, which keeps the large test archives +// fast to build, also under -race. +func newGzipWriter(t *testing.T, w io.Writer) *gzip.Writer { + t.Helper() + gzw, err := gzip.NewWriterLevel(w, gzip.BestSpeed) + require.NoError(t, err) + return gzw +} + +// writeZerosArchive builds, in memory, an archive with one entry that holds +// size zero bytes, and writes it to a temp file. format is "zip" or "tar.gz". +func writeZerosArchive(t *testing.T, format, name string, size int64) string { + t.Helper() + + var buf bytes.Buffer + switch format { + case "zip": + zw := zip.NewWriter(&buf) + zw.RegisterCompressor(zip.Deflate, func(w io.Writer) (io.WriteCloser, error) { + return flate.NewWriter(w, flate.BestSpeed) + }) + w, err := zw.CreateHeader(&zip.FileHeader{Name: name, Method: zip.Deflate}) + require.NoError(t, err) + _, err = io.CopyN(w, zeroReader{}, size) + require.NoError(t, err) + require.NoError(t, zw.Close()) + case "tar.gz": + gzw := newGzipWriter(t, &buf) + tw := tar.NewWriter(gzw) + require.NoError(t, tw.WriteHeader(&tar.Header{Name: name, Mode: 0o644, Size: size})) + _, err := io.CopyN(tw, zeroReader{}, size) + require.NoError(t, err) + require.NoError(t, tw.Close()) + require.NoError(t, gzw.Close()) + default: + t.Fatalf("unknown format %q", format) + } + + path := filepath.Join(t.TempDir(), "example-1.0.0."+format) + require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600)) + return path +} + +// ReadFile must use MaxReadSize. Each archive has one entry whose header +// claims MaxReadSize+1 bytes, but that holds no data. ReadFile rejects the +// entry before it reads it, and the error gives the limit that ReadFile used. +func TestReadFile_UsesMaxReadSize(t *testing.T) { + for _, format := range []string{"zip", "tar.gz"} { + t.Run(format, func(t *testing.T) { + var buf bytes.Buffer + switch format { + case "zip": + zw := zip.NewWriter(&buf) + _, err := zw.CreateRaw(&zip.FileHeader{Name: "PKG-INFO", Method: zip.Store, UncompressedSize64: archiver.MaxReadSize + 1}) + require.NoError(t, err) + require.NoError(t, zw.Close()) + case "tar.gz": + // WriteHeader writes the header at once. The data that the + // header claims is not written, so tw is not closed. + gzw := newGzipWriter(t, &buf) + tw := tar.NewWriter(gzw) + require.NoError(t, tw.WriteHeader(&tar.Header{Name: "PKG-INFO", Mode: 0o644, Size: archiver.MaxReadSize + 1})) + require.NoError(t, gzw.Close()) + } + path := filepath.Join(t.TempDir(), "example-1.0.0."+format) + require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600)) + + reader, err := archiver.NewArchiveReader(path) + require.NoError(t, err) + defer func() { + require.NoError(t, reader.Close()) + }() + + _, err = reader.ReadFile("PKG-INFO") + require.ErrorIs(t, err, archiver.ErrTooLarge) + assert.Contains(t, err.Error(), fmt.Sprintf("is over %d bytes", archiver.MaxReadSize)) + }) + } +} + +// With MaxReadSize, this test read 64 MiB entries and took 6 seconds under +// -race, so it uses a limit of 1 MiB. TestReadFile_UsesMaxReadSize makes sure +// that ReadFile uses MaxReadSize. +func TestReadFile_SizeLimit(t *testing.T) { + const limit = 1 << 20 + const bomb = 16 * limit // 16 MiB of zeros, about 16 KiB compressed + + tests := []struct { + name string + format string + size int64 + wantErr bool + }{ + {name: "zip at limit", format: "zip", size: limit}, + {name: "zip one over limit", format: "zip", size: limit + 1, wantErr: true}, + {name: "zip bomb", format: "zip", size: bomb, wantErr: true}, + {name: "tar.gz at limit", format: "tar.gz", size: limit}, + {name: "tar.gz one over limit", format: "tar.gz", size: limit + 1, wantErr: true}, + {name: "tar.gz bomb", format: "tar.gz", size: bomb, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := writeZerosArchive(t, tt.format, "PKG-INFO", tt.size) + + reader, err := archiver.NewArchiveReader(path) + require.NoError(t, err) + defer func() { + require.NoError(t, reader.Close()) + }() + + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + got, err := archiver.ReadFileWithin(reader, "PKG-INFO", limit) + runtime.ReadMemStats(&after) + + if !tt.wantErr { + require.NoError(t, err) + assert.Len(t, got, int(tt.size)) + return + } + require.ErrorIs(t, err, archiver.ErrTooLarge) + assert.Contains(t, err.Error(), "is over 1048576 bytes") + assert.Nil(t, got, "an entry over the limit must not be returned cut off") + // The entry is rejected before it is read, so ReadFile allocates + // far less than the limit, let alone the entry. + assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(limit/4)) + }) + } +} + +// The name limit also counts 16 bytes for each entry, so that many short names +// cannot make a list of names far larger than the limit: each string in the +// list takes 16 bytes more than its text. With MaxReadSize, a test of this +// needed about 3.9 million entries and took 8.5 seconds, so this test uses a +// limit of 64 KiB. +// +// The rows are exactly at the limit and exactly 1 byte over it, so that the +// test fails if the limit check moves by 1 byte in either direction. +func TestTarFileNames_ManyShortNames(t *testing.T) { + const limit = 64 << 10 + // Each 1-byte name counts 17 bytes. The last name then brings the total to + // the limit (2 bytes, counts 18) or 1 byte over it (3 bytes, counts 19). + const short = (limit - (2 + 16)) / (1 + 16) + require.Equal(t, limit, short*(1+16)+(2+16), "the first row is exactly at the limit") + + tests := []struct { + name string + last string + wantErr bool + }{ + {name: "at the limit", last: "ab"}, + {name: "one byte over the limit", last: "abc", wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var buf bytes.Buffer + gzw := newGzipWriter(t, &buf) + tw := tar.NewWriter(gzw) + hdr := &tar.Header{Name: "a", Mode: 0o644} + for range short { + require.NoError(t, tw.WriteHeader(hdr)) + } + require.NoError(t, tw.WriteHeader(&tar.Header{Name: tt.last, Mode: 0o644})) + require.NoError(t, tw.Close()) + require.NoError(t, gzw.Close()) + + path := filepath.Join(t.TempDir(), "example-1.0.0.tar.gz") + require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600)) + + reader, err := archiver.NewArchiveReader(path) + require.NoError(t, err) + defer func() { + require.NoError(t, reader.Close()) + }() + + names, err := archiver.TarFileNamesWithin(reader, limit) + if tt.wantErr { + require.ErrorIs(t, err, archiver.ErrTooLarge) + assert.Contains(t, err.Error(), "entry names are over 65536 bytes") + return + } + require.NoError(t, err) + assert.Len(t, names, short+1) + }) + } +} + +// With MaxReadSize, this test wrote 64 MiB of names and took 4 seconds under +// -race, so it uses a limit of 4 MiB. +func TestTarFileNames_SizeLimit(t *testing.T) { + const limit = 4 << 20 + // Each long name goes in a GNU long-name record, which tar limits to 1 MiB. + longName := strings.Repeat("a", 1<<20-1024) + fit := limit / (len(longName) + 16) // the most names that the limit allows + + tests := []struct { + name string + count int + wantErr bool + }{ + {name: "under limit", count: fit}, + {name: "over limit", count: fit + 1, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var buf bytes.Buffer + gzw := newGzipWriter(t, &buf) + tw := tar.NewWriter(gzw) + for range tt.count { + require.NoError(t, tw.WriteHeader(&tar.Header{Name: longName, Mode: 0o644, Format: tar.FormatGNU})) + } + require.NoError(t, tw.Close()) + require.NoError(t, gzw.Close()) + + path := filepath.Join(t.TempDir(), "example-1.0.0.tar.gz") + require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600)) + + reader, err := archiver.NewArchiveReader(path) + require.NoError(t, err) + defer func() { + require.NoError(t, reader.Close()) + }() + + names, err := archiver.TarFileNamesWithin(reader, limit) + if tt.wantErr { + require.ErrorIs(t, err, archiver.ErrTooLarge) + assert.Contains(t, err.Error(), "entry names are over 4194304 bytes") + return + } + require.NoError(t, err) + assert.Len(t, names, tt.count) + }) + } +} diff --git a/distribution/internal/archiver/archive_reader.go b/distribution/internal/archiver/archive_reader.go index 6b582b4..64ffaf2 100644 --- a/distribution/internal/archiver/archive_reader.go +++ b/distribution/internal/archiver/archive_reader.go @@ -12,8 +12,25 @@ import ( "log" "os" "strings" + + "github.com/posit-dev/go-python-packaging/internal/errtext" ) +// MaxReadSize is the most data one call returns: the contents of one entry for +// ReadFile, or the entry names of a tar archive for FileNames. Real METADATA +// and PKG-INFO files are kilobytes to a few megabytes, so this is far above +// them, but it stops a small archive that decompresses to gigabytes. +const MaxReadSize = 64 << 20 + +// ErrTooLarge is returned when an entry, or the list of entry names of a tar +// archive, is larger than MaxReadSize. Package types also wraps it for a GPG +// signature file that is too large, so its text does not name the archive. +var ErrTooLarge = errors.New("data is larger than the size limit") + +// ErrUnknownFormat is returned when a file is not a zip archive or a gzipped +// tar archive. +var ErrUnknownFormat = errors.New("not a known archive format") + // ArchiveReader is an interface to abstract the behavior of different archive types. type ArchiveReader interface { FileNames() ([]string, error) @@ -21,10 +38,30 @@ type ArchiveReader interface { Close() error } +// Scanner is an ArchiveReader that can read the entries a caller wants in one +// pass over the archive. The tar reader is one: it must decompress the whole +// stream for FileNames and again for each ReadFile, so one pass halves the +// work or better. A zip archive can read any entry directly, so it is not. +type Scanner interface { + ArchiveReader + // Scan reads the archive once, in order. It calls match with the name of + // each entry and the size from its header. For each entry that match + // accepts, it calls visit with the entry's contents, read with the limit + // of ReadFile, or with the error from reading them. A visit error does not + // stop the scan. Scan calls visit for an entry before it calls match for + // the next entry, so match can use what visit found. Scan returns an error + // only if the archive itself cannot be read. + Scan(match func(name string, size int64) bool, visit func(name string, data []byte, err error)) error +} + type zipReader struct { *zip.ReadCloser } +// FileNames returns the names of the entries in the zip archive. Unlike the +// tar reader, it has no size limit: a zip file stores the names uncompressed, +// so they cannot be larger than the file, and zip.OpenReader has already read +// them into memory. func (z *zipReader) FileNames() ([]string, error) { var names []string for _, f := range z.File { @@ -34,6 +71,12 @@ func (z *zipReader) FileNames() ([]string, error) { } func (z *zipReader) ReadFile(name string) ([]byte, error) { + return z.readFile(name, MaxReadSize) +} + +// readFile is ReadFile with limit in place of MaxReadSize, so that a test can +// use a small limit. +func (z *zipReader) readFile(name string, limit int64) ([]byte, error) { for _, f := range z.File { if f.Name == name { rc, err := f.Open() @@ -46,10 +89,10 @@ func (z *zipReader) ReadFile(name string) ([]byte, error) { log.Printf("error closing reader: %v", err) } }(rc) - return io.ReadAll(rc) + return readEntry(rc, name, f.UncompressedSize64, limit) } } - return nil, fmt.Errorf("file not found: %s", name) + return nil, fmt.Errorf("file not found: %s", errtext.Quote(name)) } type tarReader struct { @@ -57,7 +100,19 @@ type tarReader struct { closer io.Closer } +// FileNames returns the names of the entries in the tar archive. Their total +// size, with 16 bytes for each name, may be at most MaxReadSize. +// +// distribution.Parse does not call FileNames for a tar archive: it reads an +// sdist with Scan, and a wheel is a zip archive. The limit is for other +// callers. func (t *tarReader) FileNames() ([]string, error) { + return t.fileNames(MaxReadSize) +} + +// fileNames is FileNames with limit in place of MaxReadSize, so that a test can +// use a small limit. +func (t *tarReader) fileNames(limit int64) ([]string, error) { f, err := os.Open(t.filename) if err != nil { return nil, err @@ -80,7 +135,11 @@ func (t *tarReader) FileNames() ([]string, error) { } tarReader := tar.NewReader(gzr) + // Tar names can each be up to 1 MiB and compress well, so cap their total. + // The 16 bytes per entry count the string header, which matters for many + // short names. var names []string + var size int64 for { hdr, err := tarReader.Next() if err == io.EOF { @@ -89,12 +148,22 @@ func (t *tarReader) FileNames() ([]string, error) { if err != nil { return nil, err } + size += int64(len(hdr.Name)) + 16 + if size > limit { + return nil, fmt.Errorf("%w: entry names are over %d bytes", ErrTooLarge, limit) + } names = append(names, hdr.Name) } return names, nil } func (t *tarReader) ReadFile(name string) ([]byte, error) { + return t.readFile(name, MaxReadSize) +} + +// readFile is ReadFile with limit in place of MaxReadSize, so that a test can +// use a small limit. +func (t *tarReader) readFile(name string, limit int64) ([]byte, error) { f, err := os.Open(t.filename) if err != nil { return nil, err @@ -116,17 +185,100 @@ func (t *tarReader) ReadFile(name string) ([]byte, error) { for { hdr, err := tarReader.Next() if err == io.EOF { - return nil, fmt.Errorf("file not found: %s", name) + return nil, fmt.Errorf("file not found: %s", errtext.Quote(name)) } if err != nil { return nil, err } if hdr.Name == name { - return io.ReadAll(tarReader) + return readEntry(tarReader, name, uint64(max(hdr.Size, 0)), limit) + } + } +} + +// Scan implements Scanner. An entry that is too large does not stop the scan: +// tar.Reader skips the rest of an entry when Next is called. +func (t *tarReader) Scan(match func(name string, size int64) bool, visit func(name string, data []byte, err error)) error { + f, err := os.Open(t.filename) + if err != nil { + return err + } + defer func(f *os.File) { + err := f.Close() + if err != nil { + log.Printf("error closing file: %v", err) + } + }(f) + + gzr, err := gzip.NewReader(f) + if err != nil { + return err + } + tarReader := tar.NewReader(gzr) + for { + hdr, err := tarReader.Next() + if err == io.EOF { + return nil + } + if err != nil { + return err + } + if match(hdr.Name, hdr.Size) { + data, err := readEntry(tarReader, hdr.Name, uint64(max(hdr.Size, 0)), MaxReadSize) + visit(hdr.Name, data, err) + } + } +} + +// readEntry reads at most limit bytes of the entry. It rejects an entry whose +// header size is over the limit before it reads anything, and the LimitReader +// stops a reader that returns more bytes than its header says. The callers +// give MaxReadSize as the limit. Only a test gives a smaller one. +func readEntry(r io.Reader, name string, size uint64, limit int64) ([]byte, error) { + if size > uint64(limit) { + return nil, entryTooLarge(name, limit) + } + data, err := readAllSized(io.LimitReader(r, limit+1), min(size, maxPreallocSize)) + if err != nil { + return nil, err + } + if int64(len(data)) > limit { + return nil, entryTooLarge(name, limit) + } + return data, nil +} + +// maxPreallocSize is the most that readEntry allocates before it reads. A +// zip header's size is not checked until the data is read, so a header that +// claims 64 MiB for a small entry must not allocate 64 MiB. Real METADATA and +// PKG-INFO files are smaller than this, so most reads allocate once. +const maxPreallocSize = 1 << 20 + +// readAllSized is io.ReadAll with a first buffer of size+1 bytes, where size +// is the expected length of r. With the right size, it allocates once: the +// extra byte lets the read that finds EOF fit without growing the buffer. If +// r is longer, the buffer grows as in io.ReadAll. +func readAllSized(r io.Reader, size uint64) ([]byte, error) { + b := make([]byte, 0, size+1) + for { + n, err := r.Read(b[len(b):cap(b)]) + b = b[:len(b)+n] + if err == io.EOF { + return b, nil + } + if err != nil { + return b, err + } + if len(b) == cap(b) { + b = append(b, 0)[:len(b)] } } } +func entryTooLarge(name string, limit int64) error { + return fmt.Errorf("%w: %s is over %d bytes", ErrTooLarge, errtext.Quote(name), limit) +} + func (t *tarReader) Close() error { return t.closer.Close() } @@ -152,9 +304,9 @@ func NewArchiveReader(fqn string) (ArchiveReader, error) { if strings.HasSuffix(fqn, ".tar.gz") || strings.HasSuffix(fqn, ".tgz") { gzr, err := gzip.NewReader(f) if err != nil { - err := f.Close() - if err != nil { - log.Printf("error closing file: %v", err) + cerr := f.Close() + if cerr != nil { + log.Printf("error closing file: %v", cerr) } return nil, err } @@ -174,7 +326,7 @@ func NewArchiveReader(fqn string) (ArchiveReader, error) { if err != nil { log.Printf("error closing file: %v", err) } - return nil, fmt.Errorf("not a known archive format: %s", fqn) + return nil, fmt.Errorf("%w: %s", ErrUnknownFormat, fqn) } // tarReadCheck will attempt to read a header from the tar.Reader to diff --git a/distribution/internal/archiver/archive_reader_test.go b/distribution/internal/archiver/archive_reader_test.go index 2bf5373..eb3b20f 100644 --- a/distribution/internal/archiver/archive_reader_test.go +++ b/distribution/internal/archiver/archive_reader_test.go @@ -5,6 +5,7 @@ package archiver_test import ( "archive/tar" "compress/gzip" + "io" "os" "path/filepath" "runtime" @@ -126,3 +127,28 @@ func TestNewArchiveReader_TarReadCheckFailure_DoesNotLeakFile(t *testing.T) { after := countOpenFDs(t) assert.Equal(t, before, after, "NewArchiveReader must not leak an open file when tarReadCheck fails") } + +// TestNewArchiveReader_BadGzip is a regression test for a bug where +// NewArchiveReader returned a nil reader and a nil error for a .tar.gz that +// is not gzip, so callers crashed on the nil reader. +func TestNewArchiveReader_BadGzip(t *testing.T) { + tests := []struct { + name string + contents string + wantErr error + }{ + {name: "not gzip", contents: "not gzip data", wantErr: gzip.ErrHeader}, + {name: "empty file", contents: "", wantErr: io.EOF}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "example-1.0.0.tar.gz") + require.NoError(t, os.WriteFile(path, []byte(tt.contents), 0o600)) + + reader, err := archiver.NewArchiveReader(path) + require.ErrorIs(t, err, tt.wantErr) + assert.Nil(t, reader) + }) + } +} diff --git a/distribution/internal/archiver/export_test.go b/distribution/internal/archiver/export_test.go new file mode 100644 index 0000000..3d18f66 --- /dev/null +++ b/distribution/internal/archiver/export_test.go @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package archiver + +// TarFileNamesWithin calls FileNames of the tar reader r with limit in place +// of MaxReadSize. With a small limit, a test needs few entries. +func TarFileNamesWithin(r ArchiveReader, limit int64) ([]string, error) { + return r.(*tarReader).fileNames(limit) +} + +// ReadFileWithin calls ReadFile of r with limit in place of MaxReadSize. With +// a small limit, a test needs only small entries. +func ReadFileWithin(r ArchiveReader, name string, limit int64) ([]byte, error) { + return r.(interface { + readFile(name string, limit int64) ([]byte, error) + }).readFile(name, limit) +} diff --git a/distribution/internal/archiver/read_entry_test.go b/distribution/internal/archiver/read_entry_test.go new file mode 100644 index 0000000..64b5236 --- /dev/null +++ b/distribution/internal/archiver/read_entry_test.go @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package archiver + +import ( + "bytes" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestReadEntry_HeaderUndercountsSize checks the LimitReader path: a reader +// that gives more bytes than its header says is still stopped at the limit. +func TestReadEntry_HeaderUndercountsSize(t *testing.T) { + tests := []struct { + name string + size int64 + wantErr bool + }{ + {name: "at limit", size: MaxReadSize}, + {name: "one over limit", size: MaxReadSize + 1, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := readEntry(bytes.NewReader(make([]byte, tt.size)), "PKG-INFO", 0, MaxReadSize) + if tt.wantErr { + require.ErrorIs(t, err, ErrTooLarge) + assert.Nil(t, got) + return + } + require.NoError(t, err) + assert.Len(t, got, int(tt.size)) + }) + } +} + +// readAllSized must return all of r whatever size it is told, and allocate +// once when the size is right. +func TestReadAllSized(t *testing.T) { + data := bytes.Repeat([]byte("0123456789"), 10_000) // 100,000 bytes + for _, size := range []uint64{0, 1, 512, uint64(len(data)) - 1, uint64(len(data)), uint64(len(data)) + 1, 1 << 20} { + got, err := readAllSized(bytes.NewReader(data), size) + require.NoError(t, err, "size %d", size) + assert.Equal(t, data, got, "size %d", size) + } + + got, err := readAllSized(bytes.NewReader(nil), 0) + require.NoError(t, err) + assert.Empty(t, got) + + allocs := testing.AllocsPerRun(10, func() { + _, _ = readAllSized(bytes.NewReader(data), uint64(len(data))) + }) + assert.LessOrEqual(t, allocs, 2.0, "one buffer, and the bytes.Reader") +} + +// A header that claims a large size for a small entry allocates at most +// about maxPreallocSize, not the size it claims. +func TestReadEntry_LyingHeaderPreallocatesAtMostTheCap(t *testing.T) { + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + got, err := readEntry(bytes.NewReader([]byte("small")), "METADATA", MaxReadSize, MaxReadSize) + runtime.ReadMemStats(&after) + require.NoError(t, err) + assert.Equal(t, "small", string(got)) + assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(2*maxPreallocSize), "bytes allocated") +} diff --git a/distribution/internal/archiver/unknown_format_test.go b/distribution/internal/archiver/unknown_format_test.go new file mode 100644 index 0000000..4a2b30e --- /dev/null +++ b/distribution/internal/archiver/unknown_format_test.go @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package archiver + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNewArchiveReader_UnknownFormat(t *testing.T) { + tests := []struct { + name string + filename string + contents string + }{ + {name: "text in a wheel", filename: "foo-1.0-py3-none-any.whl", contents: "not zip data"}, + {name: "empty wheel", filename: "foo-1.0-py3-none-any.whl", contents: ""}, + {name: "text in a zip sdist", filename: "foo-1.0.zip", contents: "not zip data"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), tt.filename) + require.NoError(t, os.WriteFile(path, []byte(tt.contents), 0o600)) + + _, err := NewArchiveReader(path) + require.ErrorIs(t, err, ErrUnknownFormat) + assert.Equal(t, "not a known archive format: "+path, err.Error(), "the message does not change") + }) + } +} diff --git a/distribution/internal/distributions/distribution.go b/distribution/internal/distributions/distribution.go index 7621880..88bbc1b 100644 --- a/distribution/internal/distributions/distribution.go +++ b/distribution/internal/distributions/distribution.go @@ -29,12 +29,28 @@ import ( "strings" "unicode" + "github.com/posit-dev/go-python-packaging/internal/errtext" "golang.org/x/text/encoding/charmap" ) +// parse reads the headers of a METADATA or PKG-INFO file. The errors of +// net/mail and net/textproto show the bad line in full, so parse cuts their +// text (see cutError). func parse(r io.Reader) (*mail.Message, error) { - return mail.ReadMessage(r) + msg, err := mail.ReadMessage(r) + if err != nil { + return nil, cutError{err} + } + return msg, nil } + +// cutError is err with its text cut to errtext.MaxLen bytes, as errtext.Cut +// does. errors.Is and errors.As still find err. A header parser error quotes +// the whole bad line, so a 500 KB line gave an error of 500 KB. +type cutError struct{ err error } + +func (e cutError) Error() string { return errtext.Cut(e.err.Error()) } +func (e cutError) Unwrap() error { return e.err } func getHeaderValue(data *mail.Message, header string) string { return collapseLeadingWS(header, data.Header.Get(header)) } @@ -224,7 +240,7 @@ type BaseDistribution struct { func (bd *BaseDistribution) GetHeaderAttrs() ([]HeaderAttr, error) { ha, exists := HeaderAttrs[bd.MetadataVersion] if !exists { - return []HeaderAttr{}, fmt.Errorf("header attributes for metadata version %s not found", bd.MetadataVersion) + return []HeaderAttr{}, fmt.Errorf("header attributes for metadata version %s not found", errtext.Quote(bd.MetadataVersion)) } return ha, nil diff --git a/distribution/internal/distributions/error_text_test.go b/distribution/internal/distributions/error_text_test.go new file mode 100644 index 0000000..32b4cc6 --- /dev/null +++ b/distribution/internal/distributions/error_text_test.go @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package distributions + +import ( + "archive/zip" + "bytes" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/posit-dev/go-python-packaging/distribution/internal/archiver" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// hostileName is an entry name of 500 KB with a line break and an ANSI escape +// sequence. An error must not show all of it, or its control bytes as they are. +// Found by review: a 64 KB sdist with such a name gave a 1 MB error. +var hostileName = strings.Repeat("a", 500_000) + "\n\x1b[31m" + +// checkErrorText checks that err is short and that it has no raw line break or +// escape byte. errtext.Quote shows at most 200 bytes of each name, quoted. +func checkErrorText(t *testing.T, err error) { + t.Helper() + require.Error(t, err) + msg := err.Error() + assert.Less(t, len(msg), 1000, "error length") + assert.NotContains(t, msg, "\n", "raw line break in the error") + assert.NotContains(t, msg, "\x1b", "raw escape byte in the error") +} + +func TestSDist_EntryNameInErrorIsQuoted(t *testing.T) { + path := writeSDist(t, []tarEntry{{name: hostileName + "PKG-INFO", zeros: archiver.MaxReadSize + 1}}) + _, err := NewSDist(path) + checkErrorText(t, err) + assert.ErrorIs(t, err, archiver.ErrTooLarge) +} + +func TestWheel_EntryNameInErrorIsQuoted(t *testing.T) { + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + // A raw entry with no data, whose header claims more than MaxReadSize: + // ReadFile rejects it before it reads anything. + // A zip entry name may have at most 65,535 bytes. + _, err := zw.CreateRaw(&zip.FileHeader{ + Name: strings.Repeat("a", 60_000) + "\n\x1b[31m.dist-info/METADATA", + Method: zip.Store, + UncompressedSize64: archiver.MaxReadSize + 1, + }) + require.NoError(t, err) + require.NoError(t, zw.Close()) + path := filepath.Join(t.TempDir(), "example-1.0-py3-none-any.whl") + require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600)) + + _, err = NewWheel(path) + checkErrorText(t, err) + assert.ErrorIs(t, err, archiver.ErrTooLarge) +} + +func TestParse_MetadataVersionInErrorIsQuoted(t *testing.T) { + var bd BaseDistribution + err := bd.Parse([]byte("Metadata-Version: " + strings.Repeat("9", 500_000) + "\x1b[31m\n\n")) + checkErrorText(t, err) + assert.Contains(t, err.Error(), "header attributes for metadata version") +} + +// The header parser of net/mail quotes the whole bad line in its error. Found +// after review: a 500 KB line with no ":" gave an error of 500 KB. parse cuts +// the text, and errors.Unwrap still gives the error of net/mail. +func TestParse_MalformedHeaderLineInErrorIsCut(t *testing.T) { + var bd BaseDistribution + err := bd.Parse([]byte("Metadata-Version: 2.1\n" + strings.Repeat("a", 500_000) + "\x1b[31m\n\n")) + checkErrorText(t, err) + assert.Contains(t, err.Error(), "malformed header line") + + inner := errors.Unwrap(err) + require.NotNil(t, inner, "the error of net/mail is in the chain") + assert.Greater(t, len(inner.Error()), 500_000, "the error of net/mail keeps its full text") +} diff --git a/distribution/internal/distributions/fuzz_test.go b/distribution/internal/distributions/fuzz_test.go new file mode 100644 index 0000000..9fe0f70 --- /dev/null +++ b/distribution/internal/distributions/fuzz_test.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package distributions + +import ( + "strings" + "testing" + "time" + "unicode/utf8" + + "github.com/posit-dev/go-python-packaging/internal/fuzzseed" +) + +// metadataSeeds are METADATA documents for the fuzz seed corpus. +var metadataSeeds = []string{ + "Metadata-Version: 2.4\nName: gppfixture-alpha\nVersion: 1.0.0\n" + + "Classifier: Programming Language :: Python :: 3\n" + + "Requires-Dist: gppfixture-shared>=1.0; python_version >= \"3.8\"\n" + + "Provides-Extra: extra-one\nProject-URL: Homepage, https://example.invalid/a\n" + + "License-Expression: MIT\nLicense-File: LICENSE.txt\nDynamic: requires-dist\n" + + "\nFixture alpha description line one.\nLine two.\n", + "Metadata-Version: 2.1\nName: pkg\nVersion: 0.1\nSummary: one\n" + + "Description: first line\n |second line\n |third line\nKeywords: a,b,c\n", + "Metadata-Version: 1.0\nName: old\nVersion: 1\nLicense: UNKNOWN\nPlatform: any\n", + "Metadata-Version: 1.2\r\nName: crlf\r\nVersion: 2.0\r\nRequires-Python: >=3.6\r\n\r\nbody\r\n", + "Metadata-Version: 2.5\nName: n\nVersion: 1\nImport-Name: n\nImport-Namespace: ns\n\n", + "Metadata-Version: 2.2\nName: latin\nVersion: 1\nAuthor: J\xf6rg\n\n", + "Metadata-Version: 9.9\nName: future\nVersion: 1\n\n", + "Name: no-version-header\nVersion: 1\n\n", + "Metadata-Version: 2.1\nName: no-colon-line\nnot a header\n\n", + "\ufeffMetadata-Version: 2.1\nName: bom\nVersion: 1\n\n", +} + +func FuzzParseMetadata(f *testing.F) { + fuzzseed.AddBytes(f, metadataSeeds...) + f.Add([]byte("Metadata-Version: 2.1\nName: big\n" + strings.Repeat("Requires-Dist: a\n", 5000) + "\n")) + f.Add([]byte("Metadata-Version: 2.1\nSummary: " + strings.Repeat("x", 1<<16) + "\n\n")) + f.Add([]byte("Metadata-Version: 2.1\nSummary: x\n" + strings.Repeat(" folded\n", 5000) + "\n")) + + f.Fuzz(func(t *testing.T, in []byte) { + var bd BaseDistribution + start := time.Now() + err := bd.Parse(in) + fuzzseed.Within(t, start, string(in)) + if err != nil { + return + } + if _, ok := HeaderAttrs[bd.MetadataVersion]; !ok { + t.Fatalf("Parse(%q) returned no error with unknown Metadata-Version %q", in, bd.MetadataVersion) + } + for k, vs := range StructToMap(bd) { + for _, v := range vs { + if !utf8.ValidString(v) { + t.Fatalf("Parse(%q) gave field %s an invalid UTF-8 value %q", in, k, v) + } + } + } + }) +} diff --git a/distribution/internal/distributions/metadata.go b/distribution/internal/distributions/metadata.go index c3e297c..1d3e09c 100644 --- a/distribution/internal/distributions/metadata.go +++ b/distribution/internal/distributions/metadata.go @@ -77,7 +77,7 @@ func NewDistributionMetadata(filename string) (Distribution, string, string, err // "bdist_egg": BDist, } if err != nil { - return nil, "", "", fmt.Errorf("invalid distribution file: %s: %v", filepath.Base(filename), err) + return nil, "", "", fmt.Errorf("invalid distribution file: %s: %w", filepath.Base(filename), err) } // If this encounters a metadata version it doesn't support, it may give us diff --git a/distribution/internal/distributions/sdist.go b/distribution/internal/distributions/sdist.go index 421d9d1..ee9eb5e 100644 --- a/distribution/internal/distributions/sdist.go +++ b/distribution/internal/distributions/sdist.go @@ -21,6 +21,7 @@ import ( "strings" "github.com/posit-dev/go-python-packaging/distribution/internal/archiver" + "github.com/posit-dev/go-python-packaging/internal/errtext" ) type SDist struct { @@ -72,6 +73,18 @@ func (sd *SDist) read() ([]byte, error) { } }(archiveReader) // Ensure the archive is closed after reading + if scanner, ok := archiveReader.(archiver.Scanner); ok { + return readPKGInfoInOnePass(scanner, fqn) + } + return readPKGInfoByName(archiveReader, fqn) +} + +// readPKGInfoByName returns the contents of the PKG-INFO with the shortest +// path that holds "Metadata-Version", as twine does. It tries the candidates +// from the shallowest path down, in archive order among paths of the same +// depth, and stops at the first one that holds "Metadata-Version" or that +// fails to read. +func readPKGInfoByName(archiveReader archiver.ArchiveReader, fqn string) ([]byte, error) { fileNames, err := archiveReader.FileNames() if err != nil { return nil, err @@ -84,7 +97,9 @@ func (sd *SDist) read() ([]byte, error) { } } - sort.Slice(tuples, func(i, j int) bool { + // Stable, so paths of the same depth keep archive order, as in twine's + // sorted(), and as readPKGInfoInOnePass picks. + sort.SliceStable(tuples, func(i, j int) bool { return len(tuples[i]) < len(tuples[j]) }) @@ -92,7 +107,7 @@ func (sd *SDist) read() ([]byte, error) { candidate := strings.Join(path, "/") data, err := archiveReader.ReadFile(candidate) if err != nil { - return nil, fmt.Errorf("error reading file %s from archive: %v", candidate, err) + return nil, fmt.Errorf("error reading file %s from archive: %w", errtext.Quote(candidate), err) } if bytes.Contains(data, []byte("Metadata-Version")) { return data, nil @@ -100,3 +115,119 @@ func (sd *SDist) read() ([]byte, error) { } return nil, fmt.Errorf("no PKG-INFO in archive: %s", fqn) } + +// maxScanRead is the most bytes of PKG-INFO candidates that +// readPKGInfoInOnePass reads during its scan. A later candidate can replace +// one that the scan read, so this limits the data that the scan reads and +// then drops. Real PKG-INFO files are a few kilobytes, so they fit. +const maxScanRead = 1 << 20 + +// pkgInfoCandidate is a PKG-INFO candidate: its name, its depth (see +// pathDepth), and its position among the candidates in archive order. +type pkgInfoCandidate struct { + name string + depth int + order int +} + +// pkgInfoScan is the state of the scan in readPKGInfoInOnePass. It is one +// struct, not separate variables, so the scan allocates it once. +type pkgInfoScan struct { + found bool + best pkgInfoCandidate + bestData []byte + bestErr error + current pkgInfoCandidate + order int + scanRead int64 + // deferred holds the candidates that the scan did not read because of + // maxScanRead, in archive order. + deferred []pkgInfoCandidate +} + +// match is the match function of the scan. +func (st *pkgInfoScan) match(name string, size int64) bool { + if !strings.Contains(name, "PKG-INFO") { + return false + } + st.order++ + c := pkgInfoCandidate{name: name, depth: pathDepth(name), order: st.order} + // A candidate at the same depth as the one found, or deeper, cannot + // replace it. Scan calls visit for an entry before it calls match for the + // next one, so found and best are current. + if st.found && c.depth >= st.best.depth { + return false + } + size = max(size, 0) + if size > maxScanRead-st.scanRead { + st.deferred = append(st.deferred, c) + return false + } + st.scanRead += size + st.current = c + return true +} + +// visit is the visit function of the scan. +func (st *pkgInfoScan) visit(_ string, data []byte, err error) { + if err == nil && !bytes.Contains(data, []byte("Metadata-Version")) { + return // the loop would try the next candidate + } + // match accepts only a candidate that replaces best. + st.found, st.best, st.bestData, st.bestErr = true, st.current, data, err +} + +// readPKGInfoInOnePass returns the same result as readPKGInfoByName, from one +// pass over the archive: that function stops at the first candidate, by depth +// and then archive order, that holds "Metadata-Version" or that fails to read. +// So this keeps the first such candidate of the least depth, and only its +// contents. +// +// The scan reads a candidate only if it can replace the one found so far, and +// only while the candidates it reads total at most maxScanRead bytes. It does +// not read a larger candidate. After the scan, it reads each such candidate +// that comes before the one found, by depth and then archive order, with +// ReadFile, as readPKGInfoByName does. Thus it never reads much more than +// readPKGInfoByName, and it reads a normal sdist in one pass. +// +// One difference: when a tar archive has two entries with the same name, +// ReadFile reads the first one for both, but the scan reads each one. +func readPKGInfoInOnePass(scanner archiver.Scanner, fqn string) ([]byte, error) { + st := &pkgInfoScan{} + if err := scanner.Scan(st.match, st.visit); err != nil { + return nil, err + } + + // deferred is in archive order, so a stable sort gives the order of + // readPKGInfoByName. + deferred := st.deferred + sort.SliceStable(deferred, func(i, j int) bool { + return deferred[i].depth < deferred[j].depth + }) + for _, c := range deferred { + if st.found && (c.depth > st.best.depth || c.depth == st.best.depth && c.order > st.best.order) { + break // best comes first + } + data, err := scanner.ReadFile(c.name) + if err != nil { + return nil, fmt.Errorf("error reading file %s from archive: %w", errtext.Quote(c.name), err) + } + if bytes.Contains(data, []byte("Metadata-Version")) { + return data, nil + } + } + + if !st.found { + return nil, fmt.Errorf("no PKG-INFO in archive: %s", fqn) + } + if st.bestErr != nil { + return nil, fmt.Errorf("error reading file %s from archive: %w", errtext.Quote(st.best.name), st.bestErr) + } + return st.bestData, nil +} + +// pathDepth returns the number of parts in the archive path name, as +// readPKGInfoByName counts them. +func pathDepth(name string) int { + return strings.Count(name, "/") + 1 +} diff --git a/distribution/internal/distributions/sdist_one_pass_test.go b/distribution/internal/distributions/sdist_one_pass_test.go new file mode 100644 index 0000000..13b17a5 --- /dev/null +++ b/distribution/internal/distributions/sdist_one_pass_test.go @@ -0,0 +1,360 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package distributions + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "errors" + "fmt" + "io" + "math/rand/v2" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/posit-dev/go-python-packaging/distribution/internal/archiver" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// tarEntry is one file of a test sdist: its text, or zeros bytes of zeros. +type tarEntry struct { + name string + text string + zeros int64 +} + +// zeroReader gives an endless stream of zero bytes. +type zeroReader struct{} + +func (zeroReader) Read(p []byte) (int, error) { + clear(p) + return len(p), nil +} + +// writeSDist writes a .tar.gz with entries, in order, and returns its path. +func writeSDist(t *testing.T, entries []tarEntry) string { + t.Helper() + var buf bytes.Buffer + gzw, err := gzip.NewWriterLevel(&buf, gzip.BestSpeed) + require.NoError(t, err) + tw := tar.NewWriter(gzw) + for _, e := range entries { + size := int64(len(e.text)) + if e.zeros > 0 { + size = e.zeros + } + require.NoError(t, tw.WriteHeader(&tar.Header{Name: e.name, Mode: 0o644, Size: size})) + if e.zeros > 0 { + _, err = io.CopyN(tw, zeroReader{}, e.zeros) + } else { + _, err = tw.Write([]byte(e.text)) + } + require.NoError(t, err) + } + require.NoError(t, tw.Close()) + require.NoError(t, gzw.Close()) + path := filepath.Join(t.TempDir(), "example-1.0.tar.gz") + require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600)) + return path +} + +func metadata(name string) string { + return "Metadata-Version: 2.1\nName: " + name + "\n" +} + +// readPKGInfoInOnePass must pick the same PKG-INFO as readPKGInfoByName, which +// reads the archive once to list it and again for each candidate. +func TestReadPKGInfoInOnePass_MatchesReadByName(t *testing.T) { + // 14 candidates of the same depth: more than sort.Slice keeps in order. + var sameDepth []tarEntry + for i := range 14 { + sameDepth = append(sameDepth, tarEntry{name: fmt.Sprintf("d%d/PKG-INFO", i), text: metadata(fmt.Sprint(i))}) + } + + tests := []struct { + name string + entries []tarEntry + // want is the Name in the chosen PKG-INFO. Empty means an error. + want string + // wantErr is a part of the error text. + wantErr string + // wantErrIs is an error that the error must wrap. + wantErrIs error + }{ + { + name: "shallower path wins over an earlier deeper one", + entries: []tarEntry{ + {name: "pkg/pkg.egg-info/PKG-INFO", text: metadata("deep")}, + {name: "pkg/PKG-INFO", text: metadata("root")}, + }, + want: "root", + }, + { + name: "candidate without Metadata-Version is skipped", + entries: []tarEntry{ + {name: "pkg/PKG-INFO", text: "not metadata"}, + {name: "pkg/pkg.egg-info/PKG-INFO", text: metadata("deep")}, + }, + want: "deep", + }, + { + name: "same depth: first in archive order", + entries: []tarEntry{ + {name: "b/PKG-INFO", text: metadata("first")}, + {name: "a/PKG-INFO", text: metadata("second")}, + }, + want: "first", + }, + { + name: "many candidates of the same depth: first in archive order", + entries: sameDepth, + want: "0", + }, + { + name: "any name that holds PKG-INFO is a candidate", + entries: []tarEntry{ + {name: "pkg/x/PKG-INFO", text: metadata("deep")}, + {name: "pkg/PKG-INFO.bak", text: metadata("bak")}, + }, + want: "bak", + }, + { + name: "too large shallow candidate is an error", + entries: []tarEntry{ + {name: "pkg/PKG-INFO", zeros: archiver.MaxReadSize + 1}, + {name: "pkg/x/PKG-INFO", text: metadata("deep")}, + }, + wantErr: `error reading file "pkg/PKG-INFO" from archive`, + wantErrIs: archiver.ErrTooLarge, + }, + { + name: "too large deeper candidate is not reached", + entries: []tarEntry{ + {name: "pkg/x/PKG-INFO", zeros: archiver.MaxReadSize + 1}, + {name: "pkg/PKG-INFO", text: metadata("root")}, + }, + want: "root", + }, + { + name: "no PKG-INFO", + entries: []tarEntry{{name: "pkg/setup.py", text: "setup()"}}, + wantErr: "no PKG-INFO in archive", + }, + { + name: "no candidate holds Metadata-Version", + entries: []tarEntry{{name: "pkg/PKG-INFO", text: "not metadata"}}, + wantErr: "no PKG-INFO in archive", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := writeSDist(t, tt.entries) + reader, err := archiver.NewArchiveReader(path) + require.NoError(t, err) + defer func() { + require.NoError(t, reader.Close()) + }() + scanner, ok := reader.(archiver.Scanner) + require.True(t, ok, "a tar reader is a Scanner") + + onePass, onePassErr := readPKGInfoInOnePass(scanner, path) + byName, byNameErr := readPKGInfoByName(reader, path) + + if tt.wantErr != "" { + require.Error(t, onePassErr) + require.Error(t, byNameErr) + assert.Equal(t, byNameErr.Error(), onePassErr.Error(), "same error") + assert.Contains(t, onePassErr.Error(), tt.wantErr) + if tt.wantErrIs != nil { + assert.True(t, errors.Is(onePassErr, tt.wantErrIs), "want %v", tt.wantErrIs) + } + return + } + require.NoError(t, onePassErr) + require.NoError(t, byNameErr) + assert.Equal(t, string(byName), string(onePass), "same PKG-INFO") + assert.Equal(t, metadata(tt.want), string(onePass)) + }) + } +} + +// A stream that breaks after the PKG-INFO is still an error, as when the +// whole archive was listed first. +func TestReadPKGInfoInOnePass_BrokenStream(t *testing.T) { + // Random bytes do not compress, so cutting the archive in half cuts + // into this entry, after the PKG-INFO. + noise := make([]byte, 256<<10) + _, err := rand.NewChaCha8([32]byte{1}).Read(noise) + require.NoError(t, err) + path := writeSDist(t, []tarEntry{ + {name: "pkg/PKG-INFO", text: metadata("root")}, + {name: "pkg/noise.bin", text: string(noise)}, + }) + data, err := os.ReadFile(path) + require.NoError(t, err) + require.NoError(t, os.WriteFile(path, data[:len(data)/2], 0o600)) + + reader, err := archiver.NewArchiveReader(path) + require.NoError(t, err) + defer func() { + require.NoError(t, reader.Close()) + }() + _, onePassErr := readPKGInfoInOnePass(reader.(archiver.Scanner), path) + _, byNameErr := readPKGInfoByName(reader, path) + assert.Error(t, onePassErr) + assert.Error(t, byNameErr) +} + +// readRecorder is a Scanner that records the entries that are read: the name +// of each entry that Scan reads, and "ReadFile " and the name for each call +// to ReadFile. +type readRecorder struct { + archiver.Scanner + read []string +} + +func (r *readRecorder) Scan(match func(name string, size int64) bool, visit func(name string, data []byte, err error)) error { + return r.Scanner.Scan(func(name string, size int64) bool { + ok := match(name, size) + if ok { + r.read = append(r.read, name) + } + return ok + }, visit) +} + +func (r *readRecorder) ReadFile(name string) ([]byte, error) { + r.read = append(r.read, "ReadFile "+name) + return r.Scanner.ReadFile(name) +} + +// largeMetadata returns a PKG-INFO for name of more than size bytes. +func largeMetadata(name string, size int) string { + return metadata(name) + strings.Repeat("\n", size) +} + +// readPKGInfoInOnePass reads a candidate only if it can replace the one found +// so far, and it reads at most maxScanRead bytes of candidates in the scan. It +// reads a larger candidate after the scan, only if readPKGInfoByName would +// read it. Before, it read every candidate, so 20 deeper candidates of 32 MiB +// after the root PKG-INFO allocated 3.7 GB, and so did 20 candidates of +// 32 MiB in order of decreasing depth. +func TestReadPKGInfoInOnePass_ReadsOnlyCandidatesThatCanWin(t *testing.T) { + tests := []struct { + name string + entries []tarEntry + wantRead []string + }{ + { + name: "deeper candidates after a good one", + entries: []tarEntry{ + {name: "PKG-INFO", text: metadata("root")}, + {name: "x/PKG-INFO", zeros: 1 << 20}, + {name: "x/PKG-INFO", zeros: 1 << 20}, + }, + wantRead: []string{"PKG-INFO"}, + }, + { + name: "candidates of the same depth after a good one", + entries: []tarEntry{ + {name: "a/PKG-INFO", text: metadata("first")}, + {name: "b/PKG-INFO", text: metadata("second")}, + }, + wantRead: []string{"a/PKG-INFO"}, + }, + { + name: "a candidate without Metadata-Version does not end the search", + entries: []tarEntry{ + {name: "a/PKG-INFO", text: "not metadata"}, + {name: "b/PKG-INFO", text: metadata("second")}, + {name: "c/PKG-INFO", text: metadata("third")}, + }, + wantRead: []string{"a/PKG-INFO", "b/PKG-INFO"}, + }, + { + name: "a shallower candidate after a good one is read", + entries: []tarEntry{ + {name: "pkg/x/PKG-INFO", text: metadata("deep")}, + {name: "pkg/PKG-INFO", text: metadata("root")}, + {name: "pkg/y/PKG-INFO", text: metadata("deep2")}, + }, + wantRead: []string{"pkg/x/PKG-INFO", "pkg/PKG-INFO"}, + }, + { + name: "large candidates of decreasing depth are not read", + entries: []tarEntry{ + {name: "a/b/c/PKG-INFO", text: largeMetadata("c", maxScanRead)}, + {name: "a/b/PKG-INFO", text: largeMetadata("b", maxScanRead)}, + {name: "a/PKG-INFO", text: largeMetadata("a", maxScanRead)}, + {name: "PKG-INFO", text: metadata("root")}, + }, + wantRead: []string{"PKG-INFO"}, + }, + { + name: "a large candidate before the one found is read after the scan", + entries: []tarEntry{ + {name: "x/PKG-INFO", text: metadata("deep")}, + {name: "PKG-INFO", text: largeMetadata("root", maxScanRead)}, + }, + wantRead: []string{"x/PKG-INFO", "ReadFile PKG-INFO"}, + }, + { + name: "large candidates after the scan are read by depth, then archive order", + entries: []tarEntry{ + {name: "a/b/PKG-INFO", text: largeMetadata("deep", maxScanRead)}, + {name: "a/PKG-INFO", text: "not metadata" + strings.Repeat("\n", maxScanRead)}, + {name: "b/PKG-INFO", text: largeMetadata("b", maxScanRead)}, + {name: "c/PKG-INFO", text: largeMetadata("c", maxScanRead)}, + }, + wantRead: []string{"ReadFile a/PKG-INFO", "ReadFile b/PKG-INFO"}, + }, + { + name: "the scan reads at most maxScanRead bytes in all", + entries: []tarEntry{ + {name: "a/b/PKG-INFO", text: largeMetadata("deep", maxScanRead*3/5)}, + {name: "a/PKG-INFO", text: largeMetadata("shallow", maxScanRead*3/5)}, + }, + wantRead: []string{"a/b/PKG-INFO", "ReadFile a/PKG-INFO"}, + }, + { + name: "a large candidate that fails to read is an error", + entries: []tarEntry{ + {name: "a/PKG-INFO", zeros: archiver.MaxReadSize + 1}, + {name: "b/PKG-INFO", text: metadata("second")}, + }, + wantRead: []string{"b/PKG-INFO", "ReadFile a/PKG-INFO"}, + }, + { + name: "a large candidate after the one found is not read", + entries: []tarEntry{ + {name: "a/PKG-INFO", text: metadata("first")}, + {name: "PKG-INFO", text: largeMetadata("root", maxScanRead)}, + {name: "b/PKG-INFO", text: largeMetadata("second", maxScanRead)}, + }, + wantRead: []string{"a/PKG-INFO", "ReadFile PKG-INFO"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := writeSDist(t, tt.entries) + reader, err := archiver.NewArchiveReader(path) + require.NoError(t, err) + defer func() { + require.NoError(t, reader.Close()) + }() + recorder := &readRecorder{Scanner: reader.(archiver.Scanner)} + + onePass, onePassErr := readPKGInfoInOnePass(recorder, path) + byName, byNameErr := readPKGInfoByName(reader, path) + assert.Equal(t, fmt.Sprint(byNameErr), fmt.Sprint(onePassErr), "same error as readPKGInfoByName") + assert.Equal(t, string(byName), string(onePass), "same PKG-INFO as readPKGInfoByName") + assert.Equal(t, tt.wantRead, recorder.read, "entries read") + }) + } +} diff --git a/distribution/internal/distributions/wheel.go b/distribution/internal/distributions/wheel.go index da9aedc..71d57bb 100644 --- a/distribution/internal/distributions/wheel.go +++ b/distribution/internal/distributions/wheel.go @@ -16,12 +16,14 @@ package distributions import ( "bytes" "fmt" - "github.com/posit-dev/go-python-packaging/distribution/internal/archiver" "log" "path/filepath" "regexp" "sort" "strings" + + "github.com/posit-dev/go-python-packaging/distribution/internal/archiver" + "github.com/posit-dev/go-python-packaging/internal/errtext" ) var wheelFileRe = regexp.MustCompile(`^(?P(?P.+?)(-(?P\d.+?))?)(?:(-(?P\d.*?))?-(?P.+?)-(?P.+?)-(?P.+?)\.whl|\.dist-info)$`) @@ -97,7 +99,7 @@ func (whl *Wheel) read() ([]byte, error) { candidate := strings.Join(path, "/") data, err := archiveReader.ReadFile(candidate) if err != nil { - return nil, fmt.Errorf("error reading file %s from archive: %v", candidate, err) + return nil, fmt.Errorf("error reading file %s from archive: %w", errtext.Quote(candidate), err) } if bytes.Contains(data, []byte("Metadata-Version")) { return data, nil diff --git a/distribution/parse.go b/distribution/parse.go index c000150..d2730ac 100644 --- a/distribution/parse.go +++ b/distribution/parse.go @@ -74,7 +74,7 @@ func findDistributions(dists []string) ([]string, error) { func makePackage(filename string, signatures map[string]string) (*types.PackageFile, error) { packageFile, err := packages.NewPackageFile(filename) if err != nil { - return nil, fmt.Errorf("unable to parse %s, path may not point to a valid Python package: %v", filename, err) + return nil, fmt.Errorf("unable to parse %s, path may not point to a valid Python package: %w", filename, err) } signedName := packageFile.SignedBaseFilename diff --git a/distribution/parse_errors_test.go b/distribution/parse_errors_test.go new file mode 100644 index 0000000..7b8acbd --- /dev/null +++ b/distribution/parse_errors_test.go @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package distribution_test + +import ( + "archive/zip" + "bytes" + "compress/gzip" + "io" + "io/fs" + "os" + "path/filepath" + "testing" + + distribution "github.com/posit-dev/go-python-packaging/distribution" + "github.com/stretchr/testify/require" +) + +const corruptMetadata = "Metadata-Version: 2.1\nName: gppfixture-corrupt\nVersion: 1.0.0\n" + +// writeCorruptWheel writes a wheel whose METADATA entry is stored without +// compression, then changes one byte of it, so its CRC-32 does not match. +func writeCorruptWheel(t *testing.T, path string) { + t.Helper() + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + w, err := zw.CreateHeader(&zip.FileHeader{ + Name: "gppfixture_corrupt-1.0.0.dist-info/METADATA", + Method: zip.Store, + }) + require.NoError(t, err) + _, err = w.Write([]byte(corruptMetadata)) + require.NoError(t, err) + require.NoError(t, zw.Close()) + + data := buf.Bytes() + i := bytes.Index(data, []byte("gppfixture-corrupt")) + require.GreaterOrEqual(t, i, 0, "stored METADATA is in the file") + data[i] = 'G' + require.NoError(t, os.WriteFile(path, data, 0o600)) +} + +// When the METADATA entry cannot be read, Parse returns an error that wraps +// the cause, so errors.Is can match it. +func TestParse_CorruptWheelEntry(t *testing.T) { + path := filepath.Join(t.TempDir(), "gppfixture_corrupt-1.0.0-py3-none-any.whl") + writeCorruptWheel(t, path) + + _, err := distribution.Parse(path) + require.Error(t, err) + require.ErrorIs(t, err, zip.ErrChecksum) +} + +// When an archive cannot be opened, Parse returns an error and does not panic. +// When the error has a cause, Parse wraps it, so errors.Is can match it. +func TestParse_ArchiveOpenErrors(t *testing.T) { + tests := []struct { + name string + filename string + contents []byte + // wantErr is the cause the error must wrap. Nil means do not check. + wantErr error + // wantMsg is a substring of the error. + wantMsg string + }{ + { + name: "sdist that is not gzip", + filename: "gppfixture_bad-1.0.0.tar.gz", + contents: []byte("not gzip data"), + wantErr: gzip.ErrHeader, + wantMsg: "error getting archive", + }, + { + // Before the fix, this panicked. + name: "empty sdist", + filename: "gppfixture_bad-1.0.0.tar.gz", + contents: nil, + wantErr: io.EOF, + wantMsg: "error getting archive", + }, + { + name: "wheel that is not a zip", + filename: "gppfixture_bad-1.0.0-py3-none-any.whl", + contents: []byte("not zip data"), + wantErr: distribution.ErrUnknownArchiveFormat, + wantMsg: "not a known archive format", + }, + { + name: "empty wheel", + filename: "gppfixture_bad-1.0.0-py3-none-any.whl", + contents: nil, + wantErr: distribution.ErrUnknownArchiveFormat, + wantMsg: "not a known archive format", + }, + { + // Parse accepts ".tar.gz" but not ".tgz", so it never opens this file. + name: "tgz is not a known distribution format", + filename: "gppfixture_bad-1.0.0.tgz", + contents: nil, + wantMsg: "unknown distribution format", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), tt.filename) + require.NoError(t, os.WriteFile(path, tt.contents, 0o600)) + + require.NotPanics(t, func() { + _, err := distribution.Parse(path) + require.Error(t, err) + require.Contains(t, err.Error(), tt.wantMsg) + if tt.wantErr != nil { + require.ErrorIs(t, err, tt.wantErr) + } + }) + }) + } +} + +// A wheel that cannot be opened gives an error that wraps the cause. +func TestParse_UnreadableWheel(t *testing.T) { + path := filepath.Join(t.TempDir(), "gppfixture_locked-1.0.0-py3-none-any.whl") + require.NoError(t, os.WriteFile(path, []byte("x"), 0o000)) + if f, err := os.Open(path); err == nil { + _ = f.Close() + t.Skip("the file is readable without permission (for example, the tests run as root)") + } + + _, err := distribution.Parse(path) + require.Error(t, err) + require.Contains(t, err.Error(), "error getting archive") + require.ErrorIs(t, err, fs.ErrPermission) +} diff --git a/distribution/parse_fixture_test.go b/distribution/parse_fixture_test.go index 7cbf07c..e9afaca 100644 --- a/distribution/parse_fixture_test.go +++ b/distribution/parse_fixture_test.go @@ -14,6 +14,7 @@ import ( "testing" distribution "github.com/posit-dev/go-python-packaging/distribution" + "github.com/posit-dev/go-python-packaging/distribution/internal/archiver" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/crypto/blake2b" @@ -450,3 +451,95 @@ func TestParse_WheelMetadata25(t *testing.T) { } assert.Equal(t, want, got) } + +// TestParse_MetadataTooLarge checks that Parse keeps the archive error, so +// callers can match distribution.ErrTooLarge with errors.Is. +func TestParse_MetadataTooLarge(t *testing.T) { + tooLarge := strings.Repeat("\x00", archiver.MaxReadSize+1) + + tests := []struct { + name string + filename string + write func(t *testing.T, path string, entries []fixtureEntry) + entry string + }{ + { + name: "wheel", + filename: "gppfixture_big-1.0.0-py3-none-any.whl", + write: writeWheelFixture, + entry: "gppfixture_big-1.0.0.dist-info/METADATA", + }, + { + name: "sdist", + filename: "gppfixture_big-1.0.0.tar.gz", + write: writeSDistFixture, + entry: "gppfixture_big-1.0.0/PKG-INFO", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), tt.filename) + tt.write(t, path, []fixtureEntry{{name: tt.entry, contents: tooLarge}}) + + _, err := distribution.Parse(path) + require.ErrorIs(t, err, distribution.ErrTooLarge) + }) + } +} + +// Parse reads the GPG signature file next to a distribution. A signature file +// over 1 MiB is an error that wraps distribution.ErrTooLarge, so callers can +// match it with errors.Is, as for a METADATA file that is too large. +func TestParse_SignatureSizeLimit(t *testing.T) { + const maxSignatureSize = 1 << 20 + + tests := []struct { + name string + size int + wantErr bool + }{ + { + name: "small signature", + size: 1024, + }, + { + name: "signature at the limit", + size: maxSignatureSize, + }, + { + name: "signature one byte over the limit", + size: maxSignatureSize + 1, + wantErr: true, + }, + { + name: "very large signature", + size: 16 * maxSignatureSize, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + wheel := "gppfixture_signed-1.0.0-py3-none-any.whl" + writeWheelFixture(t, filepath.Join(dir, wheel), []fixtureEntry{{ + name: "gppfixture_signed-1.0.0.dist-info/METADATA", + contents: "Metadata-Version: 2.1\nName: gppfixture-signed\nVersion: 1.0.0\n", + }}) + signature := make([]byte, tt.size) + require.NoError(t, os.WriteFile(filepath.Join(dir, wheel+".asc"), signature, 0o600)) + + packages, err := distribution.Parse(dir) + if tt.wantErr { + require.ErrorIs(t, err, distribution.ErrTooLarge) + assert.Contains(t, err.Error(), `GPG signature "`+wheel+`.asc" is over 1048576 bytes`) + return + } + require.NoError(t, err) + require.Len(t, packages, 1) + require.NotNil(t, packages[0].GPGSignature, "Parse adds the signature") + assert.Len(t, packages[0].GPGSignature.Bytes, tt.size) + }) + } +} diff --git a/distribution/types/signature_test.go b/distribution/types/signature_test.go new file mode 100644 index 0000000..ba3e194 --- /dev/null +++ b/distribution/types/signature_test.go @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package types + +import ( + "os" + "path/filepath" + "testing" + + "github.com/posit-dev/go-python-packaging/distribution/internal/archiver" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAddGPGSignature_SizeLimit(t *testing.T) { + tests := []struct { + name string + size int + wantErr bool + }{ + {name: "small signature", size: 1024}, + {name: "signature at the limit", size: maxSignatureSize}, + {name: "signature one byte over the limit", size: maxSignatureSize + 1, wantErr: true}, + {name: "very large signature", size: 16 * maxSignatureSize, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "foo.whl.asc") + require.NoError(t, os.WriteFile(path, make([]byte, tt.size), 0o600)) + + var pf PackageFile + err := pf.AddGPGSignature(path, "foo.whl.asc") + if tt.wantErr { + require.Error(t, err) + // distribution.ErrTooLarge is archiver.ErrTooLarge. + assert.ErrorIs(t, err, archiver.ErrTooLarge) + assert.Contains(t, err.Error(), `GPG signature "foo.whl.asc" is over 1048576 bytes`) + assert.Nil(t, pf.GPGSignature) + return + } + require.NoError(t, err) + require.NotNil(t, pf.GPGSignature) + assert.Len(t, pf.GPGSignature.Bytes, tt.size) + }) + } +} + +func TestAddGPGSignature_ReadErrors(t *testing.T) { + tests := []struct { + name string + path func(t *testing.T) string + }{ + { + name: "missing file", + path: func(t *testing.T) string { return filepath.Join(t.TempDir(), "missing.asc") }, + }, + { + // A directory opens without an error, but reading it fails. + name: "directory", + path: func(t *testing.T) string { return t.TempDir() }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var pf PackageFile + err := pf.AddGPGSignature(tt.path(t), "foo.whl.asc") + require.Error(t, err) + assert.Nil(t, pf.GPGSignature) + }) + } +} + +// A signature can be added only once. +func TestAddGPGSignature_OnlyOnce(t *testing.T) { + path := filepath.Join(t.TempDir(), "foo.whl.asc") + require.NoError(t, os.WriteFile(path, []byte("sig"), 0o600)) + + var pf PackageFile + require.NoError(t, pf.AddGPGSignature(path, "foo.whl.asc")) + err := pf.AddGPGSignature(path, "foo.whl.asc") + require.Error(t, err) + assert.Contains(t, err.Error(), "can only be added once") +} diff --git a/distribution/types/types.go b/distribution/types/types.go index 8d1d076..c476f9a 100644 --- a/distribution/types/types.go +++ b/distribution/types/types.go @@ -14,11 +14,14 @@ package types import ( "errors" + "fmt" "io" "log" "os" + "github.com/posit-dev/go-python-packaging/distribution/internal/archiver" "github.com/posit-dev/go-python-packaging/distribution/internal/distributions" + "github.com/posit-dev/go-python-packaging/internal/errtext" "github.com/samber/lo" ) @@ -81,6 +84,13 @@ func (pf *PackageFile) MetadataMap() map[string][]string { return result } +// maxSignatureSize is the maximum size of a GPG signature file. An +// ASCII-armored signature is about 1 KB. +const maxSignatureSize = 1 << 20 + +// AddGPGSignature reads the GPG signature file at signatureFilepath. It returns +// an error that wraps distribution.ErrTooLarge if the file is larger than +// 1 MiB. func (pf *PackageFile) AddGPGSignature(signatureFilepath string, signatureFilename string) error { if pf.GPGSignature != nil { return errors.New("GPG Signature can only be added once") @@ -97,10 +107,14 @@ func (pf *PackageFile) AddGPGSignature(signatureFilepath string, signatureFilena } }(gpg) - bytes, err := io.ReadAll(gpg) + bytes, err := io.ReadAll(io.LimitReader(gpg, maxSignatureSize+1)) if err != nil { return err } + if len(bytes) > maxSignatureSize { + return fmt.Errorf("%w: GPG signature %s is over %d bytes", + archiver.ErrTooLarge, errtext.Quote(signatureFilename), maxSignatureSize) + } pf.GPGSignature = &Signature{ Filename: signatureFilename, diff --git a/extras/fuzz_test.go b/extras/fuzz_test.go new file mode 100644 index 0000000..9594383 --- /dev/null +++ b/extras/fuzz_test.go @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package extras_test + +import ( + "strings" + "testing" + "time" + + "github.com/posit-dev/go-python-packaging/extras" + "github.com/posit-dev/go-python-packaging/internal/fuzzseed" + "github.com/posit-dev/go-python-packaging/packagename" +) + +func FuzzNormalize(f *testing.F) { + fuzzseed.Add(f, "Foo_Bar", "a.b__c", "A---B", "..foo..", "tests", "Dev.Extra_Name", "Security") + + f.Fuzz(func(t *testing.T, in string) { + start := time.Now() + got := extras.Normalize(in) + fuzzseed.Within(t, start, in) + if again := extras.Normalize(got); again != got { + t.Fatalf("not idempotent: Normalize(%q) = %q, then %q", in, got, again) + } + if p := packagename.Normalize(in); p != got { + t.Fatalf("extras.Normalize(%q) = %q but packagename.Normalize = %q", in, got, p) + } + if strings.ContainsAny(got, "_.") || strings.Contains(got, "--") { + t.Fatalf("Normalize(%q) = %q still has separators to collapse", in, got) + } + }) +} diff --git a/internal/allocbudget/allocbudget.go b/internal/allocbudget/allocbudget.go new file mode 100644 index 0000000..38dd7bc --- /dev/null +++ b/internal/allocbudget/allocbudget.go @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Package allocbudget checks how many times a function allocates. Only +// _test.go files import it. +// +// An allocation count does not depend on the machine or its load, unlike a +// time, so a budget test is exact and can run in normal CI. Most slowdowns +// also add allocations: each regression found in the review of PR #71 did. +package allocbudget + +import ( + "math" + "testing" + + "github.com/posit-dev/go-python-packaging/internal/race" +) + +// runs is the number of calls that AllocsPerRun averages over. +const runs = 20 + +// Check fails t unless f allocates budget times per call, within a tolerance +// of 0.1% of budget, rounded down. So a budget under 1,000 is exact. +// +// The tolerance is there because a count is not always exact: Go's maps grow +// at a point that depends on a random hash seed, so code that builds a map on +// each call can allocate one more or one fewer time from run to run. A large +// budget is a call that builds many maps or entries, and a regression there +// adds an allocation for each entry, far more than 0.1%. +// +// More allocations is a regression: find the new allocation, or raise the +// budget if the change needs it. Fewer is an improvement: lower the budget, +// so that the next regression is caught. Either way, the message gives the +// new count. +// +// Check skips under the race detector, which adds allocations of its own. +// CI also runs the tests without it. +func Check(t testing.TB, budget float64, f func()) { + t.Helper() + CheckWithin(t, budget, math.Floor(budget/1000), f) +} + +// CheckWithin is Check with an explicit tolerance, for code whose count varies +// more than Check allows. For example, code that gets a buffer from a +// sync.Pool allocates a new one after a garbage collection empties the pool, +// which happens at no fixed point. Say why at the call. +func CheckWithin(t testing.TB, budget, tolerance float64, f func()) { + t.Helper() + if race.Enabled { + t.Skip("the race detector adds allocations") + } + got := testing.AllocsPerRun(runs, f) + switch { + case got > budget+tolerance: + t.Errorf("allocates %v times per call, over its budget of %v: find the new allocation, "+ + "or raise the budget to %v if it is needed", got, budget, got) + case got < budget-tolerance: + t.Errorf("allocates %v times per call, under its budget of %v: lower the budget to %v, "+ + "so that the next regression is caught", got, budget, got) + } +} diff --git a/internal/errtext/errtext.go b/internal/errtext/errtext.go new file mode 100644 index 0000000..8ec2d1d --- /dev/null +++ b/internal/errtext/errtext.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Package errtext shortens input text that an error message shows, so one +// long input cannot make a very large error. +package errtext + +import ( + "fmt" + "strconv" + "unicode/utf8" +) + +// MaxLen is the maximum number of bytes of input text that an error shows. +const MaxLen = 200 + +// Cut returns input s unchanged when it is less than or equal to MaxLen bytes. A longer s is cut +// to its first MaxLen bytes, followed by "..." and followed by the input's length. +func Cut(s string) string { + if len(s) <= MaxLen { + return s + } + return fmt.Sprintf("%s... (%d bytes)", s[:cutIndex(s)], len(s)) +} + +// Quote is like Cut, but quotes the text like %q. +func Quote(s string) string { + if len(s) <= MaxLen { + return strconv.Quote(s) + } + return fmt.Sprintf("%s... (%d bytes)", strconv.Quote(s[:cutIndex(s)]), len(s)) +} + +// cutIndex returns where to cut s: MaxLen, or less so that a multi-byte +// character is not cut in two. s must be longer than MaxLen. +// +// A character is at most utf8.UTFMax bytes, so the cut moves back at most +// utf8.UTFMax-1 bytes. If there is no character start in that range, the bytes +// are not valid UTF-8 and the cut splits no character. Without this limit, a +// long run of continuation bytes moves the cut to 0, and the error shows none +// of the input. +func cutIndex(s string) int { + i := MaxLen + for i > MaxLen-(utf8.UTFMax-1) && !utf8.RuneStart(s[i]) { + i-- + } + return i +} diff --git a/internal/errtext/errtext_test.go b/internal/errtext/errtext_test.go new file mode 100644 index 0000000..441eee9 --- /dev/null +++ b/internal/errtext/errtext_test.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package errtext + +import ( + "strconv" + "strings" + "testing" + "unicode/utf8" + + "github.com/stretchr/testify/assert" +) + +func TestCutAndQuote(t *testing.T) { + atMax := strings.Repeat("a", MaxLen) + // "€" is 3 bytes. Byte 200 is inside a character, so the cut moves back to 199. + multiByte := "a" + strings.Repeat("€", 100) + // "😀" is 4 bytes. Byte 200 is its last byte, so the cut moves back 3 bytes to 197. + fourByte := strings.Repeat("a", 197) + strings.Repeat("😀", 2) + // Continuation bytes only: not valid UTF-8, and no byte starts a character. + // The cut moves back at most 3 bytes, to 197, and not to 0. + continuation := strings.Repeat("\x80", 300) + + tests := []struct { + name string + input string + wantCut string + wantQuote string + }{ + { + name: "empty", + input: "", + wantCut: "", + wantQuote: `""`, + }, + { + name: "short", + input: "abc", + wantCut: "abc", + wantQuote: `"abc"`, + }, + { + name: "escapes", + input: "a\"b\n", + wantCut: "a\"b\n", + wantQuote: `"a\"b\n"`, + }, + { + name: "at limit", + input: atMax, + wantCut: atMax, + wantQuote: strconv.Quote(atMax), + }, + { + name: "one byte over limit", + input: atMax + "b", + wantCut: atMax + "... (201 bytes)", + wantQuote: strconv.Quote(atMax) + "... (201 bytes)", + }, + { + name: "2 MB", + input: strings.Repeat("a", 2_000_000), + wantCut: atMax + "... (2000000 bytes)", + wantQuote: strconv.Quote(atMax) + "... (2000000 bytes)", + }, + { + name: "cut inside a multi-byte character", + input: multiByte, + wantCut: multiByte[:199] + "... (301 bytes)", + wantQuote: strconv.Quote(multiByte[:199]) + "... (301 bytes)", + }, + { + name: "cut inside a 4-byte character", + input: fourByte, + wantCut: fourByte[:197] + "... (205 bytes)", + wantQuote: strconv.Quote(fourByte[:197]) + "... (205 bytes)", + }, + { + name: "continuation bytes", + input: continuation, + wantCut: continuation[:197] + "... (300 bytes)", + wantQuote: strconv.Quote(continuation[:197]) + "... (300 bytes)", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gotCut := Cut(tt.input) + assert.Equal(t, tt.wantCut, gotCut, "Cut") + if utf8.ValidString(tt.input) { + assert.True(t, utf8.ValidString(gotCut), "Cut result is valid UTF-8") + } + assert.Equal(t, tt.wantQuote, Quote(tt.input), "Quote") + }) + } +} diff --git a/internal/fuzzseed/fuzzseed.go b/internal/fuzzseed/fuzzseed.go new file mode 100644 index 0000000..bd6894e --- /dev/null +++ b/internal/fuzzseed/fuzzseed.go @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Package fuzzseed holds the hostile seed inputs and checks that the +// module's fuzz tests share. Only _test.go files import it. +package fuzzseed + +import ( + "strings" + "testing" + "time" + + "github.com/posit-dev/go-python-packaging/internal/race" +) + +// MaxDuration is the longest one parser call may take on one input. It is +// generous so that a busy fuzz worker does not fail by chance. +const MaxDuration = 2 * time.Second + +// fragments are short hostile strings. Strings puts each one before, inside, +// and after every valid seed. +var fragments = []string{ + "\x00", // NUL + "\xff", // never valid UTF-8 + "\xc3", // truncated 2-byte sequence + "\xc3\x28", // bad continuation byte + "\xed\xa0\x80", // encoded UTF-16 surrogate + "\ufeff", // byte order mark + "\u202e", // right-to-left override + "\u2066", // left-to-right isolate + "\u200b", // zero width space + "\u2028", // line separator + "\u0085", // next line (NEL) + "\u00a0", // no-break space + "\r\n", "\r", "\n", "\t", "\v", "\f", + "\x1b", "\x7f", "\x01", + "\\", "\"", "'", "#", ";", "@", ",", "[", "]", "(", ")", "==", "${A}", + "\uff11", // fullwidth digit one + "\u0661", // Arabic-Indic digit one + "\u0130", // Latin capital I with dot above (lowercases to 2 runes) + "\u212a", // Kelvin sign (lowercases to ASCII k) + "\U0001F600", // 4-byte rune +} + +// long are large hostile inputs. Strings adds each one alone and appended to +// the first valid seed. +var long = []string{ + strings.Repeat("a", 1<<14), + strings.Repeat(" ", 1<<14), + strings.Repeat("(", 5000), + strings.Repeat(")", 5000), + strings.Repeat("[", 5000), + strings.Repeat("9", 5000), + strings.Repeat("0", 5000) + "1", + strings.Repeat("1.", 5000) + "1", + strings.Repeat("-", 5000), + strings.Repeat(".", 5000), + strings.Repeat("_", 5000), + strings.Repeat("\\\n", 2000), + strings.Repeat("\xff", 4096), + strings.Repeat("\u202e", 1000), + strings.Repeat("\x00", 4096), + "18446744073709551616", // 2^64 + "9223372036854775808", // 2^63 + "99999999999999999999999999999999999999999999999999", +} + +// Strings returns the valid seeds, the hostile seeds, and each valid seed +// mixed with each short hostile fragment. +func Strings(valid ...string) []string { + out := append([]string{""}, valid...) + out = append(out, fragments...) + out = append(out, long...) + for _, v := range valid { + mid := len(v) / 2 + for _, frag := range fragments { + out = append(out, frag+v, v[:mid]+frag+v[mid:], v+frag) + } + } + if len(valid) > 0 { + for _, l := range long { + out = append(out, valid[0]+l) + } + } + return out +} + +// Add adds every string from Strings(valid...) to f's seed corpus. +func Add(f *testing.F, valid ...string) { + for _, s := range Strings(valid...) { + f.Add(s) + } +} + +// AddBytes is Add for a fuzz target that takes []byte. +func AddBytes(f *testing.F, valid ...string) { + for _, s := range Strings(valid...) { + f.Add([]byte(s)) + } +} + +// Within fails t if a call that began at start ran longer than MaxDuration. +// It does not check the time when the race detector is on (see package race). +func Within(t testing.TB, start time.Time, in string) { + t.Helper() + if race.Enabled { + return + } + if d := time.Since(start); d > MaxDuration { + t.Fatalf("took %v (limit %v) on a %d-byte input: %.200q", d, MaxDuration, len(in), in) + } +} diff --git a/internal/pep508/marker.go b/internal/pep508/marker.go index fd68823..59d72e3 100644 --- a/internal/pep508/marker.go +++ b/internal/pep508/marker.go @@ -16,6 +16,7 @@ import ( "fmt" "strconv" "strings" + "unicode/utf8" "github.com/posit-dev/go-python-packaging/extras" ) @@ -135,19 +136,94 @@ func (Literal) markerOperand() {} func (l Literal) String() string { return quoteLiteral(l.Value) } // quoteLiteral renders a literal's value back into PEP 508 quoted-string -// syntax. We do not EMIT escape sequences, so a value containing a double -// quote is rendered single-quoted instead; a value containing both quote -// characters cannot be round-tripped (packaging has the same limitation). +// syntax that parses back to the same value. A quoted string ends at the next +// quote of the same kind, so escapes cannot hide it. The rules are: +// - a backslash is written as `\\`, because the parser decodes escapes; +// - a value with a double quote is written single-quoted; +// - a value with both quote characters is written double-quoted, with each +// double quote written as `\x22`; +// - each line break is written as an escape, such as `\n` or `\u2028`, +// so that the literal stays on one line. // -// Note this is about what we emit, not what we accept: upstream runs the token -// through ast.literal_eval, so Python string escapes ARE valid on input (see -// Token.Unquoted and decodeQuotedStringContents). Do not use this comment as -// grounds for removing the escape decoding/validation. +// Other characters are written unchanged. A requirements file also needs an +// escape for a "#" or "-" after whitespace, but package reqtxt adds it. So a +// value that needs none of the escapes above stays readable by tools that do +// not decode escapes, such as packaging before 22.0. +// +// Python string escapes are valid on input (upstream runs the token through +// ast.literal_eval; see Token.Unquoted and decodeQuotedStringContents). func quoteLiteral(v string) string { - if strings.Contains(v, `"`) { + if plainLiteral(v) { + return `"` + v + `"` + } + v = strings.ReplaceAll(v, `\`, `\\`) + v = escapeLineBreaks(v) + switch { + case !strings.Contains(v, `"`): + return `"` + v + `"` + case !strings.Contains(v, "'"): return "'" + v + "'" + default: + return `"` + strings.ReplaceAll(v, `"`, `\x22`) + `"` + } +} + +// plainLiteral reports whether quoteLiteral writes v unchanged in double +// quotes: v is printable ASCII with no backslash and no double quote, so it +// needs no escape. Most literals are, and this one pass over the bytes skips +// the other passes of quoteLiteral. +func plainLiteral(v string) bool { + for i := 0; i < len(v); i++ { + if c := v[i]; c < ' ' || c > '~' || c == '\\' || c == '"' { + return false + } + } + return true +} + +// isLineBreak reports whether r has an escape in lineBreakEscapes. +func isLineBreak(r rune) bool { + _, ok := lineBreakEscapes[r] + return ok +} + +// lineBreakEscapes are the escapes for each character that Python's +// str.splitlines() reads as a line break. +var lineBreakEscapes = map[rune]string{ + '\n': `\n`, + '\r': `\r`, + '\v': `\v`, + '\f': `\f`, + '\x1c': `\x1c`, + '\x1d': `\x1d`, + '\x1e': `\x1e`, + '\u0085': `\x85`, + '\u2028': `\u2028`, + '\u2029': `\u2029`, +} + +// escapeLineBreaks writes each line break as an escape (see quoteLiteral). A +// byte that is not valid UTF-8 is written unchanged, so the literal parses +// back to the same value. +func escapeLineBreaks(v string) string { + if !strings.ContainsFunc(v, isLineBreak) { + return v + } + var b strings.Builder + for i, r := range v { + esc, isBreak := lineBreakEscapes[r] + switch { + case r == utf8.RuneError && !strings.HasPrefix(v[i:], string(utf8.RuneError)): + // range gives RuneError for each byte that is not valid UTF-8. + // WriteRune would write U+FFFD in its place. + b.WriteByte(v[i]) + case isBreak: + b.WriteString(esc) + default: + b.WriteRune(r) + } } - return `"` + v + `"` + return b.String() } // envVarAliases maps every deprecated/legacy Variable-token spelling the @@ -265,6 +341,12 @@ func groupByPrecedence(atoms []Expr, ops []LogicalOp) Expr { return &BoolExpr{Op: Or, Operands: orOperands} } +// MaxMarkerDepth is the maximum number of nested "(" groups in a marker. +// The parser recurses once for each "(", so this limit avoids excessive +// recursive calls that can lead to performance degradation or resource +// consumption. +const MaxMarkerDepth = 100 + // parseMarkerAtom parses packaging's _parse_marker_atom: an optional // parenthesized sub-expression, or a single marker item (comparison), with // optional surrounding whitespace. @@ -272,9 +354,17 @@ func parseMarkerAtom(t *Tokenizer) (Expr, error) { t.consume(WS) var atom Expr if t.check(LParen) { + start := t.pos t.read() + if t.depth >= MaxMarkerDepth { + return nil, t.NewSyntaxErrorAt( + fmt.Sprintf("Marker has more than %d nested parentheses", MaxMarkerDepth), start, t.pos, + ) + } + t.depth++ t.consume(WS) inner, err := ParseMarker(t) + t.depth-- if err != nil { return nil, err } diff --git a/internal/pep508/marker_test.go b/internal/pep508/marker_test.go index 6c60f70..e62eb9f 100644 --- a/internal/pep508/marker_test.go +++ b/internal/pep508/marker_test.go @@ -372,3 +372,167 @@ func TestParseMarker_QuotedStringRejectsMalformedUnicodeEscape(t *testing.T) { _, err := ParseMarker(tok) assert.Error(t, err) } + +// escapeLineBreaks writes each character that Python's str.splitlines() reads +// as a line break as an escape, so that a literal stays on one line. It writes +// every other character unchanged, also a byte that is not valid UTF-8. +// decodeQuotedStringContents, which the parser uses, must read each result +// back to the input. +func TestEscapeLineBreaks(t *testing.T) { + tests := []struct { + name string + input string + want string + }{ + // Text with no line break is not changed. + { + name: "empty", + input: "", + want: "", + }, + { + name: "plain text", + input: "linux 5.4-generic #1", + want: "linux 5.4-generic #1", + }, + { + // Quotes are for quoteLiteral, not for escapeLineBreaks. + name: "quotes", + input: `a"b'c`, + want: `a"b'c`, + }, + + // Each line break of str.splitlines(). + { + name: "line feed", + input: "a\nb", + want: `a\nb`, + }, + { + name: "carriage return", + input: "a\rb", + want: `a\rb`, + }, + { + name: "vertical tab", + input: "a\vb", + want: `a\vb`, + }, + { + name: "form feed", + input: "a\fb", + want: `a\fb`, + }, + { + name: "file separator U+001C", + input: "a\x1cb", + want: `a\x1cb`, + }, + { + name: "group separator U+001D", + input: "a\x1db", + want: `a\x1db`, + }, + { + name: "record separator U+001E", + input: "a\x1eb", + want: `a\x1eb`, + }, + { + name: "next line U+0085", + input: "a\u0085b", + want: `a\x85b`, + }, + { + name: "line separator U+2028", + input: "a\u2028b", + want: `a\u2028b`, + }, + { + name: "paragraph separator U+2029", + input: "a\u2029b", + want: `a\u2029b`, + }, + + // Combinations of line breaks. + { + // A CRLF pair is two characters, so it gets two escapes. + name: "carriage return and line feed", + input: "a\r\nb", + want: `a\r\nb`, + }, + { + name: "only line breaks", + input: "\n\n", + want: `\n\n`, + }, + { + name: "line breaks at the start and the end", + input: "\u2028a\x1c", + want: `\u2028a\x1c`, + }, + + // Characters that are not line breaks are not changed. + { + name: "tab", + input: "a\tb", + want: "a\tb", + }, + { + // U+001F is next to U+001C to U+001E, but it is not a line break. + name: "unit separator U+001F", + input: "a\x1fb", + want: "a\x1fb", + }, + { + // U+0084 is next to U+0085, but it is not a line break. + name: "U+0084", + input: "a\u0084b", + want: "a\u0084b", + }, + { + name: "no-break space and ideographic space", + input: "a\u00a0b\u3000c", + want: "a\u00a0b\u3000c", + }, + { + name: "non-ASCII letters", + input: "é😀", + want: "é😀", + }, + + // A byte that is not valid UTF-8 is written unchanged, not as U+FFFD. + { + name: "invalid byte", + input: "a\xffb", + want: "a\xffb", + }, + { + name: "truncated two-byte sequence", + input: "a\xc3", + want: "a\xc3", + }, + { + name: "invalid byte next to a line break", + input: "\xff\n\xfe", + want: "\xff\\n\xfe", + }, + { + // A real U+FFFD in the input is valid UTF-8 and stays U+FFFD. + name: "replacement character U+FFFD", + input: "a\ufffdb", + want: "a\ufffdb", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := escapeLineBreaks(tt.input) + assert.Equal(t, tt.want, got) + + decoded, err := decodeQuotedStringContents(got) + require.NoError(t, err) + assert.Equal(t, tt.input, decoded, "the decoder reads the result back to the input") + }) + } +} diff --git a/internal/pep508/quote_fast_path_test.go b/internal/pep508/quote_fast_path_test.go new file mode 100644 index 0000000..5a0c5e6 --- /dev/null +++ b/internal/pep508/quote_fast_path_test.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package pep508 + +import ( + "strings" + "testing" + "unicode/utf8" + + "github.com/stretchr/testify/assert" +) + +// slowQuoteLiteral is quoteLiteral without its plainLiteral fast path. +func slowQuoteLiteral(v string) string { + v = strings.ReplaceAll(v, `\`, `\\`) + v = escapeLineBreaks(v) + switch { + case !strings.Contains(v, `"`): + return `"` + v + `"` + case !strings.Contains(v, "'"): + return "'" + v + "'" + default: + return `"` + strings.ReplaceAll(v, `"`, `\x22`) + `"` + } +} + +// slowEscapeLineBreaks is escapeLineBreaks without its fast path. +func slowEscapeLineBreaks(v string) string { + var b strings.Builder + for i, r := range v { + esc, isBreak := lineBreakEscapes[r] + switch { + case r == utf8.RuneError && !strings.HasPrefix(v[i:], string(utf8.RuneError)): + b.WriteByte(v[i]) + case isBreak: + b.WriteString(esc) + default: + b.WriteRune(r) + } + } + return b.String() +} + +// The fast paths in quoteLiteral and escapeLineBreaks must not change any +// result: each input is quoted as the slow path quotes it. +func TestQuoteLiteral_FastPathMatchesSlowPath(t *testing.T) { + pieces := []string{ + "a", "0", " ", "~", "#", "-", "'", "\"", "\\", "\t", "\n", "\r", "\v", + "\x1c", "\x1f", "\x00", "\x7f", "\u0085", "\u00a0", "\u2028", "\u00e9", + "\xff", "\xc2", "\xe2\x80", + } + inputs := []string{""} + for _, a := range pieces { + inputs = append(inputs, a) + for _, b := range pieces { + inputs = append(inputs, a+b) + for _, c := range pieces { + inputs = append(inputs, a+b+c) + } + } + } + for _, v := range inputs { + if got, want := quoteLiteral(v), slowQuoteLiteral(v); got != want { + t.Errorf("quoteLiteral(%q) = %q, want %q", v, got, want) + } + if got, want := escapeLineBreaks(v), slowEscapeLineBreaks(v); got != want { + t.Errorf("escapeLineBreaks(%q) = %q, want %q", v, got, want) + } + } + for _, v := range []string{"", "posix", "3.8", "a b", "x86_64", "it's", "~=1"} { + assert.True(t, plainLiteral(v), "%q", v) + } + for _, v := range []string{`a"b`, `a\b`, "a\tb", "a\x7f", "caf\u00e9"} { + assert.False(t, plainLiteral(v), "%q", v) + } +} diff --git a/internal/pep508/requirement.go b/internal/pep508/requirement.go index 90309cf..266ee15 100644 --- a/internal/pep508/requirement.go +++ b/internal/pep508/requirement.go @@ -12,7 +12,11 @@ package pep508 -import "strings" +import ( + "strings" + + "github.com/posit-dev/go-python-packaging/internal/pyspace" +) // RawRequirement is the raw, structurally-parsed result of a PEP 508 // requirement string, before the public requirement/ package applies name @@ -217,9 +221,10 @@ func parseVersionSpec(t *Tokenizer) (string, error) { // canonical, whitespace-free clause for joining into the raw specifier // string handed to version.NewSpecifiers - which is agnostic to whether // the input had that whitespace, but round-tripping a canonical form is -// cleaner than preserving arbitrary user spacing verbatim. +// cleaner than preserving arbitrary user spacing verbatim. The whitespace is +// Python's (see package pyspace), the same as the Specifier rule allows. func normalizeSpecifierClause(s string) string { - return strings.Join(strings.Fields(s), "") + return strings.Join(strings.FieldsFunc(s, pyspace.IsSpace), "") } // parseMarkerClause parses packaging's "quoted_marker" (';' wsp* marker) if diff --git a/internal/pep508/syntax_error_test.go b/internal/pep508/syntax_error_test.go new file mode 100644 index 0000000..5fd3c3b --- /dev/null +++ b/internal/pep508/syntax_error_test.go @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package pep508 + +import ( + "strings" + "testing" + "unicode/utf8" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSyntaxError_ErrorText(t *testing.T) { + long := strings.Repeat("a", 2000) + atMax := strings.Repeat("a", maxErrorSource) + // "€" is 3 bytes, so the window edges fall inside a character. + multiByte := strings.Repeat("€", 700) + // "😀" is 4 bytes, the longest UTF-8 character. + fourByte := strings.Repeat("😀", 500) + // Continuation bytes only: not valid UTF-8, and no byte starts a character. + continuation := strings.Repeat("\x80", 2000) + dots := "..." + + tests := []struct { + name string + err SyntaxError + wantSource string + wantMarker string + }{ + // A source of at most maxErrorSource bytes is shown in full. + { + name: "short source", + err: SyntaxError{Source: "and banana", Start: 4, End: 10}, + wantSource: "and banana", + wantMarker: " ~~~~~~^", + }, + { + name: "source at maxErrorSource", + err: SyntaxError{Source: atMax, Start: 1000, End: 1001}, + wantSource: atMax, + wantMarker: strings.Repeat(" ", 1000) + "~^", + }, + + // A longer source is cut around the error span. + { + name: "error at start", + err: SyntaxError{Source: long, Start: 0, End: 0}, + wantSource: strings.Repeat("a", errorContext) + dots, + wantMarker: "^", + }, + { + name: "error in middle", + err: SyntaxError{Source: long, Start: 1000, End: 1001}, + wantSource: dots + strings.Repeat("a", 2*errorContext+1) + dots, + wantMarker: strings.Repeat(" ", len(dots)+errorContext) + "~^", + }, + { + name: "error at end", + err: SyntaxError{Source: long, Start: 2000, End: 2000}, + wantSource: dots + strings.Repeat("a", errorContext), + wantMarker: strings.Repeat(" ", len(dots)+errorContext) + "^", + }, + { + name: "long span is cut", + err: SyntaxError{Source: long, Start: 100, End: 1900}, + wantSource: dots + strings.Repeat("a", 2*errorContext+maxErrorSpan) + dots, + wantMarker: strings.Repeat(" ", len(dots)+errorContext) + strings.Repeat("~", maxErrorSpan) + "^", + }, + { + name: "start after end of source", + err: SyntaxError{Source: long, Start: 5000, End: 5000}, + wantSource: dots + strings.Repeat("a", errorContext), + wantMarker: strings.Repeat(" ", len(dots)+errorContext) + "^", + }, + { + name: "negative start", + err: SyntaxError{Source: long, Start: -5, End: 1}, + wantSource: strings.Repeat("a", 1+errorContext) + dots, + wantMarker: "~^", + }, + { + // The window grows to whole characters: 1120 becomes 1122, 1283 becomes 1284. + name: "multi-byte characters at window edges", + err: SyntaxError{Source: multiByte, Start: 1200, End: 1203}, + wantSource: dots + multiByte[1122:1284] + dots, + wantMarker: strings.Repeat(" ", len(dots)+1200-1122) + "~~~^", + }, + { + // Each edge moves 3 bytes, the most that a valid character needs: + // 921 becomes 924, 1081 becomes 1084. + name: "4-byte characters at window edges", + err: SyntaxError{Source: fourByte, Start: 1001, End: 1001}, + wantSource: dots + fourByte[924:1084] + dots, + wantMarker: strings.Repeat(" ", len(dots)+1001-924) + "^", + }, + { + // Each edge moves at most 3 bytes, so a long run of continuation + // bytes does not move it to the end of the source: 920 becomes 923, + // 1081 becomes 1084. + name: "continuation bytes at window edges", + err: SyntaxError{Source: continuation, Start: 1000, End: 1001}, + wantSource: dots + continuation[923:1084] + dots, + wantMarker: strings.Repeat(" ", len(dots)+1000-923) + "~^", + }, + + // The size limit: one byte over maxErrorSource is cut. + { + name: "source at maxErrorSource+1", + err: SyntaxError{Source: atMax + "a", Start: 1000, End: 1001}, + wantSource: dots + (atMax + "a")[1000-errorContext:], + wantMarker: strings.Repeat(" ", len(dots)+errorContext) + "~^", + }, + + // The edges where "..." starts and stops. + { + name: "error errorContext bytes from start has no leading dots", + err: SyntaxError{Source: long, Start: errorContext, End: errorContext + 1}, + wantSource: strings.Repeat("a", 2*errorContext+1) + dots, + wantMarker: strings.Repeat(" ", errorContext) + "~^", + }, + { + name: "error errorContext+1 bytes from start has leading dots", + err: SyntaxError{Source: long, Start: errorContext + 1, End: errorContext + 2}, + wantSource: dots + strings.Repeat("a", 2*errorContext+1) + dots, + wantMarker: strings.Repeat(" ", len(dots)+errorContext) + "~^", + }, + { + name: "error errorContext bytes from end has no trailing dots", + err: SyntaxError{Source: long, Start: len(long) - errorContext - 1, End: len(long) - errorContext}, + wantSource: dots + strings.Repeat("a", 2*errorContext+1), + wantMarker: strings.Repeat(" ", len(dots)+errorContext) + "~^", + }, + { + name: "error errorContext+1 bytes from end has trailing dots", + err: SyntaxError{Source: long, Start: len(long) - errorContext - 2, End: len(long) - errorContext - 1}, + wantSource: dots + strings.Repeat("a", 2*errorContext+1) + dots, + wantMarker: strings.Repeat(" ", len(dots)+errorContext) + "~^", + }, + + // The span cut. + { + name: "span of maxErrorSpan is not cut", + err: SyntaxError{Source: long, Start: 1000, End: 1000 + maxErrorSpan}, + wantSource: dots + strings.Repeat("a", 2*errorContext+maxErrorSpan) + dots, + wantMarker: strings.Repeat(" ", len(dots)+errorContext) + strings.Repeat("~", maxErrorSpan) + "^", + }, + { + name: "span of maxErrorSpan+1 is cut", + err: SyntaxError{Source: long, Start: 1000, End: 1000 + maxErrorSpan + 1}, + wantSource: dots + strings.Repeat("a", 2*errorContext+maxErrorSpan) + dots, + wantMarker: strings.Repeat(" ", len(dots)+errorContext) + strings.Repeat("~", maxErrorSpan) + "^", + }, + { + // The span cut at 1280 is inside a character. The window end grows + // from 1360 to 1362, so the source line stays valid UTF-8. + name: "span cut inside a multi-byte character", + err: SyntaxError{Source: multiByte, Start: 1200, End: 1500}, + wantSource: dots + multiByte[1122:1362] + dots, + wantMarker: strings.Repeat(" ", len(dots)+1200-1122) + strings.Repeat("~", maxErrorSpan) + "^", + }, + + // End before Start marks only Start, and does not panic. + { + name: "end before start, short source", + err: SyntaxError{Source: "and banana", Start: 6, End: 2}, + wantSource: "and banana", + wantMarker: " ^", + }, + { + name: "end before start, long source", + err: SyntaxError{Source: long, Start: 1000, End: 900}, + wantSource: dots + strings.Repeat("a", 2*errorContext) + dots, + wantMarker: strings.Repeat(" ", len(dots)+errorContext) + "^", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.err.Msg = "Expected something" + text := tt.err.Error() + if utf8.ValidString(tt.err.Source) { + assert.True(t, utf8.ValidString(text), "error text is valid UTF-8") + } + + lines := strings.Split(text, "\n") + require.Len(t, lines, 3, "Msg + source + marker line") + assert.Equal(t, tt.err.Msg, lines[0]) + assert.Equal(t, tt.wantSource, lines[1], "source line") + assert.Equal(t, tt.wantMarker, lines[2], "marker line") + }) + } +} + +// A huge input gives a short error text. +func TestSyntaxError_ErrorTextIsSmallForHugeInput(t *testing.T) { + continuation := strings.Repeat("\x80", 2_000_000) + tests := []struct { + name string + parse func(*Tokenizer) error + input string + }{ + { + name: "marker", + parse: func(t *Tokenizer) error { _, err := ParseFullMarker(t); return err }, + input: strings.Repeat("(", 2_000_000), + }, + { + name: "requirement, continuation bytes after the error", + parse: func(t *Tokenizer) error { _, err := ParseRequirement(t); return err }, + input: "foo[" + continuation, + }, + { + name: "requirement, continuation bytes before the error", + parse: func(t *Tokenizer) error { _, err := ParseRequirement(t); return err }, + input: continuation + "foo", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.parse(NewTokenizer(tt.input)) + require.Error(t, err) + assert.Less(t, len(err.Error()), 1000) + }) + } +} diff --git a/internal/pep508/tokenizer.go b/internal/pep508/tokenizer.go index 0725acc..0157a05 100644 --- a/internal/pep508/tokenizer.go +++ b/internal/pep508/tokenizer.go @@ -16,6 +16,9 @@ import ( "fmt" "regexp" "strings" + "unicode/utf8" + + "github.com/posit-dev/go-python-packaging/internal/pyspace" ) // Kind identifies a lexical token kind recognized by the Tokenizer. @@ -237,7 +240,18 @@ var tokenRules = map[Kind]*regexp.Regexp{ // That means "<1.0!=2.0" tokenizes as "<1.0!" and then fails on the // leftover "=2.0" rather than at the fusion point, which is a worse error // message for the same correct verdict. - Specifier: regexp.MustCompile(`\A(?:===\s*[^\s,;)]+|(?:==|~=|!=|<=|>=|<|>)\s*[^\s,;)<>=~]+)`), + // + // Whitespace is Python's "\s" (see package pyspace), not Go's \s + // ([\t\n\f\r ]), because upstream's pattern runs on a str. Upstream allows + // it only between the operator and the version, so "foo>=\v1.0" parses + // there. After the version, only the WS rule ([ \t]+) applies, so + // "foo>=1.0\v" and "foo>=1.0\u00a0" are errors. So the version run stops + // at any Python whitespace: with Go's \s, it took the "\v" or U+00A0 into + // the version, and package version then trimmed it, so both parsed. + Specifier: regexp.MustCompile( + `\A(?:===` + pyspace.Class + `*[^` + pyspace.Chars + `,;)]+|(?:==|~=|!=|<=|>=|<|>)` + + pyspace.Class + `*[^` + pyspace.Chars + `,;)<>=~]+)`, + ), // URL: a greedy run of non-horizontal-whitespace characters, matching // upstream packaging's own URL rule ([^ \t]+) exactly - it stops only // at a space or tab, not at a line break. It is deliberately not @@ -258,6 +272,8 @@ type Tokenizer struct { source string pos int next *Token + // depth counts the marker "(" groups that are open now. + depth int } // NewTokenizer returns a Tokenizer positioned at the start of source. @@ -348,13 +364,55 @@ type SyntaxError struct { End int } +// Limits on the source text that Error shows. A source of at most +// maxErrorSource bytes is shown in full. A longer source is cut to +// errorContext bytes on each side of the error span, and the span is cut to +// maxErrorSpan bytes, so one bad line cannot make a very large message. +const ( + maxErrorSource = 1024 + errorContext = 80 + maxErrorSpan = 80 +) + func (e *SyntaxError) Error() string { - width := e.End - e.Start - if width < 0 { - width = 0 + source, start, end := e.Source, e.Start, e.End + if len(source) > maxErrorSource { + source, start, end = errorWindow(source, start, end) + } + width := max(end-start, 0) + marker := strings.Repeat(" ", max(start, 0)) + strings.Repeat("~", width) + "^" + return e.Msg + "\n" + source + "\n" + marker +} + +// errorWindow returns the part of source around the span [start, end), with +// "..." where text was cut, and the span's position in that part. +func errorWindow(source string, start, end int) (string, int, int) { + start = min(max(start, 0), len(source)) + end = min(max(end, start), len(source), start+maxErrorSpan) + + lo := max(start-errorContext, 0) + hi := min(end+errorContext, len(source)) + // Do not cut a multi-byte character in two. A character is at most + // utf8.UTFMax bytes, so each edge moves at most utf8.UTFMax-1 bytes. If + // there is no character start in that range, the bytes are not valid + // UTF-8 and the cut splits no character. Without this limit, a long run + // of continuation bytes moves an edge to the end of the source. + for i := 0; i < utf8.UTFMax-1 && lo < start && !utf8.RuneStart(source[lo]); i++ { + lo++ + } + for i := 0; i < utf8.UTFMax-1 && hi < len(source) && !utf8.RuneStart(source[hi]); i++ { + hi++ + } + + prefix, suffix := "", "" + if lo > 0 { + prefix = "..." + } + if hi < len(source) { + suffix = "..." } - marker := strings.Repeat(" ", max(e.Start, 0)) + strings.Repeat("~", width) + "^" - return e.Msg + "\n" + e.Source + "\n" + marker + shift := len(prefix) - lo + return prefix + source[lo:hi] + suffix, start + shift, end + shift } // NewSyntaxError builds a *SyntaxError for message at the tokenizer's diff --git a/internal/pyspace/pyspace.go b/internal/pyspace/pyspace.go new file mode 100644 index 0000000..f17d472 --- /dev/null +++ b/internal/pyspace/pyspace.go @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Package pyspace holds Python's whitespace: the characters for which +// str.isspace() is true. They are also the characters that str.strip() +// removes, and that "\s" matches in a str pattern of Python's re package. +// Go's unicode.IsSpace has all of them except U+001C to U+001F, and Go's +// regexp "\s" has only [\t\n\f\r ]. +package pyspace + +import ( + "strings" + "unicode" +) + +// IsSpace reports whether r is Python whitespace: a character of +// unicode.IsSpace, or U+001C to U+001F, which Python also counts because their +// bidirectional class is B or S. +func IsSpace(r rune) bool { + return unicode.IsSpace(r) || (r >= '\x1c' && r <= '\x1f') +} + +// Trim returns s without Python whitespace at its start and end, as Python's +// str.strip() does. +func Trim(s string) string { + return strings.TrimFunc(s, IsSpace) +} + +// Chars is the inside of a Go regexp character class, with no brackets, that +// matches the same characters as IsSpace. Use Class in place of Python's "\s", +// and "[^" + Chars + "...]" in place of "[^\s...]". +const Chars = `\t\n\v\f\r \x{1c}-\x{1f}\x{85}\x{a0}\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}` + +// Class is a Go regexp character class that matches one Python whitespace +// character, as "\s" does in Python. +const Class = "[" + Chars + "]" diff --git a/internal/pyspace/pyspace_test.go b/internal/pyspace/pyspace_test.go new file mode 100644 index 0000000..e66751a --- /dev/null +++ b/internal/pyspace/pyspace_test.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package pyspace + +import ( + "regexp" + "testing" + "unicode/utf8" + + "github.com/stretchr/testify/assert" +) + +// pythonSpace is every code point for which str.isspace() is true, from +// Python 3.9.6 (Unicode 13.0.0): +// +// [c for c in range(0x110000) if chr(c).isspace()] +// +// In that Python, re's "\s" matches the same list, and str.strip() removes +// each one. +var pythonSpace = []rune{ + 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x001C, 0x001D, 0x001E, 0x001F, + 0x0020, 0x0085, 0x00A0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, + 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x2028, 0x2029, 0x202F, + 0x205F, 0x3000, +} + +// Every code point is checked, so a change in Go's unicode tables, or a +// mistake in Chars, shows up here. +func TestIsSpaceAndClassMatchPython(t *testing.T) { + want := make(map[rune]bool, len(pythonSpace)) + for _, r := range pythonSpace { + want[r] = true + } + class := regexp.MustCompile(`\A` + Class + `\z`) + + for r := rune(0); r <= utf8.MaxRune; r++ { + if !utf8.ValidRune(r) { + continue // a surrogate, which a Go string cannot hold + } + if got := IsSpace(r); got != want[r] { + t.Errorf("IsSpace(%U) = %v, want %v", r, got, want[r]) + } + if got := class.MatchString(string(r)); got != want[r] { + t.Errorf("Class matches %U: %v, want %v", r, got, want[r]) + } + } +} + +func TestTrim(t *testing.T) { + tests := []struct { + name, in, want string + }{ + {"ASCII whitespace", " \t\n\v\f\r1.0 \t\n\v\f\r", "1.0"}, + {"unit separators", "\x1c\x1d1.0\x1e\x1f", "1.0"}, + {"Unicode whitespace", "\u00a0\u20281.0\u3000\u0085", "1.0"}, + {"whitespace inside is kept", "a\u00a0b", "a\u00a0b"}, + {"other control characters are kept", "\x00\x1b1.0\x7f", "\x00\x1b1.0\x7f"}, + {"zero width space is not whitespace", "\u200b1.0", "\u200b1.0"}, + {"invalid UTF-8 is kept", "\xff1.0", "\xff1.0"}, + {"only whitespace", " \x1f\u00a0", ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, Trim(tt.in)) + }) + } +} diff --git a/internal/race/doc.go b/internal/race/doc.go new file mode 100644 index 0000000..d91c974 --- /dev/null +++ b/internal/race/doc.go @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Package race reports whether the race detector is on. Tests use it to skip +// wall-clock limits: the race detector makes some code, such as package +// regexp, 10 to 30 times slower. CI also runs the same tests without the race +// detector, so the limits are still checked. +package race diff --git a/internal/race/norace.go b/internal/race/norace.go new file mode 100644 index 0000000..9f13710 --- /dev/null +++ b/internal/race/norace.go @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//go:build !race + +package race + +// Enabled is true when the binary was built with -race. +const Enabled = false diff --git a/internal/race/race.go b/internal/race/race.go new file mode 100644 index 0000000..2639c71 --- /dev/null +++ b/internal/race/race.go @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//go:build race + +package race + +// Enabled is true when the binary was built with -race. +const Enabled = true diff --git a/marker/bench_test.go b/marker/bench_test.go new file mode 100644 index 0000000..14175d2 --- /dev/null +++ b/marker/bench_test.go @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "testing" + + "github.com/posit-dev/go-python-packaging/internal/allocbudget" +) + +// Benchmarks and allocation budgets for the hot paths of this package. The +// budget tests run in CI and fail on any change in allocations; the +// benchmarks are for comparing a branch with main (see CLAUDE.md, +// "Performance"). + +// benchMarkers are markers of common shapes. parse, str and eval are the +// allocation budgets of Parse, String and Evaluate. +var benchMarkers = []struct { + name, in string + parse, str, eval float64 +}{ + {name: "one comparison", in: `python_version >= "3.8"`, parse: 20, str: 2, eval: 36}, + {name: "and", in: `python_version >= "3.8" and os_name == "posix"`, parse: 44, str: 5, eval: 36}, + { + name: "nested", + in: `extra == "test" or (platform_machine == 'x86_64' and implementation_name == "cpython")`, + parse: 77, str: 8, eval: 2, + }, + {name: "literal with both quotes", in: `platform_version == "it's \x22quoted\x22"`, parse: 21, str: 3, eval: 0}, +} + +// benchEnv is a CPython 3.11 environment on Linux. +var benchEnv = Environment{ + OsName: "posix", + SysPlatform: "linux", + PlatformMachine: "x86_64", + PlatformPythonImplementation: "CPython", + PlatformRelease: "6.1.0", + PlatformSystem: "Linux", + PlatformVersion: "#1 SMP", + PythonVersion: "3.11", + PythonFullVersion: "3.11.4", + ImplementationName: "cpython", + ImplementationVersion: "3.11.4", +} + +func BenchmarkParse(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + for _, m := range benchMarkers { + if _, err := Parse(m.in); err != nil { + b.Fatal(err) + } + } + } +} + +func BenchmarkString(b *testing.B) { + markers := parseBenchMarkers(b) + b.ReportAllocs() + for b.Loop() { + for _, m := range markers { + _ = m.String() + } + } +} + +func BenchmarkEvaluate(b *testing.B) { + markers := parseBenchMarkers(b) + b.ReportAllocs() + for b.Loop() { + for _, m := range markers { + _ = m.Evaluate(benchEnv, []string{"test"}) + } + } +} + +func parseBenchMarkers(tb testing.TB) []Marker { + tb.Helper() + markers := make([]Marker, len(benchMarkers)) + for i, m := range benchMarkers { + var err error + if markers[i], err = Parse(m.in); err != nil { + tb.Fatal(err) + } + } + return markers +} + +func TestAllocBudget_Parse(t *testing.T) { + parseBenchMarkers(t) // each input must parse, so the budget is not an error path + for _, m := range benchMarkers { + t.Run(m.name, func(t *testing.T) { + allocbudget.Check(t, m.parse, func() { _, _ = Parse(m.in) }) + }) + } +} + +func TestAllocBudget_String(t *testing.T) { + markers := parseBenchMarkers(t) + for i, m := range benchMarkers { + t.Run(m.name, func(t *testing.T) { + allocbudget.Check(t, m.str, func() { _ = markers[i].String() }) + }) + } +} + +func TestAllocBudget_Evaluate(t *testing.T) { + markers := parseBenchMarkers(t) + extras := []string{"test"} + for i, m := range benchMarkers { + t.Run(m.name, func(t *testing.T) { + allocbudget.Check(t, m.eval, func() { _ = markers[i].Evaluate(benchEnv, extras) }) + }) + } +} diff --git a/marker/env_value_not_version_test.go b/marker/env_value_not_version_test.go new file mode 100644 index 0000000..8f5b531 --- /dev/null +++ b/marker/env_value_not_version_test.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// When the operator and the literal of a version comparison form a valid +// specifier, the specifier decides, as packaging's +// Specifier(f"{op}{rhs}").contains(lhs, prereleases=True) does, also when the +// other side is not a version. A value that is not a version then matches +// nothing, except under "===", which compares the text as written, ignoring +// case. Before, such a value fell back to the string operators, so the rows +// marked "changed" gave the opposite result. +// +// Each want was measured with packaging 26.2 and 26.3. +func TestEvaluate_VersionKeyValueNotAVersion(t *testing.T) { + tests := []struct { + expr string + env map[string]string + want bool + }{ + {`python_version != "3.11"`, map[string]string{"python_version": "garbage"}, false}, // changed + {`"garbage" != python_version`, map[string]string{"python_version": "3.11"}, false}, // changed + {`platform_release != "5.0"`, map[string]string{"platform_release": ""}, false}, // changed + {`platform_release != "6.1.0"`, map[string]string{"platform_release": "6.1.0-generic"}, false}, // changed + {`python_version === "garbage"`, map[string]string{"python_version": "garbage"}, true}, // changed + {`python_version === "GARBAGE"`, map[string]string{"python_version": "garbage"}, true}, // changed + {`platform_release === "6.1.0-generic"`, map[string]string{"platform_release": "6.1.0-generic"}, true}, // changed + {`python_full_version === "3.11.4"`, map[string]string{"python_full_version": "3.11.04"}, false}, // changed + {`python_version === "v3.11"`, map[string]string{"python_version": "v3.11"}, true}, // changed + {`python_version === "3.11"`, map[string]string{"python_version": "v3.11"}, false}, // changed + {`python_version === "v3.11"`, map[string]string{"python_version": "3.11"}, false}, + {`"3.11" === python_version`, map[string]string{"python_version": "3.11"}, true}, + {`"garbage" === python_version`, map[string]string{"python_version": "3.11"}, false}, + {`python_version == "3.11"`, map[string]string{"python_version": "garbage"}, false}, + {`python_version ~= "3.1"`, map[string]string{"python_version": "garbage"}, false}, + {`"garbage" < python_version`, map[string]string{"python_version": "3.11"}, false}, + {`platform_release >= "5"`, map[string]string{"platform_release": "6.1.0-generic"}, false}, + // No valid specifier, so the string operators still decide. + {`python_version >= "garbage"`, map[string]string{"python_version": "garbage"}, true}, + {`python_version != "garbage"`, map[string]string{"python_version": "garbage"}, false}, + {`python_version in "garbage3.11"`, map[string]string{"python_version": "garbage"}, true}, + {`platform_release == ""`, map[string]string{"platform_release": ""}, true}, + {`platform_release != ""`, map[string]string{"platform_release": ""}, false}, + } + for _, tt := range tests { + t.Run(tt.expr, func(t *testing.T) { + env, err := baseEnv().With(tt.env) + if err != nil { + t.Fatal(err) + } + assert.Equal(t, tt.want, evalStr(t, tt.expr, env, nil)) + }) + } +} diff --git a/marker/evaluate.go b/marker/evaluate.go index 7ee59ca..7873c43 100644 --- a/marker/evaluate.go +++ b/marker/evaluate.go @@ -55,8 +55,9 @@ func (m Marker) Evaluate(env Environment, extraList []string) bool { // - `~=` or `===` reaches the generic string-operator table, which has no // semantics for them (evalStringOp returns false; packaging raises // UndefinedComparison). Note this cannot happen when either operand is -// version-typed and both sides parse as PEP 440 versions, because the -// specifier path answers first and answers correctly. +// version-typed and the operator and the right-hand value form a valid +// specifier, because the specifier path answers first and answers +// correctly. // // Ordered comparisons on string operands are NOT undecidable: `<` and `>` // returning false and `<=`/`>=` collapsing to equality is faithful to @@ -71,12 +72,29 @@ func (m Marker) EvaluateUndecidable(env Environment, extraList []string) (bool, if m.ast == nil { return true, nil } - active := normalizeExtraSet(extraList) + active := &activeExtras{list: extraList} var und []Undecidable result := evalExpr(m.ast, env, active, &und) return result, und } +// activeExtras is the caller's list of active extras, normalized into a set +// the first time an `extra` comparison needs it. Most markers never compare +// `extra`, and those skip the set and its allocation. +type activeExtras struct { + list []string + set map[string]struct{} +} + +// has reports whether the normalized extra name is active. +func (a *activeExtras) has(name string) bool { + if a.set == nil { + a.set = normalizeExtraSet(a.list) + } + _, ok := a.set[name] + return ok +} + // normalizeExtraSet normalizes each active extra name (extras.Normalize) at // evaluation time and returns it as a membership set. The literal side of an // `extra` comparison is already normalized once at parse time (see @@ -92,7 +110,7 @@ func normalizeExtraSet(extraList []string) map[string]struct{} { // evalExpr walks the marker AST: a *pep508.BoolExpr short-circuits its // "and"/"or" operands, a *pep508.CompareExpr evaluates a single comparison. -func evalExpr(e pep508.Expr, env Environment, active map[string]struct{}, und *[]Undecidable) bool { +func evalExpr(e pep508.Expr, env Environment, active *activeExtras, und *[]Undecidable) bool { switch n := e.(type) { case *pep508.BoolExpr: return evalBool(n, env, active, und) @@ -104,7 +122,7 @@ func evalExpr(e pep508.Expr, env Environment, active map[string]struct{}, und *[ } } -func evalBool(n *pep508.BoolExpr, env Environment, active map[string]struct{}, und *[]Undecidable) bool { +func evalBool(n *pep508.BoolExpr, env Environment, active *activeExtras, und *[]Undecidable) bool { switch n.Op { case pep508.And: for _, operand := range n.Operands { @@ -128,10 +146,11 @@ func evalBool(n *pep508.BoolExpr, env Environment, active map[string]struct{}, u // evalCompare implements the unified per-comparison dispatch ported from // packaging's _eval_op: `extra` comparisons are set-membership (rule 3); // otherwise a version comparison is attempted whenever either operand names -// one of the four version-typed variables (rule 1), falling back on any -// failure - or immediately, for any other variable - to a single generic -// string-operator table (rule 2). -func evalCompare(n *pep508.CompareExpr, env Environment, active map[string]struct{}, und *[]Undecidable) bool { +// one of the four version-typed variables (rule 1), falling back when the +// operator and the right-hand value are not a valid specifier - or +// immediately, for any other variable - to a single generic string-operator +// table (rule 2). +func evalCompare(n *pep508.CompareExpr, env Environment, active *activeExtras, und *[]Undecidable) bool { if isExtraVar(n.Lhs) { return evalExtra(n.Op, n.Rhs, env, active) } @@ -186,9 +205,9 @@ func noteEmptyEnvVar(n *pep508.CompareExpr, operand pep508.Operand, value string // order the marker was written in). Only == and != are meaningful for // set-membership against the active-extras set; any other operator is // inapplicable and evaluates false. -func evalExtra(op pep508.CompareOp, other pep508.Operand, env Environment, active map[string]struct{}) bool { +func evalExtra(op pep508.CompareOp, other pep508.Operand, env Environment, active *activeExtras) bool { lit := resolveOperand(other, env) - _, present := active[lit] + present := active.has(lit) switch op { case "==": return present @@ -263,26 +282,45 @@ func envVarValue(name string, env Environment) string { } // tryVersionCompare attempts a PEP 440 version comparison of lhsVal op -// rhsVal: it builds a specifier from op+rhsVal and checks it against -// version.Parse(lhsVal). ok is false whenever either step fails to parse -// (e.g. op is "in"/"not in", or either side is not a valid PEP 440 version, -// including ""), signaling the caller to fall back to string semantics; the -// version.Parse/NewSpecifiers failure path never panics. +// rhsVal, as packaging's Specifier(f"{op}{rhs}").contains(lhs, +// prereleases=True) does. ok is false only when op+rhsVal is not a valid +// specifier (e.g. op is "in"/"not in", or rhsVal is not a version, including +// ""), which tells the caller to fall back to string semantics, as packaging +// does on InvalidSpecifier. The failure paths never panic. +// +// The specifier is ONE specifier, as packaging's is. A specifier set would +// read a comma or "||" in rhsVal as more constraints, so +// `python_version >= "3.8,<4"` was true here, where packaging finds no valid +// specifier and falls back to the string operators, which give false. +// +// Once the specifier is valid, the answer is the specifier's, as in +// packaging, even when lhsVal is not a version: +// +// - For "===", contains compares lhsVal as written with the operand, +// ignoring case. Check would compare the normalized version, so +// `python_full_version === "3.11.4"` would match "3.11.04". +// - For every other operator, a value that is not a version matches +// nothing. Before, it fell back to the string operators, so +// `python_version != "3.11"` was true for the value "garbage". func tryVersionCompare(op pep508.CompareOp, lhsVal, rhsVal string) (result bool, ok bool) { - spec, err := version.NewSpecifiers(string(op) + rhsVal) + spec, err := version.NewSpecifier(string(op) + rhsVal) if err != nil { return false, false } + if spec.Operator() == "===" { + return spec.Contains(lhsVal, version.WithPreReleases(version.PreReleasesInclude)), true + } pv, err := version.Parse(lhsVal) if err != nil { - return false, false + return false, true } return spec.Check(pv), true } // evalStringOp is the single generic operator table used whenever a version // comparison was not attempted (neither operand names a version-typed -// variable) or was attempted and failed to parse. `~=` and `===` have no +// variable) or the operator and the right-hand value are not a valid +// specifier. `~=` and `===` have no // meaningful string semantics - packaging raises UndefinedComparison here; // since Evaluate's signature is a fixed bool with no error channel, this is // a deliberate, documented divergence: they evaluate false rather than diff --git a/marker/evaluate_test.go b/marker/evaluate_test.go index a01af15..9fd7384 100644 --- a/marker/evaluate_test.go +++ b/marker/evaluate_test.go @@ -214,7 +214,17 @@ func TestEvaluate_EmptyStringLHS_OnVersionKey_NoPanic(t *testing.T) { assert.NotPanics(t, func() { evalStr(t, `platform_release != "5.4.0"`, env, nil) }) - assert.True(t, evalStr(t, `platform_release != "5.4.0"`, env, nil)) + // "!=5.4.0" is a valid specifier, and "" is not a version, so it matches + // nothing: false, as in packaging 26.2 and 26.3. This was true before, when + // a value that is not a version fell back to the string operators. The + // empty value is still reported, so a caller that must not drop the edge + // can tell. + m, err := Parse(`platform_release != "5.4.0"`) + require.NoError(t, err) + result, und := m.EvaluateUndecidable(env, nil) + assert.False(t, result) + require.Len(t, und, 1) + assert.Equal(t, "platform_release", und[0].Var) } // --- and/or tree evaluation and nesting --- diff --git a/marker/export_test.go b/marker/export_test.go new file mode 100644 index 0000000..5dfa285 --- /dev/null +++ b/marker/export_test.go @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "reflect" + + "github.com/posit-dev/go-python-packaging/internal/pep508" +) + +// SameTree reports whether a and b have the same parsed tree, with the same +// literal values. String() writes `a or (b or c)` as `a or b or c`, so a +// round trip can merge a group into a parent group with the same operator. +// The grouping does not change, so SameTree merges these groups before it +// compares the trees. Only the tests can use SameTree. +func SameTree(a, b Marker) bool { + return reflect.DeepEqual(mergeSameOp(a.ast), mergeSameOp(b.ast)) +} + +// mergeSameOp returns a copy of e in which each *pep508.BoolExpr operand with +// the same operator as its parent is merged into the parent. +func mergeSameOp(e pep508.Expr) pep508.Expr { + b, ok := e.(*pep508.BoolExpr) + if !ok { + return e + } + merged := &pep508.BoolExpr{Op: b.Op} + for _, operand := range b.Operands { + operand = mergeSameOp(operand) + if inner, ok := operand.(*pep508.BoolExpr); ok && inner.Op == b.Op { + merged.Operands = append(merged.Operands, inner.Operands...) + } else { + merged.Operands = append(merged.Operands, operand) + } + } + return merged +} diff --git a/marker/fuzz_test.go b/marker/fuzz_test.go new file mode 100644 index 0000000..08591f9 --- /dev/null +++ b/marker/fuzz_test.go @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker_test + +import ( + "strings" + "testing" + "time" + + "github.com/posit-dev/go-python-packaging/internal/fuzzseed" + "github.com/posit-dev/go-python-packaging/marker" +) + +func FuzzParse(f *testing.F) { + fuzzseed.Add(f, + `python_version >= "3.8"`, + `extra == "foo" and python_version >= "3.8"`, + `os_name == "nt" or (sys_platform == "linux" and platform_machine == "x86_64")`, + `python_full_version ~= "3.10.0"`, + `"3.8" <= python_version`, + `implementation_name === "cpython"`, + `platform_release in "5.15"`, + `'linux' not in sys_platform`, + `extra == 'Foo_Bar'`, + `python_version > '3' and python_version < '4' or os_name != 'posix'`, + `(python_version == "2.7")`, + `dependency_groups == "dev"`, + `os_name == '"'`, + `os_name == "'"`, + ) + // Deep nesting and long chains. Nesting at the 100-level limit parses, and + // deeper nesting returns an error (rstudio/package-manager#23020). The + // 2M-level crash input is in nesting_test.go, not here, to keep fuzzing fast. + f.Add(strings.Repeat("(", 100) + `os_name == "a"` + strings.Repeat(")", 100)) + f.Add(strings.Repeat("(", 5000) + `os_name == "a"` + strings.Repeat(")", 5000)) + f.Add(strings.Repeat(`os_name == "a" and `, 5000) + `os_name == "a"`) + f.Add(strings.Repeat(`os_name == "a" or `, 5000) + `os_name == "a"`) + f.Add(`os_name == "` + strings.Repeat("x", 1<<16) + `"`) + + // Inputs the fuzzer found that failed before they were fixed. + f.Add(`extra!="\\"`) + + // String() wrote the invalid UTF-8 byte as U+FFFD, so the value changed. + // The fuzzer did not find this input, because the check was too weak. + f.Add("os_name == \"a\xffb\"") + + // String() merges a group into a parent group with the same operator. The + // round-trip check must not fail on this. + f.Add(`os_name == "a" or (os_name == "b" or os_name == "c")`) + f.Add(`(os_name == "a" and os_name == "b") and os_name == "c"`) + + f.Fuzz(func(t *testing.T, in string) { + start := time.Now() + m, err := marker.Parse(in) + fuzzseed.Within(t, start, in) + if err != nil { + return + } + rendered := m.String() + if rendered == "" { + t.Fatalf("Parse(%q) returned no error and an empty marker", in) + } + again, err := marker.Parse(rendered) + if err != nil { + t.Fatalf("Parse(%q).String() = %q, which does not parse: %v", in, rendered, err) + } + if got := again.String(); got != rendered { + t.Fatalf("round trip of %q: %q, then %q", in, rendered, got) + } + // Comparing the two String() outputs is not sufficient. When String() + // changes a value, the changed value is in both outputs. SameTree + // compares the unexported parsed trees. + if !marker.SameTree(again, m) { + t.Fatalf("Parse(%q).String() = %q, which parses to a different marker", in, rendered) + } + env := marker.Environment{} + if a, b := m.Evaluate(env, []string{"foo"}), again.Evaluate(env, []string{"foo"}); a != b { + t.Fatalf("Evaluate differs after round trip of %q: %v, then %v", in, a, b) + } + _, _ = m.EvaluateUndecidable(env, nil) + }) +} diff --git a/marker/line_break_escape_test.go b/marker/line_break_escape_test.go new file mode 100644 index 0000000..5f925a2 --- /dev/null +++ b/marker/line_break_escape_test.go @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// String() writes each character that Python's str.splitlines() reads as a +// line break as an escape, so the literal stays on one line in a requirements +// file. +func TestString_LineBreakEscapes(t *testing.T) { + tests := []struct { + name string + input string + wantString string + }{ + {name: "LF", input: `os_name == "a\nb"`, wantString: `os_name == "a\nb"`}, + {name: "CR", input: `os_name == "a\rb"`, wantString: `os_name == "a\rb"`}, + {name: "vertical tab", input: `os_name == "a\vb"`, wantString: `os_name == "a\vb"`}, + {name: "form feed", input: `os_name == "a\fb"`, wantString: `os_name == "a\fb"`}, + {name: "file separator", input: `os_name == "a\x1cb"`, wantString: `os_name == "a\x1cb"`}, + {name: "group separator", input: `os_name == "a\x1db"`, wantString: `os_name == "a\x1db"`}, + {name: "record separator", input: `os_name == "a\x1eb"`, wantString: `os_name == "a\x1eb"`}, + {name: "next line U+0085", input: `os_name == "a\x85b"`, wantString: `os_name == "a\x85b"`}, + {name: "line separator U+2028", input: `os_name == "a\u2028b"`, wantString: `os_name == "a\u2028b"`}, + {name: "paragraph separator U+2029", input: `os_name == "a\u2029b"`, wantString: `os_name == "a\u2029b"`}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m, err := Parse(tt.input) + require.NoError(t, err) + text := m.String() + assert.Equal(t, tt.wantString, text) + assert.False( + t, + strings.ContainsAny(text, "\n\r\v\f\x1c\x1d\x1e\u0085\u2028\u2029"), + "String() has no raw line break", + ) + again, err := Parse(text) + require.NoError(t, err) + assert.Equal(t, m.ast, again.ast, "the parsed value is the same") + }) + } +} diff --git a/marker/long_input_test.go b/marker/long_input_test.go new file mode 100644 index 0000000..888c079 --- /dev/null +++ b/marker/long_input_test.go @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "errors" + "strings" + "testing" + "unicode/utf8" + + "github.com/posit-dev/go-python-packaging/internal/pep508" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// A long input with a syntax error gives a short error text, and the error +// still points at the correct place. +func TestParse_LongInputErrorText(t *testing.T) { + const hugeLen = 2_000_000 + big := strings.Repeat("a", hugeLen) + longLiteral := `python_version == "` + big + `" ` + // "€" is 3 bytes, so the error window can cut inside a character. + euro := strings.Repeat("€", hugeLen/3) + manyItems := strings.Repeat(`python_version == "3" and `, 80_000) + + tests := []struct { + name string + input string + wantStart int + wantEnd int + }{ + { + // The span is the whole 2 MB quoted string. + name: "long quoted string with a bad escape", + input: `python_version == "` + big + `\q"`, + wantStart: len(`python_version == `), + wantEnd: len(`python_version == "` + big + `\q"`), + }, + { + name: "long word where a marker variable must be", + input: big, + wantStart: 0, + wantEnd: 0, + }, + { + name: "long literal then a bad operator", + input: longLiteral + `? "x"`, + wantStart: len(longLiteral), + wantEnd: len(longLiteral), + }, + { + name: "long literal then text after the marker", + input: longLiteral + big, + wantStart: len(longLiteral), + wantEnd: len(longLiteral), + }, + { + name: "long whitespace then a bad character", + input: strings.Repeat(" ", hugeLen) + "?", + wantStart: hugeLen, + wantEnd: hugeLen, + }, + { + // A quoted string with no closing quote is not a quoted string. + name: "long quoted string with no closing quote", + input: `python_version == "` + big, + wantStart: len(`python_version == `), + wantEnd: len(`python_version == `), + }, + { + // The span is only the short quoted string, not the long one. + name: "short quoted string with a bad escape after a long literal", + input: `"` + big + `" == "\q"`, + wantStart: len(`"` + big + `" == `), + wantEnd: len(`"` + big + `" == "\q"`), + }, + { + name: "long literal then 'not' with no 'in'", + input: `"` + big + `" not "x"`, + wantStart: len(`"` + big + `" not `), + wantEnd: len(`"` + big + `" not `), + }, + { + name: "long literal then 'and' at the end", + input: longLiteral + "and ", + wantStart: len(longLiteral + "and "), + wantEnd: len(longLiteral + "and "), + }, + { + name: "many comparisons then a bad character", + input: manyItems + "?", + wantStart: len(manyItems), + wantEnd: len(manyItems), + }, + { + name: "long literal in parentheses with no ')'", + input: "(" + longLiteral, + wantStart: len("(" + longLiteral), + wantEnd: len("(" + longLiteral), + }, + { + name: "long multi-byte word where a marker variable must be", + input: euro, + wantStart: 0, + wantEnd: 0, + }, + { + name: "long multi-byte literal then a bad operator", + input: `"` + euro + `" ? "x"`, + wantStart: len(`"` + euro + `" `), + wantEnd: len(`"` + euro + `" `), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := Parse(tt.input) + require.Error(t, err) + require.Less(t, len(err.Error()), 1000, "error text is short") + assert.True(t, utf8.ValidString(err.Error()), "error text is valid UTF-8") + var syntaxErr *pep508.SyntaxError + require.True(t, errors.As(err, &syntaxErr), "want a *pep508.SyntaxError") + assert.Equal(t, tt.wantStart, syntaxErr.Start, "error start") + assert.Equal(t, tt.wantEnd, syntaxErr.End, "error end") + }) + } +} diff --git a/marker/nesting_test.go b/marker/nesting_test.go new file mode 100644 index 0000000..9df27d7 --- /dev/null +++ b/marker/nesting_test.go @@ -0,0 +1,364 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "errors" + "strings" + "testing" + + "github.com/posit-dev/go-python-packaging/internal/pep508" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + nestItem = `python_version >= "3.8"` + nestItem2 = `os_name == "posix"` + depthMsg = "nested parentheses" +) + +// nested returns nestItem inside depth pairs of parentheses, with sep after +// each "(" and before each ")". +func nested(depth int, sep string) string { + return wrapDepth("", depth, "("+sep, nestItem, sep+")") +} + +// nestedAnd returns depth levels of `(nestItem2 and )`, so each level +// holds a comparison and a deeper group. +func nestedAnd(depth int) string { + return wrapDepth("", depth, "("+nestItem2+" and ", nestItem, ")") +} + +// wrapDepth returns prefix, then depth copies of open, then inner, then depth +// copies of closing. It makes one allocation, which keeps the memory use of +// the large test inputs low. +func wrapDepth(prefix string, depth int, open, inner, closing string) string { + var b strings.Builder + b.Grow(len(prefix) + depth*(len(open)+len(closing)) + len(inner)) + b.WriteString(prefix) + for range depth { + b.WriteString(open) + } + b.WriteString(inner) + for range depth { + b.WriteString(closing) + } + return b.String() +} + +func TestParse_Nesting(t *testing.T) { + const limit = pep508.MaxMarkerDepth + atLimit := nested(limit, "") + andPrefix := len("(" + nestItem2 + " and ") + + tests := []struct { + name string + // input builds the input when its case runs, so large inputs are not + // all in memory at the same time. + input func() string + // wantString is the expected String() on success. Empty means do not check. + wantString string + // wantErr is a substring of the error message. Empty means no error. + wantErr string + // wantStart is the expected error start for a depth error. + wantStart int + }{ + // Inputs at or under the limit parse. + { + name: "depth 0", + input: func() string { return nested(0, "") }, + wantString: nestItem, + }, + { + name: "depth 1", + input: func() string { return nested(1, "") }, + wantString: nestItem, + }, + { + name: "depth 2", + input: func() string { return nested(2, "") }, + wantString: nestItem, + }, + { + name: "depth 10", + input: func() string { return nested(10, "") }, + wantString: nestItem, + }, + { + name: "depth limit-1", + input: func() string { return nested(limit-1, "") }, + wantString: nestItem, + }, + { + name: "depth limit", + input: func() string { return atLimit }, + wantString: nestItem, + }, + { + name: "depth limit with spaces", + input: func() string { return nested(limit, " ") }, + wantString: nestItem, + }, + { + name: "depth limit with tabs", + input: func() string { return nested(limit, "\t") }, + wantString: nestItem, + }, + { + name: "depth limit with and at each level", + input: func() string { return nestedAnd(limit) }, + }, + { + name: "two groups at limit joined by and", + input: func() string { return atLimit + " and " + atLimit }, + }, + { + name: "two groups at limit joined by or", + input: func() string { return atLimit + " or " + atLimit }, + }, + { + name: "ten groups at limit", + input: func() string { return strings.Repeat(atLimit+" and ", 9) + atLimit }, + }, + { + name: "group at limit then shallow group", + input: func() string { return atLimit + " or " + nested(1, "") }, + }, + { + name: "two inner groups at limit", + input: func() string { + return strings.Repeat("(", limit-1) + "(" + nestItem + ") and (" + nestItem2 + ")" + strings.Repeat(")", limit-1) + }, + }, + + // Inputs over the limit return the depth error at the first "(" over it. + { + name: "depth limit+1", + input: func() string { return nested(limit+1, "") }, + wantErr: depthMsg, + wantStart: limit, + }, + { + name: "depth limit+2", + input: func() string { return nested(limit+2, "") }, + wantErr: depthMsg, + wantStart: limit, + }, + { + name: "depth 2*limit", + input: func() string { return nested(2*limit, "") }, + wantErr: depthMsg, + wantStart: limit, + }, + { + name: "depth 1000", + input: func() string { return nested(1000, "") }, + wantErr: depthMsg, + wantStart: limit, + }, + { + name: "depth limit+1 with spaces", + input: func() string { return nested(limit+1, " ") }, + wantErr: depthMsg, + wantStart: 2 * limit, + }, + { + name: "depth limit+1 with and at each level", + input: func() string { return nestedAnd(limit + 1) }, + wantErr: depthMsg, + wantStart: limit * andPrefix, + }, + { + name: "group at limit then group at limit+1", + input: func() string { return atLimit + " and " + nested(limit+1, "") }, + wantErr: depthMsg, + wantStart: len(atLimit+" and ") + limit, + }, + { + name: "limit+1 open only", + input: func() string { return strings.Repeat("(", limit+1) }, + wantErr: depthMsg, + wantStart: limit, + }, + { + name: "limit+1 open then item", + input: func() string { return strings.Repeat("(", limit+1) + nestItem }, + wantErr: depthMsg, + wantStart: limit, + }, + + // Before the limit, about 1.3M "(" overflowed the Go stack. That is a + // fatal crash that recover cannot catch. + { + name: "2M open only", + input: func() string { return strings.Repeat("(", 2_000_000) }, + wantErr: depthMsg, + wantStart: limit, + }, + { + name: "2M open with spaces", + input: func() string { return strings.Repeat("( ", 2_000_000) }, + wantErr: depthMsg, + wantStart: 2 * limit, + }, + { + name: "2M closed", + input: func() string { return nested(2_000_000, "") }, + wantErr: depthMsg, + wantStart: limit, + }, + { + name: "2M with and at each level", + input: func() string { return nestedAnd(2_000_000) }, + wantErr: depthMsg, + wantStart: limit * andPrefix, + }, + + // Other errors at or under the limit are not changed into depth errors. + { + name: "depth limit unclosed", + input: func() string { return strings.Repeat("(", limit) + nestItem }, + wantErr: "Expected ')'", + }, + { + name: "depth limit open only", + input: func() string { return strings.Repeat("(", limit) }, + wantErr: "Expected a marker variable", + }, + { + name: "depth limit empty group", + input: func() string { return strings.Repeat("(", limit) + ")" }, + wantErr: "Expected a marker variable", + }, + { + name: "depth limit extra close", + input: func() string { return atLimit + ")" }, + wantErr: "Expected end of marker expression", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + input := tt.input() + m, err := Parse(input) + if tt.wantErr == "" { + require.NoError(t, err) + if tt.wantString != "" { + assert.Equal(t, tt.wantString, m.String()) + } + return + } + + require.Error(t, err) + assert.Less(t, len(err.Error()), 1000, "error text is short") + var syntaxErr *pep508.SyntaxError + require.True(t, errors.As(err, &syntaxErr), "want a *pep508.SyntaxError") + assert.Contains(t, syntaxErr.Msg, tt.wantErr) + if tt.wantErr == depthMsg { + assert.Equal(t, "Marker has more than 100 nested parentheses", syntaxErr.Msg) + assert.Equal(t, tt.wantStart, syntaxErr.Start, "error start") + assert.Equal(t, tt.wantStart+1, syntaxErr.End, "error end") + assert.Equal(t, "(", input[syntaxErr.Start:syntaxErr.End]) + } else { + assert.NotContains(t, syntaxErr.Msg, depthMsg) + } + }) + } +} + +// alternatingAndOr returns depth levels where "and" and "or" take turns: +// `(nestItem2 and (nestItem2 or (... nestItem)))`. +func alternatingAndOr(depth int) string { + var b strings.Builder + for i := range depth { + op := " and " + if i%2 == 1 { + op = " or " + } + b.WriteString("(" + nestItem2 + op) + } + b.WriteString(nestItem) + b.WriteString(strings.Repeat(")", depth)) + return b.String() +} + +// A marker at the limit works after it parses: String() parses again to the +// same marker, and Evaluate, EvaluateUndecidable and Variables work. +func TestParse_NestingAtLimitAfterParse(t *testing.T) { + const limit = pep508.MaxMarkerDepth + posix39 := Environment{OsName: "posix", PythonVersion: "3.9"} + nt39 := Environment{OsName: "nt", PythonVersion: "3.9"} + posix37 := Environment{OsName: "posix", PythonVersion: "3.7"} + + tests := []struct { + name string + input string + wantVars []string + // wantParens is the number of "(" in String(). + wantParens int + // The expected Evaluate result for each environment. + wantPosix39 bool + wantNt39 bool + wantPosix37 bool + }{ + { + name: "plain nesting", + input: nested(limit, ""), + wantVars: []string{"python_version"}, + wantParens: 0, + wantPosix39: true, + wantNt39: true, + wantPosix37: false, + }, + { + name: "and at each level", + input: nestedAnd(limit), + wantVars: []string{"os_name", "python_version"}, + wantParens: 0, + wantPosix39: true, + wantNt39: false, + wantPosix37: false, + }, + { + // String() adds parentheses only for each "or" inside an "and". + name: "and and or take turns", + input: alternatingAndOr(limit), + wantVars: []string{"os_name", "python_version"}, + wantParens: limit / 2, + wantPosix39: true, + wantNt39: false, + wantPosix37: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m, err := Parse(tt.input) + require.NoError(t, err) + + text := m.String() + assert.Equal(t, tt.wantParens, strings.Count(text, "("), "parentheses in String()") + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + assert.Equal(t, text, again.String(), "String() is stable") + + assert.ElementsMatch(t, tt.wantVars, m.Variables()) + + for _, c := range []struct { + name string + env Environment + want bool + }{ + {name: "posix 3.9", env: posix39, want: tt.wantPosix39}, + {name: "nt 3.9", env: nt39, want: tt.wantNt39}, + {name: "posix 3.7", env: posix37, want: tt.wantPosix37}, + } { + assert.Equal(t, c.want, m.Evaluate(c.env, nil), "Evaluate, %s", c.name) + assert.Equal(t, c.want, again.Evaluate(c.env, nil), "Evaluate after String(), %s", c.name) + got, _ := m.EvaluateUndecidable(c.env, nil) + assert.Equal(t, c.want, got, "EvaluateUndecidable, %s", c.name) + } + }) + } +} diff --git a/marker/quote_literal_test.go b/marker/quote_literal_test.go new file mode 100644 index 0000000..492849f --- /dev/null +++ b/marker/quote_literal_test.go @@ -0,0 +1,269 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// String() writes each literal so that it parses back to the same value. +func TestString_LiteralRoundTrip(t *testing.T) { + tests := []struct { + name string + input string + wantString string + }{ + { + // Found by fuzzing: the value is one backslash. + name: "backslash only", + input: `extra!="\\"`, + wantString: `extra != "\\"`, + }, + { + name: "backslash in a path", + input: `os_name == "C:\\U"`, + wantString: `os_name == "C:\\U"`, + }, + { + name: "two backslashes", + input: `os_name == "a\\\\b"`, + wantString: `os_name == "a\\\\b"`, + }, + { + name: "backslash from a hex escape", + input: `os_name == "\x5c"`, + wantString: `os_name == "\\"`, + }, + { + name: "double quote is single-quoted", + input: `os_name == '"'`, + wantString: `os_name == '"'`, + }, + { + name: "single quote is double-quoted", + input: `os_name == "'"`, + wantString: `os_name == "'"`, + }, + { + name: "backslash and double quote", + input: `os_name == '\\"'`, + wantString: `os_name == '\\"'`, + }, + { + // Before, a value with both quote characters could not be written. + name: "both quote characters", + input: `os_name == "a\x22b'c"`, + wantString: `os_name == "a\x22b'c"`, + }, + { + name: "both quote characters and a backslash", + input: `os_name == "\\\x22'"`, + wantString: `os_name == "\\\x22'"`, + }, + { + name: "text that looks like an escape", + input: `os_name == "\\x22"`, + wantString: `os_name == "\\x22"`, + }, + { + name: "newline from an escape", + input: `os_name == "a\nb"`, + wantString: `os_name == "a\nb"`, + }, + { + // A requirements file reads " #" as a comment, but package reqtxt + // escapes it, not String() (see TestEscapeMarkerLiterals in reqtxt). + name: "space then hash", + input: `os_name == "a\x20#b"`, + wantString: `os_name == "a #b"`, + }, + { + // A requirements file reads " -" as the options, but package reqtxt + // escapes it, not String(). + name: "space then dash", + input: `os_name == "a\x20-b"`, + wantString: `os_name == "a -b"`, + }, + { + name: "hash and dash with no whitespace before them are unchanged", + input: `os_name == "#1-a#b"`, + wantString: `os_name == "#1-a#b"`, + }, + { + name: "plain value is unchanged", + input: `python_version >= "3.8"`, + wantString: `python_version >= "3.8"`, + }, + + // No whitespace character before "#" or "-" causes an escape. The + // whitespace stays as it is. + { + name: "tab then hash", + input: `os_name == "a\t#b"`, + wantString: "os_name == \"a\t#b\"", + }, + { + name: "no-break space then hash", + input: `os_name == "a\xa0#b"`, + wantString: "os_name == \"a\u00a0#b\"", + }, + { + name: "ideographic space then dash", + input: `os_name == "a\u3000-b"`, + wantString: "os_name == \"a\u3000-b\"", + }, + { + // The line break is written as an escape. The "#" is not. + name: "line break then hash", + input: `os_name == "a\r\n#b"`, + wantString: `os_name == "a\r\n#b"`, + }, + + // Combinations of whitespace, "#", "-" and other escapes. + { + name: "two spaces then hash", + input: `os_name == "a #b"`, + wantString: `os_name == "a #b"`, + }, + { + name: "space, hash, then dash", + input: `os_name == "a #-b"`, + wantString: `os_name == "a #-b"`, + }, + { + name: "two spaces, each followed by a hash", + input: `os_name == "a # #b"`, + wantString: `os_name == "a # #b"`, + }, + { + name: "value is a space then a hash", + input: `os_name == " #"`, + wantString: `os_name == " #"`, + }, + { + name: "backslash, space, then hash", + input: `os_name == "a\\ #b"`, + wantString: `os_name == "a\\ #b"`, + }, + { + name: "both quote characters and space then hash", + input: `os_name == "\x22 #'"`, + wantString: `os_name == "\x22 #'"`, + }, + + // Literals in other places of a comparison. + { + name: "literal on the left side", + input: `"a #b" == os_name`, + wantString: `"a #b" == os_name`, + }, + { + name: "literal with the 'in' operator", + input: `"a -b" in os_name`, + wantString: `"a -b" in os_name`, + }, + { + // The parser normalizes the extra before String() writes it. + name: "extra value with space then dash", + input: `extra == "A -B"`, + wantString: `extra == "a -b"`, + }, + + // Other characters are written as they are, not as escapes. + { + name: "non-ASCII characters from escapes", + input: `os_name == "\u00e9\U0001F600"`, + wantString: "os_name == \"é😀\"", + }, + { + // U+001F is next to the U+001C to U+001E line breaks, but it is + // not a line break. + name: "control characters that are not line breaks", + input: `os_name == "\t\a\b\x00\x1b\x1f\x7f"`, + wantString: "os_name == \"\t\a\b\x00\x1b\x1f\x7f\"", + }, + { + name: "octal escapes", + input: `os_name == "\101\0"`, + wantString: "os_name == \"A\x00\"", + }, + { + // A known gap: Go cannot hold a lone surrogate in a string, so the + // parser writes U+FFFD. See decodeQuotedStringContents. + name: "lone surrogate becomes U+FFFD", + input: `os_name == "\ud800"`, + wantString: "os_name == \"\ufffd\"", + }, + + // A byte that is not valid UTF-8 is written unchanged. Before, String() + // wrote U+FFFD in its place, so the value changed. + { + name: "invalid UTF-8 byte", + input: "os_name == \"a\xffb\"", + wantString: "os_name == \"a\xffb\"", + }, + { + name: "invalid UTF-8 byte only", + input: "os_name == \"\xff\"", + wantString: "os_name == \"\xff\"", + }, + { + // The first two bytes of "€". + name: "cut multi-byte character", + input: "os_name == \"a\xe2\x82\"", + wantString: "os_name == \"a\xe2\x82\"", + }, + { + // U+0085 is the two bytes C2 85. One 0x85 byte is not a line break, + // so String() does not write it as the `\x85` escape. + name: "byte 0x85 alone is not a line break", + input: "os_name == \"a\x85b\"", + wantString: "os_name == \"a\x85b\"", + }, + { + name: "invalid UTF-8 byte then space then hash", + input: "os_name == \"\xff #b\"", + wantString: "os_name == \"\xff #b\"", + }, + { + // The input has the 3 bytes of U+FFFD, not an invalid byte. + name: "U+FFFD character is unchanged", + input: "os_name == \"a\ufffdb\"", + wantString: "os_name == \"a\ufffdb\"", + }, + + // The quote characters of the input do not change the output. + { + name: "empty value", + input: `os_name == ""`, + wantString: `os_name == ""`, + }, + { + name: "empty single-quoted value", + input: `os_name == ''`, + wantString: `os_name == ""`, + }, + { + name: "single-quoted plain value is double-quoted", + input: `os_name == 'posix'`, + wantString: `os_name == "posix"`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m, err := Parse(tt.input) + require.NoError(t, err) + text := m.String() + assert.Equal(t, tt.wantString, text) + + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + assert.Equal(t, text, again.String(), "String() is stable") + assert.Equal(t, m.ast, again.ast, "the parsed value is the same") + }) + } +} diff --git a/marker/specifier_literal_test.go b/marker/specifier_literal_test.go new file mode 100644 index 0000000..37689af --- /dev/null +++ b/marker/specifier_literal_test.go @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package marker + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// A comparison on a version-typed variable builds ONE specifier from the +// operator and the literal, as packaging's Specifier(f"{op}{rhs}") does. A +// comma or "||" in the literal makes that an invalid specifier, so packaging +// falls back to the string operators. This package used to build a specifier +// SET, which read the comma or "||" as more constraints, so the first five +// rows were true here. +// +// Each want was measured with packaging 26.2 and 26.3, with python_version +// 3.11 and python_full_version 3.11.4. +func TestEvaluate_VersionKeyLiteralIsOneSpecifier(t *testing.T) { + env := baseEnv() + env.PythonVersion = "3.11" + env.PythonFullVersion = "3.11.4" + tests := []struct { + expr string + want bool + }{ + {`python_version >= "3.8,<4"`, false}, + {`python_version >= "3.8||<2"`, false}, + {`python_version >= "3.8, "`, false}, + {`python_version == "3.11,"`, false}, + {`python_full_version >= "3.8,<4"`, false}, + // Whitespace around the version is part of one specifier. + {`python_version >= " 3.8"`, true}, + {`python_version >= "3.8 "`, true}, + {`python_version == "3.11.*"`, true}, + {`python_version >= "3.8.*"`, false}, + {`"3.8" < python_version`, true}, + } + for _, tt := range tests { + t.Run(tt.expr, func(t *testing.T) { + assert.Equal(t, tt.want, evalStr(t, tt.expr, env, nil)) + }) + } +} diff --git a/packagename/fuzz_test.go b/packagename/fuzz_test.go new file mode 100644 index 0000000..4961485 --- /dev/null +++ b/packagename/fuzz_test.go @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package packagename_test + +import ( + "strings" + "testing" + "time" + + "github.com/posit-dev/go-python-packaging/internal/fuzzseed" + "github.com/posit-dev/go-python-packaging/packagename" +) + +func FuzzNormalize(f *testing.F) { + fuzzseed.Add(f, "Foo_Bar", "a.b__c", "A---B", "..foo..", "requests", "zope.interface", "Django-REST_framework") + + f.Fuzz(func(t *testing.T, in string) { + start := time.Now() + got := packagename.Normalize(in) + fuzzseed.Within(t, start, in) + if again := packagename.Normalize(got); again != got { + t.Fatalf("not idempotent: Normalize(%q) = %q, then %q", in, got, again) + } + if strings.ContainsAny(got, "_.") || strings.Contains(got, "--") { + t.Fatalf("Normalize(%q) = %q still has separators to collapse", in, got) + } + if strings.ToLower(got) != got && strings.ToValidUTF8(got, "") == got { + t.Fatalf("Normalize(%q) = %q is not lower case", in, got) + } + }) +} diff --git a/reqtxt/bench_test.go b/reqtxt/bench_test.go new file mode 100644 index 0000000..72334fd --- /dev/null +++ b/reqtxt/bench_test.go @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "fmt" + "strings" + "testing" + + "github.com/posit-dev/go-python-packaging/internal/allocbudget" +) + +// Benchmarks and allocation budgets for the hot paths of this package. The +// budget tests run in CI and fail on any change in allocations; the +// benchmarks are for comparing a branch with main (see CLAUDE.md, +// "Performance"). + +// lockFile is a pip-compile style file: n pinned requirements, each with +// two hashes on continuation lines and a "via" comment. +func lockFile(n int) string { + var b strings.Builder + b.WriteString("#\n# This file is autogenerated by pip-compile\n#\n--index-url https://pypi.org/simple\n\n") + for i := range n { + fmt.Fprintf(&b, "pkg%d==1.%d.0 \\\n --hash=sha256:%064x \\\n --hash=sha256:%064x\n # via app\n", i, i, i, i+1) + } + return b.String() +} + +// mixedFile has requirements with extras and markers, URLs, paths, editable +// targets, options and comments. +func mixedFile(n int) string { + var b strings.Builder + b.WriteString("--extra-index-url https://example.com/simple\n--prefer-binary\n-c constraints.txt\n") + for i := range n { + fmt.Fprintf(&b, "lib%d[extra]>=2.%d,<3; python_version >= \"3.8\" # comment\n", i, i) + fmt.Fprintf(&b, "named%d @ https://example.com/named%d-1.0.tar.gz\n", i, i) + fmt.Fprintf(&b, "./vendor/pkg%d-1.0-py3-none-any.whl\n", i) + fmt.Fprintf(&b, "-e git+https://github.com/org/repo%d.git#egg=repo%d\n\n", i, i) + } + return b.String() +} + +// benchFiles are requirements files of common shapes. parse and str are the +// allocation budgets of Parse and of File.String. +var benchFiles = []struct { + name, in string + parse, str float64 +}{ + {name: "lock file of 100 pins", in: lockFile(100), parse: 5221, str: 803}, + {name: "mixed file of 25 groups", in: mixedFile(25), parse: 3108, str: 504}, +} + +// flattenTree serves a tree of requirements files: a root that includes +// files f0.txt to f.txt, each of which includes constraints.txt. +func flattenTree(files, constraints int) func(string) ([]byte, error) { + var root, cons strings.Builder + for i := range files { + fmt.Fprintf(&root, "-r f%d.txt\n", i) + } + for i := range constraints { + fmt.Fprintf(&cons, "pkg%d==1.%d.0 --hash=sha256:%064x\n", i, i, i) + } + return func(p string) ([]byte, error) { + switch p { + case "root.txt": + return []byte(root.String()), nil + case "constraints.txt": + return []byte(cons.String()), nil + } + return []byte("-c constraints.txt\nnumpy>=1.20\nrequests[security]>=2.8.1; python_version < \"3.9\"\n"), nil + } +} + +// benchTrees are include trees for Flatten. budget is its allocation budget. +var benchTrees = []struct { + name string + open func(string) ([]byte, error) + budget float64 +}{ + {name: "10 files sharing 50 constraints", open: flattenTree(10, 50), budget: 4725}, + {name: "50 files sharing 200 constraints", open: flattenTree(50, 200), budget: 36205}, +} + +func BenchmarkParse(b *testing.B) { + for _, f := range benchFiles { + b.Run(f.name, func(b *testing.B) { + b.ReportAllocs() + b.SetBytes(int64(len(f.in))) + for b.Loop() { + if _, err := Parse(f.in); err != nil { + b.Fatal(err) + } + } + }) + } +} + +func BenchmarkFileString(b *testing.B) { + for _, f := range benchFiles { + b.Run(f.name, func(b *testing.B) { + file, err := Parse(f.in) + if err != nil { + b.Fatal(err) + } + b.ReportAllocs() + for b.Loop() { + _ = file.String() + } + }) + } +} + +func BenchmarkFlatten(b *testing.B) { + for _, tree := range benchTrees { + b.Run(tree.name, func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + if _, err := Flatten("root.txt", tree.open); err != nil { + b.Fatal(err) + } + } + }) + } +} + +func TestAllocBudget_Parse(t *testing.T) { + for _, f := range benchFiles { + t.Run(f.name, func(t *testing.T) { + if _, err := Parse(f.in); err != nil { + t.Fatal(err) // the budget must not be an error path + } + allocbudget.Check(t, f.parse, func() { _, _ = Parse(f.in) }) + }) + } +} + +func TestAllocBudget_String(t *testing.T) { + for _, f := range benchFiles { + t.Run(f.name, func(t *testing.T) { + file, err := Parse(f.in) + if err != nil { + t.Fatal(err) + } + allocbudget.Check(t, f.str, func() { _ = file.String() }) + }) + } +} + +func TestAllocBudget_Flatten(t *testing.T) { + for _, tree := range benchTrees { + t.Run(tree.name, func(t *testing.T) { + if _, err := Flatten("root.txt", tree.open); err != nil { + t.Fatal(err) // the budget must not be an error path + } + allocbudget.Check(t, tree.budget, func() { _, _ = Flatten("root.txt", tree.open) }) + }) + } +} diff --git a/reqtxt/classify.go b/reqtxt/classify.go index acbed66..d1de549 100644 --- a/reqtxt/classify.go +++ b/reqtxt/classify.go @@ -2,7 +2,8 @@ // // Portions of this file are ported from pip // (https://github.com/pypa/pip), specifically pip/_internal/utils/misc.py's -// is_url and is_archive_file, and the VCS scheme registration in +// is_url and splitext, pip/_internal/utils/filetypes.py's is_archive_file and +// ARCHIVE_EXTENSIONS, and the VCS scheme registration in // pip/_internal/vcs/{git,mercurial,subversion,bazaar}.py, used under the MIT // license; see NOTICE for full license and copyright detail. // Changed: translated from Python to Go as a pure, shape-only string @@ -24,12 +25,15 @@ var vcsSchemePrefixes = []string{"git+", "hg+", "svn+", "bzr+"} // by pip's index backends (http/https). var urlSchemes = []string{"http://", "https://", "file://"} -// archiveExtensions are the local-archive suffixes pip's is_archive_file -// (pip/_internal/utils/misc.py) recognizes by extension. Multi-dot -// suffixes are ordered before their shorter overlapping counterpart (e.g. -// ".tar.gz" before ".tar") so the longer, more specific suffix is checked -// first. -var archiveExtensions = []string{".tar.gz", ".tar.bz2", ".whl", ".tgz", ".tar", ".zip"} +// archiveExtensions are pip's ARCHIVE_EXTENSIONS +// (pip/_internal/utils/filetypes.py): the zip, bz2, tar and xz extensions, in +// lower case. +var archiveExtensions = map[string]bool{ + ".zip": true, ".whl": true, + ".tar.bz2": true, ".tbz": true, + ".tar.gz": true, ".tgz": true, ".tar": true, + ".tar.xz": true, ".txz": true, ".tlz": true, ".tar.lz": true, ".tar.lzma": true, +} // classifyTarget determines whether tok is shaped like a VCS reference, a // direct URL, a local archive, or a local path — the non-PEP-508 @@ -48,32 +52,94 @@ var archiveExtensions = []string{".tar.gz", ".tar.bz2", ".whl", ".tgz", ".tar", // filesystem-dependent fallback, so a bare name with no path/URL/archive // shape (e.g. "flask") always falls through to (_, false) here. func classifyTarget(tok string) (kind Kind, ok bool) { - lower := strings.ToLower(tok) + if kind, ok := classifyURL(tok); ok { + return kind, true + } + if hasArchiveExtension(tok) || looksLikePath(tok) { + return KindLocalPath, true + } + return 0, false +} +// classifyURL is the first part of classifyTarget: it reports whether tok +// starts with a VCS prefix or a URL scheme, in any case, and which Kind it is. +// readAsTarget uses it alone, because it checks for a local path itself. +func classifyURL(tok string) (kind Kind, ok bool) { + lower := strings.ToLower(tok) for _, prefix := range vcsSchemePrefixes { if strings.HasPrefix(lower, prefix) { return KindVCS, true } } - for _, scheme := range urlSchemes { if strings.HasPrefix(lower, scheme) { return KindURL, true } } + return 0, false +} - for _, ext := range archiveExtensions { - if strings.HasSuffix(lower, ext) { - return KindLocalPath, true - } +// hasArchiveExtension reports whether pip's is_archive_file is true for s: +// whether the extension that pip's splitext gives for s, in lower case, is +// one of archiveExtensions. So "foo.tar.xz" is an archive, but "foo.tar.zip" +// (extension ".tar.zip") and ".zip" (no extension) are not. +func hasArchiveExtension(s string) bool { + return archiveExtensions[strings.ToLower(pipExtension(s))] +} + +// pipExtension returns the extension of path, as pip's splitext +// (pip/_internal/utils/misc.py) gives it: the extension from Python's +// posixpath.splitext, with ".tar" added in front when the rest of path ends +// with ".tar" in any case. posixpath.splitext takes the text from the last "." +// of the last path element, but gives no extension when only dots come +// before that "." in the element, as in ".zip" or "..zip". +func pipExtension(path string) string { + dot := strings.LastIndexByte(path, '.') + slash := strings.LastIndexByte(path, '/') + if dot <= slash || strings.Trim(path[slash+1:dot], ".") == "" { + return "" } + base, ext := path[:dot], path[dot:] + if hasTarSuffix(base) { + ext = base[len(base)-len(".tar"):] + ext + } + return ext +} - if strings.HasPrefix(tok, "./") || strings.HasPrefix(tok, "../") || strings.HasPrefix(tok, "/") || - tok == "." || strings.Contains(tok, "/") { - return KindLocalPath, true +// hasTarSuffix reports whether strings.ToLower(s) ends with ".tar", without +// the cost of ToLower for all of s. No rune other than ".", "t", "T", "a", +// "A", "r" and "R" lowers to text with one of the characters of ".tar", so +// only the last 4 bytes of s count. +func hasTarSuffix(s string) bool { + if len(s) < len(".tar") { + return false } + tail := s[len(s)-len(".tar"):] + return tail[0] == '.' && + tail[1]|0x20 == 't' && + tail[2]|0x20 == 'a' && + tail[3]|0x20 == 'r' +} - return 0, false +// looksLikePath reports whether tok is shaped like a local path: it is "." or +// contains "/". +func looksLikePath(tok string) bool { + return tok == "." || strings.Contains(tok, "/") +} + +// stripExtras returns s without non-empty extras in brackets at its end, as +// pip's _strip_extras (pip._internal.req.constructors) does with the regular +// expression `^(.+)(\[[^\]]+\])$`. So "foo.whl[x]" gives "foo.whl", and +// "foo.whl[]" and "foo.whl[x]>=1" are returned unchanged. +func stripExtras(s string) string { + if !strings.HasSuffix(s, "]") { + return s + } + i := strings.LastIndexByte(s, '[') + if i < 0 || i+2 >= len(s) || strings.Contains(s[i+1:len(s)-1], "]") { + return s + } + return s[:i] } // eggName returns the value of an "egg=" fragment parameter on raw diff --git a/reqtxt/classify_test.go b/reqtxt/classify_test.go index e537db2..28c2d79 100644 --- a/reqtxt/classify_test.go +++ b/reqtxt/classify_test.go @@ -119,7 +119,14 @@ func TestClassifyTargetVCSSchemePrefixCaseInsensitive(t *testing.T) { } func TestClassifyTargetArchiveExtensions(t *testing.T) { - for _, ext := range []string{".whl", ".tar.gz", ".tgz", ".tar.bz2", ".tar", ".zip"} { + // pip 21.2.4's ARCHIVE_EXTENSIONS. + exts := []string{ + ".zip", ".whl", + ".tar.bz2", ".tbz", + ".tar.gz", ".tgz", ".tar", + ".tar.xz", ".txz", ".tlz", ".tar.lz", ".tar.lzma", + } + for _, ext := range exts { tok := "pkg-1.0" + ext kind, ok := classifyTarget(tok) assert.True(t, ok, "expected %q to classify as an archive", tok) @@ -127,6 +134,58 @@ func TestClassifyTargetArchiveExtensions(t *testing.T) { } } +// Each row was checked against pip 21.2.4's is_archive_file. +func TestHasArchiveExtension(t *testing.T) { + tests := []struct { + name string + want bool + }{ + // The xz and bz2 extensions. + {"foo.tar.xz", true}, + {"foo.txz", true}, + {"foo.tlz", true}, + {"foo.tar.lz", true}, + {"foo.tar.lzma", true}, + {"foo.tbz", true}, + {"foo.tar.bz2", true}, + {"FOO.TAR.XZ", true}, + {"foo.xz", false}, + {"foo.lz", false}, + {"foo.lzma", false}, + + // pip's splitext adds a ".tar" before the extension, so the + // extension of "foo.tar.zip" is ".tar.zip", which is not an archive + // extension. + {"a.tar.gz", true}, + {"foo.tar.tar", false}, + {"foo.tar.zip", false}, + {"foo.TAR.zip", false}, + {"foo.tar.whl", false}, + {"foo.tar.tgz", false}, + + // posixpath.splitext gives no extension when only dots come before + // the last dot of the last path element. + {".zip", false}, + {"..zip", false}, + {"dir/.zip", false}, + {".tar.gz", true}, + {"x..zip", true}, + + // The extension is in the last path element only. + {"a.zip/b", false}, + {"dir/foo.whl", true}, + + // Trailing whitespace is part of the extension. + {"foo.zip ", false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, hasArchiveExtension(tt.name)) + }) + } +} + func TestEggName(t *testing.T) { cases := []struct { name string diff --git a/reqtxt/env_fuzz_test.go b/reqtxt/env_fuzz_test.go new file mode 100644 index 0000000..9328ca1 --- /dev/null +++ b/reqtxt/env_fuzz_test.go @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "errors" + "strings" + "testing" + "time" + "unicode/utf8" + + "github.com/posit-dev/go-python-packaging/internal/fuzzseed" +) + +// pipExpandEnv is pip's expand_env_variables for one line, line by line: +// find each reference in the line, then for each one in turn, replace all of +// its copies with the value, unless the value is unset or empty. pip has no +// limit, so a value that holds its own reference can grow the line without +// end. So pipExpandEnv returns false when the line would grow past limit, +// and a broken expandEnv makes the test fail, not run forever. +func pipExpandEnv(line string, lookup func(string) (string, bool), limit int) (string, bool) { + for _, m := range envVarRE.FindAllStringSubmatch(line, -1) { + envVar, varName := m[0], m[1] + value, _ := lookup(varName) + if value == "" { + continue + } + if n := strings.Count(line, envVar); len(line)+n*(len(value)-len(envVar)) > limit { + return "", false + } + line = strings.ReplaceAll(line, envVar, value) + } + return line, true +} + +// FuzzExpandEnv compares expandEnv with pip's algorithm. The fuzzer sets the +// values of the variables A, B and AB. expandEnv uses one pass when pip's +// order gives the same result, so this checks that it never takes the fast +// path when the results differ. When expandEnv returns an error, the error +// must be one of its limits, or errEnvLineBreak. A value joins bytes into a +// line break only when some input is not valid UTF-8 and pip's result has a +// multi-byte line break. +func FuzzExpandEnv(f *testing.F) { + type seed struct{ text, a, b, ab string } + seeds := []seed{ + {"--index-url https://${A}:${B}@h/s", "u", "t", ""}, + {"${A} ${B}", "${B}", "t", ""}, + {"${B} ${A}", "${B}", "t", ""}, + {"${B} ${A} ${B}", "${B}", "t", ""}, + {"${A}", "${A}x", "", ""}, + {"${A} ${A}", "${A}x", "", ""}, + {"${B} ${A}{B} ${B}", "$", "t", ""}, + {"${A${B}} ${AB}", "", "B", "t"}, + {"${MISSING} ${A} ${MISSING}", "${B}", "t", ""}, + {"${A} ${B}", "", "t", ""}, + {"$${A} ${${B}} $A ${A", "x", "y", ""}, + {strings.Repeat("${A}", 30), "${A}${A}", "", ""}, + {"${B}" + strings.Repeat(" ${A}", 100), "${A}", "t", ""}, + {strings.Repeat("${A}${B}", 1000), "x", "y", ""}, + // Values that join bytes into a line break, in one pass and in pip's + // order. + {"${A}\x85", "\xc2", "", ""}, + {"\xe2${A}${B}", "\x80", "\xa8", ""}, + {"\xc2${A}${B}x", "${B}", "\x85", ""}, + } + for _, s := range seeds { + f.Add(s.text, s.a, s.b, s.ab) + } + for _, s := range fuzzseed.Strings("${A} ${B}", "${B}${A}${AB}", "x${A}y") { + f.Add(s, "${B}", "t", "$") + } + + f.Fuzz(func(t *testing.T, text, a, b, ab string) { + lookup := func(name string) (string, bool) { + switch name { + case "A": + return a, true + case "B": + return b, true + case "AB": + return ab, true + } + return "", false + } + + start := time.Now() + got, err := expandEnv(text, lookup, maxEnvExpansion) + fuzzseed.Within(t, start, text) + if errors.Is(err, errEnvLineBreak) { + // pip's result can grow past the limit after the join. Then only + // the inputs are checked. + want, ok := pipExpandEnv(text, lookup, len(text)+maxEnvExpansion) + valid := utf8.ValidString(text) && utf8.ValidString(a) && utf8.ValidString(b) && utf8.ValidString(ab) + if valid || (ok && countMultiByteLineBreaks(want) == 0) { + t.Fatalf("expandEnv(%q) with A=%q B=%q AB=%q: no bytes can join into a line break, but: %v", + text, a, b, ab, err) + } + return + } + if err != nil { + msg := err.Error() + if !strings.Contains(msg, "more than 100 references") && !strings.Contains(msg, "makes the line longer than") && + !strings.Contains(msg, "pip's order reads more than") { + t.Fatalf("expandEnv(%q) with A=%q B=%q AB=%q: unexpected error: %v", text, a, b, ab, err) + } + return + } + // When expandEnv succeeds, each step of pip's algorithm is at most the + // one-pass length plus maxEnvGrowth, and the one-pass length is at + // most this bound. + onePassBound := len(text) + strings.Count(text, "${")*(len(a)+len(b)+len(ab)) + want, ok := pipExpandEnv(text, lookup, onePassBound+maxEnvGrowth) + if !ok { + t.Fatalf("expandEnv(%q) with A=%q B=%q AB=%q gave no error, but pip's algorithm grows past the limit", + text, a, b, ab) + } + if got != want { + t.Fatalf("expandEnv(%q) with A=%q B=%q AB=%q = %q, but pip gives %q", text, a, b, ab, got, want) + } + }) +} diff --git a/reqtxt/fast_path_test.go b/reqtxt/fast_path_test.go new file mode 100644 index 0000000..17cc41c --- /dev/null +++ b/reqtxt/fast_path_test.go @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +// fastPathPieces are short strings that the fast paths treat specially. +// fastPathInputs joins them in every order of up to three pieces. +var fastPathPieces = []string{ + "a", "Z", "0", "#", "-", ";", "@", "/", ".", " ", "\t", "\n", "\r", "\r\n", + "\v", "\f", "\x1c", "\x1e", "\x1f", "\x00", "\x7f", "\"", "'", "\\", + "\u0085", "\u00a0", "\u2028", "\u2029", "\u00e9", + "\xc2", "\xe2\x80", "\xe2", "\xff", "\x85", "\xa8", +} + +func fastPathInputs() []string { + out := []string{""} + for _, a := range fastPathPieces { + out = append(out, a) + for _, b := range fastPathPieces { + out = append(out, a+b) + for _, c := range fastPathPieces { + out = append(out, a+b+c) + } + } + } + return out +} + +// normalizeLineEndings skips lineBreaks.Replace when there is nothing to +// replace, so the two must agree on every input, also one that is not valid +// UTF-8 or that holds only part of a multi-byte line break. +func TestNormalizeLineEndings_FastPathMatchesReplacer(t *testing.T) { + for _, s := range fastPathInputs() { + if got, want := normalizeLineEndings(s), lineBreaks.Replace(s); got != want { + t.Errorf("normalizeLineEndings(%q) = %q, want %q", s, got, want) + } + } +} + +// When plainASCII is true, the full check in quoteIfNeeded must also leave s +// unchanged, so the fast path never skips a quote that is needed. +func TestPlainASCII_ImpliesNoQuotes(t *testing.T) { + for _, s := range fastPathInputs() { + if !plainASCII(s) { + continue + } + needsQuotes := strings.ContainsAny(s, `"'\`) || strings.IndexFunc(s, isPythonSpace) >= 0 || commentStartIndex(s) >= 0 + assert.False(t, needsQuotes, "%q is plain ASCII but needs quotes", s) + } + for _, s := range []string{"abc", "sha256:0123abcdef", "a#b", "x-y", "1.0", "https://h/p?q=1"} { + assert.True(t, plainASCII(s), "%q", s) + } + for _, s := range []string{"", "#a", "a b", "a\tb", "a\"b", "a'b", `a\b`, "a\x7f", "caf\u00e9"} { + assert.False(t, plainASCII(s), "%q", s) + } +} + +// firstField must return the first field that strings.Fields gives. +func TestFirstField_MatchesFields(t *testing.T) { + for _, s := range fastPathInputs() { + want := "" + if fields := strings.Fields(s); len(fields) > 0 { + want = fields[0] + } + if got := firstField(s); got != want { + t.Errorf("firstField(%q) = %q, want %q", s, got, want) + } + } +} + +// hasTarSuffix compares only the last 4 bytes, so it must agree with the +// ToLower code that it replaces on every input: also with letters in upper +// case, with runes that lower to ASCII (U+212A and U+0130), and with text +// that is not valid UTF-8. +func TestHasTarSuffix_MatchesToLower(t *testing.T) { + pieces := []string{ + "", ".", "t", "T", "a", "A", "r", "R", ".t", ".T", "ar", "AR", "aR", + "x", "K", "İ", "é", "\xff", "\xe2", "\xe2\x80", + } + for _, a := range pieces { + for _, b := range pieces { + for _, c := range pieces { + for _, d := range pieces { + s := a + b + c + d + want := strings.HasSuffix(strings.ToLower(s), ".tar") + assert.Equal(t, want, hasTarSuffix(s), "hasTarSuffix(%q)", s) + } + } + } + } +} diff --git a/reqtxt/flatten.go b/reqtxt/flatten.go index 389eb7d..0167703 100644 --- a/reqtxt/flatten.go +++ b/reqtxt/flatten.go @@ -18,7 +18,10 @@ import ( "net/url" "path" "regexp" + "slices" "strings" + + "github.com/posit-dev/go-python-packaging/internal/errtext" ) // utf8BOM is the UTF-8 encoding of U+FEFF (byte order mark), which some @@ -35,20 +38,65 @@ var utf8BOM = []byte{0xEF, 0xBB, 0xBF} // referencing file's directory. var schemeRE = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*://`) -// Flatten parses the file at root and follows its "-r"/"-c" includes -// (pip's parse_requirements / RequirementsFileParser._parse_and_recurse in -// pip._internal.req.req_file) to produce a single File with every include -// expanded inline, in the order encountered by a depth-first traversal. -// Each IncludeEntry is consumed and dropped; the entries of the file it -// references are spliced into its place. All file content is obtained via -// open, which Flatten decodes as UTF-8, stripping a leading byte-order -// mark. root is passed to open verbatim; relative include targets nested -// inside it (and inside whatever it includes) are resolved against the -// referencing file's directory using slash-based path semantics - -// deliberately not the OS-dependent filepath package, so behavior doesn't -// depend on host CWD or path separator. opts is threaded to every -// recursive Parse call, so e.g. WithEnv expansion is applied consistently -// at every level of the include tree. +// Limits on the includes that one Flatten call follows. Without them, a chain +// of includes, or a few includes in each file, can open millions of files. +// +// The file limit alone does not limit the result, because each include of a +// file adds its entries again. A 22 KB root file that includes one 10 KB file +// 2,000 times gives 10 million entries. So Flatten also limits the bytes of +// the included files and the entries it returns. Flatten parses each file +// only once, but every limit counts each include, as if it parsed the file +// again. +const ( + // maxIncludeDepth is the maximum number of nested includes. + maxIncludeDepth = 100 + // maxIncludedFiles is the maximum number of includes, the root included. + maxIncludedFiles = 10_000 + // maxIncludedBytes is the maximum total size of the included files, + // counted again for each include of a file. + maxIncludedBytes = 64 << 20 + // maxFlattenedEntries is the maximum number of entries in the File that + // Flatten returns. + maxFlattenedEntries = 100_000 +) + +// flattenState is the state that one Flatten call shares across its walk. +type flattenState struct { + // visited is the set of paths on the current include stack. + visited map[string]bool + // parsed holds each file that has been parsed, by path, so that a file + // included more than once is opened and parsed only once. + parsed map[string]parsedFile + // opened counts the includes so far, as if each one opened its file. + opened int + // bytes counts the bytes of all the included files so far, again for + // each include of a file. + bytes int + // entries counts the entries of the result so far. + entries int + // cfg is the parseConfig of the caller's options. flattenWalk sets the + // path and the limits in a copy for each file. + cfg parseConfig +} + +// parsedFile is one parsed file of a Flatten call. +type parsedFile struct { + entries []Entry + // size is the length of the file after ${NAME} expansion, for the byte + // limit. + size int +} + +// Flatten parses the file at root and follows its "-r"/"-c" includes, as pip +// does. It replaces each include with the entries of the file that it specifies, +// depth first. Flatten resolves a relative include against the directory of +// the file that includes it, with package path, so the result does not depend +// on the OS. opts applies to every file. Flatten opens and parses each file +// once, also when it is included more than once. +// +// Flatten returns an error for includes nested more than 100 deep, more than +// 10,000 includes, more than 64 MiB of included files after ${NAME} expansion, +// or more than 100,000 entries. Each include of a file counts again. func Flatten(root string, open func(path string) ([]byte, error), opts ...ParseOption) (*File, error) { // open is mandatory and is called for the root before anything else, so a nil // callback would panic on the first dereference. In a CLI a stack trace is a @@ -57,48 +105,123 @@ func Flatten(root string, open func(path string) ([]byte, error), opts ...ParseO if open == nil { return nil, errors.Join(ErrInvalidRequirementsFile, errors.New("Flatten requires a non-nil open callback")) } - entries, err := flattenWalk(root, false, map[string]bool{}, open, opts) + st := &flattenState{visited: map[string]bool{}, parsed: map[string]parsedFile{}} + for _, opt := range opts { + opt(&st.cfg) + } + entries, err := flattenWalk(root, false, st, open, nil) if err != nil { return nil, err } return &File{Entries: entries}, nil } -// flattenWalk parses the file at p and recursively expands its includes, -// returning the flattened entries it (transitively) contributes. -// constraintCtx is true if p was itself reached via a "-c"/"--constraint" -// include - specifically the immediate include directive that pulled p in, -// not any ancestor further up the include chain (see childConstraint below); -// visited is the set of resolved -// paths on the CURRENT recursion stack, used for cycle detection - a -// diamond (the same file reached via two different, non-overlapping -// branches) is fine and yields its entries twice (see the double-inclusion -// case below); a path already on the active stack is a true cycle. -func flattenWalk(p string, constraintCtx bool, visited map[string]bool, open func(string) ([]byte, error), opts []ParseOption) ([]Entry, error) { +// flattenWalk parses the file at p, expands its includes, and appends the +// entries to out. All levels append to the same slice, so no level copies an +// entry again. +// +// constraintCtx is true if the include that reached p is a "-c" include. Only +// that include sets it, not an include above it (see childConstraint). +// st.visited holds the paths on the current include stack, and a path that is +// already on it is a cycle. A file reached through two different branches is +// not a cycle, and it gives its entries two times. +// +// flattenWalk does not open or parse a file again when it is included again. +// It copies the entries from st.parsed with new slices, so no two entries of +// the result share a slice. The limits still count each include. +func flattenWalk( + p string, + constraintCtx bool, + st *flattenState, + openFn func(string) ([]byte, error), + out []Entry, +) ([]Entry, error) { + visited := st.visited if visited[p] { - return nil, errors.Join(ErrInvalidRequirementsFile, fmt.Errorf("%q recursively includes itself", p)) + return nil, errors.Join(ErrInvalidRequirementsFile, fmt.Errorf("%s recursively includes itself", errtext.Quote(p))) } - - raw, err := open(p) - if err != nil { - return nil, errors.Join(ErrInvalidRequirementsFile, fmt.Errorf("opening %q: %w", p, err)) + // visited holds the root and each include above p. + if len(visited) > maxIncludeDepth { + return nil, errors.Join( + ErrInvalidRequirementsFile, + fmt.Errorf("includes are nested more than %d deep at %s", maxIncludeDepth, errtext.Quote(p)), + ) + } + if st.opened >= maxIncludedFiles { + return nil, filesOverLimit(p) } + st.opened++ - content := decodeUTF8(raw) + file, reused := st.parsed[p] + if !reused { + raw, err := openFn(p) + if err != nil { + return nil, errors.Join(ErrInvalidRequirementsFile, fmt.Errorf("opening %s: %w", errtext.Quote(p), err)) + } + file.size = len(raw) + // Check before Parse, so that an over-limit file is not parsed. + if st.bytes+file.size > maxIncludedBytes { + return nil, bytesOverLimit(p) + } - // WithPath is appended rather than prepended so a caller's own WithPath - // cannot silently attribute every included file to one path. Each level - // records the file actually opened. - file, err := Parse(content, append(append([]ParseOption(nil), opts...), WithPath(p))...) - if err != nil { - return nil, err + // The path is set after the caller's options, so that a caller's own + // WithPath cannot attribute every included file to one path. Each level + // records the file actually opened. The limits stop Parse at the limits + // of this call, so a large file is not parsed to its end first. The + // includes that p can still have are the files that can still be + // opened: this walk counts p, and each include opens a file. ${NAME} + // expansion may add only the bytes that are left under + // maxIncludedBytes, so the byte limit counts the file as expanded. + bytesLeft := min(maxEnvExpansion, maxIncludedBytes-st.bytes-file.size) + cfg := st.cfg + cfg.path = p + cfg.flatten = flattenLimits{ + entries: maxFlattenedEntries - st.entries, + includes: maxIncludedFiles - st.opened, + envBudget: bytesLeft, + } + cfg.hasFlattenLimits = true + parsed, envGrowth, err := parseWithConfig(decodeUTF8(raw), cfg) + switch { + case errors.Is(err, errTooManyEntries): + return nil, entriesOverLimit(p) + case errors.Is(err, errTooManyIncludes): + return nil, filesOverLimit(p) + case errors.Is(err, errEnvExpansion) && bytesLeft < maxEnvExpansion: + return nil, bytesOverLimit(p) + case err != nil: + return nil, err + } + // Each later include of p counts its expanded size again. + file.size += envGrowth + file.entries = parsed.Entries + st.parsed[p] = file + } + st.bytes += file.size + if st.bytes > maxIncludedBytes { + return nil, bytesOverLimit(p) + } + + // Each entry other than an include goes into the result. An include is + // replaced by the entries of its file, which that walk counts. + for _, e := range file.entries { + if _, isInclude := e.(*IncludeEntry); !isInclude { + st.entries++ + } + } + if st.entries > maxFlattenedEntries { + return nil, entriesOverLimit(p) } visited[p] = true defer delete(visited, p) - var out []Entry - for _, e := range file.Entries { + // Each entry of the result is a copy, so that Flatten can set Constraint. + // For a file that is included again, the copy also gets new slices, as a + // second parse would give. Then a caller that changes one entry of the + // result does not change another. An IncludeEntry is not copied: Flatten + // replaces it and never returns it. + for _, e := range file.entries { switch v := e.(type) { case *IncludeEntry: target := resolveInclude(p, v.Path) @@ -117,22 +240,38 @@ func flattenWalk(p string, constraintCtx bool, visited map[string]bool, open fun // context. childConstraint := v.Constraint - children, err := flattenWalk(target, childConstraint, visited, open, opts) - if err != nil { - return nil, err + var walkErr error + out, walkErr = flattenWalk(target, childConstraint, st, openFn, out) + if walkErr != nil { + return nil, walkErr } - out = append(out, children...) case *RequirementEntry: cp := *v + if reused { + cp.Requirement.Extras = slices.Clone(v.Requirement.Extras) + cp.Hashes = slices.Clone(v.Hashes) + cp.Options = slices.Clone(v.Options) + } cp.Constraint = constraintCtx || v.Constraint out = append(out, &cp) case *UnnamedEntry: cp := *v + if reused { + cp.Hashes = slices.Clone(v.Hashes) + cp.Options = slices.Clone(v.Options) + } cp.Constraint = constraintCtx || v.Constraint out = append(out, &cp) + case *OptionEntry: + if reused { + cp := *v + e = &cp + } + out = append(out, e) + default: out = append(out, e) } @@ -141,6 +280,33 @@ func flattenWalk(p string, constraintCtx bool, visited map[string]bool, open fun return out, nil } +// bytesOverLimit is the error for an include of p that takes the bytes of the +// included files over maxIncludedBytes. +func bytesOverLimit(p string) error { + return errors.Join( + ErrInvalidRequirementsFile, + fmt.Errorf("included files are more than %d bytes in total, at %s", maxIncludedBytes, errtext.Quote(p)), + ) +} + +// filesOverLimit returns the error for more than maxIncludedFiles includes, +// found at the file p. +func filesOverLimit(p string) error { + return errors.Join( + ErrInvalidRequirementsFile, + fmt.Errorf("more than %d files are included, at %s", maxIncludedFiles, errtext.Quote(p)), + ) +} + +// entriesOverLimit returns the error for a result of more than +// maxFlattenedEntries entries, found at the file p. +func entriesOverLimit(p string) error { + return errors.Join( + ErrInvalidRequirementsFile, + fmt.Errorf("the result has more than %d entries, at %s", maxFlattenedEntries, errtext.Quote(p)), + ) +} + // decodeUTF8 decodes raw as UTF-8 text, stripping a leading byte-order // mark if present. func decodeUTF8(raw []byte) string { diff --git a/reqtxt/flatten_cache_test.go b/reqtxt/flatten_cache_test.go new file mode 100644 index 0000000..dc3d04e --- /dev/null +++ b/reqtxt/flatten_cache_test.go @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// sharedFile is included more than once by the tests below. +const sharedFile = "foo[a]>=1.0 --hash=sha256:aaa --config-settings=k=v\n" + + "./pkg.whl --hash=sha256:bbb\n" + + "--pre\n" + +// countingOpen serves files and counts the calls to open for each path. +func countingOpen(files map[string]string) (func(string) ([]byte, error), map[string]int) { + calls := map[string]int{} + return func(p string) ([]byte, error) { + calls[p]++ + return []byte(files[p]), nil + }, calls +} + +// Flatten opens and parses a file once, also when it is included more than +// once, and still returns its entries for each include. +func TestFlatten_OpensEachFileOnce(t *testing.T) { + open, calls := countingOpen(map[string]string{ + "root.txt": "-r shared.txt\n-r sub/a.txt\n-r shared.txt\n", + "sub/a.txt": "-r ../shared.txt\n", + "shared.txt": sharedFile, + }) + f, err := Flatten("root.txt", open) + require.NoError(t, err) + + assert.Equal(t, map[string]int{"root.txt": 1, "sub/a.txt": 1, "shared.txt": 1}, calls) + assert.Len(t, f.Entries, 9, "the 3 entries of shared.txt, 3 times") +} + +// Each include of a file gives entries that share nothing, as a second parse +// would, so that changing one entry of the result does not change another. +func TestFlatten_RepeatedIncludeEntriesAreIndependent(t *testing.T) { + open, _ := countingOpen(map[string]string{ + "root.txt": "-r shared.txt\n-r shared.txt\n", + "shared.txt": sharedFile, + }) + f, err := Flatten("root.txt", open) + require.NoError(t, err) + require.Len(t, f.Entries, 6) + + req1, req2 := f.Entries[0].(*RequirementEntry), f.Entries[3].(*RequirementEntry) + unnamed1, unnamed2 := f.Entries[1].(*UnnamedEntry), f.Entries[4].(*UnnamedEntry) + opt1, opt2 := f.Entries[2].(*OptionEntry), f.Entries[5].(*OptionEntry) + require.NotSame(t, req1, req2) + require.NotSame(t, unnamed1, unnamed2) + require.NotSame(t, opt1, opt2) + + req1.Requirement.Extras[0] = "changed" + req1.Hashes[0].Digest = "changed" + req1.Options[0].Value = "changed" + unnamed1.Hashes[0].Digest = "changed" + opt1.Value = "changed" + + assert.Equal(t, []string{"a"}, req2.Requirement.Extras) + assert.Equal(t, "aaa", req2.Hashes[0].Digest) + assert.Equal(t, "k=v", req2.Options[0].Value) + assert.Equal(t, "bbb", unnamed2.Hashes[0].Digest) + assert.Equal(t, "", opt2.Value) +} + +// Constraint-ness comes from each include directive, so the same file can be +// a requirement in one place and a constraint in another. +func TestFlatten_RepeatedIncludeKeepsEachConstraint(t *testing.T) { + open, calls := countingOpen(map[string]string{ + "root.txt": "-r shared.txt\n-c shared.txt\n-r shared.txt\n", + "shared.txt": sharedFile, + }) + f, err := Flatten("root.txt", open) + require.NoError(t, err) + require.Len(t, f.Entries, 9) + assert.Equal(t, 1, calls["shared.txt"]) + + for i, want := range []bool{false, true, false} { + assert.Equal(t, want, f.Entries[3*i].(*RequirementEntry).Constraint, "include %d", i) + assert.Equal(t, want, f.Entries[3*i+1].(*UnnamedEntry).Constraint, "include %d", i) + } +} diff --git a/reqtxt/flatten_limits_test.go b/reqtxt/flatten_limits_test.go new file mode 100644 index 0000000..55640f4 --- /dev/null +++ b/reqtxt/flatten_limits_test.go @@ -0,0 +1,492 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "bytes" + "errors" + "fmt" + "runtime" + "strings" + "testing" + "time" + + "github.com/posit-dev/go-python-packaging/internal/race" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// chainOpen serves a chain of files: f0.txt includes f1.txt, and so on. +// The last file, f.txt, holds one requirement. +func chainOpen(depth int) func(string) ([]byte, error) { + return includeChainOpen(depth, "-r", 1) +} + +// includeChainOpen is like chainOpen, but each file includes the next file +// count times, with the include option directive. +func includeChainOpen(depth int, directive string, count int) func(string) ([]byte, error) { + return func(p string) ([]byte, error) { + var n int + if _, err := fmt.Sscanf(p, "f%d.txt", &n); err != nil { + return nil, fmt.Errorf("unexpected path %q", p) + } + if n == depth { + return []byte("foo\n"), nil + } + return []byte(strings.Repeat(fmt.Sprintf("%s f%d.txt\n", directive, n+1), count)), nil + } +} + +// withRoot serves text as root.txt, and every other file from open. +func withRoot(text string, open func(string) ([]byte, error)) func(string) ([]byte, error) { + return func(p string) ([]byte, error) { + if p == "root.txt" { + return []byte(text), nil + } + return open(p) + } +} + +// fanOutOpen serves a root file that includes n leaf files. Each leaf holds one +// requirement. +func fanOutOpen(n int) func(string) ([]byte, error) { + return func(p string) ([]byte, error) { + if p != "root.txt" { + return []byte("foo\n"), nil + } + var b strings.Builder + for i := range n { + fmt.Fprintf(&b, "-r leaf%d.txt\n", i) + } + return []byte(b.String()), nil + } +} + +// treeOpen serves a tree in which each file at a depth less than depth +// includes two more files. +func treeOpen(depth int) func(string) ([]byte, error) { + return func(p string) ([]byte, error) { + d := strings.Count(p, "/") + if d >= depth { + return []byte("foo\n"), nil + } + dir := strings.TrimSuffix(p, ".txt") + return []byte(fmt.Sprintf("-r %s/a.txt\n-r %s/b.txt\n", lastElem(dir), lastElem(dir))), nil + } +} + +// leafOpen serves every file as one requirement. +func leafOpen(string) ([]byte, error) { + return []byte("foo\n"), nil +} + +// chainOrLeafOpen serves leaf.txt as one requirement, and every other file +// from chainOpen(depth). +func chainOrLeafOpen(depth int) func(string) ([]byte, error) { + chain := chainOpen(depth) + return func(p string) ([]byte, error) { + if p == "leaf.txt" { + return leafOpen(p) + } + return chain(p) + } +} + +// linesOpen serves every file as n lines, each one requirement. +func linesOpen(n int) func(string) ([]byte, error) { + return func(string) ([]byte, error) { + return []byte(strings.Repeat("foo\n", n)), nil + } +} + +// commentOpen serves every file as one comment line of size bytes, with no +// line break. The file has no entries. +func commentOpen(size int) func(string) ([]byte, error) { + return func(string) ([]byte, error) { + b := bytes.Repeat([]byte("x"), size) + b[0] = '#' + return b, nil + } +} + +// lastElem returns the last element of a slash path. +func lastElem(p string) string { + if i := strings.LastIndex(p, "/"); i >= 0 { + return p[i+1:] + } + return p +} + +func TestFlatten_Limits(t *testing.T) { + tests := []struct { + name string + root string + open func(string) ([]byte, error) + // wantEntries is the number of entries on success. + wantEntries int + // wantErr is a substring of the error. Empty means no error. + wantErr string + }{ + { + name: "include chain at the depth limit", + root: "f0.txt", + open: chainOpen(maxIncludeDepth), + wantEntries: 1, + }, + { + name: "include chain one deeper than the limit", + root: "f0.txt", + open: chainOpen(maxIncludeDepth + 1), + wantErr: `includes are nested more than 100 deep at "f101.txt"`, + }, + { + name: "very long include chain", + root: "f0.txt", + open: chainOpen(1_000_000), + wantErr: "includes are nested more than 100 deep", + }, + { + // The root and the leaves are exactly maxIncludedFiles files. + name: "fan-out at the file limit", + root: "root.txt", + open: fanOutOpen(maxIncludedFiles - 1), + wantEntries: maxIncludedFiles - 1, + }, + { + name: "fan-out one file over the limit", + root: "root.txt", + open: fanOutOpen(maxIncludedFiles), + wantErr: "more than 10000 files are included", + }, + { + // Found by hand: this tree is 2,097,151 files, 20 levels deep. + name: "two includes per file, 20 levels deep", + root: "r.txt", + open: treeOpen(20), + wantErr: "more than 10000 files are included", + }, + + // Each include of the same file opens it again, and counts again. + { + // The root and the includes are exactly maxIncludedFiles opens. + name: "same file included up to the file limit", + root: "root.txt", + open: withRoot(strings.Repeat("-r leaf.txt\n", maxIncludedFiles-1), leafOpen), + wantEntries: maxIncludedFiles - 1, + }, + { + // Parse stops at the include of root.txt that is over the limit, + // so the error names root.txt. + name: "same file included one time over the file limit", + root: "root.txt", + open: withRoot(strings.Repeat("-r leaf.txt\n", maxIncludedFiles), leafOpen), + wantErr: `more than 10000 files are included, at "root.txt"`, + }, + { + // 13 levels of files are 8,191 opens and 4,096 entries. + name: "each file includes the next file twice, under the file limit", + root: "f0.txt", + open: includeChainOpen(12, "-r", 2), + wantEntries: 4096, + }, + { + // 41 levels of files are 2^41 - 1 opens without the limit. + name: "each file includes the next file twice, 40 levels deep", + root: "f0.txt", + open: includeChainOpen(40, "-r", 2), + wantErr: "more than 10000 files are included", + }, + + // The depth is the number of includes on the current path, not the + // number of includes so far. + { + // root.txt, then f1.txt to f100.txt, two times. + name: "same chain included twice at the depth limit", + root: "root.txt", + open: withRoot("-r f1.txt\n-r f1.txt\n", chainOpen(maxIncludeDepth)), + wantEntries: 2, + }, + + // A "-c" include counts the same as a "-r" include. + { + name: "constraint chain at the depth limit", + root: "f0.txt", + open: includeChainOpen(maxIncludeDepth, "-c", 1), + wantEntries: 1, + }, + { + name: "constraint chain one deeper than the limit", + root: "f0.txt", + open: includeChainOpen(maxIncludeDepth+1, "-c", 1), + wantErr: `includes are nested more than 100 deep at "f101.txt"`, + }, + + // Both limits at the same time. The 100 files of the chain count + // toward the file limit. + { + // 1 root, 100 chain files and 9,899 leaves are 10,000 opens. + name: "chain at the depth limit, and leaves up to the file limit", + root: "root.txt", + open: withRoot( + "-r f1.txt\n"+strings.Repeat("-r leaf.txt\n", maxIncludedFiles-1-maxIncludeDepth), + chainOrLeafOpen(maxIncludeDepth), + ), + wantEntries: 1 + maxIncludedFiles - 1 - maxIncludeDepth, + }, + { + name: "chain at the depth limit, and leaves one over the file limit", + root: "root.txt", + open: withRoot( + "-r f1.txt\n"+strings.Repeat("-r leaf.txt\n", maxIncludedFiles-maxIncludeDepth), + chainOrLeafOpen(maxIncludeDepth), + ), + wantErr: `more than 10000 files are included, at "leaf.txt"`, + }, + + // The entries of the result. An include of the same file adds its + // entries again. + { + // 100 includes of a file with 1,000 requirements. + name: "entries at the entry limit", + root: "root.txt", + open: withRoot(strings.Repeat("-r big.txt\n", 100), linesOpen(1000)), + wantEntries: maxFlattenedEntries, + }, + { + name: "entries one over the entry limit", + root: "root.txt", + open: withRoot("foo\n"+strings.Repeat("-r big.txt\n", 100), linesOpen(1000)), + wantErr: `the result has more than 100000 entries, at "big.txt"`, + }, + { + // Found by review: 32 KB of files gave 10 million entries and + // 8 GB of allocations under the file limit. + name: "same file of 5,000 requirements included 2,000 times", + root: "root.txt", + open: withRoot(strings.Repeat("-r big.txt\n", 2000), linesOpen(5000)), + wantErr: "the result has more than 100000 entries", + }, + + { + name: "root file at the entry limit", + root: "root.txt", + open: withRoot(strings.Repeat("a\n", maxFlattenedEntries), nil), + wantEntries: maxFlattenedEntries, + }, + { + name: "root file one over the entry limit", + root: "root.txt", + open: withRoot(strings.Repeat("a\n", maxFlattenedEntries+1), nil), + wantErr: `the result has more than 100000 entries, at "root.txt"`, + }, + { + // Includes are not entries of the result, so they do not count. + name: "root file at the entry limit, with includes", + root: "root.txt", + open: withRoot( + strings.Repeat("a\n", maxFlattenedEntries)+strings.Repeat("-r empty.txt\n", 10), + func(string) ([]byte, error) { return nil, nil }, + ), + wantEntries: maxFlattenedEntries, + }, + + // A file with more includes than files that can still be opened is + // over the file limit, so Parse stops at that include. + { + // 1 root and 9,999 includes are 10,000 opens. + name: "root file with includes up to the file limit", + root: "root.txt", + open: withRoot(strings.Repeat("-r empty.txt\n", maxIncludedFiles-1), func(string) ([]byte, error) { return nil, nil }), + wantEntries: 0, + }, + { + name: "root file with includes one over the file limit", + root: "root.txt", + open: withRoot(strings.Repeat("-r empty.txt\n", maxIncludedFiles), func(string) ([]byte, error) { return nil, nil }), + wantErr: `more than 10000 files are included, at "root.txt"`, + }, + + // The bytes read. An include of the same file reads it again. + { + // The 11-byte root and the comment file are exactly + // maxIncludedBytes bytes. + name: "bytes at the byte limit", + root: "root.txt", + open: withRoot("-r big.txt\n", commentOpen(maxIncludedBytes-11)), + wantEntries: 0, + }, + { + name: "bytes one over the byte limit", + root: "root.txt", + open: withRoot("-r big.txt\n", commentOpen(maxIncludedBytes-10)), + wantErr: `included files are more than 67108864 bytes in total, at "big.txt"`, + }, + { + // No entries, but 10 GB to parse without the byte limit. + name: "same 1 MiB comment file included up to the file limit", + root: "root.txt", + open: withRoot(strings.Repeat("-r big.txt\n", maxIncludedFiles-1), commentOpen(1<<20)), + wantErr: "included files are more than 67108864 bytes in total", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // When Flatten does not obey the file limit, open returns an + // error after the limit. Then the test fails quickly, and does + // not run until the test timeout. + opens := 0 + open := func(p string) ([]byte, error) { + opens++ + if opens > maxIncludedFiles { + return nil, fmt.Errorf("test opened more than %d files", maxIncludedFiles) + } + return tt.open(p) + } + start := time.Now() + f, err := Flatten(tt.root, open) + // The race detector makes the code much slower (see package race). + if !race.Enabled { + assert.Less(t, time.Since(start), 5*time.Second, "Flatten stops quickly") + } + assert.LessOrEqual(t, opens, maxIncludedFiles, "Flatten opens at most maxIncludedFiles files") + if tt.wantErr != "" { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + assert.Len(t, f.Entries, tt.wantEntries) + }) + } +} + +// Flatten stops parsing a file at the entry limit, so a large file costs +// about as much as the limit, not as much as the file. Found by review: before, +// Flatten parsed the whole root file first, and 8 MiB of "a\n" allocated +// 2.2 GB before it returned the entry error. At the byte limit of 64 MiB, this +// was about 18 GB. +func TestFlatten_LargeFileStopsAtEntryLimit(t *testing.T) { + if race.Enabled { + t.Skip("the race detector adds allocations") + } + content := []byte(strings.Repeat("a\n", 4_000_000)) + open := func(string) ([]byte, error) { return content, nil } + + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + _, err := Flatten("root.txt", open) + runtime.ReadMemStats(&after) + + require.Error(t, err) + assert.Contains(t, err.Error(), `the result has more than 100000 entries, at "root.txt"`) + // Parse of 100,000 requirements allocates about 55 MB. + assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(200<<20), "bytes allocated") +} + +// Flatten also stops parsing a file at the include that is over the file +// limit. Before, a 20 MB file of 4 million includes made all of them first. +func TestFlatten_LargeFileStopsAtFileLimit(t *testing.T) { + if race.Enabled { + t.Skip("the race detector adds allocations") + } + content := []byte(strings.Repeat("-r x\n", 4_000_000)) + open := func(string) ([]byte, error) { return content, nil } + + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + _, err := Flatten("root.txt", open) + runtime.ReadMemStats(&after) + + require.Error(t, err) + assert.Contains(t, err.Error(), `more than 10000 files are included, at "root.txt"`) + assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(200<<20), "bytes allocated") +} + +// withFlattenLimits replaces the entry limit of Parse with two limits: one +// for the entries other than IncludeEntry, and one for the includes. Flatten +// replaces errTooManyEntries and errTooManyIncludes with its own errors. +func TestParse_WithFlattenLimits(t *testing.T) { + tests := []struct { + name string + content string + limits flattenLimits + wantErr error + }{ + {name: "at both limits", content: "a\n-r x.txt\nb\n", limits: flattenLimits{entries: 2, includes: 1}}, + {name: "one entry over", content: "a\nb\nc\n", limits: flattenLimits{entries: 2, includes: 9}, wantErr: errTooManyEntries}, + {name: "one include over", content: "-r x.txt\n-c y.txt\n", limits: flattenLimits{entries: 9, includes: 1}, wantErr: errTooManyIncludes}, + {name: "includes do not count as entries", content: "a\n-r x.txt\n-c y.txt\n", limits: flattenLimits{entries: 1, includes: 2}}, + {name: "limits of 0 and no entries", content: "# comment\n", limits: flattenLimits{}}, + {name: "option lines count as entries", content: "--pre\na\n", limits: flattenLimits{entries: 1}, wantErr: errTooManyEntries}, + { + // Flatten has its own limits, so the limit of Parse does not apply. + name: "more than maxParseEntries", + content: strings.Repeat("a\n", maxParseEntries) + "-r x.txt\n", + limits: flattenLimits{entries: maxParseEntries, includes: 1}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.content, withFlattenLimits(tt.limits)) + if tt.wantErr != nil { + assert.ErrorIs(t, err, tt.wantErr) + return + } + require.NoError(t, err) + unlimited, err := Parse(tt.content, withFlattenLimits(flattenLimits{entries: 1 << 30, includes: 1 << 30})) + require.NoError(t, err) + assert.Equal(t, unlimited.Entries, f.Entries, "same entries as with no limit") + }) + } +} + +// Flatten counts the bytes that ${NAME} expansion adds in maxIncludedBytes, +// also for each later include of a file that it parsed once. Without this, +// each of 10,000 included files could add maxEnvExpansion bytes. +func TestFlatten_EnvExpansionCountsInByteLimit(t *testing.T) { + value := strings.Repeat("x", 15<<20) // 15 MiB + lookup := func(string) (string, bool) { return value, true } + + tests := []struct { + name string + includes int + wantErr string + }{ + // 4 × 15 MiB is under 64 MiB. + {name: "four includes", includes: 4}, + // 5 × 15 MiB is over 64 MiB, although the raw files are small. + {name: "five includes", includes: 5, wantErr: `included files are more than 67108864 bytes in total, at "a.txt"`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + open := withRoot(strings.Repeat("-r a.txt\n", tt.includes), func(string) ([]byte, error) { + return []byte("${A}\n"), nil + }) + f, err := Flatten("root.txt", open, WithEnv(lookup)) + if tt.wantErr == "" { + require.NoError(t, err) + assert.Len(t, f.Entries, tt.includes) + return + } + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + }) + } +} + +// When Flatten has less than maxEnvExpansion left under maxIncludedBytes, an +// expansion over what is left is a byte-limit error, not an expansion error. +func TestFlatten_EnvExpansionOverBytesLeft(t *testing.T) { + value := strings.Repeat("x", 10<<20) // 10 MiB + lookup := func(string) (string, bool) { return value, true } + // The root is 60 MiB of comment, so 4 MiB are left for a.txt. + root := "-r a.txt\n#" + strings.Repeat("c", 60<<20) + "\n" + open := withRoot(root, func(string) ([]byte, error) { return []byte("${A}\n"), nil }) + + _, err := Flatten("root.txt", open, WithEnv(lookup)) + require.Error(t, err) + assert.Contains(t, err.Error(), `included files are more than 67108864 bytes in total, at "a.txt"`) +} diff --git a/reqtxt/flatten_test.go b/reqtxt/flatten_test.go index 4f1c42e..12dcfac 100644 --- a/reqtxt/flatten_test.go +++ b/reqtxt/flatten_test.go @@ -39,6 +39,25 @@ func TestFlatten_NestedRequirement(t *testing.T) { assert.Empty(t, f.Includes(), "IncludeEntry should be dropped, not spliced in") } +// Flatten opens only the include that pip uses on each line. mapOpener fails +// for b.txt and c.txt, so the test fails if Flatten opens them. +func TestFlatten_OnlyTheIncludeThatPipUses(t *testing.T) { + f, err := Flatten("root.txt", mapOpener(map[string][]byte{ + "root.txt": []byte("-r a.txt -r b.txt\n-c c.txt -r d.txt\n"), + "a.txt": []byte("foo\n"), + "d.txt": []byte("bar\n"), + })) + require.NoError(t, err) + require.Len(t, f.Entries, 2) + + for i, want := range []string{"foo", "bar"} { + re, ok := f.Entries[i].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[i]) + assert.Equal(t, want, re.Requirement.Name) + assert.False(t, re.Constraint, "-r wins over -c, so %s is not a constraint", want) + } +} + func TestFlatten_RelativeSubdir(t *testing.T) { var openedPaths []string base := mapOpener(map[string][]byte{ diff --git a/reqtxt/fuzz_test.go b/reqtxt/fuzz_test.go new file mode 100644 index 0000000..98b12e2 --- /dev/null +++ b/reqtxt/fuzz_test.go @@ -0,0 +1,329 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt_test + +import ( + "errors" + "fmt" + "slices" + "strings" + "testing" + "time" + "unicode" + + "github.com/posit-dev/go-python-packaging/internal/fuzzseed" + "github.com/posit-dev/go-python-packaging/reqtxt" +) + +var reqtxtSeeds = []string{ + "requests==2.31.0\nflask>=2.0 ; python_version >= \"3.8\"\n", + "# comment\n\n-i https://pypi.org/simple\n--extra-index-url https://example.com/simple\nnumpy\n", + "-r other.txt\n-c constraints.txt\n--requirement=more.txt\n", + "-rother.txt\n-cconstraints.txt\n-e.\n-ihttps://pypi.org/simple\n-fwheels\n", + "--ind https://pypi.org/simple\n--requirem other.txt\n--no-r\nfoo --ha=sha256:abc\n", + "foo -C x=y -Cb=2\n-e ./pkg -C x=y\n", + "-e git+https://github.com/pypa/pip.git#egg=pip\n", + "./local/pkg ; python_version >= \"3.8\"\n", + "https://example.com/pkg-1.0.tar.gz#sha256=abc\n", + "foo==1.0 \\\n --hash=sha256:" + strings.Repeat("a", 64) + " \\\n --hash=sha256:" + strings.Repeat("b", 64) + "\n", + "--only-binary :all:\n--no-binary numpy\n--pre\n--prefer-binary\n--require-hashes\n--no-index\n--find-links ./wheels\n--trusted-host example.com\n", + "foo ; extra == \"-bar\"\n", + "pkg @ https://example.com/a.whl\n", + "${HOME}/pkg\n", + "foo==1.0 # trailing comment\r\nbar\r\n", + "'quoted arg' \"double\"\n", +} + +func FuzzParse(f *testing.F) { + fuzzseed.Add(f, reqtxtSeeds...) + f.Add(strings.Repeat("foo\\\n", 5000)) + f.Add(strings.Repeat("-r a.txt\n", 5000)) + f.Add(strings.Repeat("'", 5001)) + + // Inputs the fuzzer found that failed before they were fixed. + f.Add("--requirement=") + f.Add("-\v 0") + f.Add("-e\v .") + f.Add("0@# #0000000000000000000") + f.Add("-\\ 0") + f.Add("-' '''''") + f.Add("00000@\\ ") + f.Add("- 0' '/") + f.Add("0.tAr@0") + f.Add("-\u00a0=") + f.Add("0 ===/") + f.Add("0 -=") + f.Add("0>1.0||*") + f.Add("-=") + f.Add("-0\xc2\"\"\x85") + // Bytes that a backslash continuation joins into a line break. + f.Add("-0\xc2\\\n\x85x") + + f.Fuzz(func(t *testing.T, in string) { + start := time.Now() + file, err := reqtxt.Parse(in) + fuzzseed.Within(t, start, in) + checkParseResult(t, in, file, err, true) + }) +} + +// checkParseResult checks the result of Parse for the input in: an error +// must wrap ErrInvalidRequirementsFile. If roundTrip is true, a File must +// also read back to the same entries after File.String(). +func checkParseResult(t *testing.T, in string, file *reqtxt.File, err error, roundTrip bool) { + t.Helper() + if err != nil { + if !errors.Is(err, reqtxt.ErrInvalidRequirementsFile) { + t.Fatalf("Parse(%q) error does not wrap ErrInvalidRequirementsFile: %v", in, err) + } + return + } + if file == nil { + t.Fatalf("Parse(%q) returned a nil File and no error", in) + } + _ = file.Requirements() + _, _ = file.IndexURL() + if !roundTrip { + return + } + rendered := file.String() + again, err := reqtxt.Parse(rendered) + if err != nil { + t.Fatalf("Parse(%q).String() = %q, which does not parse: %v", in, rendered, err) + } + if got := again.String(); got != rendered { + t.Fatalf("round trip of %q: %q, then %q", in, rendered, got) + } + if len(again.Entries) != len(file.Entries) { + t.Fatalf("round trip of %q: %d entries, then %d", in, len(file.Entries), len(again.Entries)) + } + // An entry must not change its type. For example, a requirement must + // not read back as a local path. + for i := range file.Entries { + if a, b := fmt.Sprintf("%T", file.Entries[i]), fmt.Sprintf("%T", again.Entries[i]); a != b { + t.Fatalf("round trip of %q: entry %d is %s, then %s: %q", in, i, a, b, rendered) + } + } +} + +// FuzzParseWithEnv is FuzzParse with WithEnv. The fuzzer sets the values of +// the variables A and B. String() writes the expanded text, so the round trip +// parses it with no environment. +func FuzzParseWithEnv(f *testing.F) { + values := [][2]string{ + {"https://example.com/simple", "t"}, + {"${B}", "t"}, + {"$", "{B}"}, + {"a #b", "-c"}, + {"a\nb", "x y"}, + {"${A}${A}", ""}, + } + envSeeds := slices.Concat(reqtxtSeeds, []string{ + "--index-url ${A}\n${B}==1.0\n", + "--index-url=\"${A}\" --pre\n", + "foo ; os_name == \"${A}\"\n", + "${A} ${B} ${A}\n", + "-r ${A}/${B}.txt\n", + }) + for i, s := range fuzzseed.Strings(envSeeds...) { + v := values[i%len(values)] + f.Add(s, v[0], v[1]) + } + + // Inputs the fuzzer found that failed before they were fixed. + f.Add("${A}", ". ", "0") + f.Add("-=", "", "") + f.Add("-0\xc2\"\"\x85", "", "") + // Bytes that a value or a backslash continuation joins into a line break. + f.Add("-0${A}\x85x", "\xc2", "") + f.Add("-r a\xc2${A}${B}.txt", "${B}", "\x85") + f.Add("-0\xc2\\\n\x85x", "", "") + // Targets that String() cannot write. + f.Add("${A}/", "#", "0") + f.Add("${A}-/", "\x1f", "0") + + f.Fuzz(func(t *testing.T, in, a, b string) { + lookup := func(name string) (string, bool) { + switch name { + case "A": + return a, true + case "B": + return b, true + } + return "", false + } + start := time.Now() + file, err := reqtxt.Parse(in, reqtxt.WithEnv(lookup)) + fuzzseed.Within(t, start, in) + // Some values cannot be written in a requirements file, so String() + // cannot write them so that they read back, and the round trip is not + // checked: + // - A value with a line break: a line break ends the line before + // shlex reads the quotes. + // - A target (not editable) that starts with "-", or that has a + // comment start. pip reads a target with no shlex, so nothing can + // escape it. "${A}/" with A="#" gives "#/", which reads back as a + // comment, and "${A}-/" with A="\x1f" gives "-/", which reads back + // as an option. + roundTrip := !hasLineBreak(a) && !hasLineBreak(b) && (err != nil || !hasUnwritableTarget(file)) + checkParseResult(t, in, file, err, roundTrip) + }) +} + +// hasUnwritableTarget reports whether file has a target, other than an +// editable one, whose text starts with "-" or has a comment start: a "#" at +// its start, or after whitespace. As in pip, this whitespace includes U+001C +// to U+001F. +func hasUnwritableTarget(file *reqtxt.File) bool { + for _, e := range file.Entries { + u, ok := e.(*reqtxt.UnnamedEntry) + if !ok || u.Editable { + continue + } + if strings.HasPrefix(u.Raw, "-") { + return true + } + prev := ' ' // the start of the text counts as whitespace + for _, r := range u.Raw { + if r == '#' && (unicode.IsSpace(prev) || (prev >= '\x1c' && prev <= '\x1f')) { + return true + } + prev = r + } + } + return false +} + +// hasLineBreak reports whether s has a character that Python's +// str.splitlines() reads as a line break. +func hasLineBreak(s string) bool { + return strings.ContainsAny(s, "\n\r\v\f\x1c\x1d\x1e\u0085\u2028\u2029") +} + +// FuzzFlatten serves the fuzzed text root as the root file, and the fuzzed +// text child as every included file. A child with no includes lets each include +// of the root expand. When the root served itself to its includes, every +// include made a cycle or a chain of new paths, so no successful Flatten ever +// expanded one. A budget on opens keeps an include chain from running forever. +func FuzzFlatten(f *testing.F) { + children := []string{ + "foo==1.0\nbar[x]>=2 ; python_version >= \"3.8\"\n", + "", + "--pre\n./pkg\n-e git+https://example.com/repo.git#egg=repo\n", + "# only a comment\n", + "-r other.txt\n", + } + for i, s := range fuzzseed.Strings(reqtxtSeeds...) { + f.Add(s, children[i%len(children)]) + } + f.Add("-r a.txt\n-c b.txt\nfoo\n--requirement=c.txt\n", "bar\n-e ./x\n") + f.Add("-r a.txt\n-r a.txt\n", "foo\n") + + f.Fuzz(func(t *testing.T, root, child string) { + const maxOpens = 32 + opens := 0 + errBudget := errors.New("open budget spent") + open := func(p string) ([]byte, error) { + opens++ + if opens > maxOpens { + return nil, errBudget + } + if p == "dir/requirements.txt" { + return []byte(root), nil + } + return []byte(child), nil + } + start := time.Now() + file, err := reqtxt.Flatten("dir/requirements.txt", open) + fuzzseed.Within(t, start, root+child) + if err != nil { + if !errors.Is(err, reqtxt.ErrInvalidRequirementsFile) { + t.Fatalf("Flatten(%q, %q) error does not wrap ErrInvalidRequirementsFile: %v", root, child, err) + } + return + } + if file == nil { + t.Fatalf("Flatten(%q, %q) returned a nil File and no error", root, child) + } + if n := len(file.Includes()); n != 0 { + t.Fatalf("Flatten(%q, %q) left %d include entries", root, child, n) + } + checkFlattenResult(t, root, child, file) + }) +} + +// checkFlattenResult checks a successful Flatten of root, whose includes all +// serve child, against Parse of the two texts. Each include of root gives all +// the entries of child, and a "-c" include makes each of its requirements and +// targets a constraint. Flatten succeeded, so a root with includes has a child +// that parses and has no includes: an include in child would open child +// again, with no end. Flatten removes a byte-order mark at the start of each +// file before it parses the file, so the check does too. +func checkFlattenResult(t *testing.T, root, child string, file *reqtxt.File) { + t.Helper() + const bom = "\ufeff" + rootFile, err := reqtxt.Parse(strings.TrimPrefix(root, bom)) + if err != nil { + t.Fatalf("Flatten(%q, %q) succeeded, but Parse of the root fails: %v", root, child, err) + } + includes := rootFile.Includes() + others := len(rootFile.Entries) - len(includes) + if len(includes) == 0 { + if len(file.Entries) != others { + t.Fatalf("Flatten(%q, %q) has %d entries, want the %d of the root", root, child, len(file.Entries), others) + } + return + } + childFile, err := reqtxt.Parse(strings.TrimPrefix(child, bom)) + if err != nil { + t.Fatalf("Flatten(%q, %q) succeeded, but Parse of the child fails: %v", root, child, err) + } + if n := len(childFile.Includes()); n != 0 { + t.Fatalf("Flatten(%q, %q) succeeded, but the child has %d includes", root, child, n) + } + if want := others + len(includes)*len(childFile.Entries); len(file.Entries) != want { + t.Fatalf("Flatten(%q, %q) has %d entries, want %d", root, child, len(file.Entries), want) + } + + constraintIncludes := 0 + for _, inc := range includes { + if inc.Constraint { + constraintIncludes++ + } + } + if want, got := constraintIncludes*countConstraintable(childFile), countConstraints(file); got != want { + t.Fatalf("Flatten(%q, %q) has %d constraints, want %d", root, child, got, want) + } +} + +// countConstraintable returns the number of entries of file that an include +// with "-c" makes a constraint: the requirements and the targets. +func countConstraintable(file *reqtxt.File) int { + n := 0 + for _, e := range file.Entries { + switch e.(type) { + case *reqtxt.RequirementEntry, *reqtxt.UnnamedEntry: + n++ + } + } + return n +} + +// countConstraints returns the number of requirements and targets of file that +// are constraints. +func countConstraints(file *reqtxt.File) int { + n := 0 + for _, e := range file.Entries { + switch v := e.(type) { + case *reqtxt.RequirementEntry: + if v.Constraint { + n++ + } + case *reqtxt.UnnamedEntry: + if v.Constraint { + n++ + } + } + } + return n +} diff --git a/reqtxt/line_breaks_test.go b/reqtxt/line_breaks_test.go new file mode 100644 index 0000000..3cbce00 --- /dev/null +++ b/reqtxt/line_breaks_test.go @@ -0,0 +1,629 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// pip splits a file with Python's str.splitlines(), so each of these ends a +// line. Checked with pip 21.2.4. +func TestParse_LineBreaks(t *testing.T) { + tests := []struct { + name string + input string + }{ + {name: "LF", input: "foo\nbar"}, + {name: "CRLF", input: "foo\r\nbar"}, + {name: "CR", input: "foo\rbar"}, + {name: "vertical tab", input: "foo\vbar"}, + {name: "form feed", input: "foo\fbar"}, + {name: "file separator", input: "foo\x1cbar"}, + {name: "group separator", input: "foo\x1dbar"}, + {name: "record separator", input: "foo\x1ebar"}, + {name: "next line U+0085", input: "foo\u0085bar"}, + {name: "line separator U+2028", input: "foo\u2028bar"}, + {name: "paragraph separator U+2029", input: "foo\u2029bar"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + require.NoError(t, err) + require.Len(t, f.Entries, 2) + for i, want := range []struct { + name string + line int + }{{"foo", 1}, {"bar", 2}} { + e, ok := f.Entries[i].(*RequirementEntry) + require.True(t, ok, "entry %d is a *RequirementEntry", i) + assert.Equal(t, want.name, e.Requirement.Name) + assert.Equal(t, want.line, e.Source.Line) + } + assert.Equal(t, "foo\nbar", f.String()) + }) + } +} + +// A line break inside an option line splits it, as in pip. +func TestParse_LineBreakInOptionLine(t *testing.T) { + tests := []struct { + name string + input string + // wantErr is a substring of the error. Empty means no error. + wantErr string + // wantString is File.String() on success. + wantString string + }{ + { + // Found by fuzzing. pip reads "-e" with no value. + name: "editable then vertical tab", + input: "-e\v .", + wantErr: "line 1: -e/--editable requires a value", + }, + { + name: "requirement option then form feed", + input: "-r\fother.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + // Found by fuzzing. pip ignores the lone "-", which is not an + // option, and then reads the requirement "0". + name: "dash then vertical tab", + input: "-\v 0", + wantString: "0", + }, + { + name: "hash option on the next line", + input: "foo\v--hash=sha256:abc", + wantString: "foo\n--hash=sha256:abc", + }, + + // Each line break that str.splitlines() knows splits the option from + // its value. + { + name: "LF", + input: "-r\nother.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "CR", + input: "-r\rother.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "CRLF", + input: "-r\r\nother.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "file separator", + input: "-r\x1cother.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "group separator", + input: "-r\x1dother.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "record separator", + input: "-r\x1eother.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "next line U+0085", + input: "-r\u0085other.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "line separator U+2028", + input: "-r\u2028other.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "paragraph separator U+2029", + input: "-r\u2029other.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "line break on line 2", + input: "foo\n-r\u0085other.txt", + wantErr: "line 2: -r/--requirement requires a value", + }, + + // Other options that take a value. + { + name: "constraint option", + input: "-c\vconstraints.txt", + wantErr: "line 1: -c/--constraint requires a value", + }, + { + name: "long requirement option", + input: "--requirement\vother.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "long editable option", + input: "--editable\u2028./pkg", + wantErr: "line 1: -e/--editable requires a value", + }, + { + name: "index URL option", + input: "--index-url\vhttps://example.com/simple", + wantErr: "line 1: --index-url requires a value", + }, + { + name: "short index URL option", + input: "-i\u2029https://example.com/simple", + wantErr: "line 1: --index-url requires a value", + }, + { + name: "find links option", + input: "-f\fwheels", + wantErr: "line 1: --find-links requires a value", + }, + { + name: "hash option of a requirement", + input: "foo --hash\vsha256:abc", + wantErr: "line 1: --hash requires a value", + }, + { + name: "config settings option of a requirement", + input: "foo --config-settings\vx", + wantErr: "line 1: --config-settings requires a value", + }, + + // An "=" then a line break gives an empty value. + { + name: "requirement option, equals, line break", + input: "-r=\vother.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + // The URL on the next line is a requirement of its own. + name: "index URL option, equals, line break", + input: "--index-url=\vhttps://example.com/simple", + wantString: "--index-url=\"\"\nhttps://example.com/simple", + }, + + // The text after the line break is a new line. + { + // On one line, pip ignores "foo" after "--pre". On the next + // line, "foo" is a requirement. + name: "boolean option, then a requirement", + input: "--pre\vfoo", + wantString: "--pre\nfoo", + }, + { + name: "two boolean options", + input: "--no-index\v--pre", + wantString: "--no-index\n--pre", + }, + { + name: "include, then an option", + input: "-r other.txt\v--pre", + wantString: "-r other.txt\n--pre"}, + { + // An unknown option does not take the value from the next line. + name: "unknown option, then a value", + input: "--unknown\vvalue", + wantString: "--unknown\nvalue", + }, + { + // The hash is not an option of the editable requirement. + name: "editable requirement, then a hash option", + input: "-e ./pkg\v--hash=sha256:abc", + wantString: "-e ./pkg\n--hash=sha256:abc", + }, + { + name: "requirement, then a config settings option", + input: "foo\v--config-settings=x", + wantString: "foo\n--config-settings=x", + }, + { + name: "option, then a comment", + input: "--pre\v# comment", + wantString: "--pre", + }, + + // These do not split the line. + { + // A backslash at the end of a line joins it to the next line. + name: "backslash, then a line break", + input: "-r \\\vother.txt", + wantString: "-r other.txt", + }, + { + name: "tab is not a line break", + input: "-r\tother.txt", + wantString: "-r other.txt", + }, + { + // The line break is inside the quotes, but the quote is not closed + // on line 1. + name: "line break inside a quoted value", + input: "-r 'a\vb.txt'", + wantErr: "line 1: invalid requirements file: unterminated single-quoted string", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + if tt.wantErr != "" { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + text := f.String() + assert.Equal(t, tt.wantString, text) + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + assert.Equal(t, text, again.String(), "String() is stable") + }) + } +} + +// shlex reads the file byte by byte, so removing quotes or a backslash can join +// two bytes that are not valid UTF-8 into a line break, as "\xc2\"\"\x85" gives +// U+0085. pip decodes the file before it splits the lines, so its shlex never +// joins bytes, and no file can write a word that holds a line break. So Parse +// returns an error. Found by fuzzing: before, "-0\xc2\"\"\x85" parsed, and +// String() wrote -"0\u0085", which does not parse. +func TestParse_LineBreakJoinedByShlex(t *testing.T) { + // Each line break, split into its first byte and the rest. + breaks := []struct { + name string + first, rest string + }{ + {name: "U+0085", first: "\xc2", rest: "\x85"}, + {name: "U+2028", first: "\xe2", rest: "\x80\xa8"}, + {name: "U+2029", first: "\xe2\x80", rest: "\xa9"}, + } + // How the bytes are joined. + joins := []struct { + name string + join func(first, rest string) string + }{ + {name: "empty double quotes", join: func(a, b string) string { return a + `""` + b }}, + {name: "empty single quotes", join: func(a, b string) string { return a + "''" + b }}, + {name: "quoted rest", join: func(a, b string) string { return a + `"` + b + `"` }}, + {name: "backslash", join: func(a, b string) string { return a + `\` + b }}, + } + // Where the word is. + places := []struct { + name string + format string + }{ + {name: "option name", format: "-0%s"}, + {name: "option value", format: "--index-url=a%sb"}, + {name: "option value after a space", format: "--extra-index-url a%sb"}, + {name: "include path", format: "-r a%s.txt"}, + {name: "constraint path", format: "-c a%s.txt"}, + {name: "editable path", format: "-e ./a%s"}, + {name: "requirement option", format: "foo --config-settings=a%sb"}, + } + + for _, br := range breaks { + for _, j := range joins { + for _, pl := range places { + input := fmt.Sprintf(pl.format, j.join(br.first, br.rest)) + t.Run(br.name+"/"+j.name+"/"+pl.name, func(t *testing.T) { + _, err := Parse(input) + require.Error(t, err, "Parse(%q)", input) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), "line 1: invalid requirements file: quotes or a backslash join bytes into the line break") + }) + } + } + } +} + +// A backslash continuation or a ${NAME} value can also join bytes into a line +// break. pip does neither: it decodes the file before it joins lines, and it +// gets each value as decoded text. So Parse returns an error, as it does for a +// join by shlex. Before, "-0${A}\x85x" with A="\xc2" and "-0\xc2\\\n\x85x" +// parsed, and String() wrote -"0\u0085x", which does not parse. +func TestParse_LineBreakJoinedByPreprocess(t *testing.T) { + const ( + continuationErr = "a backslash continuation joins bytes into a line break" + envErr = "an environment variable value joins bytes with the text next to it into a line break" + ) + tests := []struct { + name string + input string + env map[string]string + wantErr string + }{ + // A backslash continuation. + {name: "continuation, option name", input: "-0\xc2\\\n\x85x", wantErr: "line 1: " + continuationErr}, + {name: "continuation, option value", input: "--index-url=a\xe2\\\n\x80\xa8b", wantErr: "line 1: " + continuationErr}, + {name: "continuation, include path", input: "-r a\xe2\x80\\\n\xa9.txt", wantErr: "line 1: " + continuationErr}, + {name: "continuation, target", input: "./a\xc2\\\n\x85b", wantErr: "line 1: " + continuationErr}, + {name: "continuation, three lines", input: "-r a\xe2\\\n\x80\\\n\xa8.txt", wantErr: "line 1: " + continuationErr}, + { + // The join is checked before comments are removed, because the + // line break that it makes can start a comment. + name: "continuation, comment", + input: "foo \xc2\\\n\x85#c", + wantErr: "line 1: " + continuationErr, + }, + {name: "continuation on line 2", input: "foo\n-r a\xc2\\\n\x85b", wantErr: "line 2: " + continuationErr}, + + // A ${NAME} value and the text next to it. + {name: "value, then text", input: "-0${A}\x85x", env: map[string]string{"A": "\xc2"}, wantErr: "line 1: " + envErr}, + {name: "text, then value", input: "-r a\xe2${A}.txt", env: map[string]string{"A": "\x80\xa8"}, wantErr: "line 1: " + envErr}, + {name: "value, then value", input: "--index-url=a${A}${B}b", env: map[string]string{"A": "\xe2\x80", "B": "\xa9"}, wantErr: "line 1: " + envErr}, + {name: "value between text", input: "-r a\xe2${A}\xa8.txt", env: map[string]string{"A": "\x80"}, wantErr: "line 1: " + envErr}, + {name: "value in a target", input: "./a${A}\x85b", env: map[string]string{"A": "\xc2"}, wantErr: "line 1: " + envErr}, + { + // A marker literal could hold the line break, but the rule is the + // same everywhere. + name: "value in a marker", + input: "foo; os_name == \"${A}\x85\"", + env: map[string]string{"A": "\xc2"}, + wantErr: "line 1: " + envErr, + }, + { + // A's value is a reference to B, so expandEnv uses pip's order. + // pip replaces the copy of ${B} that A adds, because ${B} is + // also in the line. + name: "value in pip's order", + input: "-r a\xc2${A}${B}.txt", + env: map[string]string{"A": "${B}", "B": "\x85"}, + wantErr: "line 1: " + envErr, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := Parse(tt.input, WithEnv(func(name string) (string, bool) { + v, ok := tt.env[name] + return v, ok + })) + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + }) + } +} + +// These words have bytes that shlex joins, or a line break, but Parse reads +// them. +func TestParse_LineBreakNotJoinedByShlex(t *testing.T) { + tests := []struct { + name string + input string + env map[string]string + // wantValue is the value of the option of the first entry. + wantValue string + }{ + { + // A join that makes a character that is not a line break. String() + // can write "é", so the value reads back the same. + name: "join makes another character", + input: "--index-url=a\xc3\"\"\xa9", + wantValue: "a\u00e9", + }, + { + // The quotes are before the first byte of the line break, so they + // join nothing into it. The line break then ends the line. + name: "quotes before the line break", + input: "--index-url=a\"\"\u0085b", + wantValue: "a", + }, + { + // As in pip, a value of an environment variable can put a line + // break in a word. String() cannot write it (see File.String). + name: "line break from an environment variable", + input: "--index-url=${A}", + env: map[string]string{"A": "a\u2028b"}, + wantValue: "a\u2028b", + }, + { + name: "quoted line break from an environment variable", + input: "--index-url=\"${A}\"", + env: map[string]string{"A": "a\u0085b"}, + wantValue: "a\u0085b", + }, + { + // A's value is a reference to B, so expandEnv uses pip's order. + name: "line break from an environment variable in pip's order", + input: "--index-url=x${A}${B}", + env: map[string]string{"A": "${B}", "B": "a\u2029b"}, + wantValue: "xa\u2029ba\u2029b", + }, + { + // Bytes that are not valid UTF-8 next to a line break of a value do + // not make another line break. + name: "invalid bytes next to a line break from an environment variable", + input: "--index-url=\xc2${A}\x85", + env: map[string]string{"A": "\u2028"}, + wantValue: "\xc2\u2028\x85", + }, + { + // A continuation joins bytes, but they do not make a line break. + name: "continuation joins bytes into another character", + input: "--index-url=a\xc3\\\n\xa9", + wantValue: "a\u00e9", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input, WithEnv(func(name string) (string, bool) { + v, ok := tt.env[name] + return v, ok + })) + require.NoError(t, err) + require.NotEmpty(t, f.Entries) + o, ok := f.Entries[0].(*OptionEntry) + require.True(t, ok, "entry 0 is an *OptionEntry") + assert.Equal(t, tt.wantValue, o.Value) + }) + } +} + +// An include with an empty path is an error. pip fails too, when it tries to +// open the empty path. +func TestParse_EmptyIncludePath(t *testing.T) { + tests := []struct { + name string + input string + wantErr string + }{ + { + // Found by fuzzing. + name: "long requirement option with equals", + input: "--requirement=", + wantErr: "-r/--requirement requires a value", + }, + { + name: "short requirement option with equals", + input: "-r=", + wantErr: "-r/--requirement requires a value", + }, + { + name: "requirement option with empty quotes", + input: "-r ''", + wantErr: "-r/--requirement requires a value", + }, + { + name: "long constraint option with equals", + input: "--constraint=", + wantErr: "-c/--constraint requires a value", + }, + { + name: "constraint option with empty quotes", + input: `-c ""`, + wantErr: "-c/--constraint requires a value", + }, + { + name: "empty include on line 2", + input: "foo\n--requirement=", + wantErr: "line 2: -r/--requirement requires a value", + }, + + // Each spelling of the two options. + { + name: "short constraint option with equals", + input: "-c=", + wantErr: "line 1: -c/--constraint requires a value", + }, + { + name: "long requirement option with empty quotes", + input: "--requirement ''", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "long constraint option with empty quotes", + input: "--constraint ''", + wantErr: "line 1: -c/--constraint requires a value", + }, + { + name: "requirement option with empty double quotes", + input: `-r ""`, + wantErr: "line 1: -r/--requirement requires a value", + }, + + // Empty quotes after "=", or directly after the option. shlex removes + // the quotes, so the token is "-r=" or "-r". + { + name: "equals, then empty quotes", + input: "-r=''", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "long option, equals, then empty double quotes", + input: `--constraint=""`, + wantErr: "line 1: -c/--constraint requires a value", + }, + { + name: "empty quotes directly after the short option", + input: "-r''", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "empty double quotes directly after the short option", + input: `-c""`, + wantErr: "line 1: -c/--constraint requires a value", + }, + + // No value at all. + { + name: "short option at the end of the line", + input: "-r", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "long option at the end of the line", + input: "--constraint", + wantErr: "line 1: -c/--constraint requires a value", + }, + + // Other options on the same line do not change the result. + { + name: "option after the empty include", + input: "-r '' --pre", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "option before the empty include", + input: "--pre -r ''", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + // pip uses only the first -r of a line, so "-r a.txt -r ''" is not + // an error (see TestParse_OptionLineKind). + name: "empty include before an include", + input: "-r '' -r a.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "long option with equals, then an option", + input: "--requirement= --pre", + wantErr: "line 1: -r/--requirement requires a value", + }, + + // The file text around the option. + { + name: "equals, then a comment", + input: "-r= # comment", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "equals, then a tab", + input: "-r=\t", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + // The backslash joins line 2 to line 1. The error is on line 1. + name: "empty quotes on a continuation line", + input: "-r \\\n''", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + // A blank line and a comment line also count. + name: "empty include after a blank line and a comment", + input: "foo\n\n# c\n-c ''", + wantErr: "line 4: -c/--constraint requires a value", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := Parse(tt.input) + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + }) + } +} diff --git a/reqtxt/long_input_test.go b/reqtxt/long_input_test.go new file mode 100644 index 0000000..662b948 --- /dev/null +++ b/reqtxt/long_input_test.go @@ -0,0 +1,316 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "errors" + "strconv" + "strings" + "testing" + "time" + + "github.com/posit-dev/go-python-packaging/internal/errtext" + "github.com/posit-dev/go-python-packaging/internal/race" + "github.com/posit-dev/go-python-packaging/requirement" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + // markerDepthLimit is pep508.MaxMarkerDepth, which this package cannot import. + markerDepthLimit = 100 + deepItem = `python_version >= "3.8"` + // maxErrorLen is the most bytes an error for a long input may have. + maxErrorLen = 1000 + hugeLen = 2_000_000 +) + +// deepMarker returns deepItem inside depth pairs of parentheses. +func deepMarker(depth int) string { + return strings.Repeat("(", depth) + deepItem + strings.Repeat(")", depth) +} + +func TestParse_DeepMarker(t *testing.T) { + tests := []struct { + name string + // input builds the input when its case runs. + input func() string + // wantEntries is the number of entries on success. + wantEntries int + // wantLine is the line of the error. Zero means no error. + wantLine int + }{ + { + name: "marker at limit", + input: func() string { return "foo; " + deepMarker(markerDepthLimit) }, + wantEntries: 1, + }, + { + name: "marker at limit on line 3", + input: func() string { return "bar\nbaz\nfoo; " + deepMarker(markerDepthLimit) + "\n" }, + wantEntries: 3, + }, + { + name: "marker over limit", + input: func() string { return "foo; " + deepMarker(markerDepthLimit+1) }, + wantLine: 1, + }, + { + name: "marker over limit on line 3", + input: func() string { return "bar\nbaz\nfoo>=1.0; " + deepMarker(markerDepthLimit+1) + "\nqux\n" }, + wantLine: 3, + }, + { + name: "marker over limit with a per-requirement option", + input: func() string { return "foo; " + deepMarker(markerDepthLimit+1) + " --hash=sha256:abc" }, + wantLine: 1, + }, + { + // Before the limit, about 1.3M "(" overflowed the Go stack. + name: "2M open parentheses", + input: func() string { return "foo; " + strings.Repeat("(", hugeLen) }, + wantLine: 1, + }, + { + name: "2M closed parentheses on line 2", + input: func() string { return "bar\nfoo; " + deepMarker(hugeLen) }, + wantLine: 2, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input()) + if tt.wantLine == 0 { + require.NoError(t, err) + require.Len(t, f.Entries, tt.wantEntries) + last, ok := f.Entries[len(f.Entries)-1].(*RequirementEntry) + require.True(t, ok, "last entry is a *RequirementEntry") + assert.Equal(t, deepItem, last.Requirement.Marker.String()) + return + } + + require.Error(t, err) + text := err.Error() + require.Less(t, len(text), maxErrorLen, "error text is short") + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.True(t, errors.Is(err, requirement.ErrInvalidRequirement), "want requirement.ErrInvalidRequirement") + assert.Contains(t, text, "line "+strconv.Itoa(tt.wantLine)+": ") + assert.Contains(t, text, "Marker has more than 100 nested parentheses") + }) + } +} + +// The errors that reqtxt makes itself quote only the start of a long value. +func TestParse_LongValueInErrorText(t *testing.T) { + big := strings.Repeat("a", hugeLen) + + tests := []struct { + name string + input string + // wantText is a substring of the error text. + wantText string + }{ + { + name: "long editable target", + input: "-e " + big, + wantText: `editable requirement "` + big[:errtext.MaxLen] + `"... (2000000 bytes) is not a recognized`, + }, + { + name: "long direct reference with a marker", + input: "./" + big + " ; extra", + wantText: `direct-reference requirement "./` + big[:errtext.MaxLen-2] + `"... (2000010 bytes) does not support markers`, + }, + { + name: "long unexpected token", + input: "foo --hash=sha256:abc " + big, + wantText: `unexpected token "` + big[:errtext.MaxLen] + `"... (2000000 bytes) (expected a per-requirement option)`, + }, + { + name: "long malformed hash", + input: "foo --hash=" + big, + wantText: `malformed --hash value "` + big[:errtext.MaxLen] + `"... (2000000 bytes): expected`, + }, + { + // Not a reqtxt error: the requirement parser's syntax error is short too. + name: "long bad escape in a marker", + input: `foo; python_version == "` + big + `\q"`, + wantText: "invalid marker expression", + }, + { + // Not a reqtxt error: the version specifier error is short too. + name: "long bad version specifier", + input: "foo==1." + big + "!", + wantText: `invalid version specifier "==1.` + big[:errtext.MaxLen-4] + `"... (2000005 bytes): improper constraint`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := Parse(tt.input + "\n") + require.Error(t, err) + text := err.Error() + require.Less(t, len(text), maxErrorLen, "error text is short") + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, text, "line 1: ") + assert.Contains(t, text, tt.wantText) + }) + } +} + +func TestFlatten_LongPathInErrorText(t *testing.T) { + longPath := "/" + strings.Repeat("a", hugeLen) + quoted := `"` + longPath[:errtext.MaxLen] + `"... (2000001 bytes)` + + tests := []struct { + name string + open func(string) ([]byte, error) + wantText string + }{ + { + name: "file includes itself", + open: func(p string) ([]byte, error) { return []byte("-r " + p + "\n"), nil }, + wantText: quoted + " recursively includes itself", + }, + { + name: "file cannot be opened", + open: func(string) ([]byte, error) { return nil, errors.New("no such file") }, + wantText: "opening " + quoted + ": no such file", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := Flatten(longPath, tt.open) + require.Error(t, err) + text := err.Error() + require.Less(t, len(text), maxErrorLen, "error text is short") + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, text, tt.wantText) + }) + } +} + +func TestParse_ManyOptionsOnOneLine(t *testing.T) { + // manyOptions is the number of options on the line. When dispatchLine + // recursed once for each option, 40,000 options took 2.5 seconds, and the + // time grew with the square of the count, so this many took about 15 + // seconds. It is one less than maxLineOptions, so a case can add one more + // option and stay at the limit. + const manyOptions = maxLineOptions - 1 + + tests := []struct { + name string + // input builds the input when its case runs. + input func() string + // wantCount is the number of entries on success. + wantCount int + // wantName is the name of every entry on success: an OptionEntry + // name, or "-r" for an IncludeEntry. + wantName string + // wantErr is a substring of the error. Empty means no error. + wantErr string + }{ + { + name: "many flags", + input: func() string { return strings.Repeat("--pre ", manyOptions) }, + wantCount: manyOptions, + wantName: optPre, + }, + { + name: "many options with values", + input: func() string { return strings.Repeat("--extra-index-url https://a ", manyOptions) }, + wantCount: manyOptions, + wantName: optExtraIndexURL, + }, + { + name: "many flags, each followed by an ignored token", + input: func() string { return strings.Repeat("--pre foo ", manyOptions) }, + wantCount: manyOptions, + wantName: optPre, + }, + { + // pip uses only the first include of the line. + name: "many includes", + input: func() string { return strings.Repeat("-r a.txt ", manyOptions) }, + wantCount: 1, + wantName: "-r", + }, + { + name: "many flags, then an include", + input: func() string { return strings.Repeat("--pre ", manyOptions) + "-r a.txt" }, + wantCount: 1, + wantName: "-r", + }, + { + name: "flags one over the line limit", + input: func() string { return strings.Repeat("--pre ", maxLineOptions+1) }, + wantErr: "line 1: the line has more than 100000 options", + }, + { + name: "requirement options one over the line limit", + input: func() string { return "foo" + strings.Repeat(" --x", maxLineOptions+1) }, + wantErr: "line 1: the line has more than 100000 options", + }, + { + name: "editable options one over the line limit", + input: func() string { return "-e ./pkg" + strings.Repeat(" --hash=sha256:a", maxLineOptions+1) }, + wantErr: "line 1: the line has more than 100000 options", + }, + { + name: "many flags, then an invalid option", + input: func() string { return strings.Repeat("--pre ", manyOptions) + "--no-index=x" }, + wantErr: "line 1: --no-index does not take a value", + }, + { + name: "many includes, then an option with no value", + input: func() string { return strings.Repeat("-r a.txt ", manyOptions) + "--index-url" }, + wantErr: "line 1: --index-url requires a value", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + input := tt.input() + start := time.Now() + f, err := Parse(input) + // The race detector makes the code much slower (see package race). + if !race.Enabled { + assert.Less(t, time.Since(start), 5*time.Second, "Parse takes linear time") + } + if tt.wantErr != "" { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + require.Len(t, f.Entries, tt.wantCount) + for i, e := range f.Entries { + var name string + switch v := e.(type) { + case *OptionEntry: + name = v.Name + case *IncludeEntry: + name = "-r" + } + if name != tt.wantName { + t.Fatalf("entry %d is %T %q, want %q", i, e, name, tt.wantName) + } + } + }) + } +} + +// TestParse_OptionLineOrder checks that the loop in dispatchLine keeps the +// options of a line in order. +func TestParse_OptionLineOrder(t *testing.T) { + f, err := Parse("--pre --index-url=https://a foo --no-index --trusted-host h") + require.NoError(t, err) + assert.Equal(t, []OptionEntry{ + {Name: optPre, Source: Source{Line: 1}}, + {Name: optIndexURL, Value: "https://a", Source: Source{Line: 1}}, + {Name: optNoIndex, Source: Source{Line: 1}}, + {Name: optTrustedHost, Value: "h", Source: Source{Line: 1}}, + }, f.Options()) +} diff --git a/reqtxt/named_url_test.go b/reqtxt/named_url_test.go new file mode 100644 index 0000000..a761724 --- /dev/null +++ b/reqtxt/named_url_test.go @@ -0,0 +1,369 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "errors" + "testing" + + "github.com/posit-dev/go-python-packaging/requirement" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Parse decides whether a package line is a target (an archive, a local path, +// a URL or a VCS reference) or a PEP 508 requirement, as pip does (pip 21.2.4): +// - An archive-like line with "@" after a name that is not a path is a +// "name @ url" requirement (_get_url_from_path). +// - pip removes the marker at the first ";" before it reads a line that is +// not a URL as a path (parse_req_from_line), also when no whitespace comes +// before the ";". So an "@", a "/" or an archive extension in the marker +// does not count. A URL keeps its ";", because pip removes the marker of a +// URL only at "; ". +// - A target cannot have a marker or other text after it here, so that is an +// error. +func TestParse_TargetOrRequirement(t *testing.T) { + const errTrailing = "does not support markers or trailing content" + + tests := []struct { + name string + input string + // want is the entryValues of the parsed file, before and after the + // round trip through String(). + want []string + // wantErr is a part of the error text. A row with wantErr expects an + // error, which must always wrap ErrInvalidRequirementsFile. + wantErr string + // wantErrIs is a second error that the error must wrap, if any. + wantErrIs error + }{ + // "name @ url" requirements. + { + // Found by fuzzing. String() wrote "0.tAr @ 0", which did not + // parse back. + name: "archive-like name, no spaces", + input: "0.tAr@0", + want: []string{"requirement 0.tAr @ 0 hashes "}, + }, + { + name: "archive-like name with spaces", + input: "0.tAr @ 0", + want: []string{"requirement 0.tAr @ 0 hashes "}, + }, + { + name: "zip name with an https URL", + input: "foo.zip @ https://example.com/foo.zip", + want: []string{"requirement foo.zip @ https://example.com/foo.zip hashes "}, + }, + { + name: "wheel name with an https URL and a marker", + input: `foo.whl@https://example.com/x ; os_name == "posix"`, + want: []string{`requirement foo.whl @ https://example.com/x ; os_name == "posix" hashes `}, + }, + { + // The marker is removed only to decide the line type. The "@" in + // the marker stays in the requirement. + name: "wheel name with an https URL and an @ in the marker", + input: `foo.whl@https://example.com/x ; os_name == "a@b"`, + want: []string{`requirement foo.whl @ https://example.com/x ; os_name == "a@b" hashes `}, + }, + { + name: "archive-like name with a URL and a marker after a semicolon", + input: `foo.whl@https://example.com/x ;os_name=="a@b"`, + want: []string{`requirement foo.whl @ https://example.com/x ; os_name == "a@b" hashes `}, + }, + { + name: "archive-like name with a URL that starts with a hash", + input: "foo.tar@#frag", + want: []string{"requirement foo.tar @#frag hashes "}, + }, + + // Requirements with a "/" or an archive extension only in the marker. + { + // Before, this was a local path with the Raw text + // `foo;os_name=="a/b"`. + name: "slash in the marker", + input: `foo;os_name=="a/b"`, + want: []string{`requirement foo; os_name == "a/b" hashes `}, + }, + { + name: "archive extension in the marker", + input: `foo;platform_release=="a.whl"`, + want: []string{`requirement foo; platform_release == "a.whl" hashes `}, + }, + + // Targets. + { + name: "relative path with @ stays a path", + input: "./foo.zip@x", + want: []string{"unnamed ./foo.zip@x"}, + }, + { + name: "archive with no @ stays a path", + input: "foo-1.0-py3-none-any.whl", + want: []string{"unnamed foo-1.0-py3-none-any.whl"}, + }, + { + name: "archive with no marker", + input: "foo.tar.gz", + want: []string{"unnamed foo.tar.gz"}, + }, + { + name: "URL with @ stays a URL", + input: "https://user@example.com/foo.zip", + want: []string{"unnamed https://user@example.com/foo.zip"}, + }, + { + name: "URL with a semicolon", + input: `https://example.com/a.whl;os_name=="x"`, + want: []string{`unnamed https://example.com/a.whl;os_name=="x"`}, + }, + + // pip checks the archive extension of the whole text before the + // marker, after it removes non-empty extras at the end. Each row was + // checked against pip 21.2.4. + { + name: "archive with extras", + input: "foo.whl[x]", + want: []string{"unnamed foo.whl[x]"}, + }, + { + name: "archive with two extras", + input: "foo.zip[x,y]", + want: []string{"unnamed foo.zip[x,y]"}, + }, + { + name: "local version with an archive extension", + input: "foo==1.0+a.zip", + want: []string{"unnamed foo==1.0+a.zip"}, + }, + { + name: "xz archive", + input: "foo-1.0.tar.xz", + want: []string{"unnamed foo-1.0.tar.xz"}, + }, + { + name: "lzma archive with extras", + input: "foo-1.0.tar.lzma[x]", + want: []string{"unnamed foo-1.0.tar.lzma[x]"}, + }, + { + // pip's extension of "foo.tar.zip" is ".tar.zip", which is not + // an archive extension. + name: "name with .tar before an archive extension", + input: "foo.tar.zip", + want: []string{"requirement foo.tar.zip hashes "}, + }, + { + name: "archive-like name with empty extras", + input: "foo.whl[]", + want: []string{"requirement foo.whl hashes "}, + }, + { + name: "archive-like name with a space before the extras", + input: "foo.whl [x]", + want: []string{"requirement foo.whl[x] hashes "}, + }, + { + name: "archive-like name with a space before the extras, and a marker", + input: `foo.whl [x]; os_name == "a"`, + want: []string{`requirement foo.whl[x]; os_name == "a" hashes `}, + }, + { + name: "archive-like name with a version after a space", + input: "foo.whl >=1", + want: []string{"requirement foo.whl>=1 hashes "}, + }, + { + name: "archive-like name with extras and a version in parentheses", + input: "foo.whl[x] (>=1 )", + want: []string{"requirement foo.whl[x]>=1 hashes "}, + }, + { + name: "version in parentheses with an archive extension", + input: "foo (===x.whl )", + want: []string{"requirement foo===x.whl hashes "}, + }, + { + // pip reads this as the file "foo ===x.whl". + name: "version with an archive extension after a space", + input: "foo ===x.whl", + wantErr: errTrailing, + }, + { + // pip reads this as the file "foo.whl[x]" with a marker. + name: "archive with extras and a marker", + input: `foo.whl[x];os_name=="a"`, + wantErr: errTrailing, + }, + + // A path or archive with "@" and other text, when the text before "@" + // looks like a path. + { + name: "path with a slash before @", + input: "a/b.whl @ x", + wantErr: errTrailing, + }, + { + // The line must end with an archive extension to be a path. pip + // reads ".foo.tar.gz @ x" as a requirement, which is not valid. + name: "name that starts with a dot before @", + input: ".foo.tar.gz @ x.zip", + wantErr: errTrailing, + }, + + // An archive with an "@" only in its marker. Before, the "@" made the + // line a requirement named "foo.tar.gz". + { + name: "tar.gz archive with @ in the marker", + input: `foo.tar.gz ; platform_release == "a@b"`, + wantErr: errTrailing, + }, + { + name: "wheel with @ in the marker", + input: `foo-1.0-py3-none-any.whl ; os_name == "x@y"`, + wantErr: errTrailing, + }, + { + name: "zip archive with @ in the second marker clause", + input: `foo.zip ; os_name == "x" and platform_release == "@"`, + wantErr: errTrailing, + }, + + // A target with a marker after a ";" that has no whitespace before it. + // Before, an archive was a requirement named "foo.tar.gz", and a path + // kept the marker in its Raw text. + { + name: "archive with a semicolon before a marker with spaces", + input: `foo.tar.gz;os_name == "x"`, + wantErr: errTrailing, + }, + { + name: "archive with a semicolon before a marker with no spaces", + input: `foo.tar.gz;os_name=="x"`, + wantErr: errTrailing, + }, + { + name: "wheel with a semicolon before a marker", + input: `foo-1.0-py3-none-any.whl;os_name=="x"`, + wantErr: errTrailing, + }, + { + name: "archive with a semicolon and no marker", + input: `foo.tar.gz;`, + wantErr: errTrailing, + }, + { + name: "relative path with a semicolon before a marker", + input: `./pkg;os_name=="x"`, + wantErr: errTrailing, + }, + { + name: "path with a slash and a semicolon before a marker", + input: `sub/dir;os_name=="x"`, + wantErr: errTrailing, + }, + { + name: "relative path with a space before the semicolon", + input: `./pkg ;os_name=="x"`, + wantErr: errTrailing, + }, + + // A "name @ url" line with no URL, or with text after the URL. + { + name: "no URL after @", + input: "0.tar@", + wantErr: "Expected URL after '@'", + wantErrIs: requirement.ErrInvalidRequirement, + }, + { + name: "no URL after @ with a space", + input: "0.tar @", + wantErr: "Expected URL after '@'", + wantErrIs: requirement.ErrInvalidRequirement, + }, + { + name: "text after the URL", + input: "0.tar @ https://example.com/x extra", + wantErr: "Expected end of requirement string", + wantErrIs: requirement.ErrInvalidRequirement, + }, + { + name: "bad marker after the URL", + input: "0.tar@https://example.com/x ; bad marker", + wantErr: "invalid marker expression", + wantErrIs: requirement.ErrInvalidRequirement, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + if tt.wantErr != "" { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + if tt.wantErrIs != nil { + assert.True(t, errors.Is(err, tt.wantErrIs), "want %v", tt.wantErrIs) + } + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, entryValues(f)) + + again, err := Parse(f.String()) + require.NoError(t, err, "String() output parses again") + assert.Equal(t, tt.want, entryValues(again), "same entries after a round trip") + }) + } +} + +// isNamedURLRequirement follows pip's _get_url_from_path (pip 21.2.4): a line +// is "name @ url" when it has an "@" before its marker, and the text before +// the "@" does not look like a path. On POSIX, pip's _looks_like_path is true +// for text that contains "/" or starts with ".". +func TestIsNamedURLRequirement(t *testing.T) { + tests := []struct { + name string + args string + want bool + }{ + // "name @ url" requirements. + {name: "archive-like name with spaces around @", args: "foo.zip @ https://example.com/foo.zip", want: true}, + {name: "archive-like name with no spaces", args: "foo.zip@https://example.com/foo.zip", want: true}, + {name: "mixed-case archive extension", args: "0.tAr@0", want: true}, + {name: "URL that starts with a hash", args: "foo.tar@#frag", want: true}, + {name: "whitespace before the name and the @", args: " foo.zip @ x", want: true}, + {name: "@ before a marker with a space", args: `foo.whl@https://example.com/x ; os_name == "a@b"`, want: true}, + {name: "@ before a marker with no space", args: `foo.whl@https://example.com/x;os_name=="x"`, want: true}, + {name: "only the first @ counts", args: "foo.zip@user@example.com/x", want: true}, + { + // pip's _looks_like_path("") is false, so pip also reads this as + // "name @ url". requirement.Parse then rejects the empty name. + name: "empty text before @", + args: "@x", + want: true, + }, + + // No "@" before the marker. + {name: "empty args", args: "", want: false}, + {name: "archive with no @", args: "foo-1.0-py3-none-any.whl", want: false}, + {name: "@ only in the marker", args: `foo.tar.gz ; platform_release == "a@b"`, want: false}, + {name: "@ only in the marker with no space", args: `foo.tar.gz;os_name=="a@b"`, want: false}, + {name: "@ right after the semicolon", args: "foo.zip;@x", want: false}, + + // The text before "@" looks like a path. + {name: "relative path", args: "./foo.zip@x", want: false}, + {name: "parent path", args: "../foo.zip@x", want: false}, + {name: "name that starts with a dot", args: ".foo.tar.gz @ x", want: false}, + {name: "path with a slash", args: "a/b.whl @ x", want: false}, + {name: "absolute path", args: "/tmp/foo.zip@x", want: false}, + {name: "slash after whitespace before @", args: "foo /bar.zip @ x", want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, isNamedURLRequirement(tt.args)) + }) + } +} diff --git a/reqtxt/option_line_test.go b/reqtxt/option_line_test.go new file mode 100644 index 0000000..fee5a8e --- /dev/null +++ b/reqtxt/option_line_test.go @@ -0,0 +1,1002 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// On an option line, pip ignores each token that does not start with "-", +// and still reads the options after it. Checked with pip 21.2.4. +func TestParse_TokensAfterOptions(t *testing.T) { + tests := []struct { + name string + input string + want []string + }{ + { + // Found by fuzzing. "0 /" was a separate entry that File.String() + // could not write back. A lone "-" is not an option, so pip + // ignores it too. + name: "dash then a quoted token", + input: `- 0' '/`, + want: []string{}, + }, + { + name: "lone dash between options", + input: "--pre - --no-index", + want: []string{"option --pre=", "option --no-index="}, + }, + { + name: "known option then a requirement", + input: "--pre foo", + want: []string{"option --pre="}, + }, + { + name: "known option then two tokens", + input: "--pre foo bar", + want: []string{"option --pre="}, + }, + { + name: "known option then a quoted token", + input: "--pre 'foo bar'", + want: []string{"option --pre="}, + }, + { + // Before, these were errors, because the token was parsed as a + // requirement. pip ignores them. + name: "known option then a token that is not a requirement", + input: "--pre !!!", + want: []string{"option --pre="}, + }, + { + name: "known option then an unclosed extras list", + input: "--pre foo[", + want: []string{"option --pre="}, + }, + { + name: "known option then an operator only", + input: "--pre ===", + want: []string{"option --pre="}, + }, + { + name: "unknown option then a requirement", + input: "--frob foo", + want: []string{"option --frob="}, + }, + { + name: "option with a value then a requirement", + input: "--index-url=https://example.com foo", + want: []string{"option --index-url=https://example.com"}, + }, + { + name: "include then a requirement", + input: "-r other.txt foo", + want: []string{"include other.txt"}, + }, + { + name: "an option after an ignored token is still read", + input: "--pre foo --index-url=https://example.com", + want: []string{"option --pre=", "option --index-url=https://example.com"}, + }, + { + // pip ignores the other options of a line with -r (see + // TestParse_OptionLineKind). + name: "an option before an include is ignored", + input: "--pre -r other.txt", + want: []string{"include other.txt"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + require.NoError(t, err) + assert.Equal(t, tt.want, entryValues(f)) + + again, err := Parse(f.String()) + require.NoError(t, err, "String() output parses again") + assert.Equal(t, tt.want, entryValues(again), "same entries after a round trip") + }) + } +} + +// After "-e ", every token must be a per-requirement option. Unlike +// pip, which ignores such a token, this package returns an error. +// describeEntry returns a short text for e that shows its type, and for an +// include or an editable requirement, the option. +func describeEntry(e Entry) string { + switch v := e.(type) { + case *IncludeEntry: + if v.Constraint { + return "-c " + v.Path + } + return "-r " + v.Path + case *UnnamedEntry: + if v.Editable { + // renderEntry also writes the hashes and the options. + return renderEntry(v) + } + return "unnamed " + v.Raw + case *OptionEntry: + return "option " + v.Name + "=" + v.Value + case *RequirementEntry: + // renderEntry also writes the hashes and the options. + return "requirement " + renderEntry(v) + } + return "" +} + +// pip reads all of the options of a line first, so an invalid option is an +// error anywhere on the line. Then a line with -e is only that editable +// requirement. Otherwise a line with -r only includes its first -r file, and +// otherwise a line with -c only includes its first -c file. pip ignores the +// other options of such a line. Checked with pip 21.2.4. pip main has the same +// rules. +func TestParse_OptionLineKind(t *testing.T) { + tests := []struct { + name string + input string + // want is the describeEntry text of each entry, before and after the + // round trip through String(). + want []string + // wantErr is a part of the error text. A row with wantErr expects an + // error. + wantErr string + }{ + // A line with -r. + { + name: "option before the include is ignored", + input: "--pre -r a.txt", + want: []string{"-r a.txt"}, + }, + { + name: "option after the include is ignored", + input: "-r a.txt --pre", + want: []string{"-r a.txt"}, + }, + { + name: "index URL after the include is ignored", + input: "-r a.txt -i https://example.com/simple", + want: []string{"-r a.txt"}, + }, + { + name: "hash after the include is ignored", + input: "-r a.txt --hash=sha256:abc", + want: []string{"-r a.txt"}, + }, + { + name: "only the first of two requirements includes", + input: "-r a.txt -r b.txt", + want: []string{"-r a.txt"}, + }, + { + name: "an empty second requirements include is not an error", + input: "-r a.txt -r ''", + want: []string{"-r a.txt"}, + }, + { + name: "requirements include after a constraints include wins", + input: "-c a.txt -r b.txt", + want: []string{"-r b.txt"}, + }, + { + name: "requirements include before a constraints include wins", + input: "-r a.txt -c b.txt", + want: []string{"-r a.txt"}, + }, + { + name: "an empty constraints include is not an error when -r wins", + input: "-c '' -r a.txt", + want: []string{"-r a.txt"}, + }, + + // A line with -c and no -r. + { + name: "only the first of two constraints includes", + input: "-c a.txt -c b.txt", + want: []string{"-c a.txt"}, + }, + { + name: "option before the constraints include is ignored", + input: "--pre -c a.txt", + want: []string{"-c a.txt"}, + }, + + // A line with -e. + { + name: "editable requirement wins over an include", + input: "-r a.txt -e ./pkg", + want: []string{"-e ./pkg"}, + }, + { + name: "option before the editable requirement is ignored", + input: "--pre -e ./pkg", + want: []string{"-e ./pkg"}, + }, + + // A line with no -r, -c or -e keeps all of its options. + { + name: "two options", + input: "--pre --index-url=https://example.com/simple", + want: []string{"option --pre=", "option --index-url=https://example.com/simple"}, + }, + + // An invalid option is an error, also when pip ignores the option. + { + name: "empty path in the include that pip uses", + input: "-r '' -r a.txt", + wantErr: "line 1: -r/--requirement requires a value", + }, + { + name: "option with no value after the include", + input: "-r a.txt --index-url", + wantErr: "line 1: --index-url requires a value", + }, + { + name: "boolean option with a value after the include", + input: "-r a.txt --no-index=x", + wantErr: "line 1: --no-index does not take a value", + }, + { + name: "ambiguous option after the include", + input: "-r a.txt --p", + wantErr: "line 1: ambiguous option --p", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + if tt.wantErr != "" { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + got := make([]string, len(f.Entries)) + for i, e := range f.Entries { + got[i] = describeEntry(e) + } + assert.Equal(t, tt.want, got) + + again, err := Parse(f.String()) + require.NoError(t, err, "String() output parses again") + gotAgain := make([]string, len(again.Entries)) + for i, e := range again.Entries { + gotAgain[i] = describeEntry(e) + } + assert.Equal(t, tt.want, gotAgain, "same entries after a round trip") + }) + } +} + +// optparse reads a token that is only "--" as the end of the options, so pip +// ignores the rest of the line. This applies on an option line and on a +// requirement line. An option that takes a value still takes "--" as its +// value. "--=x" is an error, because optparse reads "--" as a prefix of every +// long option. Checked with pip 21.2.4. +func TestParse_EndOfOptions(t *testing.T) { + tests := []struct { + name string + input string + // want is the describeEntry text of each entry, before and after the + // round trip through String(). + want []string + // wantErr is a part of the error text. A row with wantErr expects an + // error. + wantErr string + }{ + // Option lines. + { + name: "two dashes only", + input: "--", + want: []string{}, + }, + { + name: "token after two dashes", + input: "-- foo", + want: []string{}, + }, + { + name: "option before two dashes", + input: "--pre --", + want: []string{"option --pre="}, + }, + { + name: "option after two dashes is ignored", + input: "--pre -- --index-url x", + want: []string{"option --pre="}, + }, + { + name: "only an option after two dashes", + input: "-- --pre", + want: []string{}, + }, + { + name: "include after two dashes is ignored", + input: "-r a.txt -- -r b.txt", + want: []string{"-r a.txt"}, + }, + { + name: "only an include after two dashes", + input: "-- -r a.txt", + want: []string{}, + }, + { + name: "option before two dashes and an include after them", + input: "--pre -- -r a.txt", + want: []string{"option --pre="}, + }, + { + name: "only an editable requirement after two dashes", + input: "-- -e ./pkg", + want: []string{}, + }, + + // Requirement and editable lines. + { + name: "editable requirement before two dashes", + input: "-e ./pkg --", + want: []string{"-e ./pkg"}, + }, + { + name: "requirement before two dashes", + input: "foo --", + want: []string{"requirement foo"}, + }, + { + name: "hash after two dashes is ignored", + input: "foo -- --hash=sha256:x", + want: []string{"requirement foo"}, + }, + { + name: "hash before two dashes is kept", + input: "foo --hash=sha256:x -- --hash=sha256:y", + want: []string{"requirement foo --hash=sha256:x"}, + }, + { + // A token that does not start with "-" is an error after a + // requirement, but not after "--". + name: "token after two dashes on a requirement line", + input: "foo -- bar", + want: []string{"requirement foo"}, + }, + + // Two dashes as the value of an option. + { + name: "two dashes as an index URL", + input: "--index-url --", + want: []string{"option --index-url=--"}, + }, + { + name: "two dashes as an include path", + input: "-r --", + want: []string{"-r --"}, + }, + + // Two dashes with a value. + { + name: "two dashes with a value on an option line", + input: "--=x", + wantErr: "line 1: ambiguous option --", + }, + { + name: "two dashes with a value after an option", + input: "--pre --=x", + wantErr: "line 1: ambiguous option --", + }, + { + name: "two dashes with a value on a requirement line", + input: "foo --=x", + wantErr: "line 1: ambiguous option --", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + if tt.wantErr != "" { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + got := make([]string, len(f.Entries)) + for i, e := range f.Entries { + got[i] = describeEntry(e) + } + assert.Equal(t, tt.want, got) + + again, err := Parse(f.String()) + require.NoError(t, err, "String() output parses again: %q", f.String()) + gotAgain := make([]string, len(again.Entries)) + for i, e := range again.Entries { + gotAgain[i] = describeEntry(e) + } + assert.Equal(t, tt.want, gotAgain, "same entries after a round trip") + }) + } +} + +// pip reads an option line with Python's optparse, which reads "-rother.txt" +// as "-r" with the value "other.txt". Checked with Python's optparse module. +func TestParse_ShortOptionWithAttachedValue(t *testing.T) { + nbsp := string(rune(0x00a0)) + + tests := []struct { + name string + input string + want []string + wantString string + }{ + { + name: "requirement option", + input: "-rother.txt", + want: []string{"-r other.txt"}, + wantString: "-r other.txt", + }, + { + name: "constraint option", + input: "-cconstraints.txt", + want: []string{"-c constraints.txt"}, + wantString: "-c constraints.txt", + }, + { + name: "editable option with the current directory", + input: "-e.", + want: []string{"-e ."}, + wantString: "-e .", + }, + { + name: "editable option with a path", + input: "-e./pkg", + want: []string{"-e ./pkg"}, + wantString: "-e ./pkg", + }, + { + name: "index URL option", + input: "-ihttps://example.com/simple", + want: []string{"option --index-url=https://example.com/simple"}, + wantString: "--index-url=https://example.com/simple", + }, + { + name: "find links option", + input: "-fwheels", + want: []string{"option --find-links=wheels"}, + wantString: "--find-links=wheels", + }, + { + // optparse keeps a "=" that is not directly after the option. + name: "value with an equals sign", + input: "-rfoo=bar.txt", + want: []string{"-r foo=bar.txt"}, + wantString: "-r foo=bar.txt", + }, + { + name: "value that starts with a dash", + input: "-r-dev.txt", + want: []string{"-r -dev.txt"}, + wantString: "-r -dev.txt", + }, + { + // A no-break space is not a token separator for shlex. + name: "value that starts with a no-break space", + input: "-r" + nbsp + "other.txt", + want: []string{"-r " + nbsp + "other.txt"}, + wantString: `-r "` + nbsp + `other.txt"`, + }, + { + // U+001F is not a line break. It is Python whitespace (see + // isPythonSpace), so String() quotes the value, as for the + // no-break space above. + name: "value that starts with a control character", + input: "-r\x1fother.txt", + want: []string{"-r \x1fother.txt"}, + wantString: "-r \"\x1fother.txt\"", + }, + { + // pip ignores the other options of a line with -r (see + // TestParse_OptionLineKind). + name: "option before the short option", + input: "--pre -rother.txt", + want: []string{"-r other.txt"}, + wantString: "-r other.txt", + }, + { + name: "option after the short option", + input: "-rother.txt --pre", + want: []string{"-r other.txt"}, + wantString: "-r other.txt", + }, + + // These do not change. + { + // Different from pip: optparse reads the path "=other.txt". + name: "short option, then equals", + input: "-r=other.txt", + want: []string{"-r other.txt"}, + wantString: "-r other.txt", + }, + { + name: "long option, then equals", + input: "--requirement=other.txt", + want: []string{"-r other.txt"}, + wantString: "-r other.txt", + }, + { + // Only a short option takes the rest of the token. + name: "long option with no equals", + input: "--rother.txt", + want: []string{"option --rother.txt="}, + wantString: "--rother.txt", + }, + { + name: "unknown short option", + input: "-xfoo", + want: []string{"option -xfoo="}, + wantString: "-xfoo", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + require.NoError(t, err) + var got []string + for _, e := range f.Entries { + got = append(got, describeEntry(e)) + } + assert.Equal(t, tt.want, got) + text := f.String() + assert.Equal(t, tt.wantString, text) + + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + var gotAgain []string + for _, e := range again.Entries { + gotAgain = append(gotAgain, describeEntry(e)) + } + assert.Equal(t, got, gotAgain, "same entries after a round trip") + }) + } +} + +// pip reads an option line with Python's optparse, which accepts a unique +// prefix of a long option, and fails on a prefix of two or more options. +// Checked with Python's optparse module and pip's option list. +func TestParse_AbbreviatedLongOption(t *testing.T) { + tests := []struct { + name string + input string + want []string + // wantString is File.String() on success. + wantString string + // wantErr is a substring of the error. Empty means no error. + wantErr string + }{ + // A unique prefix gives the full option. + { + name: "index URL with equals", + input: "--ind=https://example.com/simple", + want: []string{"option --index-url=https://example.com/simple"}, + wantString: "--index-url=https://example.com/simple", + }, + { + name: "index URL with a separate value", + input: "--index https://example.com/simple", + want: []string{"option --index-url=https://example.com/simple"}, + wantString: "--index-url=https://example.com/simple", + }, + { + name: "extra index URL", + input: "--extra https://example.com/simple", + want: []string{"option --extra-index-url=https://example.com/simple"}, + wantString: "--extra-index-url=https://example.com/simple", + }, + {name: "requirement option", input: "--requirem other.txt", want: []string{"-r other.txt"}, wantString: "-r other.txt"}, + {name: "constraint option", input: "--constr=c.txt", want: []string{"-c c.txt"}, wantString: "-c c.txt"}, + {name: "editable option", input: "--edit ./pkg", want: []string{"-e ./pkg"}, wantString: "-e ./pkg"}, + {name: "find links option", input: "--find wheels", want: []string{"option --find-links=wheels"}, wantString: "--find-links=wheels"}, + {name: "boolean option", input: "--pref", want: []string{"option --prefer-binary="}, wantString: "--prefer-binary"}, + { + name: "prefix on the second option of a line", + input: "--pre --ind https://example.com/simple", + want: []string{"option --pre=", "option --index-url=https://example.com/simple"}, + wantString: "--pre\n--index-url=https://example.com/simple", + }, + { + name: "hash option of a requirement", + input: "foo --ha=sha256:abc", + want: []string{"requirement foo --hash=sha256:abc"}, + wantString: "foo --hash=sha256:abc", + }, + { + name: "config settings option of a requirement", + input: "foo --conf=x=y", + want: []string{"requirement foo --config-settings=x=y"}, + wantString: "foo --config-settings=x=y", + }, + + // Options that were not known before. + { + // pip has "--pypi-url" as a second long name of --index-url. + name: "PyPI URL option", + input: "--pypi-url https://example.com/simple", + want: []string{"option --index-url=https://example.com/simple"}, + wantString: "--index-url=https://example.com/simple", + }, + { + name: "prefix of the PyPI URL option", + input: "--py https://example.com/simple", + want: []string{"option --index-url=https://example.com/simple"}, + wantString: "--index-url=https://example.com/simple", + }, + { + name: "no require hashes option", + input: "--no-r", + want: []string{"option --no-require-hashes="}, + wantString: "--no-require-hashes", + }, + + // A full name is not a prefix, also when it starts another name. + { + // "--pre" is also the start of "--prefer-binary". + name: "full name that starts another name", + input: "--pre", + want: []string{"option --pre="}, + wantString: "--pre", + }, + + // A prefix of two or more options is an error, as in pip. + { + name: "prefix of the requirement and require hashes options", + input: "--req=other.txt", + wantErr: "line 1: ambiguous option --req: it matches --require-hashes, --requirement", + }, + { + name: "prefix of three options", + input: "--no-", + wantErr: "line 1: ambiguous option --no-: it matches --no-binary, --no-index, --no-require-hashes", + }, + { + name: "ambiguous prefix on the second option of a line", + input: "--pre --p", + wantErr: "line 1: ambiguous option --p: it matches --pre, --prefer-binary, --pypi-url", + }, + { + name: "ambiguous prefix on a requirement line", + input: "foo --co=x", + wantErr: "line 1: ambiguous option --co: it matches --config-settings, --constraint", + }, + { + name: "ambiguous prefix on line 2", + input: "foo\n--e ./pkg", + wantErr: "line 2: ambiguous option --e: it matches --editable, --extra-index-url", + }, + + // These stay unknown options. + { + // "--global-option" is not an option of pip now, so it has no + // prefix. The full name still works. + name: "prefix of an option of older pip versions", + input: "foo --glob=x", + want: []string{"requirement foo --glob=x"}, + wantString: "foo --glob=x", + }, + { + name: "name that is longer than an option", + input: "--hashes", + want: []string{"option --hashes="}, + wantString: "--hashes", + }, + { + // "--" alone ends the options (see TestParse_EndOfOptions). With + // a value, optparse reads "--" as a prefix of every long option. + name: "two dashes with a value", + input: "--=x", + wantErr: "line 1: ambiguous option --: it matches --all-releases, --config-settings,", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + if tt.wantErr != "" { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + var got []string + for _, e := range f.Entries { + got = append(got, describeEntry(e)) + } + assert.Equal(t, tt.want, got) + text := f.String() + assert.Equal(t, tt.wantString, text) + + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + var gotAgain []string + for _, e := range again.Entries { + gotAgain = append(gotAgain, describeEntry(e)) + } + assert.Equal(t, got, gotAgain, "same entries after a round trip") + }) + } +} + +// pip has "-C" as the short form of "--config-settings". Checked with +// Python's optparse module. +func TestParse_ShortConfigSettingsOption(t *testing.T) { + tests := []struct { + name string + input string + want []string + // wantString is File.String() on success. + wantString string + // wantErr is a substring of the error. Empty means no error. + wantErr string + }{ + { + name: "separate value", + input: "foo -C x=y", + want: []string{"requirement foo --config-settings=x=y"}, + wantString: "foo --config-settings=x=y", + }, + { + name: "attached value", + input: "foo -Cx=y", + want: []string{"requirement foo --config-settings=x=y"}, + wantString: "foo --config-settings=x=y", + }, + { + // Different from pip: optparse reads the value "=x=y". + name: "equals, then the value", + input: "foo -C=x=y", + want: []string{"requirement foo --config-settings=x=y"}, + wantString: "foo --config-settings=x=y", + }, + { + name: "two settings", + input: "foo -C a=1 -Cb=2", + want: []string{"requirement foo --config-settings=a=1 --config-settings=b=2"}, + wantString: "foo --config-settings=a=1 --config-settings=b=2", + }, + { + name: "after a hash option", + input: "foo --hash=sha256:abc -C x=y", + want: []string{"requirement foo --hash=sha256:abc --config-settings=x=y"}, + wantString: "foo --hash=sha256:abc --config-settings=x=y", + }, + { + name: "editable requirement", + input: "-e ./pkg -C x=y", + want: []string{"-e ./pkg --config-settings=x=y"}, + wantString: "-e ./pkg --config-settings=x=y", + }, + { + name: "no value", + input: "foo -C", + wantErr: "line 1: --config-settings requires a value", + }, + { + // Short options are case sensitive. "-c" is the constraint + // option, not "--config-settings". As in pip, it takes the next + // token as its value. pip then ignores it on a requirement line, + // and this package keeps it as an option. + name: "lower case c", + input: "foo -c x=y", + want: []string{"requirement foo -c=x=y"}, + wantString: "foo -c=x=y", + }, + + // An option line with no requirement. "-C" gives the same entry as + // "--config-settings". + { + name: "attached value with no requirement", + input: "-Cx=y", + want: []string{"option --config-settings=x=y"}, + wantString: "--config-settings=x=y", + }, + { + // As with "--config-settings x=y", the next token is not the + // value. String() writes the empty value of an option that + // takes a value as "". + name: "separate value with no requirement", + input: "-C x=y", + want: []string{"option --config-settings="}, + wantString: `--config-settings=""`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + if tt.wantErr != "" { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + var got []string + for _, e := range f.Entries { + got = append(got, describeEntry(e)) + } + assert.Equal(t, tt.want, got) + text := f.String() + assert.Equal(t, tt.wantString, text) + + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + var gotAgain []string + for _, e := range again.Entries { + gotAgain = append(gotAgain, describeEntry(e)) + } + assert.Equal(t, got, gotAgain, "same entries after a round trip") + }) + } +} + +// A lone "-" after a requirement is not an option, so it is an unexpected +// token, like any other word there. Before, it was an option named "-". +func TestParse_LoneDashAfterRequirement(t *testing.T) { + for _, input := range []string{"foo -", "foo --hash=sha256:abc -", "-e ./x -"} { + t.Run(input, func(t *testing.T) { + _, err := Parse(input) + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), `line 1: unexpected token "-"`) + }) + } +} + +func TestParse_EditableWithTrailingToken(t *testing.T) { + _, err := Parse("-e ./x foo") + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), `unexpected token "foo"`) +} + +// pip reads the options of a requirement line with the same parser as an +// option line. So an option that takes a value, such as --index-url or a +// second -e, takes the next token, and the line is not an error. pip then +// ignores the option, because the line is a requirement. This package keeps +// it as an option of the requirement, the same as the "=" form. +func TestParse_ValueOptionOnRequirementLine(t *testing.T) { + tests := []struct { + name string + input string + want []string + wantString string + wantErr string + }{ + { + name: "index URL with a space", + input: "foo --index-url https://x", + want: []string{"requirement foo --index-url=https://x"}, + wantString: "foo --index-url=https://x", + }, + { + name: "index URL with a space is the same as with =", + input: "foo --index-url=https://x", + want: []string{"requirement foo --index-url=https://x"}, + wantString: "foo --index-url=https://x", + }, + { + name: "abbreviated index URL", + input: "foo --ind https://x", + want: []string{"requirement foo --index-url=https://x"}, + wantString: "foo --index-url=https://x", + }, + { + name: "short find links", + input: "foo -f ./wheels", + want: []string{"requirement foo -f=./wheels"}, + wantString: "foo -f=./wheels", + }, + { + name: "include with an attached value", + input: "foo -rother.txt", + want: []string{"requirement foo -r=other.txt"}, + wantString: "foo -r=other.txt", + }, + { + name: "two editable requirements", + input: "-e ./a -e ./b", + want: []string{"-e ./a -e=./b"}, + wantString: "-e ./a -e=./b", + }, + { + name: "editable requirement after a requirement", + input: "foo --editable ./b", + want: []string{"requirement foo --editable=./b"}, + wantString: "foo --editable=./b", + }, + { + // String() writes the empty value as "", so that the option does + // not take the next token when the line is read again. + name: "empty value", + input: `foo -c= --hash=sha256:abc`, + want: []string{"requirement foo --hash=sha256:abc -c=\"\""}, + wantString: `foo --hash=sha256:abc -c=""`, + }, + { + name: "no value", + input: "foo --index-url", + wantErr: "line 1: --index-url requires a value", + }, + { + // A boolean option does not take the next token. + name: "boolean option", + input: "foo --pre x", + wantErr: `line 1: unexpected token "x"`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + if tt.wantErr != "" { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + var got []string + for _, e := range f.Entries { + got = append(got, describeEntry(e)) + } + assert.Equal(t, tt.want, got) + text := f.String() + assert.Equal(t, tt.wantString, text) + + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + var gotAgain []string + for _, e := range again.Entries { + gotAgain = append(gotAgain, describeEntry(e)) + } + assert.Equal(t, got, gotAgain, "same entries after a round trip") + }) + } +} + +// The token "-=" gives an option named "-" with an empty value. A bare "-" is +// not an option, so String() writes this option as `-=""`, which reads back +// as the same option. Found by fuzzing. +func TestString_OptionNamedDash(t *testing.T) { + tests := []struct { + input string + want []string + wantString string + }{ + {input: "-=", want: []string{"option -="}, wantString: `-=""`}, + {input: "foo -=", want: []string{`requirement foo -=""`}, wantString: `foo -=""`}, + } + + for _, tt := range tests { + t.Run(tt.input, func(t *testing.T) { + f, err := Parse(tt.input) + require.NoError(t, err) + got := describeEntries(f) + assert.Equal(t, tt.want, got) + text := f.String() + assert.Equal(t, tt.wantString, text) + + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + assert.Equal(t, got, describeEntries(again), "same entries after a round trip") + }) + } +} diff --git a/reqtxt/parse.go b/reqtxt/parse.go index 5b1310b..f6ae998 100644 --- a/reqtxt/parse.go +++ b/reqtxt/parse.go @@ -14,8 +14,11 @@ package reqtxt import ( "errors" "fmt" + "slices" "strings" + "unicode" + "github.com/posit-dev/go-python-packaging/internal/errtext" "github.com/posit-dev/go-python-packaging/requirement" ) @@ -33,18 +36,21 @@ type knownOption struct { // this table is still accepted (see dispatchFileOption) but captured // generically, without normalization. var knownOptions = map[string]knownOption{ - "-i": {optIndexURL, 1}, - "--index-url": {optIndexURL, 1}, - "--extra-index-url": {optExtraIndexURL, 1}, - "--no-index": {optNoIndex, 0}, - "-f": {optFindLinks, 1}, - "--find-links": {optFindLinks, 1}, - "--require-hashes": {optRequireHashes, 0}, - "--pre": {optPre, 0}, - "--trusted-host": {optTrustedHost, 1}, - "--no-binary": {optNoBinary, 1}, - "--only-binary": {optOnlyBinary, 1}, - "--prefer-binary": {optPreferBinary, 0}, + "-i": {optIndexURL, 1}, + "--index-url": {optIndexURL, 1}, + // pip has "--pypi-url" as a second long name of --index-url. + "--pypi-url": {optIndexURL, 1}, + "--no-require-hashes": {optNoRequireHashes, 0}, + "--extra-index-url": {optExtraIndexURL, 1}, + "--no-index": {optNoIndex, 0}, + "-f": {optFindLinks, 1}, + "--find-links": {optFindLinks, 1}, + "--require-hashes": {optRequireHashes, 0}, + "--pre": {optPre, 0}, + "--trusted-host": {optTrustedHost, 1}, + "--no-binary": {optNoBinary, 1}, + "--only-binary": {optOnlyBinary, 1}, + "--prefer-binary": {optPreferBinary, 0}, // These three are in pip's SUPPORTED_OPTIONS and were missing here, which // mattered more than "not normalized": an unknown bare option is assumed // boolean, so its argument was dispatched as a separate line and became a @@ -59,12 +65,24 @@ var knownOptions = map[string]knownOption{ // perLineValueOptions are the per-requirement options (other than // "--hash") that pip's SUPPORTED_OPTIONS_REQ recognizes and that this // package captures onto RequirementEntry.Options / UnnamedEntry.Options. +// --global-option and --install-option are from older pip, such as 21.2.4; +// current pip has only --config-settings (see longOptionNames). var perLineValueOptions = map[string]bool{ "--config-settings": true, "--global-option": true, "--install-option": true, } +// maxParseEntries is the maximum number of entries in the File that Parse +// returns. Real requirements files have a few hundred entries at most. +const maxParseEntries = 100_000 + +// maxLineOptions is the maximum number of options on one line: the options of +// an option line, or the per-requirement options of a requirement. Parse +// checks maxParseEntries after each line, so without this limit one long line +// could make millions of entries or options first. +const maxLineOptions = 100_000 + // Parse parses content as a requirements.txt (or constraints) file. It // follows pip's req_file preprocessing pipeline (see preprocess) to // produce logical lines, then dispatches each one by its leading token @@ -72,22 +90,32 @@ var perLineValueOptions = map[string]bool{ // Entry it represents. // // Parse does not follow "-r"/"-c" includes; that is Flatten's job. +// +// Parse returns an error if the file has more than 100,000 entries, or if a +// line has more than 100,000 options. It stops at that entry or option, so a +// very large file does not use memory for all of its entries first. With +// WithEnv, it also returns an error if ${NAME} expansion adds more than 16 MiB +// to the file. func Parse(content string, opts ...ParseOption) (*File, error) { var cfg parseConfig for _, opt := range opts { opt(&cfg) } + file, _, err := parseWithConfig(content, cfg) + return file, err +} - lines, err := preprocess(content, cfg) - if err != nil { - return nil, err - } - +// parseWithConfig is Parse with its options applied to cfg. It also returns the +// number of bytes that ${NAME} expansion added to content, which Flatten counts +// in maxIncludedBytes. Flatten calls it directly, so that it does not build +// option functions for each file. +func parseWithConfig(content string, cfg parseConfig) (*File, int, error) { file := &File{} - for _, ll := range lines { + var others, includes int + envGrowth, err := eachLogicalLine(content, cfg, func(ll logicalLine) error { entries, err := dispatchLogicalLine(ll.text, ll.line) if err != nil { - return nil, err + return err } // Stamped here rather than at each construction site: every entry from a // logical line shares that line, including the per-requirement options @@ -95,11 +123,30 @@ func Parse(content string, opts ...ParseOption) (*File, error) { src := Source{Path: cfg.path, Line: ll.line} for _, e := range entries { stampSource(e, src) + if _, isInclude := e.(*IncludeEntry); isInclude { + includes++ + } else { + others++ + } + } + switch { + case !cfg.hasFlattenLimits: + if others+includes > maxParseEntries { + return lineError(ll.line, "the file has more than %d entries", maxParseEntries) + } + case others > cfg.flatten.entries: + return errTooManyEntries + case includes > cfg.flatten.includes: + return errTooManyIncludes } file.Entries = append(file.Entries, entries...) + return nil + }) + if err != nil { + return nil, 0, err } - return file, nil + return file, envGrowth, nil } // stampSource records src on e and on any per-requirement options attached to @@ -134,45 +181,118 @@ func stampSource(e Entry, src Source) { // strip quotes that are semantically significant in a "; marker" clause // and would choke on unquoted whitespace inside a version specifier. func dispatchLogicalLine(text string, lineNum int) ([]Entry, error) { - fields := strings.Fields(text) - if len(fields) == 0 { + first := firstField(text) + if first == "" { // preprocess already drops blank/all-whitespace logical lines; // guard defensively in case that invariant ever changes. return nil, nil } - if strings.HasPrefix(fields[0], "-") { + if strings.HasPrefix(first, "-") { tokens, err := shlexSplit(text) if err != nil { return nil, wrapLineErr(lineNum, err) } - return dispatchLine(tokens, lineNum) + entries, err := dispatchLine(tokens, lineNum) + if err != nil { + return nil, err + } + return selectLineEntries(entries, lineNum) } return dispatchPackageLine(text, lineNum) } -// dispatchLine dispatches the tokens of one (recursive tail of a) logical -// line into zero or more Entry values: the leading token determines the -// entry kind. It is reached only for lines whose first raw token starts -// with "-" (see dispatchLogicalLine) - -r/-c/-e, a known file option, or -// an unrecognized flag - never for a package/requirement line, which -// dispatchPackageLine handles without shlex-tokenizing the whole line. -// For the plain file-option branch only, any tokens left over after that -// flag's own value (if any) are dispatched again as if they began a new -// line — so e.g. an unrecognized boolean flag followed by a requirement -// ("--frob foo") yields two entries, rather than the flag swallowing -// "foo" as its value. The include/editable/package branches instead -// consume the *entire* remaining token stream for their own per-line -// options (hashes, etc.) and never recurse. +// selectLineEntries returns only the entry of an option line that pip uses: +// the "-e" editable requirement, else the first "-r" include, else the first +// "-c" include. pip ignores the other options of such a line (see +// _parse_and_recurse in pip._internal.req.req_file). A line with none of these +// keeps all of its entries. Only an empty path in the selected include is an +// error, because pip opens only that file. +func selectLineEntries(entries []Entry, lineNum int) ([]Entry, error) { + var firstRequirement, firstConstraint *IncludeEntry + for _, e := range entries { + switch v := e.(type) { + case *UnnamedEntry: + // Only dispatchEditable makes an UnnamedEntry on an option line. + if v.Editable { + return []Entry{v}, nil + } + case *IncludeEntry: + if v.Constraint { + if firstConstraint == nil { + firstConstraint = v + } + } else if firstRequirement == nil { + firstRequirement = v + } + } + } + + include := firstRequirement + label := "-r/--requirement" + if include == nil { + include = firstConstraint + label = "-c/--constraint" + } + if include == nil { + return entries, nil + } + if include.Path == "" { + return nil, lineError(lineNum, "%s requires a value", label) + } + return []Entry{include}, nil +} + +// dispatchLine turns the tokens of an option line (one whose first token +// starts with "-") into one Entry for each option, in order. As in pip, a +// token that is not an option (see isOptionToken) is ignored, and "--" ends +// the options. "-e" takes the rest of the line as its per-requirement +// options. +// +// It loops instead of recursing, so a line with many options takes linear +// time and a fixed amount of stack. func dispatchLine(tokens []string, lineNum int) ([]Entry, error) { - if len(tokens) == 0 { - return nil, nil + var entries []Entry + for { + for len(tokens) > 0 && !isOptionToken(tokens[0]) { + tokens = tokens[1:] + } + // optparse reads "--" as the end of the options, so pip ignores the + // rest of the line. + if len(tokens) == 0 || tokens[0] == "--" { + return entries, nil + } + + if len(entries) == maxLineOptions { + return nil, lineOptionsOverLimit(lineNum) + } + entry, remaining, err := dispatchOption(tokens, lineNum) + if err != nil { + return nil, err + } + entries = append(entries, entry) + tokens = remaining } +} - first := tokens[0] +// isOptionToken reports whether pip's optparse reads tok as an option: tok +// starts with "-" and is not only "-". optparse reads a lone "-" as an +// argument, not an option. +func isOptionToken(tok string) bool { + return len(tok) > 1 && tok[0] == '-' +} + +// dispatchOption dispatches the option that starts tokens, which must be an +// option (see isOptionToken). It returns the option's entry and the tokens +// after the option and its value. +func dispatchOption(tokens []string, lineNum int) (Entry, []string, error) { + name, eqValue, hasEq := splitOptionToken(tokens[0]) + name, err := resolveLongOption(name, lineNum) + if err != nil { + return nil, nil, err + } rest := tokens[1:] - name, eqValue, hasEq := splitFlagValue(first) switch name { case "-r", "--requirement": @@ -183,16 +303,13 @@ func dispatchLine(tokens []string, lineNum int) ([]Entry, error) { return dispatchEditable(hasEq, eqValue, rest, lineNum) } - if strings.HasPrefix(first, "-") { - return dispatchFileOption(name, hasEq, eqValue, rest, lineNum) - } - - return dispatchPackage(first, rest, lineNum) + return dispatchFileOption(name, hasEq, eqValue, rest, lineNum) } -// dispatchInclude handles a leading "-r"/"--requirement" or -// "-c"/"--constraint" directive, producing an *IncludeEntry. -func dispatchInclude(constraint, hasEq bool, eqValue string, rest []string, lineNum int) ([]Entry, error) { +// dispatchInclude handles a "-r"/"--requirement" or "-c"/"--constraint" +// directive, producing an *IncludeEntry. It returns the tokens after the +// path. +func dispatchInclude(constraint, hasEq bool, eqValue string, rest []string, lineNum int) (Entry, []string, error) { label := "-r/--requirement" if constraint { label = "-c/--constraint" @@ -200,30 +317,27 @@ func dispatchInclude(constraint, hasEq bool, eqValue string, rest []string, line path, remaining, err := takeValue(label, hasEq, eqValue, rest, lineNum) if err != nil { - return nil, err - } - - following, err := dispatchLine(remaining, lineNum) - if err != nil { - return nil, err + return nil, nil, err } + // An empty path is an error only in the include that pip uses, because + // pip fails only when it opens that file. selectLineEntries checks it. - entry := &IncludeEntry{Path: path, Constraint: constraint} - return append([]Entry{entry}, following...), nil + return &IncludeEntry{Path: path, Constraint: constraint}, remaining, nil } -// dispatchEditable handles a leading "-e"/"--editable" directive: the -// next token is the install target, classified the same way a package -// line's target would be, plus any trailing per-line options. -func dispatchEditable(hasEq bool, eqValue string, rest []string, lineNum int) ([]Entry, error) { +// dispatchEditable handles a "-e"/"--editable" directive: the next token is +// the install target, classified the same way a package line's target would +// be, plus any trailing per-line options. It consumes every token after the +// target, so it returns no remaining tokens. +func dispatchEditable(hasEq bool, eqValue string, rest []string, lineNum int) (Entry, []string, error) { target, remaining, err := takeValue("-e/--editable", hasEq, eqValue, rest, lineNum) if err != nil { - return nil, err + return nil, nil, err } kind, ok := classifyTarget(target) if !ok { - return nil, lineError(lineNum, "editable requirement %q is not a recognized VCS/URL/local-path target", target) + return nil, nil, lineError(lineNum, "editable requirement %s is not a recognized VCS/URL/local-path target", errtext.Quote(target)) } entry := &UnnamedEntry{ @@ -233,18 +347,18 @@ func dispatchEditable(hasEq bool, eqValue string, rest []string, lineNum int) ([ EggName: eggName(target), } if err := attachReqOptions(&entry.Hashes, &entry.Options, remaining, lineNum); err != nil { - return nil, err + return nil, nil, err } - return []Entry{entry}, nil + return entry, nil, nil } -// dispatchFileOption handles a leading "-"/"--" token that isn't -// -r/-c/-e: a file-level pip option, matched against knownOptions when -// recognized, or captured generically otherwise. A standalone "--hash" -// (with no preceding requirement to attach to) is rejected: "--hash" is -// only ever a per-requirement option (see attachReqOptions). -func dispatchFileOption(name string, hasEq bool, eqValue string, rest []string, lineNum int) ([]Entry, error) { +// dispatchFileOption handles a "-"/"--" token that isn't -r/-c/-e: a +// file-level pip option, matched against knownOptions when recognized, or +// captured generically otherwise. A standalone "--hash" (with no requirement +// to attach to) is kept as an OptionEntry (see below). It returns the tokens +// after the option and its value. +func dispatchFileOption(name string, hasEq bool, eqValue string, rest []string, lineNum int) (Entry, []string, error) { if name == "--hash" { // pip does NOT reject this. req_file.py logs "line %s has --hash but no // requirement, and will be ignored" and carries on, so a file containing @@ -263,11 +377,7 @@ func dispatchFileOption(name string, hasEq bool, eqValue string, rest []string, // never sees a value it can use either way. value, remaining = eqValue, rest } - following, err := dispatchLine(remaining, lineNum) - if err != nil { - return nil, err - } - return append([]Entry{&OptionEntry{Name: name, Value: value}}, following...), nil + return &OptionEntry{Name: name, Value: value}, remaining, nil } var ( @@ -282,71 +392,30 @@ func dispatchFileOption(name string, hasEq bool, eqValue string, rest []string, var err error value, remaining, err = takeValue(name, hasEq, eqValue, rest, lineNum) if err != nil { - return nil, err + return nil, nil, err } case hasEq: // A known boolean (arity-0) option given an "=value" is // invalid, matching pip optparse's rejection of a value for // an option that doesn't take one (e.g. "--no-index=x"). - return nil, lineError(lineNum, "%s does not take a value", name) + return nil, nil, lineError(lineNum, "%s does not take a value", name) default: // A boolean known option never consumes a following token. value, remaining = eqValue, rest } } else { - // Unknown flag: "--opt=value" takes the value; a bare "--opt" is - // boolean and never consumes the next token — it is left to be - // dispatched as its own, separate entry. - // - // That assumption is a guess, and it is the RIGHT guess for a boolean - // followed by a requirement ("--frob foo" yields the option and foo). It is - // the wrong guess for an unknown arity-1 option, where the argument becomes - // a fabricated requirement ("--timeout 60" yields a package named "60"). - // Both readings are guesses and neither is safe, so the fix is not to - // change the guess but to leave fewer options unknown: see knownOptions, - // which is audited against pip's SUPPORTED_OPTIONS. + // Unknown option: pip rejects it, but this package keeps it. We + // cannot know whether it takes a value, so "--opt=value" takes the + // value, and a bare "--opt" takes none. A following token that does + // not start with "-" is then ignored, as pip ignores it (see + // dispatchLine): "--timeout 60" gives "--timeout" with no value and + // drops "60". That loses the value of an unknown option that takes + // one, so the fix is to leave fewer options unknown: see knownOptions, + // which follows pip's SUPPORTED_OPTIONS. value, remaining = eqValue, rest } - following, err := dispatchLine(remaining, lineNum) - if err != nil { - return nil, err - } - - entry := &OptionEntry{Name: name, Value: value} - return append([]Entry{entry}, following...), nil -} - -// dispatchPackage handles a package/requirement line: first is either a -// VCS/URL/local-path target (classifyTarget) or a plain PEP 508 -// requirement (requirement.Parse). Unlike the file-option branch, every -// remaining token on the line is a per-requirement option attached to -// this single entry (attachReqOptions) — none of it is dispatched as a -// separate entry. -func dispatchPackage(first string, rest []string, lineNum int) ([]Entry, error) { - var ( - entry Entry - hashes *[]Hash - options *[]OptionEntry - ) - - if kind, ok := classifyTarget(first); ok { - e := &UnnamedEntry{Raw: first, Kind: kind, EggName: eggName(first)} - entry, hashes, options = e, &e.Hashes, &e.Options - } else { - req, err := requirement.Parse(first) - if err != nil { - return nil, wrapLineErr(lineNum, err) - } - e := &RequirementEntry{Requirement: req} - entry, hashes, options = e, &e.Hashes, &e.Options - } - - if err := attachReqOptions(hashes, options, rest, lineNum); err != nil { - return nil, err - } - - return []Entry{entry}, nil + return &OptionEntry{Name: name, Value: value}, remaining, nil } // dispatchPackageLine handles a package/requirement logical line - one @@ -360,15 +429,13 @@ func dispatchPackage(first string, rest []string, lineNum int) ([]Entry, error) // inside a version specifier (e.g. "Django >= 3.2, < 4.0"). The // requirement/target text is passed to classifyTarget/requirement.Parse // verbatim; only the options tail is shlex-tokenized and attached via -// attachReqOptions, exactly as dispatchPackage does for a package tail -// reached via token recursion. +// attachReqOptions. func dispatchPackageLine(line string, lineNum int) ([]Entry, error) { argsText, optionsText := breakArgsOptions(line) - - // dispatchLogicalLine only calls dispatchPackageLine when line's - // first raw token doesn't start with "-", so breakArgsOptions always - // leaves at least that one token in argsText. - argFirst := strings.Fields(argsText)[0] + // pip strips the requirement text (name.strip() in parse_req_from_line). + // The line is trimmed already, but an environment variable value can add + // whitespace at its start or end, as in "${A}" with A=" ./pkg". + argsText = strings.TrimFunc(argsText, isPythonSpace) var ( entry Entry @@ -376,7 +443,8 @@ func dispatchPackageLine(line string, lineNum int) ([]Entry, error) { options *[]OptionEntry ) - if kind, ok := classifyTarget(argFirst); ok { + kind, ok := readAsTarget(argsText) + if ok { // A bare target (VCS/URL/archive/path) must be the line's only // argument token. UnnamedEntry has no Marker field, so any // trailing content here - almost always a "; marker" clause, e.g. @@ -385,8 +453,19 @@ func dispatchPackageLine(line string, lineNum int) ([]Entry, error) { // corrupting the target. PEP 508 markers are only supported on // named requirements, which route through requirement.Parse // below. Reject instead of silently truncating/corrupting. - if fields := strings.Fields(argsText); len(fields) != 1 { - return nil, lineError(lineNum, "direct-reference requirement %q does not support markers or trailing content", argsText) + // + // A local path ends at the first ";", as in pip (see readAsTarget), + // so a ";" with no whitespace before it, as in "./pkg;os_name=='x'", + // also starts a marker. + // argsText is trimmed and not empty (readAsTarget found a field), so + // it is one field unless it has whitespace inside. + manyFields := strings.IndexFunc(argsText, unicode.IsSpace) >= 0 + if manyFields || (kind == KindLocalPath && strings.Contains(argsText, ";")) { + return nil, lineError( + lineNum, + "direct-reference requirement %s does not support markers or trailing content", + errtext.Quote(argsText), + ) } e := &UnnamedEntry{Raw: argsText, Kind: kind, EggName: eggName(argsText)} entry, hashes, options = e, &e.Hashes, &e.Options @@ -410,49 +489,142 @@ func dispatchPackageLine(line string, lineNum int) ([]Entry, error) { return []Entry{entry}, nil } +// readAsTarget reports whether dispatchPackageLine reads args, the requirement +// text of a package line, as a bare target (VCS, URL, archive or local path), +// and which Kind it is. If not, args is a PEP 508 requirement. +// +// The first token decides whether args is a VCS reference or a URL. Otherwise +// only the text before the first ";" counts, because pip's +// parse_req_from_line removes the marker there first. So +// `foo.tar.gz;os_name=="x"` is an archive, and `foo;os_name=="a/b"` is not a +// path. A URL keeps its ";", because pip removes the marker of a URL only at +// "; ". +// +// The text is a local path when: +// - its first token contains "/" or is ".", or +// - the whole text, without non-empty extras at its end, has an archive +// extension, as in pip's _get_url_from_path. So "foo.whl" and +// "foo.whl[x]" are archives, but "foo.whl[]", "foo.whl [x]" and +// "foo.whl >=1" are names. +// +// Either way, a "name @ url" requirement is not a path (see +// isNamedURLRequirement). +func readAsTarget(args string) (Kind, bool) { + first := firstField(args) + if first == "" { + return 0, false + } + if kind, ok := classifyURL(first); ok { + return kind, true + } + firstWithoutMarker, _, _ := strings.Cut(first, ";") + if firstWithoutMarker == "" { + return 0, false + } + withoutMarker, _, _ := strings.Cut(args, ";") + withoutMarker = strings.TrimFunc(withoutMarker, isPythonSpace) + isPath := looksLikePath(firstWithoutMarker) || hasArchiveExtension(stripExtras(withoutMarker)) + if !isPath || isNamedURLRequirement(args) { + return 0, false + } + return KindLocalPath, true +} + +// firstField returns the first field of s, as strings.Fields(s)[0] does, or "" +// if s has no field. Unlike strings.Fields, it does not split the rest of s. +func firstField(s string) string { + s = strings.TrimLeftFunc(s, unicode.IsSpace) + if i := strings.IndexFunc(s, unicode.IsSpace); i >= 0 { + return s[:i] + } + return s +} + +// isNamedURLRequirement reports whether args, which looks like a local path or +// archive, is a "name @ url" requirement instead. It follows pip's +// _get_url_from_path: the text before "@" must not look like a path. +// +// pip's parse_req_from_line removes the marker at the first ";" before it +// calls _get_url_from_path, so an "@" in the marker does not count. For +// example, `foo.tar.gz ; os_name == "a@b"` is an archive with a marker. +func isNamedURLRequirement(args string) bool { + withoutMarker, _, _ := strings.Cut(args, ";") + before, _, found := strings.Cut(withoutMarker, "@") + if !found { + return false + } + before = strings.TrimSpace(before) + return !strings.Contains(before, "/") && !strings.HasPrefix(before, ".") +} + // breakArgsOptions splits a package/requirement logical line into its // requirement text ("args") and its per-line options tail ("options"), -// per pip's break_args_options (pip/_internal/req/req_file.py): pip -// plain-splits the line on whitespace and takes every leading token that -// doesn't start with "-" as part of the requirement, stopping at the -// first token that does - everything from there on is the options tail. -// Both halves are returned re-joined with single spaces (not the -// original, possibly irregular, whitespace), matching pip's -// ' '.join(...) of each half. +// per pip's break_args_options (pip/_internal/req/req_file.py): every +// leading token that doesn't start with "-" is part of the requirement, +// and everything from the first token that does is the options tail. +// +// Each half keeps its original text, as pip's split(" ") and " ".join() +// do, so whitespace inside a quoted marker literal is not changed. Unlike +// pip, any whitespace (not only a space) separates the tokens. func breakArgsOptions(line string) (args string, options string) { - fields := strings.Fields(line) - - i := 0 - for ; i < len(fields); i++ { - if strings.HasPrefix(fields[i], "-") { - break + inToken := false + for i, r := range line { + switch { + case unicode.IsSpace(r): + inToken = false + case !inToken && r == '-': + return strings.TrimRightFunc(line[:i], unicode.IsSpace), line[i:] + default: + inToken = true } } - - return strings.Join(fields[:i], " "), strings.Join(fields[i:], " ") + return line, "" } // attachReqOptions consumes every token in tokens as a per-requirement // option (pip's SUPPORTED_OPTIONS_REQ), appending to *hashes or *options // as appropriate. Unlike dispatchFileOption, this never leaves tokens for // a separate entry: every token on a requirement/editable line's tail -// belongs to that one requirement. +// belongs to that one requirement. A token that is only "--" ends the +// options, and the tokens after it are ignored, as in pip. func attachReqOptions(hashes *[]Hash, options *[]OptionEntry, tokens []string, lineNum int) error { i := 0 for i < len(tokens) { tok := tokens[i] - if !strings.HasPrefix(tok, "-") { - return lineError(lineNum, "unexpected token %q (expected a per-requirement option)", tok) + if tok == "--" { + // optparse reads "--" as the end of the options, so pip ignores + // the rest of the line. + return nil + } + if len(*hashes)+len(*options) == maxLineOptions { + return lineOptionsOverLimit(lineNum) + } + // pip ignores a token that is not an option, such as a lone "-". + // This package rejects it, because it is often a mistake, such as a + // marker written after the options. + if !isOptionToken(tok) { + return lineError(lineNum, "unexpected token %s (expected a per-requirement option)", errtext.Quote(tok)) } - name, eqValue, hasEq := splitFlagValue(tok) + // pip reads the options of a requirement line with the same parser + // as an option line, so "-rfile.txt" is "-r" with a value here too. + name, eqValue, hasEq := splitOptionToken(tok) + name, err := resolveLongOption(name, lineNum) + if err != nil { + return err + } i++ var value string switch { case hasEq: value = eqValue - case name == "--hash" || perLineValueOptions[name]: + case name == "--hash" || optionTakesValue(name): + // A file-level option, such as "--index-url", takes the next + // token as its value, as in pip. pip then ignores the option, + // because the line is a requirement, but this package keeps it, + // the same as "--index-url=x". So "-e ./a -e ./b" keeps the + // second "-e" as an option of the first editable requirement. if i >= len(tokens) { return lineError(lineNum, "%s requires a value", name) } @@ -478,6 +650,12 @@ func attachReqOptions(hashes *[]Hash, options *[]OptionEntry, tokens []string, l return nil } +// lineOptionsOverLimit returns the error for a line with more than +// maxLineOptions options. +func lineOptionsOverLimit(lineNum int) error { + return lineError(lineNum, "the line has more than %d options", maxLineOptions) +} + // parseHash parses a "--hash" value ("algorithm:digest") into a Hash, // splitting on the first ':' only (a digest can't itself contain a // leading algorithm-style prefix, but be conservative and only split @@ -485,11 +663,120 @@ func attachReqOptions(hashes *[]Hash, options *[]OptionEntry, tokens []string, l func parseHash(raw string, lineNum int) (Hash, error) { algo, digest, ok := strings.Cut(raw, ":") if !ok { - return Hash{}, lineError(lineNum, "malformed --hash value %q: expected \"algorithm:digest\"", raw) + return Hash{}, lineError(lineNum, "malformed --hash value %s: expected \"algorithm:digest\"", errtext.Quote(raw)) } return Hash{Algorithm: algo, Digest: digest}, nil } +// includeAndEditableOptions are the options of pip's SUPPORTED_OPTIONS that +// take a value and that knownOptions does not list, because dispatchOption +// handles them before it looks in knownOptions. +var includeAndEditableOptions = map[string]bool{ + "-r": true, "--requirement": true, + "-c": true, "--constraint": true, + "-e": true, "--editable": true, +} + +// optionTakesValue reports whether pip's option name takes a value: a known +// file-level option with arity 1, an include or editable option, or a +// per-requirement value option. name is the name as dispatchFileOption and +// attachReqOptions store it in OptionEntry.Name. +func optionTakesValue(name string) bool { + if spec, ok := knownOptions[name]; ok { + return spec.arity == 1 + } + return includeAndEditableOptions[name] || perLineValueOptions[name] +} + +// longOptionNames are the long options of pip's SUPPORTED_OPTIONS and +// SUPPORTED_OPTIONS_REQ, in sorted order. A prefix resolves only to one of +// these names. The list follows current pip (checked against pip's main +// branch, 27.0.dev0, in December 2026), not pip 21.2.4, which other parity +// tests use. The two differ here: current pip added --no-require-hashes, +// --all-releases, --only-final and --config-settings, and removed +// --global-option and --install-option. So "--glob" is an unknown option +// here, but pip 21.2.4 reads it as --global-option. This package still reads +// --global-option and --install-option when they are written in full. +var longOptionNames = func() []string { + names := []string{"--requirement", "--constraint", "--editable", "--hash", "--config-settings"} + for name := range knownOptions { + if strings.HasPrefix(name, "--") { + names = append(names, name) + } + } + slices.Sort(names) + return names +}() + +// resolveLongOption returns the full name of the long option name. pip reads +// an option line with Python's optparse, which accepts a unique prefix of a +// long option, so "--ind" is "--index-url". A name that is not a prefix of a +// known option is returned unchanged, as an unknown option. A prefix of two or +// more known options is an error, as in pip. The callers handle a token that +// is only "--", which ends the options. So name is "--" only for a token such +// as "--=x", and it is a prefix of every long option, as in optparse. +func resolveLongOption(name string, lineNum int) (string, error) { + if !strings.HasPrefix(name, "--") || slices.Contains(longOptionNames, name) { + return name, nil + } + var matches []string + for _, full := range longOptionNames { + if strings.HasPrefix(full, name) { + matches = append(matches, full) + } + } + switch len(matches) { + case 0: + return name, nil + case 1: + return matches[0], nil + default: + return "", lineError(lineNum, "ambiguous option %s: it matches %s", name, strings.Join(matches, ", ")) + } +} + +// shortValueOptions are the short options of an option line that take a +// value. These are the short options in pip's SUPPORTED_OPTIONS. +var shortValueOptions = map[string]bool{"-r": true, "-c": true, "-e": true, "-i": true, "-f": true} + +// splitOptionToken splits the first token of an option, tok, into the option +// name and its inline value. pip reads an option line with Python's optparse, +// which reads "-rother.txt" as "-r" with the value "other.txt". So a short +// option from shortValueOptions takes the rest of tok as its value, also when +// the rest has a "=", as in "-rfoo=bar.txt". +// +// Other tokens go to splitFlagValue. A short option followed by "=" is +// different from pip: optparse reads "-r=other.txt" as the path +// "=other.txt", but this package reads it as "other.txt", the same as +// "--requirement=other.txt". +func splitOptionToken(tok string) (name, value string, hasValue bool) { + if len(tok) > 2 && shortValueOptions[tok[:2]] && tok[2] != '=' { + return tok[:2], tok[2:], true + } + return splitReqOptionToken(tok) +} + +// shortReqOptions maps each short option in pip's SUPPORTED_OPTIONS_REQ to +// its long name. +var shortReqOptions = map[string]string{"-C": "--config-settings"} + +// splitReqOptionToken splits tok, a per-requirement option, into the option +// name and its inline value. A short option from shortReqOptions gives its +// long name, and takes the rest of tok as its value, as in "-Cx=y". As with +// splitOptionToken, "-C=x" gives the value "x", but optparse gives "=x". +func splitReqOptionToken(tok string) (name, value string, hasValue bool) { + if len(tok) > 2 && tok[2] != '=' { + if long, ok := shortReqOptions[tok[:2]]; ok { + return long, tok[2:], true + } + } + name, value, hasValue = splitFlagValue(tok) + if long, ok := shortReqOptions[name]; ok { + name = long + } + return name, value, hasValue +} + // splitFlagValue splits tok on its first '=', if any, into a flag name // and inline value (e.g. "--index-url=https://x" -> "--index-url", // "https://x", true). A token with no '=' returns (tok, "", false). diff --git a/reqtxt/parse_limits_test.go b/reqtxt/parse_limits_test.go new file mode 100644 index 0000000..77f0daa --- /dev/null +++ b/reqtxt/parse_limits_test.go @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "runtime" + "strings" + "testing" + + "github.com/posit-dev/go-python-packaging/internal/race" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// A File from Parse may have at most maxParseEntries entries. Every kind of +// entry counts, includes too. +func TestParse_EntryLimit(t *testing.T) { + tests := []struct { + name string + content string + opts []ParseOption + wantEntries int + wantErr string + }{ + {name: "requirements at the limit", content: strings.Repeat("a\n", maxParseEntries), wantEntries: maxParseEntries}, + { + name: "requirements one over the limit", + content: strings.Repeat("a\n", maxParseEntries+1), + wantErr: "line 100001: the file has more than 100000 entries", + }, + { + name: "includes count", + content: strings.Repeat("a\n", maxParseEntries) + "-r x.txt\n", + wantErr: "line 100001: the file has more than 100000 entries", + }, + { + name: "option lines count", + content: strings.Repeat("--pre\n", maxParseEntries+1), + wantErr: "line 100001: the file has more than 100000 entries", + }, + { + // Comments and blank lines are not entries. The error gives the + // physical line. + name: "comments do not count", + content: "# comment\n\n" + strings.Repeat("a\n", maxParseEntries+1), + wantErr: "line 100003: the file has more than 100000 entries", + }, + { + name: "with WithEnv", + content: strings.Repeat("${A}\n", maxParseEntries+1), + opts: []ParseOption{WithEnv(func(string) (string, bool) { return "a", true })}, + wantErr: "line 100001: the file has more than 100000 entries", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.content, tt.opts...) + if tt.wantErr != "" { + require.Error(t, err) + assert.ErrorIs(t, err, ErrInvalidRequirementsFile) + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + assert.Len(t, f.Entries, tt.wantEntries) + }) + } +} + +// Parse stops at the entry limit, so a large file costs about as much as the +// limit, not as much as the file. Found by review: 8 MiB of "a\n" allocated +// 2.2 GB, with no limit. +func TestParse_LargeFileStopsAtEntryLimit(t *testing.T) { + if race.Enabled { + t.Skip("the race detector adds allocations") + } + content := strings.Repeat("a\n", 4_000_000) + + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + _, err := Parse(content) + runtime.ReadMemStats(&after) + + require.Error(t, err) + assert.Contains(t, err.Error(), "the file has more than 100000 entries") + // Parse of 100,000 requirements allocates about 55 MB. + assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(200<<20), "bytes allocated") +} diff --git a/reqtxt/parse_test.go b/reqtxt/parse_test.go index 9b89f48..fe5ca7a 100644 --- a/reqtxt/parse_test.go +++ b/reqtxt/parse_test.go @@ -182,26 +182,123 @@ func TestParse_FileOptions(t *testing.T) { } } +// An option that is not in knownOptions gives an OptionEntry with the name as +// written. pip fails on an unknown option, but this package keeps it, so that a +// caller can see it. Only "--name=value" gives a value: a bare unknown option +// does not take the next token. func TestParse_UnknownFlag(t *testing.T) { - f, err := Parse("--frobnicate=1") - require.NoError(t, err) - require.Len(t, f.Entries, 1) + line1 := Source{Line: 1} + opt := func(name, value string) *OptionEntry { + return &OptionEntry{Name: name, Value: value, Source: line1} + } - oe, ok := f.Entries[0].(*OptionEntry) - require.True(t, ok, "want *OptionEntry, got %T", f.Entries[0]) - assert.Equal(t, OptionEntry{Name: "--frobnicate", Value: "1", Source: Source{Line: 1}}, *oe) + tests := []struct { + name string + input string + want []Entry + }{ + // The value. + {name: "value after equals", input: "--frobnicate=1", want: []Entry{opt("--frobnicate", "1")}}, + {name: "no value", input: "--frob", want: []Entry{opt("--frob", "")}}, + {name: "empty value after equals", input: "--frob=", want: []Entry{opt("--frob", "")}}, + { + // Only the first "=" splits the name from the value. + name: "value with an equals sign", + input: "--frob=a=b", + want: []Entry{opt("--frob", "a=b")}, + }, + {name: "quoted value with a space", input: "--frob='a b'", want: []Entry{opt("--frob", "a b")}}, + {name: "quoted value with a hash", input: `--frob="a#b"`, want: []Entry{opt("--frob", "a#b")}}, + { + // Parse expands variables only with WithEnv. + name: "value with a variable", + input: "--frob=${HOME}", + want: []Entry{opt("--frob", "${HOME}")}, + }, - f, err = Parse("--frob foo") - require.NoError(t, err) - require.Len(t, f.Entries, 2) + // The tokens after the option. + { + // pip ignores a token after the options on an option line, so + // "foo" gives no entry. + name: "requirement after the option", + input: "--frob foo", + want: []Entry{opt("--frob", "")}, + }, + { + // The quoted token is not the value of the option. + name: "quoted token after the option", + input: "--frob 'a b'", + want: []Entry{opt("--frob", "")}, + }, + {name: "known option after the option", input: "--frob --pre", want: []Entry{opt("--frob", ""), opt("--pre", "")}}, + { + name: "token, then a known option", + input: "--frob foo --pre", + want: []Entry{opt("--frob", ""), opt("--pre", "")}, + }, + {name: "value, then a known option", input: "--frob=1 --pre", want: []Entry{opt("--frob", "1"), opt("--pre", "")}}, + {name: "same option two times", input: "--frob=1 --frob=2", want: []Entry{opt("--frob", "1"), opt("--frob", "2")}}, + { + // pip ignores the other options of a line with -r (see + // TestParse_OptionLineKind). + name: "include after the option", + input: "--frob -r other.txt", + want: []Entry{&IncludeEntry{Path: "other.txt", Source: line1}}, + }, + { + // The editable requirement takes the rest of the line as its own + // options. pip ignores the other options of a line with -e (see + // TestParse_OptionLineKind). + name: "editable requirement after the option", + input: "--frob -e ./pkg --pre", + want: []Entry{ + &UnnamedEntry{ + Raw: "./pkg", + Kind: KindLocalPath, + Editable: true, + Options: []OptionEntry{{Name: "--pre", Source: line1}}, + Source: line1, + }, + }, + }, - oe, ok = f.Entries[0].(*OptionEntry) - require.True(t, ok, "entry 0: want *OptionEntry, got %T", f.Entries[0]) - assert.Equal(t, OptionEntry{Name: "--frob", Value: "", Source: Source{Line: 1}}, *oe) + // The name is kept as written. + {name: "short option", input: "-x", want: []Entry{opt("-x", "")}}, + { + // Only -r, -c, -e, -i and -f take the rest of the token as a value. + name: "short option with text after it", + input: "-xfoo", + want: []Entry{opt("-xfoo", "")}, + }, + {name: "short option with equals", input: "-x=1", want: []Entry{opt("-x", "1")}}, + // optparse reads a lone "-" as an argument, not an option, so pip + // ignores it. + {name: "one dash", input: "-", want: nil}, + {name: "one dash then a word", input: "- foo", want: nil}, + {name: "three dashes", input: "---frob", want: []Entry{opt("---frob", "")}}, + {name: "upper case is kept", input: "--Frob", want: []Entry{opt("--Frob", "")}}, + + // The file text around the option. + {name: "comment after the option", input: "--frob=1 # comment", want: []Entry{opt("--frob", "1")}}, + { + name: "option on line 2", + input: "--pre\n--frob=1", + want: []Entry{opt("--pre", ""), &OptionEntry{Name: "--frob", Value: "1", Source: Source{Line: 2}}}, + }, + } - re, ok := f.Entries[1].(*RequirementEntry) - require.True(t, ok, "entry 1: want *RequirementEntry, got %T", f.Entries[1]) - assert.Equal(t, "foo", re.Requirement.Name) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + require.NoError(t, err) + assert.Equal(t, tt.want, f.Entries) + + // The line numbers can change, so compare entryValues. + again, err := Parse(f.String()) + require.NoError(t, err, "String() output parses again") + assert.Equal(t, entryValues(f), entryValues(again), "same values after a round trip") + }) + } } func TestParse_Hashes(t *testing.T) { @@ -309,6 +406,68 @@ func TestParse_Env(t *testing.T) { assert.Equal(t, "https://${TOKEN}@h/s", oe.Value) } +// A line is trimmed before "${NAME}" expansion, so a value can add whitespace +// at the start or end of a requirement line. pip strips the requirement text +// (name.strip() in parse_req_from_line), so the whitespace is not part of the +// entry. Checked with pip 21.2.4. Found by FuzzParseWithEnv. +func TestParse_EnvValueWhitespace(t *testing.T) { + tests := []struct { + name string + value string // the value of A, in the line "${A}" + want []string + }{ + { + name: "space after a directory", + value: ". ", + want: []string{"unnamed ."}, + }, + { + name: "space before a path", + value: " ./pkg", + want: []string{"unnamed ./pkg"}, + }, + { + name: "tab after a path", + value: "./pkg\t", + want: []string{"unnamed ./pkg"}, + }, + { + // U+001F is Python whitespace (see isPythonSpace). + name: "unit separator after a path", + value: "./pkg\x1f", + want: []string{"unnamed ./pkg"}, + }, + { + name: "space after a requirement", + value: "foo==1.0 ", + want: []string{"requirement foo==1.0 hashes "}, + }, + { + name: "space before a requirement", + value: " foo", + want: []string{"requirement foo hashes "}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + lookup := func(name string) (string, bool) { + if name == "A" { + return tt.value, true + } + return "", false + } + f, err := Parse("${A}", WithEnv(lookup)) + require.NoError(t, err) + assert.Equal(t, tt.want, entryValues(f)) + + again, err := Parse(f.String()) + require.NoError(t, err, "String() output parses again: %q", f.String()) + assert.Equal(t, tt.want, entryValues(again), "same entries after a round trip") + }) + } +} + func TestParse_ErrorLineNumber(t *testing.T) { // Line 1 is a comment, line 2 is blank, so the bad requirement is the // logical line whose *physical* line number is 3. diff --git a/reqtxt/preprocess.go b/reqtxt/preprocess.go index b183eb6..629e92b 100644 --- a/reqtxt/preprocess.go +++ b/reqtxt/preprocess.go @@ -12,16 +12,26 @@ package reqtxt import ( + "errors" + "fmt" "regexp" "strings" - "unicode" "unicode/utf8" + + "github.com/posit-dev/go-python-packaging/internal/pyspace" ) +// isPythonSpace reports whether r is whitespace for Python's str.isspace(), +// str.strip() and the "\s" of package re (see package pyspace). pip uses this +// whitespace to find comments and to trim a line. +func isPythonSpace(r rune) bool { + return pyspace.IsSpace(r) +} + // commentStartIndex returns the byte index of the '#' that begins a // comment in s, matching pip's COMMENT_RE (pip/_internal/req/req_file.py): // "(^|\s+)#.*$". A '#' at the start of s, or immediately preceded by a -// rune for which unicode.IsSpace reports true, begins a comment that runs +// rune for which isPythonSpace reports true, begins a comment that runs // to the end of s. A '#' that is not whitespace-preceded (e.g. the // fragment in "git+https://h/p#egg=name") is left alone. It returns -1 if // s contains no comment-starting '#'. @@ -40,7 +50,7 @@ func commentStartIndex(s string) int { return i } prev, _ := utf8.DecodeLastRuneInString(s[:i]) - if unicode.IsSpace(prev) { + if isPythonSpace(prev) { return i } } @@ -66,6 +76,47 @@ type parseConfig struct { // path is recorded on every entry's Source. Empty unless WithPath was // given; Flatten supplies it per included file. path string + // flatten, when hasFlattenLimits is set, replaces the entry limit of Parse + // (maxParseEntries) with the limits of a Flatten call. Only Flatten sets + // it (see withFlattenLimits). + flatten flattenLimits + hasFlattenLimits bool +} + +// flattenLimits are the limits that Flatten gives Parse for one file. Over a +// limit, Parse stops and returns errTooManyEntries or errTooManyIncludes, and +// Flatten replaces that with its own error. So a large file stops at the limit +// before Parse reads all of it. +type flattenLimits struct { + // entries is the most entries other than IncludeEntry. + entries int + // includes is the most IncludeEntry values. Flatten follows each one, so + // a file with more is over the file limit of Flatten. + includes int + // envBudget is the most bytes that ${NAME} expansion may add to the file, + // in place of maxEnvExpansion. + envBudget int +} + +// errTooManyEntries and errTooManyIncludes are returned by Parse when a file +// goes over its flattenLimits. +var ( + errTooManyEntries = errors.New("too many entries") + errTooManyIncludes = errors.New("too many includes") +) + +// errEnvExpansion is returned by expandEnv when the expansion adds more bytes +// than its maxGrowth. Parse wraps it in an error that gives the limit. +var errEnvExpansion = errors.New("expanding environment variables adds too many bytes") + +// withFlattenLimits makes Parse use limits in place of maxParseEntries and +// maxEnvExpansion. It is not exported: only Flatten uses these limits, and it +// sets them in a parseConfig itself. Tests use this option. +func withFlattenLimits(limits flattenLimits) ParseOption { + return func(cfg *parseConfig) { + cfg.flatten = limits + cfg.hasFlattenLimits = true + } } // WithPath records path on the Source of every entry Parse produces. Parse takes @@ -83,7 +134,11 @@ func WithPath(path string) ParseOption { // (NAME matching [A-Z0-9_]+) is ever expanded; a variable that lookup // reports as unset, or that resolves to the empty string, is also left // literal - matching pip's expand_env_variables behavior. Expansion is -// applied to the whole assembled logical line, before tokenization. +// applied to the whole assembled logical line, before tokenization. It may +// add at most 16 MiB to one file (see maxEnvExpansion). A value may hold a +// line break, as in pip, but a value that joins its bytes with the bytes next +// to it into a line break, as "\xc2" before "\x85" does, is an error (see +// countMultiByteLineBreaks). func WithEnv(lookup func(string) (string, bool)) ParseOption { return func(cfg *parseConfig) { cfg.env = lookup @@ -107,9 +162,10 @@ type logicalLine struct { // preprocess turns raw requirements-file content into an ordered slice of // logicalLine values, following pip's req_file.preprocess pipeline: // -// 1. Normalize line endings ("\r\n" and lone "\r" both become "\n"), +// 1. Normalize line endings: every line break that Python's +// str.splitlines() knows becomes "\n" (see normalizeLineEndings), // before anything else, so continuation joining and physical-line -// counting are CRLF-safe. +// counting match pip. // 2. Join backslash continuations: a physical line ending in "\" // concatenates directly to the next physical line, with NO separator // inserted (the trailing "\" is simply removed). The joined logical @@ -129,93 +185,351 @@ type logicalLine struct { // 5. Trim remaining surrounding whitespace. // 6. If cfg.env is set, expand "${NAME}" references (see WithEnv). // -// The returned error exists for signature stability with future callers; -// preprocess itself has no failure mode today. +// preprocess returns an error only when the expansion in step 6 goes over a +// limit (see expandEnv). func preprocess(content string, cfg parseConfig) ([]logicalLine, error) { + var lines []logicalLine + _, err := eachLogicalLine(content, cfg, func(ll logicalLine) error { + lines = append(lines, ll) + return nil + }) + if err != nil { + return nil, err + } + return lines, nil +} + +// eachLogicalLine is preprocess, but it calls yield for each logical line, in +// order, and does not keep the lines. If yield returns an error, +// eachLogicalLine stops and returns that error. So Parse can stop in the +// middle of a large file, before it reads the rest. It also returns the number +// of bytes that ${NAME} expansion added to the file. +func eachLogicalLine(content string, cfg parseConfig, yield func(logicalLine) error) (int, error) { normalized := normalizeLineEndings(content) - physicalLines := strings.Split(normalized, "\n") - var lines []logicalLine var ( joined strings.Builder joinedLine int joining bool + // continued is true when the logical line has more than one + // physical line. + continued bool ) + // envBudget is the number of bytes that ${NAME} expansion may still add to + // the file, and envGrowth is the number that it added. + envBudget := maxEnvExpansion + if cfg.hasFlattenLimits { + envBudget = cfg.flatten.envBudget + } + envGrowth := 0 + + var err error flush := func() { - if !joining { + if !joining || err != nil { return } joining = false text := joined.String() + // normalized has no multi-byte line break, so a line break here was + // made by joining the bytes at the end of one physical line with + // the bytes at the start of the next. pip decodes the file before + // it joins lines, so it never does this (see countMultiByteLineBreaks). + if continued && countMultiByteLineBreaks(text) > 0 { + err = lineError(joinedLine, "a backslash continuation joins bytes into a line break") + return + } if i := commentStartIndex(text); i >= 0 { text = text[:i] } - text = strings.TrimSpace(text) + // pip trims the line with Python's str.strip(). + text = strings.TrimFunc(text, isPythonSpace) if text == "" { return } if cfg.env != nil { - text = expandEnv(text, cfg.env) + expanded, expandErr := expandEnv(text, cfg.env, envBudget) + if errors.Is(expandErr, errEnvExpansion) { + err = lineError(joinedLine, "%w: the file would grow by more than %d bytes", expandErr, maxEnvExpansion) + return + } + if expandErr != nil { + err = lineError(joinedLine, "%w", expandErr) + return + } + envBudget -= len(expanded) - len(text) + envGrowth += len(expanded) - len(text) + text = expanded } - lines = append(lines, logicalLine{text: text, line: joinedLine}) + err = yield(logicalLine{text: text, line: joinedLine}) } - for i, physical := range physicalLines { - physicalLineNum := i + 1 + physicalLineNum := 0 + for physical := range strings.SplitSeq(normalized, "\n") { + physicalLineNum++ if !joining { joining = true joinedLine = physicalLineNum joined.Reset() + continued = false } if rest, ok := strings.CutSuffix(physical, `\`); ok && !isWholeLineComment(physical) { joined.WriteString(rest) + continued = true continue } joined.WriteString(physical) flush() + if err != nil { + return envGrowth, err + } } // A trailing continuation with no following physical line still // needs to be flushed (there's no next segment to join to). flush() - - return lines, nil + return envGrowth, err } // isWholeLineComment reports whether physical is a whole-line comment: its -// first non-whitespace (per unicode.IsSpace) character is "#". This is +// first non-whitespace (per isPythonSpace) character is "#". This is // pip's join_lines guard (COMMENT_RE.match(line), req_file.py:501) // restated for our purposes: an INLINE comment (preceded by non-whitespace // content, e.g. "django # c") does not match here and is not a whole-line // comment, even though commentStartIndex would still strip it later. func isWholeLineComment(physical string) bool { - return strings.HasPrefix(strings.TrimLeftFunc(physical, unicode.IsSpace), "#") + return strings.HasPrefix(strings.TrimLeftFunc(physical, isPythonSpace), "#") } -// normalizeLineEndings converts "\r\n" and lone "\r" to "\n", matching -// Python's universal-newlines splitlines() behavior that pip's preprocess -// relies on. +// lineBreaks converts every line break that Python's str.splitlines() knows +// to "\n". pip splits a requirements file with splitlines(), so "\v", "\f", +// U+0085, U+2028 and the others end a line there too. "\r\n" is listed first +// so that it becomes one line break, not two. +var lineBreaks = strings.NewReplacer( + "\r\n", "\n", + "\r", "\n", + "\v", "\n", + "\f", "\n", + "\x1c", "\n", + "\x1d", "\n", + "\x1e", "\n", + "\u0085", "\n", + "\u2028", "\n", + "\u2029", "\n", +) + +// normalizeLineEndings converts each line break in content to "\n" (see +// lineBreaks). Most files use only "\n", and lineBreaks.Replace copies the +// whole file even when it replaces nothing, so it runs only when needed. func normalizeLineEndings(content string) string { - content = strings.ReplaceAll(content, "\r\n", "\n") - return strings.ReplaceAll(content, "\r", "\n") -} - -// expandEnv replaces every "${NAME}" reference in text (NAME matching -// [A-Z0-9_]+) with the value lookup(NAME) returns, unless lookup reports -// the variable as unset or reports an empty value - in either case the -// literal "${NAME}" is left in place, matching pip's -// expand_env_variables. -func expandEnv(text string, lookup func(string) (string, bool)) string { - return envVarRE.ReplaceAllStringFunc(text, func(match string) string { - name := envVarRE.FindStringSubmatch(match)[1] - value, ok := lookup(name) - if !ok || value == "" { - return match - } - return value - }) + if !hasReplaceableLineBreak(content) { + return content + } + return lineBreaks.Replace(content) +} + +// hasReplaceableLineBreak reports whether s holds the bytes of a pattern of +// lineBreaks. It checks bytes, not runes, as lineBreaks does, so the two agree +// also on text that is not valid UTF-8. +func hasReplaceableLineBreak(s string) bool { + for i := 0; i < len(s); i++ { + switch c := s[i]; { + case c == '\r', c == '\v', c == '\f', c >= 0x1c && c <= 0x1e: + return true + case c == 0xc2 && i+1 < len(s) && s[i+1] == 0x85: // U+0085 + return true + case c == 0xe2 && i+2 < len(s) && s[i+1] == 0x80 && (s[i+2] == 0xa8 || s[i+2] == 0xa9): // U+2028, U+2029 + return true + } + } + return false +} + +// countMultiByteLineBreaks returns the number of U+0085, U+2028 and U+2029 in +// s. These are the line breaks of lineBreaks that have more than one byte. +// +// Parse reads the file as bytes, so it can join the bytes at the end of one +// piece of text with the bytes at the start of the next. If the pieces are not +// valid UTF-8, as "\xc2" and "\x85", the join can make one of these line +// breaks. pip decodes the file first, so it never joins bytes, and no file +// gives pip a line break inside a line. Also no file can write one, so a line +// break that a join makes cannot read back from File.String(). So Parse +// returns an error for it, where a backslash continuation (eachLogicalLine), +// a ${NAME} value (expandEnv) or quotes and backslashes (shlexSplit) join +// bytes. A one-byte line break, such as "\n", cannot be made by a join. +func countMultiByteLineBreaks(s string) int { + return strings.Count(s, "\u0085") + strings.Count(s, "\u2028") + strings.Count(s, "\u2029") +} + +// errEnvLineBreak is returned by expandEnv when a value joins bytes with the +// text next to it into a line break (see countMultiByteLineBreaks). +var errEnvLineBreak = errors.New("an environment variable value joins bytes with the text next to it into a line break") + +// expandEnv replaces each "${NAME}" reference in text (NAME matches +// [A-Z0-9_]+) with lookup(NAME), as pip's expand_env_variables does. A +// reference to an unset or empty variable stays as it is. +// +// pip replaces all copies of each reference in turn, so it also replaces a +// reference that a value adds: with NESTED="${TOKEN}" and TOKEN="t", +// "${NESTED} ${TOKEN}" gives "t t". That order is quadratic, so expandEnv +// first replaces all references in one pass. The results differ only when a +// reference in that result overlaps a value, and only then does expandEnv +// use pip's order. If pip's order goes over maxOrderedEnvRefs, maxEnvGrowth, +// or maxOrderedEnvWork, expandEnv returns an error. If the result would be +// more than maxGrowth bytes longer than text, expandEnv returns +// errEnvExpansion before it builds the result. +func expandEnv(text string, lookupFn func(string) (string, bool), maxGrowth int) (string, error) { + matches := envVarRE.FindAllStringSubmatchIndex(text, -1) + if len(matches) == 0 { + return text, nil + } + + // value returns the value of the variable name, or "" when it is unset + // or empty. pip leaves the reference unchanged in both cases. + values := make(map[string]string) + value := func(name string) string { + v, ok := values[name] + if !ok { + v, _ = lookupFn(name) + values[name] = v + } + return v + } + + // Check the length of the one-pass result before it is built, so that a + // line over maxGrowth does not allocate first. + growth := 0 + for _, m := range matches { + if v := value(text[m[2]:m[3]]); v != "" { + growth += len(v) - (m[1] - m[0]) + } + } + if growth > maxGrowth { + return "", errEnvExpansion + } + + var b strings.Builder + b.Grow(len(text) + max(growth, 0)) + var inserted [][2]int // the start and end of each value in the result + last := 0 + for _, m := range matches { + b.WriteString(text[last:m[0]]) + last = m[1] + v := value(text[m[2]:m[3]]) + if v == "" { + b.WriteString(text[m[0]:m[1]]) + continue + } + inserted = append(inserted, [2]int{b.Len(), b.Len() + len(v)}) + b.WriteString(v) + } + b.WriteString(text[last:]) + out := b.String() + + if !refOverlapsInserted(out, inserted) { + // The references are ASCII, so replacing them keeps each line break + // of text. So each line break of out is one of text, or is inside a + // value, or a join made it. + if n := countMultiByteLineBreaks(out); n > 0 { + n -= countMultiByteLineBreaks(text) + for _, r := range inserted { + n -= countMultiByteLineBreaks(out[r[0]:r[1]]) + } + if n > 0 { + return "", errEnvLineBreak + } + } + return out, nil + } + return expandEnvInOrder(text, matches, value, len(out), maxGrowth) +} + +// Limits for expandEnvInOrder. A real line has a few references and does not +// need pip's order, so it never reaches them. +const ( + // maxOrderedEnvRefs is the maximum number of references in a line that + // needs pip's order. Each reference is one pass over the line. + maxOrderedEnvRefs = 100 + // maxEnvGrowth is the most that pip's order can make the line longer than + // the one-pass result. A value that holds its own reference, such as + // D="${D}${D}", makes the line longer at each replace. + maxEnvGrowth = 1 << 20 + // maxOrderedEnvWork is the most bytes that pip's order reads in all its + // passes: the length of the line, added for each pass. Each pass reads the + // line and can copy it, so without this limit 100 references on a 16 MiB + // line allocated 1.6 GB. + maxOrderedEnvWork = 16 << 20 +) + +// maxEnvExpansion is the most bytes that ${NAME} expansion may add to one +// file, in all its lines. Without it, a 256 KB line of "${A}" with a 4 KB +// value made a 256 MB line. Flatten also counts the added bytes in +// maxIncludedBytes. +const maxEnvExpansion = 16 << 20 + +// refOverlapsInserted reports whether a reference in s overlaps one of the +// inserted ranges. Both lists are in order and do not overlap themselves. +func refOverlapsInserted(s string, inserted [][2]int) bool { + i := 0 + for _, r := range envVarRE.FindAllStringIndex(s, -1) { + for i < len(inserted) && inserted[i][1] <= r[0] { + i++ + } + if i < len(inserted) && inserted[i][0] < r[1] { + return true + } + } + return false +} + +// expandEnvInOrder replaces the references of text in pip's order (see +// expandEnv). matches are the references of text, and outLen is the length +// of the one-pass result. +func expandEnvInOrder(text string, matches [][]int, value func(string) string, outLen, maxGrowth int) (string, error) { + if len(matches) > maxOrderedEnvRefs { + return "", fmt.Errorf( + "an environment variable value makes a new ${NAME} reference, and the line has more than %d references", + maxOrderedEnvRefs) + } + original := text + limit := outLen + maxEnvGrowth + if len(original)+maxGrowth < limit { + // The line may grow by at most maxGrowth, also in pip's order. + limit = len(original) + maxGrowth + } + work := 0 + for _, m := range matches { + ref := original[m[0]:m[1]] + v := value(original[m[2]:m[3]]) + if v == "" { + continue + } + work += len(text) + if work > maxOrderedEnvWork { + return "", fmt.Errorf( + "an environment variable value makes a new ${NAME} reference, and the line is too long: "+ + "pip's order reads more than %d bytes", maxOrderedEnvWork) + } + // Check the new length first, so that the line cannot grow past the + // limit even for one replace. + n := strings.Count(text, ref) + if len(text)+n*(len(v)-len(ref)) > limit { + if limit == len(original)+maxGrowth { + return "", errEnvExpansion + } + return "", fmt.Errorf("expanding environment variables makes the line longer than %d bytes", limit) + } + // ref is ASCII, so it is not part of a line break of text, and + // replacing it keeps each one. So the replace adds the line breaks of + // each copy of v, and any more were made by a join. + before := countMultiByteLineBreaks(text) + text = strings.ReplaceAll(text, ref, v) + if countMultiByteLineBreaks(text) != before+n*countMultiByteLineBreaks(v) { + return "", errEnvLineBreak + } + } + return text, nil } diff --git a/reqtxt/preprocess_test.go b/reqtxt/preprocess_test.go index e1387f3..74dccb0 100644 --- a/reqtxt/preprocess_test.go +++ b/reqtxt/preprocess_test.go @@ -3,18 +3,29 @@ package reqtxt import ( + "errors" + "fmt" + "runtime" + "strconv" + "strings" "testing" + "github.com/posit-dev/go-python-packaging/internal/race" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestPreprocess_Continuations(t *testing.T) { - cases := []struct { +// preprocess turns the content of a file into logical lines, as pip's +// req_file.preprocess does: it joins backslash continuations, removes +// comments, drops blank lines, trims each line and keeps the line number of +// the first physical line. +func TestPreprocess(t *testing.T) { + tests := []struct { name string content string want []logicalLine }{ + // Continuations. { name: "no-space continuation joins with no separator", content: "foo==\\\n1.0", @@ -30,34 +41,13 @@ func TestPreprocess_Continuations(t *testing.T) { content: "foo==\\\r\n1.0", want: []logicalLine{{text: "foo==1.0", line: 1}}, }, - } - - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - got, err := preprocess(c.content, parseConfig{}) - require.NoError(t, err) - assert.Equal(t, c.want, got) - }) - } -} -// TestPreprocess_WholeLineCommentContinuationGuard exercises pip's -// join_lines guard (req_file.py:501): "if not line.endswith('\\') or -// COMMENT_RE.match(line)" - a physical line ending in "\" is NOT a -// continuation when it is itself a whole-line comment (COMMENT_RE matches -// at position 0, i.e. the first non-whitespace character is "#"). Without -// this guard, a trailing "\" on a comment line joins the next physical -// line directly onto the comment text, so by the time comments are -// stripped the entire logical line - including whatever followed the -// comment - is gone: e.g. "# TODO: pin this \" + "django" joins to -// "# TODO: pin this django", which commentRE then strips to nothing, -// silently discarding the "django" requirement pip would still install. -func TestPreprocess_WholeLineCommentContinuationGuard(t *testing.T) { - cases := []struct { - name string - content string - want []logicalLine - }{ + // pip's join_lines guard (req_file.py:501): "if not line.endswith('\\') + // or COMMENT_RE.match(line)". A physical line that ends in "\" is not a + // continuation when it is a whole-line comment, that is, when its first + // non-whitespace character is "#". Without this guard, the comment + // "# TODO: pin this \" joins the next line "django", and the comment is + // then removed with the "django" requirement that pip still installs. { name: "whole-line comment ending in backslash does not swallow the next line", content: "# TODO: pin this \\\ndjango", @@ -69,32 +59,25 @@ func TestPreprocess_WholeLineCommentContinuationGuard(t *testing.T) { want: []logicalLine{{text: "bar", line: 2}}, }, { - name: "regression: an ordinary continuation still joins", - content: "foo==\\\n1.0", - want: []logicalLine{{text: "foo==1.0", line: 1}}, + // Python's "\s" also matches a form feed and a vertical tab, but + // Go's RE2 "\s" does not. Both also end a line, as in pip, so + // "bar" is on line 3. + name: "form-feed-led whole-line comment ending in backslash does not swallow the next line", + content: "\f# c \\\nbar", + want: []logicalLine{{text: "bar", line: 3}}, + }, + { + name: "vertical-tab-led whole-line comment ending in backslash does not swallow the next line", + content: "\v# c \\\nbar", + want: []logicalLine{{text: "bar", line: 3}}, }, { name: "regression: an inline comment ending in backslash still joins (not a whole-line comment)", content: "django # c \\\nfoo", want: []logicalLine{{text: "django", line: 1}}, }, - } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - got, err := preprocess(c.content, parseConfig{}) - require.NoError(t, err) - assert.Equal(t, c.want, got) - }) - } -} - -func TestPreprocess_Comments(t *testing.T) { - cases := []struct { - name string - content string - want []logicalLine - }{ + // Comments. { name: "full-line comment is dropped entirely", content: "# a comment", @@ -112,61 +95,11 @@ func TestPreprocess_Comments(t *testing.T) { }, { name: "inline comment preceded by a non-breaking space is stripped", - content: "foo # a comment", + content: "foo\u00a0# a comment", want: []logicalLine{{text: "foo", line: 1}}, }, - } - - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - got, err := preprocess(c.content, parseConfig{}) - require.NoError(t, err) - assert.Equal(t, c.want, got) - }) - } -} - -// TestPreprocess_UnicodeWhitespaceWholeLineComment exercises the same -// join_lines guard as TestPreprocess_WholeLineCommentContinuationGuard, -// but with a whole-line comment led by Unicode (non-ASCII) whitespace - -// form feed and vertical tab - which Go's RE2 "\s" does not recognize but -// Python's (and thus pip's) "\s" does. Without Unicode-aware whole-line -// detection, the leading "#" would not be seen as starting at the first -// non-whitespace rune, the guard would not fire, and the trailing "\" -// would incorrectly join and swallow the next physical line. -func TestPreprocess_UnicodeWhitespaceWholeLineComment(t *testing.T) { - cases := []struct { - name string - content string - want []logicalLine - }{ - { - name: "form-feed-led whole-line comment ending in backslash does not swallow the next line", - content: "\f# c \\\nbar", - want: []logicalLine{{text: "bar", line: 2}}, - }, - { - name: "vertical-tab-led whole-line comment ending in backslash does not swallow the next line", - content: "\v# c \\\nbar", - want: []logicalLine{{text: "bar", line: 2}}, - }, - } - - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - got, err := preprocess(c.content, parseConfig{}) - require.NoError(t, err) - assert.Equal(t, c.want, got) - }) - } -} -func TestPreprocess_BlankLinesAndWhitespace(t *testing.T) { - cases := []struct { - name string - content string - want []logicalLine - }{ + // Blank lines and whitespace. { name: "blank lines are dropped", content: "foo\n\nbar", @@ -188,50 +121,56 @@ func TestPreprocess_BlankLinesAndWhitespace(t *testing.T) { content: " foo", want: []logicalLine{{text: "foo", line: 1}}, }, + + // Line numbers. + { + // Line 1 is a comment and line 2 is blank, so both are dropped. + name: "line number after dropped lines", + content: "# c\n\nfoo", + want: []logicalLine{{text: "foo", line: 3}}, + }, + { + // Lines 3 and 4 join, so the joined line has the number of line 3. + // The next line keeps its own number, 5. + name: "line numbers after a continuation join", + content: "# c\n\nfoo==\\\n1.0\nbar", + want: []logicalLine{ + {text: "foo==1.0", line: 3}, + {text: "bar", line: 5}, + }, + }, } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - got, err := preprocess(c.content, parseConfig{}) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := preprocess(tt.content, parseConfig{}) require.NoError(t, err) - assert.Equal(t, c.want, got) + assert.Equal(t, tt.want, got) }) } } -func TestPreprocess_LineNumbers(t *testing.T) { - // Line 1 is a comment (dropped), line 2 is blank (dropped), line 3 is - // the kept logical line. - content := "# c\n\nfoo" - got, err := preprocess(content, parseConfig{}) - require.NoError(t, err) - require.Len(t, got, 1) - assert.Equal(t, "foo", got[0].text) - assert.Equal(t, 3, got[0].line) -} - -func TestPreprocess_LineNumbers_AfterContinuationJoin(t *testing.T) { - // Line 1: comment (dropped). Line 2: blank (dropped). Lines 3-4: a - // continuation join whose first segment is physical line 3. Line 5: a - // trailing plain line, physical line 5. - content := "# c\n\nfoo==\\\n1.0\nbar" - got, err := preprocess(content, parseConfig{}) - require.NoError(t, err) - require.Len(t, got, 2) - assert.Equal(t, logicalLine{text: "foo==1.0", line: 3}, got[0]) - assert.Equal(t, logicalLine{text: "bar", line: 5}, got[1]) -} - +// preprocess expands "${NAME}" references after it joins lines and removes +// comments, as pip's expand_env_variables does. The expected values were +// checked with pip 21.2.4's req_file.preprocess, with the same environment. func TestPreprocess_Env(t *testing.T) { + env := map[string]string{ + "TOKEN": "t", + "EMPTY": "", + "USER_NAME": "u", + "MY_VAR_1": "v1", + "1ABC": "d", + "HASH": "a #b", + "PAD": " v ", + "NESTED": "${TOKEN}", + "NL": "a\nb", + "SELF": "${SELF}x", + "DOLLAR": "$", + "SUFFIX": "EN", + } lookup := func(name string) (string, bool) { - switch name { - case "TOKEN": - return "t", true - case "EMPTY": - return "", true - default: - return "", false - } + value, ok := env[name] + return value, ok } cases := []struct { @@ -270,6 +209,226 @@ func TestPreprocess_Env(t *testing.T) { cfg: parseConfig{}, want: []logicalLine{{text: "${TOKEN}", line: 1}}, }, + + // More than one reference in a line. + { + name: "two different vars in one line", + content: "--index-url https://${USER_NAME}:${TOKEN}@h/s", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "--index-url https://u:t@h/s", line: 1}}, + }, + { + name: "same var two times", + content: "${TOKEN}/${TOKEN}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "t/t", line: 1}}, + }, + { + name: "set, unset and empty vars in one line", + content: "${TOKEN} ${MISSING} ${EMPTY}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "t ${MISSING} ${EMPTY}", line: 1}}, + }, + + // The name. + { + name: "digits and underscores in the name", + content: "${MY_VAR_1}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "v1", line: 1}}, + }, + { + name: "name that starts with a digit", + content: "${1ABC}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "d", line: 1}}, + }, + { + name: "mixed-case name is never expanded", + content: "${Token}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${Token}", line: 1}}, + }, + { + name: "name with a space is not a reference", + content: "${TOK EN}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${TOK EN}", line: 1}}, + }, + { + name: "name with a dash is not a reference", + content: "${TOKEN-x}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${TOKEN-x}", line: 1}}, + }, + { + name: "empty name is not a reference", + content: "${}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${}", line: 1}}, + }, + + // The "${" and "}" around the name. + { + name: "var without braces is not a reference", + content: "$TOKEN", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "$TOKEN", line: 1}}, + }, + { + name: "var without a closing brace is not a reference", + content: "${TOKEN", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${TOKEN", line: 1}}, + }, + { + name: "dollar sign before a reference is kept", + content: "$${TOKEN}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "$t", line: 1}}, + }, + { + name: "only the inner reference of nested braces is expanded", + content: "${${TOKEN}}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${t}", line: 1}}, + }, + + // The value. + { + // pip finds the references in the line before it replaces any, so + // a reference that a value adds is not expanded. + name: "reference in a value is not expanded", + content: "${NESTED}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${TOKEN}", line: 1}}, + }, + + // pip replaces each reference of the line in order, and each replace + // changes all copies in the line as it is then. + { + // After NESTED adds "${TOKEN}", the replace for TOKEN also + // changes that copy. + name: "reference in a value that comes later in the line is expanded", + content: "${NESTED} ${TOKEN}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "t t", line: 1}}, + }, + { + name: "reference in a value that came earlier in the line is not expanded", + content: "${TOKEN} ${NESTED}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "t ${TOKEN}", line: 1}}, + }, + { + // The second match of TOKEN replaces the copy that NESTED added. + name: "second match of a reference expands a copy from a value", + content: "${TOKEN} ${NESTED} ${TOKEN}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "t t t", line: 1}}, + }, + { + name: "unset vars around a value with a reference", + content: "${MISSING} ${NESTED} ${MISSING}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${MISSING} ${TOKEN} ${MISSING}", line: 1}}, + }, + { + name: "value that holds its own reference", + content: "${SELF}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${SELF}x", line: 1}}, + }, + { + // Each match of SELF replaces every copy again. + name: "two matches of a value that holds its own reference", + content: "${SELF} ${SELF}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${SELF}xx ${SELF}xx", line: 1}}, + }, + { + // A value can make a reference with the text next to it, with no + // "${" in the value. + name: "dollar value makes a reference with the text after it", + content: "${DOLLAR}{TOKEN}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${TOKEN}", line: 1}}, + }, + { + name: "reference made by a dollar value is expanded by a later match", + content: "${TOKEN} ${DOLLAR}{TOKEN} ${TOKEN}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "t t t", line: 1}}, + }, + { + name: "value of name characters completes a reference", + content: "${TOK${SUFFIX}}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${TOKEN}", line: 1}}, + }, + { + name: "reference completed by a value is expanded by a later match", + content: "${TOK${SUFFIX}} ${TOKEN}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "t t", line: 1}}, + }, + { + // Whitespace is trimmed before the expansion. + name: "whitespace in a value is kept", + content: "foo ${PAD}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "foo v ", line: 1}}, + }, + { + // Lines are split before the expansion. + name: "line break in a value does not split the line", + content: "${NL}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "a\nb", line: 1}}, + }, + + // The order of the preprocess steps. + { + // Comments are removed before the expansion. + name: "hash in a value does not start a comment", + content: "foo ${HASH}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "foo a #b", line: 1}}, + }, + { + name: "reference in an inline comment is removed", + content: "foo # ${TOKEN}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "foo", line: 1}}, + }, + { + name: "reference in a whole-line comment is removed", + content: "# ${TOKEN}", + cfg: parseConfig{env: lookup}, + want: nil, + }, + { + // Lines are joined before the expansion. + name: "reference split by a continuation is expanded", + content: "${TO\\\nKEN}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "t", line: 1}}, + }, + { + name: "references on joined lines are expanded", + content: "${TOKEN}\\\n${TOKEN}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "tt", line: 1}}, + }, + { + name: "reference on line 2 keeps its line number", + content: "foo\n${TOKEN}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{ + {text: "foo", line: 1}, + {text: "t", line: 2}, + }, + }, } for _, c := range cases { @@ -281,6 +440,153 @@ func TestPreprocess_Env(t *testing.T) { } } +// expandEnv replaces references in one pass when pip's order gives the same +// result, so a long line of references takes linear time. Only when a value +// makes a new reference does it follow pip's order step by step, and then +// over maxOrderedEnvRefs references, or over maxEnvGrowth bytes of growth, is +// an error. +func TestPreprocess_EnvLimits(t *testing.T) { + env := map[string]string{ + "TOKEN": "t", + "NESTED": "${TOKEN}", + "DOUBLE": "${DOUBLE}${DOUBLE}", + } + cfg := parseConfig{env: func(name string) (string, bool) { + value, ok := env[name] + return value, ok + }} + + tests := []struct { + name string + content string + want []logicalLine + // wantErr is a part of the error text. A row with wantErr expects an + // error. + wantErr string + }{ + { + // This is far over maxOrderedEnvRefs, so it must take the + // one-pass path. + name: "many references with plain values", + content: strings.Repeat("${TOKEN}", 100_000), + want: []logicalLine{{text: strings.Repeat("t", 100_000), line: 1}}, + }, + { + name: "pip's order at the reference limit", + content: "${NESTED}" + strings.Repeat(" ${TOKEN}", maxOrderedEnvRefs-1), + want: []logicalLine{{text: "t" + strings.Repeat(" t", maxOrderedEnvRefs-1), line: 1}}, + }, + { + name: "pip's order over the reference limit", + content: "foo\n${NESTED}" + strings.Repeat(" ${TOKEN}", maxOrderedEnvRefs), + wantErr: "line 2: an environment variable value makes a new ${NAME} reference, and the line has more than 100 references", + }, + { + // The joined line starts on line 2, so the error names line 2. + name: "pip's order over the reference limit, in a line joined from two lines", + content: "foo\n${NESTED}\\\n" + + strings.Repeat(" ${TOKEN}", maxOrderedEnvRefs) + "\nbar\n", + wantErr: "line 2: an environment variable value makes a new ${NAME} reference", + }, + { + // A last line that ends with "\" is expanded after the loop over + // the lines, so its error has its own return. + name: "pip's order over the reference limit, on a last line that ends with a backslash", + content: "foo\n${NESTED}" + strings.Repeat(" ${TOKEN}", maxOrderedEnvRefs) + "\\", + wantErr: "line 2: an environment variable value makes a new ${NAME} reference", + }, + { + name: "pip's order at the reference limit, on a last line that ends with a backslash", + content: "foo\n${NESTED}" + strings.Repeat(" ${TOKEN}", maxOrderedEnvRefs-1) + "\\", + want: []logicalLine{ + {text: "foo", line: 1}, + {text: "t" + strings.Repeat(" t", maxOrderedEnvRefs-1), line: 2}, + }, + }, + { + // "${NESTED} ${TOKEN}" is 18 bytes, and the replace of NESTED + // makes the line 1 byte shorter. So the two passes read + // 2*maxOrderedEnvWork/2 - 1 bytes. + name: "pip's order just under the work limit", + content: "${NESTED} ${TOKEN}" + strings.Repeat("x", maxOrderedEnvWork/2-18), + want: []logicalLine{{text: "t t" + strings.Repeat("x", maxOrderedEnvWork/2-18), line: 1}}, + }, + { + // The two passes read maxOrderedEnvWork + 1 bytes. + name: "pip's order just over the work limit", + content: "foo\n${NESTED} ${TOKEN}" + strings.Repeat("x", maxOrderedEnvWork/2-17), + wantErr: "line 2: an environment variable value makes a new ${NAME} reference, and the line is too long: " + + "pip's order reads more than 16777216 bytes", + }, + { + // Checked with pip 21.2.4. + name: "value that doubles its own reference, two times", + content: "${DOUBLE} ${DOUBLE}", + want: []logicalLine{{ + text: "${DOUBLE}${DOUBLE}${DOUBLE}${DOUBLE} ${DOUBLE}${DOUBLE}${DOUBLE}${DOUBLE}", + line: 1, + }}, + }, + { + // Each match doubles all copies, so 30 matches would make 2^30 + // copies. pip does not stop. + name: "value that doubles its own reference, many times", + content: "foo\n" + strings.Repeat("${DOUBLE}", 30), + wantErr: "line 2: expanding environment variables makes the line longer than", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := preprocess(tt.content, cfg) + if tt.wantErr != "" { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +// pip's order reads the whole line once for each reference, so a long line +// needs maxOrderedEnvWork. Found by review: 100 references on a 16 MiB line +// allocated 1.6 GB, and on a 64 MiB line about 6.5 GB. +func TestExpandEnv_LongLineInPipsOrder(t *testing.T) { + if race.Enabled { + t.Skip("the race detector adds allocations") + } + // A has the value "${V0}", which makes a new reference, so expandEnv must + // use pip's order. Each of the other references has a different name, so + // each pass copies the line. + var b strings.Builder + b.WriteString("${A}") + for i := range maxOrderedEnvRefs - 1 { + b.WriteString("${V" + strconv.Itoa(i) + "}") + } + b.WriteString(strings.Repeat("x", 16<<20)) + line := b.String() + lookup := func(name string) (string, bool) { + if name == "A" { + return "${V0}", true + } + return "v", true + } + + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + _, err := expandEnv(line, lookup, maxEnvExpansion) + runtime.ReadMemStats(&after) + + require.Error(t, err) + assert.Contains(t, err.Error(), "pip's order reads more than 16777216 bytes") + // The one-pass expansion copies the line once, before expandEnv knows + // that it needs pip's order. + assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(100<<20), "bytes allocated") +} + func TestWithEnv(t *testing.T) { lookup := func(name string) (string, bool) { return "v", true @@ -299,3 +605,87 @@ func TestWithEnv(t *testing.T) { require.NoError(t, err) assert.Equal(t, []logicalLine{{text: "v", line: 1}}, got) } + +// ${NAME} expansion may add at most maxEnvExpansion bytes to one file, in all +// its lines. The one-pass expansion had no limit: found by review, a 256 KB +// line of "${A}" with a 4 KB value made a 256 MB line. +func TestParse_EnvExpansionLimit(t *testing.T) { + const valueLen = 4096 + value := strings.Repeat("x", valueLen) + lookup := func(string) (string, bool) { return value, true } + // Each "${A}" (4 bytes) adds valueLen-4 bytes. + perRef := valueLen - len("${A}") + atLimit := maxEnvExpansion / perRef + + tests := []struct { + name string + content string + wantErr string + }{ + {name: "one line at the limit", content: strings.Repeat("${A}", atLimit)}, + { + name: "one line over the limit", + content: strings.Repeat("${A}", atLimit+1), + wantErr: "line 1: expanding environment variables adds too many bytes: the file would grow by more than 16777216 bytes", + }, + { + // The limit counts all the lines of the file. + name: "many lines over the limit", + content: strings.Repeat("${A}\n", atLimit+1), + wantErr: fmt.Sprintf("line %d: expanding environment variables adds too many bytes", atLimit+1), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := Parse(tt.content, WithEnv(lookup)) + if tt.wantErr == "" { + require.NoError(t, err) + return + } + require.Error(t, err) + assert.ErrorIs(t, err, ErrInvalidRequirementsFile) + assert.Contains(t, err.Error(), tt.wantErr) + }) + } +} + +// expandEnv checks the length of the one-pass result before it builds it, so a +// line over the limit does not allocate the result first. +func TestExpandEnv_OverLimitDoesNotBuildTheResult(t *testing.T) { + if race.Enabled { + t.Skip("the race detector adds allocations") + } + value := strings.Repeat("x", 4096) + lookup := func(string) (string, bool) { return value, true } + line := strings.Repeat("${A}", 65_536) // 256 KB; the result would be 256 MB + + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + _, err := expandEnv(line, lookup, maxEnvExpansion) + runtime.ReadMemStats(&after) + + assert.ErrorIs(t, err, errEnvExpansion) + // The match indexes of the 65,536 references take about 10 MB, before the + // check. The result would take 256 MB. + assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(64<<20), "bytes allocated") +} + +// pip's order also stays within maxGrowth. +func TestExpandEnv_PipsOrderWithinMaxGrowth(t *testing.T) { + env := map[string]string{"NESTED": "${TOKEN}", "TOKEN": "ttttttttt"} + lookup := func(name string) (string, bool) { + v, ok := env[name] + return v, ok + } + // The line and the one-pass result "${TOKEN} ttttttttt" are both 18 bytes, + // but pip's order gives "ttttttttt ttttttttt", 19 bytes. + line := "${NESTED} ${TOKEN}" + + got, err := expandEnv(line, lookup, 1) + require.NoError(t, err) + assert.Equal(t, "ttttttttt ttttttttt", got) + + _, err = expandEnv(line, lookup, 0) + assert.ErrorIs(t, err, errEnvExpansion) +} diff --git a/reqtxt/python_space_test.go b/reqtxt/python_space_test.go new file mode 100644 index 0000000..43c0552 --- /dev/null +++ b/reqtxt/python_space_test.go @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// isPythonSpace must match Python's str.isspace(). The two sets were compared +// for every code point with Python 3.9: they differ from unicode.IsSpace only +// at U+001C to U+001F. +func TestIsPythonSpace(t *testing.T) { + tests := []struct { + r rune + want bool + }{ + // unicode.IsSpace and Python agree. + {r: ' ', want: true}, + {r: '\t', want: true}, + {r: '\n', want: true}, + {r: '\v', want: true}, + {r: '\f', want: true}, + {r: '\r', want: true}, + {r: 0x0085, want: true}, // next line + {r: 0x00A0, want: true}, // no-break space + {r: 0x2028, want: true}, // line separator + {r: 0x3000, want: true}, // ideographic space + + // Python whitespace that unicode.IsSpace does not include. + {r: 0x001C, want: true}, // file separator + {r: 0x001D, want: true}, // group separator + {r: 0x001E, want: true}, // record separator + {r: 0x001F, want: true}, // unit separator + + // Not whitespace for either. + {r: 'a', want: false}, + {r: '#', want: false}, + {r: 0x001B, want: false}, // escape, next to U+001C + {r: 0x007F, want: false}, // delete + {r: 0x200B, want: false}, // zero width space + {r: 0xFEFF, want: false}, // byte order mark + } + + for _, tt := range tests { + t.Run(fmt.Sprintf("U+%04X", tt.r), func(t *testing.T) { + assert.Equal(t, tt.want, isPythonSpace(tt.r)) + }) + } +} + +// pip finds comments and trims a line with Python's whitespace, so U+001F +// before "#" starts a comment, and U+001F at the start or end of a line is +// removed. Checked with pip 21.2.4. +func TestParse_PythonWhitespace(t *testing.T) { + tests := []struct { + name string + input string + // want is the describeEntry text of each entry, before and after the + // round trip through String(). + want []string + // wantErr is a part of the error text. A row with wantErr expects an + // error. + wantErr string + }{ + { + name: "comment after U+001F on an option line", + input: "--index-url=a\x1f#b", + want: []string{"option --index-url=a"}, + }, + { + name: "comment after U+001F on a requirement line", + input: "foo\x1f#bar", + want: []string{"requirement foo"}, + }, + { + name: "U+001F at the start of a line", + input: "\x1ffoo", + want: []string{"requirement foo"}, + }, + { + name: "U+001F at the end of a line", + input: "foo\x1f", + want: []string{"requirement foo"}, + }, + { + // A whole-line comment that ends with a backslash does not join + // the next line. + name: "whole-line comment after U+001F ends with a backslash", + input: "\x1f# comment \\\nfoo", + want: []string{"requirement foo"}, + }, + { + // pip also stops the marker at the "#", so the marker is invalid. + name: "comment after U+001F inside a marker literal", + input: `foo; os_name == "a` + "\x1f" + `#b"`, + wantErr: "invalid PEP 508 requirement", + }, + { + // pip starts the options only at " -", so U+001F does not. String() + // writes the "-" as `\x2d`, as after any whitespace of + // isPythonSpace. The value is the same. + name: "dash after U+001F inside a marker literal", + input: `foo; os_name == 'a` + "\x1f" + `-b'`, + want: []string{"requirement foo; os_name == \"a\x1f\\x2db\""}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + if tt.wantErr != "" { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + got := make([]string, len(f.Entries)) + for i, e := range f.Entries { + got[i] = describeEntry(e) + } + assert.Equal(t, tt.want, got) + + again, err := Parse(f.String()) + require.NoError(t, err, "String() output parses again: %q", f.String()) + gotAgain := make([]string, len(again.Entries)) + for i, e := range again.Entries { + gotAgain[i] = describeEntry(e) + } + assert.Equal(t, tt.want, gotAgain, "same entries after a round trip") + }) + } +} + +// File.String() must write a value with U+001F so that Parse reads it back to +// the same value: Parse now trims U+001F from the end of a line, and finds a +// comment at U+001F then "#". +func TestFileString_PythonWhitespace(t *testing.T) { + tests := []struct { + name string + entry Entry + wantString string + }{ + { + name: "option value with U+001F then a hash", + entry: &OptionEntry{Name: "--index-url", Value: "a\x1f#b"}, + wantString: "--index-url=\"a\x1f\"\\#\"b\"", + }, + { + name: "option value that ends with U+001F", + entry: &OptionEntry{Name: "--index-url", Value: "a\x1f"}, + wantString: "--index-url=\"a\x1f\"", + }, + { + name: "include path that ends with U+001F", + entry: &IncludeEntry{Path: "a.txt\x1f"}, + wantString: "-r \"a.txt\x1f\"", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := &File{Entries: []Entry{tt.entry}} + got := f.String() + assert.Equal(t, tt.wantString, got) + + again, err := Parse(got) + require.NoError(t, err, "String() output parses again: %q", got) + assert.Equal(t, entryFields(f), entryFields(again), "same entry after a round trip") + }) + } +} diff --git a/reqtxt/shlex.go b/reqtxt/shlex.go index adc1f10..d53ff42 100644 --- a/reqtxt/shlex.go +++ b/reqtxt/shlex.go @@ -44,6 +44,20 @@ import ( // A word only exists once at least one character (quoted or unquoted) has // been appended to it, so shlexSplit("") and shlexSplit(" ") both // return an empty, non-nil slice. +// +// It reads line byte by byte. Each character that it acts on is ASCII, and +// no byte of a multi-byte UTF-8 character is ASCII, so this gives the same +// words as a split by runes. Unlike a split by runes, it keeps each byte that +// is not valid UTF-8, so the words hold the same bytes as line. +// +// Because it keeps these bytes, removing a quote or a backslash can join the +// bytes on each side of it into one character, as "\xc2\"\"\x85" gives U+0085. +// pip decodes the file before it splits it, so its shlex never joins bytes. +// If such a join makes a line break of str.splitlines() (see lineBreaks), +// shlexSplit returns an error: no requirements file can write a word that +// holds a line break, because pip splits the lines before shlex reads quotes +// or escapes. A join that makes another character is kept, because String() +// can write that character and it reads back the same. func shlexSplit(line string) ([]string, error) { const ( stateNormal = iota @@ -52,70 +66,89 @@ func shlexSplit(line string) ([]string, error) { ) words := []string{} - var word []rune + var word []byte inWord := false state := stateNormal + // next is the index in line after the byte that was last appended to + // word, and joinAt is the index in word of the last byte that was + // appended after bytes of line were removed (-1 if none). A line break + // that has a byte at joinAt, but does not start there, was made by a + // join. + next, joinAt := 0, -1 - appendRune := func(r rune) { - word = append(word, r) + appendByte := func(i int) error { + if len(word) > 0 && i != next { + joinAt = len(word) + } + word = append(word, line[i]) inWord = true + next = i + 1 + if joinAt >= 0 && joinsLineBreak(word, joinAt) { + return fmt.Errorf("%w: quotes or a backslash join bytes into the line break %q", + ErrInvalidRequirementsFile, word[len(word)-lineBreakLen(word):]) + } + return nil } endWord := func() { if inWord { words = append(words, string(word)) word = word[:0] inWord = false + joinAt = -1 } } - runes := []rune(line) - for i := 0; i < len(runes); i++ { - r := runes[i] + for i := 0; i < len(line); i++ { + c := line[i] + var err error switch state { case stateNormal: switch { - case isShlexSpace(r): + case isShlexSpace(c): endWord() - case r == '\'': + case c == '\'': state = stateSingle inWord = true - case r == '"': + case c == '"': state = stateDouble inWord = true - case r == '\\': + case c == '\\': + // The escaped character can be more than one byte. Its other + // bytes are not ASCII, so the default case appends them. i++ - if i >= len(runes) { + if i >= len(line) { return nil, fmt.Errorf("%w: trailing unescaped backslash", ErrInvalidRequirementsFile) } - appendRune(runes[i]) + err = appendByte(i) default: - appendRune(r) + err = appendByte(i) } case stateSingle: - switch r { + switch c { case '\'': state = stateNormal default: - appendRune(r) + err = appendByte(i) } case stateDouble: - switch r { + switch c { case '"': state = stateNormal case '\\': - if i+1 < len(runes) && (runes[i+1] == '"' || runes[i+1] == '\\') { + if i+1 < len(line) && (line[i+1] == '"' || line[i+1] == '\\') { i++ - appendRune(runes[i]) - } else { - appendRune(r) } + err = appendByte(i) default: - appendRune(r) + err = appendByte(i) } } + if err != nil { + return nil, err + } } switch state { @@ -129,16 +162,37 @@ func shlexSplit(line string) ([]string, error) { return words, nil } -// isShlexSpace reports whether r is a word separator under Python shlex's +// isShlexSpace reports whether c is a word separator under Python shlex's // default whitespace set (shlex.whitespace = " \t\r\n"). This is narrower // than unicode.IsSpace, which also treats '\v', '\f', NEL, NBSP, and other // Unicode Zs-category runes as whitespace; those must remain ordinary word // characters here to match Python's behavior. -func isShlexSpace(r rune) bool { - switch r { +func isShlexSpace(c byte) bool { + switch c { case ' ', '\t', '\r', '\n': return true default: return false } } + +// lineBreakLen returns the length of the multi-byte line break of lineBreaks +// (U+0085, U+2028 or U+2029) at the end of word, or 0 if there is none. A +// one-byte line break cannot be made by a join. +func lineBreakLen(word []byte) int { + n := len(word) + switch { + case n >= 2 && word[n-2] == 0xc2 && word[n-1] == 0x85: + return 2 + case n >= 3 && word[n-3] == 0xe2 && word[n-2] == 0x80 && (word[n-1] == 0xa8 || word[n-1] == 0xa9): + return 3 + } + return 0 +} + +// joinsLineBreak reports whether word ends with a multi-byte line break that +// has the byte at joinAt after its first byte, so that a join made it. +func joinsLineBreak(word []byte, joinAt int) bool { + n := lineBreakLen(word) + return n > 0 && joinAt > len(word)-n +} diff --git a/reqtxt/shlex_test.go b/reqtxt/shlex_test.go index 28a4c63..9851b7a 100644 --- a/reqtxt/shlex_test.go +++ b/reqtxt/shlex_test.go @@ -90,6 +90,29 @@ func TestShlexSplit(t *testing.T) { line: "a\vb", want: []string{"a\vb"}, }, + { + // The quotes join the bytes of "é", which is not a line break. + name: "quotes join bytes into a character", + line: "a\xc3\"\"\xa9", + want: []string{"a\u00e9"}, + }, + { + // The quotes are before the line break, not inside it. + name: "quotes before a line break", + line: "a\"\"\u0085", + want: []string{"a\u0085"}, + }, + { + name: "line break after a backslash escape", + line: "\\a\u2028", + want: []string{"a\u2028"}, + }, + { + // The bytes are in different words, so they are not joined. + name: "line break bytes in two words", + line: "a\xc2 \"\"\x85", + want: []string{"a\xc2", "\x85"}, + }, } for _, c := range cases { @@ -110,6 +133,11 @@ func TestShlexSplit_Errors(t *testing.T) { {name: "unterminated single quote", line: `'abc`}, {name: "trailing bare backslash after a word", line: `a\`}, {name: "bare backslash with nothing else", line: `\`}, + {name: "double quotes join U+0085", line: "a\xc2\"\"\x85"}, + {name: "single quotes join U+2028", line: "a\xe2'\x80'\xa8"}, + {name: "two joins make U+2028", line: "a\xe2''\x80''\xa8"}, + {name: "backslash joins U+2029", line: "a\xe2\x80\\\xa9"}, + {name: "escaped quote then a join", line: "\"\\\"\xc2\"\x85"}, } for _, c := range cases { diff --git a/reqtxt/string.go b/reqtxt/string.go index 4b0bebd..5147869 100644 --- a/reqtxt/string.go +++ b/reqtxt/string.go @@ -2,18 +2,37 @@ package reqtxt -import "strings" - -// String renders f as a canonical requirements.txt document: one line per -// entry, in file order, joined with "\n". The rendering is not -// byte-identical to whatever produced f (comments and blank lines, which -// Parse drops, are never reconstructed), but Parse(f.String()) yields a -// File equivalent to f: every entry's semantic fields (name, extras, -// specifiers, marker, hashes, options, paths, ...) survive the round trip. +import ( + "strings" + "unicode/utf8" + + "github.com/posit-dev/go-python-packaging/marker" + "github.com/posit-dev/go-python-packaging/requirement" +) + +// String renders f as a requirements.txt document, with one line per entry in +// file order. Comments and blank lines are not kept, but Parse(f.String()) +// gives a File with the same entries as f. +// +// This is not true for two kinds of value. Parse gives them only with +// WithEnv, when an environment variable adds the text: +// - A value with a line break, such as "\n" or U+2028. A requirements file +// has no escape for a line break. A marker literal is not affected. +// - A target that is not editable and that starts with "-", or has "#" at +// its start or after whitespace. pip reads such a target with no quotes. +// +// String writes these values unchanged. The output can fail to parse, or read +// back as different entries. For example, the target "#/" reads back as a +// comment. func (f *File) String() string { lines := make([]string, len(f.Entries)) for i, e := range f.Entries { lines[i] = renderEntry(e) + // A line that ends with "\" continues on the next line. pip removes + // the space only after it joins lines, so the space stops that. + if strings.HasSuffix(lines[i], `\`) { + lines[i] += " " + } } return strings.Join(lines, "\n") } @@ -24,22 +43,26 @@ func renderEntry(e Entry) string { switch v := e.(type) { case *RequirementEntry: var b strings.Builder - b.WriteString(v.Requirement.String()) + b.WriteString(requirementText(v.Requirement)) writeReqOptions(&b, v.Hashes, v.Options) return b.String() case *UnnamedEntry: var b strings.Builder + // An editable target was read through shlex, so it is quoted the same + // way. Any other target is written as it was read, as pip reads it. if v.Editable { b.WriteString("-e ") + b.WriteString(quoteIfNeeded(v.Raw)) + } else { + b.WriteString(v.Raw) } - b.WriteString(v.Raw) writeReqOptions(&b, v.Hashes, v.Options) return b.String() case *IncludeEntry: if v.Constraint { - return "-c " + v.Path + return "-c " + quoteIfNeeded(v.Path) } - return "-r " + v.Path + return "-r " + quoteIfNeeded(v.Path) case *OptionEntry: // A file-level option renders as "=" (see renderOption): // a bare " " would not round-trip for an option that @@ -58,6 +81,135 @@ func renderEntry(e Entry) string { } } +// requirementText returns r.String(), changed so that Parse and pip read it +// back from a requirements file as the same requirement: +// - A "#" or "-" after whitespace in a marker literal is escaped (see +// escapeMarkerLiterals). Only pip 24.1 and later decode these escapes. +// - Text that would read as a local path (see readAsTarget) changes form: +// "foo.whl" becomes "foo.whl[]", "foo.whl[x]" becomes "foo.whl [x]", +// "foo===x.whl" becomes "foo (===x.whl )", and "foo===a/b" becomes +// "foo ===a/b". +// +// The space before ")" is necessary, because pip 21.2.4 reads ")" as part of +// a "===" version. +func requirementText(r requirement.Requirement) string { + // Render the marker only once: r.String() would render it, and the + // escape below needs it again. markerSeparator copies the separator that + // r.String() writes, which TestRequirementText_MatchesString checks. + noMarker := r + noMarker.Marker = marker.Marker{} + head := noMarker.String() + s := head + if !r.Marker.IsEmpty() { + s += markerSeparator(r) + escapeMarkerLiterals(r.Marker.String()) + } + // A "name @ url" requirement never reads as a path (see + // isNamedURLRequirement), so check only a version requirement. Most + // requirements cannot read as a path, and mayReadAsTarget finds them + // for less cost than readAsTarget. + if r.URL != "" || !mayReadAsTarget(head) { + return s + } + if _, isTarget := readAsTarget(s); !isTarget { + return s + } + + // r.String() starts with the name, then the extras in brackets, then the + // version. A name and an extra cannot contain "]". + nameEnd := len(r.Name) + end := nameEnd + if len(r.Extras) > 0 { + end += strings.IndexByte(s[end:], ']') + 1 + } + version := r.Specifiers.String() + if !strings.HasPrefix(s[end:], version) { + return s + } + nameAndExtras, rest := s[:end], s[end+len(version):] + + switch { + case version == "" && len(r.Extras) == 0: + nameAndExtras += "[]" + case version == "": + nameAndExtras = r.Name + " " + nameAndExtras[nameEnd:] + case hasArchiveExtension(version): + version = " (" + version + " )" + default: + version = " " + version + } + return nameAndExtras + version + rest +} + +// mayReadAsTarget is a cheap check before readAsTarget, for a requirement with +// no URL. head is the text before the marker. If mayReadAsTarget is false, +// readAsTarget is also false, also for a name that is not valid. It is true +// when head has one of these: +// - "/", for a URL or a path. +// - "+", for a VCS prefix such as "git+". A local version also has one. +// - ";", because readAsTarget cuts the text at the first ";". +// - A first byte that is not an ASCII letter or digit, such as "." or a space. +// - An archive extension, after non-empty extras are removed. +func mayReadAsTarget(head string) bool { + if head == "" || !isASCIIAlnum(head[0]) || strings.ContainsAny(head, "/;+") { + return true + } + return hasArchiveExtension(stripExtras(strings.TrimFunc(head, isPythonSpace))) +} + +// isASCIIAlnum reports whether c is an ASCII letter or digit. +func isASCIIAlnum(c byte) bool { + return 'a' <= c|0x20 && c|0x20 <= 'z' || '0' <= c && c <= '9' +} + +// markerSeparator returns the text that requirement.String() writes between +// the rest of r and its marker: " ; " after a URL, because a URL may hold ";", +// and "; " otherwise. +func markerSeparator(r requirement.Requirement) string { + if r.URL != "" { + return " ; " + } + return "; " +} + +// escapeMarkerLiterals writes each "#" or "-" after whitespace (see +// isPythonSpace) in a quoted literal of the marker text m as `\x23` or +// `\x2d`. pip finds a comment at " #" and the options at " -" before it parses +// the requirement, also inside quotes. The marker parser decodes the escapes, +// so each value stays the same. packaging decodes them only from 22.0 (pip +// 24.1). Older pip reads `\x23` as four characters, but it cannot read such a +// value without the escape either, because it cuts the line there. +// A literal ends at the next quote of the same kind, because marker.String() +// writes no quote of that kind inside it. +func escapeMarkerLiterals(m string) string { + if !strings.ContainsAny(m, "#-") { + return m + } + var b strings.Builder + var quote rune // the quote of the open literal, or 0 outside a literal + prev := rune(0) + for i := 0; i < len(m); { + r, size := utf8.DecodeRuneInString(m[i:]) + // Copy the bytes, so that a byte that is not valid UTF-8 stays the same. + out := m[i : i+size] + switch { + case quote == 0: + if r == '"' || r == '\'' { + quote = r + } + case r == quote: + quote = 0 + case r == '#' && isPythonSpace(prev): + out = `\x23` + case r == '-' && isPythonSpace(prev): + out = `\x2d` + } + b.WriteString(out) + prev = r + i += size + } + return b.String() +} + // writeReqOptions appends the canonical rendering of a RequirementEntry's // or UnnamedEntry's per-line "--hash" values and other options to b: each // as " --hash=:" or " =" (bare " " @@ -70,6 +222,14 @@ func renderEntry(e Entry) string { func writeReqOptions(b *strings.Builder, hashes []Hash, options []OptionEntry) { for _, h := range hashes { b.WriteString(" --hash=") + // Most hashes need no quotes, so write them without building the + // joined string first. + if plainASCII(h.Algorithm) && plainASCII(h.Digest) { + b.WriteString(h.Algorithm) + b.WriteByte(':') + b.WriteString(h.Digest) + continue + } b.WriteString(quoteIfNeeded(h.Algorithm + ":" + h.Digest)) } for _, o := range options { @@ -90,46 +250,96 @@ func writeReqOptions(b *strings.Builder, hashes []Hash, options []OptionEntry) { // Parse(f.String()) round trip. A genuinely boolean/arity-0 option (or an // unrecognized bare flag) with Value == "" is unaffected and still renders // bare, matching its actual on-the-wire form. +// +// An option named "-", which Parse gives for the token "-=", is also written +// as "-=\"\"". A bare "-" is not an option (see isOptionToken), so it would +// read back as no entry, or as an unexpected token after a requirement. func renderOption(o OptionEntry) string { + name := escapeOptionName(o.Name) if o.Value == "" { - if isValueTakingOption(o.Name) { - return o.Name + `=""` + if isValueTakingOption(o.Name) || !isOptionToken(name) { + return name + `=""` } - return o.Name + return name } - return o.Name + "=" + quoteIfNeeded(o.Value) + return name + "=" + quoteIfNeeded(o.Value) +} + +// escapeOptionName quotes the part of name after its leading "-" when needed, +// as in -" 0". The "-" stays first: only a line that starts with "-" is an +// option line, and an option name always starts with "-". +func escapeOptionName(name string) string { + rest, hasDash := strings.CutPrefix(name, "-") + quoted := quoteIfNeeded(rest) + // Most names need no quotes. Return such a name, so that no new string + // is made. + if hasDash && quoted == rest { + return name + } + return "-" + quoted } // isValueTakingOption reports whether name (an OptionEntry.Name) identifies -// an option that takes a value: a known file-level option with arity 1 -// (knownOptions, defined in parse.go), or a per-requirement value option -// (perLineValueOptions, also parse.go). Both tables are keyed by an -// option's canonical spelling, which is exactly what dispatchFileOption and -// attachReqOptions ever store into OptionEntry.Name, so a direct lookup by -// name is sufficient here. +// an option that takes a value (see optionTakesValue in parse.go). String() +// writes an empty value of such an option as "", because a bare name would +// take the next token as its value. func isValueTakingOption(name string) bool { - if spec, ok := knownOptions[name]; ok { - return spec.arity == 1 + return optionTakesValue(name) +} + +// plainASCII reports whether quoteIfNeeded returns s unchanged for a reason it +// can see in one pass over the bytes: s is not empty, does not start with +// "#", and is printable ASCII with no space, quote or backslash. It is false +// for some strings that need no quotes, such as one with "é", which +// quoteIfNeeded then checks in full. +func plainASCII(s string) bool { + if s == "" || s[0] == '#' { + return false + } + for i := 0; i < len(s); i++ { + if c := s[i]; c <= ' ' || c > '~' || c == '"' || c == '\'' || c == '\\' { + return false + } } - return perLineValueOptions[name] + return true } -// quoteIfNeeded returns s unchanged if it contains no shlex-significant -// whitespace or double quotes; otherwise it wraps s in double quotes, +// quoteIfNeeded returns s unchanged if it contains no whitespace, no quote or +// backslash, and no comment start; otherwise it wraps s in double quotes, // backslash-escaping any '"' or '\\' so the result re-tokenizes (via -// shlexSplit's double-quote handling) back to the original value. +// shlexSplit's double-quote handling) back to the original value. Any +// whitespace of isPythonSpace counts, because pip trims it from the end of a +// line. +// +// pip removes comments before shlex sees the line, so a "#" after whitespace +// starts a comment even inside quotes. Such a "#" is written as `"\#"`: the +// quotes close, an escaped "#" follows, and the quotes open again. func quoteIfNeeded(s string) string { - if !strings.ContainsAny(s, " \t\"") { + if plainASCII(s) { + return s + } + if !strings.ContainsAny(s, `"'\`) && strings.IndexFunc(s, isPythonSpace) < 0 && commentStartIndex(s) < 0 { return s } var b strings.Builder b.WriteByte('"') - for _, r := range s { - if r == '"' || r == '\\' { + prev := rune(0) + for i := 0; i < len(s); { + r, size := utf8.DecodeRuneInString(s[i:]) + switch { + case r == '#' && isPythonSpace(prev): + b.WriteString(`"\#"`) + case r == '"' || r == '\\': b.WriteByte('\\') + b.WriteByte(s[i]) + default: + // Copy the bytes, so that a byte that is not valid UTF-8 stays + // the same. WriteRune would write U+FFFD in its place. + b.WriteString(s[i : i+size]) } - b.WriteRune(r) + prev = r + i += size } b.WriteByte('"') return b.String() diff --git a/reqtxt/string_roundtrip_test.go b/reqtxt/string_roundtrip_test.go new file mode 100644 index 0000000..de1b2e8 --- /dev/null +++ b/reqtxt/string_roundtrip_test.go @@ -0,0 +1,597 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "errors" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// entryValues returns the values that each entry of f holds, so that two +// parses can be compared. +func entryValues(f *File) []string { + out := make([]string, len(f.Entries)) + for i, e := range f.Entries { + switch v := e.(type) { + case *RequirementEntry: + var hashes []string + for _, h := range v.Hashes { + hashes = append(hashes, h.Algorithm+":"+h.Digest) + } + out[i] = "requirement " + v.Requirement.String() + " hashes " + strings.Join(hashes, ",") + case *UnnamedEntry: + out[i] = "unnamed " + v.Raw + case *IncludeEntry: + out[i] = "include " + v.Path + case *OptionEntry: + out[i] = "option " + v.Name + "=" + v.Value + } + } + return out +} + +// pip reads " #" as a comment even inside quotes, and " -" as the start of the +// options, so String() must not write either one inside a value. +func TestString_RoundTripSpecialCharacters(t *testing.T) { + tests := []struct { + name string + input string + wantString string + }{ + // URLs. + { + // Found by fuzzing. + name: "URL that is only a hash", + input: "0@# #0000000000000000000", + wantString: "0 @#", + }, + { + name: "URL that starts with a hash", + input: "0@#frag", + wantString: "0 @#frag", + }, + { + name: "URL that starts with a dash", + input: "0@-x", + wantString: "0 @-x", + }, + { + name: "URL with a fragment is unchanged", + input: "foo @ https://example.com/p#egg=foo", + wantString: "foo @ https://example.com/p#egg=foo", + }, + { + // Found by fuzzing. A line that ends with "\" would continue on + // the next line, so a space follows it. + name: "URL that ends with a backslash", + input: `00000@\ `, + wantString: `00000 @ \ `, + }, + { + name: "local path that ends with a backslash", + input: "./pkg\\ \nbar", + wantString: "./pkg\\ \nbar", + }, + + // Marker literals. + { + // "\n" in a literal would split the line. + name: "newline in a literal", + input: `foo; os_name == "a\nb"`, + wantString: `foo; os_name == "a\nb"`, + }, + { + name: "line separator in a literal", + input: `foo; os_name == "a\u2028b"`, + wantString: `foo; os_name == "a\u2028b"`, + }, + { + name: "next line U+0085 in a literal", + input: `foo; os_name == "a\x85b"`, + wantString: `foo; os_name == "a\x85b"`, + }, + { + name: "vertical tab and file separator in a literal", + input: `foo; os_name == "\v\x1c"`, + wantString: `foo; os_name == "\v\x1c"`, + }, + { + name: "space then hash in a literal", + input: `foo; os_name == "\x20#"`, + wantString: `foo; os_name == " \x23"`, + }, + { + name: "tab then hash in a literal", + input: `foo; os_name == "a\t#b"`, + wantString: "foo; os_name == \"a\t\\x23b\"", + }, + { + name: "no-break space then hash in a literal", + input: "foo; os_name == \"a\u00a0\\x23\"", + wantString: "foo; os_name == \"a\u00a0\\x23\"", + }, + { + name: "space then dash in a literal", + input: `foo; os_name == "a\x20-b"`, + wantString: `foo; os_name == "a \x2db"`, + }, + { + name: "tab then dash in a literal", + input: `foo; os_name == "a\t-b"`, + wantString: "foo; os_name == \"a\t\\x2db\"", + }, + { + name: "hash after a quote is unchanged", + input: `foo; platform_version == "#1 SMP"`, + wantString: `foo; platform_version == "#1 SMP"`, + }, + { + name: "two spaces in a literal are kept", + input: `foo; os_name == "a b"`, + wantString: `foo; os_name == "a b"`, + }, + { + name: "tab in a literal is kept", + input: "foo; os_name == \"a\tb\"", + wantString: "foo; os_name == \"a\tb\"", + }, + + // Option and hash values. + { + name: "hash value with a space then a hash", + input: `foo --hash=sha256:a\ \#b`, + wantString: `foo --hash="sha256:a "\#"b"`, + }, + { + name: "option value with a space then a hash", + input: `--index-url=a\ \#b`, + wantString: `--index-url="a "\#"b"`, + }, + { + name: "option value that starts with a hash", + input: `--index-url=\#a`, + wantString: `--index-url="#a"`, + }, + { + name: "option value with a single quote", + input: `--index-url=it\'s`, + wantString: `--index-url="it's"`, + }, + { + name: "option value with a backslash", + input: `--index-url=a\\b`, + wantString: `--index-url="a\\b"`, + }, + { + // Found by fuzzing. A line loses Unicode whitespace at its end, so a + // name or value that ends with a no-break space is quoted. + name: "option name that ends with a no-break space", + input: "-\u00a0=", + wantString: "-\"\u00a0\"", + }, + { + name: "option value that ends with a no-break space", + input: "--index-url='a\u00a0'", + wantString: "--index-url=\"a\u00a0\"", + }, + { + name: "include path that ends with a no-break space", + input: "-r 'a.txt\u00a0'", + wantString: "-r \"a.txt\u00a0\"", + }, + { + name: "option value with a space is unchanged", + input: `--index-url=a\ b`, + wantString: `--index-url="a b"`, + }, + { + name: "quoted option value keeps two spaces", + input: `foo --hash="sha256:a b"`, + wantString: `foo --hash="sha256:a b"`, + }, + + // Option names. A line is an option line only if it starts with "-", + // so only the part after the "-" is quoted. + { + // Found by fuzzing. + name: "option name with a space", + input: `-\ 0`, + wantString: `-" 0"`, + }, + { + // Found by fuzzing. A line loses its trailing whitespace, so `-\ ` + // would lose the space. + name: "option name that ends with a space", + input: `-' '''''`, + wantString: `-" "`, + }, + { + name: "option name with a hash is unchanged", + input: `-a\#b`, + wantString: `-a#b`, + }, + { + name: "option name with a space then a hash", + input: `-a\ \#b`, + wantString: `-"a "\#"b"`, + }, + { + name: "per-line option name with a space", + input: `foo -\ x`, + wantString: `foo -" x"`, + }, + + // Include paths and editable targets. + { + name: "include path with a space", + input: `-r a\ b.txt`, + wantString: `-r "a b.txt"`, + }, + { + name: "include path with a space then a hash", + input: `-r a\ \#b.txt`, + wantString: `-r "a "\#"b.txt"`, + }, + { + name: "include path that starts with a hash", + input: `-r \#a.txt`, + wantString: `-r "#a.txt"`, + }, + { + name: "constraint path with a single quote", + input: `-c it\'s.txt`, + wantString: `-c "it's.txt"`, + }, + { + name: "editable path with a space", + input: `-e ./a\ b`, + wantString: `-e "./a b"`, + }, + { + name: "editable path with a space then a hash", + input: `-e ./a\ \#b`, + wantString: `-e "./a "\#"b"`, + }, + { + name: "plain path is unchanged", + input: "./pkg", + wantString: "./pkg", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + require.NoError(t, err) + text := f.String() + assert.Equal(t, tt.wantString, text) + + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + assert.Equal(t, text, again.String(), "String() is stable") + assert.Equal(t, entryValues(f), entryValues(again), "same values after a round trip") + }) + } +} + +// With WithEnv, Parse can give two kinds of value that a requirements file +// cannot write (see File.String): a value with a line break, and a target +// that starts with "-" or has a comment start. This test records that limit: +// String() writes the value unchanged, so the output is no longer the same +// file. If String() ever writes such a value in a form that reads back, change +// this test. +func TestString_UnwritableValueFromEnvironment(t *testing.T) { + env := WithEnv(func(name string) (string, bool) { + v, ok := map[string]string{"HASH": "#", "US": "\x1f", "NL": "a\nb", "LS": "a\u2028b"}[name] + return v, ok + }) + + tests := []struct { + name string + input string + // wantString is what String() writes. + wantString string + }{ + {name: "quoted include path", input: `-r "${NL}"`, wantString: "-r \"a\nb\""}, + {name: "include path", input: "-r ${LS}", wantString: "-r \"a\u2028b\""}, + {name: "option value", input: "--index-url ${LS}", wantString: "--index-url=\"a\u2028b\""}, + {name: "editable target", input: "-e ./${LS}", wantString: "-e \"./a\u2028b\""}, + {name: "URL of a requirement", input: "foo @ https://h/${LS}", wantString: "foo @ https://h/a\u2028b"}, + + // A target is written as it was read, with no quotes or escapes. + { + // "#/" reads back as a comment, so the entry is lost. + name: "target that starts with a hash", + input: "${HASH}/", + wantString: "#/", + }, + { + // Parse removes the leading U+001F, which is whitespace in pip, + // so the target is "-/". It reads back as an option. + name: "target that starts with a dash", + input: "${US}-/", + wantString: "-/", + }, + { + // U+001F is whitespace for pip's comments but not for + // strings.Fields, so this is one target. "\x1f#b" reads back as a + // comment, so the target becomes "./a". + name: "target with a hash after whitespace", + input: "./a${US}#b", + wantString: "./a\x1f#b", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input, env) + require.NoError(t, err) + text := f.String() + assert.Equal(t, tt.wantString, text) + + again, err := Parse(text) + if err == nil { + assert.NotEqual(t, entryValues(f), entryValues(again), "the output reads back as a different file") + } + }) + } +} + +// Parse reads a line as a local path when its first token contains "/", or when +// the text before the marker ends with an archive extension after non-empty +// extras are removed, as pip does. An arbitrary-equality version or a local +// version can do either, and so can a name. String() writes these +// requirements in a form that reads back as a requirement (see +// requirementText). +func TestString_RequirementThatLooksLikePath(t *testing.T) { + hash := "sha256:" + strings.Repeat("a", 64) + + tests := []struct { + name string + input string + wantString string + }{ + { + // Found by fuzzing. + name: "version that is only a slash", + input: "0 ===/", + wantString: "0 ===/", + }, + { + name: "version with a slash", + input: "0 ===a/b", + wantString: "0 ===a/b", + }, + { + name: "space after the operator", + input: "0 === a/b", + wantString: "0 ===a/b", + }, + { + // "foo ===x.whl" reads as a wheel file, as in pip. + name: "version that ends with a wheel extension", + input: "foo (===x.whl )", + wantString: "foo (===x.whl )", + }, + { + name: "version that ends with a tar.gz extension", + input: "foo (===x.tar.gz )", + wantString: "foo (===x.tar.gz )", + }, + { + name: "local version that ends with a zip extension", + input: "foo (==1.0+a.zip)", + wantString: "foo (==1.0+a.zip )", + }, + { + name: "extras", + input: "foo[bar,baz] ===a/b", + wantString: "foo[bar,baz] ===a/b", + }, + { + // "0===a/b;" would read as a path, and a path cannot have a marker. + name: "marker", + input: `0 ===a/b ; os_name == "x"`, + wantString: `0 ===a/b; os_name == "x"`, + }, + { + name: "hash option", + input: "0 ===a/b --hash=" + hash, + wantString: "0 ===a/b --hash=" + hash, + }, + + // A version that does not look like a path gets no space. + { + name: "arbitrary equality with no slash", + input: "0 ===a", + wantString: "0===a", + }, + { + name: "slash only in the marker", + input: `foo ===1.0; os_name == "a/b"`, + wantString: `foo===1.0; os_name == "a/b"`, + }, + { + name: "named URL that looks like an archive", + input: "foo.whl @ https://example.com/foo.whl", + wantString: "foo.whl @ https://example.com/foo.whl", + }, + + // A name with an archive extension and no version gets empty extras, + // or a space before its extras. pip 21.2.4 reads "foo.whl" and + // "foo.whl[x]" as wheel files, and "foo.whl[]" and "foo.whl [x]" as + // the project foo.whl. + { + name: "name with a wheel extension", + input: "foo.whl[]", + wantString: "foo.whl[]", + }, + { + name: "name with a tar.gz extension, in upper case", + input: "FOO.TAR.GZ[]", + wantString: "FOO.TAR.GZ[]", + }, + { + // "foo.tar.gz;" would read as a path, and a path cannot have a + // marker. + name: "name with an archive extension, and a marker", + input: `foo.tar.gz[] ; python_version > "3"`, + wantString: `foo.tar.gz[]; python_version > "3"`, + }, + { + name: "name with an archive extension, and a hash option", + input: "foo.zip[] --hash=" + hash, + wantString: "foo.zip[] --hash=" + hash, + }, + { + name: "name with an archive extension, and extras", + input: "foo.whl [x]", + wantString: "foo.whl [x]", + }, + { + name: "name with an archive extension, extras and a marker", + input: `foo.zip [x,y];os_name=="a"`, + wantString: `foo.zip [x,y]; os_name == "a"`, + }, + { + name: "name with an archive extension, and a version with a slash", + input: "foo.whl[] ===a/b", + wantString: "foo.whl ===a/b", + }, + { + name: "name with an archive extension, and a normal version", + input: "foo.whl[] >=1.0", + wantString: "foo.whl>=1.0", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + require.NoError(t, err) + require.Len(t, f.Requirements(), 1, "the input is a requirement") + text := f.String() + assert.Equal(t, tt.wantString, text) + + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + assert.Equal(t, text, again.String(), "String() is stable") + assert.Equal(t, entryValues(f), entryValues(again), "same values after a round trip") + }) + } +} + +// The text that String() avoids writing does not read back as written. This +// is why String() escapes or quotes it. +func TestParse_UnescapedSpecialCharacters(t *testing.T) { + tests := []struct { + name string + input string + // want is the entries on success. Nil means an error. + want []string + }{ + { + // " #" starts a comment, so the literal is cut and not closed. + name: "space then hash in a literal", + input: `foo; os_name == "a #b"`, + }, + { + // " -" starts the options, inside the literal. + name: "space then dash in a literal", + input: `foo; os_name == "a -b"`, + }, + { + // " #" starts a comment, so the URL is lost. + name: "URL that starts with a hash after a space", + input: "0 @ #", + }, + { + // A line that ends with "\" continues on the next line. + name: "URL that ends with a backslash", + input: "00000 @ \\\nbar", + want: []string{"requirement 00000 @ bar hashes "}, + }, + { + // The unquoted space splits the path, and "b.txt" is ignored. + name: "include path with an unquoted space", + input: "-r a b.txt", + want: []string{"include a"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + if tt.want == nil { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile), "want ErrInvalidRequirementsFile") + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, entryValues(f)) + }) + } +} + +// A quoted value keeps each byte that is not valid UTF-8. Before, String() +// wrote U+FFFD in its place, so the value read back was different. +func TestString_QuotedValueKeepsInvalidUTF8(t *testing.T) { + tests := []struct { + name string + input string + wantString string + }{ + { + name: "option value", + input: "--index-url=\"a \xffb\"", + wantString: "--index-url=\"a \xffb\"", + }, + { + name: "include path", + input: "-r \"a \xff.txt\"", + wantString: "-r \"a \xff.txt\"", + }, + { + name: "per-requirement option", + input: "foo --config-settings=\"k=a \xff\"", + wantString: "foo --config-settings=\"k=a \xff\"", + }, + { + name: "editable target with a quote", + input: "-e \"./a\\\"\xc3\"", + wantString: "-e \"./a\\\"\xc3\"", + }, + { + // A " #" starts a comment also inside quotes, so the input + // escapes the "#" the same way String() does. + name: "hash after whitespace", + input: "--index-url=\"\xff \"\\#\"b\"", + wantString: "--index-url=\"\xff \"\\#\"b\"", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + require.NoError(t, err) + text := f.String() + assert.Equal(t, tt.wantString, text) + + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + assert.Equal(t, describeEntries(f), describeEntries(again), "same entries after a round trip") + }) + } +} + +func describeEntries(f *File) []string { + var out []string + for _, e := range f.Entries { + out = append(out, describeEntry(e)) + } + return out +} diff --git a/reqtxt/string_test.go b/reqtxt/string_test.go index c9abd6d..7ead195 100644 --- a/reqtxt/string_test.go +++ b/reqtxt/string_test.go @@ -3,234 +3,645 @@ package reqtxt import ( + "fmt" "strings" "testing" + "github.com/posit-dev/go-python-packaging/marker" + "github.com/posit-dev/go-python-packaging/requirement" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -// reparse is a small test helper: it renders f via String(), re-parses the -// result, and returns the reparsed File, so tests can assert the two Files -// are equivalent entry-by-entry. -func reparse(t *testing.T, f *File) *File { - t.Helper() - rendered := f.String() - f2, err := Parse(rendered) - require.NoError(t, err, "reparsing rendered content failed: %q", rendered) - return f2 +// entryFields returns a text for each entry of f. The text shows each field +// that File.String() writes, so that a test can compare all of the entries of +// two files. It does not show Source, because String() does not write it. +func entryFields(f *File) []string { + out := make([]string, len(f.Entries)) + for i, e := range f.Entries { + switch v := e.(type) { + case *RequirementEntry: + out[i] = fmt.Sprintf( + "requirement %s hashes=%s options=%s", + v.Requirement.String(), + hashesText(v.Hashes), + optionsText(v.Options), + ) + case *UnnamedEntry: + out[i] = fmt.Sprintf( + "unnamed %s kind=%s editable=%t egg=%s hashes=%s options=%s", + v.Raw, + v.Kind, + v.Editable, + v.EggName, + hashesText(v.Hashes), + optionsText(v.Options), + ) + case *IncludeEntry: + out[i] = fmt.Sprintf("include %s constraint=%t", v.Path, v.Constraint) + case *OptionEntry: + out[i] = "option " + v.Name + "=" + v.Value + default: + out[i] = fmt.Sprintf("unknown entry type %T", e) + } + } + return out } -func TestFileString_RequirementWithHashesAndMarker(t *testing.T) { - f, err := Parse(`requests[security]>=2.0 ; python_version >= "3.8" --hash=sha256:aaa --hash=sha256:bbb`) - require.NoError(t, err) - require.Len(t, f.Entries, 1) - - f2 := reparse(t, f) - require.Len(t, f2.Entries, 1) - - want, ok := f.Entries[0].(*RequirementEntry) - require.True(t, ok) - got, ok := f2.Entries[0].(*RequirementEntry) - require.True(t, ok) - - assert.Equal(t, want.Requirement.Name, got.Requirement.Name) - assert.Equal(t, want.Requirement.Extras, got.Requirement.Extras) - assert.Equal(t, want.Requirement.Specifiers.String(), got.Requirement.Specifiers.String()) - assert.Equal(t, want.Requirement.Marker.String(), got.Requirement.Marker.String()) - assert.False(t, got.Requirement.Marker.IsEmpty()) - assert.Equal(t, want.Hashes, got.Hashes) - require.Len(t, got.Hashes, 2) +// hashesText returns the hashes as "algorithm:digest" values divided by ",". +func hashesText(hashes []Hash) string { + parts := make([]string, len(hashes)) + for i, h := range hashes { + parts[i] = h.Algorithm + ":" + h.Digest + } + return strings.Join(parts, ",") } -func TestFileString_EditableVCSWithEgg(t *testing.T) { - f, err := Parse("-e git+https://h/p#egg=n") - require.NoError(t, err) - require.Len(t, f.Entries, 1) - - f2 := reparse(t, f) - require.Len(t, f2.Entries, 1) - - want, ok := f.Entries[0].(*UnnamedEntry) - require.True(t, ok) - got, ok := f2.Entries[0].(*UnnamedEntry) - require.True(t, ok) - - assert.True(t, got.Editable) - assert.Equal(t, KindVCS, got.Kind) - assert.Equal(t, "n", got.EggName) - assert.Equal(t, want.Raw, got.Raw) - assert.Equal(t, want.EggName, got.EggName) - assert.Equal(t, want.Kind, got.Kind) - assert.Equal(t, want.Editable, got.Editable) +// optionsText returns the options as "name=value" values divided by ",". +func optionsText(options []OptionEntry) string { + parts := make([]string, len(options)) + for i, o := range options { + parts[i] = o.Name + "=" + o.Value + } + return strings.Join(parts, ",") } -func TestFileString_Includes(t *testing.T) { - f, err := Parse("-r base.txt\n-c constraints.txt") - require.NoError(t, err) - require.Len(t, f.Entries, 2) - - f2 := reparse(t, f) - require.Len(t, f2.Entries, 2) - - incR, ok := f2.Entries[0].(*IncludeEntry) - require.True(t, ok) - assert.Equal(t, "base.txt", incR.Path) - assert.False(t, incR.Constraint) - - incC, ok := f2.Entries[1].(*IncludeEntry) - require.True(t, ok) - assert.Equal(t, "constraints.txt", incC.Path) - assert.True(t, incC.Constraint) -} - -func TestFileString_FileOptions(t *testing.T) { - f, err := Parse("--index-url https://i/simple\n--no-index\n--find-links x\n--find-links y") - require.NoError(t, err) - - f2 := reparse(t, f) - - indexURL, ok := f2.IndexURL() - require.True(t, ok) - assert.Equal(t, "https://i/simple", indexURL) - assert.True(t, f2.NoIndex()) - assert.Equal(t, []string{"x", "y"}, f2.FindLinks()) +// File.String() writes one line for each entry, and Parse reads that text back +// to the same entries. +func TestFileString(t *testing.T) { + tests := []struct { + name string + input string + wantString string + wantEntries []string // entryFields of the parsed file, before and after the round trip + }{ + // Requirements and targets. + { + name: "requirement with extras, a marker and hashes", + input: `requests[security]>=2.0 ; python_version >= "3.8" --hash=sha256:aaa --hash=sha256:bbb`, + wantString: `requests[security]>=2.0; python_version >= "3.8" --hash=sha256:aaa --hash=sha256:bbb`, + wantEntries: []string{`requirement requests[security]>=2.0; python_version >= "3.8" hashes=sha256:aaa,sha256:bbb options=`}, + }, + { + name: "requirement with a per-line option", + input: "flask --config-settings=key=val", + wantString: "flask --config-settings=key=val", + wantEntries: []string{"requirement flask hashes= options=--config-settings=key=val"}, + }, + { + // A value-taking per-line option with an empty value must render + // in the explicit '=""' form, as a file-level option does. + name: "requirement with a per-line option that has an empty value", + input: "flask --global-option=", + wantString: `flask --global-option=""`, + wantEntries: []string{"requirement flask hashes= options=--global-option="}, + }, + { + name: "editable VCS target with an egg name", + input: "-e git+https://h/p#egg=n", + wantString: "-e git+https://h/p#egg=n", + wantEntries: []string{"unnamed git+https://h/p#egg=n kind=vcs editable=true egg=n hashes= options="}, + }, + { + name: "archive", + input: "foo-1.0.tar.gz", + wantString: "foo-1.0.tar.gz", + wantEntries: []string{"unnamed foo-1.0.tar.gz kind=local-path editable=false egg= hashes= options="}, + }, + + // Includes. + { + name: "requirements include and constraints include", + input: "-r base.txt\n-c constraints.txt", + wantString: "-r base.txt\n-c constraints.txt", + wantEntries: []string{ + "include base.txt constraint=false", + "include constraints.txt constraint=true", + }, + }, + + // File-level options. + { + name: "known options with and without a value", + input: "--index-url https://i/simple\n--no-index\n--find-links x\n--find-links y", + wantString: "--index-url=https://i/simple\n--no-index\n--find-links=x\n--find-links=y", + wantEntries: []string{ + "option --index-url=https://i/simple", + "option --no-index=", + "option --find-links=x", + "option --find-links=y", + }, + }, + { + name: "known option with a value that has a space", + input: `--find-links "/opt/my links"`, + wantString: `--find-links="/opt/my links"`, + wantEntries: []string{"option --find-links=/opt/my links"}, + }, + { + // Regression test: an unknown file-level option with a value must + // round-trip through the "=" form. A bare "--cert /etc/ssl/ca.pem" + // reparse would silently corrupt this into a boolean "--cert" plus + // a phantom UnnamedEntry for "/etc/ssl/ca.pem" (dispatchFileOption + // only recovers a value for an unrecognized flag from the inline + // "=value" form). + name: "unknown option with a value", + input: "--cert=/etc/ssl/ca.pem", + wantString: "--cert=/etc/ssl/ca.pem", + wantEntries: []string{"option --cert=/etc/ssl/ca.pem"}, + }, + { + // Regression test: a value-taking option given an explicitly empty + // value (e.g. "--index-url=") must round-trip through the explicit + // '=""' form. Rendering it as a bare "--index-url" would + // reparse as arity-1 with no value supplied at all, which is an + // error (the option "requires a value"), so Parse(f.String()) + // would fail. + name: "value-taking option with an empty value", + input: "--index-url=", + wantString: `--index-url=""`, + wantEntries: []string{"option --index-url="}, + }, + { + // A genuinely boolean (arity-0) option with an empty Value must + // still render as a bare flag, not "--no-index=\"\"": only + // value-taking options need the explicit empty-value form. + name: "boolean option renders bare", + input: "--no-index", + wantString: "--no-index", + wantEntries: []string{"option --no-index="}, + }, + + // The whole file. + { + name: "comments are dropped", + input: "# c\nflask", + wantString: "flask", + wantEntries: []string{"requirement flask hashes= options="}, + }, + { + name: "entries are joined with a newline", + input: "flask\nrequests", + wantString: "flask\nrequests", + wantEntries: []string{ + "requirement flask hashes= options=", + "requirement requests hashes= options=", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, err := Parse(tt.input) + require.NoError(t, err) + assert.Equal(t, tt.wantEntries, entryFields(f), "entries of the input") + + got := f.String() + assert.Equal(t, tt.wantString, got) + + again, err := Parse(got) + require.NoError(t, err, "String() output parses again: %q", got) + assert.Equal(t, tt.wantEntries, entryFields(again), "same entries after a round trip") + }) + } } -func TestFileString_UnknownFileOptionWithValue(t *testing.T) { - // Regression test: an unknown file-level option with a value must - // round-trip through the "=" form. A bare "--cert /etc/ssl/ca.pem" - // reparse would silently corrupt this into a boolean "--cert" plus a - // phantom UnnamedEntry for "/etc/ssl/ca.pem" (dispatchFileOption only - // recovers a value for an unrecognized flag from the inline "=value" - // form). - f, err := Parse("--cert=/etc/ssl/ca.pem") - require.NoError(t, err) - require.Len(t, f.Entries, 1) - - f2 := reparse(t, f) - require.Len(t, f2.Entries, 1, "expected exactly one entry, no phantom entry from misparsed value") - - got, ok := f2.Entries[0].(*OptionEntry) - require.True(t, ok) - assert.Equal(t, "--cert", got.Name) - assert.Equal(t, "/etc/ssl/ca.pem", got.Value) +// mayReadAsTarget is false for most requirements, so that requirementText +// does not call readAsTarget for them. It must be true for each text that +// readAsTarget reads as a target. +func TestMayReadAsTarget(t *testing.T) { + tests := []struct { + head string + want bool + }{ + // Common requirements do not go to readAsTarget. + {"foo", false}, + {"foo==1.0.0", false}, + {"foo[bar,baz]>=2.0,<3", false}, + {"Django~=4.2", false}, + {"foo===abc", false}, + {"foo.tar.zip", false}, + + // Text that can read as a target goes to readAsTarget. + {"foo===a/b", true}, + {"foo.whl", true}, + {"FOO.TAR.GZ", true}, + {"foo.zip[x]", true}, + {"foo==1.0+a.zip", true}, + {"foo==1.0+cpu", true}, + {"foo===a;b", true}, + + // A name that is not valid. + {"", true}, + {".", true}, + {" foo", true}, + {"git+foo", true}, + {"gİt+foo", true}, // strings.ToLower gives "git+foo" + {"é", true}, + } + for _, tt := range tests { + t.Run(tt.head, func(t *testing.T) { + assert.Equal(t, tt.want, mayReadAsTarget(tt.head)) + for _, s := range []string{tt.head, tt.head + `; os_name == "x"`} { + if _, isTarget := readAsTarget(s); isTarget { + assert.True(t, mayReadAsTarget(tt.head), "readAsTarget(%q) is true", s) + } + } + }) + } } -func TestFileString_KnownFileOptionValueWithSpace(t *testing.T) { - f, err := Parse(`--find-links "/opt/my links"`) - require.NoError(t, err) - require.Len(t, f.Entries, 1) - - f2 := reparse(t, f) - require.Len(t, f2.Entries, 1) - - assert.Equal(t, []string{"/opt/my links"}, f2.FindLinks()) +// FuzzMayReadAsTarget checks that mayReadAsTarget is true for each text that +// readAsTarget reads as a target, also when head is not a valid requirement. +func FuzzMayReadAsTarget(f *testing.F) { + for _, head := range []string{ + "foo==1.0", "foo.whl", "foo.zip[x]", "foo===a/b", "git+foo", + "gİt+foo", ".", " foo", "foo==1.0+cpu", "foo===a;b", + } { + f.Add(head, `os_name == "x"`) + } + f.Fuzz(func(t *testing.T, head, m string) { + for _, s := range []string{head, head + "; " + m} { + if _, isTarget := readAsTarget(s); isTarget && !mayReadAsTarget(head) { + t.Fatalf("readAsTarget(%q) is true, but mayReadAsTarget(%q) is false", s, head) + } + } + }) } -func TestFileString_PerLineOptionRoundTrip(t *testing.T) { - f, err := Parse(`flask --config-settings=key=val`) - require.NoError(t, err) - require.Len(t, f.Entries, 1) - - f2 := reparse(t, f) - require.Len(t, f2.Entries, 1) - - got, ok := f2.Entries[0].(*RequirementEntry) - require.True(t, ok) - require.Len(t, got.Options, 1) - assert.Equal(t, "--config-settings", got.Options[0].Name) - assert.Equal(t, "key=val", got.Options[0].Value) +// requirementText returns r.String(), but adds a space after the name and the +// extras when Parse would otherwise read the text as a local path. Parse must +// read the result back as the same requirement. +// requirementText builds its text without calling r.String(), so it copies +// the separator that r.String() writes before a marker (markerSeparator). +// For a requirement that needs no change for a requirements file, the two +// must be equal, so this fails if requirement.String() changes its separator. +func TestRequirementText_MatchesString(t *testing.T) { + for _, input := range []string{ + `foo; os_name == "posix"`, + `foo[a,b]>=1.0,<2.0; python_version >= "3.8" and os_name == "posix"`, + `foo @ https://example.com/foo.whl ; os_name == "posix"`, + `foo[a] @ https://example.com/a;b ; extra == "x"`, + "foo>=1.0", + "foo @ https://example.com/foo.whl", + } { + r, err := requirement.Parse(input) + require.NoError(t, err) + assert.Equal(t, r.String(), requirementText(r), "%q", input) + } } -func TestFileString_EmptyValueOptionRoundTrips(t *testing.T) { - // Regression test: a value-taking option given an explicitly empty - // value (e.g. "--index-url=") must round-trip through the explicit - // '=""' form. Rendering it as a bare "--index-url" would reparse - // as arity-1 with no value supplied at all, which is an error (the - // option "requires a value"), so Parse(f.String()) would fail. - f, err := Parse("--index-url=") - require.NoError(t, err) - require.Len(t, f.Entries, 1) - - rendered := f.String() - f2, err := Parse(rendered) - require.NoError(t, err, "reparsing rendered content failed: %q", rendered) - require.Len(t, f2.Entries, 1) - - got, ok := f2.Entries[0].(*OptionEntry) - require.True(t, ok) - assert.Equal(t, "--index-url", got.Name) - assert.Equal(t, "", got.Value) +func TestRequirementText(t *testing.T) { + tests := []struct { + name string + input string // the text that requirement.Parse reads to make r + want string + }{ + // Text that Parse reads as a requirement is not changed. + { + name: "name only", + input: "foo", + want: "foo", + }, + { + name: "version specifier", + input: "foo>=1.0", + want: "foo>=1.0", + }, + { + name: "extras and a version specifier", + input: "foo[bar]>=1.0", + want: "foo[bar]>=1.0", + }, + { + name: "arbitrary equality that is not a path", + input: "foo===abc", + want: "foo===abc", + }, + { + name: "slash in the marker", + input: `foo; os_name == "a/b"`, + want: `foo; os_name == "a/b"`, + }, + { + name: "archive extension in the marker", + input: `foo; platform_release == "a.whl"`, + want: `foo; platform_release == "a.whl"`, + }, + { + name: "archive-like name with a URL", + input: "foo.zip @ https://example.com/foo.zip", + want: "foo.zip @ https://example.com/foo.zip", + }, + { + name: "archive-like name with a URL that starts with a hash", + input: "foo.tar@#frag", + want: "foo.tar @#frag", + }, + { + name: "URL with a slash and a marker", + input: `foo @ https://example.com/a/b ; os_name == "x"`, + want: `foo @ https://example.com/a/b ; os_name == "x"`, + }, + + // A "#" or "-" after whitespace in a marker literal gets an escape + // (see TestEscapeMarkerLiterals). + { + name: "space then hash in a marker literal", + input: `foo; os_name == "a #b"`, + want: `foo; os_name == "a \x23b"`, + }, + { + // Only the marker is scanned for literals, so the quote in the + // URL does not start one. + name: "URL with a quote and a marker literal with a space then dash", + input: `foo @ https://example.com/a'b ; os_name == "c -d"`, + want: `foo @ https://example.com/a'b ; os_name == "c \x2dd"`, + }, + + { + name: "archive-like name with a version", + input: "foo.whl>=1.0", + want: "foo.whl>=1.0", + }, + + // Text that Parse would read as a local path because its first token + // contains "/" gets a space after the name and the extras. + { + name: "arbitrary equality with a slash", + input: "0===a/b", + want: "0 ===a/b", + }, + { + name: "extras before the version", + input: "foo[bar,baz]===a/b", + want: "foo[bar,baz] ===a/b", + }, + { + name: "name that is not normalized", + input: "Foo_Bar===a/b", + want: "Foo_Bar ===a/b", + }, + { + // requirement.String() writes the extra "a-" as "a_". + name: "extra with a trailing underscore", + input: "foo[a_]===a/b", + want: "foo[a_] ===a/b", + }, + { + name: "slash in the version and a marker", + input: `0===a/b; os_name == "x"`, + want: `0 ===a/b; os_name == "x"`, + }, + { + name: "archive-like name and a slash in the version", + input: "foo.whl===a/b", + want: "foo.whl ===a/b", + }, + + // Text that Parse would read as an archive because it ends with an + // archive extension. A version goes in parentheses, with a space + // before ")" for pip 21.2.4. + { + name: "arbitrary equality with an archive extension", + input: "foo===x.whl", + want: "foo (===x.whl )", + }, + { + name: "local version with an archive extension", + input: "foo==1.0+a.zip", + want: "foo (==1.0+a.zip )", + }, + { + name: "slash and an archive extension in the version", + input: "foo===a/b.whl", + want: "foo (===a/b.whl )", + }, + { + // Only the text before the ";" decides. + name: "archive extension in the version and a marker", + input: `foo===x.whl; os_name == "x"`, + want: `foo (===x.whl ); os_name == "x"`, + }, + { + name: "archive-like name, extras and an archive extension in the version", + input: "foo.whl[x]===x.whl", + want: "foo.whl[x] (===x.whl )", + }, + + // A name with an archive extension and no version. pip removes + // non-empty extras at the end before it checks the extension, so + // empty extras, or a space before the extras, keep it a name. + { + name: "archive-like name", + input: "foo.whl", + want: "foo.whl[]", + }, + { + name: "archive-like name in upper case", + input: "FOO.TAR.GZ", + want: "FOO.TAR.GZ[]", + }, + { + name: "name with an xz extension", + input: "foo.tar.xz", + want: "foo.tar.xz[]", + }, + { + name: "name with a tlz extension and extras", + input: "foo.tlz[x]", + want: "foo.tlz [x]", + }, + { + // pip's extension of "foo.tar.zip" is ".tar.zip", which is not + // an archive extension. + name: "name with .tar before an archive extension", + input: "foo.tar.zip", + want: "foo.tar.zip", + }, + { + name: "archive-like name with extras", + input: "foo.whl[x]", + want: "foo.whl [x]", + }, + { + name: "archive-like name with extras and a marker", + input: `foo.zip[x,y]; os_name == "x"`, + want: `foo.zip [x,y]; os_name == "x"`, + }, + { + name: "archive-like name with a marker", + input: `foo.tar.gz; os_name == "x"`, + want: `foo.tar.gz[]; os_name == "x"`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r, err := requirement.Parse(tt.input) + require.NoError(t, err) + + got := requirementText(r) + assert.Equal(t, tt.want, got) + + f, err := Parse(got) + require.NoError(t, err, "the result parses as a requirements file") + require.Len(t, f.Entries, 1) + entry, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "the result is a requirement, not a %T", f.Entries[0]) + assert.Equal(t, r.String(), entry.Requirement.String(), "the result is the same requirement") + }) + } } -func TestFileString_EmptyValuePerLineOptionRoundTrips(t *testing.T) { - f, err := Parse("flask --global-option=") - require.NoError(t, err) - require.Len(t, f.Entries, 1) - - rendered := f.String() - f2, err := Parse(rendered) - require.NoError(t, err, "reparsing rendered content failed: %q", rendered) - require.Len(t, f2.Entries, 1) - - got, ok := f2.Entries[0].(*RequirementEntry) - require.True(t, ok) - require.Len(t, got.Options, 1) - assert.Equal(t, "--global-option", got.Options[0].Name) - assert.Equal(t, "", got.Options[0].Value) -} - -func TestFileString_BooleanOptionStillRendersBare(t *testing.T) { - // A genuinely boolean (arity-0) option with an empty Value must still - // render as a bare flag, not "--no-index=\"\"": only value-taking - // options need the explicit empty-value form. - f, err := Parse("--no-index") - require.NoError(t, err) - require.Len(t, f.Entries, 1) - - rendered := f.String() - assert.Equal(t, "--no-index", rendered) - - f2, err := Parse(rendered) - require.NoError(t, err) - require.Len(t, f2.Entries, 1) - assert.True(t, f2.NoIndex()) -} - -func TestFileString_UnnamedArchive(t *testing.T) { - f, err := Parse("foo-1.0.tar.gz") - require.NoError(t, err) - require.Len(t, f.Entries, 1) - - f2 := reparse(t, f) - require.Len(t, f2.Entries, 1) - - got, ok := f2.Entries[0].(*UnnamedEntry) - require.True(t, ok) - assert.Equal(t, "foo-1.0.tar.gz", got.Raw) - assert.Equal(t, KindLocalPath, got.Kind) - assert.False(t, got.Editable) -} - -func TestFileString_CommentsDropped(t *testing.T) { - f, err := Parse("# c\nflask") - require.NoError(t, err) - - rendered := f.String() - assert.Contains(t, rendered, "flask") - assert.NotContains(t, rendered, "# c") - assert.NotContains(t, rendered, "#") -} - -func TestFileString_JoinsWithNewline(t *testing.T) { - f, err := Parse("flask\nrequests") - require.NoError(t, err) - require.Len(t, f.Entries, 2) - - rendered := f.String() - lines := strings.Split(rendered, "\n") - require.Len(t, lines, 2) - assert.True(t, strings.HasPrefix(lines[0], "flask")) - assert.True(t, strings.HasPrefix(lines[1], "requests")) +// pip reads " #" as a comment and " -" as the start of the options, also +// inside quotes. So escapeMarkerLiterals writes a "#" or "-" after whitespace +// in a marker literal as `\x23` or `\x2d`. marker.String() does not write these +// escapes, so they are only in a requirements file. +func TestEscapeMarkerLiterals(t *testing.T) { + tests := []struct { + name string + input string // the text that marker.Parse reads + want string // escapeMarkerLiterals of marker.String() + }{ + { + name: "space then hash", + input: `os_name == "a #b"`, + want: `os_name == "a \x23b"`, + }, + { + name: "space then dash", + input: `os_name == "a -b"`, + want: `os_name == "a \x2db"`, + }, + { + name: "hash and dash with no whitespace before them are unchanged", + input: `os_name == "#1-a#b"`, + want: `os_name == "#1-a#b"`, + }, + { + name: "plain value is unchanged", + input: `python_version >= "3.8"`, + want: `python_version >= "3.8"`, + }, + + // Each whitespace character before "#" or "-" causes the escape, not + // only a space. The whitespace stays as it is. + { + name: "tab then hash", + input: `os_name == "a\t#b"`, + want: "os_name == \"a\t\\x23b\"", + }, + { + name: "no-break space then hash", + input: `os_name == "a\xa0#b"`, + want: "os_name == \"a\u00a0\\x23b\"", + }, + { + name: "ideographic space then dash", + input: `os_name == "a\u3000-b"`, + want: "os_name == \"a\u3000\\x2db\"", + }, + { + // marker.String() writes the line break as the text `\r\n`, so no + // whitespace comes before the "#". + name: "line break then hash", + input: `os_name == "a\r\n#b"`, + want: `os_name == "a\r\n#b"`, + }, + + // Combinations of the escapes. + { + name: "two spaces then hash", + input: `os_name == "a #b"`, + want: `os_name == "a \x23b"`, + }, + { + // Only the first character after the space gets an escape. + name: "space, hash, then dash", + input: `os_name == "a #-b"`, + want: `os_name == "a \x23-b"`, + }, + { + name: "two spaces, each followed by a hash", + input: `os_name == "a # #b"`, + want: `os_name == "a \x23 \x23b"`, + }, + { + name: "value is a space then a hash", + input: `os_name == " #"`, + want: `os_name == " \x23"`, + }, + { + name: "backslash, space, then hash", + input: `os_name == "a\\ #b"`, + want: `os_name == "a\\ \x23b"`, + }, + { + name: "invalid UTF-8 byte then space then hash", + input: "os_name == \"\xff #b\"", + want: "os_name == \"\xff \\x23b\"", + }, + { + // U+001F is Python whitespace, so pip finds a comment at U+001F + // then "#" (see isPythonSpace). + name: "unit separator U+001F then hash", + input: `os_name == "a\x1f#b"`, + want: "os_name == \"a\x1f\\x23b\"", + }, + + // The quotes of a literal. + { + // A single quote does not end a double-quoted literal. + name: "both quote characters and space then hash", + input: `os_name == "\x22 #'"`, + want: `os_name == "\x22 \x23'"`, + }, + { + // A double quote does not end a single-quoted literal. + name: "single-quoted literal with a double quote", + input: `os_name == '" #'`, + want: `os_name == '" \x23'`, + }, + { + name: "two literals", + input: `os_name == "a #b" and platform_release == "c -d"`, + want: `os_name == "a \x23b" and platform_release == "c \x2dd"`, + }, + + // Literals in other places of a comparison. + { + name: "literal on the left side", + input: `"a #b" == os_name`, + want: `"a \x23b" == os_name`, + }, + { + name: "literal with the 'in' operator", + input: `"a -b" in os_name`, + want: `"a \x2db" in os_name`, + }, + { + // The parser normalizes the extra before String() writes it. + name: "extra value with space then dash", + input: `extra == "A -B"`, + want: `extra == "a \x2db"`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m, err := marker.Parse(tt.input) + require.NoError(t, err) + + got := escapeMarkerLiterals(m.String()) + assert.Equal(t, tt.want, got) + + f, err := Parse("foo; " + got) + require.NoError(t, err, "the result parses in a requirements file") + require.Len(t, f.Entries, 1) + entry, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "the result is a requirement, not a %T", f.Entries[0]) + assert.Equal(t, m.String(), entry.Requirement.Marker.String(), "the result is the same marker") + }) + } } diff --git a/reqtxt/types.go b/reqtxt/types.go index 6b4c1a5..e900c6d 100644 --- a/reqtxt/types.go +++ b/reqtxt/types.go @@ -182,11 +182,13 @@ const ( optNoIndex = "--no-index" optFindLinks = "--find-links" optRequireHashes = "--require-hashes" - optPre = "--pre" - optTrustedHost = "--trusted-host" - optNoBinary = "--no-binary" - optOnlyBinary = "--only-binary" - optPreferBinary = "--prefer-binary" + // optNoRequireHashes turns off --require-hashes in pip. + optNoRequireHashes = "--no-require-hashes" + optPre = "--pre" + optTrustedHost = "--trusted-host" + optNoBinary = "--no-binary" + optOnlyBinary = "--only-binary" + optPreferBinary = "--prefer-binary" // optAllReleases and optOnlyFinal are pip's per-package replacements for // --pre, which pip rejects in combination with it. Both take a value: // ":all:", ":none:", or a comma-separated package list. diff --git a/requirement/adjacent_specifier_test.go b/requirement/adjacent_specifier_test.go index c658664..9a53a23 100644 --- a/requirement/adjacent_specifier_test.go +++ b/requirement/adjacent_specifier_test.go @@ -129,3 +129,44 @@ func TestArbitraryEqualityKeepsItsPermissiveOperand(t *testing.T) { } } } + +// "||" is not PEP 508. Package version reads it as an OR of groups, but Parse +// must not: Parse accepted "0>1.0||*", and its String() "0>1.0||>=0.0.0" did +// not parse back. Found by FuzzParse. +// +// Expected verdicts below are the measured behaviour of pypa/packaging 24.1. +// It rejects each "||" after an operator other than "===", and it reads the +// operand of "===" as one opaque string, "||" included. +func TestParse_OrIsNotPEP508(t *testing.T) { + for _, in := range []string{ + "0>1.0||*", + "0>1.0||>=0.0.0", + "0||*", + "foo>=1.0||<2", + "foo==1.0||2.0", + "foo~=1.0||*", + "foo (>1.0||*)", + "foo>=1.0,<2||>3", + } { + if r, err := Parse(in); err == nil { + t.Errorf("Parse(%q) = %q, want an error: packaging rejects it", in, r.String()) + } + } + + for _, in := range []string{"foo===a||b", "foo===a||b,>=1.0", "foo (===||)"} { + r, err := Parse(in) + if err != nil { + t.Errorf("Parse(%q): want one === specifier, got error %v", in, err) + continue + } + s := r.String() + again, err := Parse(s) + if err != nil { + t.Errorf("Parse(%q).String() = %q, which does not parse: %v", in, s, err) + continue + } + if again.String() != s { + t.Errorf("Parse(%q).String() = %q, but it reads back as %q", in, s, again.String()) + } + } +} diff --git a/requirement/bench_test.go b/requirement/bench_test.go new file mode 100644 index 0000000..567fc7d --- /dev/null +++ b/requirement/bench_test.go @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package requirement + +import ( + "testing" + + "github.com/posit-dev/go-python-packaging/internal/allocbudget" +) + +// Benchmarks and allocation budgets for the hot paths of this package. The +// budget tests run in CI and fail on any change in allocations; the +// benchmarks are for comparing a branch with main (see CLAUDE.md, +// "Performance"). + +// benchRequirements are requirements of common shapes. parse and str are +// the allocation budgets of Parse and of String. +var benchRequirements = []struct { + name, in string + parse, str float64 +}{ + {name: "name only", in: "pyyaml", parse: 4, str: 1}, + {name: "version", in: "numpy>=1.20", parse: 34, str: 4}, + {name: "extras and versions", in: "requests[security,socks]>=2.8.1,==2.8.*", parse: 78, str: 10}, + {name: "marker", in: `requests>=2.8.1; python_version < "2.7"`, parse: 60, str: 8}, + { + name: "nested marker", + in: `django>=3.2,<4.0; python_version >= "3.8" and (os_name == "posix" or sys_platform == "win32")`, + parse: 138, str: 19, + }, + {name: "URL", in: "foo @ https://example.com/foo-1.0.tar.gz", parse: 13, str: 2}, +} + +func BenchmarkParse(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + for _, r := range benchRequirements { + if _, err := Parse(r.in); err != nil { + b.Fatal(err) + } + } + } +} + +func BenchmarkString(b *testing.B) { + reqs := make([]Requirement, len(benchRequirements)) + for i, r := range benchRequirements { + var err error + if reqs[i], err = Parse(r.in); err != nil { + b.Fatal(err) + } + } + b.ReportAllocs() + for b.Loop() { + for _, r := range reqs { + _ = r.String() + } + } +} + +func TestAllocBudget_Parse(t *testing.T) { + for _, r := range benchRequirements { + t.Run(r.name, func(t *testing.T) { + if _, err := Parse(r.in); err != nil { + t.Fatal(err) // the budget must not be an error path + } + allocbudget.Check(t, r.parse, func() { _, _ = Parse(r.in) }) + }) + } +} + +func TestAllocBudget_String(t *testing.T) { + for _, r := range benchRequirements { + t.Run(r.name, func(t *testing.T) { + req, err := Parse(r.in) + if err != nil { + t.Fatal(err) + } + allocbudget.Check(t, r.str, func() { _ = req.String() }) + }) + } +} diff --git a/requirement/control_chars_test.go b/requirement/control_chars_test.go new file mode 100644 index 0000000..5319668 --- /dev/null +++ b/requirement/control_chars_test.go @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package requirement + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The expected results follow upstream packaging at UpstreamPackagingSHA +// (26.3.dev0). Its requirement grammar allows only space and tab between the +// parts of a requirement (WS is [ \t]+). Its specifier pattern runs on a str, +// so it allows Python's "\s" between an operator and its version, and a "===" +// value is anything up to Python whitespace, ";" or ")". + +// pythonSpaceNotSpaceOrTab are the characters of Python's "\s" other than +// space and tab. +var pythonSpaceNotSpaceOrTab = map[string]string{ + "line feed": "\n", + "carriage return": "\r", + "vertical tab": "\v", + "form feed": "\f", + "unit separator U+001F": "\x1f", + "next line U+0085": "\u0085", + "no-break space U+00A0": "\u00a0", + "line separator U+2028": "\u2028", + "ideographic space U+3000": "\u3000", +} + +// otherControls are characters that are not whitespace for Python. +var otherControls = map[string]string{ + "NUL": "\x00", + "start of heading": "\x01", + "escape": "\x1b", + "delete": "\x7f", + "zero width space U+200B": "\u200b", +} + +func allNotSpaceOrTab() map[string]string { + all := make(map[string]string, len(pythonSpaceNotSpaceOrTab)+len(otherControls)) + for k, v := range pythonSpaceNotSpaceOrTab { + all[k] = v + } + for k, v := range otherControls { + all[k] = v + } + return all +} + +func TestParse_ControlCharacterBetweenParts(t *testing.T) { + for name, c := range allNotSpaceOrTab() { + t.Run(name, func(t *testing.T) { + for _, input := range []string{ + c + "foo", + "foo" + c, + "foo" + c + ">=1.0", + "foo>=1.0" + c, + "foo>=1.0" + c + ",<2.0", + "foo>=1.0," + c + "<2.0", + "foo[a" + c + "]", + "foo[a]" + c + ">=1.0", + "foo>=1.0" + c + "; os_name == \"a\"", + } { + _, err := Parse(input) + if assert.Error(t, err, "%q", input) { + assert.True(t, errors.Is(err, ErrInvalidRequirement), "%q: want ErrInvalidRequirement", input) + } + } + }) + } +} + +// Python whitespace is allowed between an operator and its version. Before, +// the U+001C to U+001F characters were an error there. +func TestParse_PythonWhitespaceAfterOperator(t *testing.T) { + for name, c := range pythonSpaceNotSpaceOrTab { + t.Run(name, func(t *testing.T) { + r, err := Parse("foo>=" + c + "1.0,<" + c + c + "2.0") + require.NoError(t, err) + assert.Equal(t, "foo>=1.0,<2.0", r.String()) + + r, err = Parse("foo===" + c + "x") + require.NoError(t, err) + assert.Equal(t, "foo===x", r.String()) + + // A "===" value ends at whitespace, and then only space or tab + // may follow. + _, err = Parse("foo===x" + c + "y") + assert.Error(t, err) + }) + } +} + +// A character that is not whitespace is part of a "===" value, and is an +// error in any other version. +func TestParse_OtherControlCharacterInVersion(t *testing.T) { + for name, c := range otherControls { + t.Run(name, func(t *testing.T) { + r, err := Parse("foo===x" + c) + require.NoError(t, err) + assert.Equal(t, "foo===x"+c, r.String()) + + _, err = Parse("foo>=" + c + "1.0") + assert.Error(t, err) + _, err = Parse("foo>=1" + c + ".0") + assert.Error(t, err) + }) + } +} + +// Space and tab are allowed between the parts of a requirement. +func TestParse_SpaceAndTabBetweenParts(t *testing.T) { + for _, c := range []string{" ", "\t", " \t "} { + r, err := Parse(c + "foo" + c + "[a]" + c + ">=1.0" + c + "," + c + "<2.0" + c + ";" + c + "os_name == \"a\"" + c) + require.NoError(t, err, "%q", c) + assert.Equal(t, "foo", r.Name) + assert.Equal(t, []string{"a"}, r.Extras) + } +} + +// A quoted marker literal can hold any character but its own quote. String() +// writes it so that it parses back the same. +func TestParse_ControlCharacterInMarkerLiteral(t *testing.T) { + for name, c := range allNotSpaceOrTab() { + t.Run(name, func(t *testing.T) { + r, err := Parse("foo; os_name == \"a" + c + "b\"") + require.NoError(t, err) + + again, err := Parse(r.String()) + require.NoError(t, err, "String() output parses again: %q", r.String()) + assert.Equal(t, r.String(), again.String()) + }) + } +} diff --git a/requirement/doc.go b/requirement/doc.go index 430f0d3..c198f12 100644 --- a/requirement/doc.go +++ b/requirement/doc.go @@ -8,7 +8,7 @@ // Parse drives the shared internal/pep508 tokenizer end-to-end in one pass // (name, extras, versionspec-or-url, then the marker clause from the // tokenizer's current position via internal/pep508's ParseRequirement), -// then delegates the version specifier to version.NewSpecifiers, +// then parses the version specifier with package version as one AND-group, // normalizes extras via extras.Normalize, and wraps the parsed marker // expression via marker.FromExpr. Every parse failure - malformed syntax, // an invalid version specifier, or an invalid marker expression - is diff --git a/requirement/extras_string_test.go b/requirement/extras_string_test.go new file mode 100644 index 0000000..35ef561 --- /dev/null +++ b/requirement/extras_string_test.go @@ -0,0 +1,330 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package requirement + +import ( + "errors" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// String() writes each normalized extra so that it parses again. An extra +// that normalizes to a trailing "-" is written with a trailing "_". Only "_" +// can end an extra in the input: "foo[a.]" does not parse, as in packaging. +func TestString_ExtrasRoundTrip(t *testing.T) { + tests := []struct { + name string + input string + wantExtras []string + wantString string + }{ + { + // Found by fuzzing. + name: "trailing underscore", + input: "0[00_]", + wantExtras: []string{"00-"}, + wantString: "0[00_]", + }, + { + name: "dot then underscore at the end", + input: "foo[a._]", + wantExtras: []string{"a-"}, + wantString: "foo[a_]", + }, + { + name: "run of trailing separators", + input: "foo[a_.__]", + wantExtras: []string{"a-"}, + wantString: "foo[a_]", + }, + { + name: "separators inside and at the end", + input: "foo[A__B_]", + wantExtras: []string{"a-b-"}, + wantString: "foo[a-b_]", + }, + { + name: "separator inside only is unchanged", + input: "foo[a_b]", + wantExtras: []string{"a-b"}, + wantString: "foo[a-b]", + }, + { + name: "two extras, one with a trailing separator", + input: "foo[x_,y]>=1.0", + wantExtras: []string{"x-", "y"}, + wantString: "foo[x_,y]>=1.0", + }, + { + name: "trailing separator with a marker", + input: `foo[x_]; python_version >= "3.8"`, + wantExtras: []string{"x-"}, + wantString: `foo[x_]; python_version >= "3.8"`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r, err := Parse(tt.input) + require.NoError(t, err) + assert.Equal(t, tt.wantExtras, r.Extras) + text := r.String() + assert.Equal(t, tt.wantString, text) + + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + assert.Equal(t, tt.wantExtras, again.Extras, "same extras after a round trip") + assert.Equal(t, text, again.String(), "String() is stable") + }) + } +} + +// A URL that starts with "#" or "-" follows "@" with no space. In a +// requirements file, " #" starts a comment and " -" starts the options. +func TestString_URLStart(t *testing.T) { + tests := []struct { + name string + input string + wantURL string + wantString string + }{ + { + name: "hash", + input: "0@#", + wantURL: "#", + wantString: "0 @#", + }, + { + name: "hash fragment", + input: "foo @ #frag", + wantURL: "#frag", + wantString: "foo @#frag", + }, + { + name: "dash", + input: "foo@-x", + wantURL: "-x", + wantString: "foo @-x", + }, + { + name: "dash with a marker", + input: `foo @ -x ; os_name == "a"`, + wantURL: "-x", + wantString: `foo @-x ; os_name == "a"`, + }, + { + name: "normal URL is unchanged", + input: "foo@https://example.com/foo.whl#sha256=abc", + wantURL: "https://example.com/foo.whl#sha256=abc", + wantString: "foo @ https://example.com/foo.whl#sha256=abc", + }, + + // A URL that starts with "#" or "-". + { + name: "dash only", + input: "foo@-", + wantURL: "-", + wantString: "foo @-", + }, + { + name: "two dashes", + input: "foo@--x", + wantURL: "--x", + wantString: "foo @--x", + }, + { + // With a space after "@", a requirements file reads this URL as a + // "--hash" option. + name: "looks like a hash option", + input: "foo @ --hash=sha256:abc", + wantURL: "--hash=sha256:abc", + wantString: "foo @--hash=sha256:abc", + }, + { + name: "two hashes", + input: "foo@##", + wantURL: "##", + wantString: "foo @##", + }, + { + name: "hash then dash", + input: "foo@#-x", + wantURL: "#-x", + wantString: "foo @#-x", + }, + { + name: "dash then hash", + input: "foo@-#x", + wantURL: "-#x", + wantString: "foo @-#x", + }, + { + name: "hash with a marker", + input: `foo @ #frag ; os_name == "a"`, + wantURL: "#frag", + wantString: `foo @#frag ; os_name == "a"`, + }, + { + name: "hash with extras", + input: "foo[bar] @ #x", + wantURL: "#x", + wantString: "foo[bar] @#x", + }, + { + name: "dash with extras", + input: "foo[bar,baz]@-x", + wantURL: "-x", + wantString: "foo[bar,baz] @-x", + }, + { + name: "dash with extras and a marker", + input: `foo[bar] @ -x ; extra == "bar"`, + wantURL: "-x", + wantString: `foo[bar] @-x ; extra == "bar"`, + }, + + // The whitespace around "@" in the input does not change the output. + { + name: "tab before a hash", + input: "foo @\t#x", + wantURL: "#x", + wantString: "foo @#x", + }, + { + name: "many spaces before a dash", + input: "foo @ -x", + wantURL: "-x", + wantString: "foo @-x", + }, + { + name: "whitespace around the requirement", + input: " foo@#x ", + wantURL: "#x", + wantString: "foo @#x"}, + + // A URL that has "#" or "-" after its first character keeps the space. + { + name: "hash after the first character", + input: "foo@a#b", + wantURL: "a#b", + wantString: "foo @ a#b", + }, + { + name: "dash after the first character", + input: "foo@a-b", + wantURL: "a-b", + wantString: "foo @ a-b", + }, + { + name: "file URL with a dash in the path", + input: "foo @ file:///tmp/-x", + wantURL: "file:///tmp/-x", + wantString: "foo @ file:///tmp/-x", + }, + + // Other start characters keep the space. + { + name: "semicolon", + input: "foo@;x", + wantURL: ";x", + wantString: "foo @ ;x", + }, + { + name: "at sign", + input: "foo@@x", + wantURL: "@x", + wantString: "foo @ @x", + }, + { + name: "slash", + input: "foo@/tmp/x", + wantURL: "/tmp/x", + wantString: "foo @ /tmp/x", + }, + { + name: "en dash is not a dash", + input: "foo@–x", + wantURL: "–x", + wantString: "foo @ –x", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r, err := Parse(tt.input) + require.NoError(t, err) + assert.Equal(t, tt.wantURL, r.URL) + text := r.String() + assert.Equal(t, tt.wantString, text) + + again, err := Parse(text) + require.NoError(t, err, "String() output parses again") + assert.Equal(t, tt.wantURL, again.URL) + assert.Equal(t, text, again.String(), "String() is stable") + }) + } +} + +// An extra must end with a letter, a digit or "_", and start with a letter or +// a digit, as in packaging. +func TestParse_ExtraWithBadEnds(t *testing.T) { + inputs := []string{ + "foo[a.]", + "foo[a-]", + "foo[.a]", + "foo[-a]", + "foo[a,b.]", + + // A run of separators at the end. + "foo[a..]", + "foo[a--]", + "foo[a.-]", + "foo[a-.]", + "foo[a_.]", + "foo[a_-]", + + // A bad start. "_" can end an extra, but it cannot start one. + "foo[_a]", + "foo[..a]", + "foo[-.a]", + + // A separator only. + "foo[.]", + "foo[-]", + "foo[_]", + + // A bad end or start in one extra of a list. + "foo[a.,b]", + "foo[a-,b]", + "foo[a,b-]", + "foo[a,.b]", + "foo[a,_b]", + "foo[a,b,c.]", + + // Whitespace in the brackets does not hide the bad end. + "foo[ a. ]", + "foo[a , b-]", + + // A non-ASCII letter is not a letter in an extra. + "foo[éa]", + "foo[aé]", + + // A bad extra before a specifier, a URL or a marker. + "foo[a.]>=1.0", + "foo[a-] @ https://example.com/foo.whl", + `foo[_a]; python_version >= "3.8"`, + } + for _, input := range inputs { + // Go writes each space in a subtest name as "_". Then "foo[ a. ]" gets + // the name "foo[_a._]". "␣" shows each space in the name. + name := strings.ReplaceAll(input, " ", "␣") + t.Run(name, func(t *testing.T) { + _, err := Parse(input) + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirement), "want ErrInvalidRequirement") + }) + } +} diff --git a/requirement/fuzz_test.go b/requirement/fuzz_test.go new file mode 100644 index 0000000..42393eb --- /dev/null +++ b/requirement/fuzz_test.go @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package requirement_test + +import ( + "errors" + "slices" + "strings" + "testing" + "time" + + "github.com/posit-dev/go-python-packaging/internal/fuzzseed" + "github.com/posit-dev/go-python-packaging/requirement" +) + +func FuzzParse(f *testing.F) { + fuzzseed.Add(f, + "requests", + "requests>=2.0", + "requests [security,tests] >= 2.8.1, == 2.8.* ; python_version < \"2.7\"", + "name@ http://foo.com", + "name @ https://example.com/pkg.whl ; os_name == \"posix\"", + "name @ git+https://example.com/repo.git@v1.0#egg=name;foo", + "Foo_Bar.baz[Extra_One]~=1.4.2", + "pip (>=20.0)", + "name===arbitrary-string", + "name>=1.0.dev0,!=1.1.*,<2", + "torch==2.4.0+cu121", + "name[]", + "name; extra == 'test'", + ) + f.Add("name" + strings.Repeat("[a", 5000)) + f.Add("name" + strings.Repeat(">=1,", 5000) + ">=1") + f.Add("name; " + strings.Repeat("(", 5000) + `os_name == "a"` + strings.Repeat(")", 5000)) + + // Inputs the fuzzer found that failed before they were fixed. + f.Add("0[00_]") + f.Add("0>1.0||*") + f.Add("0===a||b") + + f.Fuzz(func(t *testing.T, in string) { + start := time.Now() + r, err := requirement.Parse(in) + fuzzseed.Within(t, start, in) + if err != nil { + if !errors.Is(err, requirement.ErrInvalidRequirement) { + t.Fatalf("Parse(%q) error does not wrap ErrInvalidRequirement: %v", in, err) + } + return + } + if r.Name == "" { + t.Fatalf("Parse(%q) returned no error and an empty name", in) + } + rendered := r.String() + again, err := requirement.Parse(rendered) + if err != nil { + t.Fatalf("Parse(%q).String() = %q, which does not parse: %v", in, rendered, err) + } + if got := again.String(); got != rendered { + t.Fatalf("round trip of %q: %q, then %q", in, rendered, got) + } + if again.Name != r.Name || + again.URL != r.URL || + !slices.Equal(again.Extras, r.Extras) || + again.Specifiers.String() != r.Specifiers.String() || + again.Marker.String() != r.Marker.String() { + t.Fatalf("round trip of %q changed a field:\n first: %#v\nsecond: %#v", in, r, again) + } + }) +} diff --git a/requirement/long_input_test.go b/requirement/long_input_test.go new file mode 100644 index 0000000..b94677f --- /dev/null +++ b/requirement/long_input_test.go @@ -0,0 +1,311 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package requirement + +import ( + "errors" + "fmt" + "strings" + "testing" + "unicode/utf8" + + "github.com/posit-dev/go-python-packaging/internal/pep508" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// A long input with a syntax error gives a short error text, and the error +// still points at the correct place. +func TestParse_LongInputErrorText(t *testing.T) { + const hugeLen = 2_000_000 + big := strings.Repeat("a", hugeLen) + markerAfterURL := "foo @ https://example.com/" + big + " ; python_version " + urlThenSpace := "foo @ https://example.com/" + big + " " + // "€" is 3 bytes, so the error window can cut inside a character. + euro := strings.Repeat("€", hugeLen/3) + manySpecs := "foo>=1.0" + strings.Repeat(",<2", 600_000) + "," + + tests := []struct { + name string + input string + // wantClause is true when the error comes from the marker clause. + wantClause bool + wantStart int + wantEnd int + }{ + { + // The span is the whole 2 MB quoted string. + name: "long quoted string with a bad escape", + input: `foo; python_version == "` + big + `\q"`, + wantClause: true, + wantStart: len(`foo; python_version == `), + wantEnd: len(`foo; python_version == "` + big + `\q"`), + }, + { + name: "long name then a bad character", + input: big + "$", + wantStart: hugeLen, + wantEnd: hugeLen, + }, + { + name: "long extra then a bad character", + input: "foo[" + big + "$]", + wantStart: len("foo[") + hugeLen, + wantEnd: len("foo[") + hugeLen, + }, + { + name: "long URL then a bad marker operator", + input: markerAfterURL + `? "3"`, + wantClause: true, + wantStart: len(markerAfterURL), + wantEnd: len(markerAfterURL), + }, + { + name: "long word where a marker variable must be", + input: "foo; " + big, + wantClause: true, + wantStart: len("foo; "), + wantEnd: len("foo; "), + }, + { + name: "long whitespace then a bad character", + input: strings.Repeat(" ", hugeLen) + "$", + wantStart: hugeLen, + wantEnd: hugeLen, + }, + { + name: "long multi-byte name", + input: euro, + wantStart: 0, + wantEnd: 0, + }, + { + name: "long extra with no ']'", + input: "foo[" + big, + wantStart: len("foo[" + big), + wantEnd: len("foo[" + big), + }, + { + name: "long extra then a comma with no extra after it", + input: "foo[" + big + ",]", + wantStart: len("foo[" + big + ","), + wantEnd: len("foo[" + big + ","), + }, + { + name: "long specifier in parentheses with no ')'", + input: "foo (>=" + big, + wantStart: len("foo (>=" + big), + wantEnd: len("foo (>=" + big), + }, + { + name: "many specifiers then a bad character", + input: manySpecs + "$", + wantStart: len(manySpecs), + wantEnd: len(manySpecs), + }, + { + name: "long whitespace after '@' with no URL", + input: "foo @" + strings.Repeat(" ", hugeLen), + wantStart: len("foo @") + hugeLen, + wantEnd: len("foo @") + hugeLen, + }, + { + // Text after the URL must start with ";". + name: "long URL then text that is not a marker", + input: urlThenSpace + "bar", + wantStart: len(urlThenSpace), + wantEnd: len(urlThenSpace), + }, + { + // Parse reads the marker before it checks the version, so the + // marker error comes first. + name: "long bad specifier then a bad marker", + input: "foo>=" + big + "; ?", + wantClause: true, + wantStart: len("foo>=" + big + "; "), + wantEnd: len("foo>=" + big + "; "), + }, + { + name: "long extra then a bad marker operator", + input: "foo[" + big + "]; python_version ? '3'", + wantClause: true, + wantStart: len("foo[" + big + "]; python_version "), + wantEnd: len("foo[" + big + "]; python_version "), + }, + { + name: "long marker literal then 'and' at the end", + input: `foo; python_version == "` + big + `" and `, + wantClause: true, + wantStart: len(`foo; python_version == "` + big + `" and `), + wantEnd: len(`foo; python_version == "` + big + `" and `), + }, + { + name: "long marker in parentheses with no ')'", + input: `foo; (python_version == "` + big + `"`, + wantClause: true, + wantStart: len(`foo; (python_version == "` + big + `"`), + wantEnd: len(`foo; (python_version == "` + big + `"`), + }, + { + name: "long multi-byte word where a marker variable must be", + input: "foo; " + euro, + wantClause: true, + wantStart: len("foo; "), + wantEnd: len("foo; "), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := Parse(tt.input) + require.Error(t, err) + require.Less(t, len(err.Error()), 1000, "error text is short") + assert.True(t, utf8.ValidString(err.Error()), "error text is valid UTF-8") + assert.True(t, errors.Is(err, ErrInvalidRequirement), "want ErrInvalidRequirement") + var clauseErr *pep508.MarkerClauseError + assert.Equal(t, tt.wantClause, errors.As(err, &clauseErr), "error from the marker clause") + var syntaxErr *pep508.SyntaxError + require.True(t, errors.As(err, &syntaxErr), "want a *pep508.SyntaxError") + assert.Equal(t, tt.wantStart, syntaxErr.Start, "error start") + assert.Equal(t, tt.wantEnd, syntaxErr.End, "error end") + }) + } +} + +// A long version specifier gives a short error text. The specifier is quoted +// once by this package and once by the version package, and both are cut. +func TestParse_LongVersionSpecifierErrorText(t *testing.T) { + // Any specifier over 200 bytes is cut. 100 KB keeps the test fast: the + // version regexes take about 0.6 s on each 2 MB input. + big := strings.Repeat("1", 100_000) + manyConstraints := strings.Repeat(">=1.0,", 40_000) + "=" + big + "x" }, + wantText: cutSpecErr(">="+big[:198], 100_003), + }, + { + name: "long bad version with dotted name and two extras", + input: func() string { return "Foo_Bar.baz[x,y]==1." + big + "!" }, + wantText: cutSpecErr("==1."+big[:196], 100_005), + }, + { + name: "space before the specifier", + input: func() string { return "foo ==1." + big + "!" }, + wantText: cutSpecErr("==1."+big[:196], 100_005), + }, + { + name: "specifier in parentheses", + input: func() string { return "foo (==1." + big + "!)" }, + wantText: cutSpecErr("==1."+big[:196], 100_005), + }, + { + name: "marker after the specifier", + input: func() string { return "foo==1." + big + "! ; python_version > '3'" }, + wantText: cutSpecErr("==1."+big[:196], 100_005), + }, + { + name: "bad second constraint", + input: func() string { return "foo>=1.0,<" + big + "x" }, + wantText: cutSpecErr(">=1.0,<"+big[:193], 100_008), + }, + { + // The spaces around the comma are not part of the quoted specifier. + name: "spaces around the comma", + input: func() string { return "foo==1.0 , >=" + big + "x" }, + wantText: cutSpecErr("==1.0,>="+big[:192], 100_009), + }, + { + name: "many valid constraints then a bad one", + input: func() string { return "foo" + manyConstraints }, + wantText: cutSpecErr(manyConstraints[:200], 240_002), + }, + { + name: "compatible release operator", + input: func() string { return "foo~=" + big + "!" }, + wantText: cutSpecErr("~="+big[:198], 100_003), + }, + { + name: "not equal operator", + input: func() string { return "foo!=1." + big + "x" }, + wantText: cutSpecErr("!=1."+big[:196], 100_005), + }, + { + name: "empty local version", + input: func() string { return "foo<=1." + big + "+" }, + wantText: cutSpecErr("<=1."+big[:196], 100_005), + }, + { + name: "digits after a wildcard", + input: func() string { return "foo==1.0.*" + big }, + wantText: cutSpecErr("==1.0.*"+big[:193], 100_007), + }, + { + name: "wildcard with a local version", + input: func() string { return "foo==1." + big + ".*+local" }, + wantText: cutSpecErr("==1."+big[:196], 100_012), + }, + { + name: "long epoch with no release", + input: func() string { return "foo==" + big + "!" }, + wantText: cutSpecErr("=="+big[:198], 100_003), + }, + { + name: "non-ASCII character after the version", + input: func() string { return "foo==1." + big + "é" }, + wantText: cutSpecErr("==1."+big[:196], 100_006), + }, + { + // "é" is 2 bytes at bytes 199 and 200, so the cut moves back to 199. + name: "cut inside a multi-byte character", + input: func() string { return "foo==1." + big[:195] + "é" + big }, + wantText: cutSpecErr("==1."+big[:195], 100_201), + }, + + // The size limit is 200 bytes. + { + name: "specifier of 200 bytes is not cut", + input: func() string { return "foo==1." + big[:195] + "!" }, + wantText: `invalid version specifier "==1.` + big[:195] + `!": improper constraint: ==1.` + big[:195] + `!`, + }, + { + name: "specifier of 201 bytes is cut", + input: func() string { return "foo==1." + big[:196] + "!" }, + wantText: cutSpecErr("==1."+big[:196], 201), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := Parse(tt.input()) + require.Error(t, err) + text := err.Error() + require.Less(t, len(text), 1000, "error text is short") + assert.True(t, errors.Is(err, ErrInvalidRequirement), "want ErrInvalidRequirement") + var syntaxErr *pep508.SyntaxError + assert.False(t, errors.As(err, &syntaxErr), "not a syntax error") + assert.Equal(t, "invalid PEP 508 requirement: "+tt.wantText, text) + }) + } +} diff --git a/requirement/nesting_test.go b/requirement/nesting_test.go new file mode 100644 index 0000000..83cb66d --- /dev/null +++ b/requirement/nesting_test.go @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package requirement + +import ( + "errors" + "strings" + "testing" + + "github.com/posit-dev/go-python-packaging/internal/pep508" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + nestItem = `python_version >= "3.8"` + nestItem2 = `os_name == "posix"` + depthMsg = "nested parentheses" +) + +// Requirement text before the marker, one for each requirement form. +const ( + plainPrefix = "foo; " + specPrefix = "foo>=1.0; " + extrasPrefix = "foo[bar,baz]>=1.0,<2.0; " + urlPrefix = "foo @ https://example.com/foo-1.0-py3-none-any.whl ; " + noSpacePrefix = "foo;" + wsPrefix = " foo ; " +) + +// nested returns nestItem inside depth pairs of parentheses, with sep after +// each "(" and before each ")". +func nested(depth int, sep string) string { + return wrapDepth("", depth, "("+sep, nestItem, sep+")") +} + +// nestedAnd returns prefix, then depth levels of `(nestItem2 and )`, so +// each level holds a comparison and a deeper group. +func nestedAnd(prefix string, depth int) string { + return wrapDepth(prefix, depth, "("+nestItem2+" and ", nestItem, ")") +} + +// wrapDepth returns prefix, then depth copies of open, then inner, then depth +// copies of closing. It makes one allocation, which keeps the memory use of +// the large test inputs low. +func wrapDepth(prefix string, depth int, open, inner, closing string) string { + var b strings.Builder + b.Grow(len(prefix) + depth*(len(open)+len(closing)) + len(inner)) + b.WriteString(prefix) + for range depth { + b.WriteString(open) + } + b.WriteString(inner) + for range depth { + b.WriteString(closing) + } + return b.String() +} + +func TestParse_MarkerNesting(t *testing.T) { + const limit = pep508.MaxMarkerDepth + atLimit := nested(limit, "") + overLimit := nested(limit+1, "") + andPrefix := len("(" + nestItem2 + " and ") + + tests := []struct { + name string + // input builds the input when its case runs, so large inputs are not + // all in memory at the same time. + input func() string + // wantMarker is the expected Marker.String() on success. Empty means do not check. + wantMarker string + // wantErr is a substring of the error message. Empty means no error. + wantErr string + // wantClause is true when the error comes from the marker clause. + wantClause bool + // wantStart is the expected error start for a depth error. + wantStart int + }{ + // Inputs at or under the limit parse. + { + name: "depth 0", + input: func() string { return plainPrefix + nested(0, "") }, + wantMarker: nestItem, + }, + { + name: "depth 1", + input: func() string { return plainPrefix + nested(1, "") }, + wantMarker: nestItem, + }, + { + name: "depth 10", + input: func() string { return plainPrefix + nested(10, "") }, + wantMarker: nestItem, + }, + { + name: "depth limit-1", + input: func() string { return plainPrefix + nested(limit-1, "") }, + wantMarker: nestItem, + }, + { + name: "depth limit", + input: func() string { return plainPrefix + atLimit }, + wantMarker: nestItem, + }, + { + name: "depth limit with version specifier", + input: func() string { return specPrefix + atLimit }, + wantMarker: nestItem, + }, + { + name: "depth limit with extras and specifiers", + input: func() string { return extrasPrefix + atLimit }, + wantMarker: nestItem, + }, + { + name: "depth limit with URL", + input: func() string { return urlPrefix + atLimit }, + wantMarker: nestItem, + }, + { + name: "depth limit with no space after semicolon", + input: func() string { return noSpacePrefix + atLimit }, + wantMarker: nestItem, + }, + { + name: "depth limit with extra whitespace", + input: func() string { return wsPrefix + atLimit + " " }, + wantMarker: nestItem, + }, + { + name: "depth limit with spaces", + input: func() string { return plainPrefix + nested(limit, " ") }, + wantMarker: nestItem, + }, + { + name: "depth limit with tabs", + input: func() string { return plainPrefix + nested(limit, "\t") }, + wantMarker: nestItem, + }, + { + name: "depth limit with and at each level", + input: func() string { return nestedAnd(plainPrefix, limit) }, + }, + { + name: "two groups at limit joined by and", + input: func() string { return specPrefix + atLimit + " and " + atLimit }, + }, + { + name: "two groups at limit joined by or", + input: func() string { return specPrefix + atLimit + " or " + atLimit }, + }, + + // Inputs over the limit return the depth error at the first "(" over it. + { + name: "depth limit+1", + input: func() string { return plainPrefix + overLimit }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(plainPrefix) + limit, + }, + { + name: "depth limit+2", + input: func() string { return plainPrefix + nested(limit+2, "") }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(plainPrefix) + limit, + }, + { + name: "depth 1000", + input: func() string { return plainPrefix + nested(1000, "") }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(plainPrefix) + limit, + }, + { + name: "depth limit+1 with version specifier", + input: func() string { return specPrefix + overLimit }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(specPrefix) + limit, + }, + { + name: "depth limit+1 with extras and specifiers", + input: func() string { return extrasPrefix + overLimit }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(extrasPrefix) + limit, + }, + { + name: "depth limit+1 with URL", + input: func() string { return urlPrefix + overLimit }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(urlPrefix) + limit, + }, + { + name: "depth limit+1 with no space after semicolon", + input: func() string { return noSpacePrefix + overLimit }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(noSpacePrefix) + limit, + }, + { + name: "depth limit+1 with extra whitespace", + input: func() string { return wsPrefix + overLimit }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(wsPrefix) + limit, + }, + { + name: "depth limit+1 with spaces", + input: func() string { return plainPrefix + nested(limit+1, " ") }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(plainPrefix) + 2*limit, + }, + { + name: "depth limit+1 with and at each level", + input: func() string { return nestedAnd(plainPrefix, limit+1) }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(plainPrefix) + limit*andPrefix, + }, + { + name: "group at limit then group at limit+1", + input: func() string { return plainPrefix + atLimit + " and " + overLimit }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(plainPrefix+atLimit+" and ") + limit, + }, + { + name: "limit+1 open only", + input: func() string { return plainPrefix + strings.Repeat("(", limit+1) }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(plainPrefix) + limit, + }, + + // Before the limit, about 1.3M "(" overflowed the Go stack. That is a + // fatal crash that recover cannot catch. + { + name: "2M open only", + input: func() string { return plainPrefix + strings.Repeat("(", 2_000_000) }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(plainPrefix) + limit, + }, + { + name: "2M closed with version specifier", + input: func() string { return specPrefix + nested(2_000_000, "") }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(specPrefix) + limit, + }, + { + name: "2M open with spaces and URL", + input: func() string { return urlPrefix + strings.Repeat("( ", 2_000_000) }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(urlPrefix) + 2*limit, + }, + { + name: "2M with and at each level and extras", + input: func() string { return nestedAnd(extrasPrefix, 2_000_000) }, + wantErr: depthMsg, + wantClause: true, + wantStart: len(extrasPrefix) + limit*andPrefix, + }, + + // Other errors at or under the limit are not changed into depth errors. + { + name: "depth limit unclosed", + input: func() string { return plainPrefix + strings.Repeat("(", limit) + nestItem }, + wantErr: "Expected ')'", + wantClause: true, + }, + { + name: "depth limit open only", + input: func() string { return plainPrefix + strings.Repeat("(", limit) }, + wantErr: "Expected a marker variable", + wantClause: true, + }, + { + name: "depth limit empty group", + input: func() string { return plainPrefix + strings.Repeat("(", limit) + ")" }, + wantErr: "Expected a marker variable", + wantClause: true, + }, + { + name: "depth limit extra close", + input: func() string { return plainPrefix + atLimit + ")" }, + wantErr: "Expected end of requirement string", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + input := tt.input() + r, err := Parse(input) + if tt.wantErr == "" { + require.NoError(t, err) + assert.Equal(t, "foo", r.Name) + if tt.wantMarker != "" { + assert.Equal(t, tt.wantMarker, r.Marker.String()) + } + return + } + + require.True(t, errors.Is(err, ErrInvalidRequirement), "want ErrInvalidRequirement") + assert.Less(t, len(err.Error()), 1000, "error text is short") + var clauseErr *pep508.MarkerClauseError + assert.Equal(t, tt.wantClause, errors.As(err, &clauseErr), "error from the marker clause") + var syntaxErr *pep508.SyntaxError + require.True(t, errors.As(err, &syntaxErr), "want a *pep508.SyntaxError") + assert.Contains(t, syntaxErr.Msg, tt.wantErr) + if tt.wantErr == depthMsg { + assert.Equal(t, "Marker has more than 100 nested parentheses", syntaxErr.Msg) + assert.Equal(t, tt.wantStart, syntaxErr.Start, "error start") + assert.Equal(t, tt.wantStart+1, syntaxErr.End, "error end") + assert.Equal(t, "(", input[syntaxErr.Start:syntaxErr.End]) + } else { + assert.NotContains(t, syntaxErr.Msg, depthMsg) + } + }) + } +} diff --git a/requirement/requirement.go b/requirement/requirement.go index df916f4..9ede702 100644 --- a/requirement/requirement.go +++ b/requirement/requirement.go @@ -18,6 +18,7 @@ import ( "strings" "github.com/posit-dev/go-python-packaging/extras" + "github.com/posit-dev/go-python-packaging/internal/errtext" "github.com/posit-dev/go-python-packaging/internal/pep508" "github.com/posit-dev/go-python-packaging/marker" "github.com/posit-dev/go-python-packaging/version" @@ -36,7 +37,7 @@ import ( // *pep508.MarkerClauseError (itself wrapping a *pep508.SyntaxError from // the marker grammar specifically). // - invalid version specifier: the chain contains neither of the above - -// the error instead comes from version.NewSpecifiers. +// the error instead comes from package version. var ErrInvalidRequirement = errors.New("invalid PEP 508 requirement") // Requirement is a parsed PEP 508 dependency-specifier requirement: @@ -96,9 +97,9 @@ func Parse(s string) (Requirement, error) { } if raw.Specifier != "" { - specs, err := version.NewSpecifiers(raw.Specifier) + specs, err := parseSpecifiers(raw.Specifier) if err != nil { - return Requirement{}, fmt.Errorf("%w: invalid version specifier %q: %w", ErrInvalidRequirement, raw.Specifier, err) + return Requirement{}, fmt.Errorf("%w: invalid version specifier %s: %w", ErrInvalidRequirement, errtext.Quote(raw.Specifier), err) } req.Specifiers = specs } @@ -108,6 +109,16 @@ func Parse(s string) (Requirement, error) { return req, nil } +// extraForString returns a normalized extra in a form that parses again. An +// extra name cannot end with "-", so a trailing "-" (from an input such as +// "foo_") is written as "_", which normalizes back to the same extra. +func extraForString(e string) string { + if strings.HasSuffix(e, "-") { + return e[:len(e)-1] + "_" + } + return e +} + // String renders r in canonical PEP 508 requirement syntax; // Parse(r.String()) yields an equivalent Requirement. func (r Requirement) String() string { @@ -116,13 +127,24 @@ func (r Requirement) String() string { if len(r.Extras) > 0 { b.WriteString("[") - b.WriteString(strings.Join(r.Extras, ",")) + for i, e := range r.Extras { + if i > 0 { + b.WriteString(",") + } + b.WriteString(extraForString(e)) + } b.WriteString("]") } switch { case r.URL != "": - b.WriteString(" @ ") + // In a requirements file, " #" starts a comment and " -" starts the + // options, so a URL that starts with "#" or "-" follows "@" directly. + if strings.HasPrefix(r.URL, "#") || strings.HasPrefix(r.URL, "-") { + b.WriteString(" @") + } else { + b.WriteString(" @ ") + } b.WriteString(r.URL) case r.Specifiers.String() != "": b.WriteString(r.Specifiers.String()) @@ -142,3 +164,31 @@ func (r Requirement) String() string { return b.String() } + +// parseSpecifiers parses spec, the clauses of a version specifier that the +// tokenizer joined with ",", as one AND-group. +// +// version.NewSpecifiers reads "||" as an OR of groups. That is an extension of +// package version, not PEP 508: packaging rejects "foo>1.0||*", and reads +// "foo===a||b" as one "===" specifier with the operand "a||b". With +// NewSpecifiers alone, Parse accepted the first, rejected the second, and +// String() could write an OR that did not parse back. So when spec has "||", +// parseSpecifiers parses each clause with version.NewSpecifier. Without "||", +// NewSpecifiers makes one group from the same clauses, with fewer +// allocations. +func parseSpecifiers(spec string) (version.Specifiers, error) { + if !strings.Contains(spec, "||") { + return version.NewSpecifiers(spec) + } + specs := make([]version.Specifier, 0, strings.Count(spec, ",")+1) + for rest, more := spec, true; more; { + var clause string + clause, rest, more = strings.Cut(rest, ",") + s, err := version.NewSpecifier(clause) + if err != nil { + return version.Specifiers{}, err + } + specs = append(specs, s) + } + return version.NewSpecifiersFrom(specs), nil +} diff --git a/tags/bench_test.go b/tags/bench_test.go new file mode 100644 index 0000000..495ba60 --- /dev/null +++ b/tags/bench_test.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package tags + +import ( + "testing" + + "github.com/posit-dev/go-python-packaging/internal/allocbudget" +) + +// Benchmarks and allocation budgets for the hot paths of this package. The +// budget tests run in CI and fail on any change in allocations; the +// benchmarks are for comparing a branch with main (see CLAUDE.md, +// "Performance"). + +// benchTags are tags of common shapes. budget is the allocation budget of +// ParseTag. +var benchTags = []struct { + name, in string + budget float64 +}{ + {name: "single", in: "py3-none-any", budget: 5}, + {name: "compressed platform", in: "cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64", budget: 5}, + {name: "compressed interpreter", in: "cp38.cp39.cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64", budget: 5}, +} + +func BenchmarkParseTag(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + for _, tag := range benchTags { + if _, err := ParseTag(tag.in); err != nil { + b.Fatal(err) + } + } + } +} + +func TestAllocBudget_ParseTag(t *testing.T) { + for _, tag := range benchTags { + t.Run(tag.name, func(t *testing.T) { + if _, err := ParseTag(tag.in); err != nil { + t.Fatal(err) // the budget must not be an error path + } + allocbudget.Check(t, tag.budget, func() { _, _ = ParseTag(tag.in) }) + }) + } +} diff --git a/tags/control_chars_test.go b/tags/control_chars_test.go new file mode 100644 index 0000000..ef145a9 --- /dev/null +++ b/tags/control_chars_test.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package tags + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// controlCharacters are whitespace and control characters, ASCII and not. +var controlCharacters = map[string]string{ + "NUL": "\x00", + "start of heading": "\x01", + "tab": "\t", + "line feed": "\n", + "vertical tab": "\v", + "carriage return": "\r", + "escape": "\x1b", + "unit separator U+001F": "\x1f", + "space": " ", + "delete": "\x7f", + "no-break space U+00A0": "\u00a0", + "zero width space U+200B": "\u200b", +} + +// packaging's parse_tag splits a tag on "-" and "." only and keeps every +// other character, so a tag with a control character or whitespace parses, +// and the character stays in its field. Checked against packaging 21.0, as +// vendored in pip 21.2.4. +func TestParseTag_ControlCharacters(t *testing.T) { + for name, c := range controlCharacters { + t.Run(name, func(t *testing.T) { + got, err := ParseTag("py3" + c + "-none-any") + require.NoError(t, err) + assert.Equal(t, []Tag{{Interpreter: "py3" + c, ABI: "none", Platform: "any"}}, got) + + got, err = ParseTag("py3-none-" + c + ".any") + require.NoError(t, err) + assert.Equal(t, []Tag{ + {Interpreter: "py3", ABI: "none", Platform: c}, + {Interpreter: "py3", ABI: "none", Platform: "any"}, + }, got) + + // Only an empty value is an error. + _, err = ParseTag("py3-none-" + c + "..any") + assert.ErrorIs(t, err, ErrInvalidTag) + }) + } +} diff --git a/tags/fuzz_test.go b/tags/fuzz_test.go new file mode 100644 index 0000000..502fc06 --- /dev/null +++ b/tags/fuzz_test.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package tags_test + +import ( + "errors" + "strings" + "testing" + "time" + + "github.com/posit-dev/go-python-packaging/internal/fuzzseed" + "github.com/posit-dev/go-python-packaging/tags" +) + +func FuzzParseTag(f *testing.F) { + fuzzseed.Add(f, + "cp311-cp311-manylinux_2_17_x86_64", + "cp36.cp37-abi3-manylinux1_x86_64.manylinux2010_x86_64", + "cp36.cp37-abi3.abi4-manylinux1_x86_64", + "py2.py3-none-any", + "cp313t-cp313t-musllinux_1_2_aarch64", + "pp310-pypy310_pp73-macosx_11_0_arm64", + "cp312-cp312-win_amd64", + "py3--any", + "a-b-c-d", + ) + alts := strings.Repeat("a.", 29) + "a" + f.Add(alts + "-" + alts + "-" + alts) + + f.Fuzz(func(t *testing.T, in string) { + start := time.Now() + got, err := tags.ParseTag(in) + fuzzseed.Within(t, start, in) + if err != nil { + if !errors.Is(err, tags.ErrInvalidTag) { + t.Fatalf("ParseTag(%q) error is not ErrInvalidTag: %v", in, err) + } + return + } + if len(got) == 0 { + t.Fatalf("ParseTag(%q) returned no error and no tags", in) + } + for _, tag := range got { + if tag.Interpreter == "" || tag.ABI == "" || tag.Platform == "" { + t.Fatalf("ParseTag(%q) returned a tag with an empty field: %#v", in, tag) + } + again, err := tags.ParseTag(tag.String()) + if err != nil { + t.Fatalf("ParseTag(%q) gave %q, which does not parse: %v", in, tag, err) + } + if len(again) != 1 || again[0] != tag { + t.Fatalf("ParseTag(%q) gave %q, which parses to %v", in, tag, again) + } + } + }) +} diff --git a/tags/tag.go b/tags/tag.go index 2c75015..858b768 100644 --- a/tags/tag.go +++ b/tags/tag.go @@ -3,6 +3,7 @@ package tags import ( "errors" + "fmt" "strings" ) @@ -18,8 +19,14 @@ type Tag struct { func (t Tag) String() string { return t.Interpreter + "-" + t.ABI + "-" + t.Platform } +// maxTags is the maximum number of tags that ParseTag returns. The product of +// the three fields grows with the cube of the input length, so without a +// limit a 1.2 KB tag gives 8 million tags. Real wheels have a few dozen. +const maxTags = 10_000 + // ParseTag parses one PEP 425 tag component, expanding dot-compressed -// alternatives across all three fields as a full Cartesian product. +// alternatives across all three fields as a full Cartesian product. It returns +// an error that wraps ErrInvalidTag if the product has more than 10,000 tags. func ParseTag(s string) ([]Tag, error) { parts := strings.Split(s, "-") if len(parts) != 3 { @@ -37,6 +44,12 @@ func ParseTag(s string) ([]Tag, error) { if err != nil { return nil, err } + // Divide instead of multiply, so no product can overflow int, also where + // int is 32 bits. splitField gives at least one value for each field. + if len(abis) > maxTags/len(interps) || + len(plats) > maxTags/(len(interps)*len(abis)) { + return nil, fmt.Errorf("%w: more than %d tags", ErrInvalidTag, maxTags) + } out := make([]Tag, 0, len(interps)*len(abis)*len(plats)) for _, i := range interps { for _, a := range abis { diff --git a/tags/tag_limit_test.go b/tags/tag_limit_test.go new file mode 100644 index 0000000..187b827 --- /dev/null +++ b/tags/tag_limit_test.go @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package tags + +import ( + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/posit-dev/go-python-packaging/internal/race" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// field returns n dot-separated values: "0.1...". +func field(prefix string, n int) string { + parts := make([]string, n) + for i := range parts { + parts[i] = fmt.Sprintf("%s%d", prefix, i) + } + return strings.Join(parts, ".") +} + +// overflowTag has 2^21 values in each of its three fields, about 12 MB. +var overflowTag = func() string { + f := strings.Repeat("a.", 1<<21-1) + "a" + return f + "-" + f + "-" + f +}() + +func TestParseTag_Limit(t *testing.T) { + tests := []struct { + name string + input string + // wantTags is the number of tags on success. Zero means an error. + wantTags int + }{ + { + name: "100 x 100 x 1 is at the limit", + input: field("py", 100) + "-" + field("abi", 100) + "-any", + wantTags: maxTags, + }, + { + name: "1 x 1 x 10,000 is at the limit", + input: "py3-none-" + field("plat", maxTags), + wantTags: maxTags, + }, + { + name: "73 x 137 x 1 is 10,001, one over the limit", + input: field("py", 73) + "-" + field("abi", 137) + "-any", + }, + { + name: "1 x 1 x 10,001 is one over the limit", + input: "py3-none-" + field("plat", maxTags+1), + }, + { + // Found by hand: 200 x 200 x 200 is 8 million tags from 1.2 KB. + name: "three short fields with many values", + input: strings.Repeat("a.", 199) + "a-" + strings.Repeat("b.", 199) + "b-" + strings.Repeat("c.", 199) + "c", + }, + { + // The first two fields alone pass the limit, so the product of all + // three is never computed. + name: "first two fields are over the limit", + input: field("py", 1000) + "-" + field("abi", 1000) + "-" + field("p", 1000), + }, + { + // 2^21 values in each field make 2^63 tags, which wraps to a + // negative int64. A check that multiplies all three counts + // passes it, and make then panics. + name: "product of all three fields overflows int64", + input: overflowTag, + }, + { + // 2^16 x 2^16 is 2^32, which wraps to 0 in a 32-bit int. A check + // that multiplies the first two counts passes it there. + name: "product of the first two fields overflows int32", + input: field("py", 1<<16) + "-" + field("abi", 1<<16) + "-any", + }, + { + name: "a real compressed tag is unchanged", + input: "cp38.cp39.cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64", + wantTags: 6, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + start := time.Now() + got, err := ParseTag(tt.input) + // The race detector makes the code much slower (see package race). + if !race.Enabled { + assert.Less(t, time.Since(start), time.Second, "ParseTag stops quickly") + } + if tt.wantTags == 0 { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidTag), "want ErrInvalidTag") + assert.Contains(t, err.Error(), "more than 10000 tags") + assert.Nil(t, got) + return + } + require.NoError(t, err) + assert.Len(t, got, tt.wantTags) + }) + } +} diff --git a/version/bench_test.go b/version/bench_test.go new file mode 100644 index 0000000..da8aa68 --- /dev/null +++ b/version/bench_test.go @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "testing" + + "github.com/posit-dev/go-python-packaging/internal/allocbudget" +) + +// Benchmarks and allocation budgets for the hot paths of this package. The +// budget tests run in CI and fail on any change in allocations; the +// benchmarks are for comparing a branch with main (see CLAUDE.md, +// "Performance"). + +// benchVersions are versions of common shapes. +var benchVersions = []struct { + in string + budget float64 +}{ + {"1.0", 10}, + {"2.31.0", 14}, + {"1.0.0a1", 18}, + {"1.0.post1.dev2", 22}, + {"2!1.0+local.7", 29}, + {"1.2.3.4.5", 23}, + {" 3.11.4 ", 16}, +} + +// benchSpecifiers are specifier sets of common shapes. parse is the +// allocation budget of NewSpecifiers, and check the budget of checking all of +// benchCheckVersions against the set. +var benchSpecifiers = []struct { + in string + parse, check float64 +}{ + {in: ">=1.0,<2.0", parse: 45, check: 35}, + {in: "~=3.7", parse: 27, check: 34}, + {in: "==1.4.*", parse: 27, check: 73}, + {in: "!=1.5.0, >=1.0", parse: 49, check: 22}, + {in: "===foo", parse: 14, check: 22}, + {in: ">=1.0 || <0.5", parse: 49, check: 22}, +} + +// benchCheckVersions are the versions that the Check benchmark checks against +// each of benchSpecifiers: a release, a pre-release and a local version. +var benchCheckVersions = []string{"1.4.2", "3.1.0rc1", "1.5.0+local"} + +func BenchmarkParseVersions(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + for _, v := range benchVersions { + if _, err := Parse(v.in); err != nil { + b.Fatal(err) + } + } + } +} + +func BenchmarkNewSpecifiers(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + for _, s := range benchSpecifiers { + if _, err := NewSpecifiers(s.in); err != nil { + b.Fatal(err) + } + } + } +} + +func BenchmarkSpecifiersAnd(b *testing.B) { + left, err := NewSpecifiers(">=1.0,<2.0 || >=3.0") + if err != nil { + b.Fatal(err) + } + right, err := NewSpecifiers("!=1.5.0 || ==3.1.*") + if err != nil { + b.Fatal(err) + } + b.ReportAllocs() + for b.Loop() { + if _, err := left.And(right); err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkSpecifiersCheck(b *testing.B) { + sets, versions := parseBenchChecks(b) + b.ReportAllocs() + for b.Loop() { + for _, ss := range sets { + for _, v := range versions { + _ = ss.Check(v) + } + } + } +} + +// parseBenchChecks parses benchSpecifiers and benchCheckVersions. +func parseBenchChecks(tb testing.TB) ([]Specifiers, []Version) { + tb.Helper() + sets := make([]Specifiers, len(benchSpecifiers)) + for i, s := range benchSpecifiers { + var err error + if sets[i], err = NewSpecifiers(s.in); err != nil { + tb.Fatal(err) + } + } + versions := make([]Version, len(benchCheckVersions)) + for i, in := range benchCheckVersions { + var err error + if versions[i], err = Parse(in); err != nil { + tb.Fatal(err) + } + } + return sets, versions +} + +func TestAllocBudget_Parse(t *testing.T) { + for _, v := range benchVersions { + t.Run(v.in, func(t *testing.T) { + if _, err := Parse(v.in); err != nil { + t.Fatal(err) // the budget must not be an error path + } + allocbudget.Check(t, v.budget, func() { _, _ = Parse(v.in) }) + }) + } +} + +func TestAllocBudget_NewSpecifiers(t *testing.T) { + for _, s := range benchSpecifiers { + t.Run(s.in, func(t *testing.T) { + if _, err := NewSpecifiers(s.in); err != nil { + t.Fatal(err) // the budget must not be an error path + } + allocbudget.Check(t, s.parse, func() { _, _ = NewSpecifiers(s.in) }) + }) + } +} + +func TestAllocBudget_Check(t *testing.T) { + sets, versions := parseBenchChecks(t) + for i, s := range benchSpecifiers { + t.Run(s.in, func(t *testing.T) { + allocbudget.Check(t, s.check, func() { + for _, v := range versions { + _ = sets[i].Check(v) + } + }) + }) + } +} diff --git a/version/fuzz_test.go b/version/fuzz_test.go new file mode 100644 index 0000000..72c9abe --- /dev/null +++ b/version/fuzz_test.go @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version_test + +import ( + "strings" + "testing" + "time" + + "github.com/posit-dev/go-python-packaging/internal/fuzzseed" + "github.com/posit-dev/go-python-packaging/version" +) + +var versionSeeds = []string{ + "1.0", "1.0.0", "v1.2.3", "1!2.0", "1.0a1", "1.0b2", "1.0rc3", "1.0c1", + "1.0.post1", "1.0-1", "1.0.dev0", "1.0a1.post2.dev3", "1.0+local.7", + "1.0+ubuntu-1", " 1.0 ", "1.0-alpha_1", "1.0.POST", "0", "2024.10.1", + "1.0+abc.5.xyz", "2.4.0+cu121", +} + +var specifierSeeds = []string{ + ">=1.0", "==1.0.*", "!=1.1.*", "~=1.4.2", "===lolwat", "<2", ">1.0.post1", + "== 1.0", ">= v1.0 ", "1.0", "<=1!2.0", "==1.0+local", "~=1", ">1.0a1", +} + +var specifiersSeeds = []string{ + "", ">=1.0,<2", "~=1.4.2, !=1.4.5", ">=1.0, ==1.*, !=1.5", "==1.0 || ==2.0", + "<2, >=1.0a1", " >= 1.0 , < 2.0 ", ",", ">=1,", "===foo, >1", +} + +// addLarge adds large version-shaped seeds. +func addLarge(f *testing.F, prefix string) { + f.Add(prefix + strings.Repeat("9", 5000)) + f.Add(prefix + "1." + strings.Repeat("0.", 5000) + "1") + f.Add(prefix + "1" + strings.Repeat(".post1", 2000)) + f.Add(prefix + "1+" + strings.Repeat("a.", 5000) + "a") + f.Add(prefix + "18446744073709551616!1.0") + f.Add(prefix + "1.0.post18446744073709551616") +} + +func FuzzParse(f *testing.F) { + fuzzseed.Add(f, versionSeeds...) + addLarge(f, "") + + f.Fuzz(func(t *testing.T, in string) { + start := time.Now() + v, err := version.Parse(in) + fuzzseed.Within(t, start, in) + if err != nil { + return + } + rendered := v.String() + if rendered == "" { + t.Fatalf("Parse(%q) returned no error and an empty version", in) + } + again, err := version.Parse(rendered) + if err != nil { + t.Fatalf("Parse(%q).String() = %q, which does not parse: %v", in, rendered, err) + } + if got := again.String(); got != rendered { + t.Fatalf("round trip of %q: %q, then %q", in, rendered, got) + } + if c := v.Compare(again); c != 0 || !v.Equal(again) { + t.Fatalf("Parse(%q) and its round trip %q compare as %d", in, rendered, c) + } + _ = v.ReleaseKey() + _ = v.BaseVersion() + _ = v.Public() + }) +} + +// FuzzCompare checks that Compare is a consistent total order. +func FuzzCompare(f *testing.F) { + for i, a := range versionSeeds { + f.Add(a, versionSeeds[(i+1)%len(versionSeeds)], versionSeeds[(i+5)%len(versionSeeds)]) + } + f.Add("1.0", "1.0.0", "1.0.0.0") + f.Add("1.0a1", "1.0", "1.0.post1") + f.Add("1.0.dev0", "1.0a1.dev0", "1.0+local") + f.Add("18446744073709551616", "18446744073709551615", "9223372036854775808") + + f.Fuzz(func(t *testing.T, a, b, c string) { + va, errA := version.Parse(a) + vb, errB := version.Parse(b) + vc, errC := version.Parse(c) + if errA != nil || errB != nil || errC != nil { + return + } + if va.Compare(va) != 0 { + t.Fatalf("Compare(%q, %q) != 0", a, a) + } + ab, ba := va.Compare(vb), vb.Compare(va) + if ab != -ba { + t.Fatalf("Compare(%q, %q) = %d but Compare(%q, %q) = %d", a, b, ab, b, a, ba) + } + if ab <= 0 && vb.Compare(vc) <= 0 && va.Compare(vc) > 0 { + t.Fatalf("not transitive: %q <= %q <= %q but %q > %q", a, b, c, a, c) + } + if va.Equal(vb) != (ab == 0) { + t.Fatalf("Equal(%q, %q) = %v but Compare = %d", a, b, va.Equal(vb), ab) + } + }) +} + +func FuzzNewSpecifier(f *testing.F) { + fuzzseed.Add(f, specifierSeeds...) + addLarge(f, "==") + addLarge(f, "~=") + + f.Fuzz(func(t *testing.T, in string) { + start := time.Now() + s, err := version.NewSpecifier(in) + fuzzseed.Within(t, start, in) + if err != nil { + return + } + rendered := s.String() + if rendered == "" { + t.Fatalf("NewSpecifier(%q) returned no error and an empty specifier", in) + } + again, err := version.NewSpecifier(rendered) + if err != nil { + t.Fatalf("NewSpecifier(%q).String() = %q, which does not parse: %v", in, rendered, err) + } + if got := again.String(); got != rendered { + t.Fatalf("round trip of %q: %q, then %q", in, rendered, got) + } + if !s.Equal(again) { + t.Fatalf("NewSpecifier(%q) is not Equal to its round trip %q", in, rendered) + } + for _, v := range []string{"0", "1.0", "1.0a1", "2.0.post1", "1!1.0+local"} { + _ = s.Contains(v) + } + }) +} + +func FuzzNewSpecifiers(f *testing.F) { + fuzzseed.Add(f, specifiersSeeds...) + f.Add(strings.Repeat(">=1.0,", 5000) + "<2") + f.Add(strings.Repeat("==1.0 || ", 5000) + "==2") + f.Add(strings.Repeat(",", 5000)) + + f.Fuzz(func(t *testing.T, in string) { + start := time.Now() + ss, err := version.NewSpecifiers(in) + fuzzseed.Within(t, start, in) + if err != nil { + return + } + rendered := ss.String() + again, err := version.NewSpecifiers(rendered) + if err != nil { + t.Fatalf("NewSpecifiers(%q).String() = %q, which does not parse: %v", in, rendered, err) + } + if got := again.String(); got != rendered { + t.Fatalf("round trip of %q: %q, then %q", in, rendered, got) + } + if !ss.Equal(again) || ss.Len() != again.Len() { + t.Fatalf("NewSpecifiers(%q) is not Equal to its round trip %q", in, rendered) + } + }) +} + +// FuzzSpecifiersContains checks that the string and Version forms of +// Contains agree. "===" is left out: it compares text, as upstream does. +func FuzzSpecifiersContains(f *testing.F) { + for i, s := range specifiersSeeds { + f.Add(s, versionSeeds[i%len(versionSeeds)]) + } + f.Add(">=1.0a1", "1.0a2") + f.Add("==1.0.*", "1.0.post1") + f.Add("~=1.4.2", "1.4.99999999999999999999") + f.Add(">=1.0,!=1.5.*", "1.5.0+local") + + f.Fuzz(func(t *testing.T, spec, ver string) { + ss, err := version.NewSpecifiers(spec) + if err != nil || strings.Contains(spec, "===") { + return + } + v, err := version.Parse(ver) + if err != nil { + _ = ss.Contains(ver) + return + } + start := time.Now() + byString := ss.Contains(ver) + byVersion := ss.ContainsVersion(v) + _ = ss.Check(v) + fuzzseed.Within(t, start, spec+ver) + if byString != byVersion { + t.Fatalf("NewSpecifiers(%q): Contains(%q) = %v but ContainsVersion = %v", spec, ver, byString, byVersion) + } + }) +} diff --git a/version/limits_test.go b/version/limits_test.go new file mode 100644 index 0000000..88b6b41 --- /dev/null +++ b/version/limits_test.go @@ -0,0 +1,542 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "errors" + "runtime" + "strconv" + "strings" + "testing" + "time" + + "github.com/posit-dev/go-python-packaging/internal/race" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// A number in a version may have at most maxNumberDigits digits, the same +// default limit as Python's int(). +func TestParse_NumberDigitLimit(t *testing.T) { + atLimit := "1" + strings.Repeat("0", maxNumberDigits-1) + overLimit := atLimit + "0" + // zerosThenOne has maxNumberDigits+1 digits, but its value is 1. + zerosThenOne := strings.Repeat("0", maxNumberDigits) + "1" + + tests := []struct { + name string + input string + wantErr bool + }{ + {name: "release part at the limit", input: atLimit}, + {name: "release part over the limit", input: overLimit, wantErr: true}, + {name: "second release part over the limit", input: "1." + overLimit, wantErr: true}, + {name: "epoch at the limit", input: atLimit + "!1.0"}, + {name: "epoch over the limit", input: overLimit + "!1.0", wantErr: true}, + {name: "pre-release number over the limit", input: "1.0a" + overLimit, wantErr: true}, + {name: "post-release number over the limit", input: "1.0.post" + overLimit, wantErr: true}, + {name: "implicit post-release number over the limit", input: "1.0-" + overLimit, wantErr: true}, + {name: "dev number over the limit", input: "1.0.dev" + overLimit, wantErr: true}, + {name: "numeric local segment at the limit", input: "1.0+" + atLimit}, + {name: "numeric local segment over the limit", input: "1.0+abc." + overLimit, wantErr: true}, + {name: "numeric local segment after a dash over the limit", input: "1.0+abc-" + overLimit, wantErr: true}, + { + // packaging keeps a local segment that is not all digits as a + // string, so it has no digit limit. + name: "alphanumeric local segment is not limited", + input: "1.0+a" + overLimit, + }, + { + // The digits are counted as written, as Python's int() counts them. + name: "leading zeros count", + input: strings.Repeat("0", maxNumberDigits) + "1", + wantErr: true, + }, + + // The results of the rows below were checked with packaging 24.1 on + // Python 3.13, where int() has the same limit. + + // At the limit, for the numbers above that have only a row over it. + { + name: "pre-release number at the limit", + input: "1.0a" + atLimit, + }, + { + name: "post-release number at the limit", + input: "1.0.post" + atLimit, + }, + { + name: "implicit post-release number at the limit", + input: "1.0-" + atLimit, + }, + { + name: "dev number at the limit", + input: "1.0.dev" + atLimit, + }, + + // Other spellings of the pre-release, post-release and dev parts. + { + name: "alpha spelling over the limit", + input: "1.0alpha" + overLimit, + wantErr: true, + }, + { + name: "beta spelling with a dot over the limit", + input: "1.0.beta" + overLimit, + wantErr: true, + }, + { + name: "rc spelling over the limit", + input: "1.0rc" + overLimit, + wantErr: true, + }, + { + name: "c spelling over the limit", + input: "1.0c" + overLimit, + wantErr: true, + }, + { + name: "pre spelling with a dash over the limit", + input: "1.0-pre" + overLimit, + wantErr: true, + }, + { + name: "rev spelling over the limit", + input: "1.0.rev" + overLimit, + wantErr: true, + }, + { + name: "r spelling over the limit", + input: "1.0r" + overLimit, + wantErr: true, + }, + { + name: "post with an underscore over the limit", + input: "1.0_post" + overLimit, + wantErr: true, + }, + { + name: "dev with a dash over the limit", + input: "1.0-dev" + overLimit, + wantErr: true, + }, + + // Later release parts. + { + name: "third release part over the limit", + input: "1.2." + overLimit, + wantErr: true, + }, + { + // The limit is for each number, not for the whole release. + name: "two release parts at the limit", + input: atLimit + "." + atLimit, + }, + + // Text around the version. + { + name: "leading v at the limit", + input: "v" + atLimit, + }, + { + name: "leading v over the limit", + input: "v" + overLimit, + wantErr: true, + }, + { + name: "whitespace around a number over the limit", + input: " " + overLimit + "\t", + wantErr: true, + }, + + // Local segments. + { + name: "single numeric local segment over the limit", + input: "1.0+" + overLimit, + wantErr: true, + }, + { + name: "numeric local segment before text over the limit", + input: "1.0+" + overLimit + ".abc", + wantErr: true, + }, + { + name: "numeric local segment after an underscore over the limit", + input: "1.0+abc_" + overLimit, + wantErr: true, + }, + { + name: "upper-case local text, then a numeric segment over the limit", + input: "1.0+ABC." + overLimit, + wantErr: true, + }, + + // Leading zeros count in each kind of number. + { + name: "leading zeros in a local segment", + input: "1.0+" + zerosThenOne, + wantErr: true, + }, + { + name: "leading zeros in a pre-release number", + input: "1.0a" + zerosThenOne, + wantErr: true, + }, + { + name: "leading zeros in an epoch", + input: zerosThenOne + "!1.0", + wantErr: true, + }, + + { + // No single number is over the limit, so the version is valid, + // although it has about 30,000 digits. + name: "every number at the limit", + input: atLimit + "!" + atLimit + "." + atLimit + "a" + atLimit + + ".post" + atLimit + ".dev" + atLimit + "+" + atLimit, + }, + { + // Before the limit, this allocated GBs in math/big. + name: "a million digits", + input: "1" + strings.Repeat("7", 1_000_000), + wantErr: true, + }, + } + + // Parse must reject a long number before math/big reads it. Without the + // limit, "a million digits" allocates about 2 GB, but takes less than 1 s + // on a fast machine, so this checks the bytes allocated, not the time. The + // largest row allocates about 350 KB, also under -race. + const maxAlloc = 4 << 20 + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + _, err := Parse(tt.input) + runtime.ReadMemStats(&after) + assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(maxAlloc), "bytes allocated") + if !tt.wantErr { + require.NoError(t, err) + return + } + require.Error(t, err) + require.Less(t, len(err.Error()), 1000, "error text is short") + assert.Contains(t, err.Error(), "a number has more than 4300 digits") + }) + } +} + +// The version of a specifier goes through Parse, so the same limit applies, +// for each operator and each number of the version. The results match +// packaging 24.1 on Python 3.13, where int() has the same limit. +func TestNewSpecifiers_NumberDigitLimit(t *testing.T) { + atLimit := strings.Repeat("1", maxNumberDigits) + overLimit := atLimit + "1" + + tests := []struct { + name string + input string + wantErr bool + }{ + // The release segment. + { + name: "second release part at the limit", + input: ">=1." + atLimit, + }, + { + name: "second release part over the limit", + input: ">=1." + overLimit, + wantErr: true, + }, + { + name: "first release part at the limit", + input: ">=" + atLimit, + }, + { + name: "first release part over the limit", + input: ">=" + overLimit, + wantErr: true, + }, + { + // The digits are counted as written, as Python's int() counts them. + name: "leading zeros count", + input: "==" + strings.Repeat("0", maxNumberDigits) + "1", + wantErr: true, + }, + + // Each operator. + { + name: "equal over the limit", + input: "==" + overLimit, + wantErr: true, + }, + { + name: "not equal over the limit", + input: "!=" + overLimit, + wantErr: true, + }, + { + name: "less than over the limit", + input: "<" + overLimit, + wantErr: true, + }, + { + name: "less than or equal over the limit", + input: "<=" + overLimit, + wantErr: true, + }, + { + name: "greater than over the limit", + input: ">" + overLimit, + wantErr: true, + }, + { + name: "compatible release at the limit", + input: "~=1." + atLimit, + }, + { + name: "compatible release over the limit", + input: "~=1." + overLimit, + wantErr: true, + }, + { + // The ".*" is removed before Parse. + name: "prefix match at the limit", + input: "==1." + atLimit + ".*", + }, + { + name: "prefix match over the limit", + input: "==1." + overLimit + ".*", + wantErr: true, + }, + + // The other numbers of a version. + { + name: "epoch over the limit", + input: "==" + overLimit + "!1.0", + wantErr: true, + }, + { + name: "pre-release number over the limit", + input: "==1.0a" + overLimit, + wantErr: true, + }, + { + name: "post-release number over the limit", + input: "==1.0.post" + overLimit, + wantErr: true, + }, + { + name: "dev number over the limit", + input: "==1.0.dev" + overLimit, + wantErr: true, + }, + { + name: "numeric local segment over the limit", + input: "==1.0+" + overLimit, + wantErr: true, + }, + { + // packaging keeps a local segment that is not all digits as a + // string, so it has no digit limit. + name: "alphanumeric local segment is not limited", + input: "==1.0+a" + overLimit, + }, + + // Arbitrary equality. + { + // The operand of "===" is a string, not a version, so it has no + // digit limit. packaging 24.1 fails on this input only because + // other code, such as canonicalize_version, parses the operand as + // a version and lets the int() ValueError through. + name: "arbitrary equality is not limited", + input: "===" + overLimit, + }, + + // More than one specifier. + { + name: "second specifier over the limit", + input: ">=1.0, <" + overLimit, + wantErr: true, + }, + { + // "||" is this package's own syntax. packaging has no OR. + name: "second OR group over the limit", + input: ">=1.0 || ==" + overLimit, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := NewSpecifiers(tt.input) + if !tt.wantErr { + require.NoError(t, err) + return + } + require.Error(t, err) + require.Less(t, len(err.Error()), 1000, "error text is short") + assert.Contains(t, err.Error(), "a number has more than 4300 digits") + }) + } +} + +// setWithOrGroups returns a specifier set with n OR groups. +func setWithOrGroups(t *testing.T, n int) Specifiers { + t.Helper() + parts := make([]string, n) + for i := range parts { + parts[i] = "==" + strconv.Itoa(i) + ".0" + } + s, err := NewSpecifiers(strings.Join(parts, "||")) + require.NoError(t, err) + return s +} + +// And makes one OR group for each pair of groups, so when both sets have more +// than one group, the result may have at most maxOrGroups groups. A set with +// one group does not make the count grow, so it has no limit. +func TestSpecifiersAnd_OrGroupLimit(t *testing.T) { + tests := []struct { + name string + left, right int + wantGroups int + }{ + {name: "100 x 100 is at the limit", left: 100, right: 100, wantGroups: maxOrGroups}, + {name: "2 x 5,000 is at the limit", left: 2, right: maxOrGroups / 2, wantGroups: maxOrGroups}, + {name: "100 x 101 is over the limit", left: 100, right: 101}, + {name: "2 x 5,001 is over the limit", left: 2, right: maxOrGroups/2 + 1}, + {name: "2,000 x 2,000 is over the limit", left: 2000, right: 2000}, + {name: "small sets are unchanged", left: 2, right: 3, wantGroups: 6}, + + // One group on either side keeps the count of the other side. + {name: "1 x 10,000", left: 1, right: maxOrGroups, wantGroups: maxOrGroups}, + {name: "1 x 10,001", left: 1, right: maxOrGroups + 1, wantGroups: maxOrGroups + 1}, + {name: "20,000 x 1", left: 2 * maxOrGroups, right: 1, wantGroups: 2 * maxOrGroups}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + left, right := setWithOrGroups(t, tt.left), setWithOrGroups(t, tt.right) + start := time.Now() + got, err := left.And(right) + // The race detector makes the code much slower (see package race). + if !race.Enabled { + assert.Less(t, time.Since(start), 5*time.Second, "And stops quickly") + } + if tt.wantGroups == 0 { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrTooManyOrGroups), "want ErrTooManyOrGroups") + return + } + require.NoError(t, err) + assert.Len(t, got.orGroups(), tt.wantGroups) + }) + } +} + +// Each And multiplies the group counts, so a chain of small sets reaches the +// limit too. +func TestSpecifiersAnd_ChainReachesLimit(t *testing.T) { + ten := setWithOrGroups(t, 10) + s := ten + for range 3 { + var err error + s, err = s.And(ten) + require.NoError(t, err) + } + assert.Len(t, s.orGroups(), maxOrGroups) + + _, err := s.And(setWithOrGroups(t, 2)) + assert.True(t, errors.Is(err, ErrTooManyOrGroups), "want ErrTooManyOrGroups") +} + +// A set with more OR groups than the limit, which NewSpecifiers allows, can +// still be combined with an empty set or a set with one group. Before, both +// returned ErrTooManyOrGroups. +func TestSpecifiersAnd_LargeSetWithOneGroup(t *testing.T) { + big := setWithOrGroups(t, maxOrGroups+1) + empty, err := NewSpecifiers("") + require.NoError(t, err) + one, err := NewSpecifiers(">=1.0") + require.NoError(t, err) + + for name, other := range map[string]Specifiers{"empty": empty, "one group": one} { + t.Run(name, func(t *testing.T) { + got, err := big.And(other) + require.NoError(t, err) + assert.Len(t, got.orGroups(), maxOrGroups+1) + + got, err = other.And(big) + require.NoError(t, err) + assert.Len(t, got.orGroups(), maxOrGroups+1) + }) + } +} + +// setWithSizedGroups returns a set of n OR groups of size specifiers each. All +// the specifiers are different, as "!=major.k", so And removes no duplicates. +// n = 0 gives the empty set. +func setWithSizedGroups(t *testing.T, n, size, major int) Specifiers { + t.Helper() + groups := make([]string, n) + k := 0 + for i := range groups { + members := make([]string, size) + for j := range members { + members[j] = "!=" + strconv.Itoa(major) + "." + strconv.Itoa(k) + k++ + } + groups[i] = strings.Join(members, ",") + } + s, err := NewSpecifiers(strings.Join(groups, "||")) + require.NoError(t, err) + return s +} + +// And copies all the specifiers of both groups into each result group, so the +// result may have at most maxAndSpecifiers specifiers, or as many as the two +// sets together when that is more. The OR group limit does not see the size +// of each group. +func TestSpecifiersAnd_SpecifierLimit(t *testing.T) { + type side struct{ groups, size int } + tests := []struct { + name string + left, right side + wantSpecifiers int + }{ + // 2 x 5,000 is at the OR group limit, but each group has 2,001 + // specifiers: 20,010,000 in all. + {name: "2 groups of 2,000 and 5,000 groups of 1", left: side{2, 2000}, right: side{maxOrGroups / 2, 1}}, + // A set with one group has no OR group limit: 4,020,000 in all. + {name: "1 group of 200 and 20,000 groups of 1", left: side{1, 200}, right: side{20_000, 1}}, + {name: "1 group of 4 and 20,000 groups of 1 is at the limit", left: side{1, 4}, right: side{20_000, 1}, wantSpecifiers: maxAndSpecifiers}, + {name: "1 group of 4 and 20,001 groups of 1 is over the limit", left: side{1, 4}, right: side{20_001, 1}}, + {name: "small sets are unchanged", left: side{2, 3}, right: side{3, 2}, wantSpecifiers: 2*3*3 + 3*2*2}, + + // A result no larger than the input has no limit. + {name: "1 group of 60,000 and 1 group of 60,000", left: side{1, 60_000}, right: side{1, 60_000}, wantSpecifiers: 120_000}, + {name: "empty set and 1 group of 120,000", left: side{0, 0}, right: side{1, 120_000}, wantSpecifiers: 120_000}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + left := setWithSizedGroups(t, tt.left.groups, tt.left.size, 1) + right := setWithSizedGroups(t, tt.right.groups, tt.right.size, 2) + start := time.Now() + got, err := left.And(right) + // The race detector makes the code much slower (see package race). + if !race.Enabled { + assert.Less(t, time.Since(start), 5*time.Second, "And stops quickly") + } + if tt.wantSpecifiers == 0 { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrTooManySpecifiers), "want ErrTooManySpecifiers") + return + } + require.NoError(t, err) + assert.Equal(t, tt.wantSpecifiers, countSpecifiers(got.orGroups())) + }) + } +} diff --git a/version/long_input_test.go b/version/long_input_test.go new file mode 100644 index 0000000..3376195 --- /dev/null +++ b/version/long_input_test.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version_test + +import ( + "strings" + "testing" + + "github.com/posit-dev/go-python-packaging/version" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// An error for a long input quotes only the start of the input. +func TestLongInputErrorText(t *testing.T) { + const hugeLen = 2_000_000 + big := strings.Repeat("a", hugeLen) + commas := strings.Repeat(",", hugeLen) + + tests := []struct { + name string + parse func() error + // wantText is a substring of the error text. + wantText string + }{ + { + name: "Parse with a bad version", + parse: func() error { + _, err := version.Parse(big) + return err + }, + wantText: "malformed version: " + big[:200] + "... (2000000 bytes)", + }, + { + name: "NewSpecifier with a bad specifier", + parse: func() error { + _, err := version.NewSpecifier("==" + big) + return err + }, + wantText: "improper specifier: ==" + big[:198] + "... (2000002 bytes)", + }, + { + name: "NewSpecifiers with a bad constraint", + parse: func() error { + _, err := version.NewSpecifiers("==" + big) + return err + }, + wantText: "improper constraint: ==" + big[:198] + "... (2000002 bytes)", + }, + { + name: "NewSpecifiers with an empty || segment", + parse: func() error { + _, err := version.NewSpecifiers("==1.0 || || ==" + big) + return err + }, + wantText: `improper constraint: empty || segment in "==1.0 || || ==` + big[:186] + `"... (2000014 bytes)`, + }, + { + name: "NewSpecifiers with a segment of only commas", + parse: func() error { + _, err := version.NewSpecifiers("==1.0 || " + commas) + return err + }, + // The segment keeps the space after "||". + wantText: `improper constraint: " ` + commas[:199] + `"... (2000001 bytes) has no constraints in it`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.parse() + require.Error(t, err) + text := err.Error() + require.Less(t, len(text), 1000, "error text is short") + assert.Contains(t, text, tt.wantText) + }) + } +} diff --git a/version/operand_cache_test.go b/version/operand_cache_test.go new file mode 100644 index 0000000..873fe98 --- /dev/null +++ b/version/operand_cache_test.go @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "reflect" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Check uses two shortcuts that save a parse on each call: the operand that +// newSpecifier parsed, and publicVersion, which returns a version with no +// local segment as it is. These tests hold each shortcut to the parse it +// replaces. + +// sampledGrid is every step-th version of the packed grid, which has 338,688. +// The steps used here, 37 and 499, still reach every epoch, release, pre, +// post, dev and local value of the grid. +func sampledGrid(tb testing.TB, step int) []Version { + tb.Helper() + grid := gridVersions(tb) + out := make([]Version, 0, len(grid)/step+1) + for i := 0; i < len(grid); i += step { + out = append(out, grid[i]) + } + return out +} + +func TestPublicVersionMatchesReparse(t *testing.T) { + for _, v := range sampledGrid(t, 37) { + got, ok := v.publicVersion() + want, wantOK := parseOperand(v.Public()) + require.Equal(t, wantOK, ok, v.Original()) + // original is the text that was parsed, which is all that may differ. + got.original, want.original = "", "" + if !reflect.DeepEqual(got, want) { + t.Fatalf("publicVersion of %q is %q, but Parse(Public()) is %q", v.Original(), got, want) + } + } + + _, ok := Version{}.publicVersion() + assert.False(t, ok, "a zero-value Version has no public version") +} + +func TestSpecifierCachedOperandMatchesParse(t *testing.T) { + operands := []string{ + "0", "1", "1.0", "1.0.0", "01.0", "v1.0", "1.0.*", "1.*", "0!1.0", "1!1.0", "1!1.*", + "1.0a1", "1.0A1", "1.0b2", "1.0rc1", "1.0c1", "1.0pre1", "1.0.dev1", "1.0dev", "1.0.post1", + "1.0-1", "1.0.post1.dev2", "1.0a1.post1.dev1", "1.0+abc", "1.0+abc.1", "1.0+1", "2.31.0.20240406", + "1.2.3.4.5.6.7", "4294967296.1", "1.0a1048576", + } + operators := []string{"", "=", "==", "!=", "<", "<=", ">", ">=", "~=", "==="} + versions := sampledGrid(t, 499) + + built := 0 + for _, op := range operators { + for _, operand := range operands { + s, err := NewSpecifier(op + operand) + if err != nil { + continue // not a valid specifier, so there is nothing to cache + } + built++ + if op == "===" { + require.Nil(t, s.parsed, "=== has no version to cache") + } else { + require.NotNil(t, s.parsed, "%s%s must cache its operand", op, operand) + } + uncached := s + uncached.parsed = nil + for _, v := range versions { + if got, want := s.Check(v), uncached.Check(v); got != want { + t.Fatalf("(%s%s).Check(%q) is %v with the cached operand, %v without", op, operand, v.Original(), got, want) + } + } + } + } + // Most pairs are valid. A low count means the table stopped testing. + require.Greater(t, built, 200) +} diff --git a/version/sanitizer_error_test.go b/version/sanitizer_error_test.go new file mode 100644 index 0000000..fc2233a --- /dev/null +++ b/version/sanitizer_error_test.go @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version_test + +import ( + "strings" + "testing" + + "github.com/posit-dev/go-python-packaging/version" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// A sanitizer can change a valid operand into one that is not a version. The +// error then shows the version text once, not empty parentheses. +func TestNewSpecifiersWithSanitizer_BadVersionErrorText(t *testing.T) { + big := strings.Repeat("a", 2_000_000) + + tests := []struct { + name string + input string + sanitized string + wantErr string + }{ + { + name: "bad version", + input: "==1.0", + sanitized: "not a version", + wantErr: "version parse error: malformed version: not a version", + }, + { + // The ".*" is removed before the version is parsed. + name: "bad version with a wildcard", + input: "==1.0.*", + sanitized: "bad.*", + wantErr: "version parse error: malformed version: bad", + }, + { + name: "long bad version", + input: ">=1.0", + sanitized: big, + wantErr: "version parse error: malformed version: " + big[:200] + "... (2000000 bytes)", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sanitizer := func(string) string { return tt.sanitized } + _, err := version.NewSpecifiersWithSanitizer(tt.input, sanitizer) + require.Error(t, err) + require.Less(t, len(err.Error()), 1000, "error text is short") + assert.Equal(t, tt.wantErr, err.Error()) + }) + } +} diff --git a/version/specifier.go b/version/specifier.go index c4fd943..d569942 100644 --- a/version/specifier.go +++ b/version/specifier.go @@ -21,6 +21,9 @@ import ( "regexp" "slices" "strings" + + "github.com/posit-dev/go-python-packaging/internal/errtext" + "github.com/posit-dev/go-python-packaging/internal/pyspace" ) var ( @@ -78,15 +81,16 @@ func init() { // operand; every other operator keeps the version-shaped operand. The // arbitrary branch is FIRST because Go's regexp is leftmost-first and // "===" must not be decomposed into "==" + "=". - const arbitraryOperand = `[^\s,;)]+` + const arbitraryOperand = `[^` + pyspace.Chars + `,;)]+` - // ⚠️ The whitespace class must be [\s\v], not \s. Go's \s is [\t\n\f\r ] - // and EXCLUDES the vertical tab (0x0B); Python's re \s is [ \t\n\r\f\v] and - // includes it. With a bare \s, the operator/operand separator would not + // ⚠️ The whitespace class must be Python's "\s" (pyspace.Class), not Go's + // \s. Go's \s is [\t\n\f\r ]; packaging's pattern runs on a str, where \s + // also matches the vertical tab, U+001C to U+001F, and Unicode whitespace + // such as U+00A0. With a bare \s, the operator/operand separator would not // match "\v", so `<= \r \f \v v1.0` was rejected while pypa/packaging - // accepts it. versionRegex was already fixed for this; the specifier - // patterns were not. - const wsp = `[\s\v]` + // accepts it, and the same for `>=\u00a01.0`. versionRegex uses the same + // class. + const wsp = pyspace.Class specifierRegexp = regexp.MustCompile( fmt.Sprintf( @@ -159,7 +163,7 @@ func init() { // One rule, one copy. A singular constructor validating with the plural // grammar is a coupling that breaks silently whenever the plural grammar // moves, which is exactly how this was introduced. - // ⚠️ Uses the same (?i) flag and the same [\s\v] whitespace class as + // ⚠️ Uses the same (?i) flag and the same whitespace class (wsp) as // validConstraintRegexp above. The two grammars are deliberately independent // about COMMAS and must stay identical about everything else -- if the // singular one were case-sensitive, `NewSpecifier("==1.0DEV")` would be @@ -172,7 +176,27 @@ func init() { prefixRegexp = regexp.MustCompile(`^([0-9]+)((?:a|b|c|rc)[0-9]+)$`) } -type operatorFunc func(v Version, c string) bool +type operatorFunc func(v Version, spec operand) bool + +// operand is what an operatorFunc compares a version against: a specifier's +// operand text and, when the specifier was built by newSpecifier, its parse. +type operand struct { + text string + // version is Parse(text), without the ".*" of a wildcard operand. It is + // nil for "===", whose operand is not a version, and for a Specifier built + // by hand. + version *Version +} + +// parse returns Parse(text), from the cached parse when there is one. text is +// o.text, or o.text without its ".*" for a wildcard operand: the text that +// newSpecifier parsed. +func (o operand) parse(text string) (Version, bool) { + if o.version != nil { + return *o.version, true + } + return parseOperand(text) +} type Specifiers struct { specifiers [][]Specifier @@ -205,6 +229,11 @@ type Specifier struct { original string // fn is the matching function for op. fn operatorFunc + // parsed is operand parsed as a version, without the ".*" of a wildcard. + // newSpecifier parses it once, so that Check does not parse it on each + // call. It is nil for "===" and for a Specifier built by hand. A Version + // is never changed after Parse, so the pointer is safe to share. + parsed *Version // pre is the pre-release policy this specifier was built with, before // autodetection. PreReleasesAuto means "not set"; PreReleases resolves it. pre PreReleases @@ -250,7 +279,7 @@ func newRSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOp var sss [][]Specifier for _, vv := range segments { - if strings.TrimSpace(vv) == "*" { + if pyspace.Trim(vv) == "*" { vv = ">=0.0.0" } vv = strings.ReplaceAll(vv, "-", ".") @@ -292,7 +321,7 @@ func newSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOpt var sss [][]Specifier for _, vv := range segments { - if strings.TrimSpace(vv) == "*" { + if pyspace.Trim(vv) == "*" { vv = ">=0.0.0" } @@ -332,15 +361,17 @@ func newSpecifiers(v string, sanitizer func(string) string, opts ...SpecifierOpt // specifically about the "||" boundary: comma handling inside a group is a // separate question, decided in parseGroup. func splitOrSegments(v string) (segments []string, universal bool, err error) { - if strings.TrimSpace(v) == "" { + if pyspace.Trim(v) == "" { return nil, true, nil } segments = strings.Split(v, "||") for _, segment := range segments { - if strings.TrimSpace(segment) == "" { + if pyspace.Trim(segment) == "" { return nil, false, fmt.Errorf( - "improper constraint: empty || segment in %q (a leading, trailing or doubled || is not allowed)", v) + "improper constraint: empty || segment in %s (a leading, trailing or doubled || is not allowed)", + errtext.Quote(v), + ) } } return segments, false, nil @@ -391,7 +422,7 @@ func NewSpecifier(s string, opts ...SpecifierOption) (Specifier, error) { // FindStringSubmatch would happily match a prefix; the anchored grammar is // what makes the whole input have to be one specifier. if !singleConstraintRegexp.MatchString(s) { - return Specifier{}, fmt.Errorf("improper specifier: %s", s) + return Specifier{}, fmt.Errorf("improper specifier: %s", errtext.Cut(s)) } // Belt and braces: the anchored grammar already guarantees one constraint, so // this only fires if the grammar and the scanner ever disagree about where a @@ -399,7 +430,7 @@ func NewSpecifier(s string, opts ...SpecifierOption) (Specifier, error) { // parse rather than an error. found := specifierRegexp.FindAllString(s, -1) if len(found) != 1 { - return Specifier{}, fmt.Errorf("improper specifier: %s", s) + return Specifier{}, fmt.Errorf("improper specifier: %s", errtext.Cut(s)) } return newSpecifier(found[0], func(v string) string { return v }, *c) @@ -452,7 +483,7 @@ func parseGroup(vv string, sanitizer func(string) string, allowEmpty bool) ([]Sp // Drop blank comma-separated items, as upstream does. items := make([]string, 0, strings.Count(vv, ",")+1) for _, item := range strings.Split(vv, ",") { - if strings.TrimSpace(item) == "" { + if pyspace.Trim(item) == "" { continue } items = append(items, item) @@ -461,7 +492,7 @@ func parseGroup(vv string, sanitizer func(string) string, allowEmpty bool) ([]Sp if len(items) == 0 { if !allowEmpty { return nil, fmt.Errorf( - "improper constraint: %q has no constraints in it (an empty || segment is not allowed)", vv) + "improper constraint: %s has no constraints in it (an empty || segment is not allowed)", errtext.Quote(vv)) } // Every item was blank, so the whole input is punctuation: the // universal set, matching SpecifierSet(","). @@ -470,12 +501,12 @@ func parseGroup(vv string, sanitizer func(string) string, allowEmpty bool) ([]Sp normalized := strings.Join(items, ",") if !validConstraintRegexp.MatchString(normalized) { - return nil, fmt.Errorf("improper constraint: %s", vv) + return nil, fmt.Errorf("improper constraint: %s", errtext.Cut(vv)) } found := specifierRegexp.FindAllString(normalized, -1) if found == nil { - found = append(found, strings.TrimSpace(normalized)) + found = append(found, pyspace.Trim(normalized)) } specs := make([]Specifier, 0, len(found)) @@ -492,7 +523,7 @@ func parseGroup(vv string, sanitizer func(string) string, allowEmpty bool) ([]Sp func newSpecifier(s string, sanitizer func(s string) string, c conf) (Specifier, error) { m := specifierRegexp.FindStringSubmatch(s) if m == nil { - return Specifier{}, fmt.Errorf("improper specifier: %s", s) + return Specifier{}, fmt.Errorf("improper specifier: %s", errtext.Cut(s)) } operator := m[specifierRegexp.SubexpIndex("operator")] @@ -505,10 +536,13 @@ func newSpecifier(s string, sanitizer func(s string) string, c conf) (Specifier, version = sanitizer(version) } + var parsed *Version if operator != "===" { - if err := validate(operator, version); err != nil { + v, err := validate(operator, version) + if err != nil { return Specifier{}, err } + parsed = &v } return Specifier{ @@ -517,10 +551,13 @@ func newSpecifier(s string, sanitizer func(s string) string, c conf) (Specifier, original: s, fn: specifierOperators[operator], pre: c.preReleases, + parsed: parsed, }, nil } -func validate(operator, version string) error { +// validate checks that version is a valid operand for operator, and returns +// it parsed, without the ".*" of a wildcard. +func validate(operator, version string) (Version, error) { hasWildcard := false if strings.HasSuffix(version, ".*") { hasWildcard = true @@ -528,7 +565,8 @@ func validate(operator, version string) error { } v, err := Parse(version) if err != nil { - return fmt.Errorf("version parse error (%s): %w", v, err) + // err already shows the version text. + return Version{}, fmt.Errorf("version parse error: %w", err) } switch operator { @@ -540,26 +578,26 @@ func validate(operator, version string) error { // pre-release is meaningless: the wildcard covers the release segment, // which is where the pre-release marker would have to sit. if hasWildcard && (!v.pre.isNull() || !v.dev.isNull() || !v.post.isNull() || v.local != "") { - return errors.New( + return Version{}, errors.New( "the (non)equality operators don't allow to use a wild card and a pre, dev, post, or local version together", ) } case "~=": if hasWildcard { - return errors.New("a wild card is not allowed") + return Version{}, errors.New("a wild card is not allowed") } else if len(v.release) < 2 { - return errors.New("the compatible operator requires at least two digits in the release segment") + return Version{}, errors.New("the compatible operator requires at least two digits in the release segment") } else if v.local != "" { - return errors.New("local versions cannot be specified") + return Version{}, errors.New("local versions cannot be specified") } default: if hasWildcard { - return errors.New("a wild card is not allowed") + return Version{}, errors.New("a wild card is not allowed") } else if v.local != "" { - return errors.New("local versions cannot be specified") + return Version{}, errors.New("local versions cannot be specified") } } - return nil + return v, nil } // Check tests if a version satisfies all the specifiers. @@ -604,7 +642,7 @@ func (s Specifier) Check(v Version) bool { // empty Specifiers admits every version. return true } - return s.fn(v, s.operand) + return s.fn(v, operand{text: s.operand, version: s.parsed}) } // Operator returns the comparison operator as PEP 440 spells it: "==", "!=", @@ -862,7 +900,7 @@ func parseOperand(s string) (Version, bool) { return v, true } -func specifierCompatible(prospective Version, spec string) bool { +func specifierCompatible(prospective Version, spec operand) bool { // Compatible releases have an equivalent combination of >= and ==. That is that ~=2.2 is equivalent to >=2.2,==2.*. // This allows us to implement this in terms of the other specifiers instead of implementing it ourselves. // The only thing we need to do is construct the other specifiers. @@ -878,7 +916,7 @@ func specifierCompatible(prospective Version, spec string) bool { // prepends the epoch, so the operand and the prospective version agree on // component count. var prefixElements []string - for _, s := range versionSplit(spec) { + for _, s := range versionSplit(spec.text) { if !isNotSuffix(s) { break } @@ -905,15 +943,15 @@ func specifierCompatible(prospective Version, spec string) bool { prefix := versionJoin(prefixElements[:len(prefixElements)-1]) + ".*" - return specifierGreaterThanEqual(prospective, spec) && specifierEqual(prospective, prefix) + return specifierGreaterThanEqual(prospective, spec) && specifierEqual(prospective, operand{text: prefix}) } -func specifierEqual(prospective Version, spec string) bool { +func specifierEqual(prospective Version, spec operand) bool { // We need special logic to handle prefix matching. Ported from // pypa/packaging 26.2's Specifier._compare_equal. - if strings.HasSuffix(spec, ".*") { + if strings.HasSuffix(spec.text, ".*") { // In the case of prefix matching we want to ignore the local segment. - public, ok := parseOperand(prospective.Public()) + public, ok := prospective.publicVersion() if !ok { return false } @@ -924,8 +962,7 @@ func specifierEqual(prospective Version, spec string) bool { // goes through Parse first so that its normalized form (leading zeros, // separator spellings, letter case) is what gets split -- otherwise // `==1.01.*` and `==1.1.*` would split differently. - operand := strings.TrimSuffix(spec, ".*") - specVersion, ok := parseOperand(operand) + specVersion, ok := spec.parse(strings.TrimSuffix(spec.text, ".*")) if !ok { return false } @@ -949,12 +986,12 @@ func specifierEqual(prospective Version, spec string) bool { return slices.Equal(paddedProspective, splitSpec) } - specVersion, ok := parseOperand(spec) + specVersion, ok := spec.parse(spec.text) if !ok { return false } if specVersion.local == "" { - public, ok := parseOperand(prospective.Public()) + public, ok := prospective.publicVersion() if !ok { return false } @@ -964,13 +1001,13 @@ func specifierEqual(prospective Version, spec string) bool { return specVersion.Equal(prospective) } -func specifierNotEqual(prospective Version, spec string) bool { +func specifierNotEqual(prospective Version, spec operand) bool { return !specifierEqual(prospective, spec) } -func specifierLessThan(prospective Version, spec string) bool { +func specifierLessThan(prospective Version, spec operand) bool { // Convert our spec to a Version instance, since we'll want to work with it as a version. - s, ok := parseOperand(spec) + s, ok := spec.parse(spec.text) if !ok { return false } @@ -1004,9 +1041,9 @@ func specifierLessThan(prospective Version, spec string) bool { return true } -func specifierGreaterThan(prospective Version, spec string) bool { +func specifierGreaterThan(prospective Version, spec operand) bool { // Convert our spec to a Version instance, since we'll want to work with it as a version. - s, ok := parseOperand(spec) + s, ok := spec.parse(spec.text) if !ok { return false } @@ -1040,7 +1077,7 @@ func specifierGreaterThan(prospective Version, spec string) bool { // wrongly rejected `1.0a2+local`: same base version 1.0, but a different // public version, and upstream matches it. if prospective.local != "" { - public, ok := parseOperand(prospective.Public()) + public, ok := prospective.publicVersion() if ok && public.Equal(s) { return false } @@ -1048,22 +1085,22 @@ func specifierGreaterThan(prospective Version, spec string) bool { return true } -func specifierArbitrary(prospective Version, spec string) bool { - return strings.EqualFold(prospective.String(), spec) +func specifierArbitrary(prospective Version, spec operand) bool { + return strings.EqualFold(prospective.String(), spec.text) } -func specifierLessThanEqual(prospective Version, spec string) bool { - p, pok := parseOperand(prospective.Public()) - s, sok := parseOperand(spec) +func specifierLessThanEqual(prospective Version, spec operand) bool { + p, pok := prospective.publicVersion() + s, sok := spec.parse(spec.text) if !pok || !sok { return false } return p.LessThanOrEqual(s) } -func specifierGreaterThanEqual(prospective Version, spec string) bool { - p, pok := parseOperand(prospective.Public()) - s, sok := parseOperand(spec) +func specifierGreaterThanEqual(prospective Version, spec operand) bool { + p, pok := prospective.publicVersion() + s, sok := spec.parse(spec.text) if !pok || !sok { return false } diff --git a/version/specifier_query.go b/version/specifier_query.go index 57d40f3..c71e85d 100644 --- a/version/specifier_query.go +++ b/version/specifier_query.go @@ -13,6 +13,7 @@ package version import ( "errors" + "fmt" "slices" "strings" ) @@ -23,6 +24,30 @@ import ( // yields to the other. var ErrPreReleaseConflict = errors.New("cannot combine specifier sets with conflicting explicit pre-release policies") +// ErrTooManyOrGroups is returned by Specifiers.And when both sets have more +// than one OR group and the result would have more than 10,000. And makes one +// group for each pair of groups, so the count is the product of the two counts +// and grows with each call. A set with one group does not make the count +// grow, so And with it never returns this error. +var ErrTooManyOrGroups = errors.New("specifier set would have too many OR groups") + +// maxOrGroups is the maximum number of OR groups that Specifiers.And makes +// from two sets that each have more than one group. Real specifier sets have +// a few. +const maxOrGroups = 10_000 + +// ErrTooManySpecifiers is returned by Specifiers.And when the result would +// have more than 100,000 specifiers and more specifiers than the two sets +// together. And copies all the specifiers of both groups into each result +// group, so a large group is copied once for each group of the other set. +// And of two sets with one group each joins them, so it never returns this +// error. +var ErrTooManySpecifiers = errors.New("specifier set would have too many specifiers") + +// maxAndSpecifiers is the maximum number of specifiers that Specifiers.And +// makes when the result has more specifiers than the two sets together. +const maxAndSpecifiers = 100_000 + //------------------------------------------------------------------- // Resolved pre-release policy //------------------------------------------------------------------- @@ -329,6 +354,18 @@ func (ss Specifiers) And(other Specifiers) (Specifiers, error) { left := ss.orGroups() right := other.orGroups() + // With one group on a side, the result has as many groups as the other + // side, so only two sets with more than one group each can grow. Divide + // instead of multiply, so the check cannot overflow int. + if len(left) > 1 && len(right) > 1 && len(left) > maxOrGroups/len(right) { + return Specifiers{}, fmt.Errorf("%w: %d x %d is more than %d", ErrTooManyOrGroups, len(left), len(right), maxOrGroups) + } + // The group count does not show the size of each group, so also limit the + // specifiers. Without this, 2 groups of 2,000 and 5,000 groups of 1 make + // 20 million specifiers. + if limit, ok := andSizeOK(left, right); !ok { + return Specifiers{}, fmt.Errorf("%w: the result would have more than %d", ErrTooManySpecifiers, limit) + } groups := make([][]Specifier, 0, len(left)*len(right)) for _, l := range left { @@ -343,6 +380,34 @@ func (ss Specifiers) And(other Specifiers) (Specifiers, error) { }, nil } +// andSizeOK returns a limit on the specifiers of And of left and right, and +// reports whether And allocates at most that many. And allocates +// len(right)*sizeL + len(left)*sizeR, where sizeL and sizeR count the +// specifiers of each side. The limit is maxAndSpecifiers, or sizeL+sizeR when +// that is larger, so a result that is not larger than the input always passes. +func andSizeOK(left, right [][]Specifier) (int, bool) { + sizeL, sizeR := countSpecifiers(left), countSpecifiers(right) + limit := max(maxAndSpecifiers, sizeL+sizeR) + // Divide instead of multiply, so the check cannot overflow int. + if sizeL > 0 && len(right) > limit/sizeL { + return limit, false + } + if sizeR > 0 && len(left) > limit/sizeR { + return limit, false + } + // Each product is at most limit now, so the sum cannot overflow. + return limit, len(right)*sizeL+len(left)*sizeR <= limit +} + +// countSpecifiers returns the number of specifiers in groups. +func countSpecifiers(groups [][]Specifier) int { + n := 0 + for _, g := range groups { + n += len(g) + } + return n +} + // dedupeSpecifiers concatenates AND-groups, dropping any member whose canonical // form has already been seen. First-occurrence order is preserved (this package // does not sort; see Specifiers.String). diff --git a/version/version.go b/version/version.go index 617590d..2b242ce 100644 --- a/version/version.go +++ b/version/version.go @@ -18,9 +18,12 @@ package version import ( "bytes" "fmt" + "math/big" "regexp" "strings" + "github.com/posit-dev/go-python-packaging/internal/errtext" + "github.com/posit-dev/go-python-packaging/internal/pyspace" "github.com/rstudio/go-version/pkg/part" ) @@ -122,11 +125,12 @@ func (ln letterNumber) isNull() bool { } func init() { - // The surrounding-whitespace class must include the vertical tab. Go's - // \s is [\t\n\f\r ] and excludes \v, while Python's re \s is - // [ \t\n\r\f\v] and includes it -- so anchoring with a bare \s* would - // reject "1.0\v", which pypa/packaging accepts. - versionRegex = regexp.MustCompile(`(?i)^[\s\v]*` + regex + `[\s\v]*$`) + // The surrounding whitespace is Python's "\s", which packaging's pattern + // uses on a str: the vertical tab, U+001C to U+001F, and Unicode + // whitespace such as U+00A0 and U+3000. Go's \s is only [\t\n\f\r ], so + // a bare \s* would reject "1.0\v" and "1.0\u00a0", which packaging + // accepts. See package pyspace. + versionRegex = regexp.MustCompile(`(?i)^` + pyspace.Class + `*` + regex + pyspace.Class + `*$`) } // localVersionSeparators matches the separators PEP 440 permits inside a local @@ -192,6 +196,12 @@ func isASCIIDigits(s string) bool { return true } +// isZero reports whether b is zero, as b.IsNull does, without its allocation. +func isZero(b part.BigInt) bool { + bi := big.Int(b) + return bi.Sign() == 0 +} + // MustParse is like Parse but panics if the version cannot be parsed. func MustParse(v string) Version { ver, err := Parse(v) @@ -201,11 +211,41 @@ func MustParse(v string) Version { return ver } -// Parse parses the given version and returns a new Version. +// maxNumberDigits is the maximum number of digits in one number of a version. +// Python's int() has the same default limit (Python 3.11 and later), so +// packaging rejects longer numbers too. Without a limit, math/big uses +// quadratic memory: a number of 400,000 digits allocates 350 MB. +const maxNumberDigits = 4300 + +// numberTooLong reports whether the regex group name of a version, with the +// matched text m, holds a number of more than maxNumberDigits digits. A local +// segment counts only if it is all digits, because packaging keeps any other +// local segment as a string. +func numberTooLong(name, m string) bool { + switch name { + case "epoch", "pre_n", "post_n1", "post_n2", "dev_n": + return len(m) > maxNumberDigits + case "release", "local": + // A segment is no longer than m, so a short m needs no split. This + // skips the split for every real version: Parse is called often. + if len(m) <= maxNumberDigits { + return false + } + for _, seg := range localVersionSeparators.Split(m, -1) { + if len(seg) > maxNumberDigits && isASCIIDigits(seg) { + return true + } + } + } + return false +} + +// Parse parses the given version and returns a new Version. It returns an +// error if a number in v has more than 4,300 digits. func Parse(v string) (Version, error) { matches := versionRegex.FindStringSubmatch(v) if matches == nil { - return Version{}, fmt.Errorf("malformed version: %s", v) + return Version{}, fmt.Errorf("malformed version: %s", errtext.Cut(v)) } var epoch, preN, postN, devN part.BigInt @@ -219,6 +259,9 @@ func Parse(v string) (Version, error) { if m == "" { continue } + if numberTooLong(name, m) { + return Version{}, fmt.Errorf("malformed version: %s: a number has more than %d digits", errtext.Cut(v), maxNumberDigits) + } switch name { case "epoch": @@ -255,7 +298,7 @@ func Parse(v string) (Version, error) { local = normalizeLocal(m) } if err != nil { - return Version{}, fmt.Errorf("failed to parse version (%s): %w", v, err) + return Version{}, fmt.Errorf("failed to parse version (%s): %w", errtext.Cut(v), err) } } @@ -292,36 +335,48 @@ func Parse(v string) (Version, error) { // Pinned: see UpstreamPackagingSHA (L1178 at that commit). // https://github.com/pypa/packaging/blob/4eb0753dba8fcaaac8eb75463374e448f0931558/src/packaging/version.py#L1178 func cmpkey(epoch part.BigInt, release []part.BigInt, pre, post, dev letterNumber, local string) key { - // Set default values + // Each segment that is absent becomes an infinity, and only a present one + // is built as Parts: boxing a letter and a number into Parts allocates + // three times, which Parse would pay for every absent segment of every + // version and then throw away. k := key{ epoch: epoch, - pre: part.Parts{pre.letter, pre.number}, - post: part.Parts{post.letter, post.number}, - dev: part.Parts{dev.letter, dev.number}, local: part.NegativeInfinity, } - // Remove trailing zeros - k.release = part.BigIntSliceToParts(release).Normalize() + // Remove trailing zeros. This is what part.Parts.Normalize does, without + // boxing the zeros it removes or copying the slice a second time. + n := len(release) + for n > 0 && isZero(release[n-1]) { + n-- + } + k.release = part.BigIntSliceToParts(release[:n]) // Ported from pypa/packaging src/packaging/version.py, _cmpkey's // dev-only / no-pre-release rank assignment. // Pinned: see UpstreamPackagingSHA (L1230-L1234 at that commit). // https://github.com/pypa/packaging/blob/4eb0753dba8fcaaac8eb75463374e448f0931558/src/packaging/version.py#L1230-L1234 - if pre.isNull() && post.isNull() && !dev.isNull() { + switch { + case pre.isNull() && post.isNull() && !dev.isNull(): k.pre = part.NegativeInfinity - } else if pre.isNull() { + case pre.isNull(): k.pre = part.Infinity + default: + k.pre = part.Parts{pre.letter, pre.number} } // Versions without a post segment should sort before those with one. if post.isNull() { k.post = part.NegativeInfinity + } else { + k.post = part.Parts{post.letter, post.number} } // Versions without a development segment should sort after those with one. if dev.isNull() { k.dev = part.Infinity + } else { + k.dev = part.Parts{dev.letter, dev.number} } // Versions with a local segment need that segment parsed to implement the sorting rules in PEP440. @@ -565,6 +620,17 @@ func (v Version) Public() string { return strings.SplitN(v.String(), "+", 2)[0] } +// publicVersion returns the version without its local segment, as +// Parse(v.Public()) does. A version with no local segment is its own public +// version, so publicVersion returns it without the parse. ok is false for a +// zero-value Version, which has no public version. +func (v Version) publicVersion() (Version, bool) { + if v.local == "" && len(v.release) > 0 { + return v, true + } + return parseOperand(v.Public()) +} + // IsPreRelease reports whether this is a pre-release: it has a pre-release // segment (a1, b2, rc3) or a dev segment. // diff --git a/version/whitespace_test.go b/version/whitespace_test.go new file mode 100644 index 0000000..aee8e5b --- /dev/null +++ b/version/whitespace_test.go @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// pythonWhitespace is each character that Python's "\s" matches on a str, +// beyond the [\t\n\r ] that Go's \s and Python's share. packaging's Version +// and Specifier patterns allow "\s" around a version and around a specifier. +var pythonWhitespace = map[string]string{ + "vertical tab": "\v", + "form feed": "\f", + "file separator U+001C": "\x1c", + "group separator U+001D": "\x1d", + "record separator U+001E": "\x1e", + "unit separator U+001F": "\x1f", + "next line U+0085": "\u0085", + "no-break space U+00A0": "\u00a0", + "ogham space mark U+1680": "\u1680", + "en quad U+2000": "\u2000", + "hair space U+200A": "\u200a", + "line separator U+2028": "\u2028", + "paragraph separator U+2029": "\u2029", + "narrow no-break space U+202F": "\u202f", + "medium mathematical space U+205F": "\u205f", + "ideographic space U+3000": "\u3000", +} + +// otherControls are characters that are not whitespace for Python, so +// packaging rejects them around a version or a specifier. A "===" value can +// hold them, because its pattern is only "not whitespace". +var otherControls = map[string]string{ + "NUL": "\x00", + "start of heading": "\x01", + "start of text": "\x02", + "enquiry": "\x05", + "bell": "\x07", + "backspace": "\x08", + "shift out": "\x0e", + "data link escape": "\x10", + "substitute": "\x1a", + "escape": "\x1b", + "delete": "\x7f", + "zero width space U+200B": "\u200b", + "byte order mark U+FEFF": "\ufeff", +} + +// Each expected result was checked against packaging 21.0, as vendored in +// pip 21.2.4: Version(...) and Specifier(...). Current packaging uses the +// same "\s" patterns for both. +func TestParse_PythonWhitespace(t *testing.T) { + for name, c := range pythonWhitespace { + t.Run(name, func(t *testing.T) { + v, err := Parse(c + "1.0" + c) + require.NoError(t, err, "whitespace around a version is allowed") + assert.Equal(t, "1.0", v.String()) + + _, err = Parse("1" + c + ".0") + assert.Error(t, err, "whitespace inside a version is not allowed") + + s, err := NewSpecifier(c + ">=" + c + "1.0" + c) + require.NoError(t, err, "whitespace around a specifier and after its operator is allowed") + assert.Equal(t, ">=1.0", s.String()) + + s, err = NewSpecifier("===" + c + "x") + require.NoError(t, err) + assert.Equal(t, "===x", s.String()) + + _, err = NewSpecifier("===x" + c + "y") + assert.Error(t, err, "a === value ends at whitespace") + + // packaging's SpecifierSet removes Python whitespace from each + // comma-separated item. + ss, err := NewSpecifiers(">=1.0," + c + "<2.0" + c) + require.NoError(t, err) + assert.Equal(t, "<2.0,>=1.0", sortedSpecifiers(t, ss)) + }) + } +} + +func TestParse_OtherControlCharacters(t *testing.T) { + for name, c := range otherControls { + t.Run(name, func(t *testing.T) { + _, err := Parse(c + "1.0") + assert.Error(t, err, "before a version") + _, err = Parse("1.0" + c) + assert.Error(t, err, "after a version") + _, err = Parse("1" + c + ".0") + assert.Error(t, err, "inside a version") + + _, err = NewSpecifier(">=" + c + "1.0") + assert.Error(t, err, "between the operator and the version") + _, err = NewSpecifier(">=1.0" + c) + assert.Error(t, err, "after the specifier") + + s, err := NewSpecifier("===" + c + "x") + require.NoError(t, err, "a === value can hold a character that is not whitespace") + assert.Equal(t, "==="+c+"x", s.String()) + }) + } +} + +// A "||" segment that holds only Python whitespace is empty, like a segment +// with only spaces. "||" is this package's own syntax, so packaging has no +// answer here; the rule matches the comma rule above. +func TestNewSpecifiers_SegmentOfPythonWhitespace(t *testing.T) { + for name, c := range pythonWhitespace { + t.Run(name, func(t *testing.T) { + _, err := NewSpecifiers(">=1.0||" + c) + require.Error(t, err) + assert.Contains(t, err.Error(), "empty || segment") + + ss, err := NewSpecifiers(c) + require.NoError(t, err, "only whitespace is the universal set") + assert.Equal(t, "", ss.String()) + }) + } +} + +// sortedSpecifiers returns the specifiers of ss, which has one group, in +// String() order: this package does not sort, so sort here to compare. +func sortedSpecifiers(t *testing.T, ss Specifiers) string { + t.Helper() + groups := ss.orGroups() + require.Len(t, groups, 1) + parts := make([]string, len(groups[0])) + for i, s := range groups[0] { + parts[i] = s.String() + } + if len(parts) == 2 && parts[0] > parts[1] { + parts[0], parts[1] = parts[1], parts[0] + } + out := parts[0] + for _, p := range parts[1:] { + out += "," + p + } + return out +} diff --git a/wheelname/bench_test.go b/wheelname/bench_test.go new file mode 100644 index 0000000..b9c27d8 --- /dev/null +++ b/wheelname/bench_test.go @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package wheelname + +import ( + "testing" + + "github.com/posit-dev/go-python-packaging/internal/allocbudget" +) + +// Benchmarks and allocation budgets for the hot paths of this package. The +// budget tests run in CI and fail on any change in allocations; the +// benchmarks are for comparing a branch with main (see CLAUDE.md, +// "Performance"). + +// benchWheels are wheel filenames of common shapes. parse and tags are the +// allocation budgets of Parse and of ParseTags. +var benchWheels = []struct { + name, in string + parse, tags float64 +}{ + {name: "pure Python", in: "requests-2.31.0-py3-none-any.whl", parse: 21, tags: 7}, + { + name: "compressed platform tag", + in: "numpy-1.26.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", + parse: 23, tags: 7, + }, + {name: "build tag", in: "torch-2.2.0-1-cp311-cp311-win_amd64.whl", parse: 21, tags: 7}, + // Parse rejects the PEP 427 escaped version 2.5.0_cpu, so its budget is + // the error path. ParseTags reads it. + {name: "escaped local version", in: "torch-2.5.0_cpu-cp312-cp312-linux_x86_64.whl", parse: 15, tags: 7}, +} + +func BenchmarkParse(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + for _, w := range benchWheels { + _, _ = Parse(w.in) + } + } +} + +func BenchmarkParseTags(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + for _, w := range benchWheels { + if _, err := ParseTags(w.in); err != nil { + b.Fatal(err) + } + } + } +} + +func TestAllocBudget_Parse(t *testing.T) { + for _, w := range benchWheels { + t.Run(w.name, func(t *testing.T) { + allocbudget.Check(t, w.parse, func() { _, _ = Parse(w.in) }) + }) + } +} + +func TestAllocBudget_ParseTags(t *testing.T) { + for _, w := range benchWheels { + t.Run(w.name, func(t *testing.T) { + if _, err := ParseTags(w.in); err != nil { + t.Fatal(err) // the budget must not be an error path + } + allocbudget.Check(t, w.tags, func() { _, _ = ParseTags(w.in) }) + }) + } +} diff --git a/wheelname/control_chars_test.go b/wheelname/control_chars_test.go new file mode 100644 index 0000000..10b2b7d --- /dev/null +++ b/wheelname/control_chars_test.go @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package wheelname + +import ( + "testing" + + "github.com/posit-dev/go-python-packaging/tags" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// controlCharacters are whitespace and control characters, ASCII and not. +var controlCharacters = map[string]string{ + "NUL": "\x00", + "start of heading": "\x01", + "tab": "\t", + "vertical tab": "\v", + "escape": "\x1b", + "unit separator U+001F": "\x1f", + "space": " ", + "delete": "\x7f", + "no-break space U+00A0": "\u00a0", + "zero width space U+200B": "\u200b", +} + +// packaging's parse_wheel_filename keeps any character after the digits of a +// build tag, and any character in a tag field except "-" and ".". Checked +// against packaging 21.0, as vendored in pip 21.2.4. +func TestParse_ControlCharacterInBuildAndTags(t *testing.T) { + for name, c := range controlCharacters { + t.Run(name, func(t *testing.T) { + w, err := Parse("foo-1.0-1" + c + "-py3-none-any.whl") + require.NoError(t, err) + assert.Equal(t, "1"+c, w.Build) + + w, err = Parse("foo-1.0-py3" + c + "-none-any.whl") + require.NoError(t, err) + assert.Equal(t, []tags.Tag{{Interpreter: "py3" + c, ABI: "none", Platform: "any"}}, w.Tags) + }) + } +} + +// A version with a control character is an error, as in packaging, which +// parses the version with Version(). +func TestParse_ControlCharacterInVersion(t *testing.T) { + for name, c := range controlCharacters { + t.Run(name, func(t *testing.T) { + _, err := Parse("foo-1" + c + ".0-py3-none-any.whl") + assert.Error(t, err) + }) + } +} diff --git a/wheelname/fuzz_test.go b/wheelname/fuzz_test.go new file mode 100644 index 0000000..fa6d402 --- /dev/null +++ b/wheelname/fuzz_test.go @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package wheelname_test + +import ( + "math/big" + "strings" + "testing" + "time" + + "github.com/posit-dev/go-python-packaging/internal/fuzzseed" + "github.com/posit-dev/go-python-packaging/tags" + "github.com/posit-dev/go-python-packaging/wheelname" +) + +func FuzzParse(f *testing.F) { + fuzzseed.Add(f, + "numpy-1.26.0-cp311-cp311-manylinux_2_17_x86_64.whl", + "foo-1.0-1-py2.py3-none-any.whl", + "torch-2.4.0+cu121-cp311-cp311-linux_x86_64.whl", + "torch-2.5.0_post1_cpu-cp39-cp39-manylinux1_x86_64.whl", + "dcnnt-0.3.8fix-py3-none-any.whl", + "foo-1.0-py3--any.whl", + "foo-1.0-x-py3-none-any.whl", + "too-few-py3-none-any.whl", + "Foo_Bar-1.0-cp36.cp37-abi3-manylinux1_x86_64.manylinux2010_x86_64.whl", + "pkg-1.0-123abc-py3-none-any.whl", + ) + alts := strings.Repeat("a.", 29) + "a" + f.Add("foo-1.0-" + alts + "-" + alts + "-" + alts + ".whl") + + // Inputs the fuzzer found that failed before they were fixed. + f.Add("-0-0-0-0.whl") + + f.Fuzz(func(t *testing.T, in string) { + start := time.Now() + w, err := wheelname.Parse(in) + wt, errTags := wheelname.ParseTags(in) + fuzzseed.Within(t, start, in) + if err != nil { + return + } + if w.Name == "" { + t.Fatalf("Parse(%q) returned no error and an empty name", in) + } + if len(w.Tags) == 0 { + t.Fatalf("Parse(%q) returned no error and no tags", in) + } + if w.Version.String() == "" { + t.Fatalf("Parse(%q) returned no error and an empty version", in) + } + if errTags != nil { + t.Fatalf("Parse(%q) succeeded but ParseTags failed: %v", in, errTags) + } + if wt.Name != w.Name || wt.Build != w.Build || !sameTags(wt.Tags, w.Tags) { + t.Fatalf("Parse(%q) and ParseTags disagree:\n%#v\n%#v", in, w, wt) + } + }) +} + +func sameTags(a, b []tags.Tag) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// FuzzCompareBuildTags checks that CompareBuildTags is antisymmetric and +// orders the leading numbers by value, as PEP 427's (int, str) tuple does. +func FuzzCompareBuildTags(f *testing.F) { + f.Add("", "1") + f.Add("1", "2") + f.Add("10", "9") + f.Add("1a", "1b") + f.Add("01", "1") + f.Add("abc", "0abc") + f.Add("18446744073709551616", "1") + + // Inputs the fuzzer found that failed before they were fixed. + f.Add("99999999999999999999a", "99999999999999999998b") + f.Add("18446744073709551616", "9223372036854775807") + + f.Fuzz(func(t *testing.T, a, b string) { + ab, ba := wheelname.CompareBuildTags(a, b), wheelname.CompareBuildTags(b, a) + if ab != -ba { + t.Fatalf("CompareBuildTags(%q, %q) = %d but reversed = %d", a, b, ab, ba) + } + if a == "" || b == "" { + return + } + an, bn := leadingInt(a), leadingInt(b) + if c := an.Cmp(bn); c != 0 && c != ab { + t.Fatalf("CompareBuildTags(%q, %q) = %d, but the leading numbers compare as %d", a, b, ab, c) + } + }) +} + +func leadingInt(s string) *big.Int { + i := 0 + for i < len(s) && s[i] >= '0' && s[i] <= '9' { + i++ + } + n := new(big.Int) + n.SetString(s[:i], 10) // "" leaves n at 0 + return n +} diff --git a/wheelname/limits_test.go b/wheelname/limits_test.go new file mode 100644 index 0000000..6904ee1 --- /dev/null +++ b/wheelname/limits_test.go @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package wheelname + +import ( + "errors" + "fmt" + "strings" + "testing" + + "github.com/posit-dev/go-python-packaging/tags" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParse_BadFilenames(t *testing.T) { + tests := []struct { + name string + filename string + // wantIs is the sentinel the error must wrap. + wantIs error + wantErr string + }{ + { + // Found by fuzzing. packaging 24.1 accepts it. + name: "empty name", + filename: "-0-0-0-0.whl", + wantIs: ErrInvalidWheelFilename, + wantErr: "empty name", + }, + { + name: "empty name with a build tag", + filename: "-1.0-1-py3-none-any.whl", + wantIs: ErrInvalidWheelFilename, + wantErr: "empty name", + }, + { + // 101 x 100 x 1 = 10,100 tags, over the 10,000-tag limit. + name: "too many tags", + filename: "foo-1.0-" + alternatives("py", 101) + "-" + alternatives("abi", 100) + "-any.whl", + wantIs: tags.ErrInvalidTag, + wantErr: "more than 10000 tags", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := Parse(tt.filename) + require.Error(t, err) + assert.True(t, errors.Is(err, tt.wantIs), "want %v", tt.wantIs) + assert.Contains(t, err.Error(), tt.wantErr) + require.Less(t, len(err.Error()), 1000, "error text is short") + + _, err = ParseTags(tt.filename) + assert.True(t, errors.Is(err, tt.wantIs), "ParseTags: want %v", tt.wantIs) + }) + } +} + +// alternatives returns n dot-separated tag values: "0.1...". +func alternatives(prefix string, n int) string { + parts := make([]string, n) + for i := range parts { + parts[i] = fmt.Sprintf("%s%d", prefix, i) + } + return strings.Join(parts, ".") +} + +// The leading number of a build tag can be of any size. +func TestCompareBuildTags_LargeNumbers(t *testing.T) { + tests := []struct { + name string + a, b string + want int + }{ + { + // Found by hand. strconv.Atoi overflowed and gave -1. + name: "20 digits with suffixes", + a: "99999999999999999999a", + b: "99999999999999999998b", + want: 1, + }, + { + // Found by hand. Both overflowed int and compared equal. + name: "2^64 and 2^63-1", + a: "18446744073709551616", + b: "9223372036854775807", + want: 1, + }, + { + name: "longer number is larger", + a: "100000000000000000000000000000", + b: "99999999999999999999999999999", + want: 1, + }, + { + name: "leading zeros do not count", + a: "000000000000000000000000000001", + b: "2", + want: -1, + }, + { + name: "same large number, then the suffix decides", + a: "123456789012345678901234567890a", + b: "123456789012345678901234567890b", + want: -1, + }, + { + name: "same large number with and without leading zeros", + a: "0123456789012345678901234567890", + b: "123456789012345678901234567890", + want: 0, + }, + { + name: "small numbers are unchanged", + a: "10", + b: "9", + want: 1, + }, + { + name: "absent build tag sorts first", + a: "", + b: "99999999999999999999", + want: -1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, CompareBuildTags(tt.a, tt.b)) + assert.Equal(t, -tt.want, CompareBuildTags(tt.b, tt.a), "reversed") + }) + } +} diff --git a/wheelname/project_name_test.go b/wheelname/project_name_test.go new file mode 100644 index 0000000..f2ce4b1 --- /dev/null +++ b/wheelname/project_name_test.go @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package wheelname + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The project name of a wheel filename may hold only Python word characters +// (a Unicode letter or number, or "_") and ".", with no "__". Each row was +// checked against packaging 21.0, as vendored in pip 21.2.4, which has the +// same rule as packaging at UpstreamPackagingSHA, except that it allows an +// empty name. +func TestParse_ProjectName(t *testing.T) { + tests := []struct { + name string + valid bool + }{ + {"foo", true}, + {"Foo_Bar", true}, + {"foo.bar", true}, + {"foo_", true}, + {"_foo", true}, + {".foo", true}, + {".", true}, + {"foo1", true}, + {"caf\u00e9", true}, // Latin small e with acute + {"\u65e5\u672c", true}, // CJK ideographs + {"foo\u00b2", true}, // superscript two, a number + {"\u2167", true}, // Roman numeral eight, a number + {"\u0661\u0662", true}, // Arabic-Indic digits + {"foo__bar", false}, // PEP 427 escapes a run to one "_" + {"foo___bar", false}, + {"__", false}, + {"foo bar", false}, + {"foo+bar", false}, + {"foo!bar", false}, + {"foo~", false}, + {"foo\x00", false}, // NUL + {"foo\t", false}, // tab + {"foo\x1f", false}, // unit separator + {"foo\u00a0", false}, // no-break space + {"foo\u200b", false}, // zero width space + {"foo\u0301", false}, // combining acute accent, a mark + {"foo\ufffd", false}, // replacement character, a symbol + {"foo\U0001f600", false}, // emoji, a symbol + {"foo\xff", false}, // not valid UTF-8 + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + filename := tt.name + "-1.0-py3-none-any.whl" + w, err := Parse(filename) + _, tagsErr := ParseTags(filename) + if !tt.valid { + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidWheelFilename), "want ErrInvalidWheelFilename") + assert.Contains(t, err.Error(), "invalid project name") + assert.Error(t, tagsErr, "ParseTags checks the name too") + return + } + require.NoError(t, err) + require.NoError(t, tagsErr) + assert.NotEmpty(t, w.Name) + }) + } +} diff --git a/wheelname/wheelname.go b/wheelname/wheelname.go index 994a643..fc1e6fd 100644 --- a/wheelname/wheelname.go +++ b/wheelname/wheelname.go @@ -14,9 +14,10 @@ package wheelname import ( "errors" "fmt" - "strconv" "strings" + "unicode" + "github.com/posit-dev/go-python-packaging/internal/errtext" "github.com/posit-dev/go-python-packaging/tags" "github.com/posit-dev/go-python-packaging/version" ) @@ -40,6 +41,10 @@ type WheelTags struct { Tags []tags.Tag } +// Parse parses a wheel filename, as packaging's parse_wheel_filename does. It +// returns an error that wraps ErrInvalidWheelFilename if the project name is +// empty, has a character other than a Unicode letter or number, "_" or ".", +// or has "__" (see validProjectName). func Parse(filename string) (WheelFilename, error) { w, verStr, err := parseExceptVersion(filename) if err != nil { @@ -52,7 +57,7 @@ func Parse(filename string) (WheelFilename, error) { // of such a wheel should use ParseTags. ver, err := version.Parse(verStr) if err != nil { - return WheelFilename{}, fmt.Errorf("wheel %q: version: %w", filename, err) + return WheelFilename{}, fmt.Errorf("wheel %s: version: %w", errtext.Quote(filename), err) } return WheelFilename{Name: w.Name, Version: ver, Build: w.Build, Tags: w.Tags}, nil } @@ -70,6 +75,26 @@ func ParseTags(filename string) (WheelTags, error) { return w, err } +// validProjectName reports whether name, the first field of a wheel filename, +// passes packaging's parse_wheel_filename check: it has only Python word +// characters ("\w" on a str) and ".", and no "__". PEP 427 escapes a run of +// other characters, such as "-", to one "_". +// +// Python's "\w" is a Unicode letter or number, or "_". That is +// unicode.IsLetter or unicode.IsNumber in Go: the two agree on every code +// point that Python 3.9's Unicode 13 assigns. +func validProjectName(name string) bool { + if strings.Contains(name, "__") { + return false + } + for _, r := range name { + if !unicode.IsLetter(r) && !unicode.IsNumber(r) && r != '_' && r != '.' { + return false + } + } + return true +} + // parseExceptVersion splits and validates everything but the version, returning // the unparsed version string alongside. Both entry points go through it so they // cannot disagree about what a wheel filename is. @@ -82,6 +107,12 @@ func parseExceptVersion(filename string) (WheelTags, string, error) { if len(parts) != 5 && len(parts) != 6 { return WheelTags{}, "", fmt.Errorf("%w: expected 5 or 6 dash fields, got %d", ErrInvalidWheelFilename, len(parts)) } + if parts[0] == "" { + return WheelTags{}, "", fmt.Errorf("%w: empty name", ErrInvalidWheelFilename) + } + if !validProjectName(parts[0]) { + return WheelTags{}, "", fmt.Errorf("%w: invalid project name %s", ErrInvalidWheelFilename, errtext.Quote(parts[0])) + } name := strings.ToLower(parts[0]) verStr := parts[1] var build string @@ -89,21 +120,22 @@ func parseExceptVersion(filename string) (WheelTags, string, error) { if len(parts) == 6 { build = parts[2] if build == "" || build[0] < '0' || build[0] > '9' { - return WheelTags{}, "", fmt.Errorf("%w: build tag %q must start with a digit", ErrInvalidWheelFilename, build) + return WheelTags{}, "", fmt.Errorf("%w: build tag %s must start with a digit", ErrInvalidWheelFilename, errtext.Quote(build)) } tagStart = 3 } tagComponent := strings.Join(parts[tagStart:tagStart+3], "-") tg, err := tags.ParseTag(tagComponent) if err != nil { - return WheelTags{}, "", fmt.Errorf("wheel %q: tag: %w", filename, err) + return WheelTags{}, "", fmt.Errorf("wheel %s: tag: %w", errtext.Quote(filename), err) } return WheelTags{Name: name, Build: build, Tags: tg}, verStr, nil } // CompareBuildTags orders PEP 427 build tags; absent ("") sorts first; present // tags compare by (leading-int, remaining-string). Non-digit-led input is -// treated as numeric part 0 (total, never panics). +// treated as numeric part 0 (total, never panics). The leading number may be +// of any size. func CompareBuildTags(a, b string) int { if a == b { return 0 @@ -116,11 +148,10 @@ func CompareBuildTags(a, b string) int { } an, ar := splitBuild(a) bn, br := splitBuild(b) + if c := compareDigits(an, bn); c != 0 { + return c + } switch { - case an < bn: - return -1 - case an > bn: - return 1 case ar < br: return -1 case ar > br: @@ -130,11 +161,24 @@ func CompareBuildTags(a, b string) int { } } -func splitBuild(s string) (int, string) { +// splitBuild returns the leading digits of s, without leading zeros, and the +// rest of s. No digits, or only zeros, gives "" for the number 0. +func splitBuild(s string) (digits, rest string) { i := 0 for i < len(s) && s[i] >= '0' && s[i] <= '9' { i++ } - n, _ := strconv.Atoi(s[:i]) // "" -> 0 - return n, s[i:] + return strings.TrimLeft(s[:i], "0"), s[i:] +} + +// compareDigits compares two numbers written as digits with no leading zeros. +// It does not convert them to int, so a number of any size compares correctly. +func compareDigits(a, b string) int { + if len(a) != len(b) { + if len(a) < len(b) { + return -1 + } + return 1 + } + return strings.Compare(a, b) }