neofs-node icon indicating copy to clipboard operation
neofs-node copied to clipboard

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

Open cthulhu-rider opened this issue 8 months ago • 1 comments

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

  • review #2875
  • a bit related about array flags https://github.com/spf13/pflag/issues/184

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 avatar Jun 28 '24 13:06 cthulhu-rider