4
0

api_test.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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. // buildExecWithoutLogsTestConfig returns config for GHSA-jm28: user "runner" may exec but not read logs.
  468. func buildExecWithoutLogsTestConfig(t *testing.T) (*config.Config, *authpublic.AuthenticatedUser) {
  469. t.Helper()
  470. cfg := config.DefaultConfig()
  471. cfg.AuthHttpHeaderUsername = "X-Ot-User"
  472. cfg.DefaultPermissions.View = false
  473. cfg.DefaultPermissions.Exec = false
  474. cfg.DefaultPermissions.Logs = false
  475. cfg.Actions = append(cfg.Actions, &config.Action{
  476. ID: "run_only",
  477. Title: "Run Only",
  478. Shell: "echo sensitive-output",
  479. Icon: "🔒",
  480. })
  481. cfg.AccessControlLists = append(cfg.AccessControlLists, &config.AccessControlList{
  482. Name: "runner",
  483. MatchUsernames: []string{"runner"},
  484. AddToEveryAction: true,
  485. Permissions: config.PermissionsList{View: true, Exec: true, Logs: false, Kill: false},
  486. })
  487. runner := &authpublic.AuthenticatedUser{Username: "runner"}
  488. runner.BuildUserAcls(cfg)
  489. return cfg, runner
  490. }
  491. // TestStartActionAndWaitDeniesLogsPermission (GHSA-jm28-2wcr-qf3h) asserts sync execution endpoints
  492. // enforce logs ACL and do not return action output to users allowed to exec but not read logs.
  493. func TestStartActionAndWaitDeniesLogsPermission(t *testing.T) {
  494. cfg, _ := buildExecWithoutLogsTestConfig(t)
  495. ex := executor.DefaultExecutor(cfg)
  496. ex.RebuildActionMap()
  497. ts, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  498. defer ts.Close()
  499. req := connect.NewRequest(&apiv1.StartActionAndWaitRequest{
  500. ActionId: "run_only",
  501. })
  502. req.Header().Set("X-Ot-User", "runner")
  503. _, err := client.StartActionAndWait(context.Background(), req)
  504. require.Error(t, err)
  505. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err),
  506. "user with exec:true and logs:false must not receive log output from StartActionAndWait")
  507. }
  508. // TestViewPermissionAllowedSeesAction (GHSA: view permission) asserts that a user with view: true
  509. // still sees the action in the dashboard and can fetch it via GetActionBinding.
  510. func TestViewPermissionAllowedSeesAction(t *testing.T) {
  511. cfg, _, adminUser := buildViewPermissionTestConfig(t)
  512. ex := executor.DefaultExecutor(cfg)
  513. ex.RebuildActionMap()
  514. api := newServer(ex)
  515. rr := &DashboardRenderRequest{
  516. AuthenticatedUser: adminUser,
  517. cfg: cfg,
  518. ex: ex,
  519. }
  520. db := buildDefaultDashboard(rr)
  521. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  522. assert.Contains(t, bindingIdsInDashboard, "secret_action",
  523. "user with view:true must see action in dashboard; got bindingIds: %v", bindingIdsInDashboard)
  524. resp, err := api.getActionBindingResponse(adminUser, "secret_action")
  525. require.NoError(t, err)
  526. require.NotNil(t, resp)
  527. require.NotNil(t, resp.Action)
  528. assert.Equal(t, "secret_action", resp.Action.BindingId)
  529. }
  530. // TestViewPermissionExcludedFromCustomDashboard (issue #921) asserts that when a custom dashboard
  531. // lists an action by title, users without view permission do not see that action (title or icon).
  532. func TestViewPermissionExcludedFromCustomDashboard(t *testing.T) {
  533. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  534. cfg.Dashboards = []*config.DashboardComponent{
  535. {
  536. Title: "Custom",
  537. Contents: []*config.DashboardComponent{
  538. {Title: "Secret Action"},
  539. },
  540. },
  541. }
  542. ex := executor.DefaultExecutor(cfg)
  543. ex.RebuildActionMap()
  544. rr := &DashboardRenderRequest{
  545. AuthenticatedUser: lowUser,
  546. cfg: cfg,
  547. ex: ex,
  548. }
  549. dashboard := findDashboardByTitle(rr, "Custom")
  550. require.NotNil(t, dashboard)
  551. db := buildDashboardFromConfig(dashboard, rr)
  552. require.NotNil(t, db)
  553. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  554. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  555. "user with view:false must not see action on custom dashboard; got bindingIds: %v", bindingIdsInDashboard)
  556. assert.False(t, dashboardContentsContainForbiddenComponent(db.Contents, "Secret Action", "🔒"),
  557. "user with view:false must not see Secret Action title or lock icon in custom dashboard")
  558. }
  559. // TestViewPermissionExcludedFromEntityDashboard (GHSA: view permission) asserts that when a dashboard
  560. // has an entity fieldset listing an action, users without view permission do not see that action.
  561. func TestViewPermissionExcludedFromEntityDashboard(t *testing.T) {
  562. entities.ClearEntitiesOfType("vp_entity_test")
  563. defer entities.ClearEntitiesOfType("vp_entity_test")
  564. entities.AddEntity("vp_entity_test", "1", map[string]any{"title": "Test Entity"})
  565. cfg, lowUser, _ := buildViewPermissionTestConfig(t)
  566. cfg.Dashboards = []*config.DashboardComponent{
  567. {
  568. Title: "WithEntity",
  569. Contents: []*config.DashboardComponent{
  570. {
  571. Title: "Servers", Type: "fieldset", Entity: "vp_entity_test",
  572. Contents: []*config.DashboardComponent{{Title: "Secret Action"}},
  573. },
  574. },
  575. },
  576. }
  577. ex := executor.DefaultExecutor(cfg)
  578. ex.RebuildActionMap()
  579. rr := &DashboardRenderRequest{
  580. AuthenticatedUser: lowUser,
  581. cfg: cfg,
  582. ex: ex,
  583. }
  584. dashboard := findDashboardByTitle(rr, "WithEntity")
  585. require.NotNil(t, dashboard)
  586. db := buildDashboardFromConfig(dashboard, rr)
  587. require.NotNil(t, db)
  588. bindingIdsInDashboard := bindingIdsInDashboardContents(db.Contents)
  589. assert.NotContains(t, bindingIdsInDashboard, "secret_action",
  590. "user with view:false must not see action in entity fieldset; got bindingIds: %v", bindingIdsInDashboard)
  591. assert.False(t, dashboardContentsContainForbiddenComponent(db.Contents, "Secret Action", "🔒"),
  592. "user with view:false must not see Secret Action title or lock icon in entity dashboard")
  593. }
  594. func bindingIdsInDashboardContents(contents []*apiv1.DashboardComponent) []string {
  595. var ids []string
  596. for _, c := range contents {
  597. ids = append(ids, bindingIdsFromComponent(c)...)
  598. }
  599. return ids
  600. }
  601. func bindingIdsFromComponent(c *apiv1.DashboardComponent) []string {
  602. if c == nil {
  603. return nil
  604. }
  605. var ids []string
  606. if c.Action != nil && c.Action.BindingId != "" {
  607. ids = append(ids, c.Action.BindingId)
  608. }
  609. return append(ids, bindingIdsInDashboardContents(c.Contents)...)
  610. }
  611. func componentHasForbiddenTitleOrIcon(c *apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  612. return c != nil && (c.Title == forbiddenTitle || c.Icon == forbiddenIcon)
  613. }
  614. func componentOrDescendantsContainForbidden(c *apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  615. if c == nil {
  616. return false
  617. }
  618. if componentHasForbiddenTitleOrIcon(c, forbiddenTitle, forbiddenIcon) {
  619. return true
  620. }
  621. return dashboardContentsContainForbiddenComponent(c.Contents, forbiddenTitle, forbiddenIcon)
  622. }
  623. // dashboardContentsContainForbiddenComponent recursively walks contents and returns true if any
  624. // component has Title == forbiddenTitle or Icon == forbiddenIcon.
  625. func dashboardContentsContainForbiddenComponent(contents []*apiv1.DashboardComponent, forbiddenTitle, forbiddenIcon string) bool {
  626. for _, c := range contents {
  627. if componentOrDescendantsContainForbidden(c, forbiddenTitle, forbiddenIcon) {
  628. return true
  629. }
  630. }
  631. return false
  632. }
  633. func TestOrderTopLevelDashboardComponents_RegularFieldsetsPreserveConfigOrder(t *testing.T) {
  634. zebra := &apiv1.DashboardComponent{Title: "Zebra", Type: "fieldset", EntityType: ""}
  635. alpha := &apiv1.DashboardComponent{Title: "Alpha", Type: "fieldset", EntityType: ""}
  636. root := &apiv1.DashboardComponent{Title: "Actions", Type: "fieldset", EntityType: ""}
  637. components := []*apiv1.DashboardComponent{zebra, alpha, root}
  638. out := orderTopLevelDashboardComponents(components, root)
  639. require.Len(t, out, 3)
  640. assert.Same(t, zebra, out[0], "first must be Zebra (config order)")
  641. assert.Same(t, alpha, out[1], "second must be Alpha (config order)")
  642. assert.Same(t, root, out[2], "third must be root Actions fieldset")
  643. }
  644. func TestOrderTopLevelDashboardComponents_SortablesSorted(t *testing.T) {
  645. entityBeta := &apiv1.DashboardComponent{Title: "Beta", Type: "fieldset", EntityType: "server"}
  646. entityAlpha := &apiv1.DashboardComponent{Title: "Alpha", Type: "fieldset", EntityType: "server"}
  647. components := []*apiv1.DashboardComponent{entityBeta, entityAlpha}
  648. out := orderTopLevelDashboardComponents(components, nil)
  649. require.Len(t, out, 2)
  650. assert.Equal(t, "Alpha", out[0].Title, "sortables ordered by title")
  651. assert.Equal(t, "Beta", out[1].Title)
  652. }
  653. // TestEventStreamACLNoLeakToUnauthorizedUser (GHSA-228v-wc5r-j8m7) asserts that EventStream
  654. // does not send execution events or output chunks to users who are not allowed to view that action's logs.
  655. func TestEventStreamACLNoLeakToUnauthorizedUser(t *testing.T) {
  656. cfg, lowUser, adminUser := buildViewPermissionTestConfig(t)
  657. ex := executor.DefaultExecutor(cfg)
  658. ex.RebuildActionMap()
  659. api := newServer(ex)
  660. binding := ex.FindBindingByID("secret_action")
  661. require.NotNil(t, binding, "secret_action binding must exist")
  662. clientLow, clientAdmin := addEventStreamTestClients(t, api, lowUser, adminUser)
  663. defer removeEventStreamTestClients(api, clientLow, clientAdmin)
  664. runEventStreamTestExecution(t, ex, cfg, binding, adminUser)
  665. adminEvents := drainEventStreamUntilFinished(clientAdmin.channel, 2*time.Second)
  666. lowEvents := drainEventStreamWithTimeout(clientLow.channel, 50*time.Millisecond)
  667. assertEventStreamLowUserReceivesNothing(t, lowEvents)
  668. assertEventStreamAdminReceivesSecretActionEvents(t, adminEvents)
  669. }
  670. func addEventStreamTestClients(t *testing.T, api *oliveTinAPI, lowUser, adminUser *authpublic.AuthenticatedUser) (*streamingClient, *streamingClient) {
  671. t.Helper()
  672. clientLow := &streamingClient{
  673. channel: make(chan *apiv1.EventStreamResponse, 20),
  674. AuthenticatedUser: lowUser,
  675. }
  676. clientAdmin := &streamingClient{
  677. channel: make(chan *apiv1.EventStreamResponse, 20),
  678. AuthenticatedUser: adminUser,
  679. }
  680. api.streamingClientsMutex.Lock()
  681. api.streamingClients[clientLow] = struct{}{}
  682. api.streamingClients[clientAdmin] = struct{}{}
  683. api.streamingClientsMutex.Unlock()
  684. return clientLow, clientAdmin
  685. }
  686. func removeEventStreamTestClients(api *oliveTinAPI, clientLow, clientAdmin *streamingClient) {
  687. api.streamingClientsMutex.Lock()
  688. delete(api.streamingClients, clientLow)
  689. delete(api.streamingClients, clientAdmin)
  690. api.streamingClientsMutex.Unlock()
  691. close(clientLow.channel)
  692. close(clientAdmin.channel)
  693. }
  694. func runEventStreamTestExecution(t *testing.T, ex *executor.Executor, cfg *config.Config, binding *executor.ActionBinding, adminUser *authpublic.AuthenticatedUser) {
  695. t.Helper()
  696. execReq := &executor.ExecutionRequest{
  697. Binding: binding,
  698. Arguments: map[string]string{},
  699. TrackingID: uuid.NewString(),
  700. Cfg: cfg,
  701. AuthenticatedUser: adminUser,
  702. }
  703. wg, _ := ex.ExecRequest(execReq)
  704. wg.Wait()
  705. }
  706. func drainEventStreamUntilFinished(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  707. var out []*apiv1.EventStreamResponse
  708. deadline := time.Now().Add(timeout)
  709. for time.Now().Before(deadline) {
  710. ev, finished := recvEventStreamOne(ch, 50*time.Millisecond)
  711. if ev != nil {
  712. out = append(out, ev)
  713. }
  714. if finished {
  715. return out
  716. }
  717. }
  718. return out
  719. }
  720. func recvEventStreamOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  721. select {
  722. case ev, ok := <-ch:
  723. if !ok {
  724. return nil, true
  725. }
  726. return ev, ev.GetExecutionFinished() != nil
  727. case <-time.After(timeout):
  728. return nil, true
  729. }
  730. }
  731. func eventStreamRecvResult(ev *apiv1.EventStreamResponse, ok bool) (*apiv1.EventStreamResponse, bool) {
  732. if !ok {
  733. return nil, true
  734. }
  735. return ev, false
  736. }
  737. func recvEventStreamWithTimeoutOne(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) (*apiv1.EventStreamResponse, bool) {
  738. select {
  739. case ev, ok := <-ch:
  740. return eventStreamRecvResult(ev, ok)
  741. case <-time.After(timeout):
  742. return nil, true
  743. }
  744. }
  745. func drainEventStreamWithTimeout(ch <-chan *apiv1.EventStreamResponse, timeout time.Duration) []*apiv1.EventStreamResponse {
  746. var out []*apiv1.EventStreamResponse
  747. for {
  748. ev, done := recvEventStreamWithTimeoutOne(ch, timeout)
  749. if done {
  750. return out
  751. }
  752. out = append(out, ev)
  753. }
  754. }
  755. func assertEventStreamLowUserReceivesNothing(t *testing.T, lowEvents []*apiv1.EventStreamResponse) {
  756. t.Helper()
  757. for _, ev := range lowEvents {
  758. assert.Nil(t, ev.GetExecutionStarted(), "low-privilege user must not receive ExecutionStarted")
  759. assert.Nil(t, ev.GetExecutionFinished(), "low-privilege user must not receive ExecutionFinished")
  760. assert.Nil(t, ev.GetOutputChunk(), "low-privilege user must not receive OutputChunk")
  761. }
  762. assert.Empty(t, lowEvents, "low-privilege user with Logs:false must not receive any execution events")
  763. }
  764. func assertEventStreamAdminReceivesSecretActionEvents(t *testing.T, adminEvents []*apiv1.EventStreamResponse) {
  765. t.Helper()
  766. var gotStarted, gotFinished bool
  767. for _, ev := range adminEvents {
  768. if ev.GetExecutionStarted() != nil {
  769. gotStarted = true
  770. assert.Equal(t, "secret_action", ev.GetExecutionStarted().LogEntry.GetBindingId())
  771. }
  772. if ev.GetExecutionFinished() != nil {
  773. gotFinished = true
  774. assert.Equal(t, "secret_action", ev.GetExecutionFinished().LogEntry.GetBindingId())
  775. }
  776. }
  777. assert.True(t, gotStarted, "admin must receive ExecutionStarted for secret_action")
  778. assert.True(t, gotFinished, "admin must receive ExecutionFinished for secret_action")
  779. }
  780. func TestExecutionStatusReturnsBackToDashboards(t *testing.T) {
  781. cfg := config.DefaultConfig()
  782. cfg.Actions = []*config.Action{
  783. {Title: "Dashboard Action", Shell: "echo ok"},
  784. }
  785. cfg.Dashboards = []*config.DashboardComponent{
  786. {
  787. Title: "Ops",
  788. Contents: []*config.DashboardComponent{
  789. {Title: "Dashboard Action"},
  790. },
  791. },
  792. }
  793. ex := executor.DefaultExecutor(cfg)
  794. ex.RebuildActionMap()
  795. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  796. require.NotNil(t, binding)
  797. _, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  798. startResp, err := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{
  799. BindingId: binding.ID,
  800. }))
  801. require.NoError(t, err)
  802. statusResp, err := client.ExecutionStatus(context.Background(), connect.NewRequest(&apiv1.ExecutionStatusRequest{
  803. ExecutionTrackingId: startResp.Msg.ExecutionTrackingId,
  804. }))
  805. require.NoError(t, err)
  806. require.NotNil(t, statusResp.Msg)
  807. require.Len(t, statusResp.Msg.BackToDashboards, 1)
  808. assert.Equal(t, "Ops", statusResp.Msg.BackToDashboards[0].Title)
  809. assert.Equal(t, "/dashboards/Ops", statusResp.Msg.BackToDashboards[0].Path)
  810. }
  811. func TestGetActionBindingReturnsBackToDashboards(t *testing.T) {
  812. cfg := config.DefaultConfig()
  813. cfg.Actions = []*config.Action{
  814. {Title: "Dashboard Action", Shell: "echo ok"},
  815. }
  816. cfg.Dashboards = []*config.DashboardComponent{
  817. {
  818. Title: "Ops",
  819. Contents: []*config.DashboardComponent{
  820. {Title: "Dashboard Action"},
  821. },
  822. },
  823. }
  824. ex := executor.DefaultExecutor(cfg)
  825. ex.RebuildActionMap()
  826. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  827. require.NotNil(t, binding)
  828. _, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  829. resp, err := client.GetActionBinding(context.Background(), connect.NewRequest(&apiv1.GetActionBindingRequest{
  830. BindingId: binding.ID,
  831. }))
  832. require.NoError(t, err)
  833. require.NotNil(t, resp.Msg)
  834. require.Len(t, resp.Msg.BackToDashboards, 1)
  835. assert.Equal(t, "Ops", resp.Msg.BackToDashboards[0].Title)
  836. assert.Equal(t, "/dashboards/Ops", resp.Msg.BackToDashboards[0].Path)
  837. }
  838. func TestBuildActionIncludesGroups(t *testing.T) {
  839. cfg := config.DefaultConfig()
  840. cfg.ActionGroups = map[string]*config.ActionGroup{
  841. "con2queue10": {MaxConcurrent: 2, QueueSize: 10},
  842. }
  843. cfg.Actions = []*config.Action{
  844. {Title: "Long running action", Shell: "sleep 1", Groups: []string{"con2queue10", "missing"}},
  845. }
  846. cfg.Sanitize()
  847. ex := executor.DefaultExecutor(cfg)
  848. ex.RebuildActionMap()
  849. binding := ex.FindBindingWithNoEntity(cfg.Actions[0])
  850. require.NotNil(t, binding)
  851. rr := &DashboardRenderRequest{cfg: cfg, ex: ex}
  852. actionResult := buildAction(binding, rr)
  853. require.Len(t, actionResult.Groups, 2)
  854. assert.Equal(t, "con2queue10", actionResult.Groups[0].Name)
  855. assert.Equal(t, int32(2), actionResult.Groups[0].MaxConcurrent)
  856. assert.Equal(t, int32(10), actionResult.Groups[0].QueueSize)
  857. assert.Equal(t, "missing", actionResult.Groups[1].Name)
  858. assert.Equal(t, int32(0), actionResult.Groups[1].MaxConcurrent)
  859. }
  860. func TestBuildChoicesExpandsChecklistEntityChoices(t *testing.T) {
  861. entities.AddEntity("room", "0", map[string]any{"hostname": "attic"})
  862. entities.AddEntity("room", "1", map[string]any{"hostname": "basement"})
  863. t.Cleanup(func() {
  864. entities.ClearEntitiesOfType("room")
  865. })
  866. arg := config.ActionArgument{
  867. Type: "checklist",
  868. Entity: "room",
  869. Choices: []config.ActionArgumentChoice{
  870. {Title: "{{ room.hostname }}", Value: "{{ room.hostname }}"},
  871. },
  872. }
  873. choices := buildChoices(arg)
  874. require.Len(t, choices, 2)
  875. assert.Equal(t, "attic", choices[0].Value)
  876. assert.Equal(t, "attic", choices[0].Title)
  877. assert.Equal(t, "basement", choices[1].Value)
  878. assert.Equal(t, "basement", choices[1].Title)
  879. }