4
0

executor_test.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  1. package executor
  2. import (
  3. "os"
  4. "path/filepath"
  5. "slices"
  6. "strings"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/stretchr/testify/require"
  11. "github.com/OliveTin/OliveTin/internal/auth"
  12. authpublic "github.com/OliveTin/OliveTin/internal/auth/authpublic"
  13. config "github.com/OliveTin/OliveTin/internal/config"
  14. "github.com/OliveTin/OliveTin/internal/entities"
  15. )
  16. func testingExecutor() (*Executor, *config.Config) {
  17. cfg := config.DefaultConfig()
  18. e := DefaultExecutor(cfg)
  19. a1 := &config.Action{
  20. Title: "Do some tickles",
  21. Shell: "echo 'Tickling {{ person }}'",
  22. Arguments: []config.ActionArgument{
  23. {
  24. Name: "person",
  25. Type: "ascii",
  26. },
  27. },
  28. }
  29. cfg.Actions = append(cfg.Actions, a1)
  30. cfg.Sanitize()
  31. return e, cfg
  32. }
  33. func TestGetLogReturnsDefensiveCopy(t *testing.T) {
  34. e := DefaultExecutor(config.DefaultConfig())
  35. e.logs["tracking-id"] = &InternalLogEntry{
  36. Arguments: map[string]string{"message": "original"},
  37. Output: "original",
  38. Tags: []string{"original"},
  39. Binding: &ActionBinding{
  40. ID: "original-binding",
  41. OnDashboards: []DashboardNavigationTarget{
  42. {Title: "original"},
  43. },
  44. },
  45. }
  46. entry, found := e.GetLog("tracking-id")
  47. require.True(t, found)
  48. entry.Arguments["message"] = "changed"
  49. entry.Output = "changed"
  50. entry.Tags[0] = "changed"
  51. entry.Binding.ID = "changed-binding"
  52. entry.Binding.OnDashboards[0].Title = "changed"
  53. stored, found := e.GetLog("tracking-id")
  54. require.True(t, found)
  55. assert.Equal(t, "original", stored.Arguments["message"])
  56. assert.Equal(t, "original", stored.Output)
  57. assert.Equal(t, []string{"original"}, stored.Tags)
  58. require.NotNil(t, stored.Binding)
  59. assert.Equal(t, "original-binding", stored.Binding.ID)
  60. assert.Equal(t, []DashboardNavigationTarget{{Title: "original"}}, stored.Binding.OnDashboards)
  61. }
  62. func TestCreateExecutorAndExec(t *testing.T) {
  63. e, cfg := testingExecutor()
  64. req := ExecutionRequest{
  65. AuthenticatedUser: &authpublic.AuthenticatedUser{Username: "MrTickle"},
  66. Cfg: cfg,
  67. Arguments: map[string]string{
  68. "person": "yourself",
  69. },
  70. }
  71. // Ensure bindings are available and set the binding to the only configured action
  72. e.RebuildActionMap()
  73. if len(cfg.Actions) > 0 {
  74. req.Binding = e.FindBindingWithNoEntity(cfg.Actions[0])
  75. }
  76. assert.NotNil(t, e, "Create an executor")
  77. wg, _ := e.ExecRequest(&req)
  78. wg.Wait()
  79. assert.Equal(t, int32(0), req.logEntry.ExitCode, "Exit code is zero")
  80. }
  81. func TestStepRequestActionPopulateLogEntryResolvesEntityTemplates(t *testing.T) {
  82. req := &ExecutionRequest{
  83. logEntry: &InternalLogEntry{},
  84. Binding: &ActionBinding{
  85. Action: &config.Action{
  86. Title: "Do something with {{ project.name }}",
  87. Icon: "{{ project.icon }}",
  88. },
  89. Entity: &entities.Entity{
  90. Data: map[string]any{
  91. "name": "foo",
  92. "icon": "🐰",
  93. },
  94. UniqueKey: "foo-key",
  95. },
  96. },
  97. }
  98. stepRequestActionPopulateLogEntry(req)
  99. assert.Equal(t, "Do something with foo", req.logEntry.ActionTitle)
  100. assert.Equal(t, "🐰", req.logEntry.ActionIcon)
  101. assert.Equal(t, "Do something with {{ project.name }}", req.logEntry.ActionConfigTitle)
  102. assert.Equal(t, "foo-key", req.logEntry.EntityPrefix)
  103. }
  104. func TestExecNonExistant(t *testing.T) {
  105. e, cfg := testingExecutor()
  106. req := ExecutionRequest{
  107. // Binding: e.FindBindingWithNoEntity("waffles"),
  108. logEntry: &InternalLogEntry{},
  109. Cfg: cfg,
  110. }
  111. wg, _ := e.ExecRequest(&req)
  112. wg.Wait()
  113. assert.Equal(t, int32(-1337), req.logEntry.ExitCode, "Log entry is set to an internal error code")
  114. assert.Equal(t, "💩", req.logEntry.ActionIcon, "Log entry icon is a poop (not found)")
  115. }
  116. func TestArgumentNameCamelCase(t *testing.T) {
  117. req := newExecRequest()
  118. req.Binding.Action = &config.Action{
  119. Title: "Do some tickles",
  120. Shell: "echo 'Tickling {{ personName }}'",
  121. Arguments: []config.ActionArgument{
  122. {
  123. Name: "personName",
  124. Type: "ascii",
  125. },
  126. },
  127. }
  128. req.Arguments = map[string]string{
  129. "personName": "Fred",
  130. }
  131. out, err := parseActionArguments(req)
  132. assert.Equal(t, "echo 'Tickling Fred'", out)
  133. assert.NoError(t, err)
  134. }
  135. func TestArgumentNameSnakeCase(t *testing.T) {
  136. req := newExecRequest()
  137. req.Binding.Action = &config.Action{
  138. Title: "Do some tickles",
  139. Shell: "echo 'Tickling {{ person_name }}'",
  140. Arguments: []config.ActionArgument{
  141. {
  142. Name: "person_name",
  143. Type: "ascii",
  144. },
  145. },
  146. }
  147. req.Arguments = map[string]string{
  148. "person_name": "Fred",
  149. }
  150. out, err := parseActionArguments(req)
  151. assert.Equal(t, "echo 'Tickling Fred'", out)
  152. assert.NoError(t, err)
  153. }
  154. func TestGetLogsEmpty(t *testing.T) {
  155. e, cfg := testingExecutor()
  156. assert.Equal(t, int64(10), cfg.LogHistoryPageSize, "Logs page size should be 10")
  157. logs, paging := e.GetLogTrackingIds(0, 10)
  158. assert.NotNil(t, logs, "Logs should not be nil")
  159. assert.Empty(t, logs, "No logs yet")
  160. assert.Equal(t, int64(0), paging.CountRemaining, "There should be no remaining logs")
  161. }
  162. func TestGetLogsLessThanPageSize(t *testing.T) {
  163. e, cfg := testingExecutor()
  164. cfg.Actions = append(cfg.Actions, &config.Action{
  165. Title: "blat",
  166. Shell: "date",
  167. })
  168. cfg.Sanitize()
  169. // Rebuild action map to include newly added action
  170. e.RebuildActionMap()
  171. assert.Equal(t, int64(10), cfg.LogHistoryPageSize, "Logs page size should be 10")
  172. logEntries, paging := e.GetLogTrackingIds(0, 10)
  173. assert.Empty(t, logEntries, "There should be 0 logs")
  174. assert.Zero(t, paging.CountRemaining, "There should be no remaining logs")
  175. execNewReqAndWait(e, cfg)
  176. execNewReqAndWait(e, cfg)
  177. execNewReqAndWait(e, cfg)
  178. execNewReqAndWait(e, cfg)
  179. execNewReqAndWait(e, cfg)
  180. execNewReqAndWait(e, cfg)
  181. execNewReqAndWait(e, cfg)
  182. logEntries, paging = e.GetLogTrackingIds(0, 10)
  183. assert.Len(t, logEntries, 7, "There should be 7 logs")
  184. assert.Zero(t, paging.CountRemaining, "There should be no remaining logs")
  185. execNewReqAndWait(e, cfg)
  186. execNewReqAndWait(e, cfg)
  187. execNewReqAndWait(e, cfg)
  188. execNewReqAndWait(e, cfg)
  189. execNewReqAndWait(e, cfg)
  190. logEntries, paging = e.GetLogTrackingIds(0, 10)
  191. assert.Len(t, logEntries, 10, "There should be 10 logs")
  192. assert.Equal(t, int64(2), paging.CountRemaining, "There should be 1 remaining logs")
  193. }
  194. func execNewReqAndWait(e *Executor, cfg *config.Config) {
  195. req := &ExecutionRequest{
  196. // ActionTitle: title,
  197. Cfg: cfg,
  198. }
  199. // Ensure we have a binding for the requested title
  200. e.RebuildActionMap()
  201. var action *config.Action
  202. for _, a := range cfg.Actions {
  203. if a.Title == "blat" {
  204. action = a
  205. break
  206. }
  207. }
  208. if action != nil {
  209. req.Binding = e.FindBindingWithNoEntity(action)
  210. }
  211. wg, _ := e.ExecRequest(req)
  212. wg.Wait()
  213. }
  214. func TestGetPagingIndexes(t *testing.T) {
  215. assert.Zero(t, getPagingStartIndex(5, 0), "Testing start index from empty list")
  216. assert.Equal(t, int64(4), getPagingStartIndex(5, 10), "Testing start index from mid point")
  217. assert.Equal(t, int64(9), getPagingStartIndex(-1, 10), "Testing start index with negative offset")
  218. assert.Equal(t, int64(0), getPagingStartIndex(15, 10), "Testing start index with large offset")
  219. assert.Equal(t, int64(9), getPagingStartIndex(0, 10), "Testing start index with zero count")
  220. }
  221. func TestUnsetRequiredArgument(t *testing.T) {
  222. req := newExecRequest()
  223. req.Binding.Action = &config.Action{
  224. Title: "Print your name",
  225. Shell: "echo 'Your name is: {{ name }}'",
  226. Arguments: []config.ActionArgument{
  227. {
  228. Name: "name",
  229. Type: "ascii",
  230. },
  231. },
  232. }
  233. req.Arguments = map[string]string{}
  234. out, err := parseActionArguments(req)
  235. assert.Empty(t, out)
  236. assert.Error(t, err)
  237. }
  238. func TestUnusedArgumentStillPassesTypeSafetyCheck(t *testing.T) {
  239. req := newExecRequest()
  240. req.Binding.Action = &config.Action{
  241. Title: "Print your name",
  242. Shell: "echo 'Your name is: {{ name }}'",
  243. Arguments: []config.ActionArgument{
  244. {
  245. Name: "name",
  246. Type: "ascii",
  247. },
  248. {
  249. Name: "age",
  250. Type: "int",
  251. },
  252. },
  253. }
  254. req.Arguments = map[string]string{
  255. "name": "Fred",
  256. "age": "Not an integer",
  257. }
  258. out, err := parseActionArguments(req)
  259. assert.Empty(t, out)
  260. assert.Error(t, err)
  261. }
  262. // https://github.com/OliveTin/OliveTin/issues/564
  263. func TestMangleInvalidArgumentValues(t *testing.T) {
  264. e, cfg := testingExecutor()
  265. a1 := &config.Action{
  266. Title: "Validate my date without seconds because I am from an Android phone",
  267. Shell: "echo 'The date is: {{ date }}'",
  268. Arguments: []config.ActionArgument{
  269. {
  270. Name: "date",
  271. Type: "datetime",
  272. },
  273. },
  274. }
  275. cfg.Actions = append(cfg.Actions, a1)
  276. cfg.Sanitize()
  277. // Build bindings for newly added action
  278. e.RebuildActionMap()
  279. req := ExecutionRequest{
  280. // Action: a1,
  281. AuthenticatedUser: auth.UserFromSystem(cfg, "testuser"),
  282. Cfg: cfg,
  283. Arguments: map[string]string{
  284. "date": "1990-01-10T12:00", // Invalid format, should be without seconds
  285. },
  286. }
  287. // Set binding to our appended action
  288. req.Binding = e.FindBindingWithNoEntity(a1)
  289. wg, _ := e.ExecRequest(&req)
  290. wg.Wait()
  291. assert.NotNil(t, req.logEntry, "Log entry should not be nil")
  292. assert.Equal(t, "The date is: 1990-01-10T12:00:00\n", req.logEntry.Output, "Date should be mangled to a valid format")
  293. }
  294. func TestWebhookRejectsShellExecution(t *testing.T) {
  295. cfg := config.DefaultConfig()
  296. e := DefaultExecutor(cfg)
  297. a1 := &config.Action{
  298. Title: "Webhook Shell Reject",
  299. Shell: "echo '{{ msg }}'",
  300. Arguments: []config.ActionArgument{
  301. {Name: "msg", Type: "ascii"},
  302. },
  303. }
  304. cfg.Actions = append(cfg.Actions, a1)
  305. cfg.Sanitize()
  306. e.RebuildActionMap()
  307. req := ExecutionRequest{
  308. Tags: []string{"webhook"},
  309. AuthenticatedUser: auth.UserFromSystem(cfg, "webhook"),
  310. Cfg: cfg,
  311. Arguments: map[string]string{"msg": "hello"},
  312. Binding: e.FindBindingWithNoEntity(a1),
  313. }
  314. wg, _ := e.ExecRequest(&req)
  315. wg.Wait()
  316. assert.NotNil(t, req.logEntry)
  317. assert.Equal(t, int32(-1337), req.logEntry.ExitCode)
  318. assert.Contains(t, req.logEntry.Output, "webhooks cannot use Shell execution")
  319. }
  320. func TestWebhookAllowsExecExecution(t *testing.T) {
  321. cfg := config.DefaultConfig()
  322. e := DefaultExecutor(cfg)
  323. a1 := &config.Action{
  324. Title: "Webhook Exec OK",
  325. Exec: []string{"echo", "{{ msg }}"},
  326. Arguments: []config.ActionArgument{
  327. {Name: "msg", Type: "ascii"},
  328. },
  329. }
  330. cfg.Actions = append(cfg.Actions, a1)
  331. cfg.Sanitize()
  332. e.RebuildActionMap()
  333. req := ExecutionRequest{
  334. Tags: []string{"webhook"},
  335. AuthenticatedUser: auth.UserFromSystem(cfg, "webhook"),
  336. Cfg: cfg,
  337. Arguments: map[string]string{"msg": "hello"},
  338. Binding: e.FindBindingWithNoEntity(a1),
  339. }
  340. wg, _ := e.ExecRequest(&req)
  341. wg.Wait()
  342. assert.NotNil(t, req.logEntry)
  343. assert.Equal(t, int32(0), req.logEntry.ExitCode)
  344. assert.Contains(t, req.logEntry.Output, "hello")
  345. }
  346. func TestWebhookRejectsShellAfterCompleted(t *testing.T) {
  347. cfg := config.DefaultConfig()
  348. e := DefaultExecutor(cfg)
  349. a1 := &config.Action{
  350. Title: "Webhook After Shell Reject",
  351. Exec: []string{"echo", "{{ msg }}"},
  352. ShellAfterCompleted: "echo after",
  353. Arguments: []config.ActionArgument{
  354. {Name: "msg", Type: "ascii"},
  355. },
  356. }
  357. cfg.Actions = append(cfg.Actions, a1)
  358. cfg.Sanitize()
  359. e.RebuildActionMap()
  360. req := ExecutionRequest{
  361. Tags: []string{"webhook"},
  362. AuthenticatedUser: auth.UserFromSystem(cfg, "webhook"),
  363. Cfg: cfg,
  364. Arguments: map[string]string{"msg": "hello"},
  365. Binding: e.FindBindingWithNoEntity(a1),
  366. }
  367. wg, _ := e.ExecRequest(&req)
  368. wg.Wait()
  369. assert.NotNil(t, req.logEntry)
  370. assert.Contains(t, req.logEntry.Output, "webhooks cannot use shellAfterCompleted")
  371. }
  372. func TestShellAfterCompletedUsesOutputEnvSafely(t *testing.T) {
  373. cfg := config.DefaultConfig()
  374. e := DefaultExecutor(cfg)
  375. injectedPath := filepath.Join(t.TempDir(), "olivetin-injected")
  376. expectedMainOutput := "'; touch " + injectedPath + "; echo '"
  377. a1 := &config.Action{
  378. Title: "After completion escape",
  379. Shell: "printf %s \"" + expectedMainOutput + "\"",
  380. ShellAfterCompleted: "printf %s {{ output }}",
  381. }
  382. cfg.Actions = append(cfg.Actions, a1)
  383. cfg.Sanitize()
  384. e.RebuildActionMap()
  385. req := ExecutionRequest{
  386. AuthenticatedUser: auth.UserFromSystem(cfg, "cron"),
  387. Cfg: cfg,
  388. Binding: e.FindBindingWithNoEntity(a1),
  389. }
  390. wg, _ := e.ExecRequest(&req)
  391. wg.Wait()
  392. assert.NotNil(t, req.logEntry)
  393. assert.Equal(t, int32(0), req.logEntry.ExitCode)
  394. assert.True(t, strings.HasPrefix(req.logEntry.Output, expectedMainOutput))
  395. assert.Contains(t, req.logEntry.Output, "OliveTin::shellAfterCompleted stdout\n"+expectedMainOutput)
  396. _, err := os.Stat(injectedPath)
  397. assert.True(t, os.IsNotExist(err), "shellAfterCompleted must not execute injected commands from output")
  398. }
  399. func TestShellAfterCompletedExpandsQuotedPlaceholders(t *testing.T) {
  400. cases := []struct {
  401. name string
  402. sac string
  403. }{
  404. {"legacy single-quoted", `printf '%s' '{{ output }}'`},
  405. {"modern single-quoted", `printf '%s' '{{ .Arguments.output }}'`},
  406. }
  407. for _, tc := range cases {
  408. t.Run(tc.name, func(t *testing.T) {
  409. cfg := config.DefaultConfig()
  410. executor := DefaultExecutor(cfg)
  411. mainOutput := "quoted-output-ok"
  412. action := &config.Action{
  413. Title: "sac-quoted-" + tc.name,
  414. Shell: "printf %s \"" + mainOutput + "\"",
  415. ShellAfterCompleted: tc.sac,
  416. }
  417. cfg.Actions = append(cfg.Actions, action)
  418. cfg.Sanitize()
  419. executor.RebuildActionMap()
  420. req := ExecutionRequest{
  421. AuthenticatedUser: auth.UserFromSystem(cfg, "cron"),
  422. Cfg: cfg,
  423. Binding: executor.FindBindingWithNoEntity(action),
  424. }
  425. wg, _ := executor.ExecRequest(&req)
  426. wg.Wait()
  427. require.NotNil(t, req.logEntry)
  428. assert.Equal(t, int32(0), req.logEntry.ExitCode)
  429. assert.Contains(t, req.logEntry.Output, "OliveTin::shellAfterCompleted stdout\n"+mainOutput)
  430. })
  431. }
  432. }
  433. func TestShellAfterCompletedBlocksArgumentsOutputInjection(t *testing.T) {
  434. payload := func(injectedPath string) string {
  435. return "x; touch " + injectedPath + "; #"
  436. }
  437. cases := []struct {
  438. name string
  439. sac string
  440. }{
  441. {"legacy", "printf %s {{ output }}"},
  442. {"legacy compact", "printf %s {{output}}"},
  443. {"legacy extra spaces", "printf %s {{ output }}"},
  444. {"modern Arguments", "printf %s {{ .Arguments.output }}"},
  445. {"modern compact", "printf %s {{.Arguments.output}}"},
  446. {"modern exitCode still env", "printf %s {{ .Arguments.exitCode }}"},
  447. }
  448. for _, tc := range cases {
  449. t.Run(tc.name, func(t *testing.T) {
  450. cfg := config.DefaultConfig()
  451. executor := DefaultExecutor(cfg)
  452. injectedPath := filepath.Join(t.TempDir(), "injected")
  453. mainPayload := payload(injectedPath)
  454. action := &config.Action{
  455. Title: "sac-injection-" + tc.name,
  456. Shell: "printf %s \"" + mainPayload + "\"",
  457. ShellAfterCompleted: tc.sac,
  458. }
  459. cfg.Actions = append(cfg.Actions, action)
  460. cfg.Sanitize()
  461. executor.RebuildActionMap()
  462. req := ExecutionRequest{
  463. AuthenticatedUser: auth.UserFromSystem(cfg, "cron"),
  464. Cfg: cfg,
  465. Binding: executor.FindBindingWithNoEntity(action),
  466. }
  467. wg, _ := executor.ExecRequest(&req)
  468. wg.Wait()
  469. _, err := os.Stat(injectedPath)
  470. assert.True(t, os.IsNotExist(err), "shellAfterCompleted must not execute injected commands via %q", tc.sac)
  471. })
  472. }
  473. }
  474. func TestSubstituteShellAfterCompletedEnvRefs(t *testing.T) {
  475. cases := []struct {
  476. in string
  477. want string
  478. }{
  479. {`printf %s {{ output }}`, `printf %s "$OUTPUT"`},
  480. {`printf %s {{output}}`, `printf %s "$OUTPUT"`},
  481. {`printf %s {{ output }}`, `printf %s "$OUTPUT"`},
  482. {`printf %s {{ .Arguments.output }}`, `printf %s "$OUTPUT"`},
  483. {`printf %s {{.Arguments.output}}`, `printf %s "$OUTPUT"`},
  484. {`echo {{ exitCode }}`, `echo "$EXITCODE"`},
  485. {`echo {{ .Arguments.exitCode }}`, `echo "$EXITCODE"`},
  486. {`echo {{ .Arguments.exitCode }}`, `echo "$EXITCODE"`},
  487. {`printf '%s' '{{ output }}'`, `printf '%s' ''"$OUTPUT"''`},
  488. {`printf '%s' '{{ .Arguments.output }}'`, `printf '%s' ''"$OUTPUT"''`},
  489. {`printf '%s' '{{ exitCode }}'`, `printf '%s' ''"$EXITCODE"''`},
  490. {`printf '%s' '{{ .Arguments.exitCode }}'`, `printf '%s' ''"$EXITCODE"''`},
  491. }
  492. for _, tc := range cases {
  493. assert.Equal(t, tc.want, substituteShellAfterCompletedEnvRefs(tc.in))
  494. }
  495. }
  496. func TestShellAfterTemplateArgsOmitsOutputAndExitCode(t *testing.T) {
  497. args := map[string]string{
  498. "output": "evil; id",
  499. "exitCode": "1",
  500. "ot_username": "alice",
  501. "ot_executionTrackingId": "track-1",
  502. }
  503. templateArgs := shellAfterTemplateArgs(args)
  504. assert.NotContains(t, templateArgs, "output")
  505. assert.NotContains(t, templateArgs, "exitCode")
  506. assert.Equal(t, "alice", templateArgs["ot_username"])
  507. assert.Equal(t, "track-1", templateArgs["ot_executionTrackingId"])
  508. assert.Equal(t, "evil; id", args["output"], "env args map must keep output for OUTPUT=")
  509. }
  510. func TestFilterToDefinedArgumentsOnly(t *testing.T) {
  511. req := newExecRequest()
  512. req.Binding.Action = &config.Action{
  513. Title: "Filter test",
  514. Shell: "echo '{{ name }}'",
  515. Arguments: []config.ActionArgument{
  516. {Name: "name", Type: "ascii"},
  517. },
  518. }
  519. req.Arguments = map[string]string{
  520. "name": "Alice",
  521. "webhook_path": "/malicious/$(id)",
  522. "extra_undefined": "ignored",
  523. }
  524. filterToDefinedArgumentsOnly(req)
  525. assert.Equal(t, "Alice", req.Arguments["name"])
  526. assert.Empty(t, req.Arguments["webhook_path"])
  527. assert.Empty(t, req.Arguments["extra_undefined"])
  528. }
  529. func TestFilterToDefinedArgumentsDropsReservedPrefixArgs(t *testing.T) {
  530. req := newExecRequest()
  531. req.Binding.Action = &config.Action{
  532. Title: "Filter test",
  533. Shell: "echo test",
  534. Arguments: []config.ActionArgument{},
  535. }
  536. req.Arguments = map[string]string{
  537. "ot_executionTrackingId": "track-123",
  538. "ot_username": "webhook",
  539. }
  540. filterToDefinedArgumentsOnly(req)
  541. assert.Empty(t, req.Arguments["ot_executionTrackingId"])
  542. assert.Empty(t, req.Arguments["ot_username"])
  543. }
  544. func TestStepParseArgsInjectsSystemArgsAfterFiltering(t *testing.T) {
  545. req := newExecRequest()
  546. req.TrackingID = "server-track-456"
  547. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice"}
  548. req.Binding.Action = &config.Action{
  549. Title: "Filter then inject",
  550. Shell: "echo test",
  551. Arguments: []config.ActionArgument{
  552. {Name: "name", Type: "ascii"},
  553. },
  554. }
  555. req.Arguments = map[string]string{
  556. "name": "Alice",
  557. "ot_executionTrackingId": "attacker-track",
  558. "ot_username": "mallory",
  559. "ot_custom": "polluted",
  560. }
  561. assert.True(t, stepParseArgs(req))
  562. assert.Equal(t, "Alice", req.Arguments["name"])
  563. assert.Equal(t, "server-track-456", req.Arguments["ot_executionTrackingId"])
  564. assert.Equal(t, "alice", req.Arguments["ot_username"])
  565. assert.Empty(t, req.Arguments["ot_custom"])
  566. }
  567. func TestStepParseArgsDropsReservedPrefixArgsFromEnvironment(t *testing.T) {
  568. req := newExecRequest()
  569. req.TrackingID = "server-track-456"
  570. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice@example.com"}
  571. req.Binding.Action = &config.Action{
  572. Title: "No reserved prefix pollution",
  573. Shell: "echo test",
  574. Arguments: []config.ActionArgument{},
  575. }
  576. req.Arguments = map[string]string{
  577. "ot_custom": "polluted",
  578. }
  579. assert.True(t, stepParseArgs(req))
  580. env := buildEnv(req.Arguments)
  581. assert.False(t, containsEnvPrefix(env, "OT_CUSTOM="))
  582. assert.True(t, containsEnvPrefix(env, "OT_USERNAME=alice@example.com"))
  583. assert.True(t, containsEnvPrefix(env, "OT_EXECUTIONTRACKINGID=server-track-456"))
  584. }
  585. func TestSystemArgumentDefinitionsAreReservedAndShellSafe(t *testing.T) {
  586. unsafeTypes := map[string]struct{}{
  587. "email": {},
  588. "password": {},
  589. "raw_string_multiline": {},
  590. "url": {},
  591. "very_dangerous_raw_string": {},
  592. }
  593. seen := map[string]struct{}{}
  594. for _, arg := range systemArgumentDefinitions {
  595. assert.True(t, strings.HasPrefix(arg.Name, config.ReservedArgumentNamePrefix))
  596. assert.NotEmpty(t, arg.Type)
  597. assert.True(t, arg.RejectNull)
  598. _, duplicate := seen[arg.Name]
  599. assert.False(t, duplicate, "duplicate system argument definition %q", arg.Name)
  600. seen[arg.Name] = struct{}{}
  601. _, unsafe := unsafeTypes[arg.Type]
  602. assert.False(t, unsafe, "system argument %q uses unsafe type %q", arg.Name, arg.Type)
  603. }
  604. }
  605. func TestValidatedSystemArgsMatchesSystemArgumentDefinitions(t *testing.T) {
  606. req := newExecRequest()
  607. req.TrackingID = "server-track-456"
  608. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice@example.com"}
  609. args, err := validatedSystemArgs(req)
  610. require.NoError(t, err)
  611. assert.Len(t, args, len(systemArgumentDefinitions))
  612. for _, arg := range systemArgumentDefinitions {
  613. assert.Contains(t, args, arg.Name)
  614. }
  615. }
  616. func TestBuildShellAfterArgsOnlyAddsExpectedNonSystemArgs(t *testing.T) {
  617. req := newExecRequest()
  618. req.logEntry = &InternalLogEntry{
  619. Output: "hello",
  620. ExitCode: 7,
  621. }
  622. req.TrackingID = "server-track-456"
  623. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice@example.com"}
  624. req.Binding.Action = &config.Action{ShellAfterCompleted: "echo test"}
  625. args, err := buildShellAfterArgs(req)
  626. require.NoError(t, err)
  627. assert.Len(t, args, len(systemArgumentDefinitions)+2)
  628. assert.Contains(t, args, "output")
  629. assert.Contains(t, args, "exitCode")
  630. for _, arg := range systemArgumentDefinitions {
  631. assert.Contains(t, args, arg.Name)
  632. }
  633. }
  634. func TestStepParseArgsAllowsEmailUsernameSystemArg(t *testing.T) {
  635. req := newExecRequest()
  636. req.logEntry = &InternalLogEntry{}
  637. req.TrackingID = "server-track-456"
  638. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice@example.com"}
  639. req.Binding.Action = &config.Action{
  640. Title: "Email username",
  641. Shell: "echo test",
  642. Arguments: []config.ActionArgument{},
  643. }
  644. assert.True(t, stepParseArgs(req))
  645. assert.Equal(t, "alice@example.com", req.Arguments["ot_username"])
  646. }
  647. func TestStepParseArgsFailsWhenUsernameSystemArgIsInvalid(t *testing.T) {
  648. req := newExecRequest()
  649. req.logEntry = &InternalLogEntry{}
  650. req.TrackingID = "server-track-456"
  651. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice;id"}
  652. req.Binding.Action = &config.Action{
  653. Title: "Invalid system arg",
  654. Shell: "echo test",
  655. Arguments: []config.ActionArgument{},
  656. }
  657. assert.False(t, stepParseArgs(req))
  658. assert.Contains(t, req.logEntry.Output, `system argument "ot_username" failed validation`)
  659. assert.Empty(t, req.Arguments["ot_username"])
  660. }
  661. func TestStepParseArgsFailsWhenTrackingIDSystemArgIsInvalid(t *testing.T) {
  662. req := newExecRequest()
  663. req.logEntry = &InternalLogEntry{}
  664. req.TrackingID = "track/../../bad"
  665. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice"}
  666. req.Binding.Action = &config.Action{
  667. Title: "Invalid tracking ID",
  668. Shell: "echo test",
  669. Arguments: []config.ActionArgument{},
  670. }
  671. assert.False(t, stepParseArgs(req))
  672. assert.Contains(t, req.logEntry.Output, `system argument "ot_executionTrackingId" failed validation`)
  673. assert.Empty(t, req.Arguments["ot_executionTrackingId"])
  674. }
  675. func TestBuildShellAfterArgsUsesValidatedSystemArgs(t *testing.T) {
  676. req := newExecRequest()
  677. req.logEntry = &InternalLogEntry{
  678. Output: "hello",
  679. ExitCode: 7,
  680. }
  681. req.TrackingID = "server-track-456"
  682. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice@example.com"}
  683. req.Binding.Action = &config.Action{
  684. Title: "Shell after",
  685. ShellAfterCompleted: "echo test",
  686. }
  687. args, err := buildShellAfterArgs(req)
  688. require.NoError(t, err)
  689. assert.Equal(t, "alice@example.com", args["ot_username"])
  690. assert.Equal(t, "server-track-456", args["ot_executionTrackingId"])
  691. assert.Equal(t, "hello", args["output"])
  692. assert.Equal(t, "7", args["exitCode"])
  693. }
  694. func TestBuildShellAfterArgsFailsWhenSystemArgIsInvalid(t *testing.T) {
  695. req := newExecRequest()
  696. req.logEntry = &InternalLogEntry{}
  697. req.TrackingID = "server-track-456"
  698. req.AuthenticatedUser = &authpublic.AuthenticatedUser{Username: "alice;id"}
  699. req.Binding.Action = &config.Action{
  700. Title: "Shell after invalid username",
  701. ShellAfterCompleted: "echo test",
  702. }
  703. args, err := buildShellAfterArgs(req)
  704. assert.Nil(t, args)
  705. require.Error(t, err)
  706. assert.Contains(t, err.Error(), `system argument "ot_username" failed validation`)
  707. }
  708. func containsEnvPrefix(env []string, prefix string) bool {
  709. for _, item := range env {
  710. if strings.HasPrefix(item, prefix) {
  711. return true
  712. }
  713. }
  714. return false
  715. }
  716. func TestTriggerExecutesTriggeredAction(t *testing.T) {
  717. cfg := config.DefaultConfig()
  718. e := DefaultExecutor(cfg)
  719. helloAction := &config.Action{
  720. Title: "Hello world",
  721. Shell: "echo 'Hello World!'",
  722. }
  723. triggerAction := &config.Action{
  724. Title: "Simple action that triggers another action",
  725. Shell: "echo 'Hi'",
  726. Triggers: []string{"Hello world"},
  727. }
  728. cfg.Actions = append(cfg.Actions, helloAction, triggerAction)
  729. cfg.Sanitize()
  730. e.RebuildActionMap()
  731. finishedTitles := make(chan string, 4)
  732. collector := &executionFinishedCollector{ch: finishedTitles}
  733. e.AddListener(collector)
  734. req := &ExecutionRequest{
  735. AuthenticatedUser: auth.UserFromSystem(cfg, "testuser"),
  736. Cfg: cfg,
  737. Binding: e.FindBindingWithNoEntity(triggerAction),
  738. }
  739. wg, _ := e.ExecRequest(req)
  740. wg.Wait()
  741. var got []string
  742. for i := range 2 {
  743. select {
  744. case title := <-finishedTitles:
  745. got = append(got, title)
  746. case <-time.After(2 * time.Second):
  747. t.Fatalf("timed out waiting for execution %d; got %v", i+1, got)
  748. }
  749. }
  750. assert.Contains(t, got, "Hello world", "triggered action must run")
  751. assert.Contains(t, got, "Simple action that triggers another action", "triggering action must run")
  752. }
  753. func TestTriggerUnknownActionTitleSkipsWithoutPanic(t *testing.T) {
  754. cfg := config.DefaultConfig()
  755. e := DefaultExecutor(cfg)
  756. triggerAction := &config.Action{
  757. Title: "Action with bad trigger",
  758. Shell: "echo 'ok'",
  759. Triggers: []string{"Nonexistent action"},
  760. }
  761. cfg.Actions = append(cfg.Actions, triggerAction)
  762. cfg.Sanitize()
  763. e.RebuildActionMap()
  764. finishedTitles := make(chan string, 4)
  765. collector := &executionFinishedCollector{ch: finishedTitles}
  766. e.AddListener(collector)
  767. req := &ExecutionRequest{
  768. AuthenticatedUser: auth.UserFromSystem(cfg, "testuser"),
  769. Cfg: cfg,
  770. Binding: e.FindBindingWithNoEntity(triggerAction),
  771. }
  772. wg, _ := e.ExecRequest(req)
  773. wg.Wait()
  774. var got []string
  775. select {
  776. case title := <-finishedTitles:
  777. got = append(got, title)
  778. case <-time.After(500 * time.Millisecond):
  779. }
  780. assert.Len(t, got, 1, "only the triggering action runs; unknown trigger is skipped")
  781. if len(got) > 0 {
  782. assert.Equal(t, "Action with bad trigger", got[0])
  783. }
  784. }
  785. type executionFinishedCollector struct {
  786. ch chan string
  787. }
  788. func (c *executionFinishedCollector) OnExecutionStarted(_ *InternalLogEntry) {}
  789. func (c *executionFinishedCollector) OnExecutionFinished(entry *InternalLogEntry) {
  790. c.ch <- entry.ActionTitle
  791. }
  792. func (c *executionFinishedCollector) OnOutputChunk(_ []byte, _ string) {}
  793. func (c *executionFinishedCollector) OnActionMapRebuilt() {}
  794. func TestSanitizeLogFilename(t *testing.T) {
  795. tests := []struct {
  796. title string
  797. want string
  798. }{
  799. {"Echo Test", "Echo Test"},
  800. {"Create/update Monthly Report", "Create_update Monthly Report"},
  801. {`path\with\backslashes`, "path_with_backslashes"},
  802. {`a:b*c?d"e<f>g|h`, "a_b_c_d_e_f_g_h"},
  803. {"has\x00nul", "has_nul"},
  804. {"tab\there\nand\rreturn", "tab_here_and_return"},
  805. }
  806. for _, tt := range tests {
  807. assert.Equal(t, tt.want, sanitizeLogFilename(tt.title), "title=%q", tt.title)
  808. }
  809. }
  810. func TestStepSaveLogSanitizesSlashInTitle(t *testing.T) {
  811. resultsDir := t.TempDir()
  812. outputDir := t.TempDir()
  813. started := time.Unix(1714333384, 0)
  814. trackingID := "5e2dc9e5-b6b3-445b-bff9-c2082b0bbbb2"
  815. title := "Create/update Monthly Report"
  816. req := &ExecutionRequest{
  817. Cfg: &config.Config{
  818. SaveLogs: config.SaveLogsConfig{
  819. ResultsDirectory: resultsDir,
  820. OutputDirectory: outputDir,
  821. },
  822. },
  823. Binding: &ActionBinding{
  824. Action: &config.Action{},
  825. },
  826. logEntry: &InternalLogEntry{
  827. ActionTitle: title,
  828. DatetimeStarted: started,
  829. ExecutionTrackingID: trackingID,
  830. Output: "report ok",
  831. },
  832. }
  833. assert.True(t, stepSaveLog(req))
  834. expectedBase := "Create_update Monthly Report.1714333384." + trackingID
  835. resultsPath := filepath.Join(resultsDir, expectedBase+".yaml")
  836. outputPath := filepath.Join(outputDir, expectedBase+".log")
  837. assert.FileExists(t, resultsPath)
  838. assert.FileExists(t, outputPath)
  839. resultsEntries, err := os.ReadDir(resultsDir)
  840. require.NoError(t, err)
  841. assert.Len(t, resultsEntries, 1, "results file must be flat under resultsDirectory, not a subdirectory")
  842. data, err := os.ReadFile(resultsPath)
  843. require.NoError(t, err)
  844. assert.Contains(t, string(data), title, "YAML content keeps the original action title")
  845. output, err := os.ReadFile(outputPath)
  846. require.NoError(t, err)
  847. assert.Equal(t, "report ok", string(output))
  848. }
  849. func TestStepSaveLogKeepsSafeTitleFilename(t *testing.T) {
  850. resultsDir := t.TempDir()
  851. started := time.Unix(1714333384, 0)
  852. trackingID := "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
  853. req := &ExecutionRequest{
  854. Cfg: &config.Config{
  855. SaveLogs: config.SaveLogsConfig{
  856. ResultsDirectory: resultsDir,
  857. },
  858. },
  859. Binding: &ActionBinding{
  860. Action: &config.Action{},
  861. },
  862. logEntry: &InternalLogEntry{
  863. ActionTitle: "Echo Test",
  864. DatetimeStarted: started,
  865. ExecutionTrackingID: trackingID,
  866. },
  867. }
  868. assert.True(t, stepSaveLog(req))
  869. expectedPath := filepath.Join(resultsDir, "Echo Test.1714333384."+trackingID+".yaml")
  870. assert.FileExists(t, expectedPath)
  871. }
  872. func TestStepSaveLogSanitizesNULInTitle(t *testing.T) {
  873. resultsDir := t.TempDir()
  874. outputDir := t.TempDir()
  875. started := time.Unix(1714333384, 0)
  876. trackingID := "bbbbbbbb-cccc-dddd-eeee-ffffffffffff"
  877. title := "Bad\x00Title"
  878. req := &ExecutionRequest{
  879. Cfg: &config.Config{
  880. SaveLogs: config.SaveLogsConfig{
  881. ResultsDirectory: resultsDir,
  882. OutputDirectory: outputDir,
  883. },
  884. },
  885. Binding: &ActionBinding{
  886. Action: &config.Action{},
  887. },
  888. logEntry: &InternalLogEntry{
  889. ActionTitle: title,
  890. DatetimeStarted: started,
  891. ExecutionTrackingID: trackingID,
  892. Output: "nul ok",
  893. },
  894. }
  895. assert.True(t, stepSaveLog(req))
  896. expectedBase := "Bad_Title.1714333384." + trackingID
  897. resultsPath := filepath.Join(resultsDir, expectedBase+".yaml")
  898. outputPath := filepath.Join(outputDir, expectedBase+".log")
  899. assert.FileExists(t, resultsPath)
  900. assert.FileExists(t, outputPath)
  901. assert.NotContains(t, resultsPath, "\x00")
  902. assert.NotContains(t, outputPath, "\x00")
  903. output, err := os.ReadFile(outputPath)
  904. require.NoError(t, err)
  905. assert.Equal(t, "nul ok", string(output))
  906. }
  907. func TestBlockedExecutionPersistsSaveLogs(t *testing.T) {
  908. t.Parallel()
  909. resultsDir := t.TempDir()
  910. outputDir := t.TempDir()
  911. action := &config.Action{
  912. Title: "Blocked report",
  913. Shell: "sleep 1",
  914. MaxConcurrent: 1,
  915. SaveLogs: config.SaveLogsConfig{
  916. ResultsDirectory: resultsDir,
  917. OutputDirectory: outputDir,
  918. },
  919. }
  920. e, cfg := testGroupExecutor([]*config.Action{action}, nil)
  921. binding := e.FindBindingWithNoEntity(action)
  922. wg1, tracking1 := e.ExecRequest(&ExecutionRequest{
  923. Binding: binding,
  924. Cfg: cfg,
  925. AuthenticatedUser: auth.UserFromSystem(cfg, "testuser"),
  926. })
  927. waitUntilExecutionStarted(t, e, tracking1)
  928. wg2, tracking2 := e.ExecRequest(&ExecutionRequest{
  929. Binding: binding,
  930. Cfg: cfg,
  931. AuthenticatedUser: auth.UserFromSystem(cfg, "testuser"),
  932. })
  933. wg1.Wait()
  934. wg2.Wait()
  935. snapshot, ok := e.SnapshotLog(tracking2)
  936. require.True(t, ok)
  937. require.True(t, snapshot.Blocked)
  938. resultsEntries, err := os.ReadDir(resultsDir)
  939. require.NoError(t, err)
  940. var resultsPath string
  941. for _, entry := range resultsEntries {
  942. if strings.Contains(entry.Name(), tracking2) {
  943. resultsPath = filepath.Join(resultsDir, entry.Name())
  944. break
  945. }
  946. }
  947. require.NotEmpty(t, resultsPath)
  948. outputEntries, err := os.ReadDir(outputDir)
  949. require.NoError(t, err)
  950. var outputPath string
  951. for _, entry := range outputEntries {
  952. if strings.Contains(entry.Name(), tracking2) {
  953. outputPath = filepath.Join(outputDir, entry.Name())
  954. break
  955. }
  956. }
  957. require.NotEmpty(t, outputPath)
  958. resultsData, err := os.ReadFile(resultsPath)
  959. require.NoError(t, err)
  960. assert.Contains(t, string(resultsData), "blocked: true")
  961. assert.Contains(t, string(resultsData), tracking2)
  962. outputData, err := os.ReadFile(outputPath)
  963. require.NoError(t, err)
  964. assert.Contains(t, string(outputData), "Blocked from executing due to concurrency limit")
  965. }
  966. func TestStepSaveLogReturnsFalseWhenDependenciesMissing(t *testing.T) {
  967. started := time.Unix(1714333384, 0)
  968. valid := &ExecutionRequest{
  969. Cfg: &config.Config{},
  970. Binding: &ActionBinding{
  971. Action: &config.Action{},
  972. },
  973. logEntry: &InternalLogEntry{
  974. ActionTitle: "Echo",
  975. DatetimeStarted: started,
  976. ExecutionTrackingID: "cccccccc-dddd-eeee-ffff-000000000000",
  977. },
  978. }
  979. assert.False(t, stepSaveLog(nil))
  980. assert.False(t, stepSaveLog(&ExecutionRequest{}))
  981. missingLog := *valid
  982. missingLog.logEntry = nil
  983. assert.False(t, stepSaveLog(&missingLog))
  984. missingBinding := *valid
  985. missingBinding.Binding = nil
  986. assert.False(t, stepSaveLog(&missingBinding))
  987. missingAction := *valid
  988. missingAction.Binding = &ActionBinding{}
  989. assert.False(t, stepSaveLog(&missingAction))
  990. missingCfg := *valid
  991. missingCfg.Cfg = nil
  992. assert.False(t, stepSaveLog(&missingCfg))
  993. }
  994. func TestLogEntryOutputAvailableWhileRunning(t *testing.T) {
  995. cfg := config.DefaultConfig()
  996. e := DefaultExecutor(cfg)
  997. action := &config.Action{
  998. Title: "Slow output",
  999. Shell: "echo hello-mid-run; sleep 2",
  1000. }
  1001. cfg.Actions = append(cfg.Actions, action)
  1002. cfg.Sanitize()
  1003. e.RebuildActionMap()
  1004. binding := e.FindBindingWithNoEntity(action)
  1005. require.NotNil(t, binding)
  1006. wg, trackingID := e.ExecRequest(&ExecutionRequest{
  1007. Binding: binding,
  1008. Cfg: cfg,
  1009. AuthenticatedUser: auth.UserFromSystem(cfg, "testuser"),
  1010. })
  1011. var sawOutputWhileRunning bool
  1012. require.Eventually(t, func() bool {
  1013. snapshot, ok := e.SnapshotLog(trackingID)
  1014. if !ok {
  1015. return false
  1016. }
  1017. if snapshot.ExecutionFinished {
  1018. return false
  1019. }
  1020. if strings.Contains(snapshot.Output, "hello-mid-run") {
  1021. sawOutputWhileRunning = true
  1022. return true
  1023. }
  1024. return false
  1025. }, 2*time.Second, 10*time.Millisecond)
  1026. wg.Wait()
  1027. require.True(t, sawOutputWhileRunning, "expected Output to contain printed text before ExecutionFinished")
  1028. snapshot, ok := e.SnapshotLog(trackingID)
  1029. require.True(t, ok)
  1030. assert.True(t, snapshot.ExecutionFinished)
  1031. assert.Contains(t, snapshot.Output, "hello-mid-run")
  1032. }
  1033. func TestRebuildActionMapSkipsNilActions(t *testing.T) {
  1034. e, cfg := testingExecutor()
  1035. cfg.Actions = append(cfg.Actions, nil)
  1036. assert.NotPanics(t, e.RebuildActionMap)
  1037. assert.Len(t, e.MapActionBindings, 1)
  1038. }
  1039. type finishedExecution struct {
  1040. title string
  1041. output string
  1042. exitCode int32
  1043. tags []string
  1044. }
  1045. type executionResultCollector struct {
  1046. ch chan finishedExecution
  1047. }
  1048. func (c *executionResultCollector) OnExecutionStarted(_ *InternalLogEntry) {}
  1049. func (c *executionResultCollector) OnExecutionFinished(entry *InternalLogEntry) {
  1050. c.ch <- finishedExecution{
  1051. title: entry.ActionTitle,
  1052. output: entry.Output,
  1053. exitCode: entry.ExitCode,
  1054. tags: slices.Clone(entry.Tags),
  1055. }
  1056. }
  1057. func (c *executionResultCollector) OnOutputChunk(_ []byte, _ string) {}
  1058. func (c *executionResultCollector) OnActionMapRebuilt() {}
  1059. func runWebhookTriggerChain(t *testing.T, actions []*config.Action, expectedExecutions int) map[string]finishedExecution {
  1060. t.Helper()
  1061. cfg := config.DefaultConfig()
  1062. e := DefaultExecutor(cfg)
  1063. cfg.Actions = append(cfg.Actions, actions...)
  1064. cfg.Sanitize()
  1065. e.RebuildActionMap()
  1066. results := make(chan finishedExecution, expectedExecutions+2)
  1067. e.AddListener(&executionResultCollector{ch: results})
  1068. req := &ExecutionRequest{
  1069. Tags: []string{"webhook"},
  1070. AuthenticatedUser: auth.UserFromSystem(cfg, "webhook"),
  1071. Cfg: cfg,
  1072. Arguments: map[string]string{"msg": "hello"},
  1073. Binding: e.FindBindingWithNoEntity(actions[0]),
  1074. }
  1075. wg, _ := e.ExecRequest(req)
  1076. wg.Wait()
  1077. got := make(map[string]finishedExecution)
  1078. for i := range expectedExecutions {
  1079. select {
  1080. case result := <-results:
  1081. got[result.title] = result
  1082. case <-time.After(2 * time.Second):
  1083. t.Fatalf("timed out waiting for execution %d; got %v", i+1, got)
  1084. }
  1085. }
  1086. return got
  1087. }
  1088. func TestWebhookTriggerRejectsShellExecution(t *testing.T) {
  1089. marker := filepath.Join(t.TempDir(), "triggered-shell-ran")
  1090. got := runWebhookTriggerChain(t, []*config.Action{
  1091. {
  1092. Title: "Webhook entry",
  1093. Exec: []string{"echo", "entry"},
  1094. Triggers: []string{"Triggered shell"},
  1095. },
  1096. {
  1097. Title: "Triggered shell",
  1098. Shell: "touch " + marker,
  1099. },
  1100. }, 2)
  1101. triggered := got["Triggered shell"]
  1102. assert.Equal(t, int32(-1337), triggered.exitCode)
  1103. assert.Contains(t, triggered.output, "webhooks cannot use Shell execution")
  1104. assert.Contains(t, triggered.tags, "trigger")
  1105. assert.Contains(t, triggered.tags, "webhook")
  1106. assert.NoFileExists(t, marker, "triggered shell command must not run")
  1107. }
  1108. func TestWebhookTriggerRejectsShellExecutionAtDepth(t *testing.T) {
  1109. marker := filepath.Join(t.TempDir(), "nested-shell-ran")
  1110. got := runWebhookTriggerChain(t, []*config.Action{
  1111. {
  1112. Title: "Webhook entry",
  1113. Exec: []string{"echo", "entry"},
  1114. Triggers: []string{"Middle exec"},
  1115. },
  1116. {
  1117. Title: "Middle exec",
  1118. Exec: []string{"echo", "middle"},
  1119. Triggers: []string{"Nested shell"},
  1120. },
  1121. {
  1122. Title: "Nested shell",
  1123. Shell: "touch " + marker,
  1124. },
  1125. }, 3)
  1126. nested := got["Nested shell"]
  1127. assert.Equal(t, int32(-1337), nested.exitCode)
  1128. assert.Contains(t, nested.output, "webhooks cannot use Shell execution")
  1129. assert.NoFileExists(t, marker, "nested triggered shell command must not run")
  1130. }
  1131. func TestWebhookTriggerRejectsShellAfterCompleted(t *testing.T) {
  1132. marker := filepath.Join(t.TempDir(), "triggered-after-ran")
  1133. got := runWebhookTriggerChain(t, []*config.Action{
  1134. {
  1135. Title: "Webhook entry",
  1136. Exec: []string{"echo", "entry"},
  1137. Triggers: []string{"Triggered after completed"},
  1138. },
  1139. {
  1140. Title: "Triggered after completed",
  1141. Exec: []string{"echo", "triggered"},
  1142. ShellAfterCompleted: "touch " + marker,
  1143. },
  1144. }, 2)
  1145. assert.Contains(t, got["Triggered after completed"].output, "webhooks cannot use shellAfterCompleted")
  1146. assert.NoFileExists(t, marker, "triggered shellAfterCompleted must not run")
  1147. }
  1148. func TestTriggeredRequestTags(t *testing.T) {
  1149. assert.Equal(t, []string{"trigger"}, triggeredRequestTags(&ExecutionRequest{}))
  1150. assert.Equal(t, []string{"trigger"}, triggeredRequestTags(&ExecutionRequest{Tags: []string{"trigger"}}))
  1151. assert.Equal(t, []string{"trigger", "webhook"}, triggeredRequestTags(&ExecutionRequest{Tags: []string{"webhook"}}))
  1152. assert.Equal(t, []string{"trigger", "webhook"}, triggeredRequestTags(&ExecutionRequest{Tags: []string{"trigger", "webhook"}}))
  1153. }