registry_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. package commands
  2. import (
  3. "bytes"
  4. "flag"
  5. "io"
  6. "strings"
  7. "sync"
  8. "testing"
  9. "time"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/require"
  12. )
  13. // notWithheld is a stand in for a surface's own policy; these tests use ForProfiling
  14. // because it is the only such flag today, not because the registry knows about it.
  15. func notWithheld(c *Command) bool { return !c.ForProfiling }
  16. const testReason = "this surface does not run profiling commands"
  17. // textLine is a Text renderer for test commands whose result is one string.
  18. func textLine(v any, w io.Writer) error {
  19. _, err := io.WriteString(w, v.(string)+"\n")
  20. return err
  21. }
  22. func testRegistry() *Registry {
  23. r := New()
  24. r.Register(&Command{
  25. Name: "served",
  26. ShortDescription: "a command this surface serves",
  27. Run: func(fs any, a []string) (Result, error) {
  28. return Value("read " + strings.Join(a, ",")), nil
  29. },
  30. Text: textLine,
  31. })
  32. r.Register(&Command{
  33. Name: "withheld",
  34. ShortDescription: "a command this surface withholds",
  35. ForProfiling: true,
  36. Run: func(fs any, a []string) (Result, error) {
  37. return Value("wrote"), nil
  38. },
  39. Text: textLine,
  40. })
  41. return r
  42. }
  43. // TestLocalSocketServesEverythingElse: the surface serves commands by default and
  44. // withholds only those that write files on the host.
  45. func TestLocalSocketServesEverythingElse(t *testing.T) {
  46. ro := testRegistry().Filter(notWithheld, testReason)
  47. names := make([]string, 0)
  48. for _, c := range ro.All() {
  49. names = append(names, string(c.Name))
  50. }
  51. assert.ElementsMatch(t, []string{"help", "served"}, names)
  52. }
  53. func TestUnannotatedCommandIsServed(t *testing.T) {
  54. r := New()
  55. r.Register(&Command{
  56. Name: "plain",
  57. ShortDescription: "a command with no annotations",
  58. Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
  59. })
  60. cmd := r.Filter(notWithheld, testReason).Get("plain")
  61. assert.NotNil(t, cmd, "commands reach the local socket unless they say otherwise")
  62. }
  63. func TestProfilingCommandIsWithheld(t *testing.T) {
  64. r := New()
  65. r.Register(&Command{
  66. Name: "save-a-profile",
  67. ShortDescription: "drives the profiler",
  68. ForProfiling: true,
  69. Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
  70. })
  71. cmd := r.Filter(notWithheld, testReason).Get("save-a-profile")
  72. assert.Nil(t, cmd, "a profiling command must not reach the local socket")
  73. }
  74. // TestRefusesWithheldByName covers a client that knows a command exists and asks for it
  75. // anyway. The filter lives on the serving side, so the answer must not depend on what
  76. // the client was told was available.
  77. func TestRefusesWithheldByName(t *testing.T) {
  78. out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
  79. w := Output{Out: out, Err: errOut}
  80. err := testRegistry().Filter(notWithheld, testReason).DispatchArgs([]string{"withheld"}, w)
  81. require.Error(t, err)
  82. assert.Contains(t, err.Error(), "withheld is not available on this surface")
  83. assert.Empty(t, out.String(), "a withheld command must produce no output")
  84. assert.Contains(t, errOut.String(), "withheld is not available on this surface")
  85. assert.Contains(t, errOut.String(), testReason,
  86. "the registry should render the explanation the filter supplied, not one of its own")
  87. }
  88. // TestWithheldIsNotReportedAsUnknown keeps the two cases distinct: an operator who
  89. // mistypes and one who asked for a real command should not get the same answer.
  90. func TestWithheldIsNotReportedAsUnknown(t *testing.T) {
  91. out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
  92. err := testRegistry().Filter(notWithheld, testReason).DispatchArgs([]string{"no-such-command"}, Output{Out: out, Err: errOut})
  93. var f *Failure
  94. require.ErrorAs(t, err, &f, "an unknown command is a failure to the surface")
  95. assert.Contains(t, out.String(), "did not understand: no-such-command")
  96. }
  97. // TestSplitWriterKeepsOutputParseable is why the writer grew Err(): usage text on the
  98. // same stream as -json output would corrupt it.
  99. func TestSplitWriterKeepsOutputParseable(t *testing.T) {
  100. r := New()
  101. r.Register(&Command{
  102. Name: "emit",
  103. ShortDescription: "emits json",
  104. Flags: func() (*flag.FlagSet, any) {
  105. fl := flag.NewFlagSet("", flag.ContinueOnError)
  106. fl.Bool("verbose", false, "say more")
  107. return fl, nil
  108. },
  109. Run: func(fs any, a []string) (Result, error) {
  110. return Value(map[string]bool{"ok": true}), nil
  111. },
  112. })
  113. out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
  114. require.Error(t, r.DispatchArgs([]string{"emit", "-nope"}, Output{Out: out, Err: errOut}))
  115. assert.Empty(t, out.String(), "flag errors must not land on the output stream")
  116. assert.Contains(t, errOut.String(), "flag provided but not defined")
  117. }
  118. // TestMergedWriterPreservesSshBehavior: the ssh surface points both streams at one
  119. // channel, and must keep seeing a single merged stream.
  120. func TestMergedWriterPreservesSshBehavior(t *testing.T) {
  121. r := New()
  122. r.Register(&Command{
  123. Name: "emit",
  124. ShortDescription: "emits",
  125. Flags: func() (*flag.FlagSet, any) {
  126. fl := flag.NewFlagSet("", flag.ContinueOnError)
  127. fl.Bool("verbose", false, "say more")
  128. return fl, nil
  129. },
  130. Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
  131. })
  132. merged := &bytes.Buffer{}
  133. require.Error(t, r.DispatchArgs([]string{"emit", "-nope"}, MergedOutput(merged)))
  134. assert.Contains(t, merged.String(), "flag provided but not defined")
  135. }
  136. // paramRegistry holds one command with a bool flag and a duration flag, and reports what
  137. // the command saw when it ran.
  138. func paramRegistry(t *testing.T) (*Registry, *[]paramsSeen) {
  139. t.Helper()
  140. var seen []paramsSeen
  141. r := New()
  142. r.Register(&Command{
  143. Name: "set",
  144. ShortDescription: "sets things",
  145. Flags: func() (*flag.FlagSet, any) {
  146. fl := flag.NewFlagSet("", flag.ContinueOnError)
  147. s := paramsSeen{}
  148. fl.BoolVar(&s.Verbose, "verbose", false, "say more")
  149. fl.DurationVar(&s.Wait, "wait", 0, "how long")
  150. return fl, &s
  151. },
  152. Run: func(fs any, a []string) (Result, error) {
  153. seen = append(seen, *fs.(*paramsSeen))
  154. return Value("ok"), nil
  155. },
  156. })
  157. return r, &seen
  158. }
  159. type paramsSeen struct {
  160. Verbose bool
  161. Wait time.Duration
  162. }
  163. // TestInvokeReportsParametersInNameOrder: parameters arrive as an unordered object, so
  164. // with two bad ones the error must not depend on map iteration. Name order decides.
  165. func TestInvokeReportsParametersInNameOrder(t *testing.T) {
  166. r, _ := paramRegistry(t)
  167. cases := map[string]struct {
  168. params map[string]string
  169. want string
  170. }{
  171. "two unknown": {map[string]string{"zed": "1", "alpha": "1"}, `set has no parameter "alpha"`},
  172. "unknown before bad bool": {map[string]string{"aaa": "1", "verbose": "maybe"}, `set has no parameter "aaa"`},
  173. "bad bool before unknown": {map[string]string{"verbose": "maybe", "zzz": "1"}, `verbose: expected a boolean, got "maybe"`},
  174. "bad value before bad bool": {map[string]string{"wait": "soon", "verbose": "maybe"}, `verbose: expected a boolean`},
  175. }
  176. for name, tc := range cases {
  177. t.Run(name, func(t *testing.T) {
  178. // Enough runs that a map-order dependence would show.
  179. for i := 0; i < 50; i++ {
  180. _, err := Invoke(Request{Command: r.Get("set"), Params: tc.params})
  181. require.Error(t, err)
  182. assert.ErrorContains(t, err, tc.want)
  183. }
  184. })
  185. }
  186. }
  187. // TestInvokeWithABadParameterSetsNothing: a request with any bad parameter must not run
  188. // the command, and must leave nothing behind for the next request to see. The good
  189. // parameter sorts before the bad one, so a one-pass Invoke would have applied it.
  190. func TestInvokeWithABadParameterSetsNothing(t *testing.T) {
  191. r, seen := paramRegistry(t)
  192. _, err := Invoke(Request{Command: r.Get("set"), Params: map[string]string{"verbose": "true", "wait": "soon"}})
  193. require.ErrorContains(t, err, "wait:")
  194. assert.Empty(t, *seen, "the command must not run with a partial parameter set")
  195. v, err := Invoke(Request{Command: r.Get("set")})
  196. require.NoError(t, err)
  197. assert.Equal(t, "ok", v.Value)
  198. require.Len(t, *seen, 1)
  199. assert.Equal(t, paramsSeen{}, (*seen)[0], "nothing from the failed request carried over")
  200. _, err = Invoke(Request{Command: r.Get("set"), Params: map[string]string{"verbose": "true", "wait": "2s"}})
  201. require.NoError(t, err)
  202. require.Len(t, *seen, 2)
  203. assert.Equal(t, paramsSeen{Verbose: true, Wait: 2 * time.Second}, (*seen)[1])
  204. }
  205. func TestHelpListsOnlyServedCommands(t *testing.T) {
  206. out := &bytes.Buffer{}
  207. require.NoError(t, testRegistry().Filter(notWithheld, testReason).DispatchArgs(nil, MergedOutput(out)))
  208. assert.Contains(t, out.String(), "served")
  209. assert.NotContains(t, out.String(), "withheld")
  210. }
  211. func TestDispatchHelpFlag(t *testing.T) {
  212. out := &bytes.Buffer{}
  213. testRegistry().Dispatch("served -h", MergedOutput(out))
  214. assert.Contains(t, out.String(), "served - a command this surface serves")
  215. }
  216. // TestDispatchReportsUnparseableLine pins that a line shlex rejects says so on Err rather
  217. // than coming back silent, so an operator with an unbalanced quote learns the quote is the
  218. // problem instead of assuming the command is broken.
  219. func TestDispatchReportsUnparseableLine(t *testing.T) {
  220. out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
  221. testRegistry().Dispatch(`served "unterminated`, Output{Out: out, Err: errOut})
  222. assert.Empty(t, out.String())
  223. assert.Contains(t, errOut.String(), "could not parse the command line")
  224. }
  225. // TestRegisterRejectsReservedFlags pins the contract that -json and -pretty belong to the
  226. // registry, not the command. commandFlags defines them on every command's FlagSet, so a
  227. // command that declared one itself would panic with "flag redefined" the first time an
  228. // operator ran it, on a goroutine with no recover. Better to hear about it at Register.
  229. // -config and -socket are nebula ctl's, taken off its line wherever they appear, so a
  230. // command that declared one would never see it from that surface.
  231. func TestRegisterRejectsReservedFlags(t *testing.T) {
  232. for _, name := range []string{"json", "pretty", "h", "help", "config", "socket"} {
  233. t.Run(name, func(t *testing.T) {
  234. r := New()
  235. assert.PanicsWithValue(t, "commands: clash declares reserved flag -"+name, func() {
  236. r.Register(&Command{
  237. Name: "clash",
  238. Flags: func() (*flag.FlagSet, any) {
  239. fl := flag.NewFlagSet("clash", flag.ContinueOnError)
  240. fl.Bool(name, false, "")
  241. return fl, nil
  242. },
  243. Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
  244. })
  245. })
  246. })
  247. }
  248. }
  249. func TestCloneDoesNotAffectOriginal(t *testing.T) {
  250. r := testRegistry()
  251. c := r.Clone()
  252. c.Register(&Command{Name: "logout", ShortDescription: "ends the session"})
  253. assert.Nil(t, r.Get("logout"))
  254. }
  255. // TestRegistryIsSafeForConcurrentUse runs the operations the surfaces perform, filtering
  256. // and cloning per request or session, against a stream of registrations. It exists to
  257. // be run under the race detector: the map underneath is not goroutine safe.
  258. func TestRegistryIsSafeForConcurrentUse(t *testing.T) {
  259. r := testRegistry()
  260. var wg sync.WaitGroup
  261. for i := 0; i < 8; i++ {
  262. wg.Add(1)
  263. go func(i int) {
  264. defer wg.Done()
  265. for j := 0; j < 50; j++ {
  266. r.Register(&Command{
  267. Name: Name("late-" + strings.Repeat("a", i) + "-" + strings.Repeat("b", j)),
  268. ShortDescription: "registered after the surfaces started",
  269. Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
  270. })
  271. }
  272. }(i)
  273. }
  274. for i := 0; i < 8; i++ {
  275. wg.Add(1)
  276. go func() {
  277. defer wg.Done()
  278. for j := 0; j < 50; j++ {
  279. f := r.Filter(notWithheld, testReason)
  280. _ = f.Get("served")
  281. _ = f.Schema()
  282. _ = r.Clone().Match("late-")
  283. }
  284. }()
  285. }
  286. wg.Wait()
  287. f := r.Filter(notWithheld, testReason)
  288. assert.Len(t, f.Match("late-"), 8*50, "every late registration is visible once the writers finish")
  289. }
  290. // TestHelpFlagAgreesWithHelpCommand pins that -h on a command and `help <name>` print the
  291. // same text, on a clone as on the source: both render through WriteCommandHelp, and Clone
  292. // rebinds help to the copy, so a command registered on the clone is found either way.
  293. func TestHelpFlagAgreesWithHelpCommand(t *testing.T) {
  294. c := testRegistry().Clone()
  295. c.Register(&Command{
  296. Name: Logout,
  297. ShortDescription: "ends the session",
  298. Run: func(fs any, a []string) (Result, error) { return Nothing(), nil },
  299. })
  300. for _, name := range []string{"logout", "served"} {
  301. flag := &bytes.Buffer{}
  302. c.Dispatch(name+" -h", MergedOutput(flag))
  303. cmd := &bytes.Buffer{}
  304. c.Dispatch("help "+name, MergedOutput(cmd))
  305. assert.Equal(t, cmd.String(), flag.String(), name)
  306. assert.Contains(t, flag.String(), name+" - ", name)
  307. }
  308. }
  309. // TestCloneHelpSeesCloneCommands: help on a clone answers for the clone. The ssh session
  310. // registers logout on its clone, and `help logout` has to find it.
  311. func TestCloneHelpSeesCloneCommands(t *testing.T) {
  312. c := testRegistry().Clone()
  313. c.Register(&Command{Name: "logout", ShortDescription: "ends the session"})
  314. out := &bytes.Buffer{}
  315. require.NoError(t, c.DispatchArgs([]string{"help", "logout"}, MergedOutput(out)))
  316. assert.Contains(t, out.String(), "ends the session")
  317. out.Reset()
  318. require.NoError(t, c.DispatchArgs([]string{"help"}, MergedOutput(out)))
  319. assert.Contains(t, out.String(), "logout")
  320. }
  321. // TestAfterReplyRunsAfterTheReply pins the order AfterReply exists for: the reply is on
  322. // the writer before the action begins.
  323. func TestAfterReplyRunsAfterTheReply(t *testing.T) {
  324. out := &bytes.Buffer{}
  325. seen := "never ran"
  326. r := New()
  327. r.Register(&Command{
  328. Name: "act",
  329. ShortDescription: "replies, then acts",
  330. Run: func(fs any, a []string) (Result, error) {
  331. return Did("about to act"), nil
  332. },
  333. AfterReply: func() { seen = out.String() },
  334. })
  335. require.NoError(t, r.DispatchArgs([]string{"act"}, MergedOutput(out)))
  336. assert.Contains(t, seen, "about to act")
  337. assert.Equal(t, out.String(), seen)
  338. }
  339. // TestWriteCommandHelpIsTheOneRendering pins the layout both `help <command>` on the
  340. // daemon and `-h` in the client print, so the two cannot drift apart again.
  341. func TestWriteCommandHelpIsTheOneRendering(t *testing.T) {
  342. cs := CommandSchema{
  343. Name: "change-remote",
  344. Short: "changes a remote",
  345. Help: "Give it an address.",
  346. Flags: []FlagSchema{
  347. {Name: "address", Usage: "the new remote", Default: "1.2.3.4:4242"},
  348. {Name: "by-index", Bool: true, Usage: "match by index"},
  349. {Name: "json", Bool: true, Usage: "outputs as json"},
  350. },
  351. }
  352. out := &bytes.Buffer{}
  353. require.NoError(t, WriteCommandHelp(cs, out))
  354. assert.Equal(t, "change-remote - changes a remote\n"+
  355. " Give it an address.\n"+
  356. " -address string\n \tthe new remote (default 1.2.3.4:4242)\n"+
  357. " -by-index\n \tmatch by index\n"+
  358. " -json\n \toutputs as json\n", out.String())
  359. }
  360. // addrFlags is the flag struct of a test command that takes -address.
  361. type addrFlags struct{ Address string }
  362. // TestHelpFlagIsReadWhereParseReadsIt: -h asks for help only where the line's parser
  363. // reads it as a flag. As a flag's value or after -- it reaches the command as the
  364. // operand it is, and help is rendered by the same function `help <command>` uses.
  365. func TestHelpFlagIsReadWhereParseReadsIt(t *testing.T) {
  366. var seen []string
  367. r := New()
  368. r.Register(Flagged(&Command{Name: "x", ShortDescription: "takes an address"},
  369. func(fl *flag.FlagSet, s *addrFlags) { fl.StringVar(&s.Address, "address", "", "an address") },
  370. func(s *addrFlags, a []string) (Result, error) {
  371. seen = append(seen, s.Address+"|"+strings.Join(a, ","))
  372. return Nothing(), nil
  373. }))
  374. for _, line := range []string{"x -h", "x -help", "x --help", "x 10.0.0.1 -h", "x -address=1 -h"} {
  375. out := &bytes.Buffer{}
  376. r.Dispatch(line, MergedOutput(out))
  377. assert.Contains(t, out.String(), "x - takes an address\n", line)
  378. assert.Contains(t, out.String(), "-address string", line)
  379. }
  380. assert.Empty(t, seen, "asking for help must not run the command")
  381. for _, line := range []string{"x -address -h", "x -- -h"} {
  382. out := &bytes.Buffer{}
  383. r.Dispatch(line, MergedOutput(out))
  384. assert.Empty(t, out.String(), line)
  385. }
  386. assert.Equal(t, []string{"-h|", "|-h"}, seen)
  387. }
  388. // TestBadFlagIsAnsweredWithTheCommandsHelp: a flag the command does not have is reported
  389. // on the error stream followed by the command's usage, in the rendering help uses.
  390. func TestBadFlagIsAnsweredWithTheCommandsHelp(t *testing.T) {
  391. out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
  392. r := New()
  393. r.Register(&Command{Name: "x", ShortDescription: "has no flags", Run: func(fs any, a []string) (Result, error) { return Nothing(), nil }})
  394. require.Error(t, r.DispatchArgs([]string{"x", "-nope"}, Output{Out: out, Err: errOut}))
  395. assert.Empty(t, out.String())
  396. assert.Equal(t, "flag provided but not defined: -nope\nx - has no flags\n -json\n \toutputs as json\n -pretty\n \tpretty prints json, assumes -json\n", errOut.String())
  397. }