api.go 51 KB

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