api.go 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784
  1. package api
  2. import (
  3. ctx "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "os"
  9. "path"
  10. "sort"
  11. "strings"
  12. "sync"
  13. "time"
  14. "connectrpc.com/connect"
  15. "google.golang.org/protobuf/encoding/protojson"
  16. apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1"
  17. apiv1connect "github.com/OliveTin/OliveTin/gen/olivetin/api/v1/apiv1connect"
  18. "github.com/google/uuid"
  19. log "github.com/sirupsen/logrus"
  20. acl "github.com/OliveTin/OliveTin/internal/acl"
  21. auth "github.com/OliveTin/OliveTin/internal/auth"
  22. authpublic "github.com/OliveTin/OliveTin/internal/auth/authpublic"
  23. config "github.com/OliveTin/OliveTin/internal/config"
  24. entities "github.com/OliveTin/OliveTin/internal/entities"
  25. executor "github.com/OliveTin/OliveTin/internal/executor"
  26. installationinfo "github.com/OliveTin/OliveTin/internal/installationinfo"
  27. "github.com/OliveTin/OliveTin/internal/tpl"
  28. connectproto "go.akshayshah.org/connectproto"
  29. )
  30. type oliveTinAPI struct {
  31. executor *executor.Executor
  32. cfg *config.Config
  33. // streamingClients is a set of currently connected clients.
  34. // The empty struct value models set semantics (keys only) and keeps add/remove O(1).
  35. // We use a map for efficient membership and deletion; ordering is not required.
  36. streamingClients map[*streamingClient]struct{}
  37. streamingClientsMutex sync.RWMutex
  38. }
  39. const maxEventStreamClients = 16
  40. var errEventStreamClientLimit = errors.New("too many concurrent event stream clients")
  41. // This is used to avoid race conditions when iterating over the connectedClients map.
  42. // and holds the lock for as minimal time as possible to avoid blocking the API for too long.
  43. func (api *oliveTinAPI) copyOfStreamingClients() []*streamingClient {
  44. api.streamingClientsMutex.RLock()
  45. defer api.streamingClientsMutex.RUnlock()
  46. clients := make([]*streamingClient, 0, len(api.streamingClients))
  47. for client := range api.streamingClients {
  48. clients = append(clients, client)
  49. }
  50. return clients
  51. }
  52. type streamingClient struct {
  53. channel chan *apiv1.EventStreamResponse
  54. AuthenticatedUser *authpublic.AuthenticatedUser
  55. heartbeatStop chan struct{}
  56. heartbeatDone chan struct{}
  57. heartbeatStopOnce sync.Once
  58. }
  59. func (c *streamingClient) stopHeartbeat() {
  60. if c.heartbeatStop == nil || c.heartbeatDone == nil {
  61. return
  62. }
  63. c.heartbeatStopOnce.Do(func() {
  64. close(c.heartbeatStop)
  65. })
  66. <-c.heartbeatDone
  67. }
  68. // trySendEventToClient sends msg to the client's channel. Returns false if the channel is full or closed.
  69. func (api *oliveTinAPI) trySendEventToClient(client *streamingClient, msg *apiv1.EventStreamResponse) bool {
  70. if client == nil || msg == nil {
  71. return false
  72. }
  73. sent := sendToStreamingClientChannel(client.channel, msg)
  74. if !sent {
  75. log.Warnf("EventStream: client channel is full or closed, removing client")
  76. }
  77. return sent
  78. }
  79. func sendToStreamingClientChannel(ch chan *apiv1.EventStreamResponse, msg *apiv1.EventStreamResponse) (sent bool) {
  80. defer func() {
  81. if recover() != nil {
  82. sent = false
  83. }
  84. }()
  85. select {
  86. case ch <- msg:
  87. return true
  88. default:
  89. return false
  90. }
  91. }
  92. func (api *oliveTinAPI) KillAction(ctx ctx.Context, req *connect.Request[apiv1.KillActionRequest]) (*connect.Response[apiv1.KillActionResponse], error) {
  93. ret := &apiv1.KillActionResponse{
  94. ExecutionTrackingId: req.Msg.ExecutionTrackingId,
  95. }
  96. var execReqLogEntry *executor.InternalLogEntry
  97. execReqLogEntry, ret.Found = api.executor.GetLog(req.Msg.ExecutionTrackingId)
  98. if !ret.Found {
  99. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found for tracking ID %s", req.Msg.ExecutionTrackingId))
  100. }
  101. if execReqLogEntry.Binding == nil {
  102. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("log entry has no binding for tracking ID %s", req.Msg.ExecutionTrackingId))
  103. }
  104. action := execReqLogEntry.Binding.Action
  105. if action == nil {
  106. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action not found for tracking ID %s", req.Msg.ExecutionTrackingId))
  107. }
  108. log.Warnf("Killing execution request by tracking ID: %v", req.Msg.ExecutionTrackingId)
  109. user := auth.UserFromApiCall(ctx, req, api.cfg)
  110. api.killActionByTrackingId(user, action, execReqLogEntry, ret)
  111. return connect.NewResponse(ret), nil
  112. }
  113. func (api *oliveTinAPI) killActionByTrackingId(user *authpublic.AuthenticatedUser, action *config.Action, execReqLogEntry *executor.InternalLogEntry, ret *apiv1.KillActionResponse) {
  114. if !acl.IsAllowedKill(api.cfg, user, action) {
  115. log.Warnf("Killing execution request not possible - user not allowed to kill this action: %v", execReqLogEntry.ExecutionTrackingID)
  116. ret.Killed = false
  117. return
  118. }
  119. err := api.executor.Kill(execReqLogEntry)
  120. if err != nil {
  121. log.Warnf("Killing execution request err: %v", err)
  122. ret.AlreadyCompleted = true
  123. ret.Killed = false
  124. } else {
  125. ret.Killed = true
  126. }
  127. }
  128. func (api *oliveTinAPI) StartAction(ctx ctx.Context, req *connect.Request[apiv1.StartActionRequest]) (*connect.Response[apiv1.StartActionResponse], error) {
  129. pair, err := api.findBindingByIDOrNotFound(req.Msg.BindingId)
  130. if err != nil {
  131. return nil, err
  132. }
  133. authenticatedUser := auth.UserFromApiCall(ctx, req, api.cfg)
  134. args := startActionArgumentsFromProto(req.Msg.Arguments)
  135. justification := resolveStartJustification(pair.Action, pair, req.Msg.Justification, args)
  136. if err := validateJustificationRequired(pair.Action, justification, authenticatedUser); err != nil {
  137. return nil, connectInvalidJustification(err)
  138. }
  139. execReq := executor.ExecutionRequest{
  140. Binding: pair,
  141. TrackingID: req.Msg.UniqueTrackingId,
  142. Arguments: args,
  143. Justification: justification,
  144. AuthenticatedUser: authenticatedUser,
  145. Cfg: api.cfg,
  146. }
  147. api.executor.ExecRequest(&execReq)
  148. return connect.NewResponse(&apiv1.StartActionResponse{
  149. ExecutionTrackingId: execReq.TrackingID,
  150. }), nil
  151. }
  152. func (api *oliveTinAPI) PasswordHash(ctx ctx.Context, req *connect.Request[apiv1.PasswordHashRequest]) (*connect.Response[apiv1.PasswordHashResponse], error) {
  153. hash, err := createHash(req.Msg.Password)
  154. if err != nil {
  155. if errors.Is(err, ErrArgon2Busy) {
  156. return nil, connect.NewError(connect.CodeResourceExhausted, err)
  157. }
  158. return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("error creating hash: %w", err))
  159. }
  160. ret := &apiv1.PasswordHashResponse{
  161. Hash: hash,
  162. }
  163. return connect.NewResponse(ret), nil
  164. }
  165. func (api *oliveTinAPI) cookieSecure(header http.Header) bool {
  166. useTLS := header.Get("X-Forwarded-Proto") == "https"
  167. return useTLS || api.cfg.Security.ForceSecureCookies
  168. }
  169. func (api *oliveTinAPI) applyLocalLoginResult(req *apiv1.LocalUserLoginRequest, response *connect.Response[apiv1.LocalUserLoginResponse], match bool, secure bool) {
  170. if match {
  171. user := api.cfg.FindUserByUsername(req.Username)
  172. if user != nil {
  173. sid := uuid.NewString()
  174. auth.RegisterUserSession(api.cfg, "local", sid, user.Username)
  175. log.WithFields(log.Fields{"username": user.Username}).Info("LocalUserLogin: Session created and registered")
  176. cookie := &http.Cookie{
  177. Name: "olivetin-sid-local",
  178. Value: sid,
  179. MaxAge: 31556952,
  180. HttpOnly: true,
  181. Path: "/",
  182. Secure: secure,
  183. SameSite: http.SameSiteLaxMode,
  184. }
  185. response.Header().Set("Set-Cookie", cookie.String())
  186. log.WithFields(log.Fields{"username": user.Username}).Info("LocalUserLogin: User logged in successfully.")
  187. } else {
  188. log.WithFields(log.Fields{"username": req.Username}).Warn("LocalUserLogin: Password matched but user lookup failed.")
  189. }
  190. } else {
  191. log.WithFields(log.Fields{"username": req.Username}).Warn("LocalUserLogin: User login failed.")
  192. }
  193. }
  194. func (api *oliveTinAPI) localUserLoginEarlyReject(req *connect.Request[apiv1.LocalUserLoginRequest]) *connect.Response[apiv1.LocalUserLoginResponse] {
  195. if !api.cfg.AuthLocalUsers.Enabled {
  196. return connect.NewResponse(&apiv1.LocalUserLoginResponse{Success: false})
  197. }
  198. if isLocalInteractiveLoginDisabledForUser(api.cfg, req.Msg.Username) {
  199. log.WithFields(log.Fields{"username": req.Msg.Username}).Debug("LocalUserLogin: interactive login disabled (no password configured)")
  200. return connect.NewResponse(&apiv1.LocalUserLoginResponse{Success: false})
  201. }
  202. return nil
  203. }
  204. func (api *oliveTinAPI) LocalUserLogin(ctx ctx.Context, req *connect.Request[apiv1.LocalUserLoginRequest]) (*connect.Response[apiv1.LocalUserLoginResponse], error) {
  205. if early := api.localUserLoginEarlyReject(req); early != nil {
  206. return early, nil
  207. }
  208. match, err := checkUserPassword(api.cfg, req.Msg.Username, req.Msg.Password)
  209. if err != nil {
  210. if errors.Is(err, ErrArgon2Busy) {
  211. return nil, connect.NewError(connect.CodeResourceExhausted, err)
  212. }
  213. return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("checking password: %w", err))
  214. }
  215. response := connect.NewResponse(&apiv1.LocalUserLoginResponse{Success: match})
  216. api.applyLocalLoginResult(req.Msg, response, match, api.cookieSecure(req.Header()))
  217. return response, nil
  218. }
  219. func (api *oliveTinAPI) startActionAndWaitRun(binding *executor.ActionBinding, args map[string]string, justification string, user *authpublic.AuthenticatedUser) (*executor.InternalLogEntry, bool) {
  220. execReq := executor.ExecutionRequest{
  221. Binding: binding,
  222. TrackingID: uuid.NewString(),
  223. Arguments: args,
  224. Justification: justification,
  225. AuthenticatedUser: user,
  226. Cfg: api.cfg,
  227. }
  228. wg, _ := api.executor.ExecRequest(&execReq)
  229. wg.Wait()
  230. return api.executor.GetLog(execReq.TrackingID)
  231. }
  232. func (api *oliveTinAPI) findBindingOrNotFound(actionId string) (*executor.ActionBinding, error) {
  233. binding := api.executor.FindBindingByID(actionId)
  234. if binding == nil || binding.Action == nil {
  235. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action with ID %s not found", actionId))
  236. }
  237. return binding, nil
  238. }
  239. func (api *oliveTinAPI) findBindingByIDOrNotFound(bindingId string) (*executor.ActionBinding, error) {
  240. return api.findBindingOrNotFound(bindingId)
  241. }
  242. func (api *oliveTinAPI) startActionAndWaitLogEntry(binding *executor.ActionBinding, args map[string]string, justification string, user *authpublic.AuthenticatedUser) (*apiv1.LogEntry, error) {
  243. internalLogEntry, ok := api.startActionAndWaitRun(binding, args, justification, user)
  244. if !ok {
  245. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found"))
  246. }
  247. return api.logEntryForAllowedViewer(internalLogEntry, user)
  248. }
  249. func (api *oliveTinAPI) logEntryForAllowedViewer(internalLogEntry *executor.InternalLogEntry, user *authpublic.AuthenticatedUser) (*apiv1.LogEntry, error) {
  250. if err := api.requireLogEntryAllowed(internalLogEntry, user); err != nil {
  251. return nil, err
  252. }
  253. return api.internalLogEntryToPb(internalLogEntry, user), nil
  254. }
  255. func (api *oliveTinAPI) StartActionAndWait(ctx ctx.Context, req *connect.Request[apiv1.StartActionAndWaitRequest]) (*connect.Response[apiv1.StartActionAndWaitResponse], error) {
  256. binding, err := api.findBindingOrNotFound(req.Msg.ActionId)
  257. if err != nil {
  258. return nil, err
  259. }
  260. user := auth.UserFromApiCall(ctx, req, api.cfg)
  261. args := startActionArgumentsFromProto(req.Msg.Arguments)
  262. justification := resolveStartJustification(binding.Action, binding, req.Msg.Justification, args)
  263. if err = validateJustificationRequired(binding.Action, justification, user); err != nil {
  264. return nil, connectInvalidJustification(err)
  265. }
  266. logEntry, err := api.startActionAndWaitLogEntry(binding, args, justification, user)
  267. if err != nil {
  268. return nil, err
  269. }
  270. return connect.NewResponse(&apiv1.StartActionAndWaitResponse{
  271. LogEntry: logEntry,
  272. }), nil
  273. }
  274. func (api *oliveTinAPI) StartActionByGet(ctx ctx.Context, req *connect.Request[apiv1.StartActionByGetRequest]) (*connect.Response[apiv1.StartActionByGetResponse], error) {
  275. binding := api.executor.FindBindingByID(req.Msg.ActionId)
  276. if binding == nil || binding.Action == nil {
  277. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action with ID %s not found", req.Msg.ActionId))
  278. }
  279. args := make(map[string]string)
  280. execReq := executor.ExecutionRequest{
  281. Binding: binding,
  282. TrackingID: uuid.NewString(),
  283. Arguments: args,
  284. AuthenticatedUser: auth.UserFromApiCall(ctx, req, api.cfg),
  285. Cfg: api.cfg,
  286. }
  287. _, uniqueTrackingId := api.executor.ExecRequest(&execReq)
  288. return connect.NewResponse(&apiv1.StartActionByGetResponse{
  289. ExecutionTrackingId: uniqueTrackingId,
  290. }), nil
  291. }
  292. func (api *oliveTinAPI) runBindingAndWait(binding *executor.ActionBinding, args map[string]string, user *authpublic.AuthenticatedUser) (*executor.InternalLogEntry, bool) {
  293. execReq := executor.ExecutionRequest{
  294. Binding: binding,
  295. TrackingID: uuid.NewString(),
  296. Arguments: args,
  297. AuthenticatedUser: user,
  298. Cfg: api.cfg,
  299. }
  300. wg, _ := api.executor.ExecRequest(&execReq)
  301. wg.Wait()
  302. return api.executor.GetLog(execReq.TrackingID)
  303. }
  304. func (api *oliveTinAPI) startActionByGetAndWaitLogEntry(binding *executor.ActionBinding, user *authpublic.AuthenticatedUser) (*apiv1.LogEntry, error) {
  305. internalLogEntry, ok := api.runBindingAndWait(binding, map[string]string{}, user)
  306. if !ok {
  307. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found"))
  308. }
  309. return api.logEntryForAllowedViewer(internalLogEntry, user)
  310. }
  311. func (api *oliveTinAPI) StartActionByGetAndWait(ctx ctx.Context, req *connect.Request[apiv1.StartActionByGetAndWaitRequest]) (*connect.Response[apiv1.StartActionByGetAndWaitResponse], error) {
  312. binding := api.executor.FindBindingByID(req.Msg.ActionId)
  313. if binding == nil || binding.Action == nil {
  314. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action with ID %s not found", req.Msg.ActionId))
  315. }
  316. user := auth.UserFromApiCall(ctx, req, api.cfg)
  317. logEntry, err := api.startActionByGetAndWaitLogEntry(binding, user)
  318. if err != nil {
  319. return nil, err
  320. }
  321. return connect.NewResponse(&apiv1.StartActionByGetAndWaitResponse{
  322. LogEntry: logEntry,
  323. }), nil
  324. }
  325. func calculateRateLimitExpires(api *oliveTinAPI, logEntry *executor.InternalLogEntry) string {
  326. if logEntry.Binding == nil || logEntry.Binding.Action == nil {
  327. return ""
  328. }
  329. expiryUnix := api.executor.GetTimeUntilAvailable(logEntry.Binding)
  330. if expiryUnix <= 0 {
  331. return ""
  332. }
  333. return time.Unix(expiryUnix, 0).Format("2006-01-02 15:04:05")
  334. }
  335. func (api *oliveTinAPI) internalLogEntryToPb(logEntry *executor.InternalLogEntry, authenticatedUser *authpublic.AuthenticatedUser) *apiv1.LogEntry {
  336. pble := &apiv1.LogEntry{
  337. ActionTitle: logEntry.ActionTitle,
  338. ActionIcon: logEntry.ActionIcon,
  339. DatetimeStarted: logEntry.DatetimeStarted.Format("2006-01-02 15:04:05"),
  340. DatetimeFinished: logEntry.DatetimeFinished.Format("2006-01-02 15:04:05"),
  341. DatetimeIndex: logEntry.Index,
  342. Output: logEntry.Output,
  343. TimedOut: logEntry.TimedOut,
  344. Blocked: logEntry.Blocked,
  345. Queued: logEntry.Queued,
  346. QueuedForGroup: logEntry.QueuedForGroup,
  347. ExitCode: logEntry.ExitCode,
  348. Tags: logEntry.Tags,
  349. ExecutionTrackingId: logEntry.ExecutionTrackingID,
  350. ExecutionStarted: logEntry.ExecutionStarted,
  351. ExecutionFinished: logEntry.ExecutionFinished,
  352. User: logEntry.Username,
  353. BindingId: logEntry.GetBindingId(),
  354. DatetimeRateLimitExpires: calculateRateLimitExpires(api, logEntry),
  355. Justification: logEntry.Justification,
  356. Arguments: logEntryArgumentsToProto(logEntry.Arguments),
  357. }
  358. if !pble.ExecutionFinished && logEntry.Binding != nil && logEntry.Binding.Action != nil {
  359. pble.CanKill = acl.IsAllowedKill(api.cfg, authenticatedUser, logEntry.Binding.Action)
  360. }
  361. return pble
  362. }
  363. func getExecutionStatusByTrackingID(api *oliveTinAPI, executionTrackingId string) *executor.InternalLogEntry {
  364. logEntry, ok := api.executor.GetLog(executionTrackingId)
  365. if !ok {
  366. return nil
  367. }
  368. return logEntry
  369. }
  370. // This is the actual action ID, not the binding ID.
  371. func getMostRecentExecutionStatusByActionId(api *oliveTinAPI, actionId string) *executor.InternalLogEntry {
  372. var ile *executor.InternalLogEntry
  373. binding := api.executor.FindBindingByID(actionId)
  374. if binding == nil {
  375. return nil
  376. }
  377. logs := api.executor.GetLogsByBindingId(binding.ID)
  378. if len(logs) == 0 {
  379. return nil
  380. }
  381. if len(logs) == 0 {
  382. return nil
  383. } else {
  384. // Get last log entry
  385. ile = logs[len(logs)-1]
  386. }
  387. return ile
  388. }
  389. func (api *oliveTinAPI) resolveExecutionStatusForView(msg *apiv1.ExecutionStatusRequest, user *authpublic.AuthenticatedUser) (*executor.InternalLogEntry, error) {
  390. ile := api.getExecutionStatusByRequest(msg)
  391. if ile == nil {
  392. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found for tracking ID %s or action ID %s", msg.ExecutionTrackingId, msg.ActionId))
  393. }
  394. if !isValidLogEntry(ile) || !api.isLogEntryAllowed(ile, user) {
  395. return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied to view this execution"))
  396. }
  397. return ile, nil
  398. }
  399. func (api *oliveTinAPI) getExecutionStatusByRequest(msg *apiv1.ExecutionStatusRequest) *executor.InternalLogEntry {
  400. if msg.ExecutionTrackingId != "" {
  401. return getExecutionStatusByTrackingID(api, msg.ExecutionTrackingId)
  402. }
  403. return getMostRecentExecutionStatusByActionId(api, msg.ActionId)
  404. }
  405. func dashboardNavigationTargetsToPb(targets []executor.DashboardNavigationTarget) []*apiv1.DashboardNavigationTarget {
  406. if len(targets) == 0 {
  407. return nil
  408. }
  409. result := make([]*apiv1.DashboardNavigationTarget, 0, len(targets))
  410. for _, target := range targets {
  411. result = append(result, &apiv1.DashboardNavigationTarget{
  412. Title: target.Title,
  413. EntityType: target.EntityType,
  414. EntityKey: target.EntityKey,
  415. Path: target.Path,
  416. })
  417. }
  418. return result
  419. }
  420. func (api *oliveTinAPI) executionStatusBackToDashboards(ile *executor.InternalLogEntry) []*apiv1.DashboardNavigationTarget {
  421. if ile == nil || ile.Binding == nil {
  422. return nil
  423. }
  424. return dashboardNavigationTargetsToPb(ile.Binding.OnDashboards)
  425. }
  426. func (api *oliveTinAPI) ExecutionStatus(ctx ctx.Context, req *connect.Request[apiv1.ExecutionStatusRequest]) (*connect.Response[apiv1.ExecutionStatusResponse], error) {
  427. user := auth.UserFromApiCall(ctx, req, api.cfg)
  428. if err := api.checkDashboardAccess(user); err != nil {
  429. return nil, err
  430. }
  431. ile, err := api.resolveExecutionStatusForView(req.Msg, user)
  432. if err != nil {
  433. return nil, err
  434. }
  435. res := &apiv1.ExecutionStatusResponse{
  436. LogEntry: api.internalLogEntryToPb(ile, user),
  437. BackToDashboards: api.executionStatusBackToDashboards(ile),
  438. }
  439. return connect.NewResponse(res), nil
  440. }
  441. func (api *oliveTinAPI) Logout(ctx ctx.Context, req *connect.Request[apiv1.LogoutRequest]) (*connect.Response[apiv1.LogoutResponse], error) {
  442. user := auth.UserFromApiCall(ctx, req, api.cfg)
  443. auth.RevokeSessionForProvider(api.cfg, user.Provider, user.SID)
  444. log.WithFields(log.Fields{
  445. "username": user.Username,
  446. "provider": user.Provider,
  447. }).Info("Logout: User logged out")
  448. response := connect.NewResponse(&apiv1.LogoutResponse{})
  449. secure := api.cookieSecure(req.Header())
  450. // Clear the local authentication cookie by setting it to expire
  451. localCookie := &http.Cookie{
  452. Name: "olivetin-sid-local",
  453. Value: "",
  454. MaxAge: -1, // This tells the browser to delete the cookie
  455. HttpOnly: true,
  456. Path: "/",
  457. Secure: secure,
  458. SameSite: http.SameSiteLaxMode,
  459. }
  460. response.Header().Set("Set-Cookie", localCookie.String())
  461. // Clear the OAuth2 authentication cookie by setting it to expire
  462. oauth2Cookie := &http.Cookie{
  463. Name: "olivetin-sid-oauth",
  464. Value: "",
  465. MaxAge: -1, // This tells the browser to delete the cookie
  466. HttpOnly: true,
  467. Path: "/",
  468. Secure: secure,
  469. SameSite: http.SameSiteLaxMode,
  470. }
  471. response.Header().Add("Set-Cookie", oauth2Cookie.String())
  472. return response, nil
  473. }
  474. func (api *oliveTinAPI) GetActionBinding(ctx ctx.Context, req *connect.Request[apiv1.GetActionBindingRequest]) (*connect.Response[apiv1.GetActionBindingResponse], error) {
  475. user := auth.UserFromApiCall(ctx, req, api.cfg)
  476. if err := api.checkDashboardAccess(user); err != nil {
  477. return nil, err
  478. }
  479. resp, err := api.getActionBindingResponse(user, req.Msg.BindingId)
  480. if err != nil {
  481. return nil, err
  482. }
  483. return connect.NewResponse(resp), nil
  484. }
  485. func (api *oliveTinAPI) getActionBindingResponse(user *authpublic.AuthenticatedUser, bindingId string) (*apiv1.GetActionBindingResponse, error) {
  486. binding := api.executor.FindBindingByID(bindingId)
  487. if binding == nil || binding.Action == nil {
  488. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action with ID %s not found", bindingId))
  489. }
  490. if !api.userCanViewAction(user, binding.Action) {
  491. return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
  492. }
  493. return &apiv1.GetActionBindingResponse{
  494. Action: buildAction(binding, api.createDashboardRenderRequest(user, "", "")),
  495. BackToDashboards: dashboardNavigationTargetsToPb(binding.OnDashboards),
  496. }, nil
  497. }
  498. func (api *oliveTinAPI) userCanViewAction(user *authpublic.AuthenticatedUser, action *config.Action) bool {
  499. if user == nil {
  500. return true
  501. }
  502. return acl.IsAllowedView(api.cfg, user, action)
  503. }
  504. func (api *oliveTinAPI) GetDashboard(ctx ctx.Context, req *connect.Request[apiv1.GetDashboardRequest]) (*connect.Response[apiv1.GetDashboardResponse], error) {
  505. user := auth.UserFromApiCall(ctx, req, api.cfg)
  506. if err := api.checkDashboardAccess(user); err != nil {
  507. return nil, err
  508. }
  509. entityType := ""
  510. entityKey := ""
  511. if req.Msg != nil {
  512. entityType = req.Msg.EntityType
  513. entityKey = req.Msg.EntityKey
  514. }
  515. dashboardRenderRequest := api.createDashboardRenderRequest(user, entityType, entityKey)
  516. if api.isDefaultDashboard(req.Msg.Title) {
  517. return api.buildDefaultDashboardResponse(dashboardRenderRequest)
  518. }
  519. return api.buildCustomDashboardResponse(dashboardRenderRequest, req.Msg.Title)
  520. }
  521. func (api *oliveTinAPI) checkDashboardAccess(user *authpublic.AuthenticatedUser) error {
  522. if user.IsGuest() && api.cfg.AuthRequireGuestsToLogin {
  523. return connect.NewError(connect.CodePermissionDenied, fmt.Errorf("guests are not allowed to access the dashboard"))
  524. }
  525. return nil
  526. }
  527. func (api *oliveTinAPI) createDashboardRenderRequest(user *authpublic.AuthenticatedUser, entityType, entityKey string) *DashboardRenderRequest {
  528. rr := &DashboardRenderRequest{
  529. AuthenticatedUser: user,
  530. cfg: api.cfg,
  531. ex: api.executor,
  532. EntityType: entityType,
  533. EntityKey: entityKey,
  534. }
  535. populateActiveBindingStates(rr)
  536. return rr
  537. }
  538. func (api *oliveTinAPI) isDefaultDashboard(title string) bool {
  539. return title == "default" || title == "" || title == "Actions"
  540. }
  541. func (api *oliveTinAPI) buildDefaultDashboardResponse(rr *DashboardRenderRequest) (*connect.Response[apiv1.GetDashboardResponse], error) {
  542. db := buildDefaultDashboard(rr)
  543. res := &apiv1.GetDashboardResponse{
  544. Dashboard: db,
  545. }
  546. return connect.NewResponse(res), nil
  547. }
  548. func (api *oliveTinAPI) buildCustomDashboardResponse(rr *DashboardRenderRequest, title string) (*connect.Response[apiv1.GetDashboardResponse], error) {
  549. res := &apiv1.GetDashboardResponse{
  550. Dashboard: renderDashboard(rr, title),
  551. }
  552. return connect.NewResponse(res), nil
  553. }
  554. func resolveLogsPageSize(requestPageSize, defaultPageSize int64) int64 {
  555. if requestPageSize == 0 {
  556. return defaultPageSize
  557. }
  558. if requestPageSize < 10 {
  559. return 10
  560. }
  561. if requestPageSize > 100 {
  562. return 100
  563. }
  564. return requestPageSize
  565. }
  566. func (api *oliveTinAPI) GetLogs(ctx ctx.Context, req *connect.Request[apiv1.GetLogsRequest]) (*connect.Response[apiv1.GetLogsResponse], error) {
  567. user := auth.UserFromApiCall(ctx, req, api.cfg)
  568. if err := api.checkDashboardAccess(user); err != nil {
  569. return nil, err
  570. }
  571. pageSize := resolveLogsPageSize(req.Msg.GetPageSize(), api.cfg.LogHistoryPageSize)
  572. logEntries, paging, err := api.executor.GetLogTrackingIdsACL(api.cfg, user, req.Msg.StartOffset, pageSize, req.Msg.DateFilter, req.Msg.GetFilter())
  573. if err != nil {
  574. return nil, connect.NewError(connect.CodeInvalidArgument, err)
  575. }
  576. ret := &apiv1.GetLogsResponse{}
  577. for _, le := range logEntries {
  578. ret.Logs = append(ret.Logs, api.internalLogEntryToPb(le, user))
  579. }
  580. ret.CountRemaining = paging.CountRemaining
  581. ret.PageSize = paging.PageSize
  582. ret.TotalCount = paging.TotalCount
  583. ret.StartOffset = paging.StartOffset
  584. return connect.NewResponse(ret), nil
  585. }
  586. // isValidLogEntry checks if a log entry has all required fields populated.
  587. func isValidLogEntry(e *executor.InternalLogEntry) bool {
  588. return e != nil && e.Binding != nil && e.Binding.Action != nil
  589. }
  590. // isLogEntryAllowed checks if a log entry is allowed to be viewed by the user.
  591. func (api *oliveTinAPI) isLogEntryAllowed(e *executor.InternalLogEntry, user *authpublic.AuthenticatedUser) bool {
  592. if user == nil || !isValidLogEntry(e) {
  593. return false
  594. }
  595. return acl.IsAllowedLogs(api.cfg, user, e.Binding.Action)
  596. }
  597. func (api *oliveTinAPI) requireLogEntryAllowed(entry *executor.InternalLogEntry, user *authpublic.AuthenticatedUser) error {
  598. if api.isLogEntryAllowed(entry, user) {
  599. return nil
  600. }
  601. return connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied to view this execution"))
  602. }
  603. // mayViewExecutionEvent returns whether the user is allowed to receive this execution event (for EventStream ACL).
  604. func (api *oliveTinAPI) mayViewExecutionEvent(entry *executor.InternalLogEntry, user *authpublic.AuthenticatedUser) bool {
  605. if user == nil {
  606. return false
  607. }
  608. return isValidLogEntry(entry) && api.isLogEntryAllowed(entry, user)
  609. }
  610. // buildEmptyPageResponse creates a response for an empty page.
  611. func buildEmptyPageResponse(page pageInfo) *apiv1.GetActionLogsResponse {
  612. return &apiv1.GetActionLogsResponse{
  613. CountRemaining: 0,
  614. PageSize: page.size,
  615. TotalCount: page.total,
  616. StartOffset: page.start,
  617. }
  618. }
  619. // calculateReversedIndices computes the reversed indices for newest-first pagination.
  620. func calculateReversedIndices(page pageInfo, filteredLen int) (int64, int64) {
  621. startIdx := page.total - page.end
  622. endIdx := page.total - page.start
  623. if startIdx < 0 {
  624. startIdx = 0
  625. }
  626. if endIdx > int64(filteredLen) {
  627. endIdx = int64(filteredLen)
  628. }
  629. return startIdx, endIdx
  630. }
  631. // buildActionLogsResponse builds the response with paginated log entries (newest first).
  632. func (api *oliveTinAPI) buildActionLogsResponse(filtered []*executor.InternalLogEntry, page pageInfo, user *authpublic.AuthenticatedUser) *apiv1.GetActionLogsResponse {
  633. startIdx, endIdx := calculateReversedIndices(page, len(filtered))
  634. ret := &apiv1.GetActionLogsResponse{}
  635. chunk := filtered[int(startIdx):int(endIdx)]
  636. for i := len(chunk) - 1; i >= 0; i-- {
  637. ret.Logs = append(ret.Logs, api.internalLogEntryToPb(chunk[i], user))
  638. }
  639. ret.CountRemaining = page.start
  640. ret.PageSize = page.size
  641. ret.TotalCount = page.total
  642. ret.StartOffset = page.start
  643. return ret
  644. }
  645. func (api *oliveTinAPI) GetActionLogs(ctx ctx.Context, req *connect.Request[apiv1.GetActionLogsRequest]) (*connect.Response[apiv1.GetActionLogsResponse], error) {
  646. user := auth.UserFromApiCall(ctx, req, api.cfg)
  647. if err := api.checkDashboardAccess(user); err != nil {
  648. return nil, err
  649. }
  650. filtered := api.filterLogsByACL(api.executor.GetLogsByBindingId(req.Msg.ActionId), user)
  651. page := paginate(int64(len(filtered)), api.cfg.LogHistoryPageSize, req.Msg.StartOffset)
  652. if page.empty {
  653. return connect.NewResponse(buildEmptyPageResponse(page)), nil
  654. }
  655. return connect.NewResponse(api.buildActionLogsResponse(filtered, page, user)), nil
  656. }
  657. func (api *oliveTinAPI) filterLogsByACL(entries []*executor.InternalLogEntry, user *authpublic.AuthenticatedUser) []*executor.InternalLogEntry {
  658. filtered := make([]*executor.InternalLogEntry, 0, len(entries))
  659. for _, e := range entries {
  660. if !isValidLogEntry(e) {
  661. continue
  662. }
  663. if api.isLogEntryAllowed(e, user) {
  664. filtered = append(filtered, e)
  665. }
  666. }
  667. return filtered
  668. }
  669. type pageInfo struct {
  670. total int64
  671. size int64
  672. start int64
  673. end int64
  674. empty bool
  675. }
  676. func paginate(total int64, size int64, start int64) pageInfo {
  677. if start < 0 {
  678. start = 0
  679. }
  680. if start >= total {
  681. return pageInfo{total: total, size: size, start: start, end: start, empty: true}
  682. }
  683. end := min(start+size, total)
  684. return pageInfo{total: total, size: size, start: start, end: end, empty: false}
  685. }
  686. /*
  687. This function is ONLY a helper for the UI - the arguments are validated properly
  688. on the StartAction -> Executor chain. This is here basically to provide helpful
  689. error messages more quickly before starting the action.
  690. It uses the same validation logic as the executor, including mangling argument
  691. values (e.g., datetime formatting, checkbox title-to-value conversion).
  692. */
  693. func (api *oliveTinAPI) argumentNotFoundForValidation(msg *apiv1.ValidateArgumentTypeRequest) bool {
  694. if msg.BindingId == "" || msg.ArgumentName == "" {
  695. return false
  696. }
  697. arg, _ := api.findArgumentForValidation(msg.BindingId, msg.ArgumentName)
  698. return arg == nil
  699. }
  700. func (api *oliveTinAPI) validateArgumentTypeBindingAccess(user *authpublic.AuthenticatedUser, msg *apiv1.ValidateArgumentTypeRequest) error {
  701. if msg == nil || msg.BindingId == "" {
  702. return nil
  703. }
  704. return api.errUnlessUserMayValidateArgumentTypeForBinding(user, msg.BindingId)
  705. }
  706. func (api *oliveTinAPI) errUnlessUserMayValidateArgumentTypeForBinding(user *authpublic.AuthenticatedUser, bindingID string) error {
  707. binding := api.executor.FindBindingByID(bindingID)
  708. if binding == nil || binding.Action == nil {
  709. return connect.NewError(connect.CodeNotFound, fmt.Errorf("action or argument not found for binding ID %s", bindingID))
  710. }
  711. if !api.userCanViewAction(user, binding.Action) {
  712. return connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
  713. }
  714. return nil
  715. }
  716. func (api *oliveTinAPI) ValidateArgumentType(ctx ctx.Context, req *connect.Request[apiv1.ValidateArgumentTypeRequest]) (*connect.Response[apiv1.ValidateArgumentTypeResponse], error) {
  717. user := auth.UserFromApiCall(ctx, req, api.cfg)
  718. if err := api.checkDashboardAccess(user); err != nil {
  719. return nil, err
  720. }
  721. if err := api.validateArgumentTypeBindingAccess(user, req.Msg); err != nil {
  722. return nil, err
  723. }
  724. if api.argumentNotFoundForValidation(req.Msg) {
  725. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action or argument not found for binding ID %s", req.Msg.BindingId))
  726. }
  727. return api.validateArgumentTypeConnectResponse(req.Msg)
  728. }
  729. func (api *oliveTinAPI) validateArgumentTypeConnectResponse(msg *apiv1.ValidateArgumentTypeRequest) (*connect.Response[apiv1.ValidateArgumentTypeResponse], error) {
  730. err := api.validateArgumentTypeInternal(msg)
  731. desc := ""
  732. if err != nil {
  733. desc = err.Error()
  734. }
  735. return connect.NewResponse(&apiv1.ValidateArgumentTypeResponse{
  736. Valid: err == nil,
  737. Description: desc,
  738. }), nil
  739. }
  740. func (api *oliveTinAPI) validateArgumentTypeInternal(msg *apiv1.ValidateArgumentTypeRequest) error {
  741. if msg.BindingId == "" || msg.ArgumentName == "" {
  742. return executor.TypeSafetyCheck("", msg.Value, msg.Type)
  743. }
  744. arg, action := api.findArgumentForValidation(msg.BindingId, msg.ArgumentName)
  745. if arg == nil {
  746. return fmt.Errorf("argument not found")
  747. }
  748. return executor.ValidateArgument(arg, msg.Value, action)
  749. }
  750. func (api *oliveTinAPI) findArgumentForValidation(bindingId string, argumentName string) (*config.ActionArgument, *config.Action) {
  751. binding := api.executor.FindBindingByID(bindingId)
  752. if binding == nil || binding.Action == nil {
  753. return nil, nil
  754. }
  755. arg := api.findArgumentByName(binding.Action, argumentName)
  756. return arg, binding.Action
  757. }
  758. func (api *oliveTinAPI) findArgumentByName(action *config.Action, name string) *config.ActionArgument {
  759. for i := range action.Arguments {
  760. if action.Arguments[i].Name == name {
  761. return &action.Arguments[i]
  762. }
  763. }
  764. return nil
  765. }
  766. func (api *oliveTinAPI) WhoAmI(ctx ctx.Context, req *connect.Request[apiv1.WhoAmIRequest]) (*connect.Response[apiv1.WhoAmIResponse], error) {
  767. user := auth.UserFromApiCall(ctx, req, api.cfg)
  768. if err := api.checkDashboardAccess(user); err != nil {
  769. return nil, err
  770. }
  771. res := &apiv1.WhoAmIResponse{
  772. AuthenticatedUser: user.Username,
  773. Usergroup: user.UsergroupLine,
  774. Provider: user.Provider,
  775. Sid: user.SID,
  776. Acls: user.Acls,
  777. }
  778. return connect.NewResponse(res), nil
  779. }
  780. func (api *oliveTinAPI) ServerDiagnostics(ctx ctx.Context, req *connect.Request[apiv1.ServerDiagnosticsRequest]) (*connect.Response[apiv1.ServerDiagnosticsResponse], error) {
  781. user := auth.UserFromApiCall(ctx, req, api.cfg)
  782. redactVersion := !user.EffectivePolicy.ShowVersionNumber
  783. diagnostics := installationinfo.GetServerDiagnostics(redactVersion)
  784. if !api.cfg.InsecureAllowDumpServerDiagnostics {
  785. log.Info(diagnostics)
  786. diagnostics = "Your Server Diagnostics have been logged to OliveTin logs.\n\nIf you are in a safe network, you can temporarily set `insecureAllowDumpServerDiagnostics: true` in your config.yaml, restart OliveTin, and refresh this page - it will put the output directly in the browser."
  787. }
  788. ret := &apiv1.ServerDiagnosticsResponse{
  789. Alert: diagnostics,
  790. }
  791. return connect.NewResponse(ret), nil
  792. }
  793. func (api *oliveTinAPI) DumpVars(ctx ctx.Context, req *connect.Request[apiv1.DumpVarsRequest]) (*connect.Response[apiv1.DumpVarsResponse], error) {
  794. res := &apiv1.DumpVarsResponse{}
  795. if !api.cfg.InsecureAllowDumpVars {
  796. res.Alert = "Dumping variables is not allowed by default because it is insecure."
  797. return connect.NewResponse(res), nil
  798. }
  799. jsonstring, err := json.MarshalIndent(tpl.GetNewGeneralTemplateContext(), "", " ")
  800. if err != nil {
  801. log.WithError(err).Error("DumpVars: failed to marshal template context from GetNewGeneralTemplateContext")
  802. return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("dump vars: marshal template context: %w", err))
  803. }
  804. fmt.Printf("%s", jsonstring)
  805. res.Alert = "Dumping variables has been enabled in the configuration. Please set InsecureAllowDumpVars = false again after you don't need it anymore"
  806. return connect.NewResponse(res), nil
  807. }
  808. func debugBindingActionTitle(binding *executor.ActionBinding) string {
  809. if binding == nil || binding.Action == nil {
  810. return ""
  811. }
  812. return binding.Action.Title
  813. }
  814. func (api *oliveTinAPI) DumpPublicIdActionMap(ctx ctx.Context, req *connect.Request[apiv1.DumpPublicIdActionMapRequest]) (*connect.Response[apiv1.DumpPublicIdActionMapResponse], error) {
  815. res := &apiv1.DumpPublicIdActionMapResponse{}
  816. res.Contents = make(map[string]*apiv1.DebugBinding)
  817. if !api.cfg.InsecureAllowDumpActionMap {
  818. res.Alert = "Dumping Public IDs is disallowed."
  819. return connect.NewResponse(res), nil
  820. }
  821. api.executor.MapActionBindingsLock.RLock()
  822. for k, v := range api.executor.MapActionBindings {
  823. res.Contents[k] = &apiv1.DebugBinding{
  824. ActionTitle: debugBindingActionTitle(v),
  825. }
  826. }
  827. api.executor.MapActionBindingsLock.RUnlock()
  828. res.Alert = "Dumping variables has been enabled in the configuration. Please set InsecureAllowDumpActionMap = false again after you don't need it anymore"
  829. return connect.NewResponse(res), nil
  830. }
  831. func (api *oliveTinAPI) GetReadyz(ctx ctx.Context, req *connect.Request[apiv1.GetReadyzRequest]) (*connect.Response[apiv1.GetReadyzResponse], error) {
  832. res := &apiv1.GetReadyzResponse{
  833. Status: "OK",
  834. }
  835. return connect.NewResponse(res), nil
  836. }
  837. func (api *oliveTinAPI) EventStream(ctx ctx.Context, req *connect.Request[apiv1.EventStreamRequest], srv *connect.ServerStream[apiv1.EventStreamResponse]) error {
  838. log.Debugf("EventStream: %v", req.Msg)
  839. // Set X-Accel-Buffering header to disable nginx buffering for this stream
  840. // https://github.com/OliveTin/OliveTin/issues/765
  841. srv.ResponseHeader().Set("X-Accel-Buffering", "no")
  842. user := auth.UserFromApiCall(ctx, req, api.cfg)
  843. if err := api.checkDashboardAccess(user); err != nil {
  844. return err
  845. }
  846. client := &streamingClient{
  847. channel: make(chan *apiv1.EventStreamResponse, 10), // Buffered channel to hold Events
  848. AuthenticatedUser: user,
  849. heartbeatStop: make(chan struct{}),
  850. heartbeatDone: make(chan struct{}),
  851. }
  852. if err := api.registerStreamingClient(client); err != nil {
  853. return connect.NewError(connect.CodeResourceExhausted, err)
  854. }
  855. log.WithFields(log.Fields{
  856. "authenticatedUser": user.Username,
  857. }).Debugf("EventStream: client connected")
  858. go api.sendEventStreamHeartbeats(client)
  859. // loop over client channel and send events to connectedClient
  860. for msg := range client.channel {
  861. log.Debugf("Sending event to client: %v", msg)
  862. if err := srv.Send(msg); err != nil {
  863. log.Errorf("Error sending event to client: %v", err)
  864. // Remove disconnected client from the list
  865. api.removeClient(client)
  866. break
  867. }
  868. }
  869. log.Infof("EventStream: client disconnected")
  870. return nil
  871. }
  872. func (api *oliveTinAPI) registerStreamingClient(client *streamingClient) error {
  873. api.streamingClientsMutex.Lock()
  874. defer api.streamingClientsMutex.Unlock()
  875. if len(api.streamingClients) >= maxEventStreamClients {
  876. log.WithFields(log.Fields{
  877. "limit": maxEventStreamClients,
  878. }).Warn("EventStream: rejecting client; concurrent client limit reached")
  879. return errEventStreamClientLimit
  880. }
  881. api.streamingClients[client] = struct{}{}
  882. return nil
  883. }
  884. func (api *oliveTinAPI) sendEventStreamHeartbeats(client *streamingClient) {
  885. defer close(client.heartbeatDone)
  886. if !api.sendEventStreamHeartbeat(client) {
  887. go api.removeClient(client)
  888. return
  889. }
  890. ticker := time.NewTicker(10 * time.Second)
  891. defer ticker.Stop()
  892. api.runEventStreamHeartbeatLoop(client, ticker)
  893. }
  894. func (api *oliveTinAPI) runEventStreamHeartbeatLoop(client *streamingClient, ticker *time.Ticker) {
  895. for {
  896. if api.waitEventStreamHeartbeatOrDone(client.heartbeatStop, ticker) {
  897. return
  898. }
  899. if !api.sendEventStreamHeartbeat(client) {
  900. go api.removeClient(client)
  901. return
  902. }
  903. }
  904. }
  905. func (api *oliveTinAPI) waitEventStreamHeartbeatOrDone(done <-chan struct{}, ticker *time.Ticker) bool {
  906. select {
  907. case <-done:
  908. return true
  909. case <-ticker.C:
  910. return false
  911. }
  912. }
  913. func (api *oliveTinAPI) sendEventStreamHeartbeat(client *streamingClient) bool {
  914. msg := &apiv1.EventStreamResponse{
  915. Event: &apiv1.EventStreamResponse_Heartbeat{
  916. Heartbeat: &apiv1.EventHeartbeat{},
  917. },
  918. }
  919. return api.trySendEventToClient(client, msg)
  920. }
  921. func (api *oliveTinAPI) removeClient(clientToRemove *streamingClient) {
  922. if clientToRemove == nil {
  923. return
  924. }
  925. api.streamingClientsMutex.Lock()
  926. if _, exists := api.streamingClients[clientToRemove]; !exists {
  927. api.streamingClientsMutex.Unlock()
  928. return
  929. }
  930. delete(api.streamingClients, clientToRemove)
  931. api.streamingClientsMutex.Unlock()
  932. clientToRemove.stopHeartbeat()
  933. close(clientToRemove.channel)
  934. }
  935. func (api *oliveTinAPI) OnActionMapRebuilt() {
  936. toRemove := []*streamingClient{}
  937. for _, client := range api.copyOfStreamingClients() {
  938. msg := &apiv1.EventStreamResponse{
  939. Event: &apiv1.EventStreamResponse_ConfigChanged{
  940. ConfigChanged: &apiv1.EventConfigChanged{},
  941. },
  942. }
  943. if !api.trySendEventToClient(client, msg) {
  944. toRemove = append(toRemove, client)
  945. }
  946. }
  947. for _, client := range toRemove {
  948. api.removeClient(client)
  949. }
  950. }
  951. func (api *oliveTinAPI) OnExecutionStarted(ex *executor.InternalLogEntry) {
  952. toRemove := []*streamingClient{}
  953. for _, client := range api.copyOfStreamingClients() {
  954. api.maybeSendExecutionStarted(client, ex, &toRemove)
  955. }
  956. for _, client := range toRemove {
  957. api.removeClient(client)
  958. }
  959. }
  960. func (api *oliveTinAPI) maybeSendExecutionStarted(client *streamingClient, ex *executor.InternalLogEntry, toRemove *[]*streamingClient) {
  961. if client == nil {
  962. return
  963. }
  964. if !api.mayViewExecutionEvent(ex, client.AuthenticatedUser) {
  965. return
  966. }
  967. msg := &apiv1.EventStreamResponse{
  968. Event: &apiv1.EventStreamResponse_ExecutionStarted{
  969. ExecutionStarted: &apiv1.EventExecutionStarted{
  970. LogEntry: api.internalLogEntryToPb(ex, client.AuthenticatedUser),
  971. },
  972. },
  973. }
  974. if !api.trySendEventToClient(client, msg) {
  975. *toRemove = append(*toRemove, client)
  976. }
  977. }
  978. func (api *oliveTinAPI) OnExecutionFinished(ile *executor.InternalLogEntry) {
  979. toRemove := []*streamingClient{}
  980. for _, client := range api.copyOfStreamingClients() {
  981. api.maybeSendExecutionFinished(client, ile, &toRemove)
  982. }
  983. for _, client := range toRemove {
  984. api.removeClient(client)
  985. }
  986. }
  987. func (api *oliveTinAPI) maybeSendExecutionFinished(client *streamingClient, ile *executor.InternalLogEntry, toRemove *[]*streamingClient) {
  988. if client == nil {
  989. return
  990. }
  991. if !api.mayViewExecutionEvent(ile, client.AuthenticatedUser) {
  992. return
  993. }
  994. msg := &apiv1.EventStreamResponse{
  995. Event: &apiv1.EventStreamResponse_ExecutionFinished{
  996. ExecutionFinished: &apiv1.EventExecutionFinished{
  997. LogEntry: api.internalLogEntryToPb(ile, client.AuthenticatedUser),
  998. },
  999. },
  1000. }
  1001. if !api.trySendEventToClient(client, msg) {
  1002. *toRemove = append(*toRemove, client)
  1003. }
  1004. }
  1005. func (api *oliveTinAPI) GetDiagnostics(ctx ctx.Context, req *connect.Request[apiv1.GetDiagnosticsRequest]) (*connect.Response[apiv1.GetDiagnosticsResponse], error) {
  1006. user := auth.UserFromApiCall(ctx, req, api.cfg)
  1007. if err := api.checkDashboardAccess(user); err != nil {
  1008. return nil, err
  1009. }
  1010. if !user.EffectivePolicy.ShowDiagnostics {
  1011. return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("diagnostics are not available for your account"))
  1012. }
  1013. res := &apiv1.GetDiagnosticsResponse{
  1014. SshFoundKey: installationinfo.Runtime.SshFoundKey,
  1015. SshFoundConfig: installationinfo.Runtime.SshFoundConfig,
  1016. ConfigIssues: api.buildConfigIssuesForUser(user),
  1017. }
  1018. return connect.NewResponse(res), nil
  1019. }
  1020. func (api *oliveTinAPI) Init(ctx ctx.Context, req *connect.Request[apiv1.InitRequest]) (*connect.Response[apiv1.InitResponse], error) {
  1021. user := auth.UserFromApiCall(ctx, req, api.cfg)
  1022. loginRequired := user.IsGuest() && api.cfg.AuthRequireGuestsToLogin
  1023. showVersion := user.EffectivePolicy.ShowVersionNumber
  1024. currentVersion := ""
  1025. availableVersion := ""
  1026. if showVersion {
  1027. currentVersion = installationinfo.Build.Version
  1028. availableVersion = installationinfo.Runtime.AvailableVersion
  1029. }
  1030. rootDashboardEntries := api.buildRootDashboardEntries(user, api.cfg.Dashboards)
  1031. res := &apiv1.InitResponse{
  1032. ShowFooter: api.cfg.ShowFooter,
  1033. ShowNavigation: api.cfg.ShowNavigation,
  1034. ShowNewVersions: showVersion && api.cfg.ShowNewVersions,
  1035. AvailableVersion: availableVersion,
  1036. CurrentVersion: currentVersion,
  1037. PageTitle: api.cfg.PageTitle,
  1038. SectionNavigationStyle: api.cfg.SectionNavigationStyle,
  1039. DefaultIconForBack: api.cfg.DefaultIconForBack,
  1040. EnableCustomJs: api.cfg.EnableCustomJs,
  1041. AuthLoginUrl: api.cfg.AuthLoginUrl,
  1042. AuthLocalLogin: api.cfg.AuthLocalUsers.Enabled,
  1043. OAuth2Providers: buildPublicOAuth2ProvidersList(api.cfg),
  1044. AdditionalLinks: buildAdditionalLinks(api.cfg.AdditionalNavigationLinks),
  1045. StyleMods: api.cfg.StyleMods,
  1046. RootDashboards: rootDashboardTitles(rootDashboardEntries),
  1047. RootDashboardEntries: rootDashboardEntries,
  1048. AuthenticatedUser: user.Username,
  1049. AuthenticatedUserProvider: user.Provider,
  1050. EffectivePolicy: buildEffectivePolicy(user.EffectivePolicy),
  1051. BannerMessage: api.cfg.BannerMessage,
  1052. BannerCss: api.cfg.BannerCSS,
  1053. ShowDiagnostics: user.EffectivePolicy.ShowDiagnostics,
  1054. ShowLogList: user.EffectivePolicy.ShowLogList,
  1055. LoginRequired: loginRequired,
  1056. AvailableThemes: discoverAvailableThemes(api.cfg),
  1057. ShowNavigateOnStartIcons: api.cfg.ShowNavigateOnStartIcons,
  1058. ConfigIssueCount: configIssueCountForUser(api, user),
  1059. }
  1060. return connect.NewResponse(res), nil
  1061. }
  1062. // discoverAvailableThemes finds all available themes in the custom-webui/themes directory.
  1063. // A theme is considered available if it has a theme.css file.
  1064. func discoverAvailableThemes(cfg *config.Config) []string {
  1065. configDir := cfg.GetDir()
  1066. if configDir == "" {
  1067. return []string{}
  1068. }
  1069. themesDir := path.Join(configDir, "custom-webui", "themes")
  1070. entries, err := os.ReadDir(themesDir)
  1071. if err != nil {
  1072. log.WithFields(log.Fields{
  1073. "themesDir": themesDir,
  1074. "error": err,
  1075. }).Tracef("Could not read themes directory")
  1076. return []string{}
  1077. }
  1078. themes := collectValidThemes(themesDir, entries)
  1079. sort.Strings(themes)
  1080. return themes
  1081. }
  1082. // collectValidThemes collects theme names from directory entries that have a theme.css file.
  1083. func collectValidThemes(themesDir string, entries []os.DirEntry) []string {
  1084. var themes []string
  1085. for _, entry := range entries {
  1086. if themeName := getValidThemeName(themesDir, entry); themeName != "" {
  1087. themes = append(themes, themeName)
  1088. }
  1089. }
  1090. return themes
  1091. }
  1092. // getValidThemeName returns the theme name if the entry is a valid theme directory with theme.css, otherwise returns empty string.
  1093. func getValidThemeName(themesDir string, entry os.DirEntry) string {
  1094. if !entry.IsDir() {
  1095. return ""
  1096. }
  1097. themeName := entry.Name()
  1098. themeCssPath := path.Join(themesDir, themeName, "theme.css")
  1099. if _, err := os.Stat(themeCssPath); err != nil {
  1100. return ""
  1101. }
  1102. return themeName
  1103. }
  1104. func (api *oliveTinAPI) buildRootDashboards(user *authpublic.AuthenticatedUser, dashboards []*config.DashboardComponent) []string {
  1105. return rootDashboardTitles(api.buildRootDashboardEntries(user, dashboards))
  1106. }
  1107. func rootDashboardTitles(entries []*apiv1.RootDashboard) []string {
  1108. titles := make([]string, 0, len(entries))
  1109. for _, entry := range entries {
  1110. titles = append(titles, entry.Title)
  1111. }
  1112. return titles
  1113. }
  1114. func (api *oliveTinAPI) buildRootDashboardEntries(user *authpublic.AuthenticatedUser, dashboards []*config.DashboardComponent) []*apiv1.RootDashboard {
  1115. var entries []*apiv1.RootDashboard
  1116. dashboardRenderRequest := api.createDashboardRenderRequest(user, "", "")
  1117. api.addDefaultDashboardEntryIfNeeded(&entries, dashboardRenderRequest)
  1118. api.addCustomDashboardEntries(&entries, dashboards, dashboardRenderRequest)
  1119. return entries
  1120. }
  1121. func (api *oliveTinAPI) addDefaultDashboardEntryIfNeeded(entries *[]*apiv1.RootDashboard, rr *DashboardRenderRequest) {
  1122. defaultDashboard := buildDefaultDashboard(rr)
  1123. if defaultDashboard != nil && len(defaultDashboard.Contents) > 0 {
  1124. log.Tracef("defaultDashboard: %+v", defaultDashboard.Contents)
  1125. *entries = append(*entries, &apiv1.RootDashboard{Title: "Actions"})
  1126. }
  1127. }
  1128. func (api *oliveTinAPI) addCustomDashboardEntries(entries *[]*apiv1.RootDashboard, dashboards []*config.DashboardComponent, rr *DashboardRenderRequest) {
  1129. for _, dashboard := range dashboards {
  1130. // We have to build the dashboard response instead of just looping over config.dashboards,
  1131. // because we need to check if the user has access to the dashboard
  1132. renderedDashboard := renderDashboard(rr, dashboard.Title)
  1133. if renderedDashboard != nil {
  1134. *entries = append(*entries, &apiv1.RootDashboard{
  1135. Title: dashboard.Title,
  1136. Category: dashboard.Category,
  1137. })
  1138. }
  1139. }
  1140. }
  1141. func buildPublicOAuth2ProvidersList(cfg *config.Config) []*apiv1.OAuth2Provider {
  1142. var publicProviders []*apiv1.OAuth2Provider
  1143. for providerKey, provider := range cfg.AuthOAuth2Providers {
  1144. publicProviders = append(publicProviders, &apiv1.OAuth2Provider{
  1145. Title: provider.Title,
  1146. Icon: provider.Icon,
  1147. Key: providerKey,
  1148. })
  1149. }
  1150. sort.Slice(publicProviders, func(i, j int) bool {
  1151. return publicProviders[i].Key < publicProviders[j].Key
  1152. })
  1153. return publicProviders
  1154. }
  1155. func buildAdditionalLinks(links []*config.NavigationLink) []*apiv1.AdditionalLink {
  1156. var additionalLinks []*apiv1.AdditionalLink
  1157. for _, link := range links {
  1158. additionalLinks = append(additionalLinks, &apiv1.AdditionalLink{
  1159. Title: link.Title,
  1160. Url: link.Url,
  1161. })
  1162. }
  1163. return additionalLinks
  1164. }
  1165. func (api *oliveTinAPI) OnOutputChunk(content []byte, executionTrackingId string) {
  1166. entry := api.getValidLogEntryForStreaming(executionTrackingId)
  1167. if entry == nil {
  1168. return
  1169. }
  1170. msg := &apiv1.EventStreamResponse{
  1171. Event: &apiv1.EventStreamResponse_OutputChunk{
  1172. OutputChunk: &apiv1.EventOutputChunk{
  1173. Output: string(content),
  1174. ExecutionTrackingId: executionTrackingId,
  1175. },
  1176. },
  1177. }
  1178. toRemove := []*streamingClient{}
  1179. for _, client := range api.copyOfStreamingClients() {
  1180. api.maybeSendOutputChunk(client, entry, msg, &toRemove)
  1181. }
  1182. for _, client := range toRemove {
  1183. api.removeClient(client)
  1184. }
  1185. }
  1186. func (api *oliveTinAPI) getValidLogEntryForStreaming(executionTrackingId string) *executor.InternalLogEntry {
  1187. entry, ok := api.executor.GetLog(executionTrackingId)
  1188. if !ok || !isValidLogEntry(entry) {
  1189. return nil
  1190. }
  1191. return entry
  1192. }
  1193. func (api *oliveTinAPI) maybeSendOutputChunk(client *streamingClient, entry *executor.InternalLogEntry, msg *apiv1.EventStreamResponse, toRemove *[]*streamingClient) {
  1194. if client == nil {
  1195. return
  1196. }
  1197. if !api.mayViewExecutionEvent(entry, client.AuthenticatedUser) {
  1198. return
  1199. }
  1200. if !api.trySendEventToClient(client, msg) {
  1201. *toRemove = append(*toRemove, client)
  1202. }
  1203. }
  1204. func (api *oliveTinAPI) GetEntities(ctx ctx.Context, req *connect.Request[apiv1.GetEntitiesRequest]) (*connect.Response[apiv1.GetEntitiesResponse], error) {
  1205. user := auth.UserFromApiCall(ctx, req, api.cfg)
  1206. if err := api.checkDashboardAccess(user); err != nil {
  1207. return nil, err
  1208. }
  1209. entityMap := entities.GetEntities()
  1210. entityDefinitions := api.buildEntityDefinitionsResponse(req.Msg, entityMap)
  1211. res := &apiv1.GetEntitiesResponse{
  1212. EntityDefinitions: entityDefinitions,
  1213. }
  1214. return connect.NewResponse(res), nil
  1215. }
  1216. func buildSortedEntityInstances(entityType string, entityInstances map[string]*entities.Entity, properties []config.EntityProperty) []*apiv1.Entity {
  1217. instanceKeys := make([]string, 0, len(entityInstances))
  1218. for key := range entityInstances {
  1219. instanceKeys = append(instanceKeys, key)
  1220. }
  1221. sort.Strings(instanceKeys)
  1222. instances := make([]*apiv1.Entity, 0, len(instanceKeys))
  1223. for _, key := range instanceKeys {
  1224. e := entityInstances[key]
  1225. instances = append(instances, &apiv1.Entity{
  1226. Title: e.Title,
  1227. UniqueKey: e.UniqueKey,
  1228. Type: entityType,
  1229. Fields: entityListFields(e.Data, properties),
  1230. })
  1231. }
  1232. return instances
  1233. }
  1234. func findDashboardsForEntity(entityTitle string, dashboards []*config.DashboardComponent) []string {
  1235. var foundDashboards []string
  1236. seen := make(map[string]bool)
  1237. findEntityInComponents(entityTitle, "", dashboards, &foundDashboards, seen)
  1238. return foundDashboards
  1239. }
  1240. func findEntityInComponents(entityTitle string, parentTitle string, components []*config.DashboardComponent, foundDashboards *[]string, seen map[string]bool) {
  1241. for _, component := range components {
  1242. if component.Entity == entityTitle {
  1243. addEntityDashboard(component, parentTitle, foundDashboards, seen)
  1244. }
  1245. if len(component.Contents) > 0 {
  1246. findEntityInComponents(entityTitle, component.Title, component.Contents, foundDashboards, seen)
  1247. }
  1248. }
  1249. }
  1250. func addEntityDashboard(component *config.DashboardComponent, parentTitle string, foundDashboards *[]string, seen map[string]bool) {
  1251. if component.Type == "directory" {
  1252. addEntityDirectory(component, foundDashboards, seen)
  1253. } else {
  1254. addParentDashboard(parentTitle, foundDashboards, seen)
  1255. }
  1256. }
  1257. func addEntityDirectory(component *config.DashboardComponent, foundDashboards *[]string, seen map[string]bool) {
  1258. dashboardTitle := component.Title + " [Entity Directory]"
  1259. if !seen[dashboardTitle] {
  1260. *foundDashboards = append(*foundDashboards, dashboardTitle)
  1261. seen[dashboardTitle] = true
  1262. seen[component.Title] = true
  1263. }
  1264. }
  1265. func addParentDashboard(parentTitle string, foundDashboards *[]string, seen map[string]bool) {
  1266. if parentTitle != "" && !seen[parentTitle] {
  1267. *foundDashboards = append(*foundDashboards, parentTitle)
  1268. seen[parentTitle] = true
  1269. }
  1270. }
  1271. func findDirectoriesInEntityFieldsets(entityType string, dashboards []*config.DashboardComponent) []string {
  1272. var directories []string
  1273. for _, dashboard := range dashboards {
  1274. findDirectoriesInEntityFieldsetsRecursive(entityType, dashboard, &directories)
  1275. }
  1276. return directories
  1277. }
  1278. func findDirectoriesInEntityFieldsetsRecursive(entityType string, component *config.DashboardComponent, directories *[]string) {
  1279. if component.Entity == entityType {
  1280. collectDirectoriesFromComponent(component, directories)
  1281. }
  1282. if len(component.Contents) > 0 {
  1283. searchSubcomponentsForDirectories(entityType, component.Contents, directories)
  1284. }
  1285. }
  1286. func collectDirectoriesFromComponent(component *config.DashboardComponent, directories *[]string) {
  1287. for _, subitem := range component.Contents {
  1288. if subitem.Type == "directory" {
  1289. *directories = append(*directories, subitem.Title)
  1290. }
  1291. }
  1292. }
  1293. func searchSubcomponentsForDirectories(entityType string, contents []*config.DashboardComponent, directories *[]string) {
  1294. for _, subitem := range contents {
  1295. findDirectoriesInEntityFieldsetsRecursive(entityType, subitem, directories)
  1296. }
  1297. }
  1298. func (api *oliveTinAPI) GetEntity(ctx ctx.Context, req *connect.Request[apiv1.GetEntityRequest]) (*connect.Response[apiv1.Entity], error) {
  1299. user := auth.UserFromApiCall(ctx, req, api.cfg)
  1300. if err := api.checkDashboardAccess(user); err != nil {
  1301. return nil, err
  1302. }
  1303. instances := entities.GetEntityInstances(req.Msg.Type)
  1304. if len(instances) == 0 {
  1305. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("entity type %s not found", req.Msg.Type))
  1306. }
  1307. entity, ok := instances[req.Msg.UniqueKey]
  1308. if !ok {
  1309. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("entity with unique key %s not found in type %s", req.Msg.UniqueKey, req.Msg.Type))
  1310. }
  1311. res := buildEntityResponse(entity, req.Msg.Type, api.cfg)
  1312. res.RelatedActions = api.relatedActionsForEntity(user, req.Msg.Type, entity)
  1313. return connect.NewResponse(res), nil
  1314. }
  1315. func entityTypeIcon(cfg *config.Config, entityType string) string {
  1316. entityFile := entityFileForType(cfg, entityType)
  1317. if entityFile == nil {
  1318. return ""
  1319. }
  1320. return entityFile.Icon
  1321. }
  1322. func entityFileForType(cfg *config.Config, entityType string) *config.EntityFile {
  1323. for _, entityFile := range cfg.Entities {
  1324. if entityFile != nil && entityFile.Name == entityType {
  1325. return entityFile
  1326. }
  1327. }
  1328. return nil
  1329. }
  1330. func entityPropertiesFromFile(entityFile *config.EntityFile) []config.EntityProperty {
  1331. if entityFile == nil {
  1332. return nil
  1333. }
  1334. return entityFile.Properties
  1335. }
  1336. func entityDefinitionProperties(properties []config.EntityProperty) []*apiv1.EntityProperty {
  1337. if len(properties) == 0 {
  1338. return nil
  1339. }
  1340. result := make([]*apiv1.EntityProperty, 0, len(properties))
  1341. for _, property := range properties {
  1342. result = append(result, &apiv1.EntityProperty{
  1343. Name: property.Name,
  1344. Title: property.Title,
  1345. })
  1346. }
  1347. return result
  1348. }
  1349. func entityListFields(data any, properties []config.EntityProperty) map[string]string {
  1350. if len(properties) == 0 {
  1351. return nil
  1352. }
  1353. fields := make(map[string]string, len(properties))
  1354. for _, property := range properties {
  1355. fields[property.Name] = entityPropertyValue(data, property.Name)
  1356. }
  1357. return fields
  1358. }
  1359. func entityPropertyValue(data any, propertyName string) string {
  1360. dataMap, ok := data.(map[string]any)
  1361. if !ok {
  1362. return ""
  1363. }
  1364. if value, found := dataMap[propertyName]; found {
  1365. return fmt.Sprintf("%v", value)
  1366. }
  1367. return entityPropertyValueCaseInsensitive(dataMap, propertyName)
  1368. }
  1369. func entityPropertyValueCaseInsensitive(dataMap map[string]any, propertyName string) string {
  1370. propertyNameLower := strings.ToLower(propertyName)
  1371. for key, value := range dataMap {
  1372. if strings.ToLower(key) == propertyNameLower {
  1373. return fmt.Sprintf("%v", value)
  1374. }
  1375. }
  1376. return ""
  1377. }
  1378. func buildEntityResponse(entity *entities.Entity, entityType string, cfg *config.Config) *apiv1.Entity {
  1379. properties := entityPropertiesFromFile(entityFileForType(cfg, entityType))
  1380. res := &apiv1.Entity{
  1381. Title: entity.Title,
  1382. UniqueKey: entity.UniqueKey,
  1383. Type: entityType,
  1384. Directories: findDirectoriesInEntityFieldsets(entityType, cfg.Dashboards),
  1385. Fields: entityFieldsForResponse(entity.Data, properties),
  1386. Icon: entityTypeIcon(cfg, entityType),
  1387. }
  1388. return res
  1389. }
  1390. func serializeEntityFields(data any) map[string]string {
  1391. if data == nil {
  1392. return nil
  1393. }
  1394. dataMap, ok := data.(map[string]any)
  1395. if !ok {
  1396. return nil
  1397. }
  1398. fields := make(map[string]string)
  1399. for k, v := range dataMap {
  1400. fields[k] = fmt.Sprintf("%v", v)
  1401. }
  1402. return fields
  1403. }
  1404. func (api *oliveTinAPI) RestartAction(ctx ctx.Context, req *connect.Request[apiv1.RestartActionRequest]) (*connect.Response[apiv1.StartActionResponse], error) {
  1405. execReqLogEntry, err := api.restartActionLogEntry(req.Msg.ExecutionTrackingId)
  1406. if err != nil {
  1407. return nil, err
  1408. }
  1409. if err := validateRestartLogEntry(execReqLogEntry); err != nil {
  1410. return nil, err
  1411. }
  1412. authenticatedUser := auth.UserFromApiCall(ctx, req, api.cfg)
  1413. execReq := executor.ExecutionRequest{
  1414. Binding: execReqLogEntry.Binding,
  1415. Arguments: copyStringMap(execReqLogEntry.Arguments),
  1416. Justification: execReqLogEntry.Justification,
  1417. AuthenticatedUser: authenticatedUser,
  1418. Cfg: api.cfg,
  1419. }
  1420. api.executor.ExecRequest(&execReq)
  1421. return connect.NewResponse(&apiv1.StartActionResponse{
  1422. ExecutionTrackingId: execReq.TrackingID,
  1423. }), nil
  1424. }
  1425. func (api *oliveTinAPI) restartActionLogEntry(executionTrackingId string) (*executor.InternalLogEntry, error) {
  1426. execReqLogEntry, found := api.executor.GetLog(executionTrackingId)
  1427. if !found {
  1428. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found for tracking ID %s", executionTrackingId))
  1429. }
  1430. if execReqLogEntry.Binding == nil {
  1431. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("log entry has no binding for tracking ID %s", executionTrackingId))
  1432. }
  1433. if execReqLogEntry.Binding.Action == nil {
  1434. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action not found for tracking ID %s", executionTrackingId))
  1435. }
  1436. return execReqLogEntry, nil
  1437. }
  1438. var (
  1439. executorListenersMu sync.Mutex
  1440. executorListeners = map[*executor.Executor]*oliveTinAPI{}
  1441. )
  1442. // RegisterExecutorListener registers the API server as an executor listener during startup.
  1443. // Call this before background goroutines that may trigger RebuildActionMap.
  1444. func RegisterExecutorListener(ex *executor.Executor) {
  1445. ensureExecutorListener(ex)
  1446. }
  1447. func ensureExecutorListener(ex *executor.Executor) *oliveTinAPI {
  1448. executorListenersMu.Lock()
  1449. defer executorListenersMu.Unlock()
  1450. if server, ok := executorListeners[ex]; ok {
  1451. return server
  1452. }
  1453. server := newServer(ex)
  1454. executorListeners[ex] = server
  1455. return server
  1456. }
  1457. func newServer(ex *executor.Executor) *oliveTinAPI {
  1458. server := &oliveTinAPI{
  1459. cfg: ex.Cfg,
  1460. executor: ex,
  1461. streamingClients: make(map[*streamingClient]struct{}),
  1462. }
  1463. ex.AddListener(server)
  1464. return server
  1465. }
  1466. func GetNewHandler(ex *executor.Executor) (string, http.Handler) {
  1467. server := ensureExecutorListener(ex)
  1468. jsonOpt := connectproto.WithJSON(
  1469. protojson.MarshalOptions{
  1470. EmitUnpopulated: true, // https://github.com/OliveTin/OliveTin/issues/674
  1471. },
  1472. protojson.UnmarshalOptions{
  1473. DiscardUnknown: true,
  1474. },
  1475. )
  1476. return apiv1connect.NewOliveTinApiServiceHandler(server, jsonOpt)
  1477. }