api.go 64 KB

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