api.go 63 KB

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