api_test.go 37 KB

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