api.go 42 KB

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