middleware_test.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. h := &Handler{
  65. auth: tc.auth,
  66. }
  67. req := httptest.NewRequest("GET", "/foo", nil) // chi routing is prepared in test setup
  68. req = req.WithContext(tc.ctx)
  69. w := httptest.NewRecorder()
  70. h.requireAPIEnabled(tc.next)(w, req)
  71. res := w.Result()
  72. assert.Equals(t, tc.statusCode, res.StatusCode)
  73. body, err := io.ReadAll(res.Body)
  74. res.Body.Close()
  75. assert.FatalError(t, err)
  76. if res.StatusCode >= 400 {
  77. err := admin.Error{}
  78. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  79. assert.Equals(t, tc.err.Type, err.Type)
  80. assert.Equals(t, tc.err.Message, err.Message)
  81. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  82. assert.Equals(t, tc.err.Detail, err.Detail)
  83. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  84. return
  85. }
  86. // nothing to test when the requireAPIEnabled middleware succeeds, currently
  87. })
  88. }
  89. }
  90. func TestHandler_extractAuthorizeTokenAdmin(t *testing.T) {
  91. type test struct {
  92. ctx context.Context
  93. auth adminAuthority
  94. req *http.Request
  95. next nextHTTP
  96. err *admin.Error
  97. statusCode int
  98. }
  99. var tests = map[string]func(t *testing.T) test{
  100. "fail/missing-authorization-token": func(t *testing.T) test {
  101. req := httptest.NewRequest("GET", "/foo", nil)
  102. req.Header["Authorization"] = []string{""}
  103. return test{
  104. ctx: context.Background(),
  105. req: req,
  106. statusCode: 401,
  107. err: &admin.Error{
  108. Type: admin.ErrorUnauthorizedType.String(),
  109. Status: 401,
  110. Detail: "unauthorized",
  111. Message: "missing authorization header token",
  112. },
  113. }
  114. },
  115. "fail/auth.AuthorizeAdminToken": func(t *testing.T) test {
  116. req := httptest.NewRequest("GET", "/foo", nil)
  117. req.Header["Authorization"] = []string{"token"}
  118. auth := &mockAdminAuthority{
  119. MockAuthorizeAdminToken: func(r *http.Request, token string) (*linkedca.Admin, error) {
  120. assert.Equals(t, "token", token)
  121. return nil, admin.NewError(
  122. admin.ErrorUnauthorizedType,
  123. "not authorized",
  124. )
  125. },
  126. }
  127. return test{
  128. ctx: context.Background(),
  129. auth: auth,
  130. req: req,
  131. statusCode: 401,
  132. err: &admin.Error{
  133. Type: admin.ErrorUnauthorizedType.String(),
  134. Status: 401,
  135. Detail: "unauthorized",
  136. Message: "not authorized",
  137. },
  138. }
  139. },
  140. "ok": func(t *testing.T) test {
  141. req := httptest.NewRequest("GET", "/foo", nil)
  142. req.Header["Authorization"] = []string{"token"}
  143. createdAt := time.Now()
  144. var deletedAt time.Time
  145. admin := &linkedca.Admin{
  146. Id: "adminID",
  147. AuthorityId: "authorityID",
  148. Subject: "admin",
  149. ProvisionerId: "provID",
  150. Type: linkedca.Admin_SUPER_ADMIN,
  151. CreatedAt: timestamppb.New(createdAt),
  152. DeletedAt: timestamppb.New(deletedAt),
  153. }
  154. auth := &mockAdminAuthority{
  155. MockAuthorizeAdminToken: func(r *http.Request, token string) (*linkedca.Admin, error) {
  156. assert.Equals(t, "token", token)
  157. return admin, nil
  158. },
  159. }
  160. next := func(w http.ResponseWriter, r *http.Request) {
  161. ctx := r.Context()
  162. a := ctx.Value(adminContextKey) // verifying that the context now has a linkedca.Admin
  163. adm, ok := a.(*linkedca.Admin)
  164. if !ok {
  165. t.Errorf("expected *linkedca.Admin; got %T", a)
  166. return
  167. }
  168. opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.Admin{}, timestamppb.Timestamp{})}
  169. if !cmp.Equal(admin, adm, opts...) {
  170. t.Errorf("linkedca.Admin diff =\n%s", cmp.Diff(admin, adm, opts...))
  171. }
  172. w.Write(nil) // mock response with status 200
  173. }
  174. return test{
  175. ctx: context.Background(),
  176. auth: auth,
  177. req: req,
  178. next: next,
  179. statusCode: 200,
  180. err: nil,
  181. }
  182. },
  183. }
  184. for name, prep := range tests {
  185. tc := prep(t)
  186. t.Run(name, func(t *testing.T) {
  187. h := &Handler{
  188. auth: tc.auth,
  189. }
  190. req := tc.req.WithContext(tc.ctx)
  191. w := httptest.NewRecorder()
  192. h.extractAuthorizeTokenAdmin(tc.next)(w, req)
  193. res := w.Result()
  194. assert.Equals(t, tc.statusCode, res.StatusCode)
  195. body, err := io.ReadAll(res.Body)
  196. res.Body.Close()
  197. assert.FatalError(t, err)
  198. if res.StatusCode >= 400 {
  199. err := admin.Error{}
  200. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  201. assert.Equals(t, tc.err.Type, err.Type)
  202. assert.Equals(t, tc.err.Message, err.Message)
  203. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  204. assert.Equals(t, tc.err.Detail, err.Detail)
  205. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  206. return
  207. }
  208. })
  209. }
  210. }