4
0

executor_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. package executor
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strings"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/OliveTin/OliveTin/internal/auth"
  10. authpublic "github.com/OliveTin/OliveTin/internal/auth/authpublic"
  11. config "github.com/OliveTin/OliveTin/internal/config"
  12. "github.com/OliveTin/OliveTin/internal/entities"
  13. )
  14. func testingExecutor() (*Executor, *config.Config) {
  15. cfg := config.DefaultConfig()
  16. e := DefaultExecutor(cfg)
  17. a1 := &config.Action{
  18. Title: "Do some tickles",
  19. Shell: "echo 'Tickling {{ person }}'",
  20. Arguments: []config.ActionArgument{
  21. {
  22. Name: "person",
  23. Type: "ascii",
  24. },
  25. },
  26. }
  27. cfg.Actions = append(cfg.Actions, a1)
  28. cfg.Sanitize()
  29. return e, cfg
  30. }
  31. func TestCreateExecutorAndExec(t *testing.T) {
  32. e, cfg := testingExecutor()
  33. req := ExecutionRequest{
  34. AuthenticatedUser: &authpublic.AuthenticatedUser{Username: "MrTickle"},
  35. Cfg: cfg,
  36. Arguments: map[string]string{
  37. "person": "yourself",
  38. },
  39. }
  40. // Ensure bindings are available and set the binding to the only configured action
  41. e.RebuildActionMap()
  42. if len(cfg.Actions) > 0 {
  43. req.Binding = e.FindBindingWithNoEntity(cfg.Actions[0])
  44. }
  45. assert.NotNil(t, e, "Create an executor")
  46. wg, _ := e.ExecRequest(&req)
  47. wg.Wait()
  48. assert.Equal(t, int32(0), req.logEntry.ExitCode, "Exit code is zero")
  49. }
  50. func TestStepRequestActionPopulateLogEntryResolvesEntityTemplates(t *testing.T) {
  51. req := &ExecutionRequest{
  52. logEntry: &InternalLogEntry{},
  53. Binding: &ActionBinding{
  54. Action: &config.Action{
  55. Title: "Do something with {{ project.name }}",
  56. Icon: "{{ project.icon }}",
  57. },
  58. Entity: &entities.Entity{
  59. Data: map[string]any{
  60. "name": "foo",
  61. "icon": "🐰",
  62. },
  63. UniqueKey: "foo-key",
  64. },
  65. },
  66. }
  67. stepRequestActionPopulateLogEntry(req)
  68. assert.Equal(t, "Do something with foo", req.logEntry.ActionTitle)
  69. assert.Equal(t, "🐰", req.logEntry.ActionIcon)
  70. assert.Equal(t, "Do something with {{ project.name }}", req.logEntry.ActionConfigTitle)
  71. assert.Equal(t, "foo-key", req.logEntry.EntityPrefix)
  72. }
  73. func TestExecNonExistant(t *testing.T) {
  74. e, cfg := testingExecutor()
  75. req := ExecutionRequest{
  76. // Binding: e.FindBindingWithNoEntity("waffles"),
  77. logEntry: &InternalLogEntry{},
  78. Cfg: cfg,
  79. }
  80. wg, _ := e.ExecRequest(&req)
  81. wg.Wait()
  82. assert.Equal(t, int32(-1337), req.logEntry.ExitCode, "Log entry is set to an internal error code")
  83. assert.Equal(t, "💩", req.logEntry.ActionIcon, "Log entry icon is a poop (not found)")
  84. }
  85. func TestArgumentNameCamelCase(t *testing.T) {
  86. req := newExecRequest()
  87. req.Binding.Action = &config.Action{
  88. Title: "Do some tickles",
  89. Shell: "echo 'Tickling {{ personName }}'",
  90. Arguments: []config.ActionArgument{
  91. {
  92. Name: "personName",
  93. Type: "ascii",
  94. },
  95. },
  96. }
  97. req.Arguments = map[string]string{
  98. "personName": "Fred",
  99. }
  100. out, err := parseActionArguments(req)
  101. assert.Equal(t, "echo 'Tickling Fred'", out)
  102. assert.Nil(t, err)
  103. }
  104. func TestArgumentNameSnakeCase(t *testing.T) {
  105. req := newExecRequest()
  106. req.Binding.Action = &config.Action{
  107. Title: "Do some tickles",
  108. Shell: "echo 'Tickling {{ person_name }}'",
  109. Arguments: []config.ActionArgument{
  110. {
  111. Name: "person_name",
  112. Type: "ascii",
  113. },
  114. },
  115. }
  116. req.Arguments = map[string]string{
  117. "person_name": "Fred",
  118. }
  119. out, err := parseActionArguments(req)
  120. assert.Equal(t, "echo 'Tickling Fred'", out)
  121. assert.Nil(t, err)
  122. }
  123. func TestGetLogsEmpty(t *testing.T) {
  124. e, cfg := testingExecutor()
  125. assert.Equal(t, int64(10), cfg.LogHistoryPageSize, "Logs page size should be 10")
  126. logs, paging := e.GetLogTrackingIds(0, 10)
  127. assert.NotNil(t, logs, "Logs should not be nil")
  128. assert.Equal(t, 0, len(logs), "No logs yet")
  129. assert.Equal(t, int64(0), paging.CountRemaining, "There should be no remaining logs")
  130. }
  131. func TestGetLogsLessThanPageSize(t *testing.T) {
  132. e, cfg := testingExecutor()
  133. cfg.Actions = append(cfg.Actions, &config.Action{
  134. Title: "blat",
  135. Shell: "date",
  136. })
  137. cfg.Sanitize()
  138. // Rebuild action map to include newly added action
  139. e.RebuildActionMap()
  140. assert.Equal(t, int64(10), cfg.LogHistoryPageSize, "Logs page size should be 10")
  141. logEntries, paging := e.GetLogTrackingIds(0, 10)
  142. assert.Equal(t, 0, len(logEntries), "There should be 0 logs")
  143. assert.Zero(t, paging.CountRemaining, "There should be no remaining logs")
  144. execNewReqAndWait(e, "blat", cfg)
  145. execNewReqAndWait(e, "blat", cfg)
  146. execNewReqAndWait(e, "blat", cfg)
  147. execNewReqAndWait(e, "blat", cfg)
  148. execNewReqAndWait(e, "blat", cfg)
  149. execNewReqAndWait(e, "blat", cfg)
  150. execNewReqAndWait(e, "blat", cfg)
  151. logEntries, paging = e.GetLogTrackingIds(0, 10)
  152. assert.Equal(t, 7, len(logEntries), "There should be 7 logs")
  153. assert.Zero(t, paging.CountRemaining, "There should be no remaining logs")
  154. execNewReqAndWait(e, "blat", cfg)
  155. execNewReqAndWait(e, "blat", cfg)
  156. execNewReqAndWait(e, "blat", cfg)
  157. execNewReqAndWait(e, "blat", cfg)
  158. execNewReqAndWait(e, "blat", cfg)
  159. logEntries, paging = e.GetLogTrackingIds(0, 10)
  160. assert.Equal(t, 10, len(logEntries), "There should be 10 logs")
  161. assert.Equal(t, int64(2), paging.CountRemaining, "There should be 1 remaining logs")
  162. }
  163. func execNewReqAndWait(e *Executor, title string, cfg *config.Config) {
  164. req := &ExecutionRequest{
  165. // ActionTitle: title,
  166. Cfg: cfg,
  167. }
  168. // Ensure we have a binding for the requested title
  169. e.RebuildActionMap()
  170. var action *config.Action
  171. for _, a := range cfg.Actions {
  172. if a.Title == title {
  173. action = a
  174. break
  175. }
  176. }
  177. if action != nil {
  178. req.Binding = e.FindBindingWithNoEntity(action)
  179. }
  180. wg, _ := e.ExecRequest(req)
  181. wg.Wait()
  182. }
  183. func TestGetPagingIndexes(t *testing.T) {
  184. assert.Zero(t, getPagingStartIndex(5, 0), "Testing start index from empty list")
  185. assert.Equal(t, int64(4), getPagingStartIndex(5, 10), "Testing start index from mid point")
  186. assert.Equal(t, int64(9), getPagingStartIndex(-1, 10), "Testing start index with negative offset")
  187. assert.Equal(t, int64(0), getPagingStartIndex(15, 10), "Testing start index with large offset")
  188. assert.Equal(t, int64(9), getPagingStartIndex(0, 10), "Testing start index with zero count")
  189. }
  190. func TestUnsetRequiredArgument(t *testing.T) {
  191. req := newExecRequest()
  192. req.Binding.Action = &config.Action{
  193. Title: "Print your name",
  194. Shell: "echo 'Your name is: {{ name }}'",
  195. Arguments: []config.ActionArgument{
  196. {
  197. Name: "name",
  198. Type: "ascii",
  199. },
  200. },
  201. }
  202. req.Arguments = map[string]string{}
  203. out, err := parseActionArguments(req)
  204. assert.Equal(t, "", out)
  205. assert.NotNil(t, err)
  206. }
  207. func TestUnusedArgumentStillPassesTypeSafetyCheck(t *testing.T) {
  208. req := newExecRequest()
  209. req.Binding.Action = &config.Action{
  210. Title: "Print your name",
  211. Shell: "echo 'Your name is: {{ name }}'",
  212. Arguments: []config.ActionArgument{
  213. {
  214. Name: "name",
  215. Type: "ascii",
  216. },
  217. {
  218. Name: "age",
  219. Type: "int",
  220. },
  221. },
  222. }
  223. req.Arguments = map[string]string{
  224. "name": "Fred",
  225. "age": "Not an integer",
  226. }
  227. out, err := parseActionArguments(req)
  228. assert.Equal(t, "", out)
  229. assert.NotNil(t, err)
  230. }
  231. // https://github.com/OliveTin/OliveTin/issues/564
  232. func TestMangleInvalidArgumentValues(t *testing.T) {
  233. e, cfg := testingExecutor()
  234. a1 := &config.Action{
  235. Title: "Validate my date without seconds because I am from an Android phone",
  236. Shell: "echo 'The date is: {{ date }}'",
  237. Arguments: []config.ActionArgument{
  238. {
  239. Name: "date",
  240. Type: "datetime",
  241. },
  242. },
  243. }
  244. cfg.Actions = append(cfg.Actions, a1)
  245. cfg.Sanitize()
  246. // Build bindings for newly added action
  247. e.RebuildActionMap()
  248. req := ExecutionRequest{
  249. // Action: a1,
  250. AuthenticatedUser: auth.UserFromSystem(cfg, "testuser"),
  251. Cfg: cfg,
  252. Arguments: map[string]string{
  253. "date": "1990-01-10T12:00", // Invalid format, should be without seconds
  254. },
  255. }
  256. // Set binding to our appended action
  257. req.Binding = e.FindBindingWithNoEntity(a1)
  258. wg, _ := e.ExecRequest(&req)
  259. wg.Wait()
  260. assert.NotNil(t, req.logEntry, "Log entry should not be nil")
  261. assert.Equal(t, req.logEntry.Output, "The date is: 1990-01-10T12:00:00\n", "Date should be mangled to a valid format")
  262. }
  263. func TestWebhookRejectsShellExecution(t *testing.T) {
  264. cfg := config.DefaultConfig()
  265. e := DefaultExecutor(cfg)
  266. a1 := &config.Action{
  267. Title: "Webhook Shell Reject",
  268. Shell: "echo '{{ msg }}'",
  269. Arguments: []config.ActionArgument{
  270. {Name: "msg", Type: "ascii"},
  271. },
  272. }
  273. cfg.Actions = append(cfg.Actions, a1)
  274. cfg.Sanitize()
  275. e.RebuildActionMap()
  276. req := ExecutionRequest{
  277. Tags: []string{"webhook"},
  278. AuthenticatedUser: auth.UserFromSystem(cfg, "webhook"),
  279. Cfg: cfg,
  280. Arguments: map[string]string{"msg": "hello"},
  281. Binding: e.FindBindingWithNoEntity(a1),
  282. }
  283. wg, _ := e.ExecRequest(&req)
  284. wg.Wait()
  285. assert.NotNil(t, req.logEntry)
  286. assert.Equal(t, int32(-1337), req.logEntry.ExitCode)
  287. assert.Contains(t, req.logEntry.Output, "webhooks cannot use Shell execution")
  288. }
  289. func TestWebhookAllowsExecExecution(t *testing.T) {
  290. cfg := config.DefaultConfig()
  291. e := DefaultExecutor(cfg)
  292. a1 := &config.Action{
  293. Title: "Webhook Exec OK",
  294. Exec: []string{"echo", "{{ msg }}"},
  295. Arguments: []config.ActionArgument{
  296. {Name: "msg", Type: "ascii"},
  297. },
  298. }
  299. cfg.Actions = append(cfg.Actions, a1)
  300. cfg.Sanitize()
  301. e.RebuildActionMap()
  302. req := ExecutionRequest{
  303. Tags: []string{"webhook"},
  304. AuthenticatedUser: auth.UserFromSystem(cfg, "webhook"),
  305. Cfg: cfg,
  306. Arguments: map[string]string{"msg": "hello"},
  307. Binding: e.FindBindingWithNoEntity(a1),
  308. }
  309. wg, _ := e.ExecRequest(&req)
  310. wg.Wait()
  311. assert.NotNil(t, req.logEntry)
  312. assert.Equal(t, int32(0), req.logEntry.ExitCode)
  313. assert.Contains(t, req.logEntry.Output, "hello")
  314. }
  315. func TestWebhookRejectsShellAfterCompleted(t *testing.T) {
  316. cfg := config.DefaultConfig()
  317. e := DefaultExecutor(cfg)
  318. a1 := &config.Action{
  319. Title: "Webhook After Shell Reject",
  320. Exec: []string{"echo", "{{ msg }}"},
  321. ShellAfterCompleted: "echo after",
  322. Arguments: []config.ActionArgument{
  323. {Name: "msg", Type: "ascii"},
  324. },
  325. }
  326. cfg.Actions = append(cfg.Actions, a1)
  327. cfg.Sanitize()
  328. e.RebuildActionMap()
  329. req := ExecutionRequest{
  330. Tags: []string{"webhook"},
  331. AuthenticatedUser: auth.UserFromSystem(cfg, "webhook"),
  332. Cfg: cfg,
  333. Arguments: map[string]string{"msg": "hello"},
  334. Binding: e.FindBindingWithNoEntity(a1),
  335. }
  336. wg, _ := e.ExecRequest(&req)
  337. wg.Wait()
  338. assert.NotNil(t, req.logEntry)
  339. assert.Contains(t, req.logEntry.Output, "webhooks cannot use shellAfterCompleted")
  340. }
  341. func TestShellAfterCompletedUsesOutputEnvSafely(t *testing.T) {
  342. cfg := config.DefaultConfig()
  343. e := DefaultExecutor(cfg)
  344. injectedPath := filepath.Join(t.TempDir(), "olivetin-injected")
  345. a1 := &config.Action{
  346. Title: "After completion escape",
  347. Shell: "printf %s \"'; touch " + injectedPath + "; echo '\"",
  348. ShellAfterCompleted: "printf %s '{{ output }}'",
  349. }
  350. cfg.Actions = append(cfg.Actions, a1)
  351. cfg.Sanitize()
  352. e.RebuildActionMap()
  353. req := ExecutionRequest{
  354. AuthenticatedUser: auth.UserFromSystem(cfg, "cron"),
  355. Cfg: cfg,
  356. Binding: e.FindBindingWithNoEntity(a1),
  357. }
  358. wg, _ := e.ExecRequest(&req)
  359. wg.Wait()
  360. assert.NotNil(t, req.logEntry)
  361. assert.Equal(t, int32(0), req.logEntry.ExitCode)
  362. _, err := os.Stat(injectedPath)
  363. assert.True(t, os.IsNotExist(err), "shellAfterCompleted must not execute injected commands from output")
  364. }
  365. func TestFilterToDefinedArgumentsOnly(t *testing.T) {
  366. req := newExecRequest()
  367. req.Binding.Action = &config.Action{
  368. Title: "Filter test",
  369. Shell: "echo '{{ name }}'",
  370. Arguments: []config.ActionArgument{
  371. {Name: "name", Type: "ascii"},
  372. },
  373. }
  374. req.Arguments = map[string]string{
  375. "name": "Alice",
  376. "webhook_path": "/malicious/$(id)",
  377. "extra_undefined": "ignored",
  378. }
  379. filterToDefinedArgumentsOnly(req)
  380. assert.Equal(t, "Alice", req.Arguments["name"])
  381. assert.Empty(t, req.Arguments["webhook_path"])
  382. assert.Empty(t, req.Arguments["extra_undefined"])
  383. }
  384. func TestFilterToDefinedArgumentsDropsReservedPrefixArgs(t *testing.T) {
  385. req := newExecRequest()
  386. req.Binding.Action = &config.Action{
  387. Title: "Filter test",
  388. Shell: "echo test",
  389. Arguments: []config.ActionArgument{},
  390. }
  391. req.Arguments = map[string]string{
  392. "ot_executionTrackingId": "track-123",
  393. "ot_username": "webhook",
  394. }
  395. filterToDefinedArgumentsOnly(req)
  396. assert.Empty(t, req.Arguments["ot_executionTrackingId"])
  397. assert.Empty(t, req.Arguments["ot_username"])
  398. }
  399. func TestStepParseArgsInjectsSystemArgsAfterFiltering(t *testing.T) {
  400. req := newExecRequest()
  401. req.TrackingID = "server-track-456"
  402. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice"}
  403. req.Binding.Action = &config.Action{
  404. Title: "Filter then inject",
  405. Shell: "echo test",
  406. Arguments: []config.ActionArgument{
  407. {Name: "name", Type: "ascii"},
  408. },
  409. }
  410. req.Arguments = map[string]string{
  411. "name": "Alice",
  412. "ot_executionTrackingId": "attacker-track",
  413. "ot_username": "mallory",
  414. "ot_custom": "polluted",
  415. }
  416. assert.True(t, stepParseArgs(req))
  417. assert.Equal(t, "Alice", req.Arguments["name"])
  418. assert.Equal(t, "server-track-456", req.Arguments["ot_executionTrackingId"])
  419. assert.Equal(t, "alice", req.Arguments["ot_username"])
  420. assert.Empty(t, req.Arguments["ot_custom"])
  421. }
  422. func TestStepParseArgsDropsReservedPrefixArgsFromEnvironment(t *testing.T) {
  423. req := newExecRequest()
  424. req.TrackingID = "server-track-456"
  425. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice@example.com"}
  426. req.Binding.Action = &config.Action{
  427. Title: "No reserved prefix pollution",
  428. Shell: "echo test",
  429. Arguments: []config.ActionArgument{},
  430. }
  431. req.Arguments = map[string]string{
  432. "ot_custom": "polluted",
  433. }
  434. assert.True(t, stepParseArgs(req))
  435. env := buildEnv(req.Arguments)
  436. assert.False(t, containsEnvPrefix(env, "OT_CUSTOM="))
  437. assert.True(t, containsEnvPrefix(env, "OT_USERNAME=alice@example.com"))
  438. assert.True(t, containsEnvPrefix(env, "OT_EXECUTIONTRACKINGID=server-track-456"))
  439. }
  440. func TestSystemArgumentDefinitionsAreReservedAndShellSafe(t *testing.T) {
  441. unsafeTypes := map[string]struct{}{
  442. "email": {},
  443. "password": {},
  444. "raw_string_multiline": {},
  445. "url": {},
  446. "very_dangerous_raw_string": {},
  447. }
  448. seen := map[string]struct{}{}
  449. for _, arg := range systemArgumentDefinitions {
  450. assert.True(t, strings.HasPrefix(arg.Name, config.ReservedArgumentNamePrefix))
  451. assert.NotEmpty(t, arg.Type)
  452. assert.True(t, arg.RejectNull)
  453. _, duplicate := seen[arg.Name]
  454. assert.False(t, duplicate, "duplicate system argument definition %q", arg.Name)
  455. seen[arg.Name] = struct{}{}
  456. _, unsafe := unsafeTypes[arg.Type]
  457. assert.False(t, unsafe, "system argument %q uses unsafe type %q", arg.Name, arg.Type)
  458. }
  459. }
  460. func TestValidatedSystemArgsMatchesSystemArgumentDefinitions(t *testing.T) {
  461. req := newExecRequest()
  462. req.TrackingID = "server-track-456"
  463. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice@example.com"}
  464. args, err := validatedSystemArgs(req)
  465. assert.Nil(t, err)
  466. assert.Len(t, args, len(systemArgumentDefinitions))
  467. for _, arg := range systemArgumentDefinitions {
  468. assert.Contains(t, args, arg.Name)
  469. }
  470. }
  471. func TestBuildShellAfterArgsOnlyAddsExpectedNonSystemArgs(t *testing.T) {
  472. req := newExecRequest()
  473. req.logEntry = &InternalLogEntry{
  474. Output: "hello",
  475. ExitCode: 7,
  476. }
  477. req.TrackingID = "server-track-456"
  478. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice@example.com"}
  479. req.Binding.Action = &config.Action{ShellAfterCompleted: "echo test"}
  480. args, err := buildShellAfterArgs(req)
  481. assert.Nil(t, err)
  482. assert.Len(t, args, len(systemArgumentDefinitions)+2)
  483. assert.Contains(t, args, "output")
  484. assert.Contains(t, args, "exitCode")
  485. for _, arg := range systemArgumentDefinitions {
  486. assert.Contains(t, args, arg.Name)
  487. }
  488. }
  489. func TestStepParseArgsAllowsEmailUsernameSystemArg(t *testing.T) {
  490. req := newExecRequest()
  491. req.logEntry = &InternalLogEntry{}
  492. req.TrackingID = "server-track-456"
  493. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice@example.com"}
  494. req.Binding.Action = &config.Action{
  495. Title: "Email username",
  496. Shell: "echo test",
  497. Arguments: []config.ActionArgument{},
  498. }
  499. assert.True(t, stepParseArgs(req))
  500. assert.Equal(t, "alice@example.com", req.Arguments["ot_username"])
  501. }
  502. func TestStepParseArgsFailsWhenUsernameSystemArgIsInvalid(t *testing.T) {
  503. req := newExecRequest()
  504. req.logEntry = &InternalLogEntry{}
  505. req.TrackingID = "server-track-456"
  506. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice;id"}
  507. req.Binding.Action = &config.Action{
  508. Title: "Invalid system arg",
  509. Shell: "echo test",
  510. Arguments: []config.ActionArgument{},
  511. }
  512. assert.False(t, stepParseArgs(req))
  513. assert.Contains(t, req.logEntry.Output, `system argument "ot_username" failed validation`)
  514. assert.Empty(t, req.Arguments["ot_username"])
  515. }
  516. func TestStepParseArgsFailsWhenTrackingIDSystemArgIsInvalid(t *testing.T) {
  517. req := newExecRequest()
  518. req.logEntry = &InternalLogEntry{}
  519. req.TrackingID = "track/../../bad"
  520. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice"}
  521. req.Binding.Action = &config.Action{
  522. Title: "Invalid tracking ID",
  523. Shell: "echo test",
  524. Arguments: []config.ActionArgument{},
  525. }
  526. assert.False(t, stepParseArgs(req))
  527. assert.Contains(t, req.logEntry.Output, `system argument "ot_executionTrackingId" failed validation`)
  528. assert.Empty(t, req.Arguments["ot_executionTrackingId"])
  529. }
  530. func TestBuildShellAfterArgsUsesValidatedSystemArgs(t *testing.T) {
  531. req := newExecRequest()
  532. req.logEntry = &InternalLogEntry{
  533. Output: "hello",
  534. ExitCode: 7,
  535. }
  536. req.TrackingID = "server-track-456"
  537. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice@example.com"}
  538. req.Binding.Action = &config.Action{
  539. Title: "Shell after",
  540. ShellAfterCompleted: "echo test",
  541. }
  542. args, err := buildShellAfterArgs(req)
  543. assert.Nil(t, err)
  544. assert.Equal(t, "alice@example.com", args["ot_username"])
  545. assert.Equal(t, "server-track-456", args["ot_executionTrackingId"])
  546. assert.Equal(t, "hello", args["output"])
  547. assert.Equal(t, "7", args["exitCode"])
  548. }
  549. func TestBuildShellAfterArgsFailsWhenSystemArgIsInvalid(t *testing.T) {
  550. req := newExecRequest()
  551. req.logEntry = &InternalLogEntry{}
  552. req.TrackingID = "server-track-456"
  553. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice;id"}
  554. req.Binding.Action = &config.Action{
  555. Title: "Shell after invalid username",
  556. ShellAfterCompleted: "echo test",
  557. }
  558. args, err := buildShellAfterArgs(req)
  559. assert.Nil(t, args)
  560. assert.NotNil(t, err)
  561. assert.Contains(t, err.Error(), `system argument "ot_username" failed validation`)
  562. }
  563. func containsEnvPrefix(env []string, prefix string) bool {
  564. for _, item := range env {
  565. if strings.HasPrefix(item, prefix) {
  566. return true
  567. }
  568. }
  569. return false
  570. }
  571. func TestTriggerExecutesTriggeredAction(t *testing.T) {
  572. cfg := config.DefaultConfig()
  573. e := DefaultExecutor(cfg)
  574. helloAction := &config.Action{
  575. Title: "Hello world",
  576. Shell: "echo 'Hello World!'",
  577. }
  578. triggerAction := &config.Action{
  579. Title: "Simple action that triggers another action",
  580. Shell: "echo 'Hi'",
  581. Triggers: []string{"Hello world"},
  582. }
  583. cfg.Actions = append(cfg.Actions, helloAction, triggerAction)
  584. cfg.Sanitize()
  585. e.RebuildActionMap()
  586. finishedTitles := make(chan string, 4)
  587. collector := &executionFinishedCollector{ch: finishedTitles}
  588. e.AddListener(collector)
  589. req := &ExecutionRequest{
  590. AuthenticatedUser: auth.UserFromSystem(cfg, "testuser"),
  591. Cfg: cfg,
  592. Binding: e.FindBindingWithNoEntity(triggerAction),
  593. }
  594. wg, _ := e.ExecRequest(req)
  595. wg.Wait()
  596. var got []string
  597. for i := 0; i < 2; i++ {
  598. select {
  599. case title := <-finishedTitles:
  600. got = append(got, title)
  601. case <-time.After(2 * time.Second):
  602. t.Fatalf("timed out waiting for execution %d; got %v", i+1, got)
  603. }
  604. }
  605. assert.Contains(t, got, "Hello world", "triggered action must run")
  606. assert.Contains(t, got, "Simple action that triggers another action", "triggering action must run")
  607. }
  608. func TestTriggerUnknownActionTitleSkipsWithoutPanic(t *testing.T) {
  609. cfg := config.DefaultConfig()
  610. e := DefaultExecutor(cfg)
  611. triggerAction := &config.Action{
  612. Title: "Action with bad trigger",
  613. Shell: "echo 'ok'",
  614. Triggers: []string{"Nonexistent action"},
  615. }
  616. cfg.Actions = append(cfg.Actions, triggerAction)
  617. cfg.Sanitize()
  618. e.RebuildActionMap()
  619. finishedTitles := make(chan string, 4)
  620. collector := &executionFinishedCollector{ch: finishedTitles}
  621. e.AddListener(collector)
  622. req := &ExecutionRequest{
  623. AuthenticatedUser: auth.UserFromSystem(cfg, "testuser"),
  624. Cfg: cfg,
  625. Binding: e.FindBindingWithNoEntity(triggerAction),
  626. }
  627. wg, _ := e.ExecRequest(req)
  628. wg.Wait()
  629. var got []string
  630. select {
  631. case title := <-finishedTitles:
  632. got = append(got, title)
  633. case <-time.After(500 * time.Millisecond):
  634. }
  635. assert.Len(t, got, 1, "only the triggering action runs; unknown trigger is skipped")
  636. if len(got) > 0 {
  637. assert.Equal(t, "Action with bad trigger", got[0])
  638. }
  639. }
  640. type executionFinishedCollector struct {
  641. ch chan string
  642. }
  643. func (c *executionFinishedCollector) OnExecutionStarted(_ *InternalLogEntry) {}
  644. func (c *executionFinishedCollector) OnExecutionFinished(entry *InternalLogEntry) {
  645. c.ch <- entry.ActionTitle
  646. }
  647. func (c *executionFinishedCollector) OnOutputChunk(_ []byte, _ string) {}
  648. func (c *executionFinishedCollector) OnActionMapRebuilt() {}