api.go 34 KB

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