api_test.go 34 KB

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