executor.go 41 KB

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