middleware_test.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "io"
  7. "net/http"
  8. "net/http/httptest"
  9. "testing"
  10. "time"
  11. "github.com/google/go-cmp/cmp"
  12. "github.com/google/go-cmp/cmp/cmpopts"
  13. "github.com/smallstep/assert"
  14. "github.com/smallstep/certificates/authority/admin"
  15. "go.step.sm/linkedca"
  16. "google.golang.org/protobuf/types/known/timestamppb"
  17. )
  18. func TestHandler_requireAPIEnabled(t *testing.T) {
  19. type test struct {
  20. ctx context.Context
  21. auth adminAuthority
  22. next nextHTTP
  23. err *admin.Error
  24. statusCode int
  25. }
  26. var tests = map[string]func(t *testing.T) test{
  27. "fail/auth.IsAdminAPIEnabled": func(t *testing.T) test {
  28. return test{
  29. ctx: context.Background(),
  30. auth: &mockAdminAuthority{
  31. MockIsAdminAPIEnabled: func() bool {
  32. return false
  33. },
  34. },
  35. err: &admin.Error{
  36. Type: admin.ErrorNotImplementedType.String(),
  37. Status: 501,
  38. Detail: "not implemented",
  39. Message: "administration API not enabled",
  40. },
  41. statusCode: 501,
  42. }
  43. },
  44. "ok": func(t *testing.T) test {
  45. auth := &mockAdminAuthority{
  46. MockIsAdminAPIEnabled: func() bool {
  47. return true
  48. },
  49. }
  50. next := func(w http.ResponseWriter, r *http.Request) {
  51. w.Write(nil) // mock response with status 200
  52. }
  53. return test{
  54. ctx: context.Background(),
  55. auth: auth,
  56. next: next,
  57. statusCode: 200,
  58. }
  59. },
  60. }
  61. for name, prep := range tests {
  62. tc := prep(t)
  63. t.Run(name, func(t *testing.T) {
  64. mockMustAuthority(t, tc.auth)
  65. req := httptest.NewRequest("GET", "/foo", nil) // chi routing is prepared in test setup
  66. req = req.WithContext(tc.ctx)
  67. w := httptest.NewRecorder()
  68. requireAPIEnabled(tc.next)(w, req)
  69. res := w.Result()
  70. assert.Equals(t, tc.statusCode, res.StatusCode)
  71. body, err := io.ReadAll(res.Body)
  72. res.Body.Close()
  73. assert.FatalError(t, err)
  74. if res.StatusCode >= 400 {
  75. err := admin.Error{}
  76. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  77. assert.Equals(t, tc.err.Type, err.Type)
  78. assert.Equals(t, tc.err.Message, err.Message)
  79. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  80. assert.Equals(t, tc.err.Detail, err.Detail)
  81. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  82. return
  83. }
  84. // nothing to test when the requireAPIEnabled middleware succeeds, currently
  85. })
  86. }
  87. }
  88. func TestHandler_extractAuthorizeTokenAdmin(t *testing.T) {
  89. type test struct {
  90. ctx context.Context
  91. auth adminAuthority
  92. req *http.Request
  93. next nextHTTP
  94. err *admin.Error
  95. statusCode int
  96. }
  97. var tests = map[string]func(t *testing.T) test{
  98. "fail/missing-authorization-token": func(t *testing.T) test {
  99. req := httptest.NewRequest("GET", "/foo", nil)
  100. req.Header["Authorization"] = []string{""}
  101. return test{
  102. ctx: context.Background(),
  103. req: req,
  104. statusCode: 401,
  105. err: &admin.Error{
  106. Type: admin.ErrorUnauthorizedType.String(),
  107. Status: 401,
  108. Detail: "unauthorized",
  109. Message: "missing authorization header token",
  110. },
  111. }
  112. },
  113. "fail/auth.AuthorizeAdminToken": func(t *testing.T) test {
  114. req := httptest.NewRequest("GET", "/foo", nil)
  115. req.Header["Authorization"] = []string{"token"}
  116. auth := &mockAdminAuthority{
  117. MockAuthorizeAdminToken: func(r *http.Request, token string) (*linkedca.Admin, error) {
  118. assert.Equals(t, "token", token)
  119. return nil, admin.NewError(
  120. admin.ErrorUnauthorizedType,
  121. "not authorized",
  122. )
  123. },
  124. }
  125. return test{
  126. ctx: context.Background(),
  127. auth: auth,
  128. req: req,
  129. statusCode: 401,
  130. err: &admin.Error{
  131. Type: admin.ErrorUnauthorizedType.String(),
  132. Status: 401,
  133. Detail: "unauthorized",
  134. Message: "not authorized",
  135. },
  136. }
  137. },
  138. "ok": func(t *testing.T) test {
  139. req := httptest.NewRequest("GET", "/foo", nil)
  140. req.Header["Authorization"] = []string{"token"}
  141. createdAt := time.Now()
  142. var deletedAt time.Time
  143. admin := &linkedca.Admin{
  144. Id: "adminID",
  145. AuthorityId: "authorityID",
  146. Subject: "admin",
  147. ProvisionerId: "provID",
  148. Type: linkedca.Admin_SUPER_ADMIN,
  149. CreatedAt: timestamppb.New(createdAt),
  150. DeletedAt: timestamppb.New(deletedAt),
  151. }
  152. auth := &mockAdminAuthority{
  153. MockAuthorizeAdminToken: func(r *http.Request, token string) (*linkedca.Admin, error) {
  154. assert.Equals(t, "token", token)
  155. return admin, nil
  156. },
  157. }
  158. next := func(w http.ResponseWriter, r *http.Request) {
  159. ctx := r.Context()
  160. a := ctx.Value(adminContextKey) // verifying that the context now has a linkedca.Admin
  161. adm, ok := a.(*linkedca.Admin)
  162. if !ok {
  163. t.Errorf("expected *linkedca.Admin; got %T", a)
  164. return
  165. }
  166. opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.Admin{}, timestamppb.Timestamp{})}
  167. if !cmp.Equal(admin, adm, opts...) {
  168. t.Errorf("linkedca.Admin diff =\n%s", cmp.Diff(admin, adm, opts...))
  169. }
  170. w.Write(nil) // mock response with status 200
  171. }
  172. return test{
  173. ctx: context.Background(),
  174. auth: auth,
  175. req: req,
  176. next: next,
  177. statusCode: 200,
  178. err: nil,
  179. }
  180. },
  181. }
  182. for name, prep := range tests {
  183. tc := prep(t)
  184. t.Run(name, func(t *testing.T) {
  185. mockMustAuthority(t, tc.auth)
  186. req := tc.req.WithContext(tc.ctx)
  187. w := httptest.NewRecorder()
  188. extractAuthorizeTokenAdmin(tc.next)(w, req)
  189. res := w.Result()
  190. assert.Equals(t, tc.statusCode, res.StatusCode)
  191. body, err := io.ReadAll(res.Body)
  192. res.Body.Close()
  193. assert.FatalError(t, err)
  194. if res.StatusCode >= 400 {
  195. err := admin.Error{}
  196. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  197. assert.Equals(t, tc.err.Type, err.Type)
  198. assert.Equals(t, tc.err.Message, err.Message)
  199. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  200. assert.Equals(t, tc.err.Detail, err.Detail)
  201. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  202. return
  203. }
  204. })
  205. }
  206. }