api.go 64 KB

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