api_test.go 34 KB

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