4
0

executor.go 43 KB

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