middleware_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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/admin/db/nosql"
  20. "github.com/smallstep/certificates/authority/provisioner"
  21. )
  22. func TestHandler_requireAPIEnabled(t *testing.T) {
  23. type test struct {
  24. ctx context.Context
  25. auth adminAuthority
  26. next http.HandlerFunc
  27. err *admin.Error
  28. statusCode int
  29. }
  30. var tests = map[string]func(t *testing.T) test{
  31. "fail/auth.IsAdminAPIEnabled": func(t *testing.T) test {
  32. return test{
  33. ctx: context.Background(),
  34. auth: &mockAdminAuthority{
  35. MockIsAdminAPIEnabled: func() bool {
  36. return false
  37. },
  38. },
  39. err: &admin.Error{
  40. Type: admin.ErrorNotImplementedType.String(),
  41. Status: 501,
  42. Detail: "not implemented",
  43. Message: "administration API not enabled",
  44. },
  45. statusCode: 501,
  46. }
  47. },
  48. "ok": func(t *testing.T) test {
  49. auth := &mockAdminAuthority{
  50. MockIsAdminAPIEnabled: func() bool {
  51. return true
  52. },
  53. }
  54. next := func(w http.ResponseWriter, r *http.Request) {
  55. w.Write(nil) // mock response with status 200
  56. }
  57. return test{
  58. ctx: context.Background(),
  59. auth: auth,
  60. next: next,
  61. statusCode: 200,
  62. }
  63. },
  64. }
  65. for name, prep := range tests {
  66. tc := prep(t)
  67. t.Run(name, func(t *testing.T) {
  68. h := &Handler{
  69. auth: tc.auth,
  70. }
  71. req := httptest.NewRequest("GET", "/foo", nil) // chi routing is prepared in test setup
  72. req = req.WithContext(tc.ctx)
  73. w := httptest.NewRecorder()
  74. h.requireAPIEnabled(tc.next)(w, req)
  75. res := w.Result()
  76. assert.Equals(t, tc.statusCode, res.StatusCode)
  77. body, err := io.ReadAll(res.Body)
  78. res.Body.Close()
  79. assert.FatalError(t, err)
  80. if res.StatusCode >= 400 {
  81. err := admin.Error{}
  82. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  83. assert.Equals(t, tc.err.Type, err.Type)
  84. assert.Equals(t, tc.err.Message, err.Message)
  85. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  86. assert.Equals(t, tc.err.Detail, err.Detail)
  87. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  88. return
  89. }
  90. // nothing to test when the requireAPIEnabled middleware succeeds, currently
  91. })
  92. }
  93. }
  94. func TestHandler_extractAuthorizeTokenAdmin(t *testing.T) {
  95. type test struct {
  96. ctx context.Context
  97. auth adminAuthority
  98. req *http.Request
  99. next http.HandlerFunc
  100. err *admin.Error
  101. statusCode int
  102. }
  103. var tests = map[string]func(t *testing.T) test{
  104. "fail/missing-authorization-token": func(t *testing.T) test {
  105. req := httptest.NewRequest("GET", "/foo", nil)
  106. req.Header["Authorization"] = []string{""}
  107. return test{
  108. ctx: context.Background(),
  109. req: req,
  110. statusCode: 401,
  111. err: &admin.Error{
  112. Type: admin.ErrorUnauthorizedType.String(),
  113. Status: 401,
  114. Detail: "unauthorized",
  115. Message: "missing authorization header token",
  116. },
  117. }
  118. },
  119. "fail/auth.AuthorizeAdminToken": func(t *testing.T) test {
  120. req := httptest.NewRequest("GET", "/foo", nil)
  121. req.Header["Authorization"] = []string{"token"}
  122. auth := &mockAdminAuthority{
  123. MockAuthorizeAdminToken: func(r *http.Request, token string) (*linkedca.Admin, error) {
  124. assert.Equals(t, "token", token)
  125. return nil, admin.NewError(
  126. admin.ErrorUnauthorizedType,
  127. "not authorized",
  128. )
  129. },
  130. }
  131. return test{
  132. ctx: context.Background(),
  133. auth: auth,
  134. req: req,
  135. statusCode: 401,
  136. err: &admin.Error{
  137. Type: admin.ErrorUnauthorizedType.String(),
  138. Status: 401,
  139. Detail: "unauthorized",
  140. Message: "not authorized",
  141. },
  142. }
  143. },
  144. "ok": func(t *testing.T) test {
  145. req := httptest.NewRequest("GET", "/foo", nil)
  146. req.Header["Authorization"] = []string{"token"}
  147. createdAt := time.Now()
  148. var deletedAt time.Time
  149. adm := &linkedca.Admin{
  150. Id: "adminID",
  151. AuthorityId: "authorityID",
  152. Subject: "admin",
  153. ProvisionerId: "provID",
  154. Type: linkedca.Admin_SUPER_ADMIN,
  155. CreatedAt: timestamppb.New(createdAt),
  156. DeletedAt: timestamppb.New(deletedAt),
  157. }
  158. auth := &mockAdminAuthority{
  159. MockAuthorizeAdminToken: func(r *http.Request, token string) (*linkedca.Admin, error) {
  160. assert.Equals(t, "token", token)
  161. return adm, nil
  162. },
  163. }
  164. next := func(w http.ResponseWriter, r *http.Request) {
  165. ctx := r.Context()
  166. adm := linkedca.AdminFromContext(ctx) // verifying that the context now has a linkedca.Admin
  167. opts := []cmp.Option{cmpopts.IgnoreUnexported(linkedca.Admin{}, timestamppb.Timestamp{})}
  168. if !cmp.Equal(adm, adm, opts...) {
  169. t.Errorf("linkedca.Admin diff =\n%s", cmp.Diff(adm, adm, opts...))
  170. }
  171. w.Write(nil) // mock response with status 200
  172. }
  173. return test{
  174. ctx: context.Background(),
  175. auth: auth,
  176. req: req,
  177. next: next,
  178. statusCode: 200,
  179. err: nil,
  180. }
  181. },
  182. }
  183. for name, prep := range tests {
  184. tc := prep(t)
  185. t.Run(name, func(t *testing.T) {
  186. h := &Handler{
  187. auth: tc.auth,
  188. }
  189. req := tc.req.WithContext(tc.ctx)
  190. w := httptest.NewRecorder()
  191. h.extractAuthorizeTokenAdmin(tc.next)(w, req)
  192. res := w.Result()
  193. assert.Equals(t, tc.statusCode, res.StatusCode)
  194. body, err := io.ReadAll(res.Body)
  195. res.Body.Close()
  196. assert.FatalError(t, err)
  197. if res.StatusCode >= 400 {
  198. err := admin.Error{}
  199. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  200. assert.Equals(t, tc.err.Type, err.Type)
  201. assert.Equals(t, tc.err.Message, err.Message)
  202. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  203. assert.Equals(t, tc.err.Detail, err.Detail)
  204. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  205. return
  206. }
  207. })
  208. }
  209. }
  210. func TestHandler_loadProvisionerByName(t *testing.T) {
  211. type test struct {
  212. adminDB admin.DB
  213. auth adminAuthority
  214. ctx context.Context
  215. next http.HandlerFunc
  216. err *admin.Error
  217. statusCode int
  218. }
  219. var tests = map[string]func(t *testing.T) test{
  220. "fail/auth.LoadProvisionerByName": func(t *testing.T) test {
  221. chiCtx := chi.NewRouteContext()
  222. chiCtx.URLParams.Add("provisionerName", "provName")
  223. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  224. auth := &mockAdminAuthority{
  225. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  226. assert.Equals(t, "provName", name)
  227. return nil, errors.New("force")
  228. },
  229. }
  230. err := admin.WrapErrorISE(errors.New("force"), "error loading provisioner provName")
  231. err.Message = "error loading provisioner provName: force"
  232. return test{
  233. ctx: ctx,
  234. auth: auth,
  235. statusCode: 500,
  236. err: err,
  237. }
  238. },
  239. "fail/db.GetProvisioner": func(t *testing.T) test {
  240. chiCtx := chi.NewRouteContext()
  241. chiCtx.URLParams.Add("provisionerName", "provName")
  242. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  243. auth := &mockAdminAuthority{
  244. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  245. assert.Equals(t, "provName", name)
  246. return &provisioner.MockProvisioner{
  247. MgetID: func() string {
  248. return "provID"
  249. },
  250. }, nil
  251. },
  252. }
  253. db := &admin.MockDB{
  254. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  255. assert.Equals(t, "provID", id)
  256. return nil, errors.New("force")
  257. },
  258. }
  259. err := admin.WrapErrorISE(errors.New("force"), "error retrieving provisioner provName")
  260. err.Message = "error retrieving provisioner provName: force"
  261. return test{
  262. ctx: ctx,
  263. auth: auth,
  264. adminDB: db,
  265. statusCode: 500,
  266. err: err,
  267. }
  268. },
  269. "ok": func(t *testing.T) test {
  270. chiCtx := chi.NewRouteContext()
  271. chiCtx.URLParams.Add("provisionerName", "provName")
  272. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  273. auth := &mockAdminAuthority{
  274. MockLoadProvisionerByName: func(name string) (provisioner.Interface, error) {
  275. assert.Equals(t, "provName", name)
  276. return &provisioner.MockProvisioner{
  277. MgetID: func() string {
  278. return "provID"
  279. },
  280. }, nil
  281. },
  282. }
  283. db := &admin.MockDB{
  284. MockGetProvisioner: func(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  285. assert.Equals(t, "provID", id)
  286. return &linkedca.Provisioner{
  287. Id: "provID",
  288. Name: "provName",
  289. }, nil
  290. },
  291. }
  292. return test{
  293. ctx: ctx,
  294. auth: auth,
  295. adminDB: db,
  296. statusCode: 200,
  297. next: func(w http.ResponseWriter, r *http.Request) {
  298. prov := linkedca.ProvisionerFromContext(r.Context())
  299. assert.NotNil(t, prov)
  300. assert.Equals(t, "provID", prov.GetId())
  301. assert.Equals(t, "provName", prov.GetName())
  302. w.Write(nil) // mock response with status 200
  303. },
  304. }
  305. },
  306. }
  307. for name, prep := range tests {
  308. tc := prep(t)
  309. t.Run(name, func(t *testing.T) {
  310. h := &Handler{
  311. auth: tc.auth,
  312. adminDB: tc.adminDB,
  313. }
  314. req := httptest.NewRequest("GET", "/foo", nil) // chi routing is prepared in test setup
  315. req = req.WithContext(tc.ctx)
  316. w := httptest.NewRecorder()
  317. h.loadProvisionerByName(tc.next)(w, req)
  318. res := w.Result()
  319. assert.Equals(t, tc.statusCode, res.StatusCode)
  320. body, err := io.ReadAll(res.Body)
  321. res.Body.Close()
  322. assert.FatalError(t, err)
  323. if res.StatusCode >= 400 {
  324. err := admin.Error{}
  325. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  326. assert.Equals(t, tc.err.Type, err.Type)
  327. assert.Equals(t, tc.err.Message, err.Message)
  328. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  329. assert.Equals(t, tc.err.Detail, err.Detail)
  330. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  331. return
  332. }
  333. })
  334. }
  335. }
  336. func TestHandler_checkAction(t *testing.T) {
  337. type test struct {
  338. adminDB admin.DB
  339. next http.HandlerFunc
  340. supportedInStandalone bool
  341. err *admin.Error
  342. statusCode int
  343. }
  344. var tests = map[string]func(t *testing.T) test{
  345. // "standalone-mockdb-supported": func(t *testing.T) test {
  346. // err := admin.NewError(admin.ErrorNotImplementedType, "operation not supported")
  347. // err.Message = "operation not supported"
  348. // return test{
  349. // adminDB: &admin.MockDB{},
  350. // statusCode: 501,
  351. // err: err,
  352. // }
  353. // },
  354. "standalone-nosql-supported": func(t *testing.T) test {
  355. return test{
  356. supportedInStandalone: true,
  357. adminDB: &nosql.DB{},
  358. next: func(w http.ResponseWriter, r *http.Request) {
  359. w.Write(nil) // mock response with status 200
  360. },
  361. statusCode: 200,
  362. }
  363. },
  364. "standalone-nosql-not-supported": func(t *testing.T) test {
  365. err := admin.NewError(admin.ErrorNotImplementedType, "operation not supported in standalone mode")
  366. err.Message = "operation not supported in standalone mode"
  367. return test{
  368. supportedInStandalone: false,
  369. adminDB: &nosql.DB{},
  370. next: func(w http.ResponseWriter, r *http.Request) {
  371. w.Write(nil) // mock response with status 200
  372. },
  373. statusCode: 501,
  374. err: err,
  375. }
  376. },
  377. // "standalone-no-nosql-not-supported": func(t *testing.T) test {
  378. // // TODO(hs): temporarily expects an error instead of an OK response
  379. // err := admin.NewError(admin.ErrorNotImplementedType, "operation not supported")
  380. // err.Message = "operation not supported"
  381. // return test{
  382. // supportedInStandalone: false,
  383. // adminDB: &admin.MockDB{},
  384. // next: func(w http.ResponseWriter, r *http.Request) {
  385. // w.Write(nil) // mock response with status 200
  386. // },
  387. // statusCode: 501,
  388. // err: err,
  389. // }
  390. // },
  391. }
  392. for name, prep := range tests {
  393. tc := prep(t)
  394. t.Run(name, func(t *testing.T) {
  395. h := &Handler{
  396. adminDB: tc.adminDB,
  397. }
  398. req := httptest.NewRequest("GET", "/foo", nil)
  399. w := httptest.NewRecorder()
  400. h.checkAction(tc.next, tc.supportedInStandalone)(w, req)
  401. res := w.Result()
  402. assert.Equals(t, tc.statusCode, res.StatusCode)
  403. body, err := io.ReadAll(res.Body)
  404. res.Body.Close()
  405. assert.FatalError(t, err)
  406. if res.StatusCode >= 400 {
  407. err := admin.Error{}
  408. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  409. assert.Equals(t, tc.err.Type, err.Type)
  410. assert.Equals(t, tc.err.Message, err.Message)
  411. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  412. assert.Equals(t, tc.err.Detail, err.Detail)
  413. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  414. return
  415. }
  416. })
  417. }
  418. }