4
0

api.go 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989
  1. package api
  2. import (
  3. ctx "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "os"
  9. "path"
  10. "slices"
  11. "sort"
  12. "strings"
  13. "sync"
  14. "time"
  15. "connectrpc.com/connect"
  16. "google.golang.org/protobuf/encoding/protojson"
  17. apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1"
  18. apiv1connect "github.com/OliveTin/OliveTin/gen/olivetin/api/v1/apiv1connect"
  19. "github.com/google/uuid"
  20. log "github.com/sirupsen/logrus"
  21. acl "github.com/OliveTin/OliveTin/internal/acl"
  22. auth "github.com/OliveTin/OliveTin/internal/auth"
  23. authpublic "github.com/OliveTin/OliveTin/internal/auth/authpublic"
  24. config "github.com/OliveTin/OliveTin/internal/config"
  25. entities "github.com/OliveTin/OliveTin/internal/entities"
  26. executor "github.com/OliveTin/OliveTin/internal/executor"
  27. installationinfo "github.com/OliveTin/OliveTin/internal/installationinfo"
  28. "github.com/OliveTin/OliveTin/internal/tpl"
  29. connectproto "go.akshayshah.org/connectproto"
  30. )
  31. type oliveTinAPI struct {
  32. executor *executor.Executor
  33. cfg *config.Config
  34. // streamingClients is a set of currently connected clients.
  35. // The empty struct value models set semantics (keys only) and keeps add/remove O(1).
  36. // We use a map for efficient membership and deletion; ordering is not required.
  37. streamingClients map[*streamingClient]struct{}
  38. streamingClientsMutex sync.RWMutex
  39. entityListenerRegistered bool
  40. }
  41. const maxEventStreamClients = 16
  42. var errEventStreamClientLimit = errors.New("too many concurrent event stream clients")
  43. // This is used to avoid race conditions when iterating over the connectedClients map.
  44. // and holds the lock for as minimal time as possible to avoid blocking the API for too long.
  45. func (api *oliveTinAPI) copyOfStreamingClients() []*streamingClient {
  46. api.streamingClientsMutex.RLock()
  47. defer api.streamingClientsMutex.RUnlock()
  48. clients := make([]*streamingClient, 0, len(api.streamingClients))
  49. for client := range api.streamingClients {
  50. clients = append(clients, client)
  51. }
  52. return clients
  53. }
  54. type streamingClient struct {
  55. channel chan *apiv1.EventStreamResponse
  56. AuthenticatedUser *authpublic.AuthenticatedUser
  57. heartbeatStop chan struct{}
  58. heartbeatDone chan struct{}
  59. heartbeatStopOnce sync.Once
  60. }
  61. func (c *streamingClient) stopHeartbeat() {
  62. if c.heartbeatStop == nil || c.heartbeatDone == nil {
  63. return
  64. }
  65. c.heartbeatStopOnce.Do(func() {
  66. close(c.heartbeatStop)
  67. })
  68. <-c.heartbeatDone
  69. }
  70. // trySendEventToClient sends msg to the client's channel. Returns false if the channel is full or closed.
  71. func (api *oliveTinAPI) trySendEventToClient(client *streamingClient, msg *apiv1.EventStreamResponse) bool {
  72. if client == nil || msg == nil {
  73. return false
  74. }
  75. sent := sendToStreamingClientChannel(client.channel, msg)
  76. if !sent {
  77. log.Warnf("EventStream: client channel is full or closed, removing client")
  78. }
  79. return sent
  80. }
  81. func sendToStreamingClientChannel(ch chan *apiv1.EventStreamResponse, msg *apiv1.EventStreamResponse) (sent bool) {
  82. defer func() {
  83. if recover() != nil {
  84. sent = false
  85. }
  86. }()
  87. select {
  88. case ch <- msg:
  89. return true
  90. default:
  91. return false
  92. }
  93. }
  94. func (api *oliveTinAPI) KillAction(ctx ctx.Context, req *connect.Request[apiv1.KillActionRequest]) (*connect.Response[apiv1.KillActionResponse], error) {
  95. ret := &apiv1.KillActionResponse{
  96. ExecutionTrackingId: req.Msg.ExecutionTrackingId,
  97. }
  98. var execReqLogEntry *executor.InternalLogEntry
  99. execReqLogEntry, ret.Found = api.executor.GetLog(req.Msg.ExecutionTrackingId)
  100. if !ret.Found {
  101. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found for tracking ID %s", req.Msg.ExecutionTrackingId))
  102. }
  103. if execReqLogEntry.Binding == nil {
  104. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("log entry has no binding for tracking ID %s", req.Msg.ExecutionTrackingId))
  105. }
  106. action := execReqLogEntry.Binding.Action
  107. if action == nil {
  108. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action not found for tracking ID %s", req.Msg.ExecutionTrackingId))
  109. }
  110. log.Warnf("Killing execution request by tracking ID: %v", req.Msg.ExecutionTrackingId)
  111. user := auth.UserFromApiCall(ctx, req, api.cfg)
  112. api.killActionByTrackingId(user, action, execReqLogEntry, ret)
  113. return connect.NewResponse(ret), nil
  114. }
  115. func (api *oliveTinAPI) killActionByTrackingId(user *authpublic.AuthenticatedUser, action *config.Action, execReqLogEntry *executor.InternalLogEntry, ret *apiv1.KillActionResponse) {
  116. if !acl.IsAllowedKill(api.cfg, user, action) {
  117. log.Warnf("Killing execution request not possible - user not allowed to kill this action: %v", execReqLogEntry.ExecutionTrackingID)
  118. ret.Killed = false
  119. return
  120. }
  121. err := api.executor.Kill(execReqLogEntry)
  122. if err != nil {
  123. log.Warnf("Killing execution request err: %v", err)
  124. ret.AlreadyCompleted = true
  125. ret.Killed = false
  126. } else {
  127. ret.Killed = true
  128. }
  129. }
  130. func (api *oliveTinAPI) StartAction(ctx ctx.Context, req *connect.Request[apiv1.StartActionRequest]) (*connect.Response[apiv1.StartActionResponse], error) {
  131. pair, err := api.findBindingByIDOrNotFound(req.Msg.BindingId)
  132. if err != nil {
  133. return nil, err
  134. }
  135. authenticatedUser := auth.UserFromApiCall(ctx, req, api.cfg)
  136. args := startActionArgumentsFromProto(req.Msg.Arguments)
  137. if err := api.errUnlessStartEntityAccessAllowed(authenticatedUser, pair, args); err != nil {
  138. return nil, err
  139. }
  140. justification := resolveStartJustification(pair.Action, pair, req.Msg.Justification, args)
  141. if err := validateJustificationRequired(pair.Action, justification, authenticatedUser); err != nil {
  142. return nil, connectInvalidJustification(err)
  143. }
  144. execReq := executor.ExecutionRequest{
  145. Binding: pair,
  146. TrackingID: req.Msg.UniqueTrackingId,
  147. Arguments: args,
  148. Justification: justification,
  149. AuthenticatedUser: authenticatedUser,
  150. Cfg: api.cfg,
  151. }
  152. api.executor.ExecRequest(&execReq)
  153. return connect.NewResponse(&apiv1.StartActionResponse{
  154. ExecutionTrackingId: execReq.TrackingID,
  155. }), nil
  156. }
  157. func (api *oliveTinAPI) PasswordHash(ctx ctx.Context, req *connect.Request[apiv1.PasswordHashRequest]) (*connect.Response[apiv1.PasswordHashResponse], error) {
  158. hash, err := createHash(req.Msg.Password)
  159. if err != nil {
  160. if errors.Is(err, ErrArgon2Busy) {
  161. return nil, connect.NewError(connect.CodeResourceExhausted, err)
  162. }
  163. return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("error creating hash: %w", err))
  164. }
  165. ret := &apiv1.PasswordHashResponse{
  166. Hash: hash,
  167. }
  168. return connect.NewResponse(ret), nil
  169. }
  170. func (api *oliveTinAPI) cookieSecure(header http.Header) bool {
  171. useTLS := header.Get("X-Forwarded-Proto") == "https"
  172. return useTLS || api.cfg.Security.ForceSecureCookies
  173. }
  174. func (api *oliveTinAPI) applyLocalLoginResult(req *apiv1.LocalUserLoginRequest, response *connect.Response[apiv1.LocalUserLoginResponse], match bool, secure bool) {
  175. if match {
  176. user := api.cfg.FindUserByUsername(req.Username)
  177. if user != nil {
  178. sid := uuid.NewString()
  179. auth.RegisterUserSession(api.cfg, "local", sid, user.Username)
  180. log.WithFields(log.Fields{"username": user.Username}).Info("LocalUserLogin: Session created and registered")
  181. cookie := &http.Cookie{
  182. Name: "olivetin-sid-local",
  183. Value: sid,
  184. MaxAge: 31556952,
  185. HttpOnly: true,
  186. Path: "/",
  187. Secure: secure,
  188. SameSite: http.SameSiteLaxMode,
  189. }
  190. response.Header().Set("Set-Cookie", cookie.String())
  191. log.WithFields(log.Fields{"username": user.Username}).Info("LocalUserLogin: User logged in successfully.")
  192. } else {
  193. log.WithFields(log.Fields{"username": req.Username}).Warn("LocalUserLogin: Password matched but user lookup failed.")
  194. }
  195. } else {
  196. log.WithFields(log.Fields{"username": req.Username}).Warn("LocalUserLogin: User login failed.")
  197. }
  198. }
  199. func (api *oliveTinAPI) LocalUserLogin(ctx ctx.Context, req *connect.Request[apiv1.LocalUserLoginRequest]) (*connect.Response[apiv1.LocalUserLoginResponse], error) {
  200. if !api.cfg.AuthLocalUsers.Enabled {
  201. return connect.NewResponse(&apiv1.LocalUserLoginResponse{Success: false}), nil
  202. }
  203. match, err := checkUserPassword(api.cfg, req.Msg.Username, req.Msg.Password)
  204. if err != nil {
  205. if errors.Is(err, ErrArgon2Busy) {
  206. return nil, connect.NewError(connect.CodeResourceExhausted, err)
  207. }
  208. return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("checking password: %w", err))
  209. }
  210. response := connect.NewResponse(&apiv1.LocalUserLoginResponse{Success: match})
  211. api.applyLocalLoginResult(req.Msg, response, match, api.cookieSecure(req.Header()))
  212. return response, nil
  213. }
  214. func (api *oliveTinAPI) startActionAndWaitRun(binding *executor.ActionBinding, args map[string]string, justification string, user *authpublic.AuthenticatedUser) (*executor.InternalLogEntry, bool) {
  215. execReq := executor.ExecutionRequest{
  216. Binding: binding,
  217. TrackingID: uuid.NewString(),
  218. Arguments: args,
  219. Justification: justification,
  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) findBindingByIDOrNotFound(bindingId string) (*executor.ActionBinding, error) {
  235. return api.findBindingOrNotFound(bindingId)
  236. }
  237. func (api *oliveTinAPI) startActionAndWaitLogEntry(binding *executor.ActionBinding, args map[string]string, justification string, user *authpublic.AuthenticatedUser) (*apiv1.LogEntry, error) {
  238. internalLogEntry, ok := api.startActionAndWaitRun(binding, args, justification, user)
  239. if !ok {
  240. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found"))
  241. }
  242. return api.logEntryForAllowedViewer(internalLogEntry, user)
  243. }
  244. func (api *oliveTinAPI) logEntryForAllowedViewer(internalLogEntry *executor.InternalLogEntry, user *authpublic.AuthenticatedUser) (*apiv1.LogEntry, error) {
  245. if err := api.requireLogEntryAllowed(internalLogEntry, user); err != nil {
  246. return nil, err
  247. }
  248. return api.internalLogEntryToPb(internalLogEntry, user), nil
  249. }
  250. func (api *oliveTinAPI) StartActionAndWait(ctx ctx.Context, req *connect.Request[apiv1.StartActionAndWaitRequest]) (*connect.Response[apiv1.StartActionAndWaitResponse], error) {
  251. binding, err := api.findBindingOrNotFound(req.Msg.ActionId)
  252. if err != nil {
  253. return nil, err
  254. }
  255. user := auth.UserFromApiCall(ctx, req, api.cfg)
  256. args := startActionArgumentsFromProto(req.Msg.Arguments)
  257. if err = api.errUnlessStartEntityAccessAllowed(user, binding, args); err != nil {
  258. return nil, err
  259. }
  260. justification := resolveStartJustification(binding.Action, binding, req.Msg.Justification, args)
  261. if err = validateJustificationRequired(binding.Action, justification, user); err != nil {
  262. return nil, connectInvalidJustification(err)
  263. }
  264. logEntry, err := api.startActionAndWaitLogEntry(binding, args, justification, user)
  265. if err != nil {
  266. return nil, err
  267. }
  268. return connect.NewResponse(&apiv1.StartActionAndWaitResponse{
  269. LogEntry: logEntry,
  270. }), nil
  271. }
  272. func (api *oliveTinAPI) StartActionByGet(ctx ctx.Context, req *connect.Request[apiv1.StartActionByGetRequest]) (*connect.Response[apiv1.StartActionByGetResponse], error) {
  273. reportDeprecatedAPICall("StartActionByGet", "StartAction")
  274. binding := api.executor.FindBindingByID(req.Msg.ActionId)
  275. if binding == nil || binding.Action == nil {
  276. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action with ID %s not found", req.Msg.ActionId))
  277. }
  278. user := auth.UserFromApiCall(ctx, req, api.cfg)
  279. if err := api.errUnlessStartEntityAccessAllowed(user, binding, map[string]string{}); err != nil {
  280. return nil, err
  281. }
  282. args := make(map[string]string)
  283. execReq := executor.ExecutionRequest{
  284. Binding: binding,
  285. TrackingID: uuid.NewString(),
  286. Arguments: args,
  287. AuthenticatedUser: user,
  288. Cfg: api.cfg,
  289. }
  290. _, uniqueTrackingId := api.executor.ExecRequest(&execReq)
  291. return connect.NewResponse(&apiv1.StartActionByGetResponse{
  292. ExecutionTrackingId: uniqueTrackingId,
  293. }), nil
  294. }
  295. func (api *oliveTinAPI) runBindingAndWait(binding *executor.ActionBinding, args map[string]string, user *authpublic.AuthenticatedUser) (*executor.InternalLogEntry, bool) {
  296. execReq := executor.ExecutionRequest{
  297. Binding: binding,
  298. TrackingID: uuid.NewString(),
  299. Arguments: args,
  300. AuthenticatedUser: user,
  301. Cfg: api.cfg,
  302. }
  303. wg, _ := api.executor.ExecRequest(&execReq)
  304. wg.Wait()
  305. return api.executor.GetLog(execReq.TrackingID)
  306. }
  307. func (api *oliveTinAPI) startActionByGetAndWaitLogEntry(binding *executor.ActionBinding, user *authpublic.AuthenticatedUser) (*apiv1.LogEntry, error) {
  308. internalLogEntry, ok := api.runBindingAndWait(binding, map[string]string{}, user)
  309. if !ok {
  310. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found"))
  311. }
  312. return api.logEntryForAllowedViewer(internalLogEntry, user)
  313. }
  314. func (api *oliveTinAPI) StartActionByGetAndWait(ctx ctx.Context, req *connect.Request[apiv1.StartActionByGetAndWaitRequest]) (*connect.Response[apiv1.StartActionByGetAndWaitResponse], error) {
  315. reportDeprecatedAPICall("StartActionByGetAndWait", "StartActionAndWait")
  316. binding := api.executor.FindBindingByID(req.Msg.ActionId)
  317. if binding == nil || binding.Action == nil {
  318. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action with ID %s not found", req.Msg.ActionId))
  319. }
  320. user := auth.UserFromApiCall(ctx, req, api.cfg)
  321. if err := api.errUnlessStartEntityAccessAllowed(user, binding, map[string]string{}); err != nil {
  322. return nil, err
  323. }
  324. logEntry, err := api.startActionByGetAndWaitLogEntry(binding, user)
  325. if err != nil {
  326. return nil, err
  327. }
  328. return connect.NewResponse(&apiv1.StartActionByGetAndWaitResponse{
  329. LogEntry: logEntry,
  330. }), nil
  331. }
  332. func calculateRateLimitExpires(api *oliveTinAPI, logEntry *executor.InternalLogEntry) string {
  333. if logEntry.Binding == nil || logEntry.Binding.Action == nil {
  334. return ""
  335. }
  336. expiryUnix := api.executor.GetTimeUntilAvailable(logEntry.Binding)
  337. if expiryUnix <= 0 {
  338. return ""
  339. }
  340. return time.Unix(expiryUnix, 0).Format("2006-01-02 15:04:05")
  341. }
  342. func (api *oliveTinAPI) internalLogEntryToPb(logEntry *executor.InternalLogEntry, authenticatedUser *authpublic.AuthenticatedUser) *apiv1.LogEntry {
  343. pble := &apiv1.LogEntry{
  344. ActionTitle: logEntry.ActionTitle,
  345. ActionIcon: logEntry.ActionIcon,
  346. DatetimeStarted: logEntry.DatetimeStarted.Format("2006-01-02 15:04:05"),
  347. DatetimeFinished: logEntry.DatetimeFinished.Format("2006-01-02 15:04:05"),
  348. DatetimeIndex: logEntry.Index,
  349. Output: logEntry.Output,
  350. TimedOut: logEntry.TimedOut,
  351. Blocked: logEntry.Blocked,
  352. Queued: logEntry.Queued,
  353. QueuedForGroup: logEntry.QueuedForGroup,
  354. ExitCode: logEntry.ExitCode,
  355. Tags: logEntry.Tags,
  356. ExecutionTrackingId: logEntry.ExecutionTrackingID,
  357. ExecutionStarted: logEntry.ExecutionStarted,
  358. ExecutionFinished: logEntry.ExecutionFinished,
  359. User: logEntry.Username,
  360. BindingId: logEntry.GetBindingId(),
  361. DatetimeRateLimitExpires: calculateRateLimitExpires(api, logEntry),
  362. Justification: logEntry.Justification,
  363. Arguments: logEntryArgumentsToProto(logEntry.Arguments),
  364. }
  365. if !pble.ExecutionFinished && logEntry.Binding != nil && logEntry.Binding.Action != nil {
  366. pble.CanKill = acl.IsAllowedKill(api.cfg, authenticatedUser, logEntry.Binding.Action)
  367. }
  368. return pble
  369. }
  370. func getExecutionStatusByTrackingID(api *oliveTinAPI, executionTrackingId string) *executor.InternalLogEntry {
  371. logEntry, ok := api.executor.GetLog(executionTrackingId)
  372. if !ok {
  373. return nil
  374. }
  375. return logEntry
  376. }
  377. // This is the actual action ID, not the binding ID.
  378. func getMostRecentExecutionStatusByActionId(api *oliveTinAPI, actionId string) *executor.InternalLogEntry {
  379. var ile *executor.InternalLogEntry
  380. binding := api.executor.FindBindingByID(actionId)
  381. if binding == nil {
  382. return nil
  383. }
  384. logs := api.executor.GetLogsByBindingId(binding.ID)
  385. if len(logs) == 0 {
  386. return nil
  387. }
  388. if len(logs) == 0 {
  389. return nil
  390. } else {
  391. // Get last log entry
  392. ile = logs[len(logs)-1]
  393. }
  394. return ile
  395. }
  396. func (api *oliveTinAPI) resolveExecutionStatusForView(msg *apiv1.ExecutionStatusRequest, user *authpublic.AuthenticatedUser) (*executor.InternalLogEntry, error) {
  397. ile := api.getExecutionStatusByRequest(msg)
  398. if ile == nil {
  399. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found for tracking ID %s or action ID %s", msg.ExecutionTrackingId, msg.ActionId))
  400. }
  401. if !isValidLogEntry(ile) || !api.isLogEntryAllowed(ile, user) {
  402. return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied to view this execution"))
  403. }
  404. return ile, nil
  405. }
  406. func (api *oliveTinAPI) getExecutionStatusByRequest(msg *apiv1.ExecutionStatusRequest) *executor.InternalLogEntry {
  407. if msg.ExecutionTrackingId != "" {
  408. return getExecutionStatusByTrackingID(api, msg.ExecutionTrackingId)
  409. }
  410. return getMostRecentExecutionStatusByActionId(api, msg.ActionId)
  411. }
  412. func dashboardNavigationTargetsToPb(targets []executor.DashboardNavigationTarget) []*apiv1.DashboardNavigationTarget {
  413. if len(targets) == 0 {
  414. return nil
  415. }
  416. result := make([]*apiv1.DashboardNavigationTarget, 0, len(targets))
  417. for _, target := range targets {
  418. result = append(result, &apiv1.DashboardNavigationTarget{
  419. Title: target.Title,
  420. EntityType: target.EntityType,
  421. EntityKey: target.EntityKey,
  422. Path: target.Path,
  423. })
  424. }
  425. return result
  426. }
  427. func (api *oliveTinAPI) executionStatusBackToDashboards(ile *executor.InternalLogEntry) []*apiv1.DashboardNavigationTarget {
  428. if ile == nil || ile.Binding == nil {
  429. return nil
  430. }
  431. return dashboardNavigationTargetsToPb(ile.Binding.OnDashboards)
  432. }
  433. func (api *oliveTinAPI) ExecutionStatus(ctx ctx.Context, req *connect.Request[apiv1.ExecutionStatusRequest]) (*connect.Response[apiv1.ExecutionStatusResponse], error) {
  434. user := auth.UserFromApiCall(ctx, req, api.cfg)
  435. if err := api.checkDashboardAccess(user); err != nil {
  436. return nil, err
  437. }
  438. ile, err := api.resolveExecutionStatusForView(req.Msg, user)
  439. if err != nil {
  440. return nil, err
  441. }
  442. res := &apiv1.ExecutionStatusResponse{
  443. LogEntry: api.internalLogEntryToPb(ile, user),
  444. BackToDashboards: api.executionStatusBackToDashboards(ile),
  445. }
  446. return connect.NewResponse(res), nil
  447. }
  448. func (api *oliveTinAPI) Logout(ctx ctx.Context, req *connect.Request[apiv1.LogoutRequest]) (*connect.Response[apiv1.LogoutResponse], error) {
  449. user := auth.UserFromApiCall(ctx, req, api.cfg)
  450. auth.RevokeSessionForProvider(api.cfg, user.Provider, user.SID)
  451. log.WithFields(log.Fields{
  452. "username": user.Username,
  453. "provider": user.Provider,
  454. }).Info("Logout: User logged out")
  455. response := connect.NewResponse(&apiv1.LogoutResponse{})
  456. secure := api.cookieSecure(req.Header())
  457. // Clear the local authentication cookie by setting it to expire
  458. localCookie := &http.Cookie{
  459. Name: "olivetin-sid-local",
  460. Value: "",
  461. MaxAge: -1, // This tells the browser to delete the cookie
  462. HttpOnly: true,
  463. Path: "/",
  464. Secure: secure,
  465. SameSite: http.SameSiteLaxMode,
  466. }
  467. response.Header().Set("Set-Cookie", localCookie.String())
  468. // Clear the OAuth2 authentication cookie by setting it to expire
  469. oauth2Cookie := &http.Cookie{
  470. Name: "olivetin-sid-oauth",
  471. Value: "",
  472. MaxAge: -1, // This tells the browser to delete the cookie
  473. HttpOnly: true,
  474. Path: "/",
  475. Secure: secure,
  476. SameSite: http.SameSiteLaxMode,
  477. }
  478. response.Header().Add("Set-Cookie", oauth2Cookie.String())
  479. // Clear any leftover OAuth2 CSRF state cookie from an in-flight login
  480. oauthStateCookie := &http.Cookie{
  481. Name: "olivetin-oauth-state",
  482. Value: "",
  483. MaxAge: -1,
  484. HttpOnly: true,
  485. Path: "/",
  486. Secure: secure,
  487. SameSite: http.SameSiteLaxMode,
  488. }
  489. response.Header().Add("Set-Cookie", oauthStateCookie.String())
  490. return response, nil
  491. }
  492. func (api *oliveTinAPI) GetActionBinding(ctx ctx.Context, req *connect.Request[apiv1.GetActionBindingRequest]) (*connect.Response[apiv1.GetActionBindingResponse], error) {
  493. user := auth.UserFromApiCall(ctx, req, api.cfg)
  494. if err := api.checkDashboardAccess(user); err != nil {
  495. return nil, err
  496. }
  497. resp, err := api.getActionBindingResponse(user, req.Msg.BindingId)
  498. if err != nil {
  499. return nil, err
  500. }
  501. return connect.NewResponse(resp), nil
  502. }
  503. func (api *oliveTinAPI) getActionBindingResponse(user *authpublic.AuthenticatedUser, bindingId string) (*apiv1.GetActionBindingResponse, error) {
  504. binding := api.executor.FindBindingByID(bindingId)
  505. if binding == nil || binding.Action == nil {
  506. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action with ID %s not found", bindingId))
  507. }
  508. if !api.userCanViewBinding(user, binding) {
  509. return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
  510. }
  511. return &apiv1.GetActionBindingResponse{
  512. Action: buildAction(binding, api.createDashboardRenderRequest(user, "", "")),
  513. BackToDashboards: dashboardNavigationTargetsToPb(binding.OnDashboards),
  514. }, nil
  515. }
  516. func (api *oliveTinAPI) userCanViewAction(user *authpublic.AuthenticatedUser, action *config.Action) bool {
  517. if user == nil {
  518. return true
  519. }
  520. return acl.IsAllowedView(api.cfg, user, action)
  521. }
  522. func (api *oliveTinAPI) userCanViewEntityType(user *authpublic.AuthenticatedUser, entityType string) bool {
  523. return acl.IsAllowedViewEntityType(api.cfg, user, entityFileForType(api.cfg, entityType))
  524. }
  525. func (api *oliveTinAPI) userCanViewBinding(user *authpublic.AuthenticatedUser, binding *executor.ActionBinding) bool {
  526. if binding == nil || binding.Action == nil {
  527. return false
  528. }
  529. if !api.userCanViewAction(user, binding.Action) {
  530. return false
  531. }
  532. return api.bindingEntityTypeAllowed(user, binding)
  533. }
  534. func (api *oliveTinAPI) bindingEntityTypeAllowed(user *authpublic.AuthenticatedUser, binding *executor.ActionBinding) bool {
  535. if binding == nil || binding.Action == nil || binding.Action.Entity == "" {
  536. return true
  537. }
  538. return api.userCanViewEntityType(user, binding.Action.Entity)
  539. }
  540. func (api *oliveTinAPI) errUnlessBindingEntityTypeAllowed(user *authpublic.AuthenticatedUser, binding *executor.ActionBinding) error {
  541. if api.bindingEntityTypeAllowed(user, binding) {
  542. return nil
  543. }
  544. return connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
  545. }
  546. func (api *oliveTinAPI) GetDashboard(ctx ctx.Context, req *connect.Request[apiv1.GetDashboardRequest]) (*connect.Response[apiv1.GetDashboardResponse], error) {
  547. user := auth.UserFromApiCall(ctx, req, api.cfg)
  548. if err := api.checkDashboardAccess(user); err != nil {
  549. return nil, err
  550. }
  551. entityType := ""
  552. entityKey := ""
  553. if req.Msg != nil {
  554. entityType = req.Msg.EntityType
  555. entityKey = req.Msg.EntityKey
  556. }
  557. dashboardRenderRequest := api.createDashboardRenderRequest(user, entityType, entityKey)
  558. if api.isDefaultDashboard(req.Msg.Title) {
  559. return api.buildDefaultDashboardResponse(dashboardRenderRequest)
  560. }
  561. return api.buildCustomDashboardResponse(dashboardRenderRequest, req.Msg.Title)
  562. }
  563. func (api *oliveTinAPI) checkDashboardAccess(user *authpublic.AuthenticatedUser) error {
  564. if user.IsGuest() && api.cfg.AuthRequireGuestsToLogin {
  565. return connect.NewError(connect.CodePermissionDenied, fmt.Errorf("guests are not allowed to access the dashboard"))
  566. }
  567. return nil
  568. }
  569. func (api *oliveTinAPI) createDashboardRenderRequest(user *authpublic.AuthenticatedUser, entityType, entityKey string) *DashboardRenderRequest {
  570. rr := &DashboardRenderRequest{
  571. AuthenticatedUser: user,
  572. cfg: api.cfg,
  573. ex: api.executor,
  574. EntityType: entityType,
  575. EntityKey: entityKey,
  576. }
  577. populateActiveBindingStates(rr)
  578. return rr
  579. }
  580. func (api *oliveTinAPI) isDefaultDashboard(title string) bool {
  581. return title == "default" || title == "" || title == "Actions"
  582. }
  583. func (api *oliveTinAPI) buildDefaultDashboardResponse(rr *DashboardRenderRequest) (*connect.Response[apiv1.GetDashboardResponse], error) {
  584. db := buildDefaultDashboard(rr)
  585. res := &apiv1.GetDashboardResponse{
  586. Dashboard: db,
  587. }
  588. return connect.NewResponse(res), nil
  589. }
  590. func (api *oliveTinAPI) buildCustomDashboardResponse(rr *DashboardRenderRequest, title string) (*connect.Response[apiv1.GetDashboardResponse], error) {
  591. res := &apiv1.GetDashboardResponse{
  592. Dashboard: renderDashboard(rr, title),
  593. }
  594. return connect.NewResponse(res), nil
  595. }
  596. func resolveLogsPageSize(requestPageSize, defaultPageSize int64) int64 {
  597. if requestPageSize == 0 {
  598. return defaultPageSize
  599. }
  600. if requestPageSize < 10 {
  601. return 10
  602. }
  603. if requestPageSize > 100 {
  604. return 100
  605. }
  606. return requestPageSize
  607. }
  608. func (api *oliveTinAPI) GetLogs(ctx ctx.Context, req *connect.Request[apiv1.GetLogsRequest]) (*connect.Response[apiv1.GetLogsResponse], error) {
  609. user := auth.UserFromApiCall(ctx, req, api.cfg)
  610. if err := api.checkDashboardAccess(user); err != nil {
  611. return nil, err
  612. }
  613. pageSize := resolveLogsPageSize(req.Msg.GetPageSize(), api.cfg.LogHistoryPageSize)
  614. logEntries, paging, err := api.executor.GetLogTrackingIdsACL(api.cfg, user, req.Msg.StartOffset, pageSize, req.Msg.DateFilter, req.Msg.GetFilter())
  615. if err != nil {
  616. return nil, connect.NewError(connect.CodeInvalidArgument, err)
  617. }
  618. ret := &apiv1.GetLogsResponse{}
  619. for _, le := range logEntries {
  620. ret.Logs = append(ret.Logs, api.internalLogEntryToPb(le, user))
  621. }
  622. ret.CountRemaining = paging.CountRemaining
  623. ret.PageSize = paging.PageSize
  624. ret.TotalCount = paging.TotalCount
  625. ret.StartOffset = paging.StartOffset
  626. return connect.NewResponse(ret), nil
  627. }
  628. // isValidLogEntry checks if a log entry has all required fields populated.
  629. func isValidLogEntry(e *executor.InternalLogEntry) bool {
  630. return e != nil && e.Binding != nil && e.Binding.Action != nil
  631. }
  632. // isLogEntryAllowed checks if a log entry is allowed to be viewed by the user.
  633. func (api *oliveTinAPI) isLogEntryAllowed(e *executor.InternalLogEntry, user *authpublic.AuthenticatedUser) bool {
  634. if user == nil || !isValidLogEntry(e) {
  635. return false
  636. }
  637. return acl.IsAllowedLogs(api.cfg, user, e.Binding.Action)
  638. }
  639. func (api *oliveTinAPI) requireLogEntryAllowed(entry *executor.InternalLogEntry, user *authpublic.AuthenticatedUser) error {
  640. if api.isLogEntryAllowed(entry, user) {
  641. return nil
  642. }
  643. return connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied to view this execution"))
  644. }
  645. // mayViewExecutionEvent returns whether the user is allowed to receive this execution event (for EventStream ACL).
  646. func (api *oliveTinAPI) mayViewExecutionEvent(entry *executor.InternalLogEntry, user *authpublic.AuthenticatedUser) bool {
  647. if user == nil {
  648. return false
  649. }
  650. return isValidLogEntry(entry) && api.isLogEntryAllowed(entry, user)
  651. }
  652. // buildEmptyPageResponse creates a response for an empty page.
  653. func buildEmptyPageResponse(page pageInfo) *apiv1.GetActionLogsResponse {
  654. return &apiv1.GetActionLogsResponse{
  655. CountRemaining: 0,
  656. PageSize: page.size,
  657. TotalCount: page.total,
  658. StartOffset: page.start,
  659. }
  660. }
  661. // calculateReversedIndices computes the reversed indices for newest-first pagination.
  662. func calculateReversedIndices(page pageInfo, filteredLen int) (int64, int64) {
  663. startIdx := page.total - page.end
  664. endIdx := page.total - page.start
  665. if startIdx < 0 {
  666. startIdx = 0
  667. }
  668. if endIdx > int64(filteredLen) {
  669. endIdx = int64(filteredLen)
  670. }
  671. return startIdx, endIdx
  672. }
  673. // buildActionLogsResponse builds the response with paginated log entries (newest first).
  674. func (api *oliveTinAPI) buildActionLogsResponse(filtered []*executor.InternalLogEntry, page pageInfo, user *authpublic.AuthenticatedUser) *apiv1.GetActionLogsResponse {
  675. startIdx, endIdx := calculateReversedIndices(page, len(filtered))
  676. ret := &apiv1.GetActionLogsResponse{}
  677. chunk := filtered[int(startIdx):int(endIdx)]
  678. for _, c := range slices.Backward(chunk) {
  679. ret.Logs = append(ret.Logs, api.internalLogEntryToPb(c, user))
  680. }
  681. ret.CountRemaining = page.start
  682. ret.PageSize = page.size
  683. ret.TotalCount = page.total
  684. ret.StartOffset = page.start
  685. return ret
  686. }
  687. func (api *oliveTinAPI) GetActionLogs(ctx ctx.Context, req *connect.Request[apiv1.GetActionLogsRequest]) (*connect.Response[apiv1.GetActionLogsResponse], error) {
  688. user := auth.UserFromApiCall(ctx, req, api.cfg)
  689. if err := api.checkDashboardAccess(user); err != nil {
  690. return nil, err
  691. }
  692. filtered := api.filterLogsByACL(api.executor.GetLogsByBindingId(req.Msg.ActionId), user)
  693. page := paginate(int64(len(filtered)), api.cfg.LogHistoryPageSize, req.Msg.StartOffset)
  694. if page.empty {
  695. return connect.NewResponse(buildEmptyPageResponse(page)), nil
  696. }
  697. return connect.NewResponse(api.buildActionLogsResponse(filtered, page, user)), nil
  698. }
  699. func (api *oliveTinAPI) filterLogsByACL(entries []*executor.InternalLogEntry, user *authpublic.AuthenticatedUser) []*executor.InternalLogEntry {
  700. filtered := make([]*executor.InternalLogEntry, 0, len(entries))
  701. for _, e := range entries {
  702. if !isValidLogEntry(e) {
  703. continue
  704. }
  705. if api.isLogEntryAllowed(e, user) {
  706. filtered = append(filtered, e)
  707. }
  708. }
  709. return filtered
  710. }
  711. type pageInfo struct {
  712. total int64
  713. size int64
  714. start int64
  715. end int64
  716. empty bool
  717. }
  718. func paginate(total int64, size int64, start int64) pageInfo {
  719. if start < 0 {
  720. start = 0
  721. }
  722. if start >= total {
  723. return pageInfo{total: total, size: size, start: start, end: start, empty: true}
  724. }
  725. end := min(start+size, total)
  726. return pageInfo{total: total, size: size, start: start, end: end, empty: false}
  727. }
  728. /*
  729. This function is ONLY a helper for the UI - the arguments are validated properly
  730. on the StartAction -> Executor chain. This is here basically to provide helpful
  731. error messages more quickly before starting the action.
  732. It uses the same validation logic as the executor, including mangling argument
  733. values (e.g., datetime formatting, checkbox title-to-value conversion).
  734. */
  735. func (api *oliveTinAPI) argumentNotFoundForValidation(msg *apiv1.ValidateArgumentTypeRequest) bool {
  736. if msg.BindingId == "" || msg.ArgumentName == "" {
  737. return false
  738. }
  739. arg, _ := api.findArgumentForValidation(msg.BindingId, msg.ArgumentName)
  740. return arg == nil
  741. }
  742. func (api *oliveTinAPI) validateArgumentTypeBindingAccess(user *authpublic.AuthenticatedUser, msg *apiv1.ValidateArgumentTypeRequest) error {
  743. if msg == nil || msg.BindingId == "" {
  744. return nil
  745. }
  746. return api.errUnlessUserMayValidateArgumentTypeForBinding(user, msg.BindingId)
  747. }
  748. func (api *oliveTinAPI) errUnlessUserMayValidateArgumentTypeForBinding(user *authpublic.AuthenticatedUser, bindingID string) error {
  749. binding := api.executor.FindBindingByID(bindingID)
  750. if binding == nil || binding.Action == nil {
  751. return connect.NewError(connect.CodeNotFound, fmt.Errorf("action or argument not found for binding ID %s", bindingID))
  752. }
  753. if !api.userCanViewBinding(user, binding) {
  754. return connect.NewError(connect.CodePermissionDenied, fmt.Errorf("permission denied"))
  755. }
  756. return nil
  757. }
  758. func (api *oliveTinAPI) ValidateArgumentType(ctx ctx.Context, req *connect.Request[apiv1.ValidateArgumentTypeRequest]) (*connect.Response[apiv1.ValidateArgumentTypeResponse], error) {
  759. user := auth.UserFromApiCall(ctx, req, api.cfg)
  760. if err := api.checkDashboardAccess(user); err != nil {
  761. return nil, err
  762. }
  763. if err := api.validateArgumentTypeBindingAccess(user, req.Msg); err != nil {
  764. return nil, err
  765. }
  766. if api.argumentNotFoundForValidation(req.Msg) {
  767. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action or argument not found for binding ID %s", req.Msg.BindingId))
  768. }
  769. if err := api.validateArgumentTypeEntityAccess(user, req.Msg); err != nil {
  770. return nil, err
  771. }
  772. return api.validateArgumentTypeConnectResponse(req.Msg)
  773. }
  774. func (api *oliveTinAPI) validateArgumentTypeEntityAccess(user *authpublic.AuthenticatedUser, msg *apiv1.ValidateArgumentTypeRequest) error {
  775. arg := api.argumentFromValidationRequest(msg)
  776. if arg == nil {
  777. return nil
  778. }
  779. return api.errUnlessEntityArgumentAllowed(user, arg, "")
  780. }
  781. func (api *oliveTinAPI) argumentFromValidationRequest(msg *apiv1.ValidateArgumentTypeRequest) *config.ActionArgument {
  782. if msg == nil || msg.BindingId == "" || msg.ArgumentName == "" {
  783. return nil
  784. }
  785. arg, _ := api.findArgumentForValidation(msg.BindingId, msg.ArgumentName)
  786. return arg
  787. }
  788. func (api *oliveTinAPI) validateArgumentTypeConnectResponse(msg *apiv1.ValidateArgumentTypeRequest) (*connect.Response[apiv1.ValidateArgumentTypeResponse], error) {
  789. err := api.validateArgumentTypeInternal(msg)
  790. desc := ""
  791. if err != nil {
  792. desc = err.Error()
  793. }
  794. return connect.NewResponse(&apiv1.ValidateArgumentTypeResponse{
  795. Valid: err == nil,
  796. Description: desc,
  797. }), nil
  798. }
  799. func (api *oliveTinAPI) validateArgumentTypeInternal(msg *apiv1.ValidateArgumentTypeRequest) error {
  800. if msg.BindingId == "" || msg.ArgumentName == "" {
  801. return validateUnboundArgumentType(msg)
  802. }
  803. arg, action := api.findArgumentForValidation(msg.BindingId, msg.ArgumentName)
  804. if arg == nil {
  805. return fmt.Errorf("argument not found")
  806. }
  807. if err := errUnlessEntityArgumentValueAllowed(arg, msg.Value); err != nil {
  808. return err
  809. }
  810. return executor.ValidateArgument(arg, msg.Value, action)
  811. }
  812. // Custom regex types only exist on configured arguments, so validating one
  813. // without a binding would only evaluate a caller-supplied pattern.
  814. func validateUnboundArgumentType(msg *apiv1.ValidateArgumentTypeRequest) error {
  815. if strings.HasPrefix(msg.Type, "regex:") {
  816. return fmt.Errorf("custom regex types can only be validated for a configured action argument")
  817. }
  818. return executor.TypeSafetyCheck("", msg.Value, msg.Type)
  819. }
  820. func (api *oliveTinAPI) findArgumentForValidation(bindingId string, argumentName string) (*config.ActionArgument, *config.Action) {
  821. binding := api.executor.FindBindingByID(bindingId)
  822. if binding == nil || binding.Action == nil {
  823. return nil, nil
  824. }
  825. arg := api.findArgumentByName(binding.Action, argumentName)
  826. return arg, binding.Action
  827. }
  828. func (api *oliveTinAPI) findArgumentByName(action *config.Action, name string) *config.ActionArgument {
  829. for i := range action.Arguments {
  830. if action.Arguments[i].Name == name {
  831. return &action.Arguments[i]
  832. }
  833. }
  834. return nil
  835. }
  836. func (api *oliveTinAPI) WhoAmI(ctx ctx.Context, req *connect.Request[apiv1.WhoAmIRequest]) (*connect.Response[apiv1.WhoAmIResponse], error) {
  837. user := auth.UserFromApiCall(ctx, req, api.cfg)
  838. if err := api.checkDashboardAccess(user); err != nil {
  839. return nil, err
  840. }
  841. res := &apiv1.WhoAmIResponse{
  842. AuthenticatedUser: user.Username,
  843. Usergroup: user.UsergroupLine,
  844. Provider: user.Provider,
  845. Acls: user.Acls,
  846. SessionFingerprint: user.SessionFingerprint(),
  847. }
  848. return connect.NewResponse(res), nil
  849. }
  850. func (api *oliveTinAPI) ServerDiagnostics(ctx ctx.Context, req *connect.Request[apiv1.ServerDiagnosticsRequest]) (*connect.Response[apiv1.ServerDiagnosticsResponse], error) {
  851. user := auth.UserFromApiCall(ctx, req, api.cfg)
  852. redactVersion := !user.EffectivePolicy.ShowVersionNumber
  853. diagnostics := installationinfo.GetServerDiagnostics(redactVersion)
  854. if !api.cfg.InsecureAllowDumpServerDiagnostics {
  855. log.Info(diagnostics)
  856. diagnostics = "Your Server Diagnostics have been logged to OliveTin logs.\n\nIf you are in a safe network, you can temporarily set `insecureAllowDumpServerDiagnostics: true` in your config.yaml, restart OliveTin, and refresh this page - it will put the output directly in the browser."
  857. }
  858. ret := &apiv1.ServerDiagnosticsResponse{
  859. Alert: diagnostics,
  860. }
  861. return connect.NewResponse(ret), nil
  862. }
  863. func (api *oliveTinAPI) DumpVars(ctx ctx.Context, req *connect.Request[apiv1.DumpVarsRequest]) (*connect.Response[apiv1.DumpVarsResponse], error) {
  864. res := &apiv1.DumpVarsResponse{}
  865. if !api.cfg.InsecureAllowDumpVars {
  866. res.Alert = "Dumping variables is not allowed by default because it is insecure."
  867. return connect.NewResponse(res), nil
  868. }
  869. jsonstring, err := json.MarshalIndent(tpl.GetNewGeneralTemplateContext(), "", " ")
  870. if err != nil {
  871. log.WithError(err).Error("DumpVars: failed to marshal template context from GetNewGeneralTemplateContext")
  872. return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("dump vars: marshal template context: %w", err))
  873. }
  874. fmt.Printf("%s", jsonstring)
  875. res.Alert = "Dumping variables has been enabled in the configuration. Please set InsecureAllowDumpVars = false again after you don't need it anymore"
  876. return connect.NewResponse(res), nil
  877. }
  878. func debugBindingActionTitle(binding *executor.ActionBinding) string {
  879. if binding == nil || binding.Action == nil {
  880. return ""
  881. }
  882. return binding.Action.Title
  883. }
  884. func (api *oliveTinAPI) DumpPublicIdActionMap(ctx ctx.Context, req *connect.Request[apiv1.DumpPublicIdActionMapRequest]) (*connect.Response[apiv1.DumpPublicIdActionMapResponse], error) {
  885. res := &apiv1.DumpPublicIdActionMapResponse{}
  886. res.Contents = make(map[string]*apiv1.DebugBinding)
  887. if !api.cfg.InsecureAllowDumpActionMap {
  888. res.Alert = "Dumping Public IDs is disallowed."
  889. return connect.NewResponse(res), nil
  890. }
  891. api.executor.MapActionBindingsLock.RLock()
  892. for k, v := range api.executor.MapActionBindings {
  893. res.Contents[k] = &apiv1.DebugBinding{
  894. ActionTitle: debugBindingActionTitle(v),
  895. }
  896. }
  897. api.executor.MapActionBindingsLock.RUnlock()
  898. res.Alert = "Dumping variables has been enabled in the configuration. Please set InsecureAllowDumpActionMap = false again after you don't need it anymore"
  899. return connect.NewResponse(res), nil
  900. }
  901. func (api *oliveTinAPI) GetReadyz(ctx ctx.Context, req *connect.Request[apiv1.GetReadyzRequest]) (*connect.Response[apiv1.GetReadyzResponse], error) {
  902. res := &apiv1.GetReadyzResponse{
  903. Status: "OK",
  904. }
  905. return connect.NewResponse(res), nil
  906. }
  907. func (api *oliveTinAPI) EventStream(ctx ctx.Context, req *connect.Request[apiv1.EventStreamRequest], srv *connect.ServerStream[apiv1.EventStreamResponse]) error {
  908. log.Debugf("EventStream: %v", req.Msg)
  909. // Set X-Accel-Buffering header to disable nginx buffering for this stream
  910. // https://github.com/OliveTin/OliveTin/issues/765
  911. srv.ResponseHeader().Set("X-Accel-Buffering", "no")
  912. user := auth.UserFromApiCall(ctx, req, api.cfg)
  913. if err := api.checkDashboardAccess(user); err != nil {
  914. return err
  915. }
  916. client := &streamingClient{
  917. channel: make(chan *apiv1.EventStreamResponse, 10), // Buffered channel to hold Events
  918. AuthenticatedUser: user,
  919. heartbeatStop: make(chan struct{}),
  920. heartbeatDone: make(chan struct{}),
  921. }
  922. if err := api.registerStreamingClient(client); err != nil {
  923. return connect.NewError(connect.CodeResourceExhausted, err)
  924. }
  925. log.WithFields(log.Fields{
  926. "authenticatedUser": user.Username,
  927. }).Debugf("EventStream: client connected")
  928. // Release the slot on every exit path. removeClient is idempotent, so this
  929. // is safe when a broadcast or the heartbeat goroutine already removed us.
  930. defer api.removeClient(client)
  931. go api.sendEventStreamHeartbeats(client)
  932. api.forwardEventsToClient(ctx.Done(), client, srv)
  933. log.Debugf("EventStream: client disconnected")
  934. return nil
  935. }
  936. // forwardEventsToClient sends queued events to the stream until the client goes
  937. // away. Without watching done, a client that disconnected was only noticed once
  938. // a later Send failed, which net/http's buffered writer reports several
  939. // heartbeats late (or not at all while the TCP peer keeps ACKing), so its slot
  940. // in maxEventStreamClients stayed taken.
  941. func (api *oliveTinAPI) forwardEventsToClient(done <-chan struct{}, client *streamingClient, srv *connect.ServerStream[apiv1.EventStreamResponse]) {
  942. for {
  943. msg, ok := nextEvent(done, client.channel)
  944. if !ok {
  945. return
  946. }
  947. log.Debugf("Sending event to client: %v", msg)
  948. if err := srv.Send(msg); err != nil {
  949. log.Warnf("Error sending event to client: %v", err)
  950. return
  951. }
  952. }
  953. }
  954. // nextEvent waits for the next queued event. ok is false once the request is
  955. // done (the client went away) or the channel was closed by removeClient.
  956. func nextEvent(done <-chan struct{}, events <-chan *apiv1.EventStreamResponse) (*apiv1.EventStreamResponse, bool) {
  957. select {
  958. case <-done:
  959. return nil, false
  960. case msg, ok := <-events:
  961. return msg, ok
  962. }
  963. }
  964. func (api *oliveTinAPI) registerStreamingClient(client *streamingClient) error {
  965. api.streamingClientsMutex.Lock()
  966. defer api.streamingClientsMutex.Unlock()
  967. if len(api.streamingClients) >= maxEventStreamClients {
  968. log.WithFields(log.Fields{
  969. "limit": maxEventStreamClients,
  970. }).Warn("EventStream: rejecting client; concurrent client limit reached")
  971. return errEventStreamClientLimit
  972. }
  973. api.streamingClients[client] = struct{}{}
  974. return nil
  975. }
  976. func (api *oliveTinAPI) sendEventStreamHeartbeats(client *streamingClient) {
  977. defer close(client.heartbeatDone)
  978. if !api.sendEventStreamHeartbeat(client) {
  979. go api.removeClient(client)
  980. return
  981. }
  982. ticker := time.NewTicker(10 * time.Second)
  983. defer ticker.Stop()
  984. api.runEventStreamHeartbeatLoop(client, ticker)
  985. }
  986. func (api *oliveTinAPI) runEventStreamHeartbeatLoop(client *streamingClient, ticker *time.Ticker) {
  987. for {
  988. if api.waitEventStreamHeartbeatOrDone(client.heartbeatStop, ticker) {
  989. return
  990. }
  991. if !api.sendEventStreamHeartbeat(client) {
  992. go api.removeClient(client)
  993. return
  994. }
  995. }
  996. }
  997. func (api *oliveTinAPI) waitEventStreamHeartbeatOrDone(done <-chan struct{}, ticker *time.Ticker) bool {
  998. select {
  999. case <-done:
  1000. return true
  1001. case <-ticker.C:
  1002. return false
  1003. }
  1004. }
  1005. func (api *oliveTinAPI) sendEventStreamHeartbeat(client *streamingClient) bool {
  1006. msg := &apiv1.EventStreamResponse{
  1007. Event: &apiv1.EventStreamResponse_Heartbeat{
  1008. Heartbeat: &apiv1.EventHeartbeat{},
  1009. },
  1010. }
  1011. return api.trySendEventToClient(client, msg)
  1012. }
  1013. func (api *oliveTinAPI) removeClient(clientToRemove *streamingClient) {
  1014. if clientToRemove == nil {
  1015. return
  1016. }
  1017. api.streamingClientsMutex.Lock()
  1018. if _, exists := api.streamingClients[clientToRemove]; !exists {
  1019. api.streamingClientsMutex.Unlock()
  1020. return
  1021. }
  1022. delete(api.streamingClients, clientToRemove)
  1023. api.streamingClientsMutex.Unlock()
  1024. clientToRemove.stopHeartbeat()
  1025. close(clientToRemove.channel)
  1026. }
  1027. func (api *oliveTinAPI) OnActionMapRebuilt() {
  1028. api.broadcastEventStream(&apiv1.EventStreamResponse{
  1029. Event: &apiv1.EventStreamResponse_ConfigChanged{
  1030. ConfigChanged: &apiv1.EventConfigChanged{},
  1031. },
  1032. })
  1033. }
  1034. func (api *oliveTinAPI) onEntityChanged() {
  1035. api.broadcastEventStream(&apiv1.EventStreamResponse{
  1036. Event: &apiv1.EventStreamResponse_EntityChanged{
  1037. EntityChanged: &apiv1.EventEntityChanged{},
  1038. },
  1039. })
  1040. }
  1041. func (api *oliveTinAPI) broadcastEventStream(msg *apiv1.EventStreamResponse) {
  1042. toRemove := []*streamingClient{}
  1043. for _, client := range api.copyOfStreamingClients() {
  1044. if !api.trySendEventToClient(client, msg) {
  1045. toRemove = append(toRemove, client)
  1046. }
  1047. }
  1048. for _, client := range toRemove {
  1049. api.removeClient(client)
  1050. }
  1051. }
  1052. func (api *oliveTinAPI) OnExecutionStarted(ex *executor.InternalLogEntry) {
  1053. toRemove := []*streamingClient{}
  1054. for _, client := range api.copyOfStreamingClients() {
  1055. api.maybeSendExecutionStarted(client, ex, &toRemove)
  1056. }
  1057. for _, client := range toRemove {
  1058. api.removeClient(client)
  1059. }
  1060. }
  1061. func (api *oliveTinAPI) maybeSendExecutionStarted(client *streamingClient, ex *executor.InternalLogEntry, toRemove *[]*streamingClient) {
  1062. if client == nil {
  1063. return
  1064. }
  1065. if !api.mayViewExecutionEvent(ex, client.AuthenticatedUser) {
  1066. return
  1067. }
  1068. msg := &apiv1.EventStreamResponse{
  1069. Event: &apiv1.EventStreamResponse_ExecutionStarted{
  1070. ExecutionStarted: &apiv1.EventExecutionStarted{
  1071. LogEntry: api.internalLogEntryToPb(ex, client.AuthenticatedUser),
  1072. },
  1073. },
  1074. }
  1075. if !api.trySendEventToClient(client, msg) {
  1076. *toRemove = append(*toRemove, client)
  1077. }
  1078. }
  1079. func (api *oliveTinAPI) OnExecutionFinished(ile *executor.InternalLogEntry) {
  1080. toRemove := []*streamingClient{}
  1081. for _, client := range api.copyOfStreamingClients() {
  1082. api.maybeSendExecutionFinished(client, ile, &toRemove)
  1083. }
  1084. for _, client := range toRemove {
  1085. api.removeClient(client)
  1086. }
  1087. }
  1088. func (api *oliveTinAPI) maybeSendExecutionFinished(client *streamingClient, ile *executor.InternalLogEntry, toRemove *[]*streamingClient) {
  1089. if client == nil {
  1090. return
  1091. }
  1092. if !api.mayViewExecutionEvent(ile, client.AuthenticatedUser) {
  1093. return
  1094. }
  1095. msg := &apiv1.EventStreamResponse{
  1096. Event: &apiv1.EventStreamResponse_ExecutionFinished{
  1097. ExecutionFinished: &apiv1.EventExecutionFinished{
  1098. LogEntry: api.internalLogEntryToPb(ile, client.AuthenticatedUser),
  1099. },
  1100. },
  1101. }
  1102. if !api.trySendEventToClient(client, msg) {
  1103. *toRemove = append(*toRemove, client)
  1104. }
  1105. }
  1106. func (api *oliveTinAPI) GetDiagnostics(ctx ctx.Context, req *connect.Request[apiv1.GetDiagnosticsRequest]) (*connect.Response[apiv1.GetDiagnosticsResponse], error) {
  1107. user := auth.UserFromApiCall(ctx, req, api.cfg)
  1108. if err := api.checkDashboardAccess(user); err != nil {
  1109. return nil, err
  1110. }
  1111. if !user.EffectivePolicy.ShowDiagnostics {
  1112. return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("diagnostics are not available for your account"))
  1113. }
  1114. res := &apiv1.GetDiagnosticsResponse{
  1115. SshFoundKey: installationinfo.Runtime.SshFoundKey,
  1116. SshFoundConfig: installationinfo.Runtime.SshFoundConfig,
  1117. ConfigIssues: api.buildConfigIssuesForUser(user),
  1118. }
  1119. return connect.NewResponse(res), nil
  1120. }
  1121. func (api *oliveTinAPI) Init(ctx ctx.Context, req *connect.Request[apiv1.InitRequest]) (*connect.Response[apiv1.InitResponse], error) {
  1122. user := auth.UserFromApiCall(ctx, req, api.cfg)
  1123. return connect.NewResponse(api.buildInitResponse(user)), nil
  1124. }
  1125. func (api *oliveTinAPI) buildInitResponse(user *authpublic.AuthenticatedUser) *apiv1.InitResponse {
  1126. loginRequired := user.IsGuest() && api.cfg.AuthRequireGuestsToLogin
  1127. currentVersion, availableVersion, showNewVersions := initVersionFields(user, api.cfg)
  1128. showNavigation, rootDashboardEntries := api.initNavigationFields(user, loginRequired)
  1129. res := &apiv1.InitResponse{
  1130. ShowFooter: api.cfg.ShowFooter,
  1131. ShowNavigation: showNavigation,
  1132. ShowNewVersions: showNewVersions,
  1133. AvailableVersion: availableVersion,
  1134. CurrentVersion: currentVersion,
  1135. PageTitle: api.cfg.PageTitle,
  1136. SectionNavigationStyle: api.cfg.SectionNavigationStyle,
  1137. DefaultIconForBack: api.cfg.DefaultIconForBack,
  1138. EnableCustomJs: api.cfg.EnableCustomJs,
  1139. AuthLoginUrl: api.cfg.AuthLoginUrl,
  1140. AuthLocalLogin: api.cfg.AuthLocalUsers.Enabled,
  1141. OAuth2Providers: buildPublicOAuth2ProvidersList(api.cfg),
  1142. AdditionalLinks: buildAdditionalLinks(api.cfg.AdditionalNavigationLinks),
  1143. StyleMods: api.cfg.StyleMods,
  1144. RootDashboards: rootDashboardTitles(rootDashboardEntries),
  1145. RootDashboardEntries: rootDashboardEntries,
  1146. AuthenticatedUser: user.Username,
  1147. AuthenticatedUserProvider: user.Provider,
  1148. EffectivePolicy: buildEffectivePolicy(user.EffectivePolicy),
  1149. BannerMessage: api.cfg.BannerMessage,
  1150. BannerCss: api.cfg.BannerCSS,
  1151. ShowDiagnostics: user.EffectivePolicy.ShowDiagnostics,
  1152. ShowLogList: user.EffectivePolicy.ShowLogList,
  1153. LoginRequired: loginRequired,
  1154. AvailableThemes: discoverAvailableThemes(api.cfg),
  1155. ShowNavigateOnStartIcons: api.cfg.ShowNavigateOnStartIcons,
  1156. ConfigIssueCount: configIssueCountForUser(api, user),
  1157. Features: &apiv1.Features{
  1158. HeaderSearch: api.cfg.Features.HeaderSearch,
  1159. },
  1160. SearchHints: api.initSearchHints(user, loginRequired),
  1161. }
  1162. return res
  1163. }
  1164. // initNavigationFields hides sidebar navigation and dashboard titles from guests
  1165. // that must log in before using OliveTin.
  1166. func (api *oliveTinAPI) initNavigationFields(user *authpublic.AuthenticatedUser, loginRequired bool) (bool, []*apiv1.RootDashboard) {
  1167. if loginRequired {
  1168. return false, nil
  1169. }
  1170. return api.cfg.ShowNavigation, api.buildRootDashboardEntries(user, api.cfg.Dashboards)
  1171. }
  1172. func initVersionFields(user *authpublic.AuthenticatedUser, cfg *config.Config) (currentVersion string, availableVersion string, showNewVersions bool) {
  1173. if !user.EffectivePolicy.ShowVersionNumber {
  1174. return "", "", false
  1175. }
  1176. return installationinfo.Build.Version, installationinfo.Runtime.AvailableVersion, cfg.ShowNewVersions
  1177. }
  1178. func (api *oliveTinAPI) initSearchHints(user *authpublic.AuthenticatedUser, loginRequired bool) *apiv1.SearchHints {
  1179. if loginRequired || !api.cfg.Features.HeaderSearch {
  1180. return nil
  1181. }
  1182. return api.buildSearchHints(user)
  1183. }
  1184. // discoverAvailableThemes finds all available themes in the custom-webui/themes directory.
  1185. // A theme is considered available if it has a theme.css file.
  1186. func discoverAvailableThemes(cfg *config.Config) []string {
  1187. configDir := cfg.GetDir()
  1188. if configDir == "" {
  1189. return []string{}
  1190. }
  1191. themesDir := path.Join(configDir, "custom-webui", "themes")
  1192. entries, err := os.ReadDir(themesDir)
  1193. if err != nil {
  1194. log.WithFields(log.Fields{
  1195. "themesDir": themesDir,
  1196. "error": err,
  1197. }).Tracef("Could not read themes directory")
  1198. return []string{}
  1199. }
  1200. themes := collectValidThemes(themesDir, entries)
  1201. sort.Strings(themes)
  1202. return themes
  1203. }
  1204. // collectValidThemes collects theme names from directory entries that have a theme.css file.
  1205. func collectValidThemes(themesDir string, entries []os.DirEntry) []string {
  1206. var themes []string
  1207. for _, entry := range entries {
  1208. if themeName := getValidThemeName(themesDir, entry); themeName != "" {
  1209. themes = append(themes, themeName)
  1210. }
  1211. }
  1212. return themes
  1213. }
  1214. // getValidThemeName returns the theme name if the entry is a valid theme directory with theme.css, otherwise returns empty string.
  1215. func getValidThemeName(themesDir string, entry os.DirEntry) string {
  1216. if !entry.IsDir() {
  1217. return ""
  1218. }
  1219. themeName := entry.Name()
  1220. themeCssPath := path.Join(themesDir, themeName, "theme.css")
  1221. if _, err := os.Stat(themeCssPath); err != nil {
  1222. return ""
  1223. }
  1224. return themeName
  1225. }
  1226. func (api *oliveTinAPI) buildRootDashboards(user *authpublic.AuthenticatedUser, dashboards []*config.DashboardComponent) []string {
  1227. return rootDashboardTitles(api.buildRootDashboardEntries(user, dashboards))
  1228. }
  1229. func rootDashboardTitles(entries []*apiv1.RootDashboard) []string {
  1230. titles := make([]string, 0, len(entries))
  1231. for _, entry := range entries {
  1232. titles = append(titles, entry.Title)
  1233. }
  1234. return titles
  1235. }
  1236. func (api *oliveTinAPI) buildRootDashboardEntries(user *authpublic.AuthenticatedUser, dashboards []*config.DashboardComponent) []*apiv1.RootDashboard {
  1237. var entries []*apiv1.RootDashboard
  1238. dashboardRenderRequest := api.createDashboardRenderRequest(user, "", "")
  1239. api.addDefaultDashboardEntryIfNeeded(&entries, dashboardRenderRequest)
  1240. api.addCustomDashboardEntries(&entries, dashboards, dashboardRenderRequest)
  1241. return entries
  1242. }
  1243. func (api *oliveTinAPI) addDefaultDashboardEntryIfNeeded(entries *[]*apiv1.RootDashboard, rr *DashboardRenderRequest) {
  1244. defaultDashboard := buildDefaultDashboard(rr)
  1245. if defaultDashboard != nil && len(defaultDashboard.Contents) > 0 {
  1246. log.Tracef("defaultDashboard: %+v", defaultDashboard.Contents)
  1247. *entries = append(*entries, &apiv1.RootDashboard{Title: "Actions"})
  1248. }
  1249. }
  1250. func (api *oliveTinAPI) addCustomDashboardEntries(entries *[]*apiv1.RootDashboard, dashboards []*config.DashboardComponent, rr *DashboardRenderRequest) {
  1251. for _, dashboard := range dashboards {
  1252. // We have to build the dashboard response instead of just looping over config.dashboards,
  1253. // because we need to check if the user has access to the dashboard
  1254. renderedDashboard := renderDashboard(rr, dashboard.Title)
  1255. if renderedDashboard != nil {
  1256. *entries = append(*entries, &apiv1.RootDashboard{
  1257. Title: dashboard.Title,
  1258. Category: dashboard.Category,
  1259. })
  1260. }
  1261. }
  1262. }
  1263. func buildPublicOAuth2ProvidersList(cfg *config.Config) []*apiv1.OAuth2Provider {
  1264. var publicProviders []*apiv1.OAuth2Provider
  1265. for providerKey, provider := range cfg.AuthOAuth2Providers {
  1266. publicProviders = append(publicProviders, &apiv1.OAuth2Provider{
  1267. Title: provider.Title,
  1268. Icon: provider.Icon,
  1269. Key: providerKey,
  1270. })
  1271. }
  1272. sort.Slice(publicProviders, func(i, j int) bool {
  1273. return publicProviders[i].Key < publicProviders[j].Key
  1274. })
  1275. return publicProviders
  1276. }
  1277. func buildAdditionalLinks(links []*config.NavigationLink) []*apiv1.AdditionalLink {
  1278. var additionalLinks []*apiv1.AdditionalLink
  1279. for _, link := range links {
  1280. additionalLinks = append(additionalLinks, &apiv1.AdditionalLink{
  1281. Title: link.Title,
  1282. Url: link.Url,
  1283. })
  1284. }
  1285. return additionalLinks
  1286. }
  1287. func (api *oliveTinAPI) OnOutputChunk(content []byte, executionTrackingId string) {
  1288. entry := api.getValidLogEntryForStreaming(executionTrackingId)
  1289. if entry == nil {
  1290. return
  1291. }
  1292. msg := &apiv1.EventStreamResponse{
  1293. Event: &apiv1.EventStreamResponse_OutputChunk{
  1294. OutputChunk: &apiv1.EventOutputChunk{
  1295. Output: string(content),
  1296. ExecutionTrackingId: executionTrackingId,
  1297. },
  1298. },
  1299. }
  1300. toRemove := []*streamingClient{}
  1301. for _, client := range api.copyOfStreamingClients() {
  1302. api.maybeSendOutputChunk(client, entry, msg, &toRemove)
  1303. }
  1304. for _, client := range toRemove {
  1305. api.removeClient(client)
  1306. }
  1307. }
  1308. func (api *oliveTinAPI) getValidLogEntryForStreaming(executionTrackingId string) *executor.InternalLogEntry {
  1309. entry, ok := api.executor.GetLog(executionTrackingId)
  1310. if !ok || !isValidLogEntry(entry) {
  1311. return nil
  1312. }
  1313. return entry
  1314. }
  1315. func (api *oliveTinAPI) maybeSendOutputChunk(client *streamingClient, entry *executor.InternalLogEntry, msg *apiv1.EventStreamResponse, toRemove *[]*streamingClient) {
  1316. if client == nil {
  1317. return
  1318. }
  1319. if !api.mayViewExecutionEvent(entry, client.AuthenticatedUser) {
  1320. return
  1321. }
  1322. if !api.trySendEventToClient(client, msg) {
  1323. *toRemove = append(*toRemove, client)
  1324. }
  1325. }
  1326. func (api *oliveTinAPI) GetEntities(ctx ctx.Context, req *connect.Request[apiv1.GetEntitiesRequest]) (*connect.Response[apiv1.GetEntitiesResponse], error) {
  1327. user := auth.UserFromApiCall(ctx, req, api.cfg)
  1328. if err := api.checkDashboardAccess(user); err != nil {
  1329. return nil, err
  1330. }
  1331. entityMap := entities.GetEntities()
  1332. entityDefinitions := api.buildEntityDefinitionsResponse(user, req.Msg, entityMap)
  1333. res := &apiv1.GetEntitiesResponse{
  1334. EntityDefinitions: entityDefinitions,
  1335. }
  1336. return connect.NewResponse(res), nil
  1337. }
  1338. func buildSortedEntityInstances(entityType string, entityInstances map[string]*entities.Entity, properties []config.EntityProperty) []*apiv1.Entity {
  1339. instanceKeys := make([]string, 0, len(entityInstances))
  1340. for key := range entityInstances {
  1341. instanceKeys = append(instanceKeys, key)
  1342. }
  1343. sort.Strings(instanceKeys)
  1344. instances := make([]*apiv1.Entity, 0, len(instanceKeys))
  1345. for _, key := range instanceKeys {
  1346. e := entityInstances[key]
  1347. instances = append(instances, &apiv1.Entity{
  1348. Title: e.Title,
  1349. UniqueKey: e.UniqueKey,
  1350. Type: entityType,
  1351. Fields: entityListFields(e.Data, properties),
  1352. })
  1353. }
  1354. return instances
  1355. }
  1356. func findDashboardsForEntity(entityTitle string, dashboards []*config.DashboardComponent) []string {
  1357. var foundDashboards []string
  1358. seen := make(map[string]bool)
  1359. findEntityInComponents(entityTitle, "", dashboards, &foundDashboards, seen)
  1360. return foundDashboards
  1361. }
  1362. func findEntityInComponents(entityTitle string, parentTitle string, components []*config.DashboardComponent, foundDashboards *[]string, seen map[string]bool) {
  1363. for _, component := range components {
  1364. if component.Entity == entityTitle {
  1365. addEntityDashboard(component, parentTitle, foundDashboards, seen)
  1366. }
  1367. if len(component.Contents) > 0 {
  1368. findEntityInComponents(entityTitle, component.Title, component.Contents, foundDashboards, seen)
  1369. }
  1370. }
  1371. }
  1372. func addEntityDashboard(component *config.DashboardComponent, parentTitle string, foundDashboards *[]string, seen map[string]bool) {
  1373. if component.Type == "directory" {
  1374. addEntityDirectory(component, foundDashboards, seen)
  1375. } else {
  1376. addParentDashboard(parentTitle, foundDashboards, seen)
  1377. }
  1378. }
  1379. func addEntityDirectory(component *config.DashboardComponent, foundDashboards *[]string, seen map[string]bool) {
  1380. dashboardTitle := component.Title + " [Entity Directory]"
  1381. if !seen[dashboardTitle] {
  1382. *foundDashboards = append(*foundDashboards, dashboardTitle)
  1383. seen[dashboardTitle] = true
  1384. seen[component.Title] = true
  1385. }
  1386. }
  1387. func addParentDashboard(parentTitle string, foundDashboards *[]string, seen map[string]bool) {
  1388. if parentTitle != "" && !seen[parentTitle] {
  1389. *foundDashboards = append(*foundDashboards, parentTitle)
  1390. seen[parentTitle] = true
  1391. }
  1392. }
  1393. func findDirectoriesInEntityFieldsets(entityType string, dashboards []*config.DashboardComponent) []string {
  1394. var directories []string
  1395. for _, dashboard := range dashboards {
  1396. findDirectoriesInEntityFieldsetsRecursive(entityType, dashboard, &directories)
  1397. }
  1398. return directories
  1399. }
  1400. func findDirectoriesInEntityFieldsetsRecursive(entityType string, component *config.DashboardComponent, directories *[]string) {
  1401. if component.Entity == entityType {
  1402. collectDirectoriesFromComponent(component, directories)
  1403. }
  1404. if len(component.Contents) > 0 {
  1405. searchSubcomponentsForDirectories(entityType, component.Contents, directories)
  1406. }
  1407. }
  1408. func collectDirectoriesFromComponent(component *config.DashboardComponent, directories *[]string) {
  1409. for _, subitem := range component.Contents {
  1410. if subitem.Type == "directory" {
  1411. *directories = append(*directories, subitem.Title)
  1412. }
  1413. }
  1414. }
  1415. func searchSubcomponentsForDirectories(entityType string, contents []*config.DashboardComponent, directories *[]string) {
  1416. for _, subitem := range contents {
  1417. findDirectoriesInEntityFieldsetsRecursive(entityType, subitem, directories)
  1418. }
  1419. }
  1420. func (api *oliveTinAPI) GetEntity(ctx ctx.Context, req *connect.Request[apiv1.GetEntityRequest]) (*connect.Response[apiv1.Entity], error) {
  1421. user := auth.UserFromApiCall(ctx, req, api.cfg)
  1422. if err := api.checkDashboardAccess(user); err != nil {
  1423. return nil, err
  1424. }
  1425. instances := entities.GetEntityInstances(req.Msg.Type)
  1426. if len(instances) == 0 {
  1427. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("entity type %s not found", req.Msg.Type))
  1428. }
  1429. if !api.userCanViewEntityType(user, req.Msg.Type) {
  1430. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("entity type %s not found", req.Msg.Type))
  1431. }
  1432. entity, ok := instances[req.Msg.UniqueKey]
  1433. if !ok {
  1434. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("entity with unique key %s not found in type %s", req.Msg.UniqueKey, req.Msg.Type))
  1435. }
  1436. res := buildEntityResponse(entity, req.Msg.Type, api.cfg)
  1437. res.RelatedActions = api.relatedActionsForEntity(user, req.Msg.Type, entity)
  1438. return connect.NewResponse(res), nil
  1439. }
  1440. func entityTypeIcon(cfg *config.Config, entityType string) string {
  1441. entityFile := entityFileForType(cfg, entityType)
  1442. if entityFile == nil {
  1443. return ""
  1444. }
  1445. return entityFile.Icon
  1446. }
  1447. func entityFileForType(cfg *config.Config, entityType string) *config.EntityFile {
  1448. for _, entityFile := range cfg.Entities {
  1449. if entityFile != nil && entityFile.Name == entityType {
  1450. return entityFile
  1451. }
  1452. }
  1453. return nil
  1454. }
  1455. func entityPropertiesFromFile(entityFile *config.EntityFile) []config.EntityProperty {
  1456. if entityFile == nil {
  1457. return nil
  1458. }
  1459. return entityFile.Properties
  1460. }
  1461. func entityDefinitionProperties(properties []config.EntityProperty) []*apiv1.EntityProperty {
  1462. if len(properties) == 0 {
  1463. return nil
  1464. }
  1465. result := make([]*apiv1.EntityProperty, 0, len(properties))
  1466. for _, property := range properties {
  1467. result = append(result, &apiv1.EntityProperty{
  1468. Name: property.Name,
  1469. Title: property.Title,
  1470. })
  1471. }
  1472. return result
  1473. }
  1474. func entityListFields(data any, properties []config.EntityProperty) map[string]string {
  1475. if len(properties) == 0 {
  1476. return nil
  1477. }
  1478. dataMap, _ := data.(map[string]any)
  1479. displayFieldKey := entities.DisplayNameFieldKey(data)
  1480. fields := make(map[string]string, len(properties))
  1481. for _, property := range properties {
  1482. actualKey := entityDataPropertyKey(dataMap, property.Name)
  1483. if entityFieldIsSelectedDisplayName(actualKey, displayFieldKey) {
  1484. continue
  1485. }
  1486. fields[property.Name] = entityPropertyValue(data, property.Name)
  1487. }
  1488. return fields
  1489. }
  1490. func entityDataPropertyKey(dataMap map[string]any, propertyName string) string {
  1491. if dataMap == nil {
  1492. return propertyName
  1493. }
  1494. if _, found := dataMap[propertyName]; found {
  1495. return propertyName
  1496. }
  1497. propertyNameLower := strings.ToLower(propertyName)
  1498. for key := range dataMap {
  1499. if strings.ToLower(key) == propertyNameLower {
  1500. return key
  1501. }
  1502. }
  1503. return propertyName
  1504. }
  1505. func entityPropertyValue(data any, propertyName string) string {
  1506. dataMap, ok := data.(map[string]any)
  1507. if !ok {
  1508. return ""
  1509. }
  1510. if value, found := dataMap[propertyName]; found {
  1511. return fmt.Sprintf("%v", value)
  1512. }
  1513. return entityPropertyValueCaseInsensitive(dataMap, propertyName)
  1514. }
  1515. func entityPropertyValueCaseInsensitive(dataMap map[string]any, propertyName string) string {
  1516. propertyNameLower := strings.ToLower(propertyName)
  1517. for key, value := range dataMap {
  1518. if strings.ToLower(key) == propertyNameLower {
  1519. return fmt.Sprintf("%v", value)
  1520. }
  1521. }
  1522. return ""
  1523. }
  1524. func buildEntityResponse(entity *entities.Entity, entityType string, cfg *config.Config) *apiv1.Entity {
  1525. properties := entityPropertiesFromFile(entityFileForType(cfg, entityType))
  1526. res := &apiv1.Entity{
  1527. Title: entity.Title,
  1528. UniqueKey: entity.UniqueKey,
  1529. Type: entityType,
  1530. Directories: findDirectoriesInEntityFieldsets(entityType, cfg.Dashboards),
  1531. Fields: entityFieldsForResponse(entity.Data, properties),
  1532. Icon: entityTypeIcon(cfg, entityType),
  1533. }
  1534. return res
  1535. }
  1536. func serializeEntityFields(data any) map[string]string {
  1537. if data == nil {
  1538. return nil
  1539. }
  1540. dataMap, ok := data.(map[string]any)
  1541. if !ok {
  1542. return nil
  1543. }
  1544. return serializeEntityFieldsFromMap(dataMap, entities.DisplayNameFieldKey(data))
  1545. }
  1546. func serializeEntityFieldsFromMap(dataMap map[string]any, omitFieldKey string) map[string]string {
  1547. fields := make(map[string]string, len(dataMap))
  1548. for k, v := range dataMap {
  1549. if entityFieldIsSelectedDisplayName(k, omitFieldKey) {
  1550. continue
  1551. }
  1552. fields[k] = fmt.Sprintf("%v", v)
  1553. }
  1554. return fields
  1555. }
  1556. func entityFieldIsSelectedDisplayName(fieldName, displayFieldKey string) bool {
  1557. return displayFieldKey != "" && fieldName == displayFieldKey
  1558. }
  1559. func (api *oliveTinAPI) RestartAction(ctx ctx.Context, req *connect.Request[apiv1.RestartActionRequest]) (*connect.Response[apiv1.StartActionResponse], error) {
  1560. execReqLogEntry, err := api.restartActionLogEntry(req.Msg.ExecutionTrackingId)
  1561. if err != nil {
  1562. return nil, err
  1563. }
  1564. if err := validateRestartLogEntry(execReqLogEntry); err != nil {
  1565. return nil, err
  1566. }
  1567. authenticatedUser := auth.UserFromApiCall(ctx, req, api.cfg)
  1568. restartArgs := copyStringMap(execReqLogEntry.Arguments)
  1569. if err := api.errUnlessStartEntityAccessAllowed(authenticatedUser, execReqLogEntry.Binding, restartArgs); err != nil {
  1570. return nil, err
  1571. }
  1572. execReq := executor.ExecutionRequest{
  1573. Binding: execReqLogEntry.Binding,
  1574. Arguments: restartArgs,
  1575. Justification: execReqLogEntry.Justification,
  1576. AuthenticatedUser: authenticatedUser,
  1577. Cfg: api.cfg,
  1578. }
  1579. api.executor.ExecRequest(&execReq)
  1580. return connect.NewResponse(&apiv1.StartActionResponse{
  1581. ExecutionTrackingId: execReq.TrackingID,
  1582. }), nil
  1583. }
  1584. func (api *oliveTinAPI) restartActionLogEntry(executionTrackingId string) (*executor.InternalLogEntry, error) {
  1585. execReqLogEntry, found := api.executor.GetLog(executionTrackingId)
  1586. if !found {
  1587. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("execution not found for tracking ID %s", executionTrackingId))
  1588. }
  1589. if execReqLogEntry.Binding == nil {
  1590. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("log entry has no binding for tracking ID %s", executionTrackingId))
  1591. }
  1592. if execReqLogEntry.Binding.Action == nil {
  1593. return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action not found for tracking ID %s", executionTrackingId))
  1594. }
  1595. return execReqLogEntry, nil
  1596. }
  1597. var (
  1598. executorListenersMu sync.Mutex
  1599. executorListeners = map[*executor.Executor]*oliveTinAPI{}
  1600. )
  1601. // RegisterExecutorListener registers the API server as an executor listener during startup.
  1602. // Call this before background goroutines that may trigger RebuildActionMap.
  1603. func RegisterExecutorListener(ex *executor.Executor) {
  1604. server := ensureExecutorListener(ex)
  1605. if server.entityListenerRegistered {
  1606. return
  1607. }
  1608. server.entityListenerRegistered = true
  1609. entities.AddListener(server.onEntityChanged)
  1610. }
  1611. func ensureExecutorListener(ex *executor.Executor) *oliveTinAPI {
  1612. executorListenersMu.Lock()
  1613. defer executorListenersMu.Unlock()
  1614. if server, ok := executorListeners[ex]; ok {
  1615. return server
  1616. }
  1617. server := newServer(ex)
  1618. executorListeners[ex] = server
  1619. return server
  1620. }
  1621. func newServer(ex *executor.Executor) *oliveTinAPI {
  1622. server := &oliveTinAPI{
  1623. cfg: ex.Cfg,
  1624. executor: ex,
  1625. streamingClients: make(map[*streamingClient]struct{}),
  1626. }
  1627. ex.AddListener(server)
  1628. return server
  1629. }
  1630. func GetNewHandler(ex *executor.Executor) (string, http.Handler) {
  1631. server := ensureExecutorListener(ex)
  1632. jsonOpt := connectproto.WithJSON(
  1633. protojson.MarshalOptions{
  1634. EmitUnpopulated: true, // https://github.com/OliveTin/OliveTin/issues/674
  1635. },
  1636. protojson.UnmarshalOptions{
  1637. DiscardUnknown: true,
  1638. },
  1639. )
  1640. return apiv1connect.NewOliveTinApiServiceHandler(server, jsonOpt)
  1641. }