api.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. package api
  2. import (
  3. ctx "context"
  4. "encoding/json"
  5. "errors"
  6. "os"
  7. "path"
  8. "sort"
  9. "connectrpc.com/connect"
  10. "google.golang.org/protobuf/encoding/protojson"
  11. apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1"
  12. apiv1connect "github.com/OliveTin/OliveTin/gen/olivetin/api/v1/apiv1connect"
  13. "github.com/google/uuid"
  14. log "github.com/sirupsen/logrus"
  15. "fmt"
  16. "net/http"
  17. "sync"
  18. "time"
  19. acl "github.com/OliveTin/OliveTin/internal/acl"
  20. auth "github.com/OliveTin/OliveTin/internal/auth"
  21. authpublic "github.com/OliveTin/OliveTin/internal/auth/authpublic"
  22. config "github.com/OliveTin/OliveTin/internal/config"
  23. entities "github.com/OliveTin/OliveTin/internal/entities"
  24. executor "github.com/OliveTin/OliveTin/internal/executor"
  25. installationinfo "github.com/OliveTin/OliveTin/internal/installationinfo"
  26. "github.com/OliveTin/OliveTin/internal/tpl"
  27. connectproto "go.akshayshah.org/connectproto"
  28. )
  29. type oliveTinAPI struct {
  30. executor *executor.Executor
  31. cfg *config.Config
  32. // streamingClients is a set of currently connected clients.
  33. // The empty struct value models set semantics (keys only) and keeps add/remove O(1).
  34. // We use a map for efficient membership and deletion; ordering is not required.
  35. streamingClients map[*streamingClient]struct{}
  36. streamingClientsMutex sync.RWMutex
  37. }
  38. // This is used to avoid race conditions when iterating over the connectedClients map.
  39. // and holds the lock for as minimal time as possible to avoid blocking the API for too long.
  40. func (api *oliveTinAPI) copyOfStreamingClients() []*streamingClient {
  41. api.streamingClientsMutex.RLock()
  42. defer api.streamingClientsMutex.RUnlock()
  43. clients := make([]*streamingClient, 0, len(api.streamingClients))
  44. for client := range api.streamingClients {
  45. clients = append(clients, client)
  46. }
  47. return clients
  48. }
  49. type streamingClient struct {
  50. channel chan *apiv1.EventStreamResponse
  51. AuthenticatedUser *authpublic.AuthenticatedUser
  52. }
  53. func (api *oliveTinAPI) KillAction(ctx ctx.Context, req *connect.Request[apiv1.KillActionRequest]) (*connect.Response[apiv1.KillActionResponse], error) {
  54. ret := &apiv1.KillActionResponse{
  55. ExecutionTrackingId: req.Msg.ExecutionTrackingId,
  56. }
  57. var execReqLogEntry *executor.InternalLogEntry
  58. execReqLogEntry, ret.Found = api.executor.GetLog(req.Msg.ExecutionTrackingId)
  59. if !ret.Found {
  60. log.Warnf("Killing execution request not possible - not found by tracking ID: %v", req.Msg.ExecutionTrackingId)
  61. return connect.NewResponse(ret), nil
  62. }
  63. log.Warnf("Killing execution request by tracking ID: %v", req.Msg.ExecutionTrackingId)
  64. action := execReqLogEntry.Binding.Action
  65. if action == nil {
  66. log.Warnf("Killing execution request not possible - action not found: %v", execReqLogEntry.ActionTitle)
  67. ret.Killed = false
  68. return connect.NewResponse(ret), nil
  69. }
  70. user := auth.UserFromApiCall(ctx, req, api.cfg)
  71. api.killActionByTrackingId(user, action, execReqLogEntry, ret)
  72. return connect.NewResponse(ret), nil
  73. }
  74. func (api *oliveTinAPI) killActionByTrackingId(user *authpublic.AuthenticatedUser, action *config.Action, execReqLogEntry *executor.InternalLogEntry, ret *apiv1.KillActionResponse) {
  75. if !acl.IsAllowedKill(api.cfg, user, action) {
  76. log.Warnf("Killing execution request not possible - user not allowed to kill this action: %v", execReqLogEntry.ExecutionTrackingID)
  77. ret.Killed = false
  78. return
  79. }
  80. err := api.executor.Kill(execReqLogEntry)
  81. if err != nil {
  82. log.Warnf("Killing execution request err: %v", err)
  83. ret.AlreadyCompleted = true
  84. ret.Killed = false
  85. } else {
  86. ret.Killed = true
  87. }
  88. }
  89. func (api *oliveTinAPI) StartAction(ctx ctx.Context, req *connect.Request[apiv1.StartActionRequest]) (*connect.Response[apiv1.StartActionResponse], error) {
  90. args := make(map[string]string)
  91. for _, arg := range req.Msg.Arguments {
  92. args[arg.Name] = arg.Value
  93. }
  94. pair := api.executor.FindBindingByID(req.Msg.BindingId)
  95. if pair == nil || pair.Action == nil {
  96. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action with ID %s not found", req.Msg.BindingId))
  97. }
  98. authenticatedUser := auth.UserFromApiCall(ctx, req, api.cfg)
  99. execReq := executor.ExecutionRequest{
  100. Binding: pair,
  101. TrackingID: req.Msg.UniqueTrackingId,
  102. Arguments: args,
  103. AuthenticatedUser: authenticatedUser,
  104. Cfg: api.cfg,
  105. }
  106. api.executor.ExecRequest(&execReq)
  107. ret := &apiv1.StartActionResponse{
  108. ExecutionTrackingId: execReq.TrackingID,
  109. }
  110. return connect.NewResponse(ret), nil
  111. }
  112. func (api *oliveTinAPI) PasswordHash(ctx ctx.Context, req *connect.Request[apiv1.PasswordHashRequest]) (*connect.Response[apiv1.PasswordHashResponse], error) {
  113. hash, err := createHash(req.Msg.Password)
  114. if err != nil {
  115. if errors.Is(err, ErrArgon2Busy) {
  116. return nil, connect.NewError(connect.CodeResourceExhausted, err)
  117. }
  118. return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("error creating hash: %w", err))
  119. }
  120. ret := &apiv1.PasswordHashResponse{
  121. Hash: hash,
  122. }
  123. return connect.NewResponse(ret), nil
  124. }
  125. func (api *oliveTinAPI) LocalUserLogin(ctx ctx.Context, req *connect.Request[apiv1.LocalUserLoginRequest]) (*connect.Response[apiv1.LocalUserLoginResponse], error) {
  126. // Check if local user authentication is enabled
  127. if !api.cfg.AuthLocalUsers.Enabled {
  128. return connect.NewResponse(&apiv1.LocalUserLoginResponse{
  129. Success: false,
  130. }), nil
  131. }
  132. match, err := checkUserPassword(api.cfg, req.Msg.Username, req.Msg.Password)
  133. if err != nil {
  134. if errors.Is(err, ErrArgon2Busy) {
  135. return nil, connect.NewError(connect.CodeResourceExhausted, err)
  136. }
  137. return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("checking password: %w", err))
  138. }
  139. response := connect.NewResponse(&apiv1.LocalUserLoginResponse{
  140. Success: match,
  141. })
  142. if match {
  143. // Set authentication cookie for successful login
  144. user := api.cfg.FindUserByUsername(req.Msg.Username)
  145. if user != nil {
  146. sid := uuid.NewString()
  147. // Register the session in the session storage
  148. auth.RegisterUserSession(api.cfg, "local", sid, user.Username)
  149. log.WithFields(log.Fields{
  150. "username": user.Username,
  151. }).Info("LocalUserLogin: Session created and registered")
  152. // Set the authentication cookie in the response headers
  153. cookie := &http.Cookie{
  154. Name: "olivetin-sid-local",
  155. Value: sid,
  156. MaxAge: 31556952, // 1 year
  157. HttpOnly: true,
  158. Path: "/",
  159. }
  160. response.Header().Set("Set-Cookie", cookie.String())
  161. }
  162. log.WithFields(log.Fields{
  163. "username": req.Msg.Username,
  164. }).Info("LocalUserLogin: User logged in successfully.")
  165. } else {
  166. log.WithFields(log.Fields{
  167. "username": req.Msg.Username,
  168. }).Warn("LocalUserLogin: User login failed.")
  169. }
  170. return response, nil
  171. }
  172. func (api *oliveTinAPI) StartActionAndWait(ctx ctx.Context, req *connect.Request[apiv1.StartActionAndWaitRequest]) (*connect.Response[apiv1.StartActionAndWaitResponse], error) {
  173. args := make(map[string]string)
  174. for _, arg := range req.Msg.Arguments {
  175. args[arg.Name] = arg.Value
  176. }
  177. user := auth.UserFromApiCall(ctx, req, api.cfg)
  178. execReq := executor.ExecutionRequest{
  179. Binding: api.executor.FindBindingByID(req.Msg.ActionId),
  180. TrackingID: uuid.NewString(),
  181. Arguments: args,
  182. AuthenticatedUser: user,
  183. Cfg: api.cfg,
  184. }
  185. wg, _ := api.executor.ExecRequest(&execReq)
  186. wg.Wait()
  187. internalLogEntry, ok := api.executor.GetLog(execReq.TrackingID)
  188. if ok {
  189. return connect.NewResponse(&apiv1.StartActionAndWaitResponse{
  190. LogEntry: api.internalLogEntryToPb(internalLogEntry, user),
  191. }), nil
  192. } else {
  193. return nil, fmt.Errorf("execution not found")
  194. }
  195. }
  196. func (api *oliveTinAPI) StartActionByGet(ctx ctx.Context, req *connect.Request[apiv1.StartActionByGetRequest]) (*connect.Response[apiv1.StartActionByGetResponse], error) {
  197. args := make(map[string]string)
  198. execReq := executor.ExecutionRequest{
  199. Binding: api.executor.FindBindingByID(req.Msg.ActionId),
  200. TrackingID: uuid.NewString(),
  201. Arguments: args,
  202. AuthenticatedUser: auth.UserFromApiCall(ctx, req, api.cfg),
  203. Cfg: api.cfg,
  204. }
  205. _, uniqueTrackingId := api.executor.ExecRequest(&execReq)
  206. return connect.NewResponse(&apiv1.StartActionByGetResponse{
  207. ExecutionTrackingId: uniqueTrackingId,
  208. }), nil
  209. }
  210. func (api *oliveTinAPI) StartActionByGetAndWait(ctx ctx.Context, req *connect.Request[apiv1.StartActionByGetAndWaitRequest]) (*connect.Response[apiv1.StartActionByGetAndWaitResponse], error) {
  211. args := make(map[string]string)
  212. user := auth.UserFromApiCall(ctx, req, api.cfg)
  213. execReq := executor.ExecutionRequest{
  214. Binding: api.executor.FindBindingByID(req.Msg.ActionId),
  215. TrackingID: uuid.NewString(),
  216. Arguments: args,
  217. AuthenticatedUser: user,
  218. Cfg: api.cfg,
  219. }
  220. wg, _ := api.executor.ExecRequest(&execReq)
  221. wg.Wait()
  222. internalLogEntry, ok := api.executor.GetLog(execReq.TrackingID)
  223. if ok {
  224. return connect.NewResponse(&apiv1.StartActionByGetAndWaitResponse{
  225. LogEntry: api.internalLogEntryToPb(internalLogEntry, user),
  226. }), nil
  227. } else {
  228. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found"))
  229. }
  230. }
  231. func calculateRateLimitExpires(api *oliveTinAPI, logEntry *executor.InternalLogEntry) string {
  232. if logEntry.Binding == nil || logEntry.Binding.Action == nil {
  233. return ""
  234. }
  235. expiryUnix := api.executor.GetTimeUntilAvailable(logEntry.Binding)
  236. if expiryUnix <= 0 {
  237. return ""
  238. }
  239. return time.Unix(expiryUnix, 0).Format("2006-01-02 15:04:05")
  240. }
  241. func (api *oliveTinAPI) internalLogEntryToPb(logEntry *executor.InternalLogEntry, authenticatedUser *authpublic.AuthenticatedUser) *apiv1.LogEntry {
  242. pble := &apiv1.LogEntry{
  243. ActionTitle: logEntry.ActionTitle,
  244. ActionIcon: logEntry.ActionIcon,
  245. DatetimeStarted: logEntry.DatetimeStarted.Format("2006-01-02 15:04:05"),
  246. DatetimeFinished: logEntry.DatetimeFinished.Format("2006-01-02 15:04:05"),
  247. DatetimeIndex: logEntry.Index,
  248. Output: logEntry.Output,
  249. TimedOut: logEntry.TimedOut,
  250. Blocked: logEntry.Blocked,
  251. ExitCode: logEntry.ExitCode,
  252. Tags: logEntry.Tags,
  253. ExecutionTrackingId: logEntry.ExecutionTrackingID,
  254. ExecutionStarted: logEntry.ExecutionStarted,
  255. ExecutionFinished: logEntry.ExecutionFinished,
  256. User: logEntry.Username,
  257. BindingId: logEntry.GetBindingId(),
  258. DatetimeRateLimitExpires: calculateRateLimitExpires(api, logEntry),
  259. }
  260. if !pble.ExecutionFinished && logEntry.Binding != nil && logEntry.Binding.Action != nil {
  261. pble.CanKill = acl.IsAllowedKill(api.cfg, authenticatedUser, logEntry.Binding.Action)
  262. }
  263. return pble
  264. }
  265. func getExecutionStatusByTrackingID(api *oliveTinAPI, executionTrackingId string) *executor.InternalLogEntry {
  266. logEntry, ok := api.executor.GetLog(executionTrackingId)
  267. if !ok {
  268. return nil
  269. }
  270. return logEntry
  271. }
  272. // This is the actual action ID, not the binding ID.
  273. func getMostRecentExecutionStatusByActionId(api *oliveTinAPI, actionId string) *executor.InternalLogEntry {
  274. var ile *executor.InternalLogEntry
  275. binding := api.executor.FindBindingByID(actionId)
  276. if binding == nil {
  277. return nil
  278. }
  279. logs := api.executor.GetLogsByBindingId(binding.ID)
  280. if len(logs) == 0 {
  281. return nil
  282. }
  283. if len(logs) == 0 {
  284. return nil
  285. } else {
  286. // Get last log entry
  287. ile = logs[len(logs)-1]
  288. }
  289. return ile
  290. }
  291. func (api *oliveTinAPI) ExecutionStatus(ctx ctx.Context, req *connect.Request[apiv1.ExecutionStatusRequest]) (*connect.Response[apiv1.ExecutionStatusResponse], error) {
  292. res := &apiv1.ExecutionStatusResponse{}
  293. user := auth.UserFromApiCall(ctx, req, api.cfg)
  294. if err := api.checkDashboardAccess(user); err != nil {
  295. return nil, err
  296. }
  297. var ile *executor.InternalLogEntry
  298. if req.Msg.ExecutionTrackingId != "" {
  299. ile = getExecutionStatusByTrackingID(api, req.Msg.ExecutionTrackingId)
  300. } else {
  301. ile = getMostRecentExecutionStatusByActionId(api, req.Msg.ActionId)
  302. }
  303. if ile == nil {
  304. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found for tracking ID %s or action ID %s", req.Msg.ExecutionTrackingId, req.Msg.ActionId))
  305. }
  306. if !isValidLogEntry(ile) || !api.isLogEntryAllowed(ile, user) {
  307. return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied to view this execution"))
  308. }
  309. res.LogEntry = api.internalLogEntryToPb(ile, user)
  310. return connect.NewResponse(res), nil
  311. }
  312. func (api *oliveTinAPI) Logout(ctx ctx.Context, req *connect.Request[apiv1.LogoutRequest]) (*connect.Response[apiv1.LogoutResponse], error) {
  313. user := auth.UserFromApiCall(ctx, req, api.cfg)
  314. log.WithFields(log.Fields{
  315. "username": user.Username,
  316. "provider": user.Provider,
  317. }).Info("Logout: User logged out")
  318. response := connect.NewResponse(&apiv1.LogoutResponse{})
  319. // Clear the local authentication cookie by setting it to expire
  320. localCookie := &http.Cookie{
  321. Name: "olivetin-sid-local",
  322. Value: "",
  323. MaxAge: -1, // This tells the browser to delete the cookie
  324. HttpOnly: true,
  325. Path: "/",
  326. }
  327. response.Header().Set("Set-Cookie", localCookie.String())
  328. // Clear the OAuth2 authentication cookie by setting it to expire
  329. oauth2Cookie := &http.Cookie{
  330. Name: "olivetin-sid-oauth",
  331. Value: "",
  332. MaxAge: -1, // This tells the browser to delete the cookie
  333. HttpOnly: true,
  334. Path: "/",
  335. }
  336. response.Header().Add("Set-Cookie", oauth2Cookie.String())
  337. return response, nil
  338. }
  339. func (api *oliveTinAPI) GetActionBinding(ctx ctx.Context, req *connect.Request[apiv1.GetActionBindingRequest]) (*connect.Response[apiv1.GetActionBindingResponse], error) {
  340. user := auth.UserFromApiCall(ctx, req, api.cfg)
  341. if err := api.checkDashboardAccess(user); err != nil {
  342. return nil, err
  343. }
  344. binding := api.executor.FindBindingByID(req.Msg.BindingId)
  345. if binding == nil {
  346. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action with ID %s not found", req.Msg.BindingId))
  347. }
  348. return connect.NewResponse(&apiv1.GetActionBindingResponse{
  349. Action: buildAction(binding, &DashboardRenderRequest{
  350. cfg: api.cfg,
  351. AuthenticatedUser: user,
  352. ex: api.executor,
  353. }),
  354. }), nil
  355. }
  356. func (api *oliveTinAPI) GetDashboard(ctx ctx.Context, req *connect.Request[apiv1.GetDashboardRequest]) (*connect.Response[apiv1.GetDashboardResponse], error) {
  357. user := auth.UserFromApiCall(ctx, req, api.cfg)
  358. if err := api.checkDashboardAccess(user); err != nil {
  359. return nil, err
  360. }
  361. entityType := ""
  362. entityKey := ""
  363. if req.Msg != nil {
  364. entityType = req.Msg.EntityType
  365. entityKey = req.Msg.EntityKey
  366. }
  367. dashboardRenderRequest := api.createDashboardRenderRequest(user, entityType, entityKey)
  368. if api.isDefaultDashboard(req.Msg.Title) {
  369. return api.buildDefaultDashboardResponse(dashboardRenderRequest)
  370. }
  371. return api.buildCustomDashboardResponse(dashboardRenderRequest, req.Msg.Title)
  372. }
  373. func (api *oliveTinAPI) checkDashboardAccess(user *authpublic.AuthenticatedUser) error {
  374. if user.IsGuest() && api.cfg.AuthRequireGuestsToLogin {
  375. return connect.NewError(connect.CodePermissionDenied, fmt.Errorf("guests are not allowed to access the dashboard"))
  376. }
  377. return nil
  378. }
  379. func (api *oliveTinAPI) createDashboardRenderRequest(user *authpublic.AuthenticatedUser, entityType, entityKey string) *DashboardRenderRequest {
  380. return &DashboardRenderRequest{
  381. AuthenticatedUser: user,
  382. cfg: api.cfg,
  383. ex: api.executor,
  384. EntityType: entityType,
  385. EntityKey: entityKey,
  386. }
  387. }
  388. func (api *oliveTinAPI) isDefaultDashboard(title string) bool {
  389. return title == "default" || title == "" || title == "Actions"
  390. }
  391. func (api *oliveTinAPI) buildDefaultDashboardResponse(rr *DashboardRenderRequest) (*connect.Response[apiv1.GetDashboardResponse], error) {
  392. db := buildDefaultDashboard(rr)
  393. res := &apiv1.GetDashboardResponse{
  394. Dashboard: db,
  395. }
  396. return connect.NewResponse(res), nil
  397. }
  398. func (api *oliveTinAPI) buildCustomDashboardResponse(rr *DashboardRenderRequest, title string) (*connect.Response[apiv1.GetDashboardResponse], error) {
  399. res := &apiv1.GetDashboardResponse{
  400. Dashboard: renderDashboard(rr, title),
  401. }
  402. return connect.NewResponse(res), nil
  403. }
  404. func resolveLogsPageSize(requestPageSize, defaultPageSize int64) int64 {
  405. if requestPageSize == 0 {
  406. return defaultPageSize
  407. }
  408. if requestPageSize < 10 {
  409. return 10
  410. }
  411. if requestPageSize > 100 {
  412. return 100
  413. }
  414. return requestPageSize
  415. }
  416. func (api *oliveTinAPI) GetLogs(ctx ctx.Context, req *connect.Request[apiv1.GetLogsRequest]) (*connect.Response[apiv1.GetLogsResponse], error) {
  417. user := auth.UserFromApiCall(ctx, req, api.cfg)
  418. if err := api.checkDashboardAccess(user); err != nil {
  419. return nil, err
  420. }
  421. pageSize := resolveLogsPageSize(req.Msg.GetPageSize(), api.cfg.LogHistoryPageSize)
  422. logEntries, paging := api.executor.GetLogTrackingIdsACL(api.cfg, user, req.Msg.StartOffset, pageSize, req.Msg.DateFilter)
  423. ret := &apiv1.GetLogsResponse{}
  424. for _, le := range logEntries {
  425. ret.Logs = append(ret.Logs, api.internalLogEntryToPb(le, user))
  426. }
  427. ret.CountRemaining = paging.CountRemaining
  428. ret.PageSize = paging.PageSize
  429. ret.TotalCount = paging.TotalCount
  430. ret.StartOffset = paging.StartOffset
  431. return connect.NewResponse(ret), nil
  432. }
  433. // isValidLogEntry checks if a log entry has all required fields populated.
  434. func isValidLogEntry(e *executor.InternalLogEntry) bool {
  435. return e != nil && e.Binding != nil && e.Binding.Action != nil
  436. }
  437. // isLogEntryAllowed checks if a log entry is allowed to be viewed by the user.
  438. func (api *oliveTinAPI) isLogEntryAllowed(e *executor.InternalLogEntry, user *authpublic.AuthenticatedUser) bool {
  439. return acl.IsAllowedLogs(api.cfg, user, e.Binding.Action)
  440. }
  441. // buildEmptyPageResponse creates a response for an empty page.
  442. func buildEmptyPageResponse(page pageInfo) *apiv1.GetActionLogsResponse {
  443. return &apiv1.GetActionLogsResponse{
  444. CountRemaining: 0,
  445. PageSize: page.size,
  446. TotalCount: page.total,
  447. StartOffset: page.start,
  448. }
  449. }
  450. // calculateReversedIndices computes the reversed indices for newest-first pagination.
  451. func calculateReversedIndices(page pageInfo, filteredLen int) (int64, int64) {
  452. startIdx := page.total - page.end
  453. endIdx := page.total - page.start
  454. if startIdx < 0 {
  455. startIdx = 0
  456. }
  457. if endIdx > int64(filteredLen) {
  458. endIdx = int64(filteredLen)
  459. }
  460. return startIdx, endIdx
  461. }
  462. // buildActionLogsResponse builds the response with paginated log entries.
  463. func (api *oliveTinAPI) buildActionLogsResponse(filtered []*executor.InternalLogEntry, page pageInfo, user *authpublic.AuthenticatedUser) *apiv1.GetActionLogsResponse {
  464. startIdx, endIdx := calculateReversedIndices(page, len(filtered))
  465. ret := &apiv1.GetActionLogsResponse{}
  466. for _, le := range filtered[startIdx:endIdx] {
  467. ret.Logs = append(ret.Logs, api.internalLogEntryToPb(le, user))
  468. }
  469. ret.CountRemaining = page.start
  470. ret.PageSize = page.size
  471. ret.TotalCount = page.total
  472. ret.StartOffset = page.start
  473. return ret
  474. }
  475. func (api *oliveTinAPI) GetActionLogs(ctx ctx.Context, req *connect.Request[apiv1.GetActionLogsRequest]) (*connect.Response[apiv1.GetActionLogsResponse], error) {
  476. user := auth.UserFromApiCall(ctx, req, api.cfg)
  477. if err := api.checkDashboardAccess(user); err != nil {
  478. return nil, err
  479. }
  480. filtered := api.filterLogsByACL(api.executor.GetLogsByBindingId(req.Msg.ActionId), user)
  481. page := paginate(int64(len(filtered)), api.cfg.LogHistoryPageSize, req.Msg.StartOffset)
  482. if page.empty {
  483. return connect.NewResponse(buildEmptyPageResponse(page)), nil
  484. }
  485. return connect.NewResponse(api.buildActionLogsResponse(filtered, page, user)), nil
  486. }
  487. func (api *oliveTinAPI) filterLogsByACL(entries []*executor.InternalLogEntry, user *authpublic.AuthenticatedUser) []*executor.InternalLogEntry {
  488. filtered := make([]*executor.InternalLogEntry, 0, len(entries))
  489. for _, e := range entries {
  490. if !isValidLogEntry(e) {
  491. continue
  492. }
  493. if api.isLogEntryAllowed(e, user) {
  494. filtered = append(filtered, e)
  495. }
  496. }
  497. return filtered
  498. }
  499. type pageInfo struct {
  500. total int64
  501. size int64
  502. start int64
  503. end int64
  504. empty bool
  505. }
  506. func paginate(total int64, size int64, start int64) pageInfo {
  507. if start < 0 {
  508. start = 0
  509. }
  510. if start >= total {
  511. return pageInfo{total: total, size: size, start: start, end: start, empty: true}
  512. }
  513. end := start + size
  514. if end > total {
  515. end = total
  516. }
  517. return pageInfo{total: total, size: size, start: start, end: end, empty: false}
  518. }
  519. /*
  520. This function is ONLY a helper for the UI - the arguments are validated properly
  521. on the StartAction -> Executor chain. This is here basically to provide helpful
  522. error messages more quickly before starting the action.
  523. It uses the same validation logic as the executor, including mangling argument
  524. values (e.g., datetime formatting, checkbox title-to-value conversion).
  525. */
  526. func (api *oliveTinAPI) ValidateArgumentType(ctx ctx.Context, req *connect.Request[apiv1.ValidateArgumentTypeRequest]) (*connect.Response[apiv1.ValidateArgumentTypeResponse], error) {
  527. err := api.validateArgumentTypeInternal(req.Msg)
  528. desc := ""
  529. if err != nil {
  530. desc = err.Error()
  531. }
  532. return connect.NewResponse(&apiv1.ValidateArgumentTypeResponse{
  533. Valid: err == nil,
  534. Description: desc,
  535. }), nil
  536. }
  537. func (api *oliveTinAPI) validateArgumentTypeInternal(msg *apiv1.ValidateArgumentTypeRequest) error {
  538. if msg.BindingId == "" || msg.ArgumentName == "" {
  539. return executor.TypeSafetyCheck("", msg.Value, msg.Type)
  540. }
  541. arg, action := api.findArgumentForValidation(msg.BindingId, msg.ArgumentName)
  542. if arg == nil {
  543. return fmt.Errorf("argument not found")
  544. }
  545. return executor.ValidateArgument(arg, msg.Value, action)
  546. }
  547. func (api *oliveTinAPI) findArgumentForValidation(bindingId string, argumentName string) (*config.ActionArgument, *config.Action) {
  548. binding := api.executor.FindBindingByID(bindingId)
  549. if binding == nil || binding.Action == nil {
  550. return nil, nil
  551. }
  552. arg := api.findArgumentByName(binding.Action, argumentName)
  553. return arg, binding.Action
  554. }
  555. func (api *oliveTinAPI) findArgumentByName(action *config.Action, name string) *config.ActionArgument {
  556. for i := range action.Arguments {
  557. if action.Arguments[i].Name == name {
  558. return &action.Arguments[i]
  559. }
  560. }
  561. return nil
  562. }
  563. func (api *oliveTinAPI) WhoAmI(ctx ctx.Context, req *connect.Request[apiv1.WhoAmIRequest]) (*connect.Response[apiv1.WhoAmIResponse], error) {
  564. user := auth.UserFromApiCall(ctx, req, api.cfg)
  565. if err := api.checkDashboardAccess(user); err != nil {
  566. return nil, err
  567. }
  568. res := &apiv1.WhoAmIResponse{
  569. AuthenticatedUser: user.Username,
  570. Usergroup: user.UsergroupLine,
  571. Provider: user.Provider,
  572. Sid: user.SID,
  573. Acls: user.Acls,
  574. }
  575. return connect.NewResponse(res), nil
  576. }
  577. func (api *oliveTinAPI) SosReport(ctx ctx.Context, req *connect.Request[apiv1.SosReportRequest]) (*connect.Response[apiv1.SosReportResponse], error) {
  578. sos := installationinfo.GetSosReport()
  579. if !api.cfg.InsecureAllowDumpSos {
  580. log.Info(sos)
  581. sos = "Your SOS Report has been logged to OliveTin logs.\n\nIf you are in a safe network, you can temporarily set `insecureAllowDumpSos: true` in your config.yaml, restart OliveTin, and refresh this page - it will put the output directly in the browser."
  582. }
  583. ret := &apiv1.SosReportResponse{
  584. Alert: sos,
  585. }
  586. return connect.NewResponse(ret), nil
  587. }
  588. func (api *oliveTinAPI) DumpVars(ctx ctx.Context, req *connect.Request[apiv1.DumpVarsRequest]) (*connect.Response[apiv1.DumpVarsResponse], error) {
  589. res := &apiv1.DumpVarsResponse{}
  590. if !api.cfg.InsecureAllowDumpVars {
  591. res.Alert = "Dumping variables is not allowed by default because it is insecure."
  592. return connect.NewResponse(res), nil
  593. }
  594. jsonstring, err := json.MarshalIndent(tpl.GetNewGeneralTemplateContext(), "", " ")
  595. if err != nil {
  596. log.WithError(err).Error("DumpVars: failed to marshal template context from GetNewGeneralTemplateContext")
  597. return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("dump vars: marshal template context: %w", err))
  598. }
  599. fmt.Printf("%s", jsonstring)
  600. res.Alert = "Dumping variables has been enabled in the configuration. Please set InsecureAllowDumpVars = false again after you don't need it anymore"
  601. return connect.NewResponse(res), nil
  602. }
  603. func (api *oliveTinAPI) DumpPublicIdActionMap(ctx ctx.Context, req *connect.Request[apiv1.DumpPublicIdActionMapRequest]) (*connect.Response[apiv1.DumpPublicIdActionMapResponse], error) {
  604. res := &apiv1.DumpPublicIdActionMapResponse{}
  605. res.Contents = make(map[string]*apiv1.DebugBinding)
  606. if !api.cfg.InsecureAllowDumpActionMap {
  607. res.Alert = "Dumping Public IDs is disallowed."
  608. return connect.NewResponse(res), nil
  609. }
  610. api.executor.MapActionBindingsLock.RLock()
  611. for k, v := range api.executor.MapActionBindings {
  612. res.Contents[k] = &apiv1.DebugBinding{
  613. ActionTitle: v.Action.Title,
  614. }
  615. }
  616. api.executor.MapActionBindingsLock.RUnlock()
  617. res.Alert = "Dumping variables has been enabled in the configuration. Please set InsecureAllowDumpActionMap = false again after you don't need it anymore"
  618. return connect.NewResponse(res), nil
  619. }
  620. func (api *oliveTinAPI) GetReadyz(ctx ctx.Context, req *connect.Request[apiv1.GetReadyzRequest]) (*connect.Response[apiv1.GetReadyzResponse], error) {
  621. res := &apiv1.GetReadyzResponse{
  622. Status: "OK",
  623. }
  624. return connect.NewResponse(res), nil
  625. }
  626. func (api *oliveTinAPI) EventStream(ctx ctx.Context, req *connect.Request[apiv1.EventStreamRequest], srv *connect.ServerStream[apiv1.EventStreamResponse]) error {
  627. log.Debugf("EventStream: %v", req.Msg)
  628. // Set X-Accel-Buffering header to disable nginx buffering for this stream
  629. // https://github.com/OliveTin/OliveTin/issues/765
  630. srv.ResponseHeader().Set("X-Accel-Buffering", "no")
  631. user := auth.UserFromApiCall(ctx, req, api.cfg)
  632. if err := api.checkDashboardAccess(user); err != nil {
  633. return err
  634. }
  635. client := &streamingClient{
  636. channel: make(chan *apiv1.EventStreamResponse, 10), // Buffered channel to hold Events
  637. AuthenticatedUser: user,
  638. }
  639. log.WithFields(log.Fields{
  640. "authenticatedUser": user.Username,
  641. }).Debugf("EventStream: client connected")
  642. api.streamingClientsMutex.Lock()
  643. api.streamingClients[client] = struct{}{}
  644. api.streamingClientsMutex.Unlock()
  645. // loop over client channel and send events to connectedClient
  646. for msg := range client.channel {
  647. log.Debugf("Sending event to client: %v", msg)
  648. if err := srv.Send(msg); err != nil {
  649. log.Errorf("Error sending event to client: %v", err)
  650. // Remove disconnected client from the list
  651. api.removeClient(client)
  652. break
  653. }
  654. }
  655. log.Infof("EventStream: client disconnected")
  656. return nil
  657. }
  658. func (api *oliveTinAPI) removeClient(clientToRemove *streamingClient) {
  659. api.streamingClientsMutex.Lock()
  660. delete(api.streamingClients, clientToRemove)
  661. api.streamingClientsMutex.Unlock()
  662. close(clientToRemove.channel)
  663. }
  664. func (api *oliveTinAPI) OnActionMapRebuilt() {
  665. toRemove := []*streamingClient{}
  666. for _, client := range api.copyOfStreamingClients() {
  667. select {
  668. case client.channel <- &apiv1.EventStreamResponse{
  669. Event: &apiv1.EventStreamResponse_ConfigChanged{
  670. ConfigChanged: &apiv1.EventConfigChanged{},
  671. },
  672. }:
  673. default:
  674. log.Warnf("EventStream: client channel is full, removing client")
  675. toRemove = append(toRemove, client)
  676. }
  677. }
  678. for _, client := range toRemove {
  679. api.removeClient(client)
  680. }
  681. }
  682. func (api *oliveTinAPI) OnExecutionStarted(ex *executor.InternalLogEntry) {
  683. toRemove := []*streamingClient{}
  684. for _, client := range api.copyOfStreamingClients() {
  685. select {
  686. case client.channel <- &apiv1.EventStreamResponse{
  687. Event: &apiv1.EventStreamResponse_ExecutionStarted{
  688. ExecutionStarted: &apiv1.EventExecutionStarted{
  689. LogEntry: api.internalLogEntryToPb(ex, client.AuthenticatedUser),
  690. },
  691. },
  692. }:
  693. default:
  694. log.Warnf("EventStream: client channel is full, removing client")
  695. toRemove = append(toRemove, client)
  696. }
  697. }
  698. for _, client := range toRemove {
  699. api.removeClient(client)
  700. }
  701. }
  702. func (api *oliveTinAPI) OnExecutionFinished(ile *executor.InternalLogEntry) {
  703. toRemove := []*streamingClient{}
  704. for _, client := range api.copyOfStreamingClients() {
  705. select {
  706. case client.channel <- &apiv1.EventStreamResponse{
  707. Event: &apiv1.EventStreamResponse_ExecutionFinished{
  708. ExecutionFinished: &apiv1.EventExecutionFinished{
  709. LogEntry: api.internalLogEntryToPb(ile, client.AuthenticatedUser),
  710. },
  711. },
  712. }:
  713. default:
  714. log.Warnf("EventStream: client channel is full, removing client")
  715. toRemove = append(toRemove, client)
  716. }
  717. }
  718. for _, client := range toRemove {
  719. api.removeClient(client)
  720. }
  721. }
  722. func (api *oliveTinAPI) GetDiagnostics(ctx ctx.Context, req *connect.Request[apiv1.GetDiagnosticsRequest]) (*connect.Response[apiv1.GetDiagnosticsResponse], error) {
  723. user := auth.UserFromApiCall(ctx, req, api.cfg)
  724. if err := api.checkDashboardAccess(user); err != nil {
  725. return nil, err
  726. }
  727. if !user.EffectivePolicy.ShowDiagnostics {
  728. return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("diagnostics are not available for your account"))
  729. }
  730. res := &apiv1.GetDiagnosticsResponse{
  731. SshFoundKey: installationinfo.Runtime.SshFoundKey,
  732. SshFoundConfig: installationinfo.Runtime.SshFoundConfig,
  733. }
  734. return connect.NewResponse(res), nil
  735. }
  736. func (api *oliveTinAPI) Init(ctx ctx.Context, req *connect.Request[apiv1.InitRequest]) (*connect.Response[apiv1.InitResponse], error) {
  737. user := auth.UserFromApiCall(ctx, req, api.cfg)
  738. loginRequired := user.IsGuest() && api.cfg.AuthRequireGuestsToLogin
  739. res := &apiv1.InitResponse{
  740. ShowFooter: api.cfg.ShowFooter,
  741. ShowNavigation: api.cfg.ShowNavigation,
  742. ShowNewVersions: api.cfg.ShowNewVersions,
  743. AvailableVersion: installationinfo.Runtime.AvailableVersion,
  744. CurrentVersion: installationinfo.Build.Version,
  745. PageTitle: api.cfg.PageTitle,
  746. SectionNavigationStyle: api.cfg.SectionNavigationStyle,
  747. DefaultIconForBack: api.cfg.DefaultIconForBack,
  748. EnableCustomJs: api.cfg.EnableCustomJs,
  749. AuthLoginUrl: api.cfg.AuthLoginUrl,
  750. AuthLocalLogin: api.cfg.AuthLocalUsers.Enabled,
  751. OAuth2Providers: buildPublicOAuth2ProvidersList(api.cfg),
  752. AdditionalLinks: buildAdditionalLinks(api.cfg.AdditionalNavigationLinks),
  753. StyleMods: api.cfg.StyleMods,
  754. RootDashboards: api.buildRootDashboards(user, api.cfg.Dashboards),
  755. AuthenticatedUser: user.Username,
  756. AuthenticatedUserProvider: user.Provider,
  757. EffectivePolicy: buildEffectivePolicy(user.EffectivePolicy),
  758. BannerMessage: api.cfg.BannerMessage,
  759. BannerCss: api.cfg.BannerCSS,
  760. ShowDiagnostics: user.EffectivePolicy.ShowDiagnostics,
  761. ShowLogList: user.EffectivePolicy.ShowLogList,
  762. LoginRequired: loginRequired,
  763. AvailableThemes: discoverAvailableThemes(api.cfg),
  764. ShowNavigateOnStartIcons: api.cfg.ShowNavigateOnStartIcons,
  765. }
  766. return connect.NewResponse(res), nil
  767. }
  768. // discoverAvailableThemes finds all available themes in the custom-webui/themes directory.
  769. // A theme is considered available if it has a theme.css file.
  770. func discoverAvailableThemes(cfg *config.Config) []string {
  771. configDir := cfg.GetDir()
  772. if configDir == "" {
  773. return []string{}
  774. }
  775. themesDir := path.Join(configDir, "custom-webui", "themes")
  776. entries, err := os.ReadDir(themesDir)
  777. if err != nil {
  778. log.WithFields(log.Fields{
  779. "themesDir": themesDir,
  780. "error": err,
  781. }).Tracef("Could not read themes directory")
  782. return []string{}
  783. }
  784. themes := collectValidThemes(themesDir, entries)
  785. sort.Strings(themes)
  786. return themes
  787. }
  788. // collectValidThemes collects theme names from directory entries that have a theme.css file.
  789. func collectValidThemes(themesDir string, entries []os.DirEntry) []string {
  790. var themes []string
  791. for _, entry := range entries {
  792. if themeName := getValidThemeName(themesDir, entry); themeName != "" {
  793. themes = append(themes, themeName)
  794. }
  795. }
  796. return themes
  797. }
  798. // getValidThemeName returns the theme name if the entry is a valid theme directory with theme.css, otherwise returns empty string.
  799. func getValidThemeName(themesDir string, entry os.DirEntry) string {
  800. if !entry.IsDir() {
  801. return ""
  802. }
  803. themeName := entry.Name()
  804. themeCssPath := path.Join(themesDir, themeName, "theme.css")
  805. if _, err := os.Stat(themeCssPath); err != nil {
  806. return ""
  807. }
  808. return themeName
  809. }
  810. func (api *oliveTinAPI) buildRootDashboards(user *authpublic.AuthenticatedUser, dashboards []*config.DashboardComponent) []string {
  811. var rootDashboards []string
  812. dashboardRenderRequest := api.createDashboardRenderRequest(user, "", "")
  813. api.addDefaultDashboardIfNeeded(&rootDashboards, dashboardRenderRequest)
  814. api.addCustomDashboards(&rootDashboards, dashboards, dashboardRenderRequest)
  815. return rootDashboards
  816. }
  817. func (api *oliveTinAPI) addDefaultDashboardIfNeeded(rootDashboards *[]string, rr *DashboardRenderRequest) {
  818. defaultDashboard := buildDefaultDashboard(rr)
  819. if defaultDashboard != nil && len(defaultDashboard.Contents) > 0 {
  820. log.Tracef("defaultDashboard: %+v", defaultDashboard.Contents)
  821. *rootDashboards = append(*rootDashboards, "Actions")
  822. }
  823. }
  824. func (api *oliveTinAPI) addCustomDashboards(rootDashboards *[]string, dashboards []*config.DashboardComponent, rr *DashboardRenderRequest) {
  825. for _, dashboard := range dashboards {
  826. // We have to build the dashboard response instead of just looping over config.dashboards,
  827. // because we need to check if the user has access to the dashboard
  828. db := renderDashboard(rr, dashboard.Title)
  829. if db != nil {
  830. *rootDashboards = append(*rootDashboards, dashboard.Title)
  831. }
  832. }
  833. }
  834. func buildPublicOAuth2ProvidersList(cfg *config.Config) []*apiv1.OAuth2Provider {
  835. var publicProviders []*apiv1.OAuth2Provider
  836. for providerKey, provider := range cfg.AuthOAuth2Providers {
  837. publicProviders = append(publicProviders, &apiv1.OAuth2Provider{
  838. Title: provider.Title,
  839. Icon: provider.Icon,
  840. Key: providerKey,
  841. })
  842. }
  843. sort.Slice(publicProviders, func(i, j int) bool {
  844. return publicProviders[i].Key < publicProviders[j].Key
  845. })
  846. return publicProviders
  847. }
  848. func buildAdditionalLinks(links []*config.NavigationLink) []*apiv1.AdditionalLink {
  849. var additionalLinks []*apiv1.AdditionalLink
  850. for _, link := range links {
  851. additionalLinks = append(additionalLinks, &apiv1.AdditionalLink{
  852. Title: link.Title,
  853. Url: link.Url,
  854. })
  855. }
  856. return additionalLinks
  857. }
  858. func (api *oliveTinAPI) OnOutputChunk(content []byte, executionTrackingId string) {
  859. toRemove := []*streamingClient{}
  860. for _, client := range api.copyOfStreamingClients() {
  861. select {
  862. case client.channel <- &apiv1.EventStreamResponse{
  863. Event: &apiv1.EventStreamResponse_OutputChunk{
  864. OutputChunk: &apiv1.EventOutputChunk{
  865. Output: string(content),
  866. ExecutionTrackingId: executionTrackingId,
  867. },
  868. },
  869. }:
  870. default:
  871. log.Warnf("EventStream: client channel is full, removing client")
  872. toRemove = append(toRemove, client)
  873. }
  874. }
  875. for _, client := range toRemove {
  876. api.removeClient(client)
  877. }
  878. }
  879. func (api *oliveTinAPI) GetEntities(ctx ctx.Context, req *connect.Request[apiv1.GetEntitiesRequest]) (*connect.Response[apiv1.GetEntitiesResponse], error) {
  880. user := auth.UserFromApiCall(ctx, req, api.cfg)
  881. if err := api.checkDashboardAccess(user); err != nil {
  882. return nil, err
  883. }
  884. entityMap := entities.GetEntities()
  885. entityNames := make([]string, 0, len(entityMap))
  886. for name := range entityMap {
  887. entityNames = append(entityNames, name)
  888. }
  889. sort.Strings(entityNames)
  890. entityDefinitions := make([]*apiv1.EntityDefinition, 0, len(entityNames))
  891. for _, name := range entityNames {
  892. def := &apiv1.EntityDefinition{
  893. Title: name,
  894. UsedOnDashboards: findDashboardsForEntity(name, api.cfg.Dashboards),
  895. Instances: buildSortedEntityInstances(name, entityMap[name]),
  896. }
  897. entityDefinitions = append(entityDefinitions, def)
  898. }
  899. res := &apiv1.GetEntitiesResponse{
  900. EntityDefinitions: entityDefinitions,
  901. }
  902. return connect.NewResponse(res), nil
  903. }
  904. func buildSortedEntityInstances(entityType string, entityInstances map[string]*entities.Entity) []*apiv1.Entity {
  905. instanceKeys := make([]string, 0, len(entityInstances))
  906. for key := range entityInstances {
  907. instanceKeys = append(instanceKeys, key)
  908. }
  909. sort.Strings(instanceKeys)
  910. instances := make([]*apiv1.Entity, 0, len(instanceKeys))
  911. for _, key := range instanceKeys {
  912. e := entityInstances[key]
  913. instances = append(instances, &apiv1.Entity{
  914. Title: e.Title,
  915. UniqueKey: e.UniqueKey,
  916. Type: entityType,
  917. })
  918. }
  919. return instances
  920. }
  921. func findDashboardsForEntity(entityTitle string, dashboards []*config.DashboardComponent) []string {
  922. var foundDashboards []string
  923. seen := make(map[string]bool)
  924. findEntityInComponents(entityTitle, "", dashboards, &foundDashboards, seen)
  925. return foundDashboards
  926. }
  927. func findEntityInComponents(entityTitle string, parentTitle string, components []*config.DashboardComponent, foundDashboards *[]string, seen map[string]bool) {
  928. for _, component := range components {
  929. if component.Entity == entityTitle {
  930. addEntityDashboard(component, parentTitle, foundDashboards, seen)
  931. }
  932. if len(component.Contents) > 0 {
  933. findEntityInComponents(entityTitle, component.Title, component.Contents, foundDashboards, seen)
  934. }
  935. }
  936. }
  937. func addEntityDashboard(component *config.DashboardComponent, parentTitle string, foundDashboards *[]string, seen map[string]bool) {
  938. if component.Type == "directory" {
  939. addEntityDirectory(component, foundDashboards, seen)
  940. } else {
  941. addParentDashboard(parentTitle, foundDashboards, seen)
  942. }
  943. }
  944. func addEntityDirectory(component *config.DashboardComponent, foundDashboards *[]string, seen map[string]bool) {
  945. dashboardTitle := component.Title + " [Entity Directory]"
  946. if !seen[dashboardTitle] {
  947. *foundDashboards = append(*foundDashboards, dashboardTitle)
  948. seen[dashboardTitle] = true
  949. seen[component.Title] = true
  950. }
  951. }
  952. func addParentDashboard(parentTitle string, foundDashboards *[]string, seen map[string]bool) {
  953. if parentTitle != "" && !seen[parentTitle] {
  954. *foundDashboards = append(*foundDashboards, parentTitle)
  955. seen[parentTitle] = true
  956. }
  957. }
  958. func findDirectoriesInEntityFieldsets(entityType string, dashboards []*config.DashboardComponent) []string {
  959. var directories []string
  960. for _, dashboard := range dashboards {
  961. findDirectoriesInEntityFieldsetsRecursive(entityType, dashboard, &directories)
  962. }
  963. return directories
  964. }
  965. func findDirectoriesInEntityFieldsetsRecursive(entityType string, component *config.DashboardComponent, directories *[]string) {
  966. if component.Entity == entityType {
  967. collectDirectoriesFromComponent(component, directories)
  968. }
  969. if len(component.Contents) > 0 {
  970. searchSubcomponentsForDirectories(entityType, component.Contents, directories)
  971. }
  972. }
  973. func collectDirectoriesFromComponent(component *config.DashboardComponent, directories *[]string) {
  974. for _, subitem := range component.Contents {
  975. if subitem.Type == "directory" {
  976. *directories = append(*directories, subitem.Title)
  977. }
  978. }
  979. }
  980. func searchSubcomponentsForDirectories(entityType string, contents []*config.DashboardComponent, directories *[]string) {
  981. for _, subitem := range contents {
  982. findDirectoriesInEntityFieldsetsRecursive(entityType, subitem, directories)
  983. }
  984. }
  985. func (api *oliveTinAPI) GetEntity(ctx ctx.Context, req *connect.Request[apiv1.GetEntityRequest]) (*connect.Response[apiv1.Entity], error) {
  986. user := auth.UserFromApiCall(ctx, req, api.cfg)
  987. if err := api.checkDashboardAccess(user); err != nil {
  988. return nil, err
  989. }
  990. instances := entities.GetEntityInstances(req.Msg.Type)
  991. if len(instances) == 0 {
  992. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("entity type %s not found", req.Msg.Type))
  993. }
  994. entity, ok := instances[req.Msg.UniqueKey]
  995. if !ok {
  996. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("entity with unique key %s not found in type %s", req.Msg.UniqueKey, req.Msg.Type))
  997. }
  998. res := buildEntityResponse(entity, req.Msg.Type, api.cfg.Dashboards)
  999. return connect.NewResponse(res), nil
  1000. }
  1001. func buildEntityResponse(entity *entities.Entity, entityType string, dashboards []*config.DashboardComponent) *apiv1.Entity {
  1002. res := &apiv1.Entity{
  1003. Title: entity.Title,
  1004. UniqueKey: entity.UniqueKey,
  1005. Type: entityType,
  1006. Directories: findDirectoriesInEntityFieldsets(entityType, dashboards),
  1007. Fields: serializeEntityFields(entity.Data),
  1008. }
  1009. return res
  1010. }
  1011. func serializeEntityFields(data any) map[string]string {
  1012. if data == nil {
  1013. return nil
  1014. }
  1015. dataMap, ok := data.(map[string]any)
  1016. if !ok {
  1017. return nil
  1018. }
  1019. fields := make(map[string]string)
  1020. for k, v := range dataMap {
  1021. fields[k] = fmt.Sprintf("%v", v)
  1022. }
  1023. return fields
  1024. }
  1025. func (api *oliveTinAPI) RestartAction(ctx ctx.Context, req *connect.Request[apiv1.RestartActionRequest]) (*connect.Response[apiv1.StartActionResponse], error) {
  1026. ret := &apiv1.StartActionResponse{
  1027. ExecutionTrackingId: req.Msg.ExecutionTrackingId,
  1028. }
  1029. var execReqLogEntry *executor.InternalLogEntry
  1030. execReqLogEntry, found := api.executor.GetLog(req.Msg.ExecutionTrackingId)
  1031. if !found {
  1032. log.Warnf("Restarting execution request not possible - not found by tracking ID: %v", req.Msg.ExecutionTrackingId)
  1033. return connect.NewResponse(ret), nil
  1034. }
  1035. log.Warnf("Restarting execution request by tracking ID: %v", req.Msg.ExecutionTrackingId)
  1036. action := execReqLogEntry.Binding.Action
  1037. if action == nil {
  1038. log.Warnf("Restarting execution request not possible - action not found: %v", execReqLogEntry.ActionTitle)
  1039. return connect.NewResponse(ret), nil
  1040. }
  1041. return api.StartAction(ctx, &connect.Request[apiv1.StartActionRequest]{
  1042. Msg: &apiv1.StartActionRequest{
  1043. // FIXME
  1044. UniqueTrackingId: req.Msg.ExecutionTrackingId,
  1045. },
  1046. })
  1047. }
  1048. func newServer(ex *executor.Executor) *oliveTinAPI {
  1049. server := oliveTinAPI{}
  1050. server.cfg = ex.Cfg
  1051. server.executor = ex
  1052. server.streamingClients = make(map[*streamingClient]struct{})
  1053. ex.AddListener(&server)
  1054. return &server
  1055. }
  1056. func GetNewHandler(ex *executor.Executor) (string, http.Handler) {
  1057. server := newServer(ex)
  1058. jsonOpt := connectproto.WithJSON(
  1059. protojson.MarshalOptions{
  1060. EmitUnpopulated: true, // https://github.com/OliveTin/OliveTin/issues/674
  1061. },
  1062. protojson.UnmarshalOptions{
  1063. DiscardUnknown: true,
  1064. },
  1065. )
  1066. return apiv1connect.NewOliveTinApiServiceHandler(server, jsonOpt)
  1067. }