api_login_gate_test.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. package api
  2. import (
  3. "context"
  4. "net/http"
  5. "testing"
  6. "connectrpc.com/connect"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/stretchr/testify/require"
  9. "google.golang.org/protobuf/reflect/protoreflect"
  10. "google.golang.org/protobuf/types/known/emptypb"
  11. apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1"
  12. config "github.com/OliveTin/OliveTin/internal/config"
  13. "github.com/OliveTin/OliveTin/internal/executor"
  14. )
  15. // The procedures that unauthenticated visitors may call when login is required.
  16. // This list is deliberately kept separate from loginNotRequiredProcedures, so
  17. // that making a procedure public needs both to be changed on purpose.
  18. var expectedPublicProcedures = []string{
  19. "Init",
  20. "GetReadyz",
  21. "LocalUserLogin",
  22. "Logout",
  23. "PasswordHash",
  24. }
  25. // loginRequiredGuestAclConfig is the configuration from GHSA-9q82-wjpr-32jm:
  26. // login is required, and an ACL that matches the "guest" usergroup grants
  27. // every permission on the action.
  28. func loginRequiredGuestAclConfig() *config.Config {
  29. cfg := config.DefaultConfig()
  30. cfg.AuthRequireGuestsToLogin = true
  31. cfg.AccessControlLists = []*config.AccessControlList{
  32. {
  33. Name: "basic-users",
  34. MatchUsergroups: []string{"guest"},
  35. Permissions: config.PermissionsList{View: true, Exec: true, Logs: true, Kill: true},
  36. },
  37. }
  38. cfg.Actions = append(cfg.Actions, &config.Action{
  39. ID: "restart_web_server",
  40. Title: "Restart Web Server",
  41. Shell: "echo restarted",
  42. Acls: []string{"basic-users"},
  43. })
  44. cfg.Sanitize()
  45. return cfg
  46. }
  47. func oliveTinServiceDescriptor() protoreflect.ServiceDescriptor {
  48. return apiv1.File_olivetin_api_v1_olivetin_proto.Services().ByName("OliveTinApiService")
  49. }
  50. func procedureForMethod(method protoreflect.MethodDescriptor) string {
  51. return "/" + string(method.Parent().FullName()) + "/" + string(method.Name())
  52. }
  53. // callAsGuest calls any procedure with an empty message and no credentials.
  54. // An empty protobuf message is valid for every request type.
  55. func callAsGuest(baseURL string, method protoreflect.MethodDescriptor) error {
  56. client := connect.NewClient[emptypb.Empty, emptypb.Empty](http.DefaultClient, baseURL+"/api/"+string(method.Name()))
  57. if !method.IsStreamingServer() {
  58. _, err := client.CallUnary(context.Background(), connect.NewRequest(&emptypb.Empty{}))
  59. return err
  60. }
  61. stream, err := client.CallServerStream(context.Background(), connect.NewRequest(&emptypb.Empty{}))
  62. if err != nil {
  63. return err
  64. }
  65. received := stream.Receive()
  66. closeErr := stream.Close()
  67. if received {
  68. return closeErr
  69. }
  70. return stream.Err()
  71. }
  72. func TestPublicProcedureListsMatch(t *testing.T) {
  73. expected := make(map[string]bool)
  74. for _, name := range expectedPublicProcedures {
  75. method := oliveTinServiceDescriptor().Methods().ByName(protoreflect.Name(name))
  76. require.NotNil(t, method, "public procedure %s does not exist in the proto service", name)
  77. expected[procedureForMethod(method)] = true
  78. }
  79. assert.Equal(t, expected, loginNotRequiredProcedures)
  80. }
  81. // TestEveryProcedureRequiresLoginUnlessPublic (GHSA-9q82-wjpr-32jm) calls every
  82. // procedure in the proto service as an unauthenticated visitor, so a procedure
  83. // added later is covered without anyone having to remember to add a test.
  84. func TestEveryProcedureRequiresLoginUnlessPublic(t *testing.T) {
  85. cfg := loginRequiredGuestAclConfig()
  86. ts, _ := getNewTestServerAndClient(cfg)
  87. defer ts.Close()
  88. methods := oliveTinServiceDescriptor().Methods()
  89. require.Positive(t, methods.Len())
  90. for i := 0; i < methods.Len(); i++ {
  91. method := methods.Get(i)
  92. t.Run(string(method.Name()), func(t *testing.T) {
  93. err := callAsGuest(ts.URL, method)
  94. if loginNotRequiredProcedures[procedureForMethod(method)] {
  95. assert.NotEqual(t, connect.CodePermissionDenied, connect.CodeOf(err), "public procedure must be callable without logging in")
  96. return
  97. }
  98. require.Error(t, err)
  99. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err), "procedure must refuse unauthenticated visitors when login is required")
  100. })
  101. }
  102. }
  103. func TestGuestCannotStartActionsWhenLoginRequired(t *testing.T) {
  104. cfg := loginRequiredGuestAclConfig()
  105. ex := executor.DefaultExecutor(cfg)
  106. ex.RebuildActionMap()
  107. ts, client := getNewTestServerAndClientWithExecutor(cfg, ex)
  108. defer ts.Close()
  109. _, err := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{BindingId: "restart_web_server"}))
  110. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
  111. _, err = client.StartActionAndWait(context.Background(), connect.NewRequest(&apiv1.StartActionAndWaitRequest{ActionId: "restart_web_server"}))
  112. assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
  113. binding := ex.FindBindingByID("restart_web_server")
  114. require.NotNil(t, binding)
  115. assert.Empty(t, ex.GetLogsByBindingId(binding.ID), "the action must not have been requested at all")
  116. }
  117. // Real and made-up action IDs must get the same answer, so that unauthenticated
  118. // visitors cannot find out which actions exist.
  119. func TestGuestCannotTellRealActionIdsFromFakeOnes(t *testing.T) {
  120. cfg := loginRequiredGuestAclConfig()
  121. ts, client := getNewTestServerAndClient(cfg)
  122. defer ts.Close()
  123. _, realErr := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{BindingId: "restart_web_server"}))
  124. _, fakeErr := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{BindingId: "does_not_exist_1234"}))
  125. require.Error(t, realErr)
  126. require.Error(t, fakeErr)
  127. assert.Equal(t, connect.CodeOf(realErr), connect.CodeOf(fakeErr))
  128. assert.Equal(t, realErr.Error(), fakeErr.Error())
  129. }
  130. func TestGuestCanStillStartActionsWhenLoginNotRequired(t *testing.T) {
  131. cfg := loginRequiredGuestAclConfig()
  132. cfg.AuthRequireGuestsToLogin = false
  133. ts, client := getNewTestServerAndClient(cfg)
  134. defer ts.Close()
  135. res, err := client.StartActionAndWait(context.Background(), connect.NewRequest(&apiv1.StartActionAndWaitRequest{ActionId: "restart_web_server"}))
  136. require.NoError(t, err)
  137. assert.Contains(t, res.Msg.LogEntry.Output, "restarted")
  138. }