nspcc-dev / neofs-node

NeoFS is a decentralized distributed object storage integrated with the Neo blockchain
https://fs.neo.org
GNU General Public License v3.0
31 stars 38 forks source link

Check that all Cobra commands check length slice flags for emptiness if required #2879

Open cthulhu-rider opened 1 week ago

cthulhu-rider commented 1 week ago

https://pkg.go.dev/github.com/spf13/cobra is a std engine for NeoFS command line tools. Some commands accept declare flag(s) of slice/array type. They are passed as --flag XXX --flag XXX .... Then Cobra parses them into Go []T where exact T varies, e.g. StringSlice

there is one feature (???) of parsing such flags: a missing optional flag is treated the same as an explicitly specified with empty values:

$ ./cmd
$ ./cmd --flag "" --flag ""
// parsed to nothing
$ ./cmd --flag "" --flag "abc" --flag "" --flag "def"
// parsed to [abc, def]

note that if --flag is marked required, then 1st command will Error: required flag(s) "oid" not set while 2nd is still parsed as an empty slice

this not very obvious behavior can make the execution of some commands quite unexpected. For example, when command does useful actions in for loop

Expected Behavior

when command accepts slice flag and parses each element which must not be an empty string (like container/object/user IDs), passing --flag "" leads to zero-len failure

Current Behavior

if command checks flag len explicitly - fail, otherwise empty element just lost, and command may become even no-op

Possible Solution

always check length of required slice/array flags

Steps to Reproduce (for bugs)

$ neofs-cli object lock --cid F74twfixT89Wqc4qh32Yj5vzP6p9gQ7dxJCzp3C311an --lifetime 100 -r localhost:8080
Error: required flag(s) "oid" not set
$ neofs-cli object lock --cid F74twfixT89Wqc4qh32Yj5vzP6p9gQ7dxJCzp3C311an --oid 'abc' --lifetime 100 -r localhost:8080
Incorrect object arg #1: invalid length 3
$ neofs-cli object lock --cid F74twfixT89Wqc4qh32Yj5vzP6p9gQ7dxJCzp3C311an --oid '' --lifetime 100 -r localhost:8080
Store lock object in NeoFS: finish object stream: status: code = 3072 message = container not found

Context

this may also appear when working with env vars:

$ neofs-cli object lock --cid F74twfixT89Wqc4qh32Yj5vzP6p9gQ7dxJCzp3C311an --oid "$OID" --lifetime 100 -r localhost:8080

if OID will be empty for some reason, this wont be detected

Regression

no

Your Environment

cthulhu-rider commented 1 week ago

the reason is pretty understandable: such flags are CSV. For example, --flag "," is ["", ""]