api.go 40 KB

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