middleware_test.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "io"
  8. "net/http"
  9. "net/http/httptest"
  10. "testing"
  11. "time"
  12. "github.com/go-chi/chi"
  13. "github.com/google/go-cmp/cmp"
  14. "github.com/google/go-cmp/cmp/cmpopts"
  15. "google.golang.org/protobuf/types/known/timestamppb"
  16. "go.step.sm/linkedca"
  17. "github.com/smallstep/assert"
  18. "github.com/smallstep/certificates/authority/admin"
  19. "github.com/smallstep/certificates/authority/provisioner"
  20. )
  21. func TestHandler_requireAPIEnabled(t *testing.T) {
  22. type test struct {
  23. ctx context.Context
  24. auth adminAuthority
  25. next http.HandlerFunc
  26. err *admin.Error
  27. statusCode int
  28. }
  29. var tests = map[string]func(t *testing.T) test{
  30. "fail/auth.IsAdminAPIEnabled": func(t *testing.T) test {
  31. return test{
  32. ctx: context.Background(),
  33. auth: &mockAdminAuthority{
  34. MockIsAdminAPIEnabled: func() bool {
  35. return false
  36. },
  37. },
  38. err: &admin.Error{
  39. Type: admin.ErrorNotImplementedType.String(),
  40. Status: 501,
  41. Detail: "not implemented",
  42. Message: "administration API not enabled",
  43. },
  44. statusCode: 501,
  45. }
  46. },
  47. "ok": func(t *testing.T) test {
  48. auth := &mockAdminAuthority{
  49. MockIsAdminAPIEnabled: func() bool {
  50. return true
  51. },
  52. }
  53. next := func(w http.ResponseWriter, r *http.Request) {
  54. w.Write(nil) // mock response with status 200
  55. }
  56. return test{
  57. ctx: context.Background(),
  58. auth: auth,
  59. next: next,
  60. statusCode: 200,
  61. }
  62. },
  63. }
  64. for name, prep := range tests {
  65. tc := prep(t)
  66. t.Run(name, func(t *testing.T) {
  67. h := &Handler{
  68. auth: tc.auth,
  69. }
  70. req := httptest.NewRequest("GET", "/foo", nil) // chi routing is prepared in test setup
  71. req = req.WithContext(tc.ctx)
  72. w := httptest.NewRecorder()
  73. h.requireAPIEnabled(tc.next)(w, req)
  74. res := w.Result()
  75. assert.Equals(t, tc.statusCode, res.StatusCode)
  76. body, err := io.ReadAll(res.Body)
  77. res.Body.Close()
  78. assert.FatalError(t, err)
  79. if res.StatusCode >= 400 {
  80. err := admin.Error{}
  81. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  82. assert.Equals(t, tc.err.Type, err.Type)
  83. assert.Equals(t, tc.err.Message, err.Message)
  84. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  85. assert.Equals(t, tc.err.Detail, err.Detail)
  86. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  87. return
  88. }
  89. // nothing to test when the requireAPIEnabled middleware succeeds, currently
  90. })
  91. }
  92. }
  93. func TestHandler_extractAuthorizeTokenAdmin(t *testing.T) {
  94. type test struct {
  95. ctx context.Context
  96. auth adminAuthority
  97. req *http.Request
  98. next http.HandlerFunc
  99. err *admin.Error
  100. statusCode int
  101. }
  102. var tests = map[string]func(t *testing.T) test{
  103. "fail/missing-authorization-token": func(t *testing.T) test {
  104. req := httptest.NewRequest("GET", "/foo", nil)
  105. req.Header["Authorization"] = []string{""}
  106. return test{
  107. ctx: context.Background(),
  108. req: req,
  109. statusCode: 401,
  110. err: &admin.Error{
  111. Type: admin.ErrorUnauthorizedType.String(),
  112. Status: 401,
  113. Detail: "unauthorized",
  114. Message: "missing authorization header token",
  115. },
  116. }
  117. },
  118. "fail/auth.AuthorizeAdminToken": func(t *testing.T) test {
  119. req := httptest.NewRequest("GET", "/foo", nil)
  120. req.Header["Authorization"] = []string{"token"}
  121. auth := &mockAdminAuthority{
  122. MockAuthorizeAdminToken: func(r *http.Request, token string) (*linkedca.Admin, error) {
  123. assert.Equals(t, "token", token)
  124. return nil, admin.NewError(
  125. admin.ErrorUnauthorizedType,
  126. "not authorized",
  127. )
  128. },
  129. }
  130. return test{
  131. ctx: context.Background(),
  132. auth: auth,
  133. req: req,
  134. statusCode: 401,
  135. err: &admin.Error{
  136. Type: admin.ErrorUnauthorizedType.String(),
  137. Status: 401,
  138. Detail: "unauthorized",
  139. Message: "not authorized",
  140. },
  141. }
  142. },
  143. "ok": func(t *testing.T) test {
  144. req := httptest.NewRequest("GET", "/foo", nil)
  145. req.Header["Authorization"] = []string{"token"}
  146. createdAt := time.Now()
  147. var deletedAt time.Time
  148. adm := &linkedca.Admin{
  149. Id: "adminID",
  150. AuthorityId: "authorityID",
  151. Subject: "admin",
  152. ProvisionerId: "provID",
  153. Type: linkedca.Admin_SUPER_ADMIN,
  154. CreatedAt: timestamppb.New(createdAt),
  155. DeletedAt: timestamppb.New(deletedAt),
  156. }
  157. auth := &mockAdminAuthority{
  158. MockAuthorizeAdminToken: func(r *http.Request, token string) (*linkedca.Admin, error) {
  159. assert.Equals(t, "token", token)
  160. return adm, nil
  161. },
  162. }
  163. next := func(w http.ResponseWriter, r *http.Request) {
  164. ctx := r.Context()
  165. adm := linkedca.AdminFromContext(ctx) // verifying that the context now has a linkedca.Admin
  166. opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.Admin{}, timestamppb.Timestamp{})}
  167. if !cmp.Equal(adm, adm, opts...) {
  168. t.Errorf("linkedca.Admin diff =\n%s", cmp.Diff(adm, 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. h := &Handler{
  186. auth: tc.auth,
  187. }
  188. req := tc.req.WithContext(tc.ctx)
  189. w := httptest.NewRecorder()
  190. h.extractAuthorizeTokenAdmin(tc.next)(w, req)
  191. res := w.Result()
  192. assert.Equals(t, tc.statusCode, res.StatusCode)
  193. body, err := io.ReadAll(res.Body)
  194. res.Body.Close()
  195. assert.FatalError(t, err)
  196. if res.StatusCode >= 400 {
  197. err := admin.Error{}
  198. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  199. assert.Equals(t, tc.err.Type, err.Type)
  200. assert.Equals(t, tc.err.Message, err.Message)
  201. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  202. assert.Equals(t, tc.err.Detail, err.Detail)
  203. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  204. return
  205. }
  206. })
  207. }
  208. }
  209. func TestHandler_loadProvisionerByName(t *testing.T) {
  210. type test struct {
  211. adminDB admin.DB
  212. auth adminAuthority
  213. ctx context.Context
  214. next http.HandlerFunc
  215. err *admin.Error
  216. statusCode int
  217. }
  218. var tests = map[string]func(t *testing.T) test{
  219. "fail/auth.LoadProvisionerByName": func(t *testing.T) test {
  220. chiCtx := chi.NewRouteContext()
  221. chiCtx.URLParams.Add("provisionerName", "provName")
  222. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  223. auth := &mockAdminAuthority{
  224. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  225. assert.Equals(t, "provName", name)
  226. return nil, errors.New("force")
  227. },
  228. }
  229. err := admin.WrapErrorISE(errors.New("force"), "error loading provisioner provName")
  230. err.Message = "error loading provisioner provName: force"
  231. return test{
  232. ctx: ctx,
  233. auth: auth,
  234. statusCode: 500,
  235. err: err,
  236. }
  237. },
  238. "fail/db.GetProvisioner": func(t *testing.T) test {
  239. chiCtx := chi.NewRouteContext()
  240. chiCtx.URLParams.Add("provisionerName", "provName")
  241. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  242. auth := &mockAdminAuthority{
  243. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  244. assert.Equals(t, "provName", name)
  245. return &provisioner.MockProvisioner{
  246. MgetID: func() string {
  247. return "provID"
  248. },
  249. }, nil
  250. },
  251. }
  252. db := &admin.MockDB{
  253. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  254. assert.Equals(t, "provID", id)
  255. return nil, errors.New("force")
  256. },
  257. }
  258. err := admin.WrapErrorISE(errors.New("force"), "error retrieving provisioner provName")
  259. err.Message = "error retrieving provisioner provName: force"
  260. return test{
  261. ctx: ctx,
  262. auth: auth,
  263. adminDB: db,
  264. statusCode: 500,
  265. err: err,
  266. }
  267. },
  268. "ok": func(t *testing.T) test {
  269. chiCtx := chi.NewRouteContext()
  270. chiCtx.URLParams.Add("provisionerName", "provName")
  271. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  272. auth := &mockAdminAuthority{
  273. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  274. assert.Equals(t, "provName", name)
  275. return &provisioner.MockProvisioner{
  276. MgetID: func() string {
  277. return "provID"
  278. },
  279. }, nil
  280. },
  281. }
  282. db := &admin.MockDB{
  283. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  284. assert.Equals(t, "provID", id)
  285. return &linkedca.Provisioner{
  286. Id: "provID",
  287. Name: "provName",
  288. }, nil
  289. },
  290. }
  291. return test{
  292. ctx: ctx,
  293. auth: auth,
  294. adminDB: db,
  295. statusCode: 200,
  296. next: func(w http.ResponseWriter, r *http.Request) {
  297. prov := linkedca.ProvisionerFromContext(r.Context())
  298. assert.NotNil(t, prov)
  299. assert.Equals(t, "provID", prov.GetId())
  300. assert.Equals(t, "provName", prov.GetName())
  301. w.Write(nil) // mock response with status 200
  302. },
  303. }
  304. },
  305. }
  306. for name, prep := range tests {
  307. tc := prep(t)
  308. t.Run(name, func(t *testing.T) {
  309. h := &Handler{
  310. auth: tc.auth,
  311. adminDB: tc.adminDB,
  312. }
  313. req := httptest.NewRequest("GET", "/foo", nil) // chi routing is prepared in test setup
  314. req = req.WithContext(tc.ctx)
  315. w := httptest.NewRecorder()
  316. h.loadProvisionerByName(tc.next)(w, req)
  317. res := w.Result()
  318. assert.Equals(t, tc.statusCode, res.StatusCode)
  319. body, err := io.ReadAll(res.Body)
  320. res.Body.Close()
  321. assert.FatalError(t, err)
  322. if res.StatusCode >= 400 {
  323. err := admin.Error{}
  324. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  325. assert.Equals(t, tc.err.Type, err.Type)
  326. assert.Equals(t, tc.err.Message, err.Message)
  327. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  328. assert.Equals(t, tc.err.Detail, err.Detail)
  329. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  330. return
  331. }
  332. })
  333. }
  334. }