executor.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  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. func filterToDefinedArgumentsOnly(req *ExecutionRequest) {
  747. definedNames := make(map[string]struct{})
  748. for _, arg := range req.Binding.Action.Arguments {
  749. definedNames[arg.Name] = struct{}{}
  750. }
  751. filtered := make(map[string]string)
  752. for k, v := range req.Arguments {
  753. if keepArgument(k, definedNames) {
  754. filtered[k] = v
  755. }
  756. }
  757. req.Arguments = filtered
  758. }
  759. func keepArgument(name string, definedNames map[string]struct{}) bool {
  760. _, ok := definedNames[name]
  761. return ok
  762. }
  763. func hasWebhookTag(req *ExecutionRequest) bool {
  764. return slices.Contains(req.Tags, "webhook")
  765. }
  766. var systemArgumentDefinitions = []config.ActionArgument{
  767. {Name: "ot_executionTrackingId", Type: "ascii_identifier", RejectNull: true},
  768. {Name: "ot_username", Type: "shell_safe_identifier", RejectNull: true},
  769. }
  770. func injectSystemArgs(req *ExecutionRequest) error {
  771. args, err := validatedSystemArgs(req)
  772. if err != nil {
  773. return err
  774. }
  775. maps.Copy(req.Arguments, args)
  776. return nil
  777. }
  778. func validatedSystemArgs(req *ExecutionRequest) (map[string]string, error) {
  779. values := map[string]string{
  780. "ot_executionTrackingId": req.TrackingID,
  781. "ot_username": req.AuthenticatedUser.Username,
  782. }
  783. for i := range systemArgumentDefinitions {
  784. arg := &systemArgumentDefinitions[i]
  785. if err := ValidateArgument(arg, values[arg.Name], req.Binding.Action); err != nil {
  786. return nil, fmt.Errorf("system argument %q failed validation: %w", arg.Name, err)
  787. }
  788. }
  789. return values, nil
  790. }
  791. func hasBindingAndAction(req *ExecutionRequest) bool {
  792. return req.Binding != nil && req.Binding.Action != nil
  793. }
  794. func hasExec(req *ExecutionRequest) bool {
  795. return len(req.Binding.Action.Exec) > 0
  796. }
  797. func fail(req *ExecutionRequest, err error) bool {
  798. req.mutateLogEntry(func(entry *InternalLogEntry) {
  799. entry.Output = err.Error()
  800. })
  801. log.Warn(err.Error())
  802. return false
  803. }
  804. func stepRequestAction(req *ExecutionRequest) bool {
  805. metricActionsRequested.Inc()
  806. if !stepRequestActionHasBinding(req) {
  807. return false
  808. }
  809. stepRequestActionPopulateLogEntry(req)
  810. stepRequestActionRegisterLog(req)
  811. log.WithFields(log.Fields{
  812. "actionTitle": req.logEntry.ActionTitle,
  813. "tags": req.Tags,
  814. }).Infof("Action requested")
  815. notifyListenersStarted(req)
  816. return true
  817. }
  818. func stepRequestActionHasBinding(req *ExecutionRequest) bool {
  819. if req.Binding == nil || req.Binding.Action == nil {
  820. log.Warnf("Action request has no binding/action; skipping execution")
  821. return false
  822. }
  823. return true
  824. }
  825. func stepRequestActionPopulateLogEntry(req *ExecutionRequest) {
  826. req.mutateLogEntry(func(entry *InternalLogEntry) {
  827. entry.Binding = req.Binding
  828. entry.ActionConfigTitle = req.Binding.Action.Title
  829. entry.ActionTitle = tpl.ParseTemplateOfActionBeforeExec(req.Binding.Action.Title, req.Binding.Entity)
  830. entry.ActionIcon = tpl.ParseTemplateOfActionBeforeExec(req.Binding.Action.Icon, req.Binding.Entity)
  831. entry.Tags = req.Tags
  832. entry.Justification = ResolveJustification(req)
  833. if req.Binding.Entity != nil {
  834. entry.EntityPrefix = req.Binding.Entity.UniqueKey
  835. }
  836. })
  837. }
  838. func stepRequestActionRegisterLog(req *ExecutionRequest) {
  839. req.executor.logmutex.Lock()
  840. defer req.executor.logmutex.Unlock()
  841. if _, containsKey := req.executor.LogsByBindingId[req.Binding.ID]; !containsKey {
  842. req.executor.LogsByBindingId[req.Binding.ID] = make([]*InternalLogEntry, 0)
  843. }
  844. req.executor.LogsByBindingId[req.Binding.ID] = append(req.executor.LogsByBindingId[req.Binding.ID], req.logEntry)
  845. }
  846. func stepLogStart(req *ExecutionRequest) bool {
  847. log.WithFields(log.Fields{
  848. "actionTitle": req.logEntry.ActionTitle,
  849. "timeout": req.Binding.Action.Timeout,
  850. }).Infof("Action started")
  851. return true
  852. }
  853. func stepLogFinish(req *ExecutionRequest) bool {
  854. req.mutateLogEntry(func(entry *InternalLogEntry) {
  855. entry.ExecutionFinished = true
  856. })
  857. log.WithFields(log.Fields{
  858. "actionTitle": req.logEntry.ActionTitle,
  859. "outputLength": len(req.logEntry.Output),
  860. "timedOut": req.logEntry.TimedOut,
  861. "exit": req.logEntry.ExitCode,
  862. }).Infof("Action finished")
  863. return true
  864. }
  865. func notifyListenersFinished(req *ExecutionRequest) {
  866. for _, listener := range req.executor.copyListeners() {
  867. listener.OnExecutionFinished(req.logEntry)
  868. }
  869. }
  870. func notifyListenersStarted(req *ExecutionRequest) {
  871. for _, listener := range req.executor.copyListeners() {
  872. listener.OnExecutionStarted(req.logEntry)
  873. }
  874. }
  875. func appendErrorToStderr(req *ExecutionRequest, err error) {
  876. if err == nil {
  877. return
  878. }
  879. req.mutateLogEntry(func(entry *InternalLogEntry) {
  880. entry.Output = err.Error() + "\n\n" + entry.Output
  881. })
  882. }
  883. type OutputStreamer struct {
  884. Req *ExecutionRequest
  885. output bytes.Buffer
  886. mu sync.Mutex
  887. }
  888. func (ost *OutputStreamer) Write(o []byte) (n int, err error) {
  889. for _, listener := range ost.Req.executor.copyListeners() {
  890. listener.OnOutputChunk(o, ost.Req.TrackingID)
  891. }
  892. ost.mu.Lock()
  893. n, err = ost.output.Write(o)
  894. outputSoFar := ""
  895. if err == nil {
  896. outputSoFar = ost.output.String()
  897. }
  898. ost.mu.Unlock()
  899. if err != nil {
  900. return n, err
  901. }
  902. // Keep the log entry's Output in sync while the command is still running so
  903. // ExecutionStatus / mid-run result views can show output produced so far.
  904. ost.Req.mutateLogEntry(func(entry *InternalLogEntry) {
  905. entry.Output = outputSoFar
  906. })
  907. return n, nil
  908. }
  909. func (ost *OutputStreamer) String() string {
  910. ost.mu.Lock()
  911. defer ost.mu.Unlock()
  912. return ost.output.String()
  913. }
  914. func buildEnv(args map[string]string) []string {
  915. ret := append(os.Environ(), "OLIVETIN=1")
  916. for k, v := range args {
  917. varName := fmt.Sprintf("%v", strings.TrimSpace(strings.ToUpper(k)))
  918. // Skip arguments that might not have a name (eg, confirmation), as this causes weird bugs on Windows.
  919. if varName == "" {
  920. continue
  921. }
  922. ret = append(ret, fmt.Sprintf("%v=%v", varName, v))
  923. }
  924. return ret
  925. }
  926. func commandExitCode(cmd *exec.Cmd) int {
  927. if cmd == nil || cmd.ProcessState == nil {
  928. return -1
  929. }
  930. return cmd.ProcessState.ExitCode()
  931. }
  932. func stepExec(req *ExecutionRequest) bool {
  933. ctx, cancel := newTimeoutContext(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second, req.executor)
  934. defer cancel()
  935. streamer := &OutputStreamer{Req: req}
  936. cmd := buildCommand(ctx, req)
  937. if cmd == nil {
  938. req.mutateLogEntry(func(entry *InternalLogEntry) {
  939. entry.Output = "Cannot execute: no command arguments provided"
  940. })
  941. log.Warn("Cannot execute: no command arguments provided")
  942. return false
  943. }
  944. prepareCommand(cmd, streamer, req)
  945. runerr := cmd.Start()
  946. req.mutateLogEntry(func(entry *InternalLogEntry) {
  947. entry.Process = cmd.Process
  948. })
  949. ctx.setProcess(cmd.Process)
  950. waiterr := cmd.Wait()
  951. finalOutput := streamer.String()
  952. req.mutateLogEntry(func(entry *InternalLogEntry) {
  953. entry.ExitCode = int32(commandExitCode(cmd))
  954. entry.Output = finalOutput
  955. })
  956. appendErrorToStderr(req, runerr)
  957. appendErrorToStderr(req, waiterr)
  958. if errors.Is(ctx.Err(), context.DeadlineExceeded) {
  959. log.WithFields(log.Fields{
  960. "actionTitle": req.logEntry.ActionTitle,
  961. }).Warnf("Action timed out")
  962. req.mutateLogEntry(func(entry *InternalLogEntry) {
  963. entry.TimedOut = true
  964. 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."
  965. })
  966. }
  967. req.mutateLogEntry(func(entry *InternalLogEntry) {
  968. entry.DatetimeFinished = time.Now()
  969. })
  970. return true
  971. }
  972. func buildCommand(ctx context.Context, req *ExecutionRequest) *exec.Cmd {
  973. if req.useDirectExec {
  974. return wrapCommandDirect(ctx, req.execArgs)
  975. }
  976. return wrapCommandInShell(ctx, req.finalParsedCommand)
  977. }
  978. func prepareCommand(cmd *exec.Cmd, streamer *OutputStreamer, req *ExecutionRequest) {
  979. cmd.Stdout = streamer
  980. cmd.Stderr = streamer
  981. cmd.Env = buildEnv(req.Arguments)
  982. started := false
  983. req.mutateLogEntry(func(entry *InternalLogEntry) {
  984. if entry.ExecutionStarted {
  985. return
  986. }
  987. entry.ExecutionStarted = true
  988. started = true
  989. })
  990. if started {
  991. notifyListenersStarted(req)
  992. }
  993. }
  994. func stepExecAfter(req *ExecutionRequest) bool {
  995. ctx, cancel := newTimeoutContext(context.Background(), time.Duration(req.Binding.Action.Timeout)*time.Second, req.executor)
  996. defer cancel()
  997. var stdout bytes.Buffer
  998. var stderr bytes.Buffer
  999. cmd, args, err := buildShellAfterCommand(ctx, req, &stdout, &stderr)
  1000. if err != nil {
  1001. return fail(req, err)
  1002. }
  1003. if cmd == nil {
  1004. return true
  1005. }
  1006. cmd.Env = buildEnv(args)
  1007. runerr := cmd.Start()
  1008. ctx.setProcess(cmd.Process)
  1009. waiterr := cmd.Wait()
  1010. req.mutateLogEntry(func(entry *InternalLogEntry) {
  1011. entry.Output += "\n"
  1012. entry.Output += "OliveTin::shellAfterCompleted stdout\n"
  1013. entry.Output += stdout.String()
  1014. entry.Output += "OliveTin::shellAfterCompleted stderr\n"
  1015. entry.Output += stderr.String()
  1016. entry.Output += "OliveTin::shellAfterCompleted errors and summary\n"
  1017. })
  1018. appendErrorToStderr(req, runerr)
  1019. appendErrorToStderr(req, waiterr)
  1020. if errors.Is(ctx.Err(), context.DeadlineExceeded) {
  1021. req.mutateLogEntry(func(entry *InternalLogEntry) {
  1022. entry.Output += "Your shellAfterCompleted command timed out."
  1023. })
  1024. }
  1025. req.mutateLogEntry(func(entry *InternalLogEntry) {
  1026. entry.Output += fmt.Sprintf("Your shellAfterCompleted exited with code %v\n", commandExitCode(cmd))
  1027. entry.Output += "OliveTin::shellAfterCompleted output complete\n"
  1028. })
  1029. return true
  1030. }
  1031. func shellAfterCompletedAction(req *ExecutionRequest) (*config.Action, bool) {
  1032. if req == nil {
  1033. return nil, false
  1034. }
  1035. if !hasBindingAndAction(req) {
  1036. return nil, false
  1037. }
  1038. if req.Binding.Action.ShellAfterCompleted == "" {
  1039. return nil, false
  1040. }
  1041. return req.Binding.Action, true
  1042. }
  1043. // Matches legacy and modern template forms for shellAfterCompleted output/exitCode,
  1044. // including optional .Arguments. prefix and flexible whitespace. These must become
  1045. // quoted env refs before template execution so command output cannot inject into sh -c.
  1046. var (
  1047. shellAfterOutputRef = regexp.MustCompile(`\{\{\s*(?:\.Arguments\.)?output\s*\}\}`)
  1048. shellAfterExitCodeRef = regexp.MustCompile(`\{\{\s*(?:\.Arguments\.)?exitCode\s*\}\}`)
  1049. )
  1050. func substituteShellAfterCompletedEnvRefs(command string) string {
  1051. command = replaceShellAfterEnvRef(command, shellAfterOutputRef, "$OUTPUT")
  1052. command = replaceShellAfterEnvRef(command, shellAfterExitCodeRef, "$EXITCODE")
  1053. return command
  1054. }
  1055. func replaceShellAfterEnvRef(command string, pattern *regexp.Regexp, envRef string) string {
  1056. matches := pattern.FindAllStringIndex(command, -1)
  1057. for _, match := range slices.Backward(matches) {
  1058. start, end := match[0], match[1]
  1059. replacement := `"` + envRef + `"`
  1060. if shellPosInsideSingleQuotes(command, start) {
  1061. // Break out of single quotes so the env ref can expand at runtime.
  1062. replacement = `'` + replacement + `'`
  1063. }
  1064. command = command[:start] + replacement + command[end:]
  1065. }
  1066. return command
  1067. }
  1068. func shellPosInsideSingleQuotes(command string, pos int) bool {
  1069. inSingle := false
  1070. inDouble := false
  1071. i := 0
  1072. for i < pos {
  1073. inSingle, inDouble, i = advanceShellQuoteState(command, i, pos, inSingle, inDouble)
  1074. }
  1075. return inSingle
  1076. }
  1077. func advanceShellQuoteState(command string, i, pos int, inSingle, inDouble bool) (bool, bool, int) {
  1078. if inSingle {
  1079. return advanceInsideSingleQuote(command, i, inSingle, inDouble)
  1080. }
  1081. if inDouble {
  1082. return advanceInsideDoubleQuote(command, i, pos, inSingle, inDouble)
  1083. }
  1084. return advanceOutsideQuotes(command, i, inSingle, inDouble)
  1085. }
  1086. func advanceInsideSingleQuote(command string, i int, inSingle, inDouble bool) (bool, bool, int) {
  1087. if command[i] == '\'' {
  1088. return false, inDouble, i + 1
  1089. }
  1090. return inSingle, inDouble, i + 1
  1091. }
  1092. func advanceInsideDoubleQuote(command string, i, pos int, inSingle, inDouble bool) (bool, bool, int) {
  1093. if command[i] == '\\' && i+1 < pos {
  1094. return inSingle, inDouble, i + 2
  1095. }
  1096. if command[i] == '"' {
  1097. return inSingle, false, i + 1
  1098. }
  1099. return inSingle, inDouble, i + 1
  1100. }
  1101. func advanceOutsideQuotes(command string, i int, inSingle, inDouble bool) (bool, bool, int) {
  1102. switch command[i] {
  1103. case '\'':
  1104. return true, inDouble, i + 1
  1105. case '"':
  1106. return inSingle, true, i + 1
  1107. default:
  1108. return inSingle, inDouble, i + 1
  1109. }
  1110. }
  1111. // shellAfterTemplateArgs omits output/exitCode so templates cannot expand them
  1112. // raw. Those values are only provided as OUTPUT/EXITCODE process environment.
  1113. func shellAfterTemplateArgs(args map[string]string) map[string]string {
  1114. templateArgs := make(map[string]string, len(args))
  1115. for name, value := range args {
  1116. if name == "output" || name == "exitCode" {
  1117. continue
  1118. }
  1119. templateArgs[name] = value
  1120. }
  1121. return templateArgs
  1122. }
  1123. func parseShellAfterCompletedCommand(req *ExecutionRequest, commandTemplate string, args map[string]string) (string, error) {
  1124. finalParsedCommand, err := tpl.ParseTemplateWithActionContext(commandTemplate, req.Binding.Entity, args)
  1125. if err != nil {
  1126. msg := "Could not prepare shellAfterCompleted command: " + err.Error() + "\n"
  1127. req.mutateLogEntry(func(entry *InternalLogEntry) {
  1128. entry.Output += msg
  1129. })
  1130. log.Warn(msg)
  1131. return "", err
  1132. }
  1133. return finalParsedCommand, nil
  1134. }
  1135. //gocyclo:ignore
  1136. func buildShellAfterCommand(ctx context.Context, req *ExecutionRequest, stdout, stderr *bytes.Buffer) (*exec.Cmd, map[string]string, error) {
  1137. action, ok := shellAfterCompletedAction(req)
  1138. if !ok {
  1139. return nil, nil, nil
  1140. }
  1141. if hasWebhookTag(req) {
  1142. 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")
  1143. }
  1144. args, err := buildShellAfterArgs(req)
  1145. if err != nil {
  1146. return nil, nil, err
  1147. }
  1148. commandTemplate := substituteShellAfterCompletedEnvRefs(action.ShellAfterCompleted)
  1149. finalParsedCommand, err := parseShellAfterCompletedCommand(req, commandTemplate, shellAfterTemplateArgs(args))
  1150. if err != nil {
  1151. return nil, nil, err
  1152. }
  1153. cmd := wrapCommandInShell(ctx, finalParsedCommand)
  1154. cmd.Stdout = stdout
  1155. cmd.Stderr = stderr
  1156. return cmd, args, nil
  1157. }
  1158. func buildShellAfterArgs(req *ExecutionRequest) (map[string]string, error) {
  1159. args, err := validatedSystemArgs(req)
  1160. if err != nil {
  1161. return nil, err
  1162. }
  1163. args["output"] = req.logEntry.Output
  1164. args["exitCode"] = fmt.Sprintf("%v", req.logEntry.ExitCode)
  1165. return args, nil
  1166. }
  1167. //gocyclo:ignore
  1168. func stepTrigger(req *ExecutionRequest) bool {
  1169. if req.Binding.Action.Triggers == nil {
  1170. return true
  1171. }
  1172. if req.TriggerDepth >= MaxTriggerDepth {
  1173. log.WithFields(log.Fields{
  1174. "actionTitle": req.logEntry.ActionTitle,
  1175. "depth": req.TriggerDepth,
  1176. }).Warnf("Trigger action reached maximum depth of %v. Not triggering further actions.", MaxTriggerDepth)
  1177. req.mutateLogEntry(func(entry *InternalLogEntry) {
  1178. entry.Output += fmt.Sprintf("OliveTin::trigger - this action reached maximum trigger depth of %v. Not triggering further actions.", MaxTriggerDepth)
  1179. })
  1180. return true
  1181. }
  1182. if len(req.Tags) > 0 && req.Tags[0] == "trigger" {
  1183. log.Warnf("Trigger action is triggering another trigger action. This is allowed, but be careful not to create trigger loops.")
  1184. }
  1185. triggerLoop(req)
  1186. return true
  1187. }
  1188. func triggerLoop(req *ExecutionRequest) {
  1189. for _, triggerTitle := range req.Binding.Action.Triggers {
  1190. binding := req.executor.findBindingByActionTitle(triggerTitle, "")
  1191. if binding == nil {
  1192. log.WithFields(log.Fields{
  1193. "triggerTitle": triggerTitle,
  1194. "fromAction": req.logEntry.ActionTitle,
  1195. }).Warnf("Trigger references unknown action title; skipping")
  1196. continue
  1197. }
  1198. trigger := &ExecutionRequest{
  1199. Binding: binding,
  1200. TrackingID: uuid.NewString(),
  1201. Tags: triggeredRequestTags(req),
  1202. AuthenticatedUser: req.AuthenticatedUser,
  1203. Arguments: req.Arguments,
  1204. Cfg: req.Cfg,
  1205. TriggerDepth: req.TriggerDepth + 1,
  1206. Justification: fmt.Sprintf("Triggered by action: %s", req.logEntry.ActionTitle),
  1207. }
  1208. req.executor.ExecRequest(trigger)
  1209. }
  1210. }
  1211. // Triggered actions inherit the webhook tag so that the webhook shell
  1212. // restrictions apply to the whole trigger chain, not just the first action.
  1213. func triggeredRequestTags(req *ExecutionRequest) []string {
  1214. tags := []string{"trigger"}
  1215. if hasWebhookTag(req) {
  1216. tags = append(tags, "webhook")
  1217. }
  1218. return tags
  1219. }
  1220. func stepSaveLog(req *ExecutionRequest) bool {
  1221. if !canSaveExecutionLog(req) {
  1222. log.Warnf("Cannot save execution log; missing request, log entry, binding/action, or config")
  1223. return false
  1224. }
  1225. filename := fmt.Sprintf("%v.%v.%v", sanitizeLogFilename(req.logEntry.ActionTitle), req.logEntry.DatetimeStarted.Unix(), req.logEntry.ExecutionTrackingID)
  1226. saveLogResults(req, filename)
  1227. saveLogOutput(req, filename)
  1228. return true
  1229. }
  1230. func canSaveExecutionLog(req *ExecutionRequest) bool {
  1231. return req != nil && req.logEntry != nil && req.Binding != nil && req.Binding.Action != nil && req.Cfg != nil
  1232. }
  1233. // sanitizeLogFilename replaces characters that are unsafe in filenames so action
  1234. // titles like "Create/update Report" do not create nested paths or fail to write.
  1235. func sanitizeLogFilename(title string) string {
  1236. oldnew := []string{
  1237. "/", "_",
  1238. "\\", "_",
  1239. ":", "_",
  1240. "*", "_",
  1241. "?", "_",
  1242. "\"", "_",
  1243. "<", "_",
  1244. ">", "_",
  1245. "|", "_",
  1246. }
  1247. // NUL and other C0 controls plus DEL are invalid or problematic in filenames.
  1248. for i := range 32 {
  1249. oldnew = append(oldnew, string(rune(i)), "_")
  1250. }
  1251. oldnew = append(oldnew, "\x7f", "_")
  1252. return strings.NewReplacer(oldnew...).Replace(title)
  1253. }
  1254. func firstNonEmpty(one, two string) string {
  1255. if one != "" {
  1256. return one
  1257. }
  1258. return two
  1259. }
  1260. func saveLogResults(req *ExecutionRequest, filename string) {
  1261. dir := firstNonEmpty(req.Binding.Action.SaveLogs.ResultsDirectory, req.Cfg.SaveLogs.ResultsDirectory)
  1262. if dir != "" {
  1263. data, err := yaml.Marshal(req.logEntry)
  1264. if err != nil {
  1265. log.Warnf("%v", err)
  1266. }
  1267. filepath := path.Join(dir, filename+".yaml")
  1268. err = os.WriteFile(filepath, data, 0600)
  1269. if err != nil {
  1270. log.Warnf("%v", err)
  1271. }
  1272. }
  1273. }
  1274. func saveLogOutput(req *ExecutionRequest, filename string) {
  1275. dir := firstNonEmpty(req.Binding.Action.SaveLogs.OutputDirectory, req.Cfg.SaveLogs.OutputDirectory)
  1276. if dir != "" {
  1277. data := req.logEntry.Output
  1278. filepath := path.Join(dir, filename+".log")
  1279. err := os.WriteFile(filepath, []byte(data), 0600)
  1280. if err != nil {
  1281. log.Warnf("%v", err)
  1282. }
  1283. }
  1284. }