api_test.go 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  1. package api
  2. import (
  3. "context"
  4. "net/http"
  5. "net/http/httptest"
  6. "path"
  7. "testing"
  8. "time"
  9. "connectrpc.com/connect"
  10. "github.com/google/uuid"
  11. log "github.com/sirupsen/logrus"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/stretchr/testify/require"
  14. apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1"
  15. apiv1connect "github.com/OliveTin/OliveTin/gen/olivetin/api/v1/apiv1connect"
  16. authpublic "github.com/OliveTin/OliveTin/internal/auth/authpublic"
  17. config "github.com/OliveTin/OliveTin/internal/config"
  18. "github.com/OliveTin/OliveTin/internal/entities"
  19. "github.com/OliveTin/OliveTin/internal/executor"
  20. )
  21. func getNewTestServerAndClient(injectedConfig *config.Config) (*httptest.Server, apiv1connect.OliveTinApiServiceClient) {
  22. ex := executor.DefaultExecutor(injectedConfig)
  23. ex.RebuildActionMap()
  24. return getNewTestServerAndClientWithExecutor(injectedConfig, ex)
  25. }
  26. func getNewTestServerAndClientWithExecutor(injectedConfig *config.Config, ex *executor.Executor) (*httptest.Server, apiv1connect.OliveTinApiServiceClient) {
  27. ex.Cfg = injectedConfig
  28. apiPath, apiHandler := GetNewHandler(ex)
  29. mux := http.NewServeMux()
  30. mux.Handle("/api/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  31. log.Infof("HTTP Request: %s %s", r.Method, r.URL.Path)
  32. // Translate /api/<service>/<method> to <service>/<method>
  33. fn := path.Base(r.URL.Path)
  34. r.URL.Path = apiPath + fn
  35. apiHandler.ServeHTTP(w, r)
  36. }))
  37. log.Infof("API path is %s", apiPath)
  38. httpclient := &http.Client{}
  39. ts := httptest.NewServer(mux)
  40. client := apiv1connect.NewOliveTinApiServiceClient(httpclient, ts.URL+"/api")
  41. log.Infof("Test server URL is %s", ts.URL+"/api"+apiPath)
  42. return ts, client
  43. }
  44. func TestApplyActionExecTriggersIncludesWebhookHeaderAndQueryMatches(t *testing.T) {
  45. cfg := &config.Action{
  46. ExecOnWebhook: []config.WebhookConfig{
  47. {
  48. MatchHeaders: map[string]string{"X-GitHub-Event": "push"},
  49. MatchQuery: map[string]string{"source": "github"},
  50. },
  51. },
  52. }
  53. pb := &apiv1.Action{}
  54. applyActionExecTriggers(pb, cfg)
  55. require.Len(t, pb.ExecOnWebhooks, 1)
  56. assert.Equal(t, cfg.ExecOnWebhook[0].MatchHeaders, pb.ExecOnWebhooks[0].MatchHeaders)
  57. assert.Equal(t, cfg.ExecOnWebhook[0].MatchQuery, pb.ExecOnWebhooks[0].MatchQuery)
  58. }
  59. func TestGetActionsAndStart(t *testing.T) {
  60. cfg := config.DefaultConfig()
  61. btn1 := &config.Action{}
  62. btn1.Title = "blat"
  63. btn1.ID = "blat"
  64. btn1.Shell = "echo 'test'"
  65. cfg.Actions = append(cfg.Actions, btn1)
  66. ex := executor.DefaultExecutor(cfg)
  67. ex.RebuildActionMap()
  68. conn, client := getNewTestServerAndClient(cfg)
  69. respInit, errInit := client.Init(context.Background(), connect.NewRequest(&apiv1.InitRequest{}))
  70. respGetReady, errReady := client.GetReadyz(context.Background(), connect.NewRequest(&apiv1.GetReadyzRequest{}))
  71. if errInit != nil {
  72. t.Errorf("Init request failed: %v", errInit)
  73. return
  74. }
  75. if errReady != nil {
  76. t.Errorf("GetReadyz request failed: %v", errReady)
  77. return
  78. }
  79. log.Infof("GetReadyz response: %v", respGetReady.Msg)
  80. // assert.Equal(t, 1, len(respGb.Msg.Actions), "Got 1 action button back")
  81. log.Printf("Response: %+v", respInit)
  82. respSa, err := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{
  83. // ActionId: "blat"
  84. }))
  85. require.Error(t, err, "Error 404 after start action")
  86. assert.Nil(t, respSa, "Nil response for non existing action")
  87. defer conn.Close()
  88. }
  89. func TestGetEntities(t *testing.T) {
  90. cfg := config.DefaultConfig()
  91. cfg.Entities = []*config.EntityFile{
  92. {
  93. Name: "server",
  94. Properties: []config.EntityProperty{
  95. {Name: "hostname", Title: "Hostname"},
  96. },
  97. },
  98. }
  99. cfg.Sanitize()
  100. ts, client := getNewTestServerAndClient(cfg)
  101. defer ts.Close()
  102. setupTestEntities()
  103. resp, err := client.GetEntities(context.Background(), connect.NewRequest(&apiv1.GetEntitiesRequest{}))
  104. require.NoError(t, err, "GetEntities should not return an error")
  105. require.NotNil(t, resp, "GetEntities response should not be nil")
  106. require.NotNil(t, resp.Msg, "GetEntities response message should not be nil")
  107. entityDefinitions := resp.Msg.EntityDefinitions
  108. require.Len(t, entityDefinitions, 3, "Should return 3 entity definitions")
  109. validateEntityOrderAndStructure(t, entityDefinitions)
  110. validateNoDuplicates(t, entityDefinitions)
  111. validateConsistency(t, client, entityDefinitions)
  112. validateEntityListProperties(t, client)
  113. }
  114. func validateEntityListProperties(t *testing.T, client apiv1connect.OliveTinApiServiceClient) {
  115. t.Helper()
  116. resp, err := client.GetEntities(context.Background(), connect.NewRequest(&apiv1.GetEntitiesRequest{
  117. EntityType: "server",
  118. Page: 1,
  119. PageSize: 10,
  120. }))
  121. require.NoError(t, err)
  122. require.Len(t, resp.Msg.EntityDefinitions, 1)
  123. serverDef := resp.Msg.EntityDefinitions[0]
  124. require.NotNil(t, serverDef, "server entity definition should be present")
  125. require.Len(t, serverDef.Properties, 1)
  126. assert.Equal(t, "hostname", serverDef.Properties[0].Name)
  127. assert.Equal(t, "Hostname", serverDef.Properties[0].Title)
  128. assert.Equal(t, int32(3), serverDef.TotalInstances)
  129. require.Len(t, serverDef.Instances, 3)
  130. assert.Equal(t, "alpha.example.com", serverDef.Instances[0].Fields["hostname"])
  131. }
  132. func setupTestEntities() {
  133. entities.ClearEntitiesOfType("server")
  134. entities.ClearEntitiesOfType("database")
  135. entities.ClearEntitiesOfType("application")
  136. entities.AddEntity("server", "zebra", map[string]any{"title": "Server Zebra", "hostname": "zebra.example.com"})
  137. entities.AddEntity("server", "alpha", map[string]any{"title": "Server Alpha", "hostname": "alpha.example.com"})
  138. entities.AddEntity("server", "beta", map[string]any{"title": "Server Beta", "hostname": "beta.example.com"})
  139. entities.AddEntity("database", "mysql", map[string]any{"title": "MySQL Database", "type": "mysql"})
  140. entities.AddEntity("database", "postgres", map[string]any{"title": "PostgreSQL Database", "type": "postgres"})
  141. entities.AddEntity("application", "webapp", map[string]any{"title": "Web Application", "port": 8080})
  142. }
  143. func validateEntityOrderAndStructure(t *testing.T, entityDefinitions []*apiv1.EntityDefinition) {
  144. t.Helper()
  145. require.GreaterOrEqual(t, len(entityDefinitions), 3, "Need at least three entity definitions before indexing")
  146. assert.Equal(t, "application", entityDefinitions[0].Title, "First entity should be 'application' (alphabetically first)")
  147. assert.Len(t, entityDefinitions[0].Instances, 1, "Application should have 1 instance")
  148. assert.Equal(t, "webapp", entityDefinitions[0].Instances[0].UniqueKey, "Application instance should be 'webapp'")
  149. assert.Equal(t, "database", entityDefinitions[1].Title, "Second entity should be 'database' (alphabetically second)")
  150. assert.Len(t, entityDefinitions[1].Instances, 2, "Database should have 2 instances")
  151. assert.Equal(t, "mysql", entityDefinitions[1].Instances[0].UniqueKey, "First database instance should be 'mysql' (alphabetically first)")
  152. assert.Equal(t, "postgres", entityDefinitions[1].Instances[1].UniqueKey, "Second database instance should be 'postgres' (alphabetically second)")
  153. assert.Equal(t, "server", entityDefinitions[2].Title, "Third entity should be 'server' (alphabetically third)")
  154. assert.Empty(t, entityDefinitions[2].Instances, "Server instances should not be included in bulk list response")
  155. assert.Equal(t, int32(3), entityDefinitions[2].TotalInstances, "Server should report total instance count")
  156. }
  157. func validateNoDuplicates(t *testing.T, entityDefinitions []*apiv1.EntityDefinition) {
  158. t.Helper()
  159. instanceKeys := make(map[string]map[string]bool)
  160. for _, def := range entityDefinitions {
  161. instanceKeys[def.Title] = make(map[string]bool)
  162. for _, inst := range def.Instances {
  163. assert.False(t, instanceKeys[def.Title][inst.UniqueKey], "Instance key %s should not be duplicated in entity %s", inst.UniqueKey, def.Title)
  164. instanceKeys[def.Title][inst.UniqueKey] = true
  165. }
  166. }
  167. }
  168. func validateConsistency(t *testing.T, client apiv1connect.OliveTinApiServiceClient, entityDefinitions []*apiv1.EntityDefinition) {
  169. t.Helper()
  170. resp2, err2 := client.GetEntities(context.Background(), connect.NewRequest(&apiv1.GetEntitiesRequest{}))
  171. require.NoError(t, err2, "Second GetEntities call should not return an error")
  172. require.NotNil(t, resp2.Msg)
  173. require.Len(t, resp2.Msg.EntityDefinitions, len(entityDefinitions), "Second call should return same number of entity definitions")
  174. for i, def := range entityDefinitions {
  175. assert.Equal(t, def.Title, resp2.Msg.EntityDefinitions[i].Title, "Entity order should be consistent across calls")
  176. require.Len(t, resp2.Msg.EntityDefinitions[i].Instances, len(def.Instances), "Instance count should be consistent")
  177. for j, inst := range def.Instances {
  178. assert.Equal(t, inst.UniqueKey, resp2.Msg.EntityDefinitions[i].Instances[j].UniqueKey, "Instance order should be consistent across calls")
  179. }
  180. }
  181. }
  182. func TestEvaluateEnabledExpression(t *testing.T) {
  183. tests := []struct {
  184. entity *entities.Entity
  185. name string
  186. expression string
  187. expectedResult bool
  188. }{
  189. {
  190. name: "empty expression returns true",
  191. expression: "",
  192. entity: nil,
  193. expectedResult: true,
  194. },
  195. {
  196. name: "literal true returns true",
  197. expression: "true",
  198. entity: nil,
  199. expectedResult: true,
  200. },
  201. {
  202. name: "literal True returns true (case insensitive)",
  203. expression: "True",
  204. entity: nil,
  205. expectedResult: true,
  206. },
  207. {
  208. name: "literal 1 returns true",
  209. expression: "1",
  210. entity: nil,
  211. expectedResult: true,
  212. },
  213. {
  214. name: "literal false returns false",
  215. expression: "false",
  216. entity: nil,
  217. expectedResult: false,
  218. },
  219. {
  220. name: "literal 0 returns false",
  221. expression: "0",
  222. entity: nil,
  223. expectedResult: false,
  224. },
  225. {
  226. name: "empty result returns false",
  227. expression: "{{ .NonExistent }}",
  228. entity: nil,
  229. expectedResult: false,
  230. },
  231. {
  232. name: "expression with CurrentEntity true",
  233. expression: "{{ eq .CurrentEntity.powered_on true }}",
  234. entity: &entities.Entity{Data: map[string]any{"powered_on": true}},
  235. expectedResult: true,
  236. },
  237. {
  238. name: "expression with CurrentEntity false",
  239. expression: "{{ eq .CurrentEntity.powered_on true }}",
  240. entity: &entities.Entity{Data: map[string]any{"powered_on": false}},
  241. expectedResult: false,
  242. },
  243. {
  244. name: "expression with CurrentEntity integer 1",
  245. expression: "{{ .CurrentEntity.status }}",
  246. entity: &entities.Entity{Data: map[string]any{"status": 1}},
  247. expectedResult: true,
  248. },
  249. {
  250. name: "expression with CurrentEntity integer 0",
  251. expression: "{{ .CurrentEntity.status }}",
  252. entity: &entities.Entity{Data: map[string]any{"status": 0}},
  253. expectedResult: false,
  254. },
  255. {
  256. name: "template parse error returns false",
  257. expression: "{{ invalid syntax }}",
  258. entity: nil,
  259. expectedResult: false,
  260. },
  261. {
  262. name: "template exec error returns false",
  263. expression: "{{ .CurrentEntity.nonexistent }}",
  264. entity: nil,
  265. expectedResult: false,
  266. },
  267. }
  268. for _, tt := range tests {
  269. t.Run(tt.name, func(t *testing.T) {
  270. action := &config.Action{
  271. EnabledExpression: tt.expression,
  272. }
  273. result := evaluateEnabledExpression(action, tt.entity)
  274. assert.Equal(t, tt.expectedResult, result, "evaluateEnabledExpression should return expected result")
  275. })
  276. }
  277. }
  278. func TestBuildActionWithEnabledExpression(t *testing.T) {
  279. cfg := config.DefaultConfig()
  280. cfg.DefaultPermissions.Exec = true
  281. action := &config.Action{
  282. Title: "Test Action",
  283. Shell: "echo test",
  284. EnabledExpression: "{{ eq .CurrentEntity.enabled true }}",
  285. }
  286. cfg.Actions = append(cfg.Actions, action)
  287. ex := executor.DefaultExecutor(cfg)
  288. ex.RebuildActionMap()
  289. binding := findBindingByTitle(ex, "Test Action")
  290. assert.NotNil(t, binding, "Binding should be found")
  291. rr := &DashboardRenderRequest{
  292. AuthenticatedUser: &authpublic.AuthenticatedUser{Username: "testuser"},
  293. cfg: cfg,
  294. ex: ex,
  295. }
  296. testWithEntity(t, binding, rr, true, true, "Action should be executable when entity.enabled is true")
  297. testWithEntity(t, binding, rr, false, false, "Action should not be executable when entity.enabled is false")
  298. bindingNoExpr := findBindingByTitle(ex, "Test Action No Expression")
  299. if bindingNoExpr == nil {
  300. actionNoExpression := &config.Action{
  301. Title: "Test Action No Expression",
  302. Shell: "echo test",
  303. }
  304. cfg.Actions = append(cfg.Actions, actionNoExpression)
  305. ex.RebuildActionMap()
  306. bindingNoExpr = findBindingByTitle(ex, "Test Action No Expression")
  307. }
  308. actionResult := buildAction(bindingNoExpr, rr)
  309. assert.True(t, actionResult.CanExec, "Action without enabledExpression should be executable")
  310. }
  311. func findBindingByTitle(ex *executor.Executor, title string) *executor.ActionBinding {
  312. ex.MapActionBindingsLock.RLock()
  313. defer ex.MapActionBindingsLock.RUnlock()
  314. for _, b := range ex.MapActionBindings {
  315. if b.Action.Title == title {
  316. return b
  317. }
  318. }
  319. return nil
  320. }
  321. func testWithEntity(t *testing.T, binding *executor.ActionBinding, rr *DashboardRenderRequest, enabled bool, expectedCanExec bool, message string) {
  322. t.Helper()
  323. binding.Entity = &entities.Entity{
  324. UniqueKey: "test-entity",
  325. Data: map[string]any{"enabled": enabled},
  326. }
  327. actionResult := buildAction(binding, rr)
  328. assert.Equal(t, expectedCanExec, actionResult.CanExec, message)
  329. }
  330. // buildExecWithoutLogsTestConfig returns config for GHSA-jm28-2wcr-qf3h: user "runner" may exec but not read logs.
  331. func buildExecWithoutLogsTestConfig(t *testing.T) (*config.Config, *authpublic.AuthenticatedUser) {
  332. t.Helper()
  333. cfg := config.DefaultConfig()
  334. cfg.AuthHttpHeaderUsername = "X-Ot-User"
  335. cfg.DefaultPermissions.View = false
  336. cfg.DefaultPermissions.Exec = false
  337. cfg.DefaultPermissions.Logs = false
  338. cfg.Actions = append(cfg.Actions, &config.Action{
  339. ID: "run_only",
  340. Title: "Run Only",
  341. Shell: "echo sensitive-output",
  342. Icon: "🔒",
  343. })
  344. cfg.AccessControlLists = append(cfg.AccessControlLists, &config.AccessControlList{
  345. Name: "runner",
  346. MatchUsernames: []string{"runner"},
  347. AddToEveryAction: true,
  348. Permissions: config.PermissionsList{View: true, Exec: true, Logs: false, Kill: false},
  349. })
  350. runner := &authpublic.AuthenticatedUser{Username: "runner"}
  351. runner.BuildUserAcls(cfg)
  352. return cfg, runner
  353. }
  354. // TestStartActionAndWaitDeniesLogsPermission (GHSA-jm28-2wcr-qf3h) asserts sync execution endpoints
  355. // enforce logs ACL and do not return action output to users allowed to exec but not read logs.
  356. func TestStartActionAndWaitDeniesLogsPermission(t *testing.T) {
  357. cfg, _ := buildExecWithoutLogsTestConfig(t)
  358. ex := executor.DefaultExecutor(cfg)
  359. ex.RebuildActionMap()
  360. ts, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  361. defer ts.Close()
  362. req := connect.NewRequest(&apiv1.StartActionAndWaitRequest{
  363. ActionId: "run_only",
  364. })
  365. req.Header().Set("X-Ot-User", "runner")
  366. _, err := client.StartActionAndWait(context.Background(), req)
  367. require.Error(t, err)
  368. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  369. "user with exec:true and logs:false must not receive log output from StartActionAndWait")
  370. }
  371. // buildViewPermissionTestConfig returns config and users for GHSA view-permission tests:
  372. // one action "secret_action", ACL "restricted" (view:false, logs:false) for user "low", ACL "full" (view:true, logs:true) for user "admin".
  373. func buildViewPermissionTestConfig(t *testing.T) (*config.Config, *authpublic.AuthenticatedUser, *authpublic.AuthenticatedUser) {
  374. t.Helper()
  375. cfg := config.DefaultConfig()
  376. cfg.DefaultPermissions.View = false
  377. cfg.DefaultPermissions.Exec = false
  378. cfg.DefaultPermissions.Logs = false
  379. cfg.Actions = append(cfg.Actions, &config.Action{
  380. ID: "secret_action",
  381. Title: "Secret Action",
  382. Shell: "echo sensitive",
  383. Icon: "🔒",
  384. })
  385. cfg.AccessControlLists = append(cfg.AccessControlLists,
  386. &config.AccessControlList{
  387. Name: "restricted",
  388. MatchUsernames: []string{"low"},
  389. AddToEveryAction: true,
  390. Permissions: config.PermissionsList{View: false, Exec: false, Logs: false, Kill: false},
  391. },
  392. &config.AccessControlList{
  393. Name: "full",
  394. MatchUsernames: []string{"admin"},
  395. AddToEveryAction: true,
  396. Permissions: config.PermissionsList{View: true, Exec: true, Logs: true, Kill: true},
  397. },
  398. )
  399. lowUser := &authpublic.AuthenticatedUser{Username: "low"}
  400. lowUser.BuildUserAcls(cfg)
  401. adminUser := &authpublic.AuthenticatedUser{Username: "admin"}
  402. adminUser.BuildUserAcls(cfg)
  403. return cfg, lowUser, adminUser
  404. }
  405. // TestViewPermissionExcludedFromDashboard (GHSA: view permission) asserts that when a user has view: false,
  406. // the default dashboard must not include that action. Covers GetDashboard not leaking action metadata.
  407. func TestViewPermissionExcludedFromDashboard(t *testing.T) {
  408. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  409. ex := executor.DefaultExecutor(cfg)
  410. ex.RebuildActionMap()
  411. rr := &DashboardRenderRequest{
  412. AuthenticatedUser: lowUser,
  413. cfg: cfg,
  414. ex: ex,
  415. }
  416. db := buildDefaultDashboard(rr)
  417. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  418. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  419. "user with view:false must not see action in dashboard; got bindingIds: %v", bindingIdsInDashboard)
  420. }
  421. // TestGetActionBindingDeniedWhenNoViewPermission (GHSA: view permission) asserts that GetActionBinding
  422. // returns permission denied for a user with view: false. Covers GetActionBinding not exposing action details.
  423. func TestGetActionBindingDeniedWhenNoViewPermission(t *testing.T) {
  424. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  425. ex := executor.DefaultExecutor(cfg)
  426. ex.RebuildActionMap()
  427. api := newServer(ex)
  428. _, err := api.getActionBindingResponse(lowUser, "secret_action")
  429. require.Error(t, err)
  430. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  431. "user with view:false must get permission denied from GetActionBinding")
  432. }
  433. // TestValidateArgumentTypeDeniesGuestsWhenLoginRequired (GHSA-f637-w7p2-m7fx) asserts that when
  434. // guests must log in, ValidateArgumentType does not bypass dashboard access controls.
  435. func TestValidateArgumentTypeDeniesGuestsWhenLoginRequired(t *testing.T) {
  436. cfg := config.DefaultConfig()
  437. cfg.AuthRequireGuestsToLogin = true
  438. cfg.Actions = append(cfg.Actions, &config.Action{
  439. ID: "a1",
  440. Title: "Probe",
  441. Shell: "echo",
  442. Arguments: []config.ActionArgument{
  443. {Name: "x", Type: "ascii"},
  444. },
  445. })
  446. ex := executor.DefaultExecutor(cfg)
  447. ex.RebuildActionMap()
  448. ts, client := getNewTestServerAndClient(cfg)
  449. defer ts.Close()
  450. _, err := client.ValidateArgumentType(context.Background(), connect.NewRequest(&apiv1.ValidateArgumentTypeRequest{
  451. BindingId: "a1",
  452. ArgumentName: "x",
  453. Value: "v",
  454. Type: "ascii",
  455. }))
  456. require.Error(t, err)
  457. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  458. "guest must not call ValidateArgumentType when AuthRequireGuestsToLogin is true")
  459. }
  460. // TestValidateArgumentTypeDeniedWithoutViewPermission (GHSA-f637-w7p2-m7fx) asserts ValidateArgumentType
  461. // respects the same view ACL as GetActionBinding so the RPC cannot enumerate restricted actions.
  462. func TestValidateArgumentTypeDeniedWithoutViewPermission(t *testing.T) {
  463. cfg, _, _ := buildViewPermissionTestConfig(t)
  464. cfg.AuthHttpHeaderUsername = "X-Ot-User"
  465. for i := range cfg.Actions {
  466. if cfg.Actions[i].ID == "secret_action" {
  467. cfg.Actions[i].Arguments = []config.ActionArgument{{Name: "target", Type: "ascii"}}
  468. break
  469. }
  470. }
  471. ex := executor.DefaultExecutor(cfg)
  472. ex.RebuildActionMap()
  473. ts, client := getNewTestServerAndClient(cfg)
  474. defer ts.Close()
  475. req := connect.NewRequest(&apiv1.ValidateArgumentTypeRequest{
  476. BindingId: "secret_action",
  477. ArgumentName: "target",
  478. Value: "ok",
  479. Type: "ascii",
  480. })
  481. req.Header().Set("X-Ot-User", "low")
  482. _, err := client.ValidateArgumentType(context.Background(), req)
  483. require.Error(t, err)
  484. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  485. "user with view:false must get permission denied from ValidateArgumentType")
  486. }
  487. // TestValidateArgumentTypeAllowedWithViewPermission (GHSA-f637-w7p2-m7fx) asserts authenticated users
  488. // with view access can still use ValidateArgumentType for argument validation.
  489. func TestValidateArgumentTypeAllowedWithViewPermission(t *testing.T) {
  490. cfg, _, _ := buildViewPermissionTestConfig(t)
  491. cfg.AuthHttpHeaderUsername = "X-Ot-User"
  492. for i := range cfg.Actions {
  493. if cfg.Actions[i].ID == "secret_action" {
  494. cfg.Actions[i].Arguments = []config.ActionArgument{{Name: "target", Type: "ascii"}}
  495. break
  496. }
  497. }
  498. ex := executor.DefaultExecutor(cfg)
  499. ex.RebuildActionMap()
  500. ts, client := getNewTestServerAndClient(cfg)
  501. defer ts.Close()
  502. req := connect.NewRequest(&apiv1.ValidateArgumentTypeRequest{
  503. BindingId: "secret_action",
  504. ArgumentName: "target",
  505. Value: "ok",
  506. Type: "ascii",
  507. })
  508. req.Header().Set("X-Ot-User", "admin")
  509. resp, err := client.ValidateArgumentType(context.Background(), req)
  510. require.NoError(t, err)
  511. require.NotNil(t, resp)
  512. require.NotNil(t, resp.Msg)
  513. assert.True(t, resp.Msg.Valid, "admin with view:true should get successful validation for a valid ascii value")
  514. }
  515. // TestViewPermissionAllowedSeesAction (GHSA: view permission) asserts that a user with view: true
  516. // still sees the action in the dashboard and can fetch it via GetActionBinding.
  517. func TestViewPermissionAllowedSeesAction(t *testing.T) {
  518. cfg, _, adminUser := buildViewPermissionTestConfig(t)
  519. ex := executor.DefaultExecutor(cfg)
  520. ex.RebuildActionMap()
  521. api := newServer(ex)
  522. rr := &DashboardRenderRequest{
  523. AuthenticatedUser: adminUser,
  524. cfg: cfg,
  525. ex: ex,
  526. }
  527. db := buildDefaultDashboard(rr)
  528. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  529. assert.Contains(t, bindingIdsInDashboard, "secret_action",
  530. "user with view:true must see action in dashboard; got bindingIds: %v", bindingIdsInDashboard)
  531. resp, err := api.getActionBindingResponse(adminUser, "secret_action")
  532. require.NoError(t, err)
  533. require.NotNil(t, resp)
  534. require.NotNil(t, resp.Action)
  535. assert.Equal(t, "secret_action", resp.Action.BindingId)
  536. }
  537. // TestGetActionBindingAllowsHiddenWhenViewAllowed asserts that hidden is not a security control:
  538. // users with view permission can fetch action details for hidden actions (e.g. webhook helpers).
  539. func TestGetActionBindingAllowsHiddenWhenViewAllowed(t *testing.T) {
  540. cfg, lowUser, adminUser := buildViewPermissionTestConfig(t)
  541. cfg.Actions = append(cfg.Actions, &config.Action{
  542. ID: "webhook_helper",
  543. Title: "Webhook Helper",
  544. Shell: "echo webhook",
  545. Hidden: true,
  546. })
  547. ex := executor.DefaultExecutor(cfg)
  548. ex.RebuildActionMap()
  549. api := newServer(ex)
  550. rr := &DashboardRenderRequest{
  551. AuthenticatedUser: adminUser,
  552. cfg: cfg,
  553. ex: ex,
  554. }
  555. db := buildDefaultDashboard(rr)
  556. assert.NotContains(t, bindingIdsInDashboardContents(db.Contents), "webhook_helper",
  557. "hidden actions must stay off the default dashboard")
  558. resp, err := api.getActionBindingResponse(adminUser, "webhook_helper")
  559. require.NoError(t, err)
  560. require.NotNil(t, resp)
  561. require.NotNil(t, resp.Action)
  562. assert.Equal(t, "webhook_helper", resp.Action.BindingId)
  563. assert.Equal(t, "Webhook Helper", resp.Action.Title)
  564. _, err = api.getActionBindingResponse(lowUser, "webhook_helper")
  565. require.Error(t, err)
  566. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  567. "users without view ACL must still be denied for hidden actions")
  568. }
  569. // TestViewPermissionExcludedFromCustomDashboard (issue #921) asserts that when a custom dashboard
  570. // lists an action by title, users without view permission do not see that action (title or icon).
  571. func TestViewPermissionExcludedFromCustomDashboard(t *testing.T) {
  572. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  573. cfg.Dashboards = []*config.DashboardComponent{
  574. {
  575. Title: "Custom",
  576. Contents: []*config.DashboardComponent{
  577. {Title: "Secret Action"},
  578. },
  579. },
  580. }
  581. ex := executor.DefaultExecutor(cfg)
  582. ex.RebuildActionMap()
  583. rr := &DashboardRenderRequest{
  584. AuthenticatedUser: lowUser,
  585. cfg: cfg,
  586. ex: ex,
  587. }
  588. dashboard := findDashboardByTitle(rr, "Custom")
  589. require.NotNil(t, dashboard)
  590. db := buildDashboardFromConfig(dashboard, rr)
  591. require.NotNil(t, db)
  592. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  593. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  594. "user with view:false must not see action on custom dashboard; got bindingIds: %v", bindingIdsInDashboard)
  595. assert.False(t, dashboardContentsContainForbiddenComponent(db.Contents, "Secret Action", "🔒"),
  596. "user with view:false must not see Secret Action title or lock icon in custom dashboard")
  597. }
  598. // TestViewPermissionExcludedFromEntityDashboard (GHSA: view permission) asserts that when a dashboard
  599. // has an entity fieldset listing an action, users without view permission do not see that action.
  600. func TestViewPermissionExcludedFromEntityDashboard(t *testing.T) {
  601. entities.ClearEntitiesOfType("vp_entity_test")
  602. defer entities.ClearEntitiesOfType("vp_entity_test")
  603. entities.AddEntity("vp_entity_test", "1", map[string]any{"title": "Test Entity"})
  604. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  605. cfg.Dashboards = []*config.DashboardComponent{
  606. {
  607. Title: "WithEntity",
  608. Contents: []*config.DashboardComponent{
  609. {
  610. Title: "Servers", Type: "fieldset", Entity: "vp_entity_test",
  611. Contents: []*config.DashboardComponent{{Title: "Secret Action"}},
  612. },
  613. },
  614. },
  615. }
  616. ex := executor.DefaultExecutor(cfg)
  617. ex.RebuildActionMap()
  618. rr := &DashboardRenderRequest{
  619. AuthenticatedUser: lowUser,
  620. cfg: cfg,
  621. ex: ex,
  622. }
  623. dashboard := findDashboardByTitle(rr, "WithEntity")
  624. require.NotNil(t, dashboard)
  625. db := buildDashboardFromConfig(dashboard, rr)
  626. require.NotNil(t, db)
  627. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  628. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  629. "user with view:false must not see action in entity fieldset; got bindingIds: %v", bindingIdsInDashboard)
  630. assert.False(t, dashboardContentsContainForbiddenComponent(db.Contents, "Secret Action", "🔒"),
  631. "user with view:false must not see Secret Action title or lock icon in entity dashboard")
  632. }
  633. func bindingIdsInDashboardContents(contents []*apiv1.DashboardComponent) []string {
  634. var ids []string
  635. for _, c := range contents {
  636. ids = append(ids, bindingIdsFromComponent(c)...)
  637. }
  638. return ids
  639. }
  640. func bindingIdsFromComponent(c *apiv1.DashboardComponent) []string {
  641. if c == nil {
  642. return nil
  643. }
  644. var ids []string
  645. if c.Action != nil && c.Action.BindingId != "" {
  646. ids = append(ids, c.Action.BindingId)
  647. }
  648. return append(ids, bindingIdsInDashboardContents(c.Contents)...)
  649. }
  650. func componentHasForbiddenTitleOrIcon(c *apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  651. return c != nil && (c.Title == forbiddenTitle || c.Icon == forbiddenIcon)
  652. }
  653. func componentOrDescendantsContainForbidden(c *apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  654. if c == nil {
  655. return false
  656. }
  657. if componentHasForbiddenTitleOrIcon(c, forbiddenTitle, forbiddenIcon) {
  658. return true
  659. }
  660. return dashboardContentsContainForbiddenComponent(c.Contents, forbiddenTitle, forbiddenIcon)
  661. }
  662. // dashboardContentsContainForbiddenComponent recursively walks contents and returns true if any
  663. // component has Title == forbiddenTitle or Icon == forbiddenIcon.
  664. func dashboardContentsContainForbiddenComponent(contents []*apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  665. for _, c := range contents {
  666. if componentOrDescendantsContainForbidden(c, forbiddenTitle, forbiddenIcon) {
  667. return true
  668. }
  669. }
  670. return false
  671. }
  672. func TestOrderTopLevelDashboardComponents_RegularFieldsetsPreserveConfigOrder(t *testing.T) {
  673. zebra := &apiv1.DashboardComponent{Title: "Zebra", Type: "fieldset", EntityType: ""}
  674. alpha := &apiv1.DashboardComponent{Title: "Alpha", Type: "fieldset", EntityType: ""}
  675. root := &apiv1.DashboardComponent{Title: "Actions", Type: "fieldset", EntityType: ""}
  676. components := []*apiv1.DashboardComponent{zebra, alpha, root}
  677. out := orderTopLevelDashboardComponents(components, root)
  678. require.Len(t, out, 3)
  679. assert.Same(t, zebra, out[0], "first must be Zebra (config order)")
  680. assert.Same(t, alpha, out[1], "second must be Alpha (config order)")
  681. assert.Same(t, root, out[2], "third must be root Actions fieldset")
  682. }
  683. func TestOrderTopLevelDashboardComponents_SortablesSorted(t *testing.T) {
  684. entityBeta := &apiv1.DashboardComponent{Title: "Beta", Type: "fieldset", EntityType: "server"}
  685. entityAlpha := &apiv1.DashboardComponent{Title: "Alpha", Type: "fieldset", EntityType: "server"}
  686. components := []*apiv1.DashboardComponent{entityBeta, entityAlpha}
  687. out := orderTopLevelDashboardComponents(components, nil)
  688. require.Len(t, out, 2)
  689. assert.Equal(t, "Alpha", out[0].Title, "sortables ordered by title")
  690. assert.Equal(t, "Beta", out[1].Title)
  691. }
  692. // TestEventStreamACLNoLeakToUnauthorizedUser (GHSA-228v-wc5r-j8m7) asserts that EventStream
  693. // does not send execution events or output chunks to users who are not allowed to view that action's logs.
  694. func TestEventStreamACLNoLeakToUnauthorizedUser(t *testing.T) {
  695. cfg, lowUser, adminUser := buildViewPermissionTestConfig(t)
  696. ex := executor.DefaultExecutor(cfg)
  697. ex.RebuildActionMap()
  698. api := newServer(ex)
  699. binding := ex.FindBindingByID("secret_action")
  700. require.NotNil(t, binding, "secret_action binding must exist")
  701. clientLow, clientAdmin := addEventStreamTestClients(t, api, lowUser, adminUser)
  702. defer removeEventStreamTestClients(api, clientLow, clientAdmin)
  703. runEventStreamTestExecution(t, ex, cfg, binding, adminUser)
  704. adminEvents := drainEventStreamUntilFinished(clientAdmin.channel, 2*time.Second)
  705. lowEvents := drainEventStreamWithTimeout(clientLow.channel, 50*time.Millisecond)
  706. assertEventStreamLowUserReceivesNothing(t, lowEvents)
  707. assertEventStreamAdminReceivesSecretActionEvents(t, adminEvents)
  708. }
  709. func TestEntityChangedEventBroadcast(t *testing.T) {
  710. cfg := config.DefaultConfig()
  711. ex := executor.DefaultExecutor(cfg)
  712. api := newServer(ex)
  713. user := &authpublic.AuthenticatedUser{Username: "entity-test"}
  714. client := &streamingClient{
  715. channel: make(chan *apiv1.EventStreamResponse, 1),
  716. AuthenticatedUser: user,
  717. heartbeatStop: make(chan struct{}),
  718. heartbeatDone: make(chan struct{}),
  719. }
  720. close(client.heartbeatDone)
  721. require.NoError(t, api.registerStreamingClient(client))
  722. defer api.removeClient(client)
  723. api.onEntityChanged()
  724. select {
  725. case ev := <-client.channel:
  726. require.NotNil(t, ev.GetEntityChanged())
  727. default:
  728. t.Fatal("expected EventEntityChanged on event stream")
  729. }
  730. }
  731. func TestRegisterStreamingClientEnforcesLimit(t *testing.T) {
  732. cfg := config.DefaultConfig()
  733. ex := executor.DefaultExecutor(cfg)
  734. api := newServer(ex)
  735. user := &authpublic.AuthenticatedUser{Username: "limit-test"}
  736. clients := make([]*streamingClient, 0, maxEventStreamClients)
  737. for i := 0; i < maxEventStreamClients; i++ {
  738. client := &streamingClient{
  739. channel: make(chan *apiv1.EventStreamResponse, 1),
  740. AuthenticatedUser: user,
  741. heartbeatStop: make(chan struct{}),
  742. heartbeatDone: make(chan struct{}),
  743. }
  744. close(client.heartbeatDone)
  745. require.NoError(t, api.registerStreamingClient(client))
  746. clients = append(clients, client)
  747. }
  748. overflow := &streamingClient{
  749. channel: make(chan *apiv1.EventStreamResponse, 1),
  750. AuthenticatedUser: user,
  751. heartbeatStop: make(chan struct{}),
  752. heartbeatDone: make(chan struct{}),
  753. }
  754. close(overflow.heartbeatDone)
  755. err := api.registerStreamingClient(overflow)
  756. require.ErrorIs(t, err, errEventStreamClientLimit)
  757. assert.Len(t, api.streamingClients, maxEventStreamClients)
  758. api.removeClient(clients[0])
  759. require.NoError(t, api.registerStreamingClient(overflow))
  760. assert.Len(t, api.streamingClients, maxEventStreamClients)
  761. for _, client := range clients[1:] {
  762. api.removeClient(client)
  763. }
  764. api.removeClient(overflow)
  765. }
  766. // TestEventStreamReleasesSlotWhenClientDisconnects fills every EventStream slot,
  767. // disconnects all those clients and expects the slots to be released right
  768. // away, so a new client is accepted instead of being rejected with
  769. // "concurrent client limit reached".
  770. func TestEventStreamReleasesSlotWhenClientDisconnects(t *testing.T) {
  771. cfg := config.DefaultConfig()
  772. ex := executor.DefaultExecutor(cfg)
  773. ex.RebuildActionMap()
  774. ts, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  775. defer ts.Close()
  776. server := ensureExecutorListener(ex)
  777. cancels := make([]context.CancelFunc, 0, maxEventStreamClients)
  778. for i := 0; i < maxEventStreamClients; i++ {
  779. cancels = append(cancels, openEventStreamAndReadHeartbeat(t, client))
  780. }
  781. require.Equal(t, maxEventStreamClients, countStreamingClients(server))
  782. for _, cancel := range cancels {
  783. cancel()
  784. }
  785. // The next heartbeat is 10s away, so anything under that proves the
  786. // disconnect itself released the slots, not a later failed write.
  787. require.Eventually(t, func() bool {
  788. return countStreamingClients(server) == 0
  789. }, 2*time.Second, 10*time.Millisecond, "disconnected EventStream clients still hold their slots")
  790. cancel := openEventStreamAndReadHeartbeat(t, client)
  791. cancel()
  792. }
  793. func openEventStreamAndReadHeartbeat(t *testing.T, client apiv1connect.OliveTinApiServiceClient) context.CancelFunc {
  794. t.Helper()
  795. ctx, cancel := context.WithCancel(context.Background())
  796. stream, err := client.EventStream(ctx, connect.NewRequest(&apiv1.EventStreamRequest{}))
  797. require.NoError(t, err)
  798. require.True(t, stream.Receive(), "expected an initial heartbeat, got error: %v", stream.Err())
  799. require.NotNil(t, stream.Msg().GetHeartbeat())
  800. return cancel
  801. }
  802. func countStreamingClients(api *oliveTinAPI) int {
  803. api.streamingClientsMutex.RLock()
  804. defer api.streamingClientsMutex.RUnlock()
  805. return len(api.streamingClients)
  806. }
  807. func addEventStreamTestClients(t *testing.T, api *oliveTinAPI, lowUser, adminUser *authpublic.AuthenticatedUser) (*streamingClient, *streamingClient) {
  808. t.Helper()
  809. clientLow := &streamingClient{
  810. channel: make(chan *apiv1.EventStreamResponse, 20),
  811. AuthenticatedUser: lowUser,
  812. }
  813. clientAdmin := &streamingClient{
  814. channel: make(chan *apiv1.EventStreamResponse, 20),
  815. AuthenticatedUser: adminUser,
  816. }
  817. api.streamingClientsMutex.Lock()
  818. api.streamingClients[clientLow] = struct{}{}
  819. api.streamingClients[clientAdmin] = struct{}{}
  820. api.streamingClientsMutex.Unlock()
  821. return clientLow, clientAdmin
  822. }
  823. func removeEventStreamTestClients(api *oliveTinAPI, clientLow, clientAdmin *streamingClient) {
  824. api.streamingClientsMutex.Lock()
  825. delete(api.streamingClients, clientLow)
  826. delete(api.streamingClients, clientAdmin)
  827. api.streamingClientsMutex.Unlock()
  828. close(clientLow.channel)
  829. close(clientAdmin.channel)
  830. }
  831. func runEventStreamTestExecution(t *testing.T, ex *executor.Executor, cfg *config.Config, binding *executor.ActionBinding, adminUser *authpublic.AuthenticatedUser) {
  832. t.Helper()
  833. execReq := &executor.ExecutionRequest{
  834. Binding: binding,
  835. Arguments: map[string]string{},
  836. TrackingID: uuid.NewString(),
  837. Cfg: cfg,
  838. AuthenticatedUser: adminUser,
  839. }
  840. wg, _ := ex.ExecRequest(execReq)
  841. wg.Wait()
  842. }
  843. func drainEventStreamUntilFinished(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  844. var out []*apiv1.EventStreamResponse
  845. deadline := time.Now().Add(timeout)
  846. for time.Now().Before(deadline) {
  847. ev, finished := recvEventStreamOne(ch, 50*time.Millisecond)
  848. if ev != nil {
  849. out = append(out, ev)
  850. }
  851. if finished {
  852. return out
  853. }
  854. }
  855. return out
  856. }
  857. func recvEventStreamOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  858. select {
  859. case ev, ok := <-ch:
  860. if !ok {
  861. return nil, true
  862. }
  863. return ev, ev.GetExecutionFinished() != nil
  864. case <-time.After(timeout):
  865. return nil, true
  866. }
  867. }
  868. func eventStreamRecvResult(ev *apiv1.EventStreamResponse, ok bool) (*apiv1.EventStreamResponse, bool) {
  869. if !ok {
  870. return nil, true
  871. }
  872. return ev, false
  873. }
  874. func recvEventStreamWithTimeoutOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  875. select {
  876. case ev, ok := <-ch:
  877. return eventStreamRecvResult(ev, ok)
  878. case <-time.After(timeout):
  879. return nil, true
  880. }
  881. }
  882. func drainEventStreamWithTimeout(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  883. var out []*apiv1.EventStreamResponse
  884. for {
  885. ev, done := recvEventStreamWithTimeoutOne(ch, timeout)
  886. if done {
  887. return out
  888. }
  889. out = append(out, ev)
  890. }
  891. }
  892. func assertEventStreamLowUserReceivesNothing(t *testing.T, lowEvents []*apiv1.EventStreamResponse) {
  893. t.Helper()
  894. for _, ev := range lowEvents {
  895. assert.Nil(t, ev.GetExecutionStarted(), "low-privilege user must not receive ExecutionStarted")
  896. assert.Nil(t, ev.GetExecutionFinished(), "low-privilege user must not receive ExecutionFinished")
  897. assert.Nil(t, ev.GetOutputChunk(), "low-privilege user must not receive OutputChunk")
  898. }
  899. assert.Empty(t, lowEvents, "low-privilege user with Logs:false must not receive any execution events")
  900. }
  901. func assertEventStreamAdminReceivesSecretActionEvents(t *testing.T, adminEvents []*apiv1.EventStreamResponse) {
  902. t.Helper()
  903. var gotStarted, gotFinished bool
  904. for _, ev := range adminEvents {
  905. if ev.GetExecutionStarted() != nil {
  906. gotStarted = true
  907. assert.Equal(t, "secret_action", ev.GetExecutionStarted().LogEntry.GetBindingId())
  908. }
  909. if ev.GetExecutionFinished() != nil {
  910. gotFinished = true
  911. assert.Equal(t, "secret_action", ev.GetExecutionFinished().LogEntry.GetBindingId())
  912. }
  913. }
  914. assert.True(t, gotStarted, "admin must receive ExecutionStarted for secret_action")
  915. assert.True(t, gotFinished, "admin must receive ExecutionFinished for secret_action")
  916. }
  917. func TestExecutionStatusReturnsBackToDashboards(t *testing.T) {
  918. cfg := config.DefaultConfig()
  919. cfg.Actions = []*config.Action{
  920. {Title: "Dashboard Action", Shell: "echo ok"},
  921. }
  922. cfg.Dashboards = []*config.DashboardComponent{
  923. {
  924. Title: "Ops",
  925. Contents: []*config.DashboardComponent{
  926. {Title: "Dashboard Action"},
  927. },
  928. },
  929. }
  930. ex := executor.DefaultExecutor(cfg)
  931. ex.RebuildActionMap()
  932. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  933. require.NotNil(t, binding)
  934. _, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  935. startResp, err := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{
  936. BindingId: binding.ID,
  937. }))
  938. require.NoError(t, err)
  939. statusResp, err := client.ExecutionStatus(context.Background(), connect.NewRequest(&apiv1.ExecutionStatusRequest{
  940. ExecutionTrackingId: startResp.Msg.ExecutionTrackingId,
  941. }))
  942. require.NoError(t, err)
  943. require.NotNil(t, statusResp.Msg)
  944. require.Len(t, statusResp.Msg.BackToDashboards, 1)
  945. assert.Equal(t, "Ops", statusResp.Msg.BackToDashboards[0].Title)
  946. assert.Equal(t, "/dashboards/Ops", statusResp.Msg.BackToDashboards[0].Path)
  947. }
  948. func TestGetActionBindingReturnsBackToDashboards(t *testing.T) {
  949. cfg := config.DefaultConfig()
  950. cfg.Actions = []*config.Action{
  951. {Title: "Dashboard Action", Shell: "echo ok"},
  952. }
  953. cfg.Dashboards = []*config.DashboardComponent{
  954. {
  955. Title: "Ops",
  956. Contents: []*config.DashboardComponent{
  957. {Title: "Dashboard Action"},
  958. },
  959. },
  960. }
  961. ex := executor.DefaultExecutor(cfg)
  962. ex.RebuildActionMap()
  963. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  964. require.NotNil(t, binding)
  965. _, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  966. resp, err := client.GetActionBinding(context.Background(), connect.NewRequest(&apiv1.GetActionBindingRequest{
  967. BindingId: binding.ID,
  968. }))
  969. require.NoError(t, err)
  970. require.NotNil(t, resp.Msg)
  971. require.Len(t, resp.Msg.BackToDashboards, 1)
  972. assert.Equal(t, "Ops", resp.Msg.BackToDashboards[0].Title)
  973. assert.Equal(t, "/dashboards/Ops", resp.Msg.BackToDashboards[0].Path)
  974. }
  975. func TestBuildActionIncludesGroups(t *testing.T) {
  976. cfg := config.DefaultConfig()
  977. cfg.ActionGroups = map[string]*config.ActionGroup{
  978. "con2queue10": {MaxConcurrent: 2, QueueSize: 10},
  979. }
  980. cfg.Actions = []*config.Action{
  981. {Title: "Long running action", Shell: "sleep 1", Groups: []string{"con2queue10", "missing"}},
  982. }
  983. cfg.Sanitize()
  984. ex := executor.DefaultExecutor(cfg)
  985. ex.RebuildActionMap()
  986. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  987. require.NotNil(t, binding)
  988. rr := &DashboardRenderRequest{cfg: cfg, ex: ex}
  989. actionResult := buildAction(binding, rr)
  990. require.Len(t, actionResult.Groups, 2)
  991. assert.Equal(t, "con2queue10", actionResult.Groups[0].Name)
  992. assert.Equal(t, int32(2), actionResult.Groups[0].MaxConcurrent)
  993. assert.Equal(t, int32(10), actionResult.Groups[0].QueueSize)
  994. assert.Equal(t, "missing", actionResult.Groups[1].Name)
  995. assert.Equal(t, int32(0), actionResult.Groups[1].MaxConcurrent)
  996. }
  997. func TestBuildChoicesExpandsChecklistEntityChoices(t *testing.T) {
  998. entities.AddEntity("room", "0", map[string]any{"hostname": "attic"})
  999. entities.AddEntity("room", "1", map[string]any{"hostname": "basement"})
  1000. t.Cleanup(func() {
  1001. entities.ClearEntitiesOfType("room")
  1002. })
  1003. cfg := config.DefaultConfig()
  1004. cfg.Entities = []*config.EntityFile{
  1005. {Name: "room", File: "room.yaml"},
  1006. }
  1007. cfg.Sanitize()
  1008. user := &authpublic.AuthenticatedUser{Username: "guest", Provider: "system"}
  1009. user.BuildUserAcls(cfg)
  1010. arg := config.ActionArgument{
  1011. Type: "checklist",
  1012. Entity: "room",
  1013. Choices: []config.ActionArgumentChoice{
  1014. {Title: "{{ room.hostname }}", Value: "{{ room.hostname }}"},
  1015. },
  1016. }
  1017. choices := buildChoices(arg, &DashboardRenderRequest{AuthenticatedUser: user, cfg: cfg})
  1018. require.Len(t, choices, 2)
  1019. assert.Equal(t, "attic", choices[0].Value)
  1020. assert.Equal(t, "attic", choices[0].Title)
  1021. assert.Equal(t, "basement", choices[1].Value)
  1022. assert.Equal(t, "basement", choices[1].Title)
  1023. }