api_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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. apiPath, apiHandler := GetNewHandler(ex)
  25. mux := http.NewServeMux()
  26. mux.Handle("/api/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  27. log.Infof("HTTP Request: %s %s", r.Method, r.URL.Path)
  28. // Translate /api/<service>/<method> to <service>/<method>
  29. fn := path.Base(r.URL.Path)
  30. r.URL.Path = apiPath + fn
  31. apiHandler.ServeHTTP(w, r)
  32. }))
  33. log.Infof("API path is %s", apiPath)
  34. httpclient := &http.Client{}
  35. ts := httptest.NewServer(mux)
  36. client := apiv1connect.NewOliveTinApiServiceClient(httpclient, ts.URL+"/api")
  37. log.Infof("Test server URL is %s", ts.URL+"/api"+apiPath)
  38. return ts, client
  39. }
  40. func TestGetActionsAndStart(t *testing.T) {
  41. cfg := config.DefaultConfig()
  42. btn1 := &config.Action{}
  43. btn1.Title = "blat"
  44. btn1.ID = "blat"
  45. btn1.Shell = "echo 'test'"
  46. cfg.Actions = append(cfg.Actions, btn1)
  47. ex := executor.DefaultExecutor(cfg)
  48. ex.RebuildActionMap()
  49. conn, client := getNewTestServerAndClient(cfg)
  50. respInit, errInit := client.Init(context.Background(), connect.NewRequest(&apiv1.InitRequest{}))
  51. respGetReady, errReady := client.GetReadyz(context.Background(), connect.NewRequest(&apiv1.GetReadyzRequest{}))
  52. if errInit != nil {
  53. t.Errorf("Init request failed: %v", errInit)
  54. return
  55. }
  56. if errReady != nil {
  57. t.Errorf("GetReadyz request failed: %v", errReady)
  58. return
  59. }
  60. log.Infof("GetReadyz response: %v", respGetReady.Msg)
  61. assert.Equal(t, true, true, "sayHello Failed")
  62. // assert.Equal(t, 1, len(respGb.Msg.Actions), "Got 1 action button back")
  63. log.Printf("Response: %+v", respInit)
  64. respSa, err := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{
  65. // ActionId: "blat"
  66. }))
  67. assert.NotNil(t, err, "Error 404 after start action")
  68. assert.Nil(t, respSa, "Nil response for non existing action")
  69. defer conn.Close()
  70. }
  71. func TestGetEntities(t *testing.T) {
  72. cfg := config.DefaultConfig()
  73. ts, client := getNewTestServerAndClient(cfg)
  74. defer ts.Close()
  75. setupTestEntities()
  76. resp, err := client.GetEntities(context.Background(), connect.NewRequest(&apiv1.GetEntitiesRequest{}))
  77. assert.NoError(t, err, "GetEntities should not return an error")
  78. assert.NotNil(t, resp, "GetEntities response should not be nil")
  79. assert.NotNil(t, resp.Msg, "GetEntities response message should not be nil")
  80. entityDefinitions := resp.Msg.EntityDefinitions
  81. assert.Equal(t, 3, len(entityDefinitions), "Should return 3 entity definitions")
  82. validateEntityOrderAndStructure(t, entityDefinitions)
  83. validateNoDuplicates(t, entityDefinitions)
  84. validateConsistency(t, client, entityDefinitions)
  85. }
  86. func setupTestEntities() {
  87. entities.ClearEntitiesOfType("server")
  88. entities.ClearEntitiesOfType("database")
  89. entities.ClearEntitiesOfType("application")
  90. entities.AddEntity("server", "zebra", map[string]any{"title": "Server Zebra", "hostname": "zebra.example.com"})
  91. entities.AddEntity("server", "alpha", map[string]any{"title": "Server Alpha", "hostname": "alpha.example.com"})
  92. entities.AddEntity("server", "beta", map[string]any{"title": "Server Beta", "hostname": "beta.example.com"})
  93. entities.AddEntity("database", "mysql", map[string]any{"title": "MySQL Database", "type": "mysql"})
  94. entities.AddEntity("database", "postgres", map[string]any{"title": "PostgreSQL Database", "type": "postgres"})
  95. entities.AddEntity("application", "webapp", map[string]any{"title": "Web Application", "port": 8080})
  96. }
  97. func validateEntityOrderAndStructure(t *testing.T, entityDefinitions []*apiv1.EntityDefinition) {
  98. assert.Equal(t, "application", entityDefinitions[0].Title, "First entity should be 'application' (alphabetically first)")
  99. assert.Equal(t, 1, len(entityDefinitions[0].Instances), "Application should have 1 instance")
  100. assert.Equal(t, "webapp", entityDefinitions[0].Instances[0].UniqueKey, "Application instance should be 'webapp'")
  101. assert.Equal(t, "database", entityDefinitions[1].Title, "Second entity should be 'database' (alphabetically second)")
  102. assert.Equal(t, 2, len(entityDefinitions[1].Instances), "Database should have 2 instances")
  103. assert.Equal(t, "mysql", entityDefinitions[1].Instances[0].UniqueKey, "First database instance should be 'mysql' (alphabetically first)")
  104. assert.Equal(t, "postgres", entityDefinitions[1].Instances[1].UniqueKey, "Second database instance should be 'postgres' (alphabetically second)")
  105. assert.Equal(t, "server", entityDefinitions[2].Title, "Third entity should be 'server' (alphabetically third)")
  106. assert.Equal(t, 3, len(entityDefinitions[2].Instances), "Server should have 3 instances")
  107. assert.Equal(t, "alpha", entityDefinitions[2].Instances[0].UniqueKey, "First server instance should be 'alpha' (alphabetically first)")
  108. assert.Equal(t, "beta", entityDefinitions[2].Instances[1].UniqueKey, "Second server instance should be 'beta' (alphabetically second)")
  109. assert.Equal(t, "zebra", entityDefinitions[2].Instances[2].UniqueKey, "Third server instance should be 'zebra' (alphabetically third)")
  110. }
  111. func validateNoDuplicates(t *testing.T, entityDefinitions []*apiv1.EntityDefinition) {
  112. instanceKeys := make(map[string]map[string]bool)
  113. for _, def := range entityDefinitions {
  114. instanceKeys[def.Title] = make(map[string]bool)
  115. for _, inst := range def.Instances {
  116. assert.False(t, instanceKeys[def.Title][inst.UniqueKey], "Instance key %s should not be duplicated in entity %s", inst.UniqueKey, def.Title)
  117. instanceKeys[def.Title][inst.UniqueKey] = true
  118. }
  119. }
  120. }
  121. func validateConsistency(t *testing.T, client apiv1connect.OliveTinApiServiceClient, entityDefinitions []*apiv1.EntityDefinition) {
  122. resp2, err2 := client.GetEntities(context.Background(), connect.NewRequest(&apiv1.GetEntitiesRequest{}))
  123. assert.NoError(t, err2, "Second GetEntities call should not return an error")
  124. assert.Equal(t, len(entityDefinitions), len(resp2.Msg.EntityDefinitions), "Second call should return same number of entity definitions")
  125. for i, def := range entityDefinitions {
  126. assert.Equal(t, def.Title, resp2.Msg.EntityDefinitions[i].Title, "Entity order should be consistent across calls")
  127. assert.Equal(t, len(def.Instances), len(resp2.Msg.EntityDefinitions[i].Instances), "Instance count should be consistent")
  128. for j, inst := range def.Instances {
  129. assert.Equal(t, inst.UniqueKey, resp2.Msg.EntityDefinitions[i].Instances[j].UniqueKey, "Instance order should be consistent across calls")
  130. }
  131. }
  132. }
  133. func TestEvaluateEnabledExpression(t *testing.T) {
  134. tests := []struct {
  135. name string
  136. expression string
  137. entity *entities.Entity
  138. expectedResult bool
  139. }{
  140. {
  141. name: "empty expression returns true",
  142. expression: "",
  143. entity: nil,
  144. expectedResult: true,
  145. },
  146. {
  147. name: "literal true returns true",
  148. expression: "true",
  149. entity: nil,
  150. expectedResult: true,
  151. },
  152. {
  153. name: "literal True returns true (case insensitive)",
  154. expression: "True",
  155. entity: nil,
  156. expectedResult: true,
  157. },
  158. {
  159. name: "literal 1 returns true",
  160. expression: "1",
  161. entity: nil,
  162. expectedResult: true,
  163. },
  164. {
  165. name: "literal false returns false",
  166. expression: "false",
  167. entity: nil,
  168. expectedResult: false,
  169. },
  170. {
  171. name: "literal 0 returns false",
  172. expression: "0",
  173. entity: nil,
  174. expectedResult: false,
  175. },
  176. {
  177. name: "empty result returns false",
  178. expression: "{{ .NonExistent }}",
  179. entity: nil,
  180. expectedResult: false,
  181. },
  182. {
  183. name: "expression with CurrentEntity true",
  184. expression: "{{ eq .CurrentEntity.powered_on true }}",
  185. entity: &entities.Entity{Data: map[string]any{"powered_on": true}},
  186. expectedResult: true,
  187. },
  188. {
  189. name: "expression with CurrentEntity false",
  190. expression: "{{ eq .CurrentEntity.powered_on true }}",
  191. entity: &entities.Entity{Data: map[string]any{"powered_on": false}},
  192. expectedResult: false,
  193. },
  194. {
  195. name: "expression with CurrentEntity integer 1",
  196. expression: "{{ .CurrentEntity.status }}",
  197. entity: &entities.Entity{Data: map[string]any{"status": 1}},
  198. expectedResult: true,
  199. },
  200. {
  201. name: "expression with CurrentEntity integer 0",
  202. expression: "{{ .CurrentEntity.status }}",
  203. entity: &entities.Entity{Data: map[string]any{"status": 0}},
  204. expectedResult: false,
  205. },
  206. {
  207. name: "template parse error returns false",
  208. expression: "{{ invalid syntax }}",
  209. entity: nil,
  210. expectedResult: false,
  211. },
  212. {
  213. name: "template exec error returns false",
  214. expression: "{{ .CurrentEntity.nonexistent }}",
  215. entity: nil,
  216. expectedResult: false,
  217. },
  218. }
  219. for _, tt := range tests {
  220. t.Run(tt.name, func(t *testing.T) {
  221. action := &config.Action{
  222. EnabledExpression: tt.expression,
  223. }
  224. result := evaluateEnabledExpression(action, tt.entity)
  225. assert.Equal(t, tt.expectedResult, result, "evaluateEnabledExpression should return expected result")
  226. })
  227. }
  228. }
  229. func TestBuildActionWithEnabledExpression(t *testing.T) {
  230. cfg := config.DefaultConfig()
  231. cfg.DefaultPermissions.Exec = true
  232. action := &config.Action{
  233. Title: "Test Action",
  234. Shell: "echo test",
  235. EnabledExpression: "{{ eq .CurrentEntity.enabled true }}",
  236. }
  237. cfg.Actions = append(cfg.Actions, action)
  238. ex := executor.DefaultExecutor(cfg)
  239. ex.RebuildActionMap()
  240. binding := findBindingByTitle(ex, "Test Action")
  241. assert.NotNil(t, binding, "Binding should be found")
  242. rr := &DashboardRenderRequest{
  243. AuthenticatedUser: &authpublic.AuthenticatedUser{Username: "testuser"},
  244. cfg: cfg,
  245. ex: ex,
  246. }
  247. testWithEntity(t, binding, rr, true, true, "Action should be executable when entity.enabled is true")
  248. testWithEntity(t, binding, rr, false, false, "Action should not be executable when entity.enabled is false")
  249. bindingNoExpr := findBindingByTitle(ex, "Test Action No Expression")
  250. if bindingNoExpr == nil {
  251. actionNoExpression := &config.Action{
  252. Title: "Test Action No Expression",
  253. Shell: "echo test",
  254. }
  255. cfg.Actions = append(cfg.Actions, actionNoExpression)
  256. ex.RebuildActionMap()
  257. bindingNoExpr = findBindingByTitle(ex, "Test Action No Expression")
  258. }
  259. actionResult := buildAction(bindingNoExpr, rr)
  260. assert.True(t, actionResult.CanExec, "Action without enabledExpression should be executable")
  261. }
  262. func findBindingByTitle(ex *executor.Executor, title string) *executor.ActionBinding {
  263. ex.MapActionBindingsLock.RLock()
  264. defer ex.MapActionBindingsLock.RUnlock()
  265. for _, b := range ex.MapActionBindings {
  266. if b.Action.Title == title {
  267. return b
  268. }
  269. }
  270. return nil
  271. }
  272. func testWithEntity(t *testing.T, binding *executor.ActionBinding, rr *DashboardRenderRequest, enabled bool, expectedCanExec bool, message string) {
  273. binding.Entity = &entities.Entity{
  274. UniqueKey: "test-entity",
  275. Data: map[string]any{"enabled": enabled},
  276. }
  277. actionResult := buildAction(binding, rr)
  278. assert.Equal(t, expectedCanExec, actionResult.CanExec, message)
  279. }
  280. // buildViewPermissionTestConfig returns config and users for GHSA view-permission tests:
  281. // one action "secret_action", ACL "restricted" (view:false, logs:false) for user "low", ACL "full" (view:true, logs:true) for user "admin".
  282. func buildViewPermissionTestConfig(t *testing.T) (*config.Config, *authpublic.AuthenticatedUser, *authpublic.AuthenticatedUser) {
  283. t.Helper()
  284. cfg := config.DefaultConfig()
  285. cfg.DefaultPermissions.View = false
  286. cfg.DefaultPermissions.Exec = false
  287. cfg.DefaultPermissions.Logs = false
  288. cfg.Actions = append(cfg.Actions, &config.Action{
  289. ID: "secret_action",
  290. Title: "Secret Action",
  291. Shell: "echo sensitive",
  292. Icon: "🔒",
  293. })
  294. cfg.AccessControlLists = append(cfg.AccessControlLists,
  295. &config.AccessControlList{
  296. Name: "restricted",
  297. MatchUsernames: []string{"low"},
  298. AddToEveryAction: true,
  299. Permissions: config.PermissionsList{View: false, Exec: false, Logs: false, Kill: false},
  300. },
  301. &config.AccessControlList{
  302. Name: "full",
  303. MatchUsernames: []string{"admin"},
  304. AddToEveryAction: true,
  305. Permissions: config.PermissionsList{View: true, Exec: true, Logs: true, Kill: true},
  306. },
  307. )
  308. lowUser := &authpublic.AuthenticatedUser{Username: "low"}
  309. lowUser.BuildUserAcls(cfg)
  310. adminUser := &authpublic.AuthenticatedUser{Username: "admin"}
  311. adminUser.BuildUserAcls(cfg)
  312. return cfg, lowUser, adminUser
  313. }
  314. // TestViewPermissionExcludedFromDashboard (GHSA: view permission) asserts that when a user has view: false,
  315. // the default dashboard must not include that action. Covers GetDashboard not leaking action metadata.
  316. func TestViewPermissionExcludedFromDashboard(t *testing.T) {
  317. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  318. ex := executor.DefaultExecutor(cfg)
  319. ex.RebuildActionMap()
  320. rr := &DashboardRenderRequest{
  321. AuthenticatedUser: lowUser,
  322. cfg: cfg,
  323. ex: ex,
  324. }
  325. db := buildDefaultDashboard(rr)
  326. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  327. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  328. "user with view:false must not see action in dashboard; got bindingIds: %v", bindingIdsInDashboard)
  329. }
  330. // TestGetActionBindingDeniedWhenNoViewPermission (GHSA: view permission) asserts that GetActionBinding
  331. // returns permission denied for a user with view: false. Covers GetActionBinding not exposing action details.
  332. func TestGetActionBindingDeniedWhenNoViewPermission(t *testing.T) {
  333. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  334. ex := executor.DefaultExecutor(cfg)
  335. ex.RebuildActionMap()
  336. api := newServer(ex)
  337. _, err := api.getActionBindingResponse(lowUser, "secret_action")
  338. require.Error(t, err)
  339. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  340. "user with view:false must get permission denied from GetActionBinding")
  341. }
  342. // TestViewPermissionAllowedSeesAction (GHSA: view permission) asserts that a user with view: true
  343. // still sees the action in the dashboard and can fetch it via GetActionBinding.
  344. func TestViewPermissionAllowedSeesAction(t *testing.T) {
  345. cfg, _, adminUser := buildViewPermissionTestConfig(t)
  346. ex := executor.DefaultExecutor(cfg)
  347. ex.RebuildActionMap()
  348. api := newServer(ex)
  349. rr := &DashboardRenderRequest{
  350. AuthenticatedUser: adminUser,
  351. cfg: cfg,
  352. ex: ex,
  353. }
  354. db := buildDefaultDashboard(rr)
  355. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  356. assert.Contains(t, bindingIdsInDashboard, "secret_action",
  357. "user with view:true must see action in dashboard; got bindingIds: %v", bindingIdsInDashboard)
  358. resp, err := api.getActionBindingResponse(adminUser, "secret_action")
  359. require.NoError(t, err)
  360. require.NotNil(t, resp)
  361. require.NotNil(t, resp.Action)
  362. assert.Equal(t, "secret_action", resp.Action.BindingId)
  363. }
  364. // TestViewPermissionExcludedFromCustomDashboard (issue #921) asserts that when a custom dashboard
  365. // lists an action by title, users without view permission do not see that action (title or icon).
  366. func TestViewPermissionExcludedFromCustomDashboard(t *testing.T) {
  367. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  368. cfg.Dashboards = []*config.DashboardComponent{
  369. {
  370. Title: "Custom",
  371. Contents: []*config.DashboardComponent{
  372. {Title: "Secret Action"},
  373. },
  374. },
  375. }
  376. ex := executor.DefaultExecutor(cfg)
  377. ex.RebuildActionMap()
  378. rr := &DashboardRenderRequest{
  379. AuthenticatedUser: lowUser,
  380. cfg: cfg,
  381. ex: ex,
  382. }
  383. dashboard := findDashboardByTitle(rr, "Custom")
  384. require.NotNil(t, dashboard)
  385. db := buildDashboardFromConfig(dashboard, rr)
  386. require.NotNil(t, db)
  387. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  388. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  389. "user with view:false must not see action on custom dashboard; got bindingIds: %v", bindingIdsInDashboard)
  390. assert.False(t, dashboardContentsContainForbiddenComponent(db.Contents, "Secret Action", "🔒"),
  391. "user with view:false must not see Secret Action title or lock icon in custom dashboard")
  392. }
  393. // TestViewPermissionExcludedFromEntityDashboard (GHSA: view permission) asserts that when a dashboard
  394. // has an entity fieldset listing an action, users without view permission do not see that action.
  395. func TestViewPermissionExcludedFromEntityDashboard(t *testing.T) {
  396. entities.ClearEntitiesOfType("vp_entity_test")
  397. defer entities.ClearEntitiesOfType("vp_entity_test")
  398. entities.AddEntity("vp_entity_test", "1", map[string]any{"title": "Test Entity"})
  399. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  400. cfg.Dashboards = []*config.DashboardComponent{
  401. {
  402. Title: "WithEntity",
  403. Contents: []*config.DashboardComponent{
  404. {
  405. Title: "Servers", Type: "fieldset", Entity: "vp_entity_test",
  406. Contents: []*config.DashboardComponent{{Title: "Secret Action"}},
  407. },
  408. },
  409. },
  410. }
  411. ex := executor.DefaultExecutor(cfg)
  412. ex.RebuildActionMap()
  413. rr := &DashboardRenderRequest{
  414. AuthenticatedUser: lowUser,
  415. cfg: cfg,
  416. ex: ex,
  417. }
  418. dashboard := findDashboardByTitle(rr, "WithEntity")
  419. require.NotNil(t, dashboard)
  420. db := buildDashboardFromConfig(dashboard, rr)
  421. require.NotNil(t, db)
  422. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  423. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  424. "user with view:false must not see action in entity fieldset; got bindingIds: %v", bindingIdsInDashboard)
  425. assert.False(t, dashboardContentsContainForbiddenComponent(db.Contents, "Secret Action", "🔒"),
  426. "user with view:false must not see Secret Action title or lock icon in entity dashboard")
  427. }
  428. func bindingIdsInDashboardContents(contents []*apiv1.DashboardComponent) []string {
  429. var ids []string
  430. for _, c := range contents {
  431. ids = append(ids, bindingIdsFromComponent(c)...)
  432. }
  433. return ids
  434. }
  435. func bindingIdsFromComponent(c *apiv1.DashboardComponent) []string {
  436. if c == nil {
  437. return nil
  438. }
  439. var ids []string
  440. if c.Action != nil && c.Action.BindingId != "" {
  441. ids = append(ids, c.Action.BindingId)
  442. }
  443. return append(ids, bindingIdsInDashboardContents(c.Contents)...)
  444. }
  445. func componentHasForbiddenTitleOrIcon(c *apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  446. return c != nil && (c.Title == forbiddenTitle || c.Icon == forbiddenIcon)
  447. }
  448. func componentOrDescendantsContainForbidden(c *apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  449. if c == nil {
  450. return false
  451. }
  452. if componentHasForbiddenTitleOrIcon(c, forbiddenTitle, forbiddenIcon) {
  453. return true
  454. }
  455. return dashboardContentsContainForbiddenComponent(c.Contents, forbiddenTitle, forbiddenIcon)
  456. }
  457. // dashboardContentsContainForbiddenComponent recursively walks contents and returns true if any
  458. // component has Title == forbiddenTitle or Icon == forbiddenIcon.
  459. func dashboardContentsContainForbiddenComponent(contents []*apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  460. for _, c := range contents {
  461. if componentOrDescendantsContainForbidden(c, forbiddenTitle, forbiddenIcon) {
  462. return true
  463. }
  464. }
  465. return false
  466. }
  467. func TestOrderTopLevelDashboardComponents_RegularFieldsetsPreserveConfigOrder(t *testing.T) {
  468. zebra := &apiv1.DashboardComponent{Title: "Zebra", Type: "fieldset", EntityType: ""}
  469. alpha := &apiv1.DashboardComponent{Title: "Alpha", Type: "fieldset", EntityType: ""}
  470. root := &apiv1.DashboardComponent{Title: "Actions", Type: "fieldset", EntityType: ""}
  471. components := []*apiv1.DashboardComponent{zebra, alpha, root}
  472. out := orderTopLevelDashboardComponents(components, root)
  473. require.Len(t, out, 3)
  474. assert.Same(t, zebra, out[0], "first must be Zebra (config order)")
  475. assert.Same(t, alpha, out[1], "second must be Alpha (config order)")
  476. assert.Same(t, root, out[2], "third must be root Actions fieldset")
  477. }
  478. func TestOrderTopLevelDashboardComponents_SortablesSorted(t *testing.T) {
  479. entityBeta := &apiv1.DashboardComponent{Title: "Beta", Type: "fieldset", EntityType: "server"}
  480. entityAlpha := &apiv1.DashboardComponent{Title: "Alpha", Type: "fieldset", EntityType: "server"}
  481. components := []*apiv1.DashboardComponent{entityBeta, entityAlpha}
  482. out := orderTopLevelDashboardComponents(components, nil)
  483. require.Len(t, out, 2)
  484. assert.Equal(t, "Alpha", out[0].Title, "sortables ordered by title")
  485. assert.Equal(t, "Beta", out[1].Title)
  486. }
  487. // TestEventStreamACLNoLeakToUnauthorizedUser (GHSA-228v-wc5r-j8m7) asserts that EventStream
  488. // does not send execution events or output chunks to users who are not allowed to view that action's logs.
  489. func TestEventStreamACLNoLeakToUnauthorizedUser(t *testing.T) {
  490. cfg, lowUser, adminUser := buildViewPermissionTestConfig(t)
  491. ex := executor.DefaultExecutor(cfg)
  492. ex.RebuildActionMap()
  493. api := newServer(ex)
  494. binding := ex.FindBindingByID("secret_action")
  495. require.NotNil(t, binding, "secret_action binding must exist")
  496. clientLow, clientAdmin := addEventStreamTestClients(t, api, lowUser, adminUser)
  497. defer removeEventStreamTestClients(api, clientLow, clientAdmin)
  498. runEventStreamTestExecution(t, ex, cfg, binding, adminUser)
  499. adminEvents := drainEventStreamUntilFinished(clientAdmin.channel, 2*time.Second)
  500. lowEvents := drainEventStreamWithTimeout(clientLow.channel, 50*time.Millisecond)
  501. assertEventStreamLowUserReceivesNothing(t, lowEvents)
  502. assertEventStreamAdminReceivesSecretActionEvents(t, adminEvents)
  503. }
  504. func addEventStreamTestClients(t *testing.T, api *oliveTinAPI, lowUser, adminUser *authpublic.AuthenticatedUser) (*streamingClient, *streamingClient) {
  505. t.Helper()
  506. clientLow := &streamingClient{
  507. channel: make(chan *apiv1.EventStreamResponse, 20),
  508. AuthenticatedUser: lowUser,
  509. }
  510. clientAdmin := &streamingClient{
  511. channel: make(chan *apiv1.EventStreamResponse, 20),
  512. AuthenticatedUser: adminUser,
  513. }
  514. api.streamingClientsMutex.Lock()
  515. api.streamingClients[clientLow] = struct{}{}
  516. api.streamingClients[clientAdmin] = struct{}{}
  517. api.streamingClientsMutex.Unlock()
  518. return clientLow, clientAdmin
  519. }
  520. func removeEventStreamTestClients(api *oliveTinAPI, clientLow, clientAdmin *streamingClient) {
  521. api.streamingClientsMutex.Lock()
  522. delete(api.streamingClients, clientLow)
  523. delete(api.streamingClients, clientAdmin)
  524. api.streamingClientsMutex.Unlock()
  525. close(clientLow.channel)
  526. close(clientAdmin.channel)
  527. }
  528. func runEventStreamTestExecution(t *testing.T, ex *executor.Executor, cfg *config.Config, binding *executor.ActionBinding, adminUser *authpublic.AuthenticatedUser) {
  529. t.Helper()
  530. execReq := &executor.ExecutionRequest{
  531. Binding: binding,
  532. Arguments: map[string]string{},
  533. TrackingID: uuid.NewString(),
  534. Cfg: cfg,
  535. AuthenticatedUser: adminUser,
  536. }
  537. wg, _ := ex.ExecRequest(execReq)
  538. wg.Wait()
  539. }
  540. func drainEventStreamUntilFinished(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  541. var out []*apiv1.EventStreamResponse
  542. deadline := time.Now().Add(timeout)
  543. for time.Now().Before(deadline) {
  544. ev, finished := recvEventStreamOne(ch, 50*time.Millisecond)
  545. if ev != nil {
  546. out = append(out, ev)
  547. }
  548. if finished {
  549. return out
  550. }
  551. }
  552. return out
  553. }
  554. func recvEventStreamOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  555. select {
  556. case ev, ok := <-ch:
  557. if !ok {
  558. return nil, true
  559. }
  560. return ev, ev.GetExecutionFinished() != nil
  561. case <-time.After(timeout):
  562. return nil, true
  563. }
  564. }
  565. func drainEventStreamWithTimeout(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  566. var out []*apiv1.EventStreamResponse
  567. for {
  568. ev, stop := recvOneEventOrTimeout(ch, timeout)
  569. if stop {
  570. return out
  571. }
  572. out = append(out, ev)
  573. }
  574. }
  575. func recvOneEventOrTimeout(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  576. select {
  577. case ev, ok := <-ch:
  578. if !ok {
  579. return nil, true
  580. }
  581. return ev, false
  582. case <-time.After(timeout):
  583. return nil, true
  584. }
  585. }
  586. func assertEventStreamLowUserReceivesNothing(t *testing.T, lowEvents []*apiv1.EventStreamResponse) {
  587. t.Helper()
  588. for _, ev := range lowEvents {
  589. assert.Nil(t, ev.GetExecutionStarted(), "low-privilege user must not receive ExecutionStarted")
  590. assert.Nil(t, ev.GetExecutionFinished(), "low-privilege user must not receive ExecutionFinished")
  591. assert.Nil(t, ev.GetOutputChunk(), "low-privilege user must not receive OutputChunk")
  592. }
  593. assert.Empty(t, lowEvents, "low-privilege user with Logs:false must not receive any execution events")
  594. }
  595. func assertEventStreamAdminReceivesSecretActionEvents(t *testing.T, adminEvents []*apiv1.EventStreamResponse) {
  596. t.Helper()
  597. var gotStarted, gotFinished bool
  598. for _, ev := range adminEvents {
  599. if ev.GetExecutionStarted() != nil {
  600. gotStarted = true
  601. assert.Equal(t, "secret_action", ev.GetExecutionStarted().LogEntry.GetBindingId())
  602. }
  603. if ev.GetExecutionFinished() != nil {
  604. gotFinished = true
  605. assert.Equal(t, "secret_action", ev.GetExecutionFinished().LogEntry.GetBindingId())
  606. }
  607. }
  608. assert.True(t, gotStarted, "admin must receive ExecutionStarted for secret_action")
  609. assert.True(t, gotFinished, "admin must receive ExecutionFinished for secret_action")
  610. }