api_test.go 39 KB

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