4
0

api_test.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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 TestRegisterStreamingClientEnforcesLimit(t *testing.T) {
  710. cfg := config.DefaultConfig()
  711. ex := executor.DefaultExecutor(cfg)
  712. api := newServer(ex)
  713. user := &authpublic.AuthenticatedUser{Username: "limit-test"}
  714. clients := make([]*streamingClient, 0, maxEventStreamClients)
  715. for i := 0; i < maxEventStreamClients; i++ {
  716. client := &streamingClient{
  717. channel: make(chan *apiv1.EventStreamResponse, 1),
  718. AuthenticatedUser: user,
  719. heartbeatStop: make(chan struct{}),
  720. heartbeatDone: make(chan struct{}),
  721. }
  722. close(client.heartbeatDone)
  723. require.NoError(t, api.registerStreamingClient(client))
  724. clients = append(clients, client)
  725. }
  726. overflow := &streamingClient{
  727. channel: make(chan *apiv1.EventStreamResponse, 1),
  728. AuthenticatedUser: user,
  729. heartbeatStop: make(chan struct{}),
  730. heartbeatDone: make(chan struct{}),
  731. }
  732. close(overflow.heartbeatDone)
  733. err := api.registerStreamingClient(overflow)
  734. require.ErrorIs(t, err, errEventStreamClientLimit)
  735. assert.Len(t, api.streamingClients, maxEventStreamClients)
  736. api.removeClient(clients[0])
  737. require.NoError(t, api.registerStreamingClient(overflow))
  738. assert.Len(t, api.streamingClients, maxEventStreamClients)
  739. for _, client := range clients[1:] {
  740. api.removeClient(client)
  741. }
  742. api.removeClient(overflow)
  743. }
  744. func addEventStreamTestClients(t *testing.T, api *oliveTinAPI, lowUser, adminUser *authpublic.AuthenticatedUser) (*streamingClient, *streamingClient) {
  745. t.Helper()
  746. clientLow := &streamingClient{
  747. channel: make(chan *apiv1.EventStreamResponse, 20),
  748. AuthenticatedUser: lowUser,
  749. }
  750. clientAdmin := &streamingClient{
  751. channel: make(chan *apiv1.EventStreamResponse, 20),
  752. AuthenticatedUser: adminUser,
  753. }
  754. api.streamingClientsMutex.Lock()
  755. api.streamingClients[clientLow] = struct{}{}
  756. api.streamingClients[clientAdmin] = struct{}{}
  757. api.streamingClientsMutex.Unlock()
  758. return clientLow, clientAdmin
  759. }
  760. func removeEventStreamTestClients(api *oliveTinAPI, clientLow, clientAdmin *streamingClient) {
  761. api.streamingClientsMutex.Lock()
  762. delete(api.streamingClients, clientLow)
  763. delete(api.streamingClients, clientAdmin)
  764. api.streamingClientsMutex.Unlock()
  765. close(clientLow.channel)
  766. close(clientAdmin.channel)
  767. }
  768. func runEventStreamTestExecution(t *testing.T, ex *executor.Executor, cfg *config.Config, binding *executor.ActionBinding, adminUser *authpublic.AuthenticatedUser) {
  769. t.Helper()
  770. execReq := &executor.ExecutionRequest{
  771. Binding: binding,
  772. Arguments: map[string]string{},
  773. TrackingID: uuid.NewString(),
  774. Cfg: cfg,
  775. AuthenticatedUser: adminUser,
  776. }
  777. wg, _ := ex.ExecRequest(execReq)
  778. wg.Wait()
  779. }
  780. func drainEventStreamUntilFinished(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  781. var out []*apiv1.EventStreamResponse
  782. deadline := time.Now().Add(timeout)
  783. for time.Now().Before(deadline) {
  784. ev, finished := recvEventStreamOne(ch, 50*time.Millisecond)
  785. if ev != nil {
  786. out = append(out, ev)
  787. }
  788. if finished {
  789. return out
  790. }
  791. }
  792. return out
  793. }
  794. func recvEventStreamOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  795. select {
  796. case ev, ok := <-ch:
  797. if !ok {
  798. return nil, true
  799. }
  800. return ev, ev.GetExecutionFinished() != nil
  801. case <-time.After(timeout):
  802. return nil, true
  803. }
  804. }
  805. func eventStreamRecvResult(ev *apiv1.EventStreamResponse, ok bool) (*apiv1.EventStreamResponse, bool) {
  806. if !ok {
  807. return nil, true
  808. }
  809. return ev, false
  810. }
  811. func recvEventStreamWithTimeoutOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  812. select {
  813. case ev, ok := <-ch:
  814. return eventStreamRecvResult(ev, ok)
  815. case <-time.After(timeout):
  816. return nil, true
  817. }
  818. }
  819. func drainEventStreamWithTimeout(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  820. var out []*apiv1.EventStreamResponse
  821. for {
  822. ev, done := recvEventStreamWithTimeoutOne(ch, timeout)
  823. if done {
  824. return out
  825. }
  826. out = append(out, ev)
  827. }
  828. }
  829. func assertEventStreamLowUserReceivesNothing(t *testing.T, lowEvents []*apiv1.EventStreamResponse) {
  830. t.Helper()
  831. for _, ev := range lowEvents {
  832. assert.Nil(t, ev.GetExecutionStarted(), "low-privilege user must not receive ExecutionStarted")
  833. assert.Nil(t, ev.GetExecutionFinished(), "low-privilege user must not receive ExecutionFinished")
  834. assert.Nil(t, ev.GetOutputChunk(), "low-privilege user must not receive OutputChunk")
  835. }
  836. assert.Empty(t, lowEvents, "low-privilege user with Logs:false must not receive any execution events")
  837. }
  838. func assertEventStreamAdminReceivesSecretActionEvents(t *testing.T, adminEvents []*apiv1.EventStreamResponse) {
  839. t.Helper()
  840. var gotStarted, gotFinished bool
  841. for _, ev := range adminEvents {
  842. if ev.GetExecutionStarted() != nil {
  843. gotStarted = true
  844. assert.Equal(t, "secret_action", ev.GetExecutionStarted().LogEntry.GetBindingId())
  845. }
  846. if ev.GetExecutionFinished() != nil {
  847. gotFinished = true
  848. assert.Equal(t, "secret_action", ev.GetExecutionFinished().LogEntry.GetBindingId())
  849. }
  850. }
  851. assert.True(t, gotStarted, "admin must receive ExecutionStarted for secret_action")
  852. assert.True(t, gotFinished, "admin must receive ExecutionFinished for secret_action")
  853. }
  854. func TestExecutionStatusReturnsBackToDashboards(t *testing.T) {
  855. cfg := config.DefaultConfig()
  856. cfg.Actions = []*config.Action{
  857. {Title: "Dashboard Action", Shell: "echo ok"},
  858. }
  859. cfg.Dashboards = []*config.DashboardComponent{
  860. {
  861. Title: "Ops",
  862. Contents: []*config.DashboardComponent{
  863. {Title: "Dashboard Action"},
  864. },
  865. },
  866. }
  867. ex := executor.DefaultExecutor(cfg)
  868. ex.RebuildActionMap()
  869. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  870. require.NotNil(t, binding)
  871. _, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  872. startResp, err := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{
  873. BindingId: binding.ID,
  874. }))
  875. require.NoError(t, err)
  876. statusResp, err := client.ExecutionStatus(context.Background(), connect.NewRequest(&apiv1.ExecutionStatusRequest{
  877. ExecutionTrackingId: startResp.Msg.ExecutionTrackingId,
  878. }))
  879. require.NoError(t, err)
  880. require.NotNil(t, statusResp.Msg)
  881. require.Len(t, statusResp.Msg.BackToDashboards, 1)
  882. assert.Equal(t, "Ops", statusResp.Msg.BackToDashboards[0].Title)
  883. assert.Equal(t, "/dashboards/Ops", statusResp.Msg.BackToDashboards[0].Path)
  884. }
  885. func TestGetActionBindingReturnsBackToDashboards(t *testing.T) {
  886. cfg := config.DefaultConfig()
  887. cfg.Actions = []*config.Action{
  888. {Title: "Dashboard Action", Shell: "echo ok"},
  889. }
  890. cfg.Dashboards = []*config.DashboardComponent{
  891. {
  892. Title: "Ops",
  893. Contents: []*config.DashboardComponent{
  894. {Title: "Dashboard Action"},
  895. },
  896. },
  897. }
  898. ex := executor.DefaultExecutor(cfg)
  899. ex.RebuildActionMap()
  900. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  901. require.NotNil(t, binding)
  902. _, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  903. resp, err := client.GetActionBinding(context.Background(), connect.NewRequest(&apiv1.GetActionBindingRequest{
  904. BindingId: binding.ID,
  905. }))
  906. require.NoError(t, err)
  907. require.NotNil(t, resp.Msg)
  908. require.Len(t, resp.Msg.BackToDashboards, 1)
  909. assert.Equal(t, "Ops", resp.Msg.BackToDashboards[0].Title)
  910. assert.Equal(t, "/dashboards/Ops", resp.Msg.BackToDashboards[0].Path)
  911. }
  912. func TestBuildActionIncludesGroups(t *testing.T) {
  913. cfg := config.DefaultConfig()
  914. cfg.ActionGroups = map[string]*config.ActionGroup{
  915. "con2queue10": {MaxConcurrent: 2, QueueSize: 10},
  916. }
  917. cfg.Actions = []*config.Action{
  918. {Title: "Long running action", Shell: "sleep 1", Groups: []string{"con2queue10", "missing"}},
  919. }
  920. cfg.Sanitize()
  921. ex := executor.DefaultExecutor(cfg)
  922. ex.RebuildActionMap()
  923. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  924. require.NotNil(t, binding)
  925. rr := &DashboardRenderRequest{cfg: cfg, ex: ex}
  926. actionResult := buildAction(binding, rr)
  927. require.Len(t, actionResult.Groups, 2)
  928. assert.Equal(t, "con2queue10", actionResult.Groups[0].Name)
  929. assert.Equal(t, int32(2), actionResult.Groups[0].MaxConcurrent)
  930. assert.Equal(t, int32(10), actionResult.Groups[0].QueueSize)
  931. assert.Equal(t, "missing", actionResult.Groups[1].Name)
  932. assert.Equal(t, int32(0), actionResult.Groups[1].MaxConcurrent)
  933. }
  934. func TestBuildChoicesExpandsChecklistEntityChoices(t *testing.T) {
  935. entities.AddEntity("room", "0", map[string]any{"hostname": "attic"})
  936. entities.AddEntity("room", "1", map[string]any{"hostname": "basement"})
  937. t.Cleanup(func() {
  938. entities.ClearEntitiesOfType("room")
  939. })
  940. cfg := config.DefaultConfig()
  941. cfg.Entities = []*config.EntityFile{
  942. {Name: "room", File: "room.yaml"},
  943. }
  944. cfg.Sanitize()
  945. user := &authpublic.AuthenticatedUser{Username: "guest", Provider: "system"}
  946. user.BuildUserAcls(cfg)
  947. arg := config.ActionArgument{
  948. Type: "checklist",
  949. Entity: "room",
  950. Choices: []config.ActionArgumentChoice{
  951. {Title: "{{ room.hostname }}", Value: "{{ room.hostname }}"},
  952. },
  953. }
  954. choices := buildChoices(arg, &DashboardRenderRequest{AuthenticatedUser: user, cfg: cfg})
  955. require.Len(t, choices, 2)
  956. assert.Equal(t, "attic", choices[0].Value)
  957. assert.Equal(t, "attic", choices[0].Title)
  958. assert.Equal(t, "basement", choices[1].Value)
  959. assert.Equal(t, "basement", choices[1].Title)
  960. }