api.go 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575
  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 := api.executor.GetLogTrackingIdsACL(api.cfg, user, req.Msg.StartOffset, pageSize, req.Msg.DateFilter)
  519. ret := &apiv1.GetLogsResponse{}
  520. for _, le := range logEntries {
  521. ret.Logs = append(ret.Logs, api.internalLogEntryToPb(le, user))
  522. }
  523. ret.CountRemaining = paging.CountRemaining
  524. ret.PageSize = paging.PageSize
  525. ret.TotalCount = paging.TotalCount
  526. ret.StartOffset = paging.StartOffset
  527. return connect.NewResponse(ret), nil
  528. }
  529. // isValidLogEntry checks if a log entry has all required fields populated.
  530. func isValidLogEntry(e *executor.InternalLogEntry) bool {
  531. return e != nil && e.Binding != nil && e.Binding.Action != nil
  532. }
  533. // isLogEntryAllowed checks if a log entry is allowed to be viewed by the user.
  534. func (api *oliveTinAPI) isLogEntryAllowed(e *executor.InternalLogEntry, user *authpublic.AuthenticatedUser) bool {
  535. if user == nil || !isValidLogEntry(e) {
  536. return false
  537. }
  538. return acl.IsAllowedLogs(api.cfg, user, e.Binding.Action)
  539. }
  540. // mayViewExecutionEvent returns whether the user is allowed to receive this execution event (for EventStream ACL).
  541. func (api *oliveTinAPI) mayViewExecutionEvent(entry *executor.InternalLogEntry, user *authpublic.AuthenticatedUser) bool {
  542. if user == nil {
  543. return false
  544. }
  545. return isValidLogEntry(entry) && api.isLogEntryAllowed(entry, user)
  546. }
  547. // buildEmptyPageResponse creates a response for an empty page.
  548. func buildEmptyPageResponse(page pageInfo) *apiv1.GetActionLogsResponse {
  549. return &apiv1.GetActionLogsResponse{
  550. CountRemaining: 0,
  551. PageSize: page.size,
  552. TotalCount: page.total,
  553. StartOffset: page.start,
  554. }
  555. }
  556. // calculateReversedIndices computes the reversed indices for newest-first pagination.
  557. func calculateReversedIndices(page pageInfo, filteredLen int) (int64, int64) {
  558. startIdx := page.total - page.end
  559. endIdx := page.total - page.start
  560. if startIdx < 0 {
  561. startIdx = 0
  562. }
  563. if endIdx > int64(filteredLen) {
  564. endIdx = int64(filteredLen)
  565. }
  566. return startIdx, endIdx
  567. }
  568. // buildActionLogsResponse builds the response with paginated log entries (newest first).
  569. func (api *oliveTinAPI) buildActionLogsResponse(filtered []*executor.InternalLogEntry, page pageInfo, user *authpublic.AuthenticatedUser) *apiv1.GetActionLogsResponse {
  570. startIdx, endIdx := calculateReversedIndices(page, len(filtered))
  571. ret := &apiv1.GetActionLogsResponse{}
  572. chunk := filtered[int(startIdx):int(endIdx)]
  573. for i := len(chunk) - 1; i >= 0; i-- {
  574. ret.Logs = append(ret.Logs, api.internalLogEntryToPb(chunk[i], user))
  575. }
  576. ret.CountRemaining = page.start
  577. ret.PageSize = page.size
  578. ret.TotalCount = page.total
  579. ret.StartOffset = page.start
  580. return ret
  581. }
  582. func (api *oliveTinAPI) GetActionLogs(ctx ctx.Context, req *connect.Request[apiv1.GetActionLogsRequest]) (*connect.Response[apiv1.GetActionLogsResponse], error) {
  583. user := auth.UserFromApiCall(ctx, req, api.cfg)
  584. if err := api.checkDashboardAccess(user); err != nil {
  585. return nil, err
  586. }
  587. filtered := api.filterLogsByACL(api.executor.GetLogsByBindingId(req.Msg.ActionId), user)
  588. page := paginate(int64(len(filtered)), api.cfg.LogHistoryPageSize, req.Msg.StartOffset)
  589. if page.empty {
  590. return connect.NewResponse(buildEmptyPageResponse(page)), nil
  591. }
  592. return connect.NewResponse(api.buildActionLogsResponse(filtered, page, user)), nil
  593. }
  594. func (api *oliveTinAPI) filterLogsByACL(entries []*executor.InternalLogEntry, user *authpublic.AuthenticatedUser) []*executor.InternalLogEntry {
  595. filtered := make([]*executor.InternalLogEntry, 0, len(entries))
  596. for _, e := range entries {
  597. if !isValidLogEntry(e) {
  598. continue
  599. }
  600. if api.isLogEntryAllowed(e, user) {
  601. filtered = append(filtered, e)
  602. }
  603. }
  604. return filtered
  605. }
  606. type pageInfo struct {
  607. total int64
  608. size int64
  609. start int64
  610. end int64
  611. empty bool
  612. }
  613. func paginate(total int64, size int64, start int64) pageInfo {
  614. if start < 0 {
  615. start = 0
  616. }
  617. if start >= total {
  618. return pageInfo{total: total, size: size, start: start, end: start, empty: true}
  619. }
  620. end := start + size
  621. if end > total {
  622. end = total
  623. }
  624. return pageInfo{total: total, size: size, start: start, end: end, empty: false}
  625. }
  626. /*
  627. This function is ONLY a helper for the UI - the arguments are validated properly
  628. on the StartAction -> Executor chain. This is here basically to provide helpful
  629. error messages more quickly before starting the action.
  630. It uses the same validation logic as the executor, including mangling argument
  631. values (e.g., datetime formatting, checkbox title-to-value conversion).
  632. */
  633. func (api *oliveTinAPI) argumentNotFoundForValidation(msg *apiv1.ValidateArgumentTypeRequest) bool {
  634. if msg.BindingId == "" || msg.ArgumentName == "" {
  635. return false
  636. }
  637. arg, _ := api.findArgumentForValidation(msg.BindingId, msg.ArgumentName)
  638. return arg == nil
  639. }
  640. func (api *oliveTinAPI) validateArgumentTypeBindingAccess(user *authpublic.AuthenticatedUser, msg *apiv1.ValidateArgumentTypeRequest) error {
  641. if msg == nil || msg.BindingId == "" {
  642. return nil
  643. }
  644. return api.errUnlessUserMayValidateArgumentTypeForBinding(user, msg.BindingId)
  645. }
  646. func (api *oliveTinAPI) errUnlessUserMayValidateArgumentTypeForBinding(user *authpublic.AuthenticatedUser, bindingID string) error {
  647. binding := api.executor.FindBindingByID(bindingID)
  648. if binding == nil || binding.Action == nil {
  649. return connect.NewError(connect.CodeNotFound, fmt.Errorf("action or argument not found for binding ID %s", bindingID))
  650. }
  651. if !api.userCanViewAction(user, binding.Action) {
  652. return connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
  653. }
  654. return nil
  655. }
  656. func (api *oliveTinAPI) ValidateArgumentType(ctx ctx.Context, req *connect.Request[apiv1.ValidateArgumentTypeRequest]) (*connect.Response[apiv1.ValidateArgumentTypeResponse], error) {
  657. user := auth.UserFromApiCall(ctx, req, api.cfg)
  658. if err := api.checkDashboardAccess(user); err != nil {
  659. return nil, err
  660. }
  661. if err := api.validateArgumentTypeBindingAccess(user, req.Msg); err != nil {
  662. return nil, err
  663. }
  664. if api.argumentNotFoundForValidation(req.Msg) {
  665. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action or argument not found for binding ID %s", req.Msg.BindingId))
  666. }
  667. return api.validateArgumentTypeConnectResponse(req.Msg)
  668. }
  669. func (api *oliveTinAPI) validateArgumentTypeConnectResponse(msg *apiv1.ValidateArgumentTypeRequest) (*connect.Response[apiv1.ValidateArgumentTypeResponse], error) {
  670. err := api.validateArgumentTypeInternal(msg)
  671. desc := ""
  672. if err != nil {
  673. desc = err.Error()
  674. }
  675. return connect.NewResponse(&apiv1.ValidateArgumentTypeResponse{
  676. Valid: err == nil,
  677. Description: desc,
  678. }), nil
  679. }
  680. func (api *oliveTinAPI) validateArgumentTypeInternal(msg *apiv1.ValidateArgumentTypeRequest) error {
  681. if msg.BindingId == "" || msg.ArgumentName == "" {
  682. return executor.TypeSafetyCheck("", msg.Value, msg.Type)
  683. }
  684. arg, action := api.findArgumentForValidation(msg.BindingId, msg.ArgumentName)
  685. if arg == nil {
  686. return fmt.Errorf("argument not found")
  687. }
  688. return executor.ValidateArgument(arg, msg.Value, action)
  689. }
  690. func (api *oliveTinAPI) findArgumentForValidation(bindingId string, argumentName string) (*config.ActionArgument, *config.Action) {
  691. binding := api.executor.FindBindingByID(bindingId)
  692. if binding == nil || binding.Action == nil {
  693. return nil, nil
  694. }
  695. arg := api.findArgumentByName(binding.Action, argumentName)
  696. return arg, binding.Action
  697. }
  698. func (api *oliveTinAPI) findArgumentByName(action *config.Action, name string) *config.ActionArgument {
  699. for i := range action.Arguments {
  700. if action.Arguments[i].Name == name {
  701. return &action.Arguments[i]
  702. }
  703. }
  704. return nil
  705. }
  706. func (api *oliveTinAPI) WhoAmI(ctx ctx.Context, req *connect.Request[apiv1.WhoAmIRequest]) (*connect.Response[apiv1.WhoAmIResponse], error) {
  707. user := auth.UserFromApiCall(ctx, req, api.cfg)
  708. if err := api.checkDashboardAccess(user); err != nil {
  709. return nil, err
  710. }
  711. res := &apiv1.WhoAmIResponse{
  712. AuthenticatedUser: user.Username,
  713. Usergroup: user.UsergroupLine,
  714. Provider: user.Provider,
  715. Sid: user.SID,
  716. Acls: user.Acls,
  717. }
  718. return connect.NewResponse(res), nil
  719. }
  720. func (api *oliveTinAPI) SosReport(ctx ctx.Context, req *connect.Request[apiv1.SosReportRequest]) (*connect.Response[apiv1.SosReportResponse], error) {
  721. user := auth.UserFromApiCall(ctx, req, api.cfg)
  722. redactVersion := !user.EffectivePolicy.ShowVersionNumber
  723. sos := installationinfo.GetSosReport(redactVersion)
  724. if !api.cfg.InsecureAllowDumpSos {
  725. log.Info(sos)
  726. 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."
  727. }
  728. ret := &apiv1.SosReportResponse{
  729. Alert: sos,
  730. }
  731. return connect.NewResponse(ret), nil
  732. }
  733. func (api *oliveTinAPI) DumpVars(ctx ctx.Context, req *connect.Request[apiv1.DumpVarsRequest]) (*connect.Response[apiv1.DumpVarsResponse], error) {
  734. res := &apiv1.DumpVarsResponse{}
  735. if !api.cfg.InsecureAllowDumpVars {
  736. res.Alert = "Dumping variables is not allowed by default because it is insecure."
  737. return connect.NewResponse(res), nil
  738. }
  739. jsonstring, err := json.MarshalIndent(tpl.GetNewGeneralTemplateContext(), "", " ")
  740. if err != nil {
  741. log.WithError(err).Error("DumpVars: failed to marshal template context from GetNewGeneralTemplateContext")
  742. return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("dump vars: marshal template context: %w", err))
  743. }
  744. fmt.Printf("%s", jsonstring)
  745. res.Alert = "Dumping variables has been enabled in the configuration. Please set InsecureAllowDumpVars = false again after you don't need it anymore"
  746. return connect.NewResponse(res), nil
  747. }
  748. func debugBindingActionTitle(binding *executor.ActionBinding) string {
  749. if binding == nil || binding.Action == nil {
  750. return ""
  751. }
  752. return binding.Action.Title
  753. }
  754. func (api *oliveTinAPI) DumpPublicIdActionMap(ctx ctx.Context, req *connect.Request[apiv1.DumpPublicIdActionMapRequest]) (*connect.Response[apiv1.DumpPublicIdActionMapResponse], error) {
  755. res := &apiv1.DumpPublicIdActionMapResponse{}
  756. res.Contents = make(map[string]*apiv1.DebugBinding)
  757. if !api.cfg.InsecureAllowDumpActionMap {
  758. res.Alert = "Dumping Public IDs is disallowed."
  759. return connect.NewResponse(res), nil
  760. }
  761. api.executor.MapActionBindingsLock.RLock()
  762. for k, v := range api.executor.MapActionBindings {
  763. res.Contents[k] = &apiv1.DebugBinding{
  764. ActionTitle: debugBindingActionTitle(v),
  765. }
  766. }
  767. api.executor.MapActionBindingsLock.RUnlock()
  768. res.Alert = "Dumping variables has been enabled in the configuration. Please set InsecureAllowDumpActionMap = false again after you don't need it anymore"
  769. return connect.NewResponse(res), nil
  770. }
  771. func (api *oliveTinAPI) GetReadyz(ctx ctx.Context, req *connect.Request[apiv1.GetReadyzRequest]) (*connect.Response[apiv1.GetReadyzResponse], error) {
  772. res := &apiv1.GetReadyzResponse{
  773. Status: "OK",
  774. }
  775. return connect.NewResponse(res), nil
  776. }
  777. func (api *oliveTinAPI) EventStream(ctx ctx.Context, req *connect.Request[apiv1.EventStreamRequest], srv *connect.ServerStream[apiv1.EventStreamResponse]) error {
  778. log.Debugf("EventStream: %v", req.Msg)
  779. // Set X-Accel-Buffering header to disable nginx buffering for this stream
  780. // https://github.com/OliveTin/OliveTin/issues/765
  781. srv.ResponseHeader().Set("X-Accel-Buffering", "no")
  782. user := auth.UserFromApiCall(ctx, req, api.cfg)
  783. if err := api.checkDashboardAccess(user); err != nil {
  784. return err
  785. }
  786. client := &streamingClient{
  787. channel: make(chan *apiv1.EventStreamResponse, 10), // Buffered channel to hold Events
  788. AuthenticatedUser: user,
  789. heartbeatStop: make(chan struct{}),
  790. heartbeatDone: make(chan struct{}),
  791. }
  792. log.WithFields(log.Fields{
  793. "authenticatedUser": user.Username,
  794. }).Debugf("EventStream: client connected")
  795. api.streamingClientsMutex.Lock()
  796. api.streamingClients[client] = struct{}{}
  797. api.streamingClientsMutex.Unlock()
  798. go api.sendEventStreamHeartbeats(client)
  799. // loop over client channel and send events to connectedClient
  800. for msg := range client.channel {
  801. log.Debugf("Sending event to client: %v", msg)
  802. if err := srv.Send(msg); err != nil {
  803. log.Errorf("Error sending event to client: %v", err)
  804. // Remove disconnected client from the list
  805. api.removeClient(client)
  806. break
  807. }
  808. }
  809. log.Infof("EventStream: client disconnected")
  810. return nil
  811. }
  812. func (api *oliveTinAPI) sendEventStreamHeartbeats(client *streamingClient) {
  813. defer close(client.heartbeatDone)
  814. if !api.sendEventStreamHeartbeat(client) {
  815. return
  816. }
  817. ticker := time.NewTicker(10 * time.Second)
  818. defer ticker.Stop()
  819. api.runEventStreamHeartbeatLoop(client, ticker)
  820. }
  821. func (api *oliveTinAPI) runEventStreamHeartbeatLoop(client *streamingClient, ticker *time.Ticker) {
  822. for {
  823. if api.waitEventStreamHeartbeatOrDone(client.heartbeatStop, ticker) {
  824. return
  825. }
  826. if !api.sendEventStreamHeartbeat(client) {
  827. return
  828. }
  829. }
  830. }
  831. func (api *oliveTinAPI) waitEventStreamHeartbeatOrDone(done <-chan struct{}, ticker *time.Ticker) bool {
  832. select {
  833. case <-done:
  834. return true
  835. case <-ticker.C:
  836. return false
  837. }
  838. }
  839. func (api *oliveTinAPI) sendEventStreamHeartbeat(client *streamingClient) bool {
  840. msg := &apiv1.EventStreamResponse{
  841. Event: &apiv1.EventStreamResponse_Heartbeat{
  842. Heartbeat: &apiv1.EventHeartbeat{},
  843. },
  844. }
  845. return api.trySendEventToClient(client, msg)
  846. }
  847. func (api *oliveTinAPI) removeClient(clientToRemove *streamingClient) {
  848. if clientToRemove == nil {
  849. return
  850. }
  851. api.streamingClientsMutex.Lock()
  852. if _, exists := api.streamingClients[clientToRemove]; !exists {
  853. api.streamingClientsMutex.Unlock()
  854. return
  855. }
  856. delete(api.streamingClients, clientToRemove)
  857. api.streamingClientsMutex.Unlock()
  858. clientToRemove.stopHeartbeat()
  859. close(clientToRemove.channel)
  860. }
  861. func (api *oliveTinAPI) OnActionMapRebuilt() {
  862. toRemove := []*streamingClient{}
  863. for _, client := range api.copyOfStreamingClients() {
  864. msg := &apiv1.EventStreamResponse{
  865. Event: &apiv1.EventStreamResponse_ConfigChanged{
  866. ConfigChanged: &apiv1.EventConfigChanged{},
  867. },
  868. }
  869. if !api.trySendEventToClient(client, msg) {
  870. toRemove = append(toRemove, client)
  871. }
  872. }
  873. for _, client := range toRemove {
  874. api.removeClient(client)
  875. }
  876. }
  877. func (api *oliveTinAPI) OnExecutionStarted(ex *executor.InternalLogEntry) {
  878. toRemove := []*streamingClient{}
  879. for _, client := range api.copyOfStreamingClients() {
  880. api.maybeSendExecutionStarted(client, ex, &toRemove)
  881. }
  882. for _, client := range toRemove {
  883. api.removeClient(client)
  884. }
  885. }
  886. func (api *oliveTinAPI) maybeSendExecutionStarted(client *streamingClient, ex *executor.InternalLogEntry, toRemove *[]*streamingClient) {
  887. if client == nil {
  888. return
  889. }
  890. if !api.mayViewExecutionEvent(ex, client.AuthenticatedUser) {
  891. return
  892. }
  893. msg := &apiv1.EventStreamResponse{
  894. Event: &apiv1.EventStreamResponse_ExecutionStarted{
  895. ExecutionStarted: &apiv1.EventExecutionStarted{
  896. LogEntry: api.internalLogEntryToPb(ex, client.AuthenticatedUser),
  897. },
  898. },
  899. }
  900. if !api.trySendEventToClient(client, msg) {
  901. *toRemove = append(*toRemove, client)
  902. }
  903. }
  904. func (api *oliveTinAPI) OnExecutionFinished(ile *executor.InternalLogEntry) {
  905. toRemove := []*streamingClient{}
  906. for _, client := range api.copyOfStreamingClients() {
  907. api.maybeSendExecutionFinished(client, ile, &toRemove)
  908. }
  909. for _, client := range toRemove {
  910. api.removeClient(client)
  911. }
  912. }
  913. func (api *oliveTinAPI) maybeSendExecutionFinished(client *streamingClient, ile *executor.InternalLogEntry, toRemove *[]*streamingClient) {
  914. if client == nil {
  915. return
  916. }
  917. if !api.mayViewExecutionEvent(ile, client.AuthenticatedUser) {
  918. return
  919. }
  920. msg := &apiv1.EventStreamResponse{
  921. Event: &apiv1.EventStreamResponse_ExecutionFinished{
  922. ExecutionFinished: &apiv1.EventExecutionFinished{
  923. LogEntry: api.internalLogEntryToPb(ile, client.AuthenticatedUser),
  924. },
  925. },
  926. }
  927. if !api.trySendEventToClient(client, msg) {
  928. *toRemove = append(*toRemove, client)
  929. }
  930. }
  931. func (api *oliveTinAPI) GetDiagnostics(ctx ctx.Context, req *connect.Request[apiv1.GetDiagnosticsRequest]) (*connect.Response[apiv1.GetDiagnosticsResponse], error) {
  932. user := auth.UserFromApiCall(ctx, req, api.cfg)
  933. if err := api.checkDashboardAccess(user); err != nil {
  934. return nil, err
  935. }
  936. if !user.EffectivePolicy.ShowDiagnostics {
  937. return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("diagnostics are not available for your account"))
  938. }
  939. res := &apiv1.GetDiagnosticsResponse{
  940. SshFoundKey: installationinfo.Runtime.SshFoundKey,
  941. SshFoundConfig: installationinfo.Runtime.SshFoundConfig,
  942. }
  943. return connect.NewResponse(res), nil
  944. }
  945. func (api *oliveTinAPI) Init(ctx ctx.Context, req *connect.Request[apiv1.InitRequest]) (*connect.Response[apiv1.InitResponse], error) {
  946. user := auth.UserFromApiCall(ctx, req, api.cfg)
  947. loginRequired := user.IsGuest() && api.cfg.AuthRequireGuestsToLogin
  948. showVersion := user.EffectivePolicy.ShowVersionNumber
  949. currentVersion := ""
  950. availableVersion := ""
  951. if showVersion {
  952. currentVersion = installationinfo.Build.Version
  953. availableVersion = installationinfo.Runtime.AvailableVersion
  954. }
  955. res := &apiv1.InitResponse{
  956. ShowFooter: api.cfg.ShowFooter,
  957. ShowNavigation: api.cfg.ShowNavigation,
  958. ShowNewVersions: showVersion && api.cfg.ShowNewVersions,
  959. AvailableVersion: availableVersion,
  960. CurrentVersion: currentVersion,
  961. PageTitle: api.cfg.PageTitle,
  962. SectionNavigationStyle: api.cfg.SectionNavigationStyle,
  963. DefaultIconForBack: api.cfg.DefaultIconForBack,
  964. EnableCustomJs: api.cfg.EnableCustomJs,
  965. AuthLoginUrl: api.cfg.AuthLoginUrl,
  966. AuthLocalLogin: api.cfg.AuthLocalUsers.Enabled,
  967. OAuth2Providers: buildPublicOAuth2ProvidersList(api.cfg),
  968. AdditionalLinks: buildAdditionalLinks(api.cfg.AdditionalNavigationLinks),
  969. StyleMods: api.cfg.StyleMods,
  970. RootDashboards: api.buildRootDashboards(user, api.cfg.Dashboards),
  971. AuthenticatedUser: user.Username,
  972. AuthenticatedUserProvider: user.Provider,
  973. EffectivePolicy: buildEffectivePolicy(user.EffectivePolicy),
  974. BannerMessage: api.cfg.BannerMessage,
  975. BannerCss: api.cfg.BannerCSS,
  976. ShowDiagnostics: user.EffectivePolicy.ShowDiagnostics,
  977. ShowLogList: user.EffectivePolicy.ShowLogList,
  978. LoginRequired: loginRequired,
  979. AvailableThemes: discoverAvailableThemes(api.cfg),
  980. ShowNavigateOnStartIcons: api.cfg.ShowNavigateOnStartIcons,
  981. }
  982. return connect.NewResponse(res), nil
  983. }
  984. // discoverAvailableThemes finds all available themes in the custom-webui/themes directory.
  985. // A theme is considered available if it has a theme.css file.
  986. func discoverAvailableThemes(cfg *config.Config) []string {
  987. configDir := cfg.GetDir()
  988. if configDir == "" {
  989. return []string{}
  990. }
  991. themesDir := path.Join(configDir, "custom-webui", "themes")
  992. entries, err := os.ReadDir(themesDir)
  993. if err != nil {
  994. log.WithFields(log.Fields{
  995. "themesDir": themesDir,
  996. "error": err,
  997. }).Tracef("Could not read themes directory")
  998. return []string{}
  999. }
  1000. themes := collectValidThemes(themesDir, entries)
  1001. sort.Strings(themes)
  1002. return themes
  1003. }
  1004. // collectValidThemes collects theme names from directory entries that have a theme.css file.
  1005. func collectValidThemes(themesDir string, entries []os.DirEntry) []string {
  1006. var themes []string
  1007. for _, entry := range entries {
  1008. if themeName := getValidThemeName(themesDir, entry); themeName != "" {
  1009. themes = append(themes, themeName)
  1010. }
  1011. }
  1012. return themes
  1013. }
  1014. // getValidThemeName returns the theme name if the entry is a valid theme directory with theme.css, otherwise returns empty string.
  1015. func getValidThemeName(themesDir string, entry os.DirEntry) string {
  1016. if !entry.IsDir() {
  1017. return ""
  1018. }
  1019. themeName := entry.Name()
  1020. themeCssPath := path.Join(themesDir, themeName, "theme.css")
  1021. if _, err := os.Stat(themeCssPath); err != nil {
  1022. return ""
  1023. }
  1024. return themeName
  1025. }
  1026. func (api *oliveTinAPI) buildRootDashboards(user *authpublic.AuthenticatedUser, dashboards []*config.DashboardComponent) []string {
  1027. var rootDashboards []string
  1028. dashboardRenderRequest := api.createDashboardRenderRequest(user, "", "")
  1029. api.addDefaultDashboardIfNeeded(&rootDashboards, dashboardRenderRequest)
  1030. api.addCustomDashboards(&rootDashboards, dashboards, dashboardRenderRequest)
  1031. return rootDashboards
  1032. }
  1033. func (api *oliveTinAPI) addDefaultDashboardIfNeeded(rootDashboards *[]string, rr *DashboardRenderRequest) {
  1034. defaultDashboard := buildDefaultDashboard(rr)
  1035. if defaultDashboard != nil && len(defaultDashboard.Contents) > 0 {
  1036. log.Tracef("defaultDashboard: %+v", defaultDashboard.Contents)
  1037. *rootDashboards = append(*rootDashboards, "Actions")
  1038. }
  1039. }
  1040. func (api *oliveTinAPI) addCustomDashboards(rootDashboards *[]string, dashboards []*config.DashboardComponent, rr *DashboardRenderRequest) {
  1041. for _, dashboard := range dashboards {
  1042. // We have to build the dashboard response instead of just looping over config.dashboards,
  1043. // because we need to check if the user has access to the dashboard
  1044. db := renderDashboard(rr, dashboard.Title)
  1045. if db != nil {
  1046. *rootDashboards = append(*rootDashboards, dashboard.Title)
  1047. }
  1048. }
  1049. }
  1050. func buildPublicOAuth2ProvidersList(cfg *config.Config) []*apiv1.OAuth2Provider {
  1051. var publicProviders []*apiv1.OAuth2Provider
  1052. for providerKey, provider := range cfg.AuthOAuth2Providers {
  1053. publicProviders = append(publicProviders, &apiv1.OAuth2Provider{
  1054. Title: provider.Title,
  1055. Icon: provider.Icon,
  1056. Key: providerKey,
  1057. })
  1058. }
  1059. sort.Slice(publicProviders, func(i, j int) bool {
  1060. return publicProviders[i].Key < publicProviders[j].Key
  1061. })
  1062. return publicProviders
  1063. }
  1064. func buildAdditionalLinks(links []*config.NavigationLink) []*apiv1.AdditionalLink {
  1065. var additionalLinks []*apiv1.AdditionalLink
  1066. for _, link := range links {
  1067. additionalLinks = append(additionalLinks, &apiv1.AdditionalLink{
  1068. Title: link.Title,
  1069. Url: link.Url,
  1070. })
  1071. }
  1072. return additionalLinks
  1073. }
  1074. func (api *oliveTinAPI) OnOutputChunk(content []byte, executionTrackingId string) {
  1075. entry := api.getValidLogEntryForStreaming(executionTrackingId)
  1076. if entry == nil {
  1077. return
  1078. }
  1079. msg := &apiv1.EventStreamResponse{
  1080. Event: &apiv1.EventStreamResponse_OutputChunk{
  1081. OutputChunk: &apiv1.EventOutputChunk{
  1082. Output: string(content),
  1083. ExecutionTrackingId: executionTrackingId,
  1084. },
  1085. },
  1086. }
  1087. toRemove := []*streamingClient{}
  1088. for _, client := range api.copyOfStreamingClients() {
  1089. api.maybeSendOutputChunk(client, entry, msg, &toRemove)
  1090. }
  1091. for _, client := range toRemove {
  1092. api.removeClient(client)
  1093. }
  1094. }
  1095. func (api *oliveTinAPI) getValidLogEntryForStreaming(executionTrackingId string) *executor.InternalLogEntry {
  1096. entry, ok := api.executor.GetLog(executionTrackingId)
  1097. if !ok || !isValidLogEntry(entry) {
  1098. return nil
  1099. }
  1100. return entry
  1101. }
  1102. func (api *oliveTinAPI) maybeSendOutputChunk(client *streamingClient, entry *executor.InternalLogEntry, msg *apiv1.EventStreamResponse, toRemove *[]*streamingClient) {
  1103. if client == nil {
  1104. return
  1105. }
  1106. if !api.mayViewExecutionEvent(entry, client.AuthenticatedUser) {
  1107. return
  1108. }
  1109. if !api.trySendEventToClient(client, msg) {
  1110. *toRemove = append(*toRemove, client)
  1111. }
  1112. }
  1113. func (api *oliveTinAPI) GetEntities(ctx ctx.Context, req *connect.Request[apiv1.GetEntitiesRequest]) (*connect.Response[apiv1.GetEntitiesResponse], error) {
  1114. user := auth.UserFromApiCall(ctx, req, api.cfg)
  1115. if err := api.checkDashboardAccess(user); err != nil {
  1116. return nil, err
  1117. }
  1118. entityMap := entities.GetEntities()
  1119. entityNames := make([]string, 0, len(entityMap))
  1120. for name := range entityMap {
  1121. entityNames = append(entityNames, name)
  1122. }
  1123. sort.Strings(entityNames)
  1124. entityDefinitions := make([]*apiv1.EntityDefinition, 0, len(entityNames))
  1125. for _, name := range entityNames {
  1126. def := &apiv1.EntityDefinition{
  1127. Title: name,
  1128. UsedOnDashboards: findDashboardsForEntity(name, api.cfg.Dashboards),
  1129. Instances: buildSortedEntityInstances(name, entityMap[name]),
  1130. }
  1131. entityDefinitions = append(entityDefinitions, def)
  1132. }
  1133. res := &apiv1.GetEntitiesResponse{
  1134. EntityDefinitions: entityDefinitions,
  1135. }
  1136. return connect.NewResponse(res), nil
  1137. }
  1138. func buildSortedEntityInstances(entityType string, entityInstances map[string]*entities.Entity) []*apiv1.Entity {
  1139. instanceKeys := make([]string, 0, len(entityInstances))
  1140. for key := range entityInstances {
  1141. instanceKeys = append(instanceKeys, key)
  1142. }
  1143. sort.Strings(instanceKeys)
  1144. instances := make([]*apiv1.Entity, 0, len(instanceKeys))
  1145. for _, key := range instanceKeys {
  1146. e := entityInstances[key]
  1147. instances = append(instances, &apiv1.Entity{
  1148. Title: e.Title,
  1149. UniqueKey: e.UniqueKey,
  1150. Type: entityType,
  1151. })
  1152. }
  1153. return instances
  1154. }
  1155. func findDashboardsForEntity(entityTitle string, dashboards []*config.DashboardComponent) []string {
  1156. var foundDashboards []string
  1157. seen := make(map[string]bool)
  1158. findEntityInComponents(entityTitle, "", dashboards, &foundDashboards, seen)
  1159. return foundDashboards
  1160. }
  1161. func findEntityInComponents(entityTitle string, parentTitle string, components []*config.DashboardComponent, foundDashboards *[]string, seen map[string]bool) {
  1162. for _, component := range components {
  1163. if component.Entity == entityTitle {
  1164. addEntityDashboard(component, parentTitle, foundDashboards, seen)
  1165. }
  1166. if len(component.Contents) > 0 {
  1167. findEntityInComponents(entityTitle, component.Title, component.Contents, foundDashboards, seen)
  1168. }
  1169. }
  1170. }
  1171. func addEntityDashboard(component *config.DashboardComponent, parentTitle string, foundDashboards *[]string, seen map[string]bool) {
  1172. if component.Type == "directory" {
  1173. addEntityDirectory(component, foundDashboards, seen)
  1174. } else {
  1175. addParentDashboard(parentTitle, foundDashboards, seen)
  1176. }
  1177. }
  1178. func addEntityDirectory(component *config.DashboardComponent, foundDashboards *[]string, seen map[string]bool) {
  1179. dashboardTitle := component.Title + " [Entity Directory]"
  1180. if !seen[dashboardTitle] {
  1181. *foundDashboards = append(*foundDashboards, dashboardTitle)
  1182. seen[dashboardTitle] = true
  1183. seen[component.Title] = true
  1184. }
  1185. }
  1186. func addParentDashboard(parentTitle string, foundDashboards *[]string, seen map[string]bool) {
  1187. if parentTitle != "" && !seen[parentTitle] {
  1188. *foundDashboards = append(*foundDashboards, parentTitle)
  1189. seen[parentTitle] = true
  1190. }
  1191. }
  1192. func findDirectoriesInEntityFieldsets(entityType string, dashboards []*config.DashboardComponent) []string {
  1193. var directories []string
  1194. for _, dashboard := range dashboards {
  1195. findDirectoriesInEntityFieldsetsRecursive(entityType, dashboard, &directories)
  1196. }
  1197. return directories
  1198. }
  1199. func findDirectoriesInEntityFieldsetsRecursive(entityType string, component *config.DashboardComponent, directories *[]string) {
  1200. if component.Entity == entityType {
  1201. collectDirectoriesFromComponent(component, directories)
  1202. }
  1203. if len(component.Contents) > 0 {
  1204. searchSubcomponentsForDirectories(entityType, component.Contents, directories)
  1205. }
  1206. }
  1207. func collectDirectoriesFromComponent(component *config.DashboardComponent, directories *[]string) {
  1208. for _, subitem := range component.Contents {
  1209. if subitem.Type == "directory" {
  1210. *directories = append(*directories, subitem.Title)
  1211. }
  1212. }
  1213. }
  1214. func searchSubcomponentsForDirectories(entityType string, contents []*config.DashboardComponent, directories *[]string) {
  1215. for _, subitem := range contents {
  1216. findDirectoriesInEntityFieldsetsRecursive(entityType, subitem, directories)
  1217. }
  1218. }
  1219. func (api *oliveTinAPI) GetEntity(ctx ctx.Context, req *connect.Request[apiv1.GetEntityRequest]) (*connect.Response[apiv1.Entity], error) {
  1220. user := auth.UserFromApiCall(ctx, req, api.cfg)
  1221. if err := api.checkDashboardAccess(user); err != nil {
  1222. return nil, err
  1223. }
  1224. instances := entities.GetEntityInstances(req.Msg.Type)
  1225. if len(instances) == 0 {
  1226. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("entity type %s not found", req.Msg.Type))
  1227. }
  1228. entity, ok := instances[req.Msg.UniqueKey]
  1229. if !ok {
  1230. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("entity with unique key %s not found in type %s", req.Msg.UniqueKey, req.Msg.Type))
  1231. }
  1232. res := buildEntityResponse(entity, req.Msg.Type, api.cfg.Dashboards)
  1233. return connect.NewResponse(res), nil
  1234. }
  1235. func buildEntityResponse(entity *entities.Entity, entityType string, dashboards []*config.DashboardComponent) *apiv1.Entity {
  1236. res := &apiv1.Entity{
  1237. Title: entity.Title,
  1238. UniqueKey: entity.UniqueKey,
  1239. Type: entityType,
  1240. Directories: findDirectoriesInEntityFieldsets(entityType, dashboards),
  1241. Fields: serializeEntityFields(entity.Data),
  1242. }
  1243. return res
  1244. }
  1245. func serializeEntityFields(data any) map[string]string {
  1246. if data == nil {
  1247. return nil
  1248. }
  1249. dataMap, ok := data.(map[string]any)
  1250. if !ok {
  1251. return nil
  1252. }
  1253. fields := make(map[string]string)
  1254. for k, v := range dataMap {
  1255. fields[k] = fmt.Sprintf("%v", v)
  1256. }
  1257. return fields
  1258. }
  1259. func (api *oliveTinAPI) RestartAction(ctx ctx.Context, req *connect.Request[apiv1.RestartActionRequest]) (*connect.Response[apiv1.StartActionResponse], error) {
  1260. ret := &apiv1.StartActionResponse{
  1261. ExecutionTrackingId: req.Msg.ExecutionTrackingId,
  1262. }
  1263. execReqLogEntry, found := api.executor.GetLog(req.Msg.ExecutionTrackingId)
  1264. if !found {
  1265. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found for tracking ID %s", req.Msg.ExecutionTrackingId))
  1266. }
  1267. if execReqLogEntry.Binding == nil {
  1268. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("log entry has no binding for tracking ID %s", req.Msg.ExecutionTrackingId))
  1269. }
  1270. action := execReqLogEntry.Binding.Action
  1271. if action == nil {
  1272. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action not found for tracking ID %s", req.Msg.ExecutionTrackingId))
  1273. }
  1274. authenticatedUser := auth.UserFromApiCall(ctx, req, api.cfg)
  1275. // TrackingID is deliberately not passed to the executor, so that it generates a new one for the restarted execution.
  1276. // This is because the old execution (identified by the old TrackingID) is already used.
  1277. execReq := executor.ExecutionRequest{
  1278. Binding: execReqLogEntry.Binding,
  1279. Arguments: make(map[string]string),
  1280. AuthenticatedUser: authenticatedUser,
  1281. Cfg: api.cfg,
  1282. }
  1283. api.executor.ExecRequest(&execReq)
  1284. ret.ExecutionTrackingId = execReq.TrackingID
  1285. return connect.NewResponse(ret), nil
  1286. }
  1287. func newServer(ex *executor.Executor) *oliveTinAPI {
  1288. server := oliveTinAPI{}
  1289. server.cfg = ex.Cfg
  1290. server.executor = ex
  1291. server.streamingClients = make(map[*streamingClient]struct{})
  1292. ex.AddListener(&server)
  1293. return &server
  1294. }
  1295. func GetNewHandler(ex *executor.Executor) (string, http.Handler) {
  1296. server := newServer(ex)
  1297. jsonOpt := connectproto.WithJSON(
  1298. protojson.MarshalOptions{
  1299. EmitUnpopulated: true, // https://github.com/OliveTin/OliveTin/issues/674
  1300. },
  1301. protojson.UnmarshalOptions{
  1302. DiscardUnknown: true,
  1303. },
  1304. )
  1305. return apiv1connect.NewOliveTinApiServiceHandler(server, jsonOpt)
  1306. }