api_test.go 29 KB

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