api.go 63 KB

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