executor.go 43 KB

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