middleware_test.go 6.0 KB

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