executor.go 42 KB

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