executor.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  1. package executor
  2. import (
  3. acl "github.com/OliveTin/OliveTin/internal/acl"
  4. "github.com/OliveTin/OliveTin/internal/auth"
  5. authpublic "github.com/OliveTin/OliveTin/internal/auth/authpublic"
  6. config "github.com/OliveTin/OliveTin/internal/config"
  7. "github.com/OliveTin/OliveTin/internal/entities"
  8. "github.com/OliveTin/OliveTin/internal/logfilter"
  9. "github.com/OliveTin/OliveTin/internal/tpl"
  10. "github.com/google/uuid"
  11. log "github.com/sirupsen/logrus"
  12. "gopkg.in/yaml.v3"
  13. "bytes"
  14. "context"
  15. "errors"
  16. "fmt"
  17. "maps"
  18. "os"
  19. "os/exec"
  20. "path"
  21. "regexp"
  22. "slices"
  23. "strings"
  24. "sync"
  25. "time"
  26. )
  27. const (
  28. DefaultExitCodeNotExecuted = -1337
  29. MaxTriggerDepth = 10
  30. )
  31. var validTrackingIDPattern = regexp.MustCompile(`^[a-fA-F0-9\-]+$`)
  32. func isValidTrackingID(id string) bool {
  33. const MaxTrackingIDLength = 36
  34. return id != "" && len(id) <= MaxTrackingIDLength && validTrackingIDPattern.MatchString(id)
  35. }
  36. type ActionBinding struct {
  37. Action *config.Action
  38. Entity *entities.Entity
  39. ID string
  40. OnDashboards []DashboardNavigationTarget
  41. ConfigOrder int
  42. }
  43. type Executor struct {
  44. logs map[string]*InternalLogEntry
  45. LogsByBindingId map[string][]*InternalLogEntry
  46. MapActionBindings map[string]*ActionBinding
  47. Cfg *config.Config
  48. logsTrackingIdsByDate []string
  49. listeners []listener
  50. chainOfCommand []executorStepFunc
  51. groupQueue []*queuedExecution
  52. logmutex sync.RWMutex
  53. MapActionBindingsLock sync.RWMutex
  54. listenersMu sync.RWMutex
  55. groupQueueMu sync.Mutex
  56. }
  57. // ExecutionRequest is a request to execute an action. It's passed to an
  58. // Executor. They're created from the api.
  59. type ExecutionRequest struct {
  60. Arguments map[string]string
  61. Binding *ActionBinding
  62. Cfg *config.Config
  63. AuthenticatedUser *authpublic.AuthenticatedUser
  64. executor *Executor
  65. logEntry *InternalLogEntry
  66. finalParsedCommand string
  67. TrackingID string
  68. Justification string
  69. Tags []string
  70. execArgs []string
  71. TriggerDepth int
  72. useDirectExec bool
  73. skipRequestRegistration bool
  74. }
  75. func (req *ExecutionRequest) mutateLogEntry(mutator func(*InternalLogEntry)) {
  76. if req.executor == nil {
  77. mutator(req.logEntry)
  78. return
  79. }
  80. req.executor.logmutex.Lock()
  81. defer req.executor.logmutex.Unlock()
  82. mutator(req.logEntry)
  83. }
  84. // LogEntrySnapshot is a copy of selected log entry fields for race-safe reads.
  85. type LogEntrySnapshot struct {
  86. Output string
  87. ExitCode int32
  88. Queued bool
  89. Blocked bool
  90. ExecutionStarted bool
  91. ExecutionFinished bool
  92. }
  93. // SnapshotLog returns a copy of selected log entry fields under read lock.
  94. func (e *Executor) SnapshotLog(trackingID string) (LogEntrySnapshot, bool) {
  95. e.logmutex.RLock()
  96. defer e.logmutex.RUnlock()
  97. entry, found := e.logs[trackingID]
  98. if !found {
  99. return LogEntrySnapshot{}, false
  100. }
  101. return LogEntrySnapshot{
  102. Queued: entry.Queued,
  103. Blocked: entry.Blocked,
  104. ExecutionStarted: entry.ExecutionStarted,
  105. ExecutionFinished: entry.ExecutionFinished,
  106. ExitCode: entry.ExitCode,
  107. Output: entry.Output,
  108. }, true
  109. }
  110. // InternalLogEntry objects are created by an Executor, and represent the final
  111. // state of execution (even if the command is not executed). It's designed to be
  112. // easily serializable.
  113. type InternalLogEntry struct {
  114. DatetimeStarted time.Time
  115. DatetimeFinished time.Time
  116. Binding *ActionBinding
  117. Process *os.Process
  118. Arguments map[string]string
  119. ExecutionTrackingID string
  120. Justification string
  121. QueuedForGroup string
  122. ActionIcon string
  123. ActionTitle string
  124. ActionConfigTitle string
  125. Output string
  126. Username string
  127. EntityPrefix string
  128. Tags []string
  129. Index int64
  130. ExitCode int32
  131. Blocked bool
  132. ExecutionFinished bool
  133. ExecutionStarted bool
  134. Queued bool
  135. TimedOut bool
  136. }
  137. func cloneInternalLogEntry(entry *InternalLogEntry) *InternalLogEntry {
  138. if entry == nil {
  139. return nil
  140. }
  141. cloned := *entry
  142. cloned.Arguments = maps.Clone(entry.Arguments)
  143. cloned.Tags = slices.Clone(entry.Tags)
  144. return &cloned
  145. }
  146. // .Binding can be nil, so we need to handle that.
  147. func (e *InternalLogEntry) GetBindingId() string {
  148. if e.Binding == nil {
  149. return ""
  150. }
  151. return e.Binding.ID
  152. }
  153. type executorStepFunc func(*ExecutionRequest) bool
  154. // DefaultExecutor returns an Executor, with a sensible "chain of command" for
  155. // executing actions.
  156. func DefaultExecutor(cfg *config.Config) *Executor {
  157. e := Executor{}
  158. e.Cfg = cfg
  159. e.logs = make(map[string]*InternalLogEntry)
  160. e.logsTrackingIdsByDate = make([]string, 0)
  161. e.LogsByBindingId = make(map[string][]*InternalLogEntry)
  162. e.MapActionBindings = make(map[string]*ActionBinding)
  163. e.chainOfCommand = []executorStepFunc{
  164. stepRequestAction,
  165. stepConcurrencyCheck,
  166. stepRateCheck,
  167. stepACLCheck,
  168. stepParseArgs,
  169. stepLogStart,
  170. stepExec,
  171. stepExecAfter,
  172. stepLogFinish,
  173. stepTrigger,
  174. }
  175. return &e
  176. }
  177. type listener interface {
  178. OnExecutionStarted(logEntry *InternalLogEntry)
  179. OnExecutionFinished(logEntry *InternalLogEntry)
  180. OnOutputChunk(o []byte, executionTrackingId string)
  181. OnActionMapRebuilt()
  182. }
  183. func (e *Executor) AddListener(m listener) {
  184. e.listenersMu.Lock()
  185. defer e.listenersMu.Unlock()
  186. e.listeners = append(e.listeners, m)
  187. }
  188. func (e *Executor) copyListeners() []listener {
  189. e.listenersMu.RLock()
  190. defer e.listenersMu.RUnlock()
  191. out := make([]listener, len(e.listeners))
  192. copy(out, e.listeners)
  193. return out
  194. }
  195. // getPagingStartIndex calculates the starting index for log pagination.
  196. // Parameters:
  197. //
  198. // startOffset: The offset from the most recent log (0 means start from the most recent)
  199. // totalLogCount: Total number of logs available
  200. // count: Number of logs to retrieve
  201. //
  202. // Returns: The calculated starting index for pagination
  203. func getPagingStartIndex(startOffset int64, totalLogCount int64) int64 {
  204. var startIndex int64
  205. if startOffset <= 0 {
  206. startIndex = totalLogCount
  207. } else {
  208. startIndex = (totalLogCount - startOffset)
  209. if startIndex < 0 {
  210. startIndex = 1
  211. }
  212. }
  213. return startIndex - 1
  214. }
  215. type PagingResult struct {
  216. CountRemaining int64
  217. PageSize int64
  218. TotalCount int64
  219. StartOffset int64
  220. }
  221. func (e *Executor) GetLogTrackingIds(startOffset int64, pageCount int64) ([]*InternalLogEntry, *PagingResult) {
  222. pagingResult := &PagingResult{
  223. CountRemaining: 0,
  224. PageSize: pageCount,
  225. TotalCount: 0,
  226. StartOffset: startOffset,
  227. }
  228. e.logmutex.RLock()
  229. totalLogCount := int64(len(e.logsTrackingIdsByDate))
  230. pagingResult.TotalCount = totalLogCount
  231. startIndex := getPagingStartIndex(startOffset, totalLogCount)
  232. pageCount = min(totalLogCount, pageCount)
  233. endIndex := max(0, (startIndex-pageCount)+1)
  234. log.WithFields(log.Fields{
  235. "startOffset": startOffset,
  236. "pageCount": pageCount,
  237. "total": totalLogCount,
  238. "startIndex": startIndex,
  239. "endIndex": endIndex,
  240. }).Tracef("GetLogTrackingIds")
  241. trackingIds := make([]*InternalLogEntry, 0, pageCount)
  242. if totalLogCount > 0 {
  243. for i := startIndex; i >= endIndex; i-- {
  244. trackingIds = append(trackingIds, cloneInternalLogEntry(e.logs[e.logsTrackingIdsByDate[i]]))
  245. }
  246. }
  247. e.logmutex.RUnlock()
  248. pagingResult.CountRemaining = endIndex
  249. return trackingIds, pagingResult
  250. }
  251. func isValidLogEntryForACL(entry *InternalLogEntry) bool {
  252. return entry != nil && entry.Binding != nil && entry.Binding.Action != nil
  253. }
  254. func isLogEntryAllowedByACL(cfg *config.Config, user *authpublic.AuthenticatedUser, entry *InternalLogEntry) bool {
  255. return acl.IsAllowedLogs(cfg, user, entry.Binding.Action)
  256. }
  257. func (e *Executor) filterLogsByACL(cfg *config.Config, user *authpublic.AuthenticatedUser, dateFilter string) []*InternalLogEntry {
  258. e.logmutex.RLock()
  259. defer e.logmutex.RUnlock()
  260. filtered := make([]*InternalLogEntry, 0, len(e.logsTrackingIdsByDate))
  261. filterDate, hasDateFilter := parseDateFilter(dateFilter)
  262. for _, trackingId := range e.logsTrackingIdsByDate {
  263. entry := e.logs[trackingId]
  264. if shouldIncludeLogEntry(cfg, user, entry, filterDate, hasDateFilter) {
  265. filtered = append(filtered, cloneInternalLogEntry(entry))
  266. }
  267. }
  268. return filtered
  269. }
  270. // parseDateFilter parses the date filter string and returns filter information.
  271. func parseDateFilter(dateFilter string) (filterDate time.Time, hasDateFilter bool) {
  272. if dateFilter == "" {
  273. return time.Time{}, false
  274. }
  275. parsedDate, err := time.Parse("2006-01-02", dateFilter)
  276. if err != nil {
  277. log.WithFields(log.Fields{
  278. "dateFilter": dateFilter,
  279. "error": err,
  280. }).Errorf("Failed to parse date filter, expected format YYYY-MM-DD")
  281. return time.Time{}, false
  282. }
  283. return parsedDate, true
  284. }
  285. // shouldIncludeLogEntry determines if a log entry should be included based on ACL and date filter.
  286. func shouldIncludeLogEntry(cfg *config.Config, user *authpublic.AuthenticatedUser, entry *InternalLogEntry, filterDate time.Time, hasDateFilter bool) bool {
  287. if !isValidLogEntryForACL(entry) {
  288. return false
  289. }
  290. if !isLogEntryAllowedByACL(cfg, user, entry) {
  291. return false
  292. }
  293. return matchesDateFilter(entry, filterDate, hasDateFilter)
  294. }
  295. // matchesDateFilter checks if the log entry matches the date filter.
  296. func matchesDateFilter(entry *InternalLogEntry, filterDate time.Time, hasDateFilter bool) bool {
  297. if !hasDateFilter {
  298. return true
  299. }
  300. entryDate := entry.DatetimeStarted.UTC().Truncate(24 * time.Hour)
  301. filterDateUTC := filterDate.UTC().Truncate(24 * time.Hour)
  302. return entryDate.Equal(filterDateUTC)
  303. }
  304. // paginateFilteredLogs applies pagination to a filtered list of logs and returns
  305. // the paginated results along with pagination metadata.
  306. func paginateFilteredLogs(filtered []*InternalLogEntry, startOffset int64, pageCount int64) ([]*InternalLogEntry, *PagingResult) {
  307. total := int64(len(filtered))
  308. paging := &PagingResult{PageSize: pageCount, TotalCount: total, StartOffset: startOffset}
  309. if total == 0 {
  310. paging.CountRemaining = 0
  311. return []*InternalLogEntry{}, paging
  312. }
  313. startIndex := getPagingStartIndex(startOffset, total)
  314. pageCount = min(total, pageCount)
  315. endIndex := max(0, (startIndex-pageCount)+1)
  316. out := make([]*InternalLogEntry, 0, pageCount)
  317. for i := startIndex; i >= endIndex && i < int64(len(filtered)); i-- {
  318. out = append(out, filtered[i])
  319. }
  320. paging.CountRemaining = endIndex
  321. return out, paging
  322. }
  323. // GetLogTrackingIdsACL returns logs filtered by ACL visibility for the user and
  324. // paginated correctly based on the filtered set.
  325. // dateFilter is optional and should be in YYYY-MM-DD format. If empty, no date filtering is applied.
  326. // expressionFilter is an optional filter expression applied after ACL checks.
  327. func (e *Executor) GetLogTrackingIdsACL(cfg *config.Config, user *authpublic.AuthenticatedUser, startOffset int64, pageCount int64, dateFilter string, expressionFilter string) ([]*InternalLogEntry, *PagingResult, error) {
  328. filtered := e.filterLogsByACL(cfg, user, dateFilter)
  329. program, err := logfilter.Compile(expressionFilter)
  330. if err != nil {
  331. return nil, nil, err
  332. }
  333. filtered, err = applyLogFilter(filtered, program)
  334. if err != nil {
  335. return nil, nil, err
  336. }
  337. logs, paging := paginateFilteredLogs(filtered, startOffset, pageCount)
  338. return logs, paging, nil
  339. }
  340. func (e *Executor) GetLog(trackingID string) (*InternalLogEntry, bool) {
  341. e.logmutex.RLock()
  342. defer e.logmutex.RUnlock()
  343. entry, found := e.logs[trackingID]
  344. return cloneInternalLogEntry(entry), found
  345. }
  346. func (e *Executor) GetLogsByBindingId(bindingId string) []*InternalLogEntry {
  347. e.logmutex.RLock()
  348. defer e.logmutex.RUnlock()
  349. logs, found := e.LogsByBindingId[bindingId]
  350. if !found {
  351. return make([]*InternalLogEntry, 0)
  352. }
  353. cloned := make([]*InternalLogEntry, 0, len(logs))
  354. for _, entry := range logs {
  355. cloned = append(cloned, cloneInternalLogEntry(entry))
  356. }
  357. return cloned
  358. }
  359. // shouldCountExecution checks if a log entry should be counted for rate limiting.
  360. func shouldCountExecution(logEntry *InternalLogEntry, windowStart time.Time) bool {
  361. return !logEntry.Blocked && !logEntry.Queued && logEntry.DatetimeStarted.After(windowStart)
  362. }
  363. // updateOldestExecution updates the oldest execution time if this entry is older.
  364. func updateOldestExecution(oldestExecutionTime **time.Time, logEntry *InternalLogEntry) {
  365. if *oldestExecutionTime == nil {
  366. *oldestExecutionTime = &logEntry.DatetimeStarted
  367. } else if logEntry.DatetimeStarted.Before(**oldestExecutionTime) {
  368. *oldestExecutionTime = &logEntry.DatetimeStarted
  369. }
  370. }
  371. // findOldestExecutionInWindow finds the oldest execution within the time window and counts executions.
  372. // Returns the count of executions and the oldest execution time, or nil if none found.
  373. func findOldestExecutionInWindow(logs []*InternalLogEntry, windowStart time.Time) (int, *time.Time) {
  374. executions := 0
  375. var oldestExecutionTime *time.Time
  376. for _, logEntry := range logs {
  377. if !shouldCountExecution(logEntry, windowStart) {
  378. continue
  379. }
  380. executions++
  381. updateOldestExecution(&oldestExecutionTime, logEntry)
  382. }
  383. return executions, oldestExecutionTime
  384. }
  385. // calculateExpiryTime calculates when the oldest execution will fall outside the rate limit window.
  386. func calculateExpiryTime(oldestExecutionTime time.Time, duration time.Duration, now time.Time) time.Time {
  387. expiryTime := oldestExecutionTime.Add(duration)
  388. if !expiryTime.After(now) {
  389. return time.Time{}
  390. }
  391. return expiryTime
  392. }
  393. // updateMaxExpiryTime updates maxExpiryTime if expiryTime is later.
  394. func updateMaxExpiryTime(maxExpiryTime *time.Time, expiryTime time.Time) {
  395. if expiryTime.IsZero() {
  396. return
  397. }
  398. if maxExpiryTime.IsZero() || expiryTime.After(*maxExpiryTime) {
  399. *maxExpiryTime = expiryTime
  400. }
  401. }
  402. // calculateExpiryForRate calculates the expiry time for a single rate limit rule.
  403. // Returns the expiry time if the rate limit is exceeded, or zero time if not.
  404. func calculateExpiryForRate(rate config.RateSpec, logs []*InternalLogEntry, now time.Time) time.Time {
  405. duration := parseDuration(rate)
  406. if duration <= 0 {
  407. return time.Time{}
  408. }
  409. windowStart := now.Add(-duration)
  410. executions, oldestExecutionTime := findOldestExecutionInWindow(logs, windowStart)
  411. if executions < rate.Limit || oldestExecutionTime == nil {
  412. return time.Time{}
  413. }
  414. return calculateExpiryTime(*oldestExecutionTime, duration, now)
  415. }
  416. // getLogsForBinding retrieves logs for a binding ID.
  417. func (e *Executor) getLogsForBinding(bindingId string) []*InternalLogEntry {
  418. e.logmutex.RLock()
  419. logs, found := e.LogsByBindingId[bindingId]
  420. e.logmutex.RUnlock()
  421. if !found || len(logs) == 0 {
  422. return nil
  423. }
  424. return logs
  425. }
  426. // calculateMaxExpiryTimeFromRates calculates the maximum expiry time across all rate limit rules.
  427. func calculateMaxExpiryTimeFromRates(rates []config.RateSpec, logs []*InternalLogEntry, now time.Time) time.Time {
  428. var maxExpiryTime time.Time
  429. for _, rate := range rates {
  430. expiryTime := calculateExpiryForRate(rate, logs, now)
  431. updateMaxExpiryTime(&maxExpiryTime, expiryTime)
  432. }
  433. return maxExpiryTime
  434. }
  435. // GetTimeUntilAvailable calculates when an action will be available again based on rate limits.
  436. // Returns the Unix timestamp in seconds when the rate limit expires, or 0 if the action is available now.
  437. func (e *Executor) GetTimeUntilAvailable(binding *ActionBinding) int64 {
  438. if len(binding.Action.MaxRate) == 0 {
  439. return 0
  440. }
  441. logs := e.getLogsForBinding(binding.ID)
  442. if logs == nil {
  443. return 0
  444. }
  445. maxExpiryTime := calculateMaxExpiryTimeFromRates(binding.Action.MaxRate, logs, time.Now())
  446. if maxExpiryTime.IsZero() {
  447. return 0
  448. }
  449. return maxExpiryTime.Unix()
  450. }
  451. func (e *Executor) SetLog(trackingID string, entry *InternalLogEntry) string {
  452. e.logmutex.Lock()
  453. defer e.logmutex.Unlock()
  454. if _, found := e.logs[trackingID]; found || !isValidTrackingID(trackingID) {
  455. trackingID = uuid.NewString()
  456. entry.ExecutionTrackingID = trackingID
  457. }
  458. entry.Index = int64(len(e.logsTrackingIdsByDate))
  459. e.logs[trackingID] = entry
  460. e.logsTrackingIdsByDate = append(e.logsTrackingIdsByDate, trackingID)
  461. return trackingID
  462. }
  463. // ExecRequest processes an ExecutionRequest
  464. func (e *Executor) ExecRequest(req *ExecutionRequest) (*sync.WaitGroup, string) {
  465. e.initializeExecRequest(req)
  466. log.Tracef("executor.ExecRequest(): trackingID=%s bindingID=%s", req.TrackingID, bindingIDForTrace(req))
  467. req.TrackingID = e.SetLog(req.TrackingID, req.logEntry)
  468. wg := new(sync.WaitGroup)
  469. wg.Add(1)
  470. go func() {
  471. queued := e.execChain(req, wg)
  472. if !queued {
  473. wg.Done()
  474. }
  475. }()
  476. return wg, req.TrackingID
  477. }
  478. func (e *Executor) initializeExecRequest(req *ExecutionRequest) {
  479. if req.AuthenticatedUser == nil {
  480. req.AuthenticatedUser = auth.UserGuest(req.Cfg)
  481. }
  482. req.executor = e
  483. req.logEntry = &InternalLogEntry{
  484. Binding: req.Binding,
  485. DatetimeStarted: time.Now(),
  486. ExecutionTrackingID: req.TrackingID,
  487. Output: "",
  488. ExitCode: DefaultExitCodeNotExecuted,
  489. ExecutionStarted: false,
  490. ExecutionFinished: false,
  491. ActionTitle: "notfound",
  492. ActionIcon: "&#x1f4a9;",
  493. Username: req.AuthenticatedUser.Username,
  494. }
  495. }
  496. func bindingIDForTrace(req *ExecutionRequest) string {
  497. if req.Binding == nil {
  498. return ""
  499. }
  500. return req.Binding.ID
  501. }
  502. func (e *Executor) execChain(req *ExecutionRequest, wg *sync.WaitGroup) bool {
  503. if !req.skipRequestRegistration {
  504. finished, queued := e.registerOrQueueRequest(req, wg)
  505. if finished || queued {
  506. return queued
  507. }
  508. }
  509. e.runExecutionSteps(req)
  510. e.finishExecChain(req)
  511. return false
  512. }
  513. func (e *Executor) registerOrQueueRequest(req *ExecutionRequest, wg *sync.WaitGroup) (finished bool, queued bool) {
  514. if !stepRequestAction(req) {
  515. e.finishExecChain(req)
  516. return true, false
  517. }
  518. if e.finishIfConcurrencyBlocked(req) {
  519. return true, false
  520. }
  521. return e.queueRequestIfGroupLimited(req, wg)
  522. }
  523. func (e *Executor) finishIfConcurrencyBlocked(req *ExecutionRequest) bool {
  524. if actionNeedsGroupLimit(req) {
  525. return false
  526. }
  527. if stepConcurrencyCheck(req) {
  528. return false
  529. }
  530. e.finishExecChain(req)
  531. return true
  532. }
  533. func (e *Executor) queueRequestIfGroupLimited(req *ExecutionRequest, wg *sync.WaitGroup) (finished bool, queued bool) {
  534. if !actionNeedsGroupLimit(req) || e.groupsHaveCapacityForActive(req) {
  535. return false, false
  536. }
  537. return e.queueRequestAfterACL(req, wg)
  538. }
  539. func (e *Executor) queueRequestAfterACL(req *ExecutionRequest, wg *sync.WaitGroup) (finished bool, queued bool) {
  540. if !stepACLCheck(req) {
  541. e.finishExecChain(req)
  542. return true, false
  543. }
  544. if e.queueRequest(req, wg) {
  545. e.finishExecChain(req)
  546. return true, false
  547. }
  548. notifyListenersStarted(req)
  549. return false, true
  550. }
  551. func (e *Executor) runExecutionSteps(req *ExecutionRequest) {
  552. for _, step := range e.chainOfCommand[1:] {
  553. if !step(req) {
  554. break
  555. }
  556. }
  557. }
  558. func (e *Executor) finishExecChain(req *ExecutionRequest) {
  559. req.mutateLogEntry(func(entry *InternalLogEntry) {
  560. if entry.DatetimeFinished.IsZero() {
  561. entry.DatetimeFinished = time.Now()
  562. }
  563. entry.ExecutionFinished = true
  564. })
  565. recordExecutionMetrics(req.logEntry)
  566. notifyListenersFinished(req)
  567. stepSaveLog(req)
  568. e.drainGroupQueue()
  569. }
  570. func getConcurrentCount(req *ExecutionRequest) int {
  571. concurrentCount := 0
  572. req.executor.logmutex.RLock()
  573. logs := req.executor.LogsByBindingId[req.Binding.ID]
  574. for _, logEntry := range logs {
  575. if !logEntry.ExecutionFinished && !logEntry.Queued {
  576. concurrentCount += 1
  577. }
  578. }
  579. req.executor.logmutex.RUnlock()
  580. return concurrentCount
  581. }
  582. func stepConcurrencyCheck(req *ExecutionRequest) bool {
  583. if actionNeedsGroupLimit(req) {
  584. return true
  585. }
  586. concurrentCount := getConcurrentCount(req)
  587. // Note that the current execution is counted int the logs, so when checking we +1
  588. if concurrentCount >= (req.Binding.Action.MaxConcurrent + 1) {
  589. log.WithFields(log.Fields{
  590. "actionTitle": req.logEntry.ActionTitle,
  591. "concurrentCount": concurrentCount,
  592. "maxConcurrent": req.Binding.Action.MaxConcurrent,
  593. }).Warnf("Blocked from executing due to concurrency limit")
  594. req.mutateLogEntry(func(entry *InternalLogEntry) {
  595. entry.Output = "Blocked from executing due to concurrency limit"
  596. entry.Blocked = true
  597. })
  598. return false
  599. }
  600. return true
  601. }
  602. func parseDuration(rate config.RateSpec) time.Duration {
  603. duration, err := time.ParseDuration(rate.Duration)
  604. if err != nil {
  605. log.Warnf("Could not parse duration: %v", rate.Duration)
  606. return -1 * time.Minute
  607. }
  608. return duration
  609. }
  610. func entityPrefixForRequest(req *ExecutionRequest) string {
  611. if req.Binding != nil && req.Binding.Entity != nil {
  612. return req.Binding.Entity.UniqueKey
  613. }
  614. return ""
  615. }
  616. func rateExecutionMatchesScope(logEntry *InternalLogEntry, req *ExecutionRequest, entityPrefix string) bool {
  617. if logEntry.EntityPrefix != entityPrefix {
  618. return false
  619. }
  620. return !logEntry.Queued && logEntry.ExecutionTrackingID != req.TrackingID
  621. }
  622. func logEntryStartedInWindow(logEntry *InternalLogEntry, windowStart time.Time) bool {
  623. return logEntry.DatetimeStarted.After(windowStart) && !logEntry.Blocked
  624. }
  625. func rateExecutionCountsForRate(logEntry *InternalLogEntry, req *ExecutionRequest, entityPrefix string, windowStart time.Time) bool {
  626. return rateExecutionMatchesScope(logEntry, req, entityPrefix) && logEntryStartedInWindow(logEntry, windowStart)
  627. }
  628. func countRateExecutions(logs []*InternalLogEntry, req *ExecutionRequest, entityPrefix string, windowStart time.Time) int {
  629. executions := 0
  630. for _, logEntry := range logs {
  631. if rateExecutionCountsForRate(logEntry, req, entityPrefix, windowStart) {
  632. executions += 1
  633. }
  634. }
  635. return executions
  636. }
  637. func getExecutionsCount(rate config.RateSpec, req *ExecutionRequest) int {
  638. duration := parseDuration(rate)
  639. then := time.Now().Add(-duration)
  640. req.executor.logmutex.RLock()
  641. logs := req.executor.LogsByBindingId[req.Binding.ID]
  642. executions := countRateExecutions(logs, req, entityPrefixForRequest(req), then)
  643. req.executor.logmutex.RUnlock()
  644. return executions
  645. }
  646. func stepRateCheck(req *ExecutionRequest) bool {
  647. for _, rate := range req.Binding.Action.MaxRate {
  648. executions := getExecutionsCount(rate, req)
  649. if executions >= rate.Limit {
  650. log.WithFields(log.Fields{
  651. "actionTitle": req.logEntry.ActionTitle,
  652. "executions": executions,
  653. "limit": rate.Limit,
  654. "duration": rate.Duration,
  655. }).Infof("Blocked from executing due to rate limit")
  656. req.mutateLogEntry(func(entry *InternalLogEntry) {
  657. entry.Output = "Blocked from executing due to rate limit"
  658. entry.Blocked = true
  659. })
  660. return false
  661. }
  662. }
  663. return true
  664. }
  665. func stepACLCheck(req *ExecutionRequest) bool {
  666. canExec := acl.IsAllowedExec(req.Cfg, req.AuthenticatedUser, req.Binding.Action)
  667. if !canExec {
  668. req.mutateLogEntry(func(entry *InternalLogEntry) {
  669. entry.Output = "ACL check failed. Blocked from executing."
  670. entry.Blocked = true
  671. })
  672. log.WithFields(log.Fields{
  673. "actionTitle": req.logEntry.ActionTitle,
  674. }).Warnf("ACL check failed. Blocked from executing.")
  675. }
  676. return canExec
  677. }
  678. func stepParseArgs(req *ExecutionRequest) bool {
  679. if !prepareArgumentsForExecution(req) {
  680. return false
  681. }
  682. ok := parseActionForExecution(req)
  683. if ok {
  684. copyStorableArgumentsToLogEntry(req)
  685. }
  686. return ok
  687. }
  688. func prepareArgumentsForExecution(req *ExecutionRequest) bool {
  689. ensureArgumentMap(req)
  690. if !hasBindingAndAction(req) {
  691. return fail(req, fmt.Errorf("cannot parse arguments: Binding or Action is nil"))
  692. }
  693. filterToDefinedArgumentsOnly(req)
  694. if err := injectSystemArgs(req); err != nil {
  695. return fail(req, err)
  696. }
  697. mangleInvalidArgumentValues(req)
  698. return true
  699. }
  700. func parseActionForExecution(req *ExecutionRequest) bool {
  701. if hasExec(req) {
  702. return handleExecBranch(req)
  703. }
  704. return handleShellBranch(req)
  705. }
  706. func handleExecBranch(req *ExecutionRequest) bool {
  707. args, err := parseActionExec(req.Arguments, req.Binding.Action, req.Binding.Entity)
  708. if err != nil {
  709. return fail(req, err)
  710. }
  711. req.useDirectExec = true
  712. req.execArgs = args
  713. return true
  714. }
  715. func handleShellBranch(req *ExecutionRequest) bool {
  716. if hasWebhookTag(req) {
  717. return fail(req, fmt.Errorf("webhooks cannot use Shell execution; use exec instead. See https://docs.olivetin.app/action_execution/shellvsexec.html"))
  718. }
  719. if err := checkShellArgumentSafety(req.Binding.Action); err != nil {
  720. return fail(req, err)
  721. }
  722. cmd, err := parseActionArguments(req)
  723. if err != nil {
  724. return fail(req, err)
  725. }
  726. req.useDirectExec = false
  727. req.finalParsedCommand = cmd
  728. return true
  729. }
  730. func ensureArgumentMap(req *ExecutionRequest) {
  731. if req.Arguments == nil {
  732. req.Arguments = make(map[string]string)
  733. }
  734. }
  735. func filterToDefinedArgumentsOnly(req *ExecutionRequest) {
  736. definedNames := make(map[string]struct{})
  737. for _, arg := range req.Binding.Action.Arguments {
  738. definedNames[arg.Name] = struct{}{}
  739. }
  740. filtered := make(map[string]string)
  741. for k, v := range req.Arguments {
  742. if keepArgument(k, definedNames) {
  743. filtered[k] = v
  744. }
  745. }
  746. req.Arguments = filtered
  747. }
  748. func keepArgument(name string, definedNames map[string]struct{}) bool {
  749. _, ok := definedNames[name]
  750. return ok
  751. }
  752. func hasWebhookTag(req *ExecutionRequest) bool {
  753. return slices.Contains(req.Tags, "webhook")
  754. }
  755. var systemArgumentDefinitions = []config.ActionArgument{
  756. {Name: "ot_executionTrackingId", Type: "ascii_identifier", RejectNull: true},
  757. {Name: "ot_username", Type: "shell_safe_identifier", RejectNull: true},
  758. }
  759. func injectSystemArgs(req *ExecutionRequest) error {
  760. args, err := validatedSystemArgs(req)
  761. if err != nil {
  762. return err
  763. }
  764. maps.Copy(req.Arguments, args)
  765. return nil
  766. }
  767. func validatedSystemArgs(req *ExecutionRequest) (map[string]string, error) {
  768. values := map[string]string{
  769. "ot_executionTrackingId": req.TrackingID,
  770. "ot_username": req.AuthenticatedUser.Username,
  771. }
  772. for i := range systemArgumentDefinitions {
  773. arg := &systemArgumentDefinitions[i]
  774. if err := ValidateArgument(arg, values[arg.Name], req.Binding.Action); err != nil {
  775. return nil, fmt.Errorf("system argument %q failed validation: %w", arg.Name, err)
  776. }
  777. }
  778. return values, nil
  779. }
  780. func hasBindingAndAction(req *ExecutionRequest) bool {
  781. return req.Binding != nil && req.Binding.Action != nil
  782. }
  783. func hasExec(req *ExecutionRequest) bool {
  784. return len(req.Binding.Action.Exec) > 0
  785. }
  786. func fail(req *ExecutionRequest, err error) bool {
  787. req.mutateLogEntry(func(entry *InternalLogEntry) {
  788. entry.Output = err.Error()
  789. })
  790. log.Warn(err.Error())
  791. return false
  792. }
  793. func stepRequestAction(req *ExecutionRequest) bool {
  794. metricActionsRequested.Inc()
  795. if !stepRequestActionHasBinding(req) {
  796. return false
  797. }
  798. stepRequestActionPopulateLogEntry(req)
  799. stepRequestActionRegisterLog(req)
  800. log.WithFields(log.Fields{
  801. "actionTitle": req.logEntry.ActionTitle,
  802. "tags": req.Tags,
  803. }).Infof("Action requested")
  804. notifyListenersStarted(req)
  805. return true
  806. }
  807. func stepRequestActionHasBinding(req *ExecutionRequest) bool {
  808. if req.Binding == nil || req.Binding.Action == nil {
  809. log.Warnf("Action request has no binding/action; skipping execution")
  810. return false
  811. }
  812. return true
  813. }
  814. func stepRequestActionPopulateLogEntry(req *ExecutionRequest) {
  815. req.mutateLogEntry(func(entry *InternalLogEntry) {
  816. entry.Binding = req.Binding
  817. entry.ActionConfigTitle = req.Binding.Action.Title
  818. entry.ActionTitle = tpl.ParseTemplateOfActionBeforeExec(req.Binding.Action.Title, req.Binding.Entity)
  819. entry.ActionIcon = tpl.ParseTemplateOfActionBeforeExec(req.Binding.Action.Icon, req.Binding.Entity)
  820. entry.Tags = req.Tags
  821. entry.Justification = ResolveJustification(req)
  822. if req.Binding.Entity != nil {
  823. entry.EntityPrefix = req.Binding.Entity.UniqueKey
  824. }
  825. })
  826. }
  827. func stepRequestActionRegisterLog(req *ExecutionRequest) {
  828. req.executor.logmutex.Lock()
  829. defer req.executor.logmutex.Unlock()
  830. if _, containsKey := req.executor.LogsByBindingId[req.Binding.ID]; !containsKey {
  831. req.executor.LogsByBindingId[req.Binding.ID] = make([]*InternalLogEntry, 0)
  832. }
  833. req.executor.LogsByBindingId[req.Binding.ID] = append(req.executor.LogsByBindingId[req.Binding.ID], req.logEntry)
  834. }
  835. func stepLogStart(req *ExecutionRequest) bool {
  836. log.WithFields(log.Fields{
  837. "actionTitle": req.logEntry.ActionTitle,
  838. "timeout": req.Binding.Action.Timeout,
  839. }).Infof("Action started")
  840. return true
  841. }
  842. func stepLogFinish(req *ExecutionRequest) bool {
  843. req.mutateLogEntry(func(entry *InternalLogEntry) {
  844. entry.ExecutionFinished = true
  845. })
  846. log.WithFields(log.Fields{
  847. "actionTitle": req.logEntry.ActionTitle,
  848. "outputLength": len(req.logEntry.Output),
  849. "timedOut": req.logEntry.TimedOut,
  850. "exit": req.logEntry.ExitCode,
  851. }).Infof("Action finished")
  852. return true
  853. }
  854. func notifyListenersFinished(req *ExecutionRequest) {
  855. for _, listener := range req.executor.copyListeners() {
  856. listener.OnExecutionFinished(req.logEntry)
  857. }
  858. }
  859. func notifyListenersStarted(req *ExecutionRequest) {
  860. for _, listener := range req.executor.copyListeners() {
  861. listener.OnExecutionStarted(req.logEntry)
  862. }
  863. }
  864. func appendErrorToStderr(req *ExecutionRequest, err error) {
  865. if err == nil {
  866. return
  867. }
  868. req.mutateLogEntry(func(entry *InternalLogEntry) {
  869. entry.Output = err.Error() + "\n\n" + entry.Output
  870. })
  871. }
  872. type OutputStreamer struct {
  873. Req *ExecutionRequest
  874. output bytes.Buffer
  875. mu sync.Mutex
  876. }
  877. func (ost *OutputStreamer) Write(o []byte) (n int, err error) {
  878. for _, listener := range ost.Req.executor.copyListeners() {
  879. listener.OnOutputChunk(o, ost.Req.TrackingID)
  880. }
  881. ost.mu.Lock()
  882. n, err = ost.output.Write(o)
  883. outputSoFar := ""
  884. if err == nil {
  885. outputSoFar = ost.output.String()
  886. }
  887. ost.mu.Unlock()
  888. if err != nil {
  889. return n, err
  890. }
  891. // Keep the log entry's Output in sync while the command is still running so
  892. // ExecutionStatus / mid-run result views can show output produced so far.
  893. ost.Req.mutateLogEntry(func(entry *InternalLogEntry) {
  894. entry.Output = outputSoFar
  895. })
  896. return n, nil
  897. }
  898. func (ost *OutputStreamer) String() string {
  899. ost.mu.Lock()
  900. defer ost.mu.Unlock()
  901. return ost.output.String()
  902. }
  903. func buildEnv(args map[string]string) []string {
  904. ret := append(os.Environ(), "OLIVETIN=1")
  905. for k, v := range args {
  906. varName := fmt.Sprintf("%v", strings.TrimSpace(strings.ToUpper(k)))
  907. // Skip arguments that might not have a name (eg, confirmation), as this causes weird bugs on Windows.
  908. if varName == "" {
  909. continue
  910. }
  911. ret = append(ret, fmt.Sprintf("%v=%v", varName, v))
  912. }
  913. return ret
  914. }
  915. func commandExitCode(cmd *exec.Cmd) int {
  916. if cmd == nil || cmd.ProcessState == nil {
  917. return -1
  918. }
  919. return cmd.ProcessState.ExitCode()
  920. }
  921. func stepExec(req *ExecutionRequest) bool {
  922. ctx, cancel := newTimeoutContext(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second, req.executor)
  923. defer cancel()
  924. streamer := &OutputStreamer{Req: req}
  925. cmd := buildCommand(ctx, req)
  926. if cmd == nil {
  927. req.mutateLogEntry(func(entry *InternalLogEntry) {
  928. entry.Output = "Cannot execute: no command arguments provided"
  929. })
  930. log.Warn("Cannot execute: no command arguments provided")
  931. return false
  932. }
  933. prepareCommand(cmd, streamer, req)
  934. runerr := cmd.Start()
  935. req.mutateLogEntry(func(entry *InternalLogEntry) {
  936. entry.Process = cmd.Process
  937. })
  938. ctx.setProcess(cmd.Process)
  939. waiterr := cmd.Wait()
  940. finalOutput := streamer.String()
  941. req.mutateLogEntry(func(entry *InternalLogEntry) {
  942. entry.ExitCode = int32(commandExitCode(cmd))
  943. entry.Output = finalOutput
  944. })
  945. appendErrorToStderr(req, runerr)
  946. appendErrorToStderr(req, waiterr)
  947. if errors.Is(ctx.Err(), context.DeadlineExceeded) {
  948. log.WithFields(log.Fields{
  949. "actionTitle": req.logEntry.ActionTitle,
  950. }).Warnf("Action timed out")
  951. req.mutateLogEntry(func(entry *InternalLogEntry) {
  952. entry.TimedOut = true
  953. entry.Output += "OliveTin::timeout - this action timed out after " + fmt.Sprintf("%v", req.Binding.Action.Timeout) + " seconds. If you need more time for this action, set a longer timeout. See https://docs.olivetin.app/action_customization/timeouts.html for more help."
  954. })
  955. }
  956. req.mutateLogEntry(func(entry *InternalLogEntry) {
  957. entry.DatetimeFinished = time.Now()
  958. })
  959. return true
  960. }
  961. func buildCommand(ctx context.Context, req *ExecutionRequest) *exec.Cmd {
  962. if req.useDirectExec {
  963. return wrapCommandDirect(ctx, req.execArgs)
  964. }
  965. return wrapCommandInShell(ctx, req.finalParsedCommand)
  966. }
  967. func prepareCommand(cmd *exec.Cmd, streamer *OutputStreamer, req *ExecutionRequest) {
  968. cmd.Stdout = streamer
  969. cmd.Stderr = streamer
  970. cmd.Env = buildEnv(req.Arguments)
  971. started := false
  972. req.mutateLogEntry(func(entry *InternalLogEntry) {
  973. if entry.ExecutionStarted {
  974. return
  975. }
  976. entry.ExecutionStarted = true
  977. started = true
  978. })
  979. if started {
  980. notifyListenersStarted(req)
  981. }
  982. }
  983. func stepExecAfter(req *ExecutionRequest) bool {
  984. ctx, cancel := newTimeoutContext(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second, req.executor)
  985. defer cancel()
  986. var stdout bytes.Buffer
  987. var stderr bytes.Buffer
  988. cmd, args, err := buildShellAfterCommand(ctx, req, &stdout, &stderr)
  989. if err != nil {
  990. return fail(req, err)
  991. }
  992. if cmd == nil {
  993. return true
  994. }
  995. cmd.Env = buildEnv(args)
  996. runerr := cmd.Start()
  997. ctx.setProcess(cmd.Process)
  998. waiterr := cmd.Wait()
  999. req.mutateLogEntry(func(entry *InternalLogEntry) {
  1000. entry.Output += "\n"
  1001. entry.Output += "OliveTin::shellAfterCompleted stdout\n"
  1002. entry.Output += stdout.String()
  1003. entry.Output += "OliveTin::shellAfterCompleted stderr\n"
  1004. entry.Output += stderr.String()
  1005. entry.Output += "OliveTin::shellAfterCompleted errors and summary\n"
  1006. })
  1007. appendErrorToStderr(req, runerr)
  1008. appendErrorToStderr(req, waiterr)
  1009. if errors.Is(ctx.Err(), context.DeadlineExceeded) {
  1010. req.mutateLogEntry(func(entry *InternalLogEntry) {
  1011. entry.Output += "Your shellAfterCompleted command timed out."
  1012. })
  1013. }
  1014. req.mutateLogEntry(func(entry *InternalLogEntry) {
  1015. entry.Output += fmt.Sprintf("Your shellAfterCompleted exited with code %v\n", commandExitCode(cmd))
  1016. entry.Output += "OliveTin::shellAfterCompleted output complete\n"
  1017. })
  1018. return true
  1019. }
  1020. func shellAfterCompletedAction(req *ExecutionRequest) (*config.Action, bool) {
  1021. if req == nil {
  1022. return nil, false
  1023. }
  1024. if !hasBindingAndAction(req) {
  1025. return nil, false
  1026. }
  1027. if req.Binding.Action.ShellAfterCompleted == "" {
  1028. return nil, false
  1029. }
  1030. return req.Binding.Action, true
  1031. }
  1032. // Matches legacy and modern template forms for shellAfterCompleted output/exitCode,
  1033. // including optional .Arguments. prefix and flexible whitespace. These must become
  1034. // quoted env refs before template execution so command output cannot inject into sh -c.
  1035. var (
  1036. shellAfterOutputRef = regexp.MustCompile(`\{\{\s*(?:\.Arguments\.)?output\s*\}\}`)
  1037. shellAfterExitCodeRef = regexp.MustCompile(`\{\{\s*(?:\.Arguments\.)?exitCode\s*\}\}`)
  1038. )
  1039. func substituteShellAfterCompletedEnvRefs(command string) string {
  1040. command = replaceShellAfterEnvRef(command, shellAfterOutputRef, "$OUTPUT")
  1041. command = replaceShellAfterEnvRef(command, shellAfterExitCodeRef, "$EXITCODE")
  1042. return command
  1043. }
  1044. func replaceShellAfterEnvRef(command string, pattern *regexp.Regexp, envRef string) string {
  1045. matches := pattern.FindAllStringIndex(command, -1)
  1046. for i := len(matches) - 1; i >= 0; i-- {
  1047. start, end := matches[i][0], matches[i][1]
  1048. replacement := `"` + envRef + `"`
  1049. if shellPosInsideSingleQuotes(command, start) {
  1050. // Break out of single quotes so the env ref can expand at runtime.
  1051. replacement = `'` + replacement + `'`
  1052. }
  1053. command = command[:start] + replacement + command[end:]
  1054. }
  1055. return command
  1056. }
  1057. func shellPosInsideSingleQuotes(command string, pos int) bool {
  1058. inSingle := false
  1059. inDouble := false
  1060. i := 0
  1061. for i < pos {
  1062. inSingle, inDouble, i = advanceShellQuoteState(command, i, pos, inSingle, inDouble)
  1063. }
  1064. return inSingle
  1065. }
  1066. func advanceShellQuoteState(command string, i, pos int, inSingle, inDouble bool) (bool, bool, int) {
  1067. if inSingle {
  1068. return advanceInsideSingleQuote(command, i, inSingle, inDouble)
  1069. }
  1070. if inDouble {
  1071. return advanceInsideDoubleQuote(command, i, pos, inSingle, inDouble)
  1072. }
  1073. return advanceOutsideQuotes(command, i, inSingle, inDouble)
  1074. }
  1075. func advanceInsideSingleQuote(command string, i int, inSingle, inDouble bool) (bool, bool, int) {
  1076. if command[i] == '\'' {
  1077. return false, inDouble, i + 1
  1078. }
  1079. return inSingle, inDouble, i + 1
  1080. }
  1081. func advanceInsideDoubleQuote(command string, i, pos int, inSingle, inDouble bool) (bool, bool, int) {
  1082. if command[i] == '\\' && i+1 < pos {
  1083. return inSingle, inDouble, i + 2
  1084. }
  1085. if command[i] == '"' {
  1086. return inSingle, false, i + 1
  1087. }
  1088. return inSingle, inDouble, i + 1
  1089. }
  1090. func advanceOutsideQuotes(command string, i int, inSingle, inDouble bool) (bool, bool, int) {
  1091. switch command[i] {
  1092. case '\'':
  1093. return true, inDouble, i + 1
  1094. case '"':
  1095. return inSingle, true, i + 1
  1096. default:
  1097. return inSingle, inDouble, i + 1
  1098. }
  1099. }
  1100. // shellAfterTemplateArgs omits output/exitCode so templates cannot expand them
  1101. // raw. Those values are only provided as OUTPUT/EXITCODE process environment.
  1102. func shellAfterTemplateArgs(args map[string]string) map[string]string {
  1103. templateArgs := make(map[string]string, len(args))
  1104. for name, value := range args {
  1105. if name == "output" || name == "exitCode" {
  1106. continue
  1107. }
  1108. templateArgs[name] = value
  1109. }
  1110. return templateArgs
  1111. }
  1112. func parseShellAfterCompletedCommand(req *ExecutionRequest, commandTemplate string, args map[string]string) (string, error) {
  1113. finalParsedCommand, err := tpl.ParseTemplateWithActionContext(commandTemplate, req.Binding.Entity, args)
  1114. if err != nil {
  1115. msg := "Could not prepare shellAfterCompleted command: " + err.Error() + "\n"
  1116. req.mutateLogEntry(func(entry *InternalLogEntry) {
  1117. entry.Output += msg
  1118. })
  1119. log.Warn(msg)
  1120. return "", err
  1121. }
  1122. return finalParsedCommand, nil
  1123. }
  1124. //gocyclo:ignore
  1125. func buildShellAfterCommand(ctx context.Context, req *ExecutionRequest, stdout, stderr *bytes.Buffer) (*exec.Cmd, map[string]string, error) {
  1126. action, ok := shellAfterCompletedAction(req)
  1127. if !ok {
  1128. return nil, nil, nil
  1129. }
  1130. if hasWebhookTag(req) {
  1131. return nil, nil, fmt.Errorf("webhooks cannot use shellAfterCompleted; use exec without after-completion shell instead. See https://docs.olivetin.app/action_execution/shellvsexec.html")
  1132. }
  1133. args, err := buildShellAfterArgs(req)
  1134. if err != nil {
  1135. return nil, nil, err
  1136. }
  1137. commandTemplate := substituteShellAfterCompletedEnvRefs(action.ShellAfterCompleted)
  1138. finalParsedCommand, err := parseShellAfterCompletedCommand(req, commandTemplate, shellAfterTemplateArgs(args))
  1139. if err != nil {
  1140. return nil, nil, err
  1141. }
  1142. cmd := wrapCommandInShell(ctx, finalParsedCommand)
  1143. cmd.Stdout = stdout
  1144. cmd.Stderr = stderr
  1145. return cmd, args, nil
  1146. }
  1147. func buildShellAfterArgs(req *ExecutionRequest) (map[string]string, error) {
  1148. args, err := validatedSystemArgs(req)
  1149. if err != nil {
  1150. return nil, err
  1151. }
  1152. args["output"] = req.logEntry.Output
  1153. args["exitCode"] = fmt.Sprintf("%v", req.logEntry.ExitCode)
  1154. return args, nil
  1155. }
  1156. //gocyclo:ignore
  1157. func stepTrigger(req *ExecutionRequest) bool {
  1158. if req.Binding.Action.Triggers == nil {
  1159. return true
  1160. }
  1161. if req.TriggerDepth >= MaxTriggerDepth {
  1162. log.WithFields(log.Fields{
  1163. "actionTitle": req.logEntry.ActionTitle,
  1164. "depth": req.TriggerDepth,
  1165. }).Warnf("Trigger action reached maximum depth of %v. Not triggering further actions.", MaxTriggerDepth)
  1166. req.mutateLogEntry(func(entry *InternalLogEntry) {
  1167. entry.Output += fmt.Sprintf("OliveTin::trigger - this action reached maximum trigger depth of %v. Not triggering further actions.", MaxTriggerDepth)
  1168. })
  1169. return true
  1170. }
  1171. if len(req.Tags) > 0 && req.Tags[0] == "trigger" {
  1172. log.Warnf("Trigger action is triggering another trigger action. This is allowed, but be careful not to create trigger loops.")
  1173. }
  1174. triggerLoop(req)
  1175. return true
  1176. }
  1177. func triggerLoop(req *ExecutionRequest) {
  1178. for _, triggerTitle := range req.Binding.Action.Triggers {
  1179. binding := req.executor.findBindingByActionTitle(triggerTitle, "")
  1180. if binding == nil {
  1181. log.WithFields(log.Fields{
  1182. "triggerTitle": triggerTitle,
  1183. "fromAction": req.logEntry.ActionTitle,
  1184. }).Warnf("Trigger references unknown action title; skipping")
  1185. continue
  1186. }
  1187. trigger := &ExecutionRequest{
  1188. Binding: binding,
  1189. TrackingID: uuid.NewString(),
  1190. Tags: []string{"trigger"},
  1191. AuthenticatedUser: req.AuthenticatedUser,
  1192. Arguments: req.Arguments,
  1193. Cfg: req.Cfg,
  1194. TriggerDepth: req.TriggerDepth + 1,
  1195. Justification: fmt.Sprintf("Triggered by action: %s", req.logEntry.ActionTitle),
  1196. }
  1197. req.executor.ExecRequest(trigger)
  1198. }
  1199. }
  1200. func stepSaveLog(req *ExecutionRequest) bool {
  1201. if !canSaveExecutionLog(req) {
  1202. log.Warnf("Cannot save execution log; missing request, log entry, binding/action, or config")
  1203. return false
  1204. }
  1205. filename := fmt.Sprintf("%v.%v.%v", sanitizeLogFilename(req.logEntry.ActionTitle), req.logEntry.DatetimeStarted.Unix(), req.logEntry.ExecutionTrackingID)
  1206. saveLogResults(req, filename)
  1207. saveLogOutput(req, filename)
  1208. return true
  1209. }
  1210. func canSaveExecutionLog(req *ExecutionRequest) bool {
  1211. return req != nil && req.logEntry != nil && req.Binding != nil && req.Binding.Action != nil && req.Cfg != nil
  1212. }
  1213. // sanitizeLogFilename replaces characters that are unsafe in filenames so action
  1214. // titles like "Create/update Report" do not create nested paths or fail to write.
  1215. func sanitizeLogFilename(title string) string {
  1216. oldnew := []string{
  1217. "/", "_",
  1218. "\\", "_",
  1219. ":", "_",
  1220. "*", "_",
  1221. "?", "_",
  1222. "\"", "_",
  1223. "<", "_",
  1224. ">", "_",
  1225. "|", "_",
  1226. }
  1227. // NUL and other C0 controls plus DEL are invalid or problematic in filenames.
  1228. for i := 0; i < 32; i++ {
  1229. oldnew = append(oldnew, string(rune(i)), "_")
  1230. }
  1231. oldnew = append(oldnew, "\x7f", "_")
  1232. return strings.NewReplacer(oldnew...).Replace(title)
  1233. }
  1234. func firstNonEmpty(one, two string) string {
  1235. if one != "" {
  1236. return one
  1237. }
  1238. return two
  1239. }
  1240. func saveLogResults(req *ExecutionRequest, filename string) {
  1241. dir := firstNonEmpty(req.Binding.Action.SaveLogs.ResultsDirectory, req.Cfg.SaveLogs.ResultsDirectory)
  1242. if dir != "" {
  1243. data, err := yaml.Marshal(req.logEntry)
  1244. if err != nil {
  1245. log.Warnf("%v", err)
  1246. }
  1247. filepath := path.Join(dir, filename+".yaml")
  1248. err = os.WriteFile(filepath, data, 0600)
  1249. if err != nil {
  1250. log.Warnf("%v", err)
  1251. }
  1252. }
  1253. }
  1254. func saveLogOutput(req *ExecutionRequest, filename string) {
  1255. dir := firstNonEmpty(req.Binding.Action.SaveLogs.OutputDirectory, req.Cfg.SaveLogs.OutputDirectory)
  1256. if dir != "" {
  1257. data := req.logEntry.Output
  1258. filepath := path.Join(dir, filename+".log")
  1259. err := os.WriteFile(filepath, []byte(data), 0600)
  1260. if err != nil {
  1261. log.Warnf("%v", err)
  1262. }
  1263. }
  1264. }