api_test.go 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  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. assert.NotNil(t, resp, "GetEntities response should not be nil")
  106. assert.NotNil(t, resp.Msg, "GetEntities response message should not be nil")
  107. entityDefinitions := resp.Msg.EntityDefinitions
  108. assert.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. assert.Equal(t, "application", entityDefinitions[0].Title, "First entity should be 'application' (alphabetically first)")
  146. assert.Len(t, entityDefinitions[0].Instances, 1, "Application should have 1 instance")
  147. assert.Equal(t, "webapp", entityDefinitions[0].Instances[0].UniqueKey, "Application instance should be 'webapp'")
  148. assert.Equal(t, "database", entityDefinitions[1].Title, "Second entity should be 'database' (alphabetically second)")
  149. assert.Len(t, entityDefinitions[1].Instances, 2, "Database should have 2 instances")
  150. assert.Equal(t, "mysql", entityDefinitions[1].Instances[0].UniqueKey, "First database instance should be 'mysql' (alphabetically first)")
  151. assert.Equal(t, "postgres", entityDefinitions[1].Instances[1].UniqueKey, "Second database instance should be 'postgres' (alphabetically second)")
  152. assert.Equal(t, "server", entityDefinitions[2].Title, "Third entity should be 'server' (alphabetically third)")
  153. assert.Empty(t, entityDefinitions[2].Instances, "Server instances should not be included in bulk list response")
  154. assert.Equal(t, int32(3), entityDefinitions[2].TotalInstances, "Server should report total instance count")
  155. }
  156. func validateNoDuplicates(t *testing.T, entityDefinitions []*apiv1.EntityDefinition) {
  157. t.Helper()
  158. instanceKeys := make(map[string]map[string]bool)
  159. for _, def := range entityDefinitions {
  160. instanceKeys[def.Title] = make(map[string]bool)
  161. for _, inst := range def.Instances {
  162. assert.False(t, instanceKeys[def.Title][inst.UniqueKey], "Instance key %s should not be duplicated in entity %s", inst.UniqueKey, def.Title)
  163. instanceKeys[def.Title][inst.UniqueKey] = true
  164. }
  165. }
  166. }
  167. func validateConsistency(t *testing.T, client apiv1connect.OliveTinApiServiceClient, entityDefinitions []*apiv1.EntityDefinition) {
  168. t.Helper()
  169. resp2, err2 := client.GetEntities(context.Background(), connect.NewRequest(&apiv1.GetEntitiesRequest{}))
  170. require.NoError(t, err2, "Second GetEntities call should not return an error")
  171. assert.Len(t, entityDefinitions, len(resp2.Msg.EntityDefinitions), "Second call should return same number of entity definitions")
  172. for i, def := range entityDefinitions {
  173. assert.Equal(t, def.Title, resp2.Msg.EntityDefinitions[i].Title, "Entity order should be consistent across calls")
  174. assert.Len(t, def.Instances, len(resp2.Msg.EntityDefinitions[i].Instances), "Instance count should be consistent")
  175. for j, inst := range def.Instances {
  176. assert.Equal(t, inst.UniqueKey, resp2.Msg.EntityDefinitions[i].Instances[j].UniqueKey, "Instance order should be consistent across calls")
  177. }
  178. }
  179. }
  180. func TestEvaluateEnabledExpression(t *testing.T) {
  181. tests := []struct {
  182. entity *entities.Entity
  183. name string
  184. expression string
  185. expectedResult bool
  186. }{
  187. {
  188. name: "empty expression returns true",
  189. expression: "",
  190. entity: nil,
  191. expectedResult: true,
  192. },
  193. {
  194. name: "literal true returns true",
  195. expression: "true",
  196. entity: nil,
  197. expectedResult: true,
  198. },
  199. {
  200. name: "literal True returns true (case insensitive)",
  201. expression: "True",
  202. entity: nil,
  203. expectedResult: true,
  204. },
  205. {
  206. name: "literal 1 returns true",
  207. expression: "1",
  208. entity: nil,
  209. expectedResult: true,
  210. },
  211. {
  212. name: "literal false returns false",
  213. expression: "false",
  214. entity: nil,
  215. expectedResult: false,
  216. },
  217. {
  218. name: "literal 0 returns false",
  219. expression: "0",
  220. entity: nil,
  221. expectedResult: false,
  222. },
  223. {
  224. name: "empty result returns false",
  225. expression: "{{ .NonExistent }}",
  226. entity: nil,
  227. expectedResult: false,
  228. },
  229. {
  230. name: "expression with CurrentEntity true",
  231. expression: "{{ eq .CurrentEntity.powered_on true }}",
  232. entity: &entities.Entity{Data: map[string]any{"powered_on": true}},
  233. expectedResult: true,
  234. },
  235. {
  236. name: "expression with CurrentEntity false",
  237. expression: "{{ eq .CurrentEntity.powered_on true }}",
  238. entity: &entities.Entity{Data: map[string]any{"powered_on": false}},
  239. expectedResult: false,
  240. },
  241. {
  242. name: "expression with CurrentEntity integer 1",
  243. expression: "{{ .CurrentEntity.status }}",
  244. entity: &entities.Entity{Data: map[string]any{"status": 1}},
  245. expectedResult: true,
  246. },
  247. {
  248. name: "expression with CurrentEntity integer 0",
  249. expression: "{{ .CurrentEntity.status }}",
  250. entity: &entities.Entity{Data: map[string]any{"status": 0}},
  251. expectedResult: false,
  252. },
  253. {
  254. name: "template parse error returns false",
  255. expression: "{{ invalid syntax }}",
  256. entity: nil,
  257. expectedResult: false,
  258. },
  259. {
  260. name: "template exec error returns false",
  261. expression: "{{ .CurrentEntity.nonexistent }}",
  262. entity: nil,
  263. expectedResult: false,
  264. },
  265. }
  266. for _, tt := range tests {
  267. t.Run(tt.name, func(t *testing.T) {
  268. action := &config.Action{
  269. EnabledExpression: tt.expression,
  270. }
  271. result := evaluateEnabledExpression(action, tt.entity)
  272. assert.Equal(t, tt.expectedResult, result, "evaluateEnabledExpression should return expected result")
  273. })
  274. }
  275. }
  276. func TestBuildActionWithEnabledExpression(t *testing.T) {
  277. cfg := config.DefaultConfig()
  278. cfg.DefaultPermissions.Exec = true
  279. action := &config.Action{
  280. Title: "Test Action",
  281. Shell: "echo test",
  282. EnabledExpression: "{{ eq .CurrentEntity.enabled true }}",
  283. }
  284. cfg.Actions = append(cfg.Actions, action)
  285. ex := executor.DefaultExecutor(cfg)
  286. ex.RebuildActionMap()
  287. binding := findBindingByTitle(ex, "Test Action")
  288. assert.NotNil(t, binding, "Binding should be found")
  289. rr := &DashboardRenderRequest{
  290. AuthenticatedUser: &authpublic.AuthenticatedUser{Username: "testuser"},
  291. cfg: cfg,
  292. ex: ex,
  293. }
  294. testWithEntity(t, binding, rr, true, true, "Action should be executable when entity.enabled is true")
  295. testWithEntity(t, binding, rr, false, false, "Action should not be executable when entity.enabled is false")
  296. bindingNoExpr := findBindingByTitle(ex, "Test Action No Expression")
  297. if bindingNoExpr == nil {
  298. actionNoExpression := &config.Action{
  299. Title: "Test Action No Expression",
  300. Shell: "echo test",
  301. }
  302. cfg.Actions = append(cfg.Actions, actionNoExpression)
  303. ex.RebuildActionMap()
  304. bindingNoExpr = findBindingByTitle(ex, "Test Action No Expression")
  305. }
  306. actionResult := buildAction(bindingNoExpr, rr)
  307. assert.True(t, actionResult.CanExec, "Action without enabledExpression should be executable")
  308. }
  309. func findBindingByTitle(ex *executor.Executor, title string) *executor.ActionBinding {
  310. ex.MapActionBindingsLock.RLock()
  311. defer ex.MapActionBindingsLock.RUnlock()
  312. for _, b := range ex.MapActionBindings {
  313. if b.Action.Title == title {
  314. return b
  315. }
  316. }
  317. return nil
  318. }
  319. func testWithEntity(t *testing.T, binding *executor.ActionBinding, rr *DashboardRenderRequest, enabled bool, expectedCanExec bool, message string) {
  320. t.Helper()
  321. binding.Entity = &entities.Entity{
  322. UniqueKey: "test-entity",
  323. Data: map[string]any{"enabled": enabled},
  324. }
  325. actionResult := buildAction(binding, rr)
  326. assert.Equal(t, expectedCanExec, actionResult.CanExec, message)
  327. }
  328. // buildExecWithoutLogsTestConfig returns config for GHSA-jm28-2wcr-qf3h: user "runner" may exec but not read logs.
  329. func buildExecWithoutLogsTestConfig(t *testing.T) (*config.Config, *authpublic.AuthenticatedUser) {
  330. t.Helper()
  331. cfg := config.DefaultConfig()
  332. cfg.AuthHttpHeaderUsername = "X-Ot-User"
  333. cfg.DefaultPermissions.View = false
  334. cfg.DefaultPermissions.Exec = false
  335. cfg.DefaultPermissions.Logs = false
  336. cfg.Actions = append(cfg.Actions, &config.Action{
  337. ID: "run_only",
  338. Title: "Run Only",
  339. Shell: "echo sensitive-output",
  340. Icon: "🔒",
  341. })
  342. cfg.AccessControlLists = append(cfg.AccessControlLists, &config.AccessControlList{
  343. Name: "runner",
  344. MatchUsernames: []string{"runner"},
  345. AddToEveryAction: true,
  346. Permissions: config.PermissionsList{View: true, Exec: true, Logs: false, Kill: false},
  347. })
  348. runner := &authpublic.AuthenticatedUser{Username: "runner"}
  349. runner.BuildUserAcls(cfg)
  350. return cfg, runner
  351. }
  352. // TestStartActionAndWaitDeniesLogsPermission (GHSA-jm28-2wcr-qf3h) asserts sync execution endpoints
  353. // enforce logs ACL and do not return action output to users allowed to exec but not read logs.
  354. func TestStartActionAndWaitDeniesLogsPermission(t *testing.T) {
  355. cfg, _ := buildExecWithoutLogsTestConfig(t)
  356. ex := executor.DefaultExecutor(cfg)
  357. ex.RebuildActionMap()
  358. ts, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  359. defer ts.Close()
  360. req := connect.NewRequest(&apiv1.StartActionAndWaitRequest{
  361. ActionId: "run_only",
  362. })
  363. req.Header().Set("X-Ot-User", "runner")
  364. _, err := client.StartActionAndWait(context.Background(), req)
  365. require.Error(t, err)
  366. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  367. "user with exec:true and logs:false must not receive log output from StartActionAndWait")
  368. }
  369. // buildViewPermissionTestConfig returns config and users for GHSA view-permission tests:
  370. // one action "secret_action", ACL "restricted" (view:false, logs:false) for user "low", ACL "full" (view:true, logs:true) for user "admin".
  371. func buildViewPermissionTestConfig(t *testing.T) (*config.Config, *authpublic.AuthenticatedUser, *authpublic.AuthenticatedUser) {
  372. t.Helper()
  373. cfg := config.DefaultConfig()
  374. cfg.DefaultPermissions.View = false
  375. cfg.DefaultPermissions.Exec = false
  376. cfg.DefaultPermissions.Logs = false
  377. cfg.Actions = append(cfg.Actions, &config.Action{
  378. ID: "secret_action",
  379. Title: "Secret Action",
  380. Shell: "echo sensitive",
  381. Icon: "🔒",
  382. })
  383. cfg.AccessControlLists = append(cfg.AccessControlLists,
  384. &config.AccessControlList{
  385. Name: "restricted",
  386. MatchUsernames: []string{"low"},
  387. AddToEveryAction: true,
  388. Permissions: config.PermissionsList{View: false, Exec: false, Logs: false, Kill: false},
  389. },
  390. &config.AccessControlList{
  391. Name: "full",
  392. MatchUsernames: []string{"admin"},
  393. AddToEveryAction: true,
  394. Permissions: config.PermissionsList{View: true, Exec: true, Logs: true, Kill: true},
  395. },
  396. )
  397. lowUser := &authpublic.AuthenticatedUser{Username: "low"}
  398. lowUser.BuildUserAcls(cfg)
  399. adminUser := &authpublic.AuthenticatedUser{Username: "admin"}
  400. adminUser.BuildUserAcls(cfg)
  401. return cfg, lowUser, adminUser
  402. }
  403. // TestViewPermissionExcludedFromDashboard (GHSA: view permission) asserts that when a user has view: false,
  404. // the default dashboard must not include that action. Covers GetDashboard not leaking action metadata.
  405. func TestViewPermissionExcludedFromDashboard(t *testing.T) {
  406. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  407. ex := executor.DefaultExecutor(cfg)
  408. ex.RebuildActionMap()
  409. rr := &DashboardRenderRequest{
  410. AuthenticatedUser: lowUser,
  411. cfg: cfg,
  412. ex: ex,
  413. }
  414. db := buildDefaultDashboard(rr)
  415. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  416. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  417. "user with view:false must not see action in dashboard; got bindingIds: %v", bindingIdsInDashboard)
  418. }
  419. // TestGetActionBindingDeniedWhenNoViewPermission (GHSA: view permission) asserts that GetActionBinding
  420. // returns permission denied for a user with view: false. Covers GetActionBinding not exposing action details.
  421. func TestGetActionBindingDeniedWhenNoViewPermission(t *testing.T) {
  422. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  423. ex := executor.DefaultExecutor(cfg)
  424. ex.RebuildActionMap()
  425. api := newServer(ex)
  426. _, err := api.getActionBindingResponse(lowUser, "secret_action")
  427. require.Error(t, err)
  428. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  429. "user with view:false must get permission denied from GetActionBinding")
  430. }
  431. // TestValidateArgumentTypeDeniesGuestsWhenLoginRequired (GHSA-f637-w7p2-m7fx) asserts that when
  432. // guests must log in, ValidateArgumentType does not bypass dashboard access controls.
  433. func TestValidateArgumentTypeDeniesGuestsWhenLoginRequired(t *testing.T) {
  434. cfg := config.DefaultConfig()
  435. cfg.AuthRequireGuestsToLogin = true
  436. cfg.Actions = append(cfg.Actions, &config.Action{
  437. ID: "a1",
  438. Title: "Probe",
  439. Shell: "echo",
  440. Arguments: []config.ActionArgument{
  441. {Name: "x", Type: "ascii"},
  442. },
  443. })
  444. ex := executor.DefaultExecutor(cfg)
  445. ex.RebuildActionMap()
  446. ts, client := getNewTestServerAndClient(cfg)
  447. defer ts.Close()
  448. _, err := client.ValidateArgumentType(context.Background(), connect.NewRequest(&apiv1.ValidateArgumentTypeRequest{
  449. BindingId: "a1",
  450. ArgumentName: "x",
  451. Value: "v",
  452. Type: "ascii",
  453. }))
  454. require.Error(t, err)
  455. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  456. "guest must not call ValidateArgumentType when AuthRequireGuestsToLogin is true")
  457. }
  458. // TestValidateArgumentTypeDeniedWithoutViewPermission (GHSA-f637-w7p2-m7fx) asserts ValidateArgumentType
  459. // respects the same view ACL as GetActionBinding so the RPC cannot enumerate restricted actions.
  460. func TestValidateArgumentTypeDeniedWithoutViewPermission(t *testing.T) {
  461. cfg, _, _ := buildViewPermissionTestConfig(t)
  462. cfg.AuthHttpHeaderUsername = "X-Ot-User"
  463. for i := range cfg.Actions {
  464. if cfg.Actions[i].ID == "secret_action" {
  465. cfg.Actions[i].Arguments = []config.ActionArgument{{Name: "target", Type: "ascii"}}
  466. break
  467. }
  468. }
  469. ex := executor.DefaultExecutor(cfg)
  470. ex.RebuildActionMap()
  471. ts, client := getNewTestServerAndClient(cfg)
  472. defer ts.Close()
  473. req := connect.NewRequest(&apiv1.ValidateArgumentTypeRequest{
  474. BindingId: "secret_action",
  475. ArgumentName: "target",
  476. Value: "ok",
  477. Type: "ascii",
  478. })
  479. req.Header().Set("X-Ot-User", "low")
  480. _, err := client.ValidateArgumentType(context.Background(), req)
  481. require.Error(t, err)
  482. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  483. "user with view:false must get permission denied from ValidateArgumentType")
  484. }
  485. // TestValidateArgumentTypeAllowedWithViewPermission (GHSA-f637-w7p2-m7fx) asserts authenticated users
  486. // with view access can still use ValidateArgumentType for argument validation.
  487. func TestValidateArgumentTypeAllowedWithViewPermission(t *testing.T) {
  488. cfg, _, _ := buildViewPermissionTestConfig(t)
  489. cfg.AuthHttpHeaderUsername = "X-Ot-User"
  490. for i := range cfg.Actions {
  491. if cfg.Actions[i].ID == "secret_action" {
  492. cfg.Actions[i].Arguments = []config.ActionArgument{{Name: "target", Type: "ascii"}}
  493. break
  494. }
  495. }
  496. ex := executor.DefaultExecutor(cfg)
  497. ex.RebuildActionMap()
  498. ts, client := getNewTestServerAndClient(cfg)
  499. defer ts.Close()
  500. req := connect.NewRequest(&apiv1.ValidateArgumentTypeRequest{
  501. BindingId: "secret_action",
  502. ArgumentName: "target",
  503. Value: "ok",
  504. Type: "ascii",
  505. })
  506. req.Header().Set("X-Ot-User", "admin")
  507. resp, err := client.ValidateArgumentType(context.Background(), req)
  508. require.NoError(t, err)
  509. require.NotNil(t, resp)
  510. require.NotNil(t, resp.Msg)
  511. assert.True(t, resp.Msg.Valid, "admin with view:true should get successful validation for a valid ascii value")
  512. }
  513. // TestViewPermissionAllowedSeesAction (GHSA: view permission) asserts that a user with view: true
  514. // still sees the action in the dashboard and can fetch it via GetActionBinding.
  515. func TestViewPermissionAllowedSeesAction(t *testing.T) {
  516. cfg, _, adminUser := buildViewPermissionTestConfig(t)
  517. ex := executor.DefaultExecutor(cfg)
  518. ex.RebuildActionMap()
  519. api := newServer(ex)
  520. rr := &DashboardRenderRequest{
  521. AuthenticatedUser: adminUser,
  522. cfg: cfg,
  523. ex: ex,
  524. }
  525. db := buildDefaultDashboard(rr)
  526. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  527. assert.Contains(t, bindingIdsInDashboard, "secret_action",
  528. "user with view:true must see action in dashboard; got bindingIds: %v", bindingIdsInDashboard)
  529. resp, err := api.getActionBindingResponse(adminUser, "secret_action")
  530. require.NoError(t, err)
  531. require.NotNil(t, resp)
  532. require.NotNil(t, resp.Action)
  533. assert.Equal(t, "secret_action", resp.Action.BindingId)
  534. }
  535. // TestViewPermissionExcludedFromCustomDashboard (issue #921) asserts that when a custom dashboard
  536. // lists an action by title, users without view permission do not see that action (title or icon).
  537. func TestViewPermissionExcludedFromCustomDashboard(t *testing.T) {
  538. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  539. cfg.Dashboards = []*config.DashboardComponent{
  540. {
  541. Title: "Custom",
  542. Contents: []*config.DashboardComponent{
  543. {Title: "Secret Action"},
  544. },
  545. },
  546. }
  547. ex := executor.DefaultExecutor(cfg)
  548. ex.RebuildActionMap()
  549. rr := &DashboardRenderRequest{
  550. AuthenticatedUser: lowUser,
  551. cfg: cfg,
  552. ex: ex,
  553. }
  554. dashboard := findDashboardByTitle(rr, "Custom")
  555. require.NotNil(t, dashboard)
  556. db := buildDashboardFromConfig(dashboard, rr)
  557. require.NotNil(t, db)
  558. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  559. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  560. "user with view:false must not see action on custom dashboard; got bindingIds: %v", bindingIdsInDashboard)
  561. assert.False(t, dashboardContentsContainForbiddenComponent(db.Contents, "Secret Action", "🔒"),
  562. "user with view:false must not see Secret Action title or lock icon in custom dashboard")
  563. }
  564. // TestViewPermissionExcludedFromEntityDashboard (GHSA: view permission) asserts that when a dashboard
  565. // has an entity fieldset listing an action, users without view permission do not see that action.
  566. func TestViewPermissionExcludedFromEntityDashboard(t *testing.T) {
  567. entities.ClearEntitiesOfType("vp_entity_test")
  568. defer entities.ClearEntitiesOfType("vp_entity_test")
  569. entities.AddEntity("vp_entity_test", "1", map[string]any{"title": "Test Entity"})
  570. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  571. cfg.Dashboards = []*config.DashboardComponent{
  572. {
  573. Title: "WithEntity",
  574. Contents: []*config.DashboardComponent{
  575. {
  576. Title: "Servers", Type: "fieldset", Entity: "vp_entity_test",
  577. Contents: []*config.DashboardComponent{{Title: "Secret Action"}},
  578. },
  579. },
  580. },
  581. }
  582. ex := executor.DefaultExecutor(cfg)
  583. ex.RebuildActionMap()
  584. rr := &DashboardRenderRequest{
  585. AuthenticatedUser: lowUser,
  586. cfg: cfg,
  587. ex: ex,
  588. }
  589. dashboard := findDashboardByTitle(rr, "WithEntity")
  590. require.NotNil(t, dashboard)
  591. db := buildDashboardFromConfig(dashboard, rr)
  592. require.NotNil(t, db)
  593. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  594. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  595. "user with view:false must not see action in entity fieldset; got bindingIds: %v", bindingIdsInDashboard)
  596. assert.False(t, dashboardContentsContainForbiddenComponent(db.Contents, "Secret Action", "🔒"),
  597. "user with view:false must not see Secret Action title or lock icon in entity dashboard")
  598. }
  599. func bindingIdsInDashboardContents(contents []*apiv1.DashboardComponent) []string {
  600. var ids []string
  601. for _, c := range contents {
  602. ids = append(ids, bindingIdsFromComponent(c)...)
  603. }
  604. return ids
  605. }
  606. func bindingIdsFromComponent(c *apiv1.DashboardComponent) []string {
  607. if c == nil {
  608. return nil
  609. }
  610. var ids []string
  611. if c.Action != nil && c.Action.BindingId != "" {
  612. ids = append(ids, c.Action.BindingId)
  613. }
  614. return append(ids, bindingIdsInDashboardContents(c.Contents)...)
  615. }
  616. func componentHasForbiddenTitleOrIcon(c *apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  617. return c != nil && (c.Title == forbiddenTitle || c.Icon == forbiddenIcon)
  618. }
  619. func componentOrDescendantsContainForbidden(c *apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  620. if c == nil {
  621. return false
  622. }
  623. if componentHasForbiddenTitleOrIcon(c, forbiddenTitle, forbiddenIcon) {
  624. return true
  625. }
  626. return dashboardContentsContainForbiddenComponent(c.Contents, forbiddenTitle, forbiddenIcon)
  627. }
  628. // dashboardContentsContainForbiddenComponent recursively walks contents and returns true if any
  629. // component has Title == forbiddenTitle or Icon == forbiddenIcon.
  630. func dashboardContentsContainForbiddenComponent(contents []*apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  631. for _, c := range contents {
  632. if componentOrDescendantsContainForbidden(c, forbiddenTitle, forbiddenIcon) {
  633. return true
  634. }
  635. }
  636. return false
  637. }
  638. func TestOrderTopLevelDashboardComponents_RegularFieldsetsPreserveConfigOrder(t *testing.T) {
  639. zebra := &apiv1.DashboardComponent{Title: "Zebra", Type: "fieldset", EntityType: ""}
  640. alpha := &apiv1.DashboardComponent{Title: "Alpha", Type: "fieldset", EntityType: ""}
  641. root := &apiv1.DashboardComponent{Title: "Actions", Type: "fieldset", EntityType: ""}
  642. components := []*apiv1.DashboardComponent{zebra, alpha, root}
  643. out := orderTopLevelDashboardComponents(components, root)
  644. require.Len(t, out, 3)
  645. assert.Same(t, zebra, out[0], "first must be Zebra (config order)")
  646. assert.Same(t, alpha, out[1], "second must be Alpha (config order)")
  647. assert.Same(t, root, out[2], "third must be root Actions fieldset")
  648. }
  649. func TestOrderTopLevelDashboardComponents_SortablesSorted(t *testing.T) {
  650. entityBeta := &apiv1.DashboardComponent{Title: "Beta", Type: "fieldset", EntityType: "server"}
  651. entityAlpha := &apiv1.DashboardComponent{Title: "Alpha", Type: "fieldset", EntityType: "server"}
  652. components := []*apiv1.DashboardComponent{entityBeta, entityAlpha}
  653. out := orderTopLevelDashboardComponents(components, nil)
  654. require.Len(t, out, 2)
  655. assert.Equal(t, "Alpha", out[0].Title, "sortables ordered by title")
  656. assert.Equal(t, "Beta", out[1].Title)
  657. }
  658. // TestEventStreamACLNoLeakToUnauthorizedUser (GHSA-228v-wc5r-j8m7) asserts that EventStream
  659. // does not send execution events or output chunks to users who are not allowed to view that action's logs.
  660. func TestEventStreamACLNoLeakToUnauthorizedUser(t *testing.T) {
  661. cfg, lowUser, adminUser := buildViewPermissionTestConfig(t)
  662. ex := executor.DefaultExecutor(cfg)
  663. ex.RebuildActionMap()
  664. api := newServer(ex)
  665. binding := ex.FindBindingByID("secret_action")
  666. require.NotNil(t, binding, "secret_action binding must exist")
  667. clientLow, clientAdmin := addEventStreamTestClients(t, api, lowUser, adminUser)
  668. defer removeEventStreamTestClients(api, clientLow, clientAdmin)
  669. runEventStreamTestExecution(t, ex, cfg, binding, adminUser)
  670. adminEvents := drainEventStreamUntilFinished(clientAdmin.channel, 2*time.Second)
  671. lowEvents := drainEventStreamWithTimeout(clientLow.channel, 50*time.Millisecond)
  672. assertEventStreamLowUserReceivesNothing(t, lowEvents)
  673. assertEventStreamAdminReceivesSecretActionEvents(t, adminEvents)
  674. }
  675. func TestRegisterStreamingClientEnforcesLimit(t *testing.T) {
  676. cfg := config.DefaultConfig()
  677. ex := executor.DefaultExecutor(cfg)
  678. api := newServer(ex)
  679. user := &authpublic.AuthenticatedUser{Username: "limit-test"}
  680. clients := make([]*streamingClient, 0, maxEventStreamClients)
  681. for i := 0; i < maxEventStreamClients; i++ {
  682. client := &streamingClient{
  683. channel: make(chan *apiv1.EventStreamResponse, 1),
  684. AuthenticatedUser: user,
  685. heartbeatStop: make(chan struct{}),
  686. heartbeatDone: make(chan struct{}),
  687. }
  688. close(client.heartbeatDone)
  689. require.NoError(t, api.registerStreamingClient(client))
  690. clients = append(clients, client)
  691. }
  692. overflow := &streamingClient{
  693. channel: make(chan *apiv1.EventStreamResponse, 1),
  694. AuthenticatedUser: user,
  695. heartbeatStop: make(chan struct{}),
  696. heartbeatDone: make(chan struct{}),
  697. }
  698. close(overflow.heartbeatDone)
  699. err := api.registerStreamingClient(overflow)
  700. require.ErrorIs(t, err, errEventStreamClientLimit)
  701. assert.Len(t, api.streamingClients, maxEventStreamClients)
  702. api.removeClient(clients[0])
  703. require.NoError(t, api.registerStreamingClient(overflow))
  704. assert.Len(t, api.streamingClients, maxEventStreamClients)
  705. for _, client := range clients[1:] {
  706. api.removeClient(client)
  707. }
  708. api.removeClient(overflow)
  709. }
  710. func addEventStreamTestClients(t *testing.T, api *oliveTinAPI, lowUser, adminUser *authpublic.AuthenticatedUser) (*streamingClient, *streamingClient) {
  711. t.Helper()
  712. clientLow := &streamingClient{
  713. channel: make(chan *apiv1.EventStreamResponse, 20),
  714. AuthenticatedUser: lowUser,
  715. }
  716. clientAdmin := &streamingClient{
  717. channel: make(chan *apiv1.EventStreamResponse, 20),
  718. AuthenticatedUser: adminUser,
  719. }
  720. api.streamingClientsMutex.Lock()
  721. api.streamingClients[clientLow] = struct{}{}
  722. api.streamingClients[clientAdmin] = struct{}{}
  723. api.streamingClientsMutex.Unlock()
  724. return clientLow, clientAdmin
  725. }
  726. func removeEventStreamTestClients(api *oliveTinAPI, clientLow, clientAdmin *streamingClient) {
  727. api.streamingClientsMutex.Lock()
  728. delete(api.streamingClients, clientLow)
  729. delete(api.streamingClients, clientAdmin)
  730. api.streamingClientsMutex.Unlock()
  731. close(clientLow.channel)
  732. close(clientAdmin.channel)
  733. }
  734. func runEventStreamTestExecution(t *testing.T, ex *executor.Executor, cfg *config.Config, binding *executor.ActionBinding, adminUser *authpublic.AuthenticatedUser) {
  735. t.Helper()
  736. execReq := &executor.ExecutionRequest{
  737. Binding: binding,
  738. Arguments: map[string]string{},
  739. TrackingID: uuid.NewString(),
  740. Cfg: cfg,
  741. AuthenticatedUser: adminUser,
  742. }
  743. wg, _ := ex.ExecRequest(execReq)
  744. wg.Wait()
  745. }
  746. func drainEventStreamUntilFinished(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  747. var out []*apiv1.EventStreamResponse
  748. deadline := time.Now().Add(timeout)
  749. for time.Now().Before(deadline) {
  750. ev, finished := recvEventStreamOne(ch, 50*time.Millisecond)
  751. if ev != nil {
  752. out = append(out, ev)
  753. }
  754. if finished {
  755. return out
  756. }
  757. }
  758. return out
  759. }
  760. func recvEventStreamOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  761. select {
  762. case ev, ok := <-ch:
  763. if !ok {
  764. return nil, true
  765. }
  766. return ev, ev.GetExecutionFinished() != nil
  767. case <-time.After(timeout):
  768. return nil, true
  769. }
  770. }
  771. func eventStreamRecvResult(ev *apiv1.EventStreamResponse, ok bool) (*apiv1.EventStreamResponse, bool) {
  772. if !ok {
  773. return nil, true
  774. }
  775. return ev, false
  776. }
  777. func recvEventStreamWithTimeoutOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  778. select {
  779. case ev, ok := <-ch:
  780. return eventStreamRecvResult(ev, ok)
  781. case <-time.After(timeout):
  782. return nil, true
  783. }
  784. }
  785. func drainEventStreamWithTimeout(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  786. var out []*apiv1.EventStreamResponse
  787. for {
  788. ev, done := recvEventStreamWithTimeoutOne(ch, timeout)
  789. if done {
  790. return out
  791. }
  792. out = append(out, ev)
  793. }
  794. }
  795. func assertEventStreamLowUserReceivesNothing(t *testing.T, lowEvents []*apiv1.EventStreamResponse) {
  796. t.Helper()
  797. for _, ev := range lowEvents {
  798. assert.Nil(t, ev.GetExecutionStarted(), "low-privilege user must not receive ExecutionStarted")
  799. assert.Nil(t, ev.GetExecutionFinished(), "low-privilege user must not receive ExecutionFinished")
  800. assert.Nil(t, ev.GetOutputChunk(), "low-privilege user must not receive OutputChunk")
  801. }
  802. assert.Empty(t, lowEvents, "low-privilege user with Logs:false must not receive any execution events")
  803. }
  804. func assertEventStreamAdminReceivesSecretActionEvents(t *testing.T, adminEvents []*apiv1.EventStreamResponse) {
  805. t.Helper()
  806. var gotStarted, gotFinished bool
  807. for _, ev := range adminEvents {
  808. if ev.GetExecutionStarted() != nil {
  809. gotStarted = true
  810. assert.Equal(t, "secret_action", ev.GetExecutionStarted().LogEntry.GetBindingId())
  811. }
  812. if ev.GetExecutionFinished() != nil {
  813. gotFinished = true
  814. assert.Equal(t, "secret_action", ev.GetExecutionFinished().LogEntry.GetBindingId())
  815. }
  816. }
  817. assert.True(t, gotStarted, "admin must receive ExecutionStarted for secret_action")
  818. assert.True(t, gotFinished, "admin must receive ExecutionFinished for secret_action")
  819. }
  820. func TestExecutionStatusReturnsBackToDashboards(t *testing.T) {
  821. cfg := config.DefaultConfig()
  822. cfg.Actions = []*config.Action{
  823. {Title: "Dashboard Action", Shell: "echo ok"},
  824. }
  825. cfg.Dashboards = []*config.DashboardComponent{
  826. {
  827. Title: "Ops",
  828. Contents: []*config.DashboardComponent{
  829. {Title: "Dashboard Action"},
  830. },
  831. },
  832. }
  833. ex := executor.DefaultExecutor(cfg)
  834. ex.RebuildActionMap()
  835. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  836. require.NotNil(t, binding)
  837. _, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  838. startResp, err := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{
  839. BindingId: binding.ID,
  840. }))
  841. require.NoError(t, err)
  842. statusResp, err := client.ExecutionStatus(context.Background(), connect.NewRequest(&apiv1.ExecutionStatusRequest{
  843. ExecutionTrackingId: startResp.Msg.ExecutionTrackingId,
  844. }))
  845. require.NoError(t, err)
  846. require.NotNil(t, statusResp.Msg)
  847. require.Len(t, statusResp.Msg.BackToDashboards, 1)
  848. assert.Equal(t, "Ops", statusResp.Msg.BackToDashboards[0].Title)
  849. assert.Equal(t, "/dashboards/Ops", statusResp.Msg.BackToDashboards[0].Path)
  850. }
  851. func TestGetActionBindingReturnsBackToDashboards(t *testing.T) {
  852. cfg := config.DefaultConfig()
  853. cfg.Actions = []*config.Action{
  854. {Title: "Dashboard Action", Shell: "echo ok"},
  855. }
  856. cfg.Dashboards = []*config.DashboardComponent{
  857. {
  858. Title: "Ops",
  859. Contents: []*config.DashboardComponent{
  860. {Title: "Dashboard Action"},
  861. },
  862. },
  863. }
  864. ex := executor.DefaultExecutor(cfg)
  865. ex.RebuildActionMap()
  866. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  867. require.NotNil(t, binding)
  868. _, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  869. resp, err := client.GetActionBinding(context.Background(), connect.NewRequest(&apiv1.GetActionBindingRequest{
  870. BindingId: binding.ID,
  871. }))
  872. require.NoError(t, err)
  873. require.NotNil(t, resp.Msg)
  874. require.Len(t, resp.Msg.BackToDashboards, 1)
  875. assert.Equal(t, "Ops", resp.Msg.BackToDashboards[0].Title)
  876. assert.Equal(t, "/dashboards/Ops", resp.Msg.BackToDashboards[0].Path)
  877. }
  878. func TestBuildActionIncludesGroups(t *testing.T) {
  879. cfg := config.DefaultConfig()
  880. cfg.ActionGroups = map[string]*config.ActionGroup{
  881. "con2queue10": {MaxConcurrent: 2, QueueSize: 10},
  882. }
  883. cfg.Actions = []*config.Action{
  884. {Title: "Long running action", Shell: "sleep 1", Groups: []string{"con2queue10", "missing"}},
  885. }
  886. cfg.Sanitize()
  887. ex := executor.DefaultExecutor(cfg)
  888. ex.RebuildActionMap()
  889. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  890. require.NotNil(t, binding)
  891. rr := &DashboardRenderRequest{cfg: cfg, ex: ex}
  892. actionResult := buildAction(binding, rr)
  893. require.Len(t, actionResult.Groups, 2)
  894. assert.Equal(t, "con2queue10", actionResult.Groups[0].Name)
  895. assert.Equal(t, int32(2), actionResult.Groups[0].MaxConcurrent)
  896. assert.Equal(t, int32(10), actionResult.Groups[0].QueueSize)
  897. assert.Equal(t, "missing", actionResult.Groups[1].Name)
  898. assert.Equal(t, int32(0), actionResult.Groups[1].MaxConcurrent)
  899. }
  900. func TestBuildChoicesExpandsChecklistEntityChoices(t *testing.T) {
  901. entities.AddEntity("room", "0", map[string]any{"hostname": "attic"})
  902. entities.AddEntity("room", "1", map[string]any{"hostname": "basement"})
  903. t.Cleanup(func() {
  904. entities.ClearEntitiesOfType("room")
  905. })
  906. arg := config.ActionArgument{
  907. Type: "checklist",
  908. Entity: "room",
  909. Choices: []config.ActionArgumentChoice{
  910. {Title: "{{ room.hostname }}", Value: "{{ room.hostname }}"},
  911. },
  912. }
  913. choices := buildChoices(arg)
  914. require.Len(t, choices, 2)
  915. assert.Equal(t, "attic", choices[0].Value)
  916. assert.Equal(t, "attic", choices[0].Title)
  917. assert.Equal(t, "basement", choices[1].Value)
  918. assert.Equal(t, "basement", choices[1].Title)
  919. }