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