api_test.go 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  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. // TestViewPermissionExcludedFromCustomDashboard (issue #921) asserts that when a custom dashboard
  538. // lists an action by title, users without view permission do not see that action (title or icon).
  539. func TestViewPermissionExcludedFromCustomDashboard(t *testing.T) {
  540. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  541. cfg.Dashboards = []*config.DashboardComponent{
  542. {
  543. Title: "Custom",
  544. Contents: []*config.DashboardComponent{
  545. {Title: "Secret Action"},
  546. },
  547. },
  548. }
  549. ex := executor.DefaultExecutor(cfg)
  550. ex.RebuildActionMap()
  551. rr := &DashboardRenderRequest{
  552. AuthenticatedUser: lowUser,
  553. cfg: cfg,
  554. ex: ex,
  555. }
  556. dashboard := findDashboardByTitle(rr, "Custom")
  557. require.NotNil(t, dashboard)
  558. db := buildDashboardFromConfig(dashboard, rr)
  559. require.NotNil(t, db)
  560. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  561. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  562. "user with view:false must not see action on custom dashboard; got bindingIds: %v", bindingIdsInDashboard)
  563. assert.False(t, dashboardContentsContainForbiddenComponent(db.Contents, "Secret Action", "🔒"),
  564. "user with view:false must not see Secret Action title or lock icon in custom dashboard")
  565. }
  566. // TestViewPermissionExcludedFromEntityDashboard (GHSA: view permission) asserts that when a dashboard
  567. // has an entity fieldset listing an action, users without view permission do not see that action.
  568. func TestViewPermissionExcludedFromEntityDashboard(t *testing.T) {
  569. entities.ClearEntitiesOfType("vp_entity_test")
  570. defer entities.ClearEntitiesOfType("vp_entity_test")
  571. entities.AddEntity("vp_entity_test", "1", map[string]any{"title": "Test Entity"})
  572. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  573. cfg.Dashboards = []*config.DashboardComponent{
  574. {
  575. Title: "WithEntity",
  576. Contents: []*config.DashboardComponent{
  577. {
  578. Title: "Servers", Type: "fieldset", Entity: "vp_entity_test",
  579. Contents: []*config.DashboardComponent{{Title: "Secret Action"}},
  580. },
  581. },
  582. },
  583. }
  584. ex := executor.DefaultExecutor(cfg)
  585. ex.RebuildActionMap()
  586. rr := &DashboardRenderRequest{
  587. AuthenticatedUser: lowUser,
  588. cfg: cfg,
  589. ex: ex,
  590. }
  591. dashboard := findDashboardByTitle(rr, "WithEntity")
  592. require.NotNil(t, dashboard)
  593. db := buildDashboardFromConfig(dashboard, rr)
  594. require.NotNil(t, db)
  595. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  596. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  597. "user with view:false must not see action in entity fieldset; got bindingIds: %v", bindingIdsInDashboard)
  598. assert.False(t, dashboardContentsContainForbiddenComponent(db.Contents, "Secret Action", "🔒"),
  599. "user with view:false must not see Secret Action title or lock icon in entity dashboard")
  600. }
  601. func bindingIdsInDashboardContents(contents []*apiv1.DashboardComponent) []string {
  602. var ids []string
  603. for _, c := range contents {
  604. ids = append(ids, bindingIdsFromComponent(c)...)
  605. }
  606. return ids
  607. }
  608. func bindingIdsFromComponent(c *apiv1.DashboardComponent) []string {
  609. if c == nil {
  610. return nil
  611. }
  612. var ids []string
  613. if c.Action != nil && c.Action.BindingId != "" {
  614. ids = append(ids, c.Action.BindingId)
  615. }
  616. return append(ids, bindingIdsInDashboardContents(c.Contents)...)
  617. }
  618. func componentHasForbiddenTitleOrIcon(c *apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  619. return c != nil && (c.Title == forbiddenTitle || c.Icon == forbiddenIcon)
  620. }
  621. func componentOrDescendantsContainForbidden(c *apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  622. if c == nil {
  623. return false
  624. }
  625. if componentHasForbiddenTitleOrIcon(c, forbiddenTitle, forbiddenIcon) {
  626. return true
  627. }
  628. return dashboardContentsContainForbiddenComponent(c.Contents, forbiddenTitle, forbiddenIcon)
  629. }
  630. // dashboardContentsContainForbiddenComponent recursively walks contents and returns true if any
  631. // component has Title == forbiddenTitle or Icon == forbiddenIcon.
  632. func dashboardContentsContainForbiddenComponent(contents []*apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  633. for _, c := range contents {
  634. if componentOrDescendantsContainForbidden(c, forbiddenTitle, forbiddenIcon) {
  635. return true
  636. }
  637. }
  638. return false
  639. }
  640. func TestOrderTopLevelDashboardComponents_RegularFieldsetsPreserveConfigOrder(t *testing.T) {
  641. zebra := &apiv1.DashboardComponent{Title: "Zebra", Type: "fieldset", EntityType: ""}
  642. alpha := &apiv1.DashboardComponent{Title: "Alpha", Type: "fieldset", EntityType: ""}
  643. root := &apiv1.DashboardComponent{Title: "Actions", Type: "fieldset", EntityType: ""}
  644. components := []*apiv1.DashboardComponent{zebra, alpha, root}
  645. out := orderTopLevelDashboardComponents(components, root)
  646. require.Len(t, out, 3)
  647. assert.Same(t, zebra, out[0], "first must be Zebra (config order)")
  648. assert.Same(t, alpha, out[1], "second must be Alpha (config order)")
  649. assert.Same(t, root, out[2], "third must be root Actions fieldset")
  650. }
  651. func TestOrderTopLevelDashboardComponents_SortablesSorted(t *testing.T) {
  652. entityBeta := &apiv1.DashboardComponent{Title: "Beta", Type: "fieldset", EntityType: "server"}
  653. entityAlpha := &apiv1.DashboardComponent{Title: "Alpha", Type: "fieldset", EntityType: "server"}
  654. components := []*apiv1.DashboardComponent{entityBeta, entityAlpha}
  655. out := orderTopLevelDashboardComponents(components, nil)
  656. require.Len(t, out, 2)
  657. assert.Equal(t, "Alpha", out[0].Title, "sortables ordered by title")
  658. assert.Equal(t, "Beta", out[1].Title)
  659. }
  660. // TestEventStreamACLNoLeakToUnauthorizedUser (GHSA-228v-wc5r-j8m7) asserts that EventStream
  661. // does not send execution events or output chunks to users who are not allowed to view that action's logs.
  662. func TestEventStreamACLNoLeakToUnauthorizedUser(t *testing.T) {
  663. cfg, lowUser, adminUser := buildViewPermissionTestConfig(t)
  664. ex := executor.DefaultExecutor(cfg)
  665. ex.RebuildActionMap()
  666. api := newServer(ex)
  667. binding := ex.FindBindingByID("secret_action")
  668. require.NotNil(t, binding, "secret_action binding must exist")
  669. clientLow, clientAdmin := addEventStreamTestClients(t, api, lowUser, adminUser)
  670. defer removeEventStreamTestClients(api, clientLow, clientAdmin)
  671. runEventStreamTestExecution(t, ex, cfg, binding, adminUser)
  672. adminEvents := drainEventStreamUntilFinished(clientAdmin.channel, 2*time.Second)
  673. lowEvents := drainEventStreamWithTimeout(clientLow.channel, 50*time.Millisecond)
  674. assertEventStreamLowUserReceivesNothing(t, lowEvents)
  675. assertEventStreamAdminReceivesSecretActionEvents(t, adminEvents)
  676. }
  677. func TestRegisterStreamingClientEnforcesLimit(t *testing.T) {
  678. cfg := config.DefaultConfig()
  679. ex := executor.DefaultExecutor(cfg)
  680. api := newServer(ex)
  681. user := &authpublic.AuthenticatedUser{Username: "limit-test"}
  682. clients := make([]*streamingClient, 0, maxEventStreamClients)
  683. for i := 0; i < maxEventStreamClients; i++ {
  684. client := &streamingClient{
  685. channel: make(chan *apiv1.EventStreamResponse, 1),
  686. AuthenticatedUser: user,
  687. heartbeatStop: make(chan struct{}),
  688. heartbeatDone: make(chan struct{}),
  689. }
  690. close(client.heartbeatDone)
  691. require.NoError(t, api.registerStreamingClient(client))
  692. clients = append(clients, client)
  693. }
  694. overflow := &streamingClient{
  695. channel: make(chan *apiv1.EventStreamResponse, 1),
  696. AuthenticatedUser: user,
  697. heartbeatStop: make(chan struct{}),
  698. heartbeatDone: make(chan struct{}),
  699. }
  700. close(overflow.heartbeatDone)
  701. err := api.registerStreamingClient(overflow)
  702. require.ErrorIs(t, err, errEventStreamClientLimit)
  703. assert.Len(t, api.streamingClients, maxEventStreamClients)
  704. api.removeClient(clients[0])
  705. require.NoError(t, api.registerStreamingClient(overflow))
  706. assert.Len(t, api.streamingClients, maxEventStreamClients)
  707. for _, client := range clients[1:] {
  708. api.removeClient(client)
  709. }
  710. api.removeClient(overflow)
  711. }
  712. func addEventStreamTestClients(t *testing.T, api *oliveTinAPI, lowUser, adminUser *authpublic.AuthenticatedUser) (*streamingClient, *streamingClient) {
  713. t.Helper()
  714. clientLow := &streamingClient{
  715. channel: make(chan *apiv1.EventStreamResponse, 20),
  716. AuthenticatedUser: lowUser,
  717. }
  718. clientAdmin := &streamingClient{
  719. channel: make(chan *apiv1.EventStreamResponse, 20),
  720. AuthenticatedUser: adminUser,
  721. }
  722. api.streamingClientsMutex.Lock()
  723. api.streamingClients[clientLow] = struct{}{}
  724. api.streamingClients[clientAdmin] = struct{}{}
  725. api.streamingClientsMutex.Unlock()
  726. return clientLow, clientAdmin
  727. }
  728. func removeEventStreamTestClients(api *oliveTinAPI, clientLow, clientAdmin *streamingClient) {
  729. api.streamingClientsMutex.Lock()
  730. delete(api.streamingClients, clientLow)
  731. delete(api.streamingClients, clientAdmin)
  732. api.streamingClientsMutex.Unlock()
  733. close(clientLow.channel)
  734. close(clientAdmin.channel)
  735. }
  736. func runEventStreamTestExecution(t *testing.T, ex *executor.Executor, cfg *config.Config, binding *executor.ActionBinding, adminUser *authpublic.AuthenticatedUser) {
  737. t.Helper()
  738. execReq := &executor.ExecutionRequest{
  739. Binding: binding,
  740. Arguments: map[string]string{},
  741. TrackingID: uuid.NewString(),
  742. Cfg: cfg,
  743. AuthenticatedUser: adminUser,
  744. }
  745. wg, _ := ex.ExecRequest(execReq)
  746. wg.Wait()
  747. }
  748. func drainEventStreamUntilFinished(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  749. var out []*apiv1.EventStreamResponse
  750. deadline := time.Now().Add(timeout)
  751. for time.Now().Before(deadline) {
  752. ev, finished := recvEventStreamOne(ch, 50*time.Millisecond)
  753. if ev != nil {
  754. out = append(out, ev)
  755. }
  756. if finished {
  757. return out
  758. }
  759. }
  760. return out
  761. }
  762. func recvEventStreamOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  763. select {
  764. case ev, ok := <-ch:
  765. if !ok {
  766. return nil, true
  767. }
  768. return ev, ev.GetExecutionFinished() != nil
  769. case <-time.After(timeout):
  770. return nil, true
  771. }
  772. }
  773. func eventStreamRecvResult(ev *apiv1.EventStreamResponse, ok bool) (*apiv1.EventStreamResponse, bool) {
  774. if !ok {
  775. return nil, true
  776. }
  777. return ev, false
  778. }
  779. func recvEventStreamWithTimeoutOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  780. select {
  781. case ev, ok := <-ch:
  782. return eventStreamRecvResult(ev, ok)
  783. case <-time.After(timeout):
  784. return nil, true
  785. }
  786. }
  787. func drainEventStreamWithTimeout(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  788. var out []*apiv1.EventStreamResponse
  789. for {
  790. ev, done := recvEventStreamWithTimeoutOne(ch, timeout)
  791. if done {
  792. return out
  793. }
  794. out = append(out, ev)
  795. }
  796. }
  797. func assertEventStreamLowUserReceivesNothing(t *testing.T, lowEvents []*apiv1.EventStreamResponse) {
  798. t.Helper()
  799. for _, ev := range lowEvents {
  800. assert.Nil(t, ev.GetExecutionStarted(), "low-privilege user must not receive ExecutionStarted")
  801. assert.Nil(t, ev.GetExecutionFinished(), "low-privilege user must not receive ExecutionFinished")
  802. assert.Nil(t, ev.GetOutputChunk(), "low-privilege user must not receive OutputChunk")
  803. }
  804. assert.Empty(t, lowEvents, "low-privilege user with Logs:false must not receive any execution events")
  805. }
  806. func assertEventStreamAdminReceivesSecretActionEvents(t *testing.T, adminEvents []*apiv1.EventStreamResponse) {
  807. t.Helper()
  808. var gotStarted, gotFinished bool
  809. for _, ev := range adminEvents {
  810. if ev.GetExecutionStarted() != nil {
  811. gotStarted = true
  812. assert.Equal(t, "secret_action", ev.GetExecutionStarted().LogEntry.GetBindingId())
  813. }
  814. if ev.GetExecutionFinished() != nil {
  815. gotFinished = true
  816. assert.Equal(t, "secret_action", ev.GetExecutionFinished().LogEntry.GetBindingId())
  817. }
  818. }
  819. assert.True(t, gotStarted, "admin must receive ExecutionStarted for secret_action")
  820. assert.True(t, gotFinished, "admin must receive ExecutionFinished for secret_action")
  821. }
  822. func TestExecutionStatusReturnsBackToDashboards(t *testing.T) {
  823. cfg := config.DefaultConfig()
  824. cfg.Actions = []*config.Action{
  825. {Title: "Dashboard Action", Shell: "echo ok"},
  826. }
  827. cfg.Dashboards = []*config.DashboardComponent{
  828. {
  829. Title: "Ops",
  830. Contents: []*config.DashboardComponent{
  831. {Title: "Dashboard Action"},
  832. },
  833. },
  834. }
  835. ex := executor.DefaultExecutor(cfg)
  836. ex.RebuildActionMap()
  837. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  838. require.NotNil(t, binding)
  839. _, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  840. startResp, err := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{
  841. BindingId: binding.ID,
  842. }))
  843. require.NoError(t, err)
  844. statusResp, err := client.ExecutionStatus(context.Background(), connect.NewRequest(&apiv1.ExecutionStatusRequest{
  845. ExecutionTrackingId: startResp.Msg.ExecutionTrackingId,
  846. }))
  847. require.NoError(t, err)
  848. require.NotNil(t, statusResp.Msg)
  849. require.Len(t, statusResp.Msg.BackToDashboards, 1)
  850. assert.Equal(t, "Ops", statusResp.Msg.BackToDashboards[0].Title)
  851. assert.Equal(t, "/dashboards/Ops", statusResp.Msg.BackToDashboards[0].Path)
  852. }
  853. func TestGetActionBindingReturnsBackToDashboards(t *testing.T) {
  854. cfg := config.DefaultConfig()
  855. cfg.Actions = []*config.Action{
  856. {Title: "Dashboard Action", Shell: "echo ok"},
  857. }
  858. cfg.Dashboards = []*config.DashboardComponent{
  859. {
  860. Title: "Ops",
  861. Contents: []*config.DashboardComponent{
  862. {Title: "Dashboard Action"},
  863. },
  864. },
  865. }
  866. ex := executor.DefaultExecutor(cfg)
  867. ex.RebuildActionMap()
  868. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  869. require.NotNil(t, binding)
  870. _, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  871. resp, err := client.GetActionBinding(context.Background(), connect.NewRequest(&apiv1.GetActionBindingRequest{
  872. BindingId: binding.ID,
  873. }))
  874. require.NoError(t, err)
  875. require.NotNil(t, resp.Msg)
  876. require.Len(t, resp.Msg.BackToDashboards, 1)
  877. assert.Equal(t, "Ops", resp.Msg.BackToDashboards[0].Title)
  878. assert.Equal(t, "/dashboards/Ops", resp.Msg.BackToDashboards[0].Path)
  879. }
  880. func TestBuildActionIncludesGroups(t *testing.T) {
  881. cfg := config.DefaultConfig()
  882. cfg.ActionGroups = map[string]*config.ActionGroup{
  883. "con2queue10": {MaxConcurrent: 2, QueueSize: 10},
  884. }
  885. cfg.Actions = []*config.Action{
  886. {Title: "Long running action", Shell: "sleep 1", Groups: []string{"con2queue10", "missing"}},
  887. }
  888. cfg.Sanitize()
  889. ex := executor.DefaultExecutor(cfg)
  890. ex.RebuildActionMap()
  891. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  892. require.NotNil(t, binding)
  893. rr := &DashboardRenderRequest{cfg: cfg, ex: ex}
  894. actionResult := buildAction(binding, rr)
  895. require.Len(t, actionResult.Groups, 2)
  896. assert.Equal(t, "con2queue10", actionResult.Groups[0].Name)
  897. assert.Equal(t, int32(2), actionResult.Groups[0].MaxConcurrent)
  898. assert.Equal(t, int32(10), actionResult.Groups[0].QueueSize)
  899. assert.Equal(t, "missing", actionResult.Groups[1].Name)
  900. assert.Equal(t, int32(0), actionResult.Groups[1].MaxConcurrent)
  901. }
  902. func TestBuildChoicesExpandsChecklistEntityChoices(t *testing.T) {
  903. entities.AddEntity("room", "0", map[string]any{"hostname": "attic"})
  904. entities.AddEntity("room", "1", map[string]any{"hostname": "basement"})
  905. t.Cleanup(func() {
  906. entities.ClearEntitiesOfType("room")
  907. })
  908. arg := config.ActionArgument{
  909. Type: "checklist",
  910. Entity: "room",
  911. Choices: []config.ActionArgumentChoice{
  912. {Title: "{{ room.hostname }}", Value: "{{ room.hostname }}"},
  913. },
  914. }
  915. choices := buildChoices(arg)
  916. require.Len(t, choices, 2)
  917. assert.Equal(t, "attic", choices[0].Value)
  918. assert.Equal(t, "attic", choices[0].Title)
  919. assert.Equal(t, "basement", choices[1].Value)
  920. assert.Equal(t, "basement", choices[1].Title)
  921. }