Repository navigation
fix(shift): throw ExecutionLimitError when $# exceeds maxArrayElements - #734
abhiramshaji-cyber wants to merge 25 commits into
Conversation
shift looped up to $# to read and clear parameters, so a $# seeded through the environment made it build and rewrite that many slots before any limit applied. It now stops at the first parameter that is not set, capped at $#, so the work follows real state.
|
@abhiramshaji-cyber is attempting to deploy a commit to the Vercel Labs Team on Vercel. A member of the Team first needs to authorize it. |
🤖 auto-maintain reviewAutomated, advisory triage for
Review panel: 🟡 medium highest severity just-bash maintainer code review: 🟢 low
General code review: 🟢 low
Adversarial security: 🟡 medium
Adversarial security (second opinion): 🟢 low
Standard Bash and host portability: 🟢 low
Posted by auto-maintain. This automated code review is advisory; a human maintainer makes the call. |
The first version capped the count at the parameters it could walk, which changed $# for sourced files with more than nine arguments, stopped while [ $# -gt 0 ] loops from ending when $# was above the set parameters, and left later parameters behind after a gap. The count, the range check and the new $# now follow $# exactly as before, and only the data move is limited to the numbered keys that exist.
The previous commit left slots without a stored value unset, while main
sets every slot up to the new $# (empty when missing), which set -u,
${N-x} and [ -v N ] can tell apart. Main's walk now runs unchanged
whenever $# is within the environment size or maxArrayElements, and only
a $# beyond both moves the stored keys alone.
…rflows The previous bound used the environment size and maxArrayElements, but main's walk succeeds far above both. The switch now sits exactly where the full walk would exceed the JavaScript limits measured on Node 24: 2 ** 27 array elements, or 2 ** 24 Map entries counting the new slots and $@. Below that, shift runs main's code unchanged. Above it, $# is counted down with BigInt so loops past 2 ** 53 still end.
The engine measured caps made the switch depend on V8 and still let a seeded $# drive millions of slots per shift. The switch is back at max(env.size, maxArrayElements), so the work is bounded by real entries or the host's own limit on every engine. Above it, slots with nothing stored behind them stay unset, which only a host seeded $# can reach, and $# still counts down with BigInt past 2 ** 53.
Above the bound, the range check and the subtraction now use BigInt on the digits of $# and the shift count, and stored keys are matched with BigInt, so large values no longer round. $# is read once and the out of range error is shared by both paths. Tests pin the existing walk below the bound and the exact results past 2 ** 53.
…size
The walk used to switch on count > max(env.size, maxArrayElements), so
${2-U} and [ -v 2 ] changed with the number of unrelated variables, and a
$# just under maxArrayElements still built and walked a 1,000,000 slot
array on every shift. Now there is one behavior: each stored $1..$# key
moves down by n and slots with nothing behind them stay unset. The keys
are found by walking 1..$# when $# <= env.size and by scanning env
otherwise, so both give the same keys and the work is bounded by
min($#, env.size).
BigInt parsed $# and every numeric env key on each shift with no length limit, so a host seeded value of a million digits made every shift slow. Numbers now keep at most 19 significant digits, the width bash reads as intmax_t. A longer shift count is always out of range, a longer $# stops with an ExecutionLimitError, and stored keys longer than $# are skipped before any parsing.
Gaps now stay unset after shift, so a set -u script that read one of them (source with more than nine arguments before vercel-labs#729, or a host seeded $# above the stored keys) died with "unbound variable" where main printed an empty line. getVariable now raises the nounset error for $N only when N is above $#, which is what bash means by $#. The sourced file test also checks the moved values.
The common walk used BigInt counters and was about 2.4x slower than main. When $# is at most env.size it now walks with plain numbers and moves each stored key in place, which is a little faster than main; BigInt is only used for the env scan. shift 0 and the out of range check run before the $# bound again, so shift 0 keeps returning 0. A $# above intmax_t max now fails with status 1 instead of throwing an ExecutionLimitError, and the tests use maxExecutionTimeMs instead of wall clock asserts and cover both sides of 2 ** 63 - 1.
The parser and the stored key move now live in helpers/stored-params.ts. shift checks the $# bound before the range check, so every shift other than shift 0 on a $# above 2 ** 63 - 1 gives the same error. set -u reads $# with the same bounded parser instead of parseInt, which rounded above 2 ** 53 and reparsed a long $# on every reference. set -- now removes the stored keys up to the old $# before its existing walk, so a gap left by shift no longer keeps later keys alive. The host limit tests no longer set maxArrayElements, which shift does not read, and the sourced file test checks exact values with and without vercel-labs#729.
After moveStoredParams removed $1 to $#, the existing walk still started at 1, found nothing and stopped, so keys above the old $# (the caller's $10 and $11 inside a sourced file, or a stored key past a seeded $#) survived where main cleared them. The walk now starts at $# + 1. The sourced set -u test pins the output without vercel-labs#729 instead of probing for it.
The sourced set -u test pinned output that changes once vercel-labs#729 stores $10 and later, so it now uses a seeded gap that does not depend on vercel-labs#729. New tests cover set -u with a non numeric or too large $#, where every $N past the stored keys still errors, and set -- with a seeded $# above env.size, which takes the scan path. The changeset now says shift 0 still returns 0 above 2 ** 63 - 1 and describes the set -- clearing.
|
Thanks so much for the careful review, all three points were spot on and the repros made them easy to confirm. 2bfa05b: shift now moves only the 76a0e37, d1d5d5f and ba8e700: 22e0607, ba8e700 and a2df117: since gaps now stay unset after a shift, set -u treats ac23d5c adds tests for the seeded gap under set -u, set -u with an unusable Hey @jamalkamaladdin, hope you're doing well! Does keeping gaps unset sound right to you, or would you rather shift throw an ExecutionLimitError when |
|
Hi @jamalkamaladdin, hope you're doing well, and I know you have a lot on your plate, so no rush at all! Just checking in: the review feedback is addressed in 2bfa05b and the commits after it, and I'm happy to change anything, including having shift throw an ExecutionLimitError instead if you'd prefer. Would anything else help on my side? |
|
Hi @privatenumber, hope you're doing well! I know there's a lot on your plate, so please take your time. I left a note here on the 16th and wanted to check in with you directly, since I think you're the right person to ask. The auto-maintain points are addressed in 2bfa05b and the commits after it. Is there anything else that would help, or anything you'd like done differently? I'm glad to rework it however suits you best, including having |
|
To answer your question on sparse gaps vs Reasons:
If we enforce a bounded positional-count limit with |
Restores shift, set --, set -u and the shift tests to main, per the review decision to bound $# with ExecutionLimitError instead.
Every reader of $# goes through positionalCount, so shift, function calls, getopts and every positional expansion share one bound.
|
Hey @privatenumber, hope your week's going well, and thanks so much for taking the time to lay that out, the three reasons made the call really easy to follow. I reworked it the way you suggested.
I also merged main in. I reused |
|
A new push changed this PR and the review now contains a higher-severity finding. See the updated review comment above. |
… bare for over $@
|
Thanks for the careful review, all three points held up when I tried them, and the repros made them quick to confirm. 62aaeba fixes each one:
New tests in @privatenumber, for the bare |
…metic fallbacks
Catch blocks that fall back on a failed array subscript or arithmetic evaluation, plus the [[ ]] and (( )) error handlers, swallowed the positional limit error, so ${a[$#]} read a[0] and [[ $# -gt 0 ]] kept going instead of stopping.
|
A new push changed this PR and the review now contains a higher-severity finding. See the updated review comment above. |
…hmetic fallbacks
Swap the hand written ExecutionLimitError rethrows for the shared helper, so aborts and security violations pass through too, and cover the compound array, ${a[i]:=v} and local a[i]=v index fallbacks, where a=(['a[$#]']=x) wrote to index 0 instead of stopping.
A host that passed a huge
$#inenvcould makeshift, function calls or$*hang or crash, and now they stop at once withExecutionLimitError.This is the follow up to the
shiftloop from #729 (thanks again @jamalkamaladdin for spotting it), reworked the way @privatenumber decided in review: a bounded positional count instead ofBigIntand two shift paths.What this code is for
$#is the number of positional parameters ($1,$2, ...). Scripts set it throughset --, function calls andsource, but a host can also pass"#"inenvwhen it callsnew Bash(...).shift, function calls,getoptsand every positional expansion ($*,"$@",${#@},${@:n},${!#}) read$#and then loop from1to$#.Before this PR
A host calls
new Bash({ env: { "#": "1000000000", "1": "a", "2": "b" } })and runsshift; echo "$*".handleShiftreads$#withNumber.parseInt(ctx.state.env.get("#") || "0", 10): 1000000000.1to$#, callingenv.getand pushing one value per slot into an array.$*and the other positional readers inexpansion/read$#the same way and loop over the same range.Invalid array lengthonce the array cannot grow.After this PR
Same host, same script.
handleShiftreads$#throughpositionalCount(ctx).positionalCountparses it exactly as before, then compares it withctx.limits.maxArrayElements(1000000 by default).ExecutionLimitError("positional parameter limit exceeded (1000000)", "array_elements").$*,"$@", a function call or any other reader. That includes$#inside an array subscript, so${a[$#]},a[$#]=z,a=(['a[$#]']=x),unset 'a[$#]'and[[ $# -gt 0 ]]stop too instead of falling back toa[0]or an ordinary exit 1 or 2.A script whose
$#is at or below the limit takes the same path as on main.The diagram
flowchart LR classDef box fill:#eef1ff,stroke:#4c5bd4,color:#111827 classDef bad fill:#ffd6d6,stroke:#cc0000,color:#111827,stroke-width:3px classDef good fill:#c8f0c8,stroke:#008800,color:#111827,stroke-width:3px subgraph BEFORE["BEFORE: $# = 1000000000 hangs or crashes"] direction TB B1["host seeds $#, script runs shift or $*"] --> B2["handleShift or a $* reader"] B2 --> B3["Number.parseInt reads $#"] B3 --> B4{"loop from 1 to $#"} B4 -->|"$# is huge"| B5["hang or Invalid array length"] B4 -->|"$# is small"| B6["works"] end subgraph AFTER["AFTER: exit 126 in about 55 ms"] direction TB A1["host seeds $#, script runs shift or $*"] --> A2["handleShift or a $* reader"] A2 --> A3["positionalCount reads $#"] A3 --> A4{"THE CHANGE: $# above maxArrayElements?"} A4 -->|"yes"| A5["ExecutionLimitError, exit 126"] A4 -->|"no"| A6["same loop as main, works"] end B1 ~~~ A1 class B1,B2,B3,B6 box class A1,A2,A3,A6 box class B4,B5 bad class A4,A5 good linkStyle 3 stroke:#cc0000,stroke-width:5px linkStyle 8 stroke:#008800,stroke-width:5px style BEFORE fill:#fff5f5,stroke:#cc0000,color:#111827 style AFTER fill:#f3fff3,stroke:#008800,color:#111827The change
The fix is
positionalCount(ctx)in the newhelpers/positional-count.ts. It replaces all 17 inlineNumber.parseInt(ctx.state.env.get("#") ...)reads inshift,getopts,callFunction,expansion.tsand the files underexpansion/. Theifthat throws iscount > ctx.limits.maxArrayElements.Three readers did not parse
$#but follow it: the bare$#and the stored$@ingetVariable, and a barefor x; doinexecuteFor. They callpositionalCount(ctx)first, so every path gives the same answer for the same$#.$#is read only where positional work happens.computeIsEmptycallspositionalCount(ctx)only in its$*and$@branches, so${foo:-bar}never reads$#.hasQuotedMultiValueAtlooks for a quoted plain"$@"in the redirect target first and reads$#only when it finds one, soecho ok > filenever reads it either.A bare
for x; doalso walks the stored$@withmatchAll(/[^ ]+/g)andappendBoundedElements, instead ofsplit(" "). A host can seed a small$#next to a$@with any number of words, and the loop now throwsfor-loop expansion element limit exceeded (N)once it passesmaxArrayElementsinstead of building the whole list. Below the limit it gives the same words assplit(" ").filter(Boolean)on main.set --, function calls andsourceset$#from their own arguments, and the existing expanded argument check already rejects more thanmaxArrayElementsof those, so they cannot write a$#above the limit. The new tests check that too.Several
catchblocks fall back when an array subscript or an arithmetic value fails to evaluate:getVariableandisVariableSetinexpansion/variable.ts, the subscript, integer and nameref fallbacks insimple-command-assignments.ts,declare,readonly,unset,test -v, the[[ ]]arithmetic operand inconditionals.ts,let, and the[[ ]]and(( ))handlers ininterpreter.ts. The index fallbacks for a compound array assignment likea=(['a[$#]']=x),${a[i]:=v}andlocal a[i]=vwork the same way. Each of thesecatchblocks now starts withrethrowFatalExecutionError(error)fromfatal-execution-error.ts, as @jamalkamaladdin suggested, so the limit error frompositionalCount, an abort and a security violation are no longer turned intoa[0],0or a plain exit 1 or 2. Other errors still take the same fallback as on main.The earlier
BigInt, sparse shift andset -u/set --changes on this branch are reverted, so those files match main.What changes for a user
sourceandset --behave exactly as on main whenever$#is at or belowmaxArrayElements, including a host seeded$#exactly at the limit.$#above the limit makes the first command that reads it stop with exit code 126 andpositional parameter limit exceeded (N), instead of hanging or crashing.$#above the limit does not touch commands that never read it:${foo:-bar},${HOME:+set}andecho ok > filework as on main.for x; doover a host seeded$@with more thanmaxArrayElementswords stops with exit code 126, even when$#is small.$#inside an array subscript (including a compound array assignment),[[ ]],(( ))orletstops the same way when it is above the limit, instead of readinga[0]or carrying on after an error message.$#from the host behaves as on main.shiftstill walks1to$#on every call, as on main. That is the same cost as a script that ranset -- $(seq 1000000)itself, and was accepted in review.helpers/positional-count.test.tscovers each reader above the limit, a count exactly at the limit, a huge count with default limits, a non numeric$#,set --and function arguments past the limit,${foo:-bar},${HOME:+set}and a plain redirect with$#above the limit, a bareforover a$@with too many words, and$#inside a subscript, a compound array assignment,declare,readonly, a nameref write,unset,test -v,[[ ]],letand(( ))(each of those fails without the fix). The bash comparison suite passes, and the rest of the suite shows no new failures.