4
0

api_test.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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. // TestValidateArgumentTypeDeniesGuestsWhenLoginRequired (GHSA-f637-w7p2-m7fx) asserts that when
  343. // guests must log in, ValidateArgumentType does not bypass dashboard access controls.
  344. func TestValidateArgumentTypeDeniesGuestsWhenLoginRequired(t *testing.T) {
  345. cfg := config.DefaultConfig()
  346. cfg.AuthRequireGuestsToLogin = true
  347. cfg.Actions = append(cfg.Actions, &config.Action{
  348. ID: "a1",
  349. Title: "Probe",
  350. Shell: "echo",
  351. Arguments: []config.ActionArgument{
  352. {Name: "x", Type: "ascii"},
  353. },
  354. })
  355. ex := executor.DefaultExecutor(cfg)
  356. ex.RebuildActionMap()
  357. ts, client := getNewTestServerAndClient(cfg)
  358. defer ts.Close()
  359. _, err := client.ValidateArgumentType(context.Background(), connect.NewRequest(&apiv1.ValidateArgumentTypeRequest{
  360. BindingId: "a1",
  361. ArgumentName: "x",
  362. Value: "v",
  363. Type: "ascii",
  364. }))
  365. require.Error(t, err)
  366. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  367. "guest must not call ValidateArgumentType when AuthRequireGuestsToLogin is true")
  368. }
  369. // TestValidateArgumentTypeDeniedWithoutViewPermission (GHSA-f637-w7p2-m7fx) asserts ValidateArgumentType
  370. // respects the same view ACL as GetActionBinding so the RPC cannot enumerate restricted actions.
  371. func TestValidateArgumentTypeDeniedWithoutViewPermission(t *testing.T) {
  372. cfg, _, _ := buildViewPermissionTestConfig(t)
  373. cfg.AuthHttpHeaderUsername = "X-Ot-User"
  374. for i := range cfg.Actions {
  375. if cfg.Actions[i].ID == "secret_action" {
  376. cfg.Actions[i].Arguments = []config.ActionArgument{{Name: "target", Type: "ascii"}}
  377. break
  378. }
  379. }
  380. ex := executor.DefaultExecutor(cfg)
  381. ex.RebuildActionMap()
  382. ts, client := getNewTestServerAndClient(cfg)
  383. defer ts.Close()
  384. req := connect.NewRequest(&apiv1.ValidateArgumentTypeRequest{
  385. BindingId: "secret_action",
  386. ArgumentName: "target",
  387. Value: "ok",
  388. Type: "ascii",
  389. })
  390. req.Header().Set("X-Ot-User", "low")
  391. _, err := client.ValidateArgumentType(context.Background(), req)
  392. require.Error(t, err)
  393. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  394. "user with view:false must get permission denied from ValidateArgumentType")
  395. }
  396. // TestValidateArgumentTypeAllowedWithViewPermission (GHSA-f637-w7p2-m7fx) asserts authenticated users
  397. // with view access can still use ValidateArgumentType for argument validation.
  398. func TestValidateArgumentTypeAllowedWithViewPermission(t *testing.T) {
  399. cfg, _, _ := buildViewPermissionTestConfig(t)
  400. cfg.AuthHttpHeaderUsername = "X-Ot-User"
  401. for i := range cfg.Actions {
  402. if cfg.Actions[i].ID == "secret_action" {
  403. cfg.Actions[i].Arguments = []config.ActionArgument{{Name: "target", Type: "ascii"}}
  404. break
  405. }
  406. }
  407. ex := executor.DefaultExecutor(cfg)
  408. ex.RebuildActionMap()
  409. ts, client := getNewTestServerAndClient(cfg)
  410. defer ts.Close()
  411. req := connect.NewRequest(&apiv1.ValidateArgumentTypeRequest{
  412. BindingId: "secret_action",
  413. ArgumentName: "target",
  414. Value: "ok",
  415. Type: "ascii",
  416. })
  417. req.Header().Set("X-Ot-User", "admin")
  418. resp, err := client.ValidateArgumentType(context.Background(), req)
  419. require.NoError(t, err)
  420. require.NotNil(t, resp)
  421. require.NotNil(t, resp.Msg)
  422. assert.True(t, resp.Msg.Valid, "admin with view:true should get successful validation for a valid ascii value")
  423. }
  424. // TestViewPermissionAllowedSeesAction (GHSA: view permission) asserts that a user with view: true
  425. // still sees the action in the dashboard and can fetch it via GetActionBinding.
  426. func TestViewPermissionAllowedSeesAction(t *testing.T) {
  427. cfg, _, adminUser := buildViewPermissionTestConfig(t)
  428. ex := executor.DefaultExecutor(cfg)
  429. ex.RebuildActionMap()
  430. api := newServer(ex)
  431. rr := &DashboardRenderRequest{
  432. AuthenticatedUser: adminUser,
  433. cfg: cfg,
  434. ex: ex,
  435. }
  436. db := buildDefaultDashboard(rr)
  437. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  438. assert.Contains(t, bindingIdsInDashboard, "secret_action",
  439. "user with view:true must see action in dashboard; got bindingIds: %v", bindingIdsInDashboard)
  440. resp, err := api.getActionBindingResponse(adminUser, "secret_action")
  441. require.NoError(t, err)
  442. require.NotNil(t, resp)
  443. require.NotNil(t, resp.Action)
  444. assert.Equal(t, "secret_action", resp.Action.BindingId)
  445. }
  446. // TestViewPermissionExcludedFromCustomDashboard (issue #921) asserts that when a custom dashboard
  447. // lists an action by title, users without view permission do not see that action (title or icon).
  448. func TestViewPermissionExcludedFromCustomDashboard(t *testing.T) {
  449. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  450. cfg.Dashboards = []*config.DashboardComponent{
  451. {
  452. Title: "Custom",
  453. Contents: []*config.DashboardComponent{
  454. {Title: "Secret Action"},
  455. },
  456. },
  457. }
  458. ex := executor.DefaultExecutor(cfg)
  459. ex.RebuildActionMap()
  460. rr := &DashboardRenderRequest{
  461. AuthenticatedUser: lowUser,
  462. cfg: cfg,
  463. ex: ex,
  464. }
  465. dashboard := findDashboardByTitle(rr, "Custom")
  466. require.NotNil(t, dashboard)
  467. db := buildDashboardFromConfig(dashboard, rr)
  468. require.NotNil(t, db)
  469. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  470. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  471. "user with view:false must not see action on custom dashboard; got bindingIds: %v", bindingIdsInDashboard)
  472. assert.False(t, dashboardContentsContainForbiddenComponent(db.Contents, "Secret Action", "🔒"),
  473. "user with view:false must not see Secret Action title or lock icon in custom dashboard")
  474. }
  475. // TestViewPermissionExcludedFromEntityDashboard (GHSA: view permission) asserts that when a dashboard
  476. // has an entity fieldset listing an action, users without view permission do not see that action.
  477. func TestViewPermissionExcludedFromEntityDashboard(t *testing.T) {
  478. entities.ClearEntitiesOfType("vp_entity_test")
  479. defer entities.ClearEntitiesOfType("vp_entity_test")
  480. entities.AddEntity("vp_entity_test", "1", map[string]any{"title": "Test Entity"})
  481. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  482. cfg.Dashboards = []*config.DashboardComponent{
  483. {
  484. Title: "WithEntity",
  485. Contents: []*config.DashboardComponent{
  486. {
  487. Title: "Servers", Type: "fieldset", Entity: "vp_entity_test",
  488. Contents: []*config.DashboardComponent{{Title: "Secret Action"}},
  489. },
  490. },
  491. },
  492. }
  493. ex := executor.DefaultExecutor(cfg)
  494. ex.RebuildActionMap()
  495. rr := &DashboardRenderRequest{
  496. AuthenticatedUser: lowUser,
  497. cfg: cfg,
  498. ex: ex,
  499. }
  500. dashboard := findDashboardByTitle(rr, "WithEntity")
  501. require.NotNil(t, dashboard)
  502. db := buildDashboardFromConfig(dashboard, rr)
  503. require.NotNil(t, db)
  504. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  505. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  506. "user with view:false must not see action in entity fieldset; got bindingIds: %v", bindingIdsInDashboard)
  507. assert.False(t, dashboardContentsContainForbiddenComponent(db.Contents, "Secret Action", "🔒"),
  508. "user with view:false must not see Secret Action title or lock icon in entity dashboard")
  509. }
  510. func bindingIdsInDashboardContents(contents []*apiv1.DashboardComponent) []string {
  511. var ids []string
  512. for _, c := range contents {
  513. ids = append(ids, bindingIdsFromComponent(c)...)
  514. }
  515. return ids
  516. }
  517. func bindingIdsFromComponent(c *apiv1.DashboardComponent) []string {
  518. if c == nil {
  519. return nil
  520. }
  521. var ids []string
  522. if c.Action != nil && c.Action.BindingId != "" {
  523. ids = append(ids, c.Action.BindingId)
  524. }
  525. return append(ids, bindingIdsInDashboardContents(c.Contents)...)
  526. }
  527. func componentHasForbiddenTitleOrIcon(c *apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  528. return c != nil && (c.Title == forbiddenTitle || c.Icon == forbiddenIcon)
  529. }
  530. func componentOrDescendantsContainForbidden(c *apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  531. if c == nil {
  532. return false
  533. }
  534. if componentHasForbiddenTitleOrIcon(c, forbiddenTitle, forbiddenIcon) {
  535. return true
  536. }
  537. return dashboardContentsContainForbiddenComponent(c.Contents, forbiddenTitle, forbiddenIcon)
  538. }
  539. // dashboardContentsContainForbiddenComponent recursively walks contents and returns true if any
  540. // component has Title == forbiddenTitle or Icon == forbiddenIcon.
  541. func dashboardContentsContainForbiddenComponent(contents []*apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  542. for _, c := range contents {
  543. if componentOrDescendantsContainForbidden(c, forbiddenTitle, forbiddenIcon) {
  544. return true
  545. }
  546. }
  547. return false
  548. }
  549. func TestOrderTopLevelDashboardComponents_RegularFieldsetsPreserveConfigOrder(t *testing.T) {
  550. zebra := &apiv1.DashboardComponent{Title: "Zebra", Type: "fieldset", EntityType: ""}
  551. alpha := &apiv1.DashboardComponent{Title: "Alpha", Type: "fieldset", EntityType: ""}
  552. root := &apiv1.DashboardComponent{Title: "Actions", Type: "fieldset", EntityType: ""}
  553. components := []*apiv1.DashboardComponent{zebra, alpha, root}
  554. out := orderTopLevelDashboardComponents(components, root)
  555. require.Len(t, out, 3)
  556. assert.Same(t, zebra, out[0], "first must be Zebra (config order)")
  557. assert.Same(t, alpha, out[1], "second must be Alpha (config order)")
  558. assert.Same(t, root, out[2], "third must be root Actions fieldset")
  559. }
  560. func TestOrderTopLevelDashboardComponents_SortablesSorted(t *testing.T) {
  561. entityBeta := &apiv1.DashboardComponent{Title: "Beta", Type: "fieldset", EntityType: "server"}
  562. entityAlpha := &apiv1.DashboardComponent{Title: "Alpha", Type: "fieldset", EntityType: "server"}
  563. components := []*apiv1.DashboardComponent{entityBeta, entityAlpha}
  564. out := orderTopLevelDashboardComponents(components, nil)
  565. require.Len(t, out, 2)
  566. assert.Equal(t, "Alpha", out[0].Title, "sortables ordered by title")
  567. assert.Equal(t, "Beta", out[1].Title)
  568. }
  569. // TestEventStreamACLNoLeakToUnauthorizedUser (GHSA-228v-wc5r-j8m7) asserts that EventStream
  570. // does not send execution events or output chunks to users who are not allowed to view that action's logs.
  571. func TestEventStreamACLNoLeakToUnauthorizedUser(t *testing.T) {
  572. cfg, lowUser, adminUser := buildViewPermissionTestConfig(t)
  573. ex := executor.DefaultExecutor(cfg)
  574. ex.RebuildActionMap()
  575. api := newServer(ex)
  576. binding := ex.FindBindingByID("secret_action")
  577. require.NotNil(t, binding, "secret_action binding must exist")
  578. clientLow, clientAdmin := addEventStreamTestClients(t, api, lowUser, adminUser)
  579. defer removeEventStreamTestClients(api, clientLow, clientAdmin)
  580. runEventStreamTestExecution(t, ex, cfg, binding, adminUser)
  581. adminEvents := drainEventStreamUntilFinished(clientAdmin.channel, 2*time.Second)
  582. lowEvents := drainEventStreamWithTimeout(clientLow.channel, 50*time.Millisecond)
  583. assertEventStreamLowUserReceivesNothing(t, lowEvents)
  584. assertEventStreamAdminReceivesSecretActionEvents(t, adminEvents)
  585. }
  586. func addEventStreamTestClients(t *testing.T, api *oliveTinAPI, lowUser, adminUser *authpublic.AuthenticatedUser) (*streamingClient, *streamingClient) {
  587. t.Helper()
  588. clientLow := &streamingClient{
  589. channel: make(chan *apiv1.EventStreamResponse, 20),
  590. AuthenticatedUser: lowUser,
  591. }
  592. clientAdmin := &streamingClient{
  593. channel: make(chan *apiv1.EventStreamResponse, 20),
  594. AuthenticatedUser: adminUser,
  595. }
  596. api.streamingClientsMutex.Lock()
  597. api.streamingClients[clientLow] = struct{}{}
  598. api.streamingClients[clientAdmin] = struct{}{}
  599. api.streamingClientsMutex.Unlock()
  600. return clientLow, clientAdmin
  601. }
  602. func removeEventStreamTestClients(api *oliveTinAPI, clientLow, clientAdmin *streamingClient) {
  603. api.streamingClientsMutex.Lock()
  604. delete(api.streamingClients, clientLow)
  605. delete(api.streamingClients, clientAdmin)
  606. api.streamingClientsMutex.Unlock()
  607. close(clientLow.channel)
  608. close(clientAdmin.channel)
  609. }
  610. func runEventStreamTestExecution(t *testing.T, ex *executor.Executor, cfg *config.Config, binding *executor.ActionBinding, adminUser *authpublic.AuthenticatedUser) {
  611. t.Helper()
  612. execReq := &executor.ExecutionRequest{
  613. Binding: binding,
  614. Arguments: map[string]string{},
  615. TrackingID: uuid.NewString(),
  616. Cfg: cfg,
  617. AuthenticatedUser: adminUser,
  618. }
  619. wg, _ := ex.ExecRequest(execReq)
  620. wg.Wait()
  621. }
  622. func drainEventStreamUntilFinished(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  623. var out []*apiv1.EventStreamResponse
  624. deadline := time.Now().Add(timeout)
  625. for time.Now().Before(deadline) {
  626. ev, finished := recvEventStreamOne(ch, 50*time.Millisecond)
  627. if ev != nil {
  628. out = append(out, ev)
  629. }
  630. if finished {
  631. return out
  632. }
  633. }
  634. return out
  635. }
  636. func recvEventStreamOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  637. select {
  638. case ev, ok := <-ch:
  639. if !ok {
  640. return nil, true
  641. }
  642. return ev, ev.GetExecutionFinished() != nil
  643. case <-time.After(timeout):
  644. return nil, true
  645. }
  646. }
  647. func eventStreamRecvResult(ev *apiv1.EventStreamResponse, ok bool) (*apiv1.EventStreamResponse, bool) {
  648. if !ok {
  649. return nil, true
  650. }
  651. return ev, false
  652. }
  653. func recvEventStreamWithTimeoutOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  654. select {
  655. case ev, ok := <-ch:
  656. return eventStreamRecvResult(ev, ok)
  657. case <-time.After(timeout):
  658. return nil, true
  659. }
  660. }
  661. func drainEventStreamWithTimeout(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  662. var out []*apiv1.EventStreamResponse
  663. for {
  664. ev, done := recvEventStreamWithTimeoutOne(ch, timeout)
  665. if done {
  666. return out
  667. }
  668. out = append(out, ev)
  669. }
  670. }
  671. func assertEventStreamLowUserReceivesNothing(t *testing.T, lowEvents []*apiv1.EventStreamResponse) {
  672. t.Helper()
  673. for _, ev := range lowEvents {
  674. assert.Nil(t, ev.GetExecutionStarted(), "low-privilege user must not receive ExecutionStarted")
  675. assert.Nil(t, ev.GetExecutionFinished(), "low-privilege user must not receive ExecutionFinished")
  676. assert.Nil(t, ev.GetOutputChunk(), "low-privilege user must not receive OutputChunk")
  677. }
  678. assert.Empty(t, lowEvents, "low-privilege user with Logs:false must not receive any execution events")
  679. }
  680. func assertEventStreamAdminReceivesSecretActionEvents(t *testing.T, adminEvents []*apiv1.EventStreamResponse) {
  681. t.Helper()
  682. var gotStarted, gotFinished bool
  683. for _, ev := range adminEvents {
  684. if ev.GetExecutionStarted() != nil {
  685. gotStarted = true
  686. assert.Equal(t, "secret_action", ev.GetExecutionStarted().LogEntry.GetBindingId())
  687. }
  688. if ev.GetExecutionFinished() != nil {
  689. gotFinished = true
  690. assert.Equal(t, "secret_action", ev.GetExecutionFinished().LogEntry.GetBindingId())
  691. }
  692. }
  693. assert.True(t, gotStarted, "admin must receive ExecutionStarted for secret_action")
  694. assert.True(t, gotFinished, "admin must receive ExecutionFinished for secret_action")
  695. }