4
0

client_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. package ca
  2. import (
  3. "bytes"
  4. "crypto/x509"
  5. "encoding/json"
  6. "encoding/pem"
  7. "fmt"
  8. "net/http"
  9. "net/http/httptest"
  10. "net/url"
  11. "reflect"
  12. "testing"
  13. "time"
  14. "github.com/smallstep/assert"
  15. "github.com/smallstep/certificates/api"
  16. "github.com/smallstep/certificates/authority/provisioner"
  17. "github.com/smallstep/cli/crypto/x509util"
  18. )
  19. const (
  20. rootPEM = `-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BAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
  37. BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
  38. /iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
  39. zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
  40. HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
  41. WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
  42. yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
  43. -----END CERTIFICATE-----`
  44. certPEM = `-----BEGIN CERTIFICATE-----
  45. MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE
  46. BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl
  47. cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMTI5MTMyNzQzWhcNMTQwNTI5MDAwMDAw
  48. WjBpMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN
  49. TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEYMBYGA1UEAwwPbWFp
  50. bC5nb29nbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfRrObuSW5T7q
  51. 5CnSEqefEmtH4CCv6+5EckuriNr1CjfVvqzwfAhopXkLrq45EQm8vkmf7W96XJhC
  52. 7ZM0dYi1/qOCAU8wggFLMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAa
  53. BgNVHREEEzARgg9tYWlsLmdvb2dsZS5jb20wCwYDVR0PBAQDAgeAMGgGCCsGAQUF
  54. BwEBBFwwWjArBggrBgEFBQcwAoYfaHR0cDovL3BraS5nb29nbGUuY29tL0dJQUcy
  55. LmNydDArBggrBgEFBQcwAYYfaHR0cDovL2NsaWVudHMxLmdvb2dsZS5jb20vb2Nz
  56. cDAdBgNVHQ4EFgQUiJxtimAuTfwb+aUtBn5UYKreKvMwDAYDVR0TAQH/BAIwADAf
  57. BgNVHSMEGDAWgBRK3QYWG7z2aLV29YG2u2IaulqBLzAXBgNVHSAEEDAOMAwGCisG
  58. AQQB1nkCBQEwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3BraS5nb29nbGUuY29t
  59. L0dJQUcyLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAH6RYHxHdcGpMpFE3oxDoFnP+
  60. gtuBCHan2yE2GRbJ2Cw8Lw0MmuKqHlf9RSeYfd3BXeKkj1qO6TVKwCh+0HdZk283
  61. TZZyzmEOyclm3UGFYe82P/iDFt+CeQ3NpmBg+GoaVCuWAARJN/KfglbLyyYygcQq
  62. 0SgeDh8dRKUiaW3HQSoYvTvdTuqzwK4CXsr3b5/dAOY8uMuG/IAR3FgwTbZ1dtoW
  63. RvOTa8hYiU6A475WuZKyEHcwnGYe57u2I2KbMgcKjPniocj4QzgYsVAVKW3IwaOh
  64. yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
  65. -----END CERTIFICATE-----`
  66. csrPEM = `-----BEGIN CERTIFICATE REQUEST-----
  67. MIIEYjCCAkoCAQAwHTEbMBkGA1UEAxMSdGVzdC5zbWFsbHN0ZXAuY29tMIICIjAN
  68. BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAuCpifZfoZhYNywfpnPa21NezXgtn
  69. wrWBFE6xhVzE7YDSIqtIsj8aR7R8zwEymxfv5j5298LUy/XSmItVH31CsKyfcGqN
  70. QM0PZr9XY3z5V6qchGMqjzt/jqlYMBHujcxIFBfz4HATxSgKyvHqvw14ESsS2huu
  71. 7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f6ZNAF4gqaNE
  87. Q7vMNPBWrJWu+A++vHY61WGET+h4lY3GFr2I8OE4IiHPQi1D7Y0+fwOmStwuRPM4
  88. 2rARcJChNdiYBkkuvs4kixKTTjdXhB8RQtuBSrJ0M1tzq2qMbm7F8G01rOg4KlXU
  89. 58jHzJwr1K7cx0lpWfGTtc5bseCGtTKmDBXTziw04yl8eE1+ZFOganixGwCtl4Tt
  90. DCbKzWTW8lqVdp9Kyf7XEhhc2R8C5w==
  91. -----END CERTIFICATE REQUEST-----`
  92. )
  93. func parseCertificate(data string) *x509.Certificate {
  94. block, _ := pem.Decode([]byte(data))
  95. if block == nil {
  96. panic("failed to parse certificate PEM")
  97. }
  98. cert, err := x509.ParseCertificate(block.Bytes)
  99. if err != nil {
  100. panic("failed to parse certificate: " + err.Error())
  101. }
  102. return cert
  103. }
  104. func parseCertificateRequest(data string) *x509.CertificateRequest {
  105. block, _ := pem.Decode([]byte(csrPEM))
  106. if block == nil {
  107. panic("failed to parse certificate request PEM")
  108. }
  109. csr, err := x509.ParseCertificateRequest(block.Bytes)
  110. if err != nil {
  111. panic("failed to parse certificate request: " + err.Error())
  112. }
  113. return csr
  114. }
  115. func equalJSON(t *testing.T, a interface{}, b interface{}) bool {
  116. if reflect.DeepEqual(a, b) {
  117. return true
  118. }
  119. ab, err := json.Marshal(a)
  120. if err != nil {
  121. t.Error(err)
  122. return false
  123. }
  124. bb, err := json.Marshal(b)
  125. if err != nil {
  126. t.Error(err)
  127. return false
  128. }
  129. return bytes.Equal(ab, bb)
  130. }
  131. func TestClient_Health(t *testing.T) {
  132. ok := &api.HealthResponse{Status: "ok"}
  133. nok := api.InternalServerError(fmt.Errorf("Internal Server Error"))
  134. tests := []struct {
  135. name string
  136. response interface{}
  137. responseCode int
  138. wantErr bool
  139. }{
  140. {"ok", ok, 200, false},
  141. {"not ok", nok, 500, true},
  142. }
  143. srv := httptest.NewServer(nil)
  144. defer srv.Close()
  145. for _, tt := range tests {
  146. t.Run(tt.name, func(t *testing.T) {
  147. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  148. if err != nil {
  149. t.Errorf("NewClient() error = %v", err)
  150. return
  151. }
  152. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  153. w.WriteHeader(tt.responseCode)
  154. api.JSON(w, tt.response)
  155. })
  156. got, err := c.Health()
  157. if (err != nil) != tt.wantErr {
  158. fmt.Printf("%+v", err)
  159. t.Errorf("Client.Health() error = %v, wantErr %v", err, tt.wantErr)
  160. return
  161. }
  162. switch {
  163. case err != nil:
  164. if got != nil {
  165. t.Errorf("Client.Health() = %v, want nil", got)
  166. }
  167. if !reflect.DeepEqual(err, tt.response) {
  168. t.Errorf("Client.Health() error = %v, want %v", err, tt.response)
  169. }
  170. default:
  171. if !reflect.DeepEqual(got, tt.response) {
  172. t.Errorf("Client.Health() = %v, want %v", got, tt.response)
  173. }
  174. }
  175. })
  176. }
  177. }
  178. func TestClient_Root(t *testing.T) {
  179. ok := &api.RootResponse{
  180. RootPEM: api.Certificate{Certificate: parseCertificate(rootPEM)},
  181. }
  182. notFound := api.NotFound(fmt.Errorf("Not Found"))
  183. tests := []struct {
  184. name string
  185. shasum string
  186. response interface{}
  187. responseCode int
  188. wantErr bool
  189. }{
  190. {"ok", "a047a37fa2d2e118a4f5095fe074d6cfe0e352425a7632bf8659c03919a6c81d", ok, 200, false},
  191. {"not found", "invalid", notFound, 404, true},
  192. }
  193. srv := httptest.NewServer(nil)
  194. defer srv.Close()
  195. for _, tt := range tests {
  196. t.Run(tt.name, func(t *testing.T) {
  197. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  198. if err != nil {
  199. t.Errorf("NewClient() error = %v", err)
  200. return
  201. }
  202. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  203. expected := "/root/" + tt.shasum
  204. if req.RequestURI != expected {
  205. t.Errorf("RequestURI = %s, want %s", req.RequestURI, expected)
  206. }
  207. w.WriteHeader(tt.responseCode)
  208. api.JSON(w, tt.response)
  209. })
  210. got, err := c.Root(tt.shasum)
  211. if (err != nil) != tt.wantErr {
  212. t.Errorf("Client.Root() error = %v, wantErr %v", err, tt.wantErr)
  213. return
  214. }
  215. switch {
  216. case err != nil:
  217. if got != nil {
  218. t.Errorf("Client.Root() = %v, want nil", got)
  219. }
  220. if !reflect.DeepEqual(err, tt.response) {
  221. t.Errorf("Client.Root() error = %v, want %v", err, tt.response)
  222. }
  223. default:
  224. if !reflect.DeepEqual(got, tt.response) {
  225. t.Errorf("Client.Root() = %v, want %v", got, tt.response)
  226. }
  227. }
  228. })
  229. }
  230. }
  231. func TestClient_Sign(t *testing.T) {
  232. ok := &api.SignResponse{
  233. ServerPEM: api.Certificate{Certificate: parseCertificate(certPEM)},
  234. CaPEM: api.Certificate{Certificate: parseCertificate(rootPEM)},
  235. }
  236. request := &api.SignRequest{
  237. CsrPEM: api.CertificateRequest{CertificateRequest: parseCertificateRequest(csrPEM)},
  238. OTT: "the-ott",
  239. NotBefore: api.NewTimeDuration(time.Now()),
  240. NotAfter: api.NewTimeDuration(time.Now().AddDate(0, 1, 0)),
  241. }
  242. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  243. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  244. tests := []struct {
  245. name string
  246. request *api.SignRequest
  247. response interface{}
  248. responseCode int
  249. wantErr bool
  250. }{
  251. {"ok", request, ok, 200, false},
  252. {"unauthorized", request, unauthorized, 401, true},
  253. {"empty request", &api.SignRequest{}, badRequest, 403, true},
  254. {"nil request", nil, badRequest, 403, true},
  255. }
  256. srv := httptest.NewServer(nil)
  257. defer srv.Close()
  258. for _, tt := range tests {
  259. t.Run(tt.name, func(t *testing.T) {
  260. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  261. if err != nil {
  262. t.Errorf("NewClient() error = %v", err)
  263. return
  264. }
  265. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  266. body := new(api.SignRequest)
  267. if err := api.ReadJSON(req.Body, body); err != nil {
  268. api.WriteError(w, badRequest)
  269. return
  270. } else if !equalJSON(t, body, tt.request) {
  271. if tt.request == nil {
  272. if !reflect.DeepEqual(body, &api.SignRequest{}) {
  273. t.Errorf("Client.Sign() request = %v, wants %v", body, tt.request)
  274. }
  275. } else {
  276. t.Errorf("Client.Sign() request = %v, wants %v", body, tt.request)
  277. }
  278. }
  279. w.WriteHeader(tt.responseCode)
  280. api.JSON(w, tt.response)
  281. })
  282. got, err := c.Sign(tt.request)
  283. if (err != nil) != tt.wantErr {
  284. fmt.Printf("%+v", err)
  285. t.Errorf("Client.Sign() error = %v, wantErr %v", err, tt.wantErr)
  286. return
  287. }
  288. switch {
  289. case err != nil:
  290. if got != nil {
  291. t.Errorf("Client.Sign() = %v, want nil", got)
  292. }
  293. if !reflect.DeepEqual(err, tt.response) {
  294. t.Errorf("Client.Sign() error = %v, want %v", err, tt.response)
  295. }
  296. default:
  297. if !reflect.DeepEqual(got, tt.response) {
  298. t.Errorf("Client.Sign() = %v, want %v", got, tt.response)
  299. }
  300. }
  301. })
  302. }
  303. }
  304. func TestClient_Revoke(t *testing.T) {
  305. ok := &api.RevokeResponse{Status: "ok"}
  306. request := &api.RevokeRequest{
  307. Serial: "sn",
  308. OTT: "the-ott",
  309. ReasonCode: 4,
  310. }
  311. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  312. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  313. tests := []struct {
  314. name string
  315. request *api.RevokeRequest
  316. response interface{}
  317. responseCode int
  318. wantErr bool
  319. }{
  320. {"ok", request, ok, 200, false},
  321. {"unauthorized", request, unauthorized, 401, true},
  322. {"nil request", nil, badRequest, 403, true},
  323. }
  324. srv := httptest.NewServer(nil)
  325. defer srv.Close()
  326. for _, tt := range tests {
  327. t.Run(tt.name, func(t *testing.T) {
  328. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  329. if err != nil {
  330. t.Errorf("NewClient() error = %v", err)
  331. return
  332. }
  333. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  334. body := new(api.RevokeRequest)
  335. if err := api.ReadJSON(req.Body, body); err != nil {
  336. api.WriteError(w, badRequest)
  337. return
  338. } else if !equalJSON(t, body, tt.request) {
  339. if tt.request == nil {
  340. if !reflect.DeepEqual(body, &api.RevokeRequest{}) {
  341. t.Errorf("Client.Revoke() request = %v, wants %v", body, tt.request)
  342. }
  343. } else {
  344. t.Errorf("Client.Revoke() request = %v, wants %v", body, tt.request)
  345. }
  346. }
  347. w.WriteHeader(tt.responseCode)
  348. api.JSON(w, tt.response)
  349. })
  350. got, err := c.Revoke(tt.request, nil)
  351. if (err != nil) != tt.wantErr {
  352. fmt.Printf("%+v", err)
  353. t.Errorf("Client.Revoke() error = %v, wantErr %v", err, tt.wantErr)
  354. return
  355. }
  356. switch {
  357. case err != nil:
  358. if got != nil {
  359. t.Errorf("Client.Revoke() = %v, want nil", got)
  360. }
  361. if !reflect.DeepEqual(err, tt.response) {
  362. t.Errorf("Client.Revoke() error = %v, want %v", err, tt.response)
  363. }
  364. default:
  365. if !reflect.DeepEqual(got, tt.response) {
  366. t.Errorf("Client.Revoke() = %v, want %v", got, tt.response)
  367. }
  368. }
  369. })
  370. }
  371. }
  372. func TestClient_Renew(t *testing.T) {
  373. ok := &api.SignResponse{
  374. ServerPEM: api.Certificate{Certificate: parseCertificate(certPEM)},
  375. CaPEM: api.Certificate{Certificate: parseCertificate(rootPEM)},
  376. }
  377. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  378. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  379. tests := []struct {
  380. name string
  381. response interface{}
  382. responseCode int
  383. wantErr bool
  384. }{
  385. {"ok", ok, 200, false},
  386. {"unauthorized", unauthorized, 401, true},
  387. {"empty request", badRequest, 403, true},
  388. {"nil request", badRequest, 403, true},
  389. }
  390. srv := httptest.NewServer(nil)
  391. defer srv.Close()
  392. for _, tt := range tests {
  393. t.Run(tt.name, func(t *testing.T) {
  394. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  395. if err != nil {
  396. t.Errorf("NewClient() error = %v", err)
  397. return
  398. }
  399. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  400. w.WriteHeader(tt.responseCode)
  401. api.JSON(w, tt.response)
  402. })
  403. got, err := c.Renew(nil)
  404. if (err != nil) != tt.wantErr {
  405. fmt.Printf("%+v", err)
  406. t.Errorf("Client.Renew() error = %v, wantErr %v", err, tt.wantErr)
  407. return
  408. }
  409. switch {
  410. case err != nil:
  411. if got != nil {
  412. t.Errorf("Client.Renew() = %v, want nil", got)
  413. }
  414. if !reflect.DeepEqual(err, tt.response) {
  415. t.Errorf("Client.Renew() error = %v, want %v", err, tt.response)
  416. }
  417. default:
  418. if !reflect.DeepEqual(got, tt.response) {
  419. t.Errorf("Client.Renew() = %v, want %v", got, tt.response)
  420. }
  421. }
  422. })
  423. }
  424. }
  425. func TestClient_Provisioners(t *testing.T) {
  426. ok := &api.ProvisionersResponse{
  427. Provisioners: provisioner.List{},
  428. }
  429. internalServerError := api.InternalServerError(fmt.Errorf("Internal Server Error"))
  430. tests := []struct {
  431. name string
  432. args []ProvisionerOption
  433. expectedURI string
  434. response interface{}
  435. responseCode int
  436. wantErr bool
  437. }{
  438. {"ok", nil, "/provisioners", ok, 200, false},
  439. {"ok with cursor", []ProvisionerOption{WithProvisionerCursor("abc")}, "/provisioners?cursor=abc", ok, 200, false},
  440. {"ok with limit", []ProvisionerOption{WithProvisionerLimit(10)}, "/provisioners?limit=10", ok, 200, false},
  441. {"ok with cursor+limit", []ProvisionerOption{WithProvisionerCursor("abc"), WithProvisionerLimit(10)}, "/provisioners?cursor=abc&limit=10", ok, 200, false},
  442. {"fail", nil, "/provisioners", internalServerError, 500, true},
  443. }
  444. srv := httptest.NewServer(nil)
  445. defer srv.Close()
  446. for _, tt := range tests {
  447. t.Run(tt.name, func(t *testing.T) {
  448. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  449. if err != nil {
  450. t.Errorf("NewClient() error = %v", err)
  451. return
  452. }
  453. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  454. if req.RequestURI != tt.expectedURI {
  455. t.Errorf("RequestURI = %s, want %s", req.RequestURI, tt.expectedURI)
  456. }
  457. w.WriteHeader(tt.responseCode)
  458. api.JSON(w, tt.response)
  459. })
  460. got, err := c.Provisioners(tt.args...)
  461. if (err != nil) != tt.wantErr {
  462. t.Errorf("Client.Provisioners() error = %v, wantErr %v", err, tt.wantErr)
  463. return
  464. }
  465. switch {
  466. case err != nil:
  467. if got != nil {
  468. t.Errorf("Client.Provisioners() = %v, want nil", got)
  469. }
  470. if !reflect.DeepEqual(err, tt.response) {
  471. t.Errorf("Client.Provisioners() error = %v, want %v", err, tt.response)
  472. }
  473. default:
  474. if !reflect.DeepEqual(got, tt.response) {
  475. t.Errorf("Client.Provisioners() = %v, want %v", got, tt.response)
  476. }
  477. }
  478. })
  479. }
  480. }
  481. func TestClient_ProvisionerKey(t *testing.T) {
  482. ok := &api.ProvisionerKeyResponse{
  483. Key: "an encrypted key",
  484. }
  485. notFound := api.NotFound(fmt.Errorf("Not Found"))
  486. tests := []struct {
  487. name string
  488. kid string
  489. response interface{}
  490. responseCode int
  491. wantErr bool
  492. }{
  493. {"ok", "kid", ok, 200, false},
  494. {"fail", "invalid", notFound, 500, true},
  495. }
  496. srv := httptest.NewServer(nil)
  497. defer srv.Close()
  498. for _, tt := range tests {
  499. t.Run(tt.name, func(t *testing.T) {
  500. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  501. if err != nil {
  502. t.Errorf("NewClient() error = %v", err)
  503. return
  504. }
  505. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  506. expected := "/provisioners/" + tt.kid + "/encrypted-key"
  507. if req.RequestURI != expected {
  508. t.Errorf("RequestURI = %s, want %s", req.RequestURI, expected)
  509. }
  510. w.WriteHeader(tt.responseCode)
  511. api.JSON(w, tt.response)
  512. })
  513. got, err := c.ProvisionerKey(tt.kid)
  514. if (err != nil) != tt.wantErr {
  515. t.Errorf("Client.ProvisionerKey() error = %v, wantErr %v", err, tt.wantErr)
  516. return
  517. }
  518. switch {
  519. case err != nil:
  520. if got != nil {
  521. t.Errorf("Client.ProvisionerKey() = %v, want nil", got)
  522. }
  523. if !reflect.DeepEqual(err, tt.response) {
  524. t.Errorf("Client.ProvisionerKey() error = %v, want %v", err, tt.response)
  525. }
  526. default:
  527. if !reflect.DeepEqual(got, tt.response) {
  528. t.Errorf("Client.ProvisionerKey() = %v, want %v", got, tt.response)
  529. }
  530. }
  531. })
  532. }
  533. }
  534. func TestClient_Roots(t *testing.T) {
  535. ok := &api.RootsResponse{
  536. Certificates: []api.Certificate{
  537. {Certificate: parseCertificate(rootPEM)},
  538. },
  539. }
  540. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  541. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  542. tests := []struct {
  543. name string
  544. response interface{}
  545. responseCode int
  546. wantErr bool
  547. }{
  548. {"ok", ok, 200, false},
  549. {"unauthorized", unauthorized, 401, true},
  550. {"empty request", badRequest, 403, true},
  551. {"nil request", badRequest, 403, true},
  552. }
  553. srv := httptest.NewServer(nil)
  554. defer srv.Close()
  555. for _, tt := range tests {
  556. t.Run(tt.name, func(t *testing.T) {
  557. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  558. if err != nil {
  559. t.Errorf("NewClient() error = %v", err)
  560. return
  561. }
  562. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  563. w.WriteHeader(tt.responseCode)
  564. api.JSON(w, tt.response)
  565. })
  566. got, err := c.Roots()
  567. if (err != nil) != tt.wantErr {
  568. fmt.Printf("%+v", err)
  569. t.Errorf("Client.Roots() error = %v, wantErr %v", err, tt.wantErr)
  570. return
  571. }
  572. switch {
  573. case err != nil:
  574. if got != nil {
  575. t.Errorf("Client.Roots() = %v, want nil", got)
  576. }
  577. if !reflect.DeepEqual(err, tt.response) {
  578. t.Errorf("Client.Roots() error = %v, want %v", err, tt.response)
  579. }
  580. default:
  581. if !reflect.DeepEqual(got, tt.response) {
  582. t.Errorf("Client.Roots() = %v, want %v", got, tt.response)
  583. }
  584. }
  585. })
  586. }
  587. }
  588. func TestClient_Federation(t *testing.T) {
  589. ok := &api.FederationResponse{
  590. Certificates: []api.Certificate{
  591. {Certificate: parseCertificate(rootPEM)},
  592. },
  593. }
  594. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  595. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  596. tests := []struct {
  597. name string
  598. response interface{}
  599. responseCode int
  600. wantErr bool
  601. }{
  602. {"ok", ok, 200, false},
  603. {"unauthorized", unauthorized, 401, true},
  604. {"empty request", badRequest, 403, true},
  605. {"nil request", badRequest, 403, true},
  606. }
  607. srv := httptest.NewServer(nil)
  608. defer srv.Close()
  609. for _, tt := range tests {
  610. t.Run(tt.name, func(t *testing.T) {
  611. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  612. if err != nil {
  613. t.Errorf("NewClient() error = %v", err)
  614. return
  615. }
  616. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  617. w.WriteHeader(tt.responseCode)
  618. api.JSON(w, tt.response)
  619. })
  620. got, err := c.Federation()
  621. if (err != nil) != tt.wantErr {
  622. fmt.Printf("%+v", err)
  623. t.Errorf("Client.Federation() error = %v, wantErr %v", err, tt.wantErr)
  624. return
  625. }
  626. switch {
  627. case err != nil:
  628. if got != nil {
  629. t.Errorf("Client.Federation() = %v, want nil", got)
  630. }
  631. if !reflect.DeepEqual(err, tt.response) {
  632. t.Errorf("Client.Federation() error = %v, want %v", err, tt.response)
  633. }
  634. default:
  635. if !reflect.DeepEqual(got, tt.response) {
  636. t.Errorf("Client.Federation() = %v, want %v", got, tt.response)
  637. }
  638. }
  639. })
  640. }
  641. }
  642. func Test_parseEndpoint(t *testing.T) {
  643. expected1 := &url.URL{Scheme: "https", Host: "ca.smallstep.com"}
  644. expected2 := &url.URL{Scheme: "https", Host: "ca.smallstep.com", Path: "/1.0/sign"}
  645. type args struct {
  646. endpoint string
  647. }
  648. tests := []struct {
  649. name string
  650. args args
  651. want *url.URL
  652. wantErr bool
  653. }{
  654. {"ok", args{"https://ca.smallstep.com"}, expected1, false},
  655. {"ok no scheme", args{"//ca.smallstep.com"}, expected1, false},
  656. {"ok only host", args{"ca.smallstep.com"}, expected1, false},
  657. {"ok no bars", args{"https://ca.smallstep.com"}, expected1, false},
  658. {"ok schema, host and path", args{"https://ca.smallstep.com/1.0/sign"}, expected2, false},
  659. {"ok no bars with path", args{"https://ca.smallstep.com/1.0/sign"}, expected2, false},
  660. {"ok host and path", args{"ca.smallstep.com/1.0/sign"}, expected2, false},
  661. {"ok host and port", args{"ca.smallstep.com:443"}, &url.URL{Scheme: "https", Host: "ca.smallstep.com:443"}, false},
  662. {"ok host, path and port", args{"ca.smallstep.com:443/1.0/sign"}, &url.URL{Scheme: "https", Host: "ca.smallstep.com:443", Path: "/1.0/sign"}, false},
  663. {"fail bad url", args{"://ca.smallstep.com"}, nil, true},
  664. {"fail no host", args{"https://"}, nil, true},
  665. }
  666. for _, tt := range tests {
  667. t.Run(tt.name, func(t *testing.T) {
  668. got, err := parseEndpoint(tt.args.endpoint)
  669. if (err != nil) != tt.wantErr {
  670. t.Errorf("parseEndpoint() error = %v, wantErr %v", err, tt.wantErr)
  671. return
  672. }
  673. if !reflect.DeepEqual(got, tt.want) {
  674. t.Errorf("parseEndpoint() = %v, want %v", got, tt.want)
  675. }
  676. })
  677. }
  678. }
  679. func TestClient_RootFingerprint(t *testing.T) {
  680. ok := &api.HealthResponse{Status: "ok"}
  681. nok := api.InternalServerError(fmt.Errorf("Internal Server Error"))
  682. httpsServer := httptest.NewTLSServer(nil)
  683. defer httpsServer.Close()
  684. httpsServerFingerprint := x509util.Fingerprint(httpsServer.Certificate())
  685. httpServer := httptest.NewServer(nil)
  686. defer httpServer.Close()
  687. tests := []struct {
  688. name string
  689. server *httptest.Server
  690. response interface{}
  691. responseCode int
  692. want string
  693. wantErr bool
  694. }{
  695. {"ok", httpsServer, ok, 200, httpsServerFingerprint, false},
  696. {"ok with error", httpsServer, nok, 500, httpsServerFingerprint, false},
  697. {"fail", httpServer, ok, 200, "", true},
  698. }
  699. for _, tt := range tests {
  700. t.Run(tt.name, func(t *testing.T) {
  701. tr := tt.server.Client().Transport
  702. c, err := NewClient(tt.server.URL, WithTransport(tr))
  703. if err != nil {
  704. t.Errorf("NewClient() error = %v", err)
  705. return
  706. }
  707. tt.server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  708. w.WriteHeader(tt.responseCode)
  709. api.JSON(w, tt.response)
  710. })
  711. got, err := c.RootFingerprint()
  712. if (err != nil) != tt.wantErr {
  713. fmt.Printf("%+v", err)
  714. t.Errorf("Client.RootFingerprint() error = %v, wantErr %v", err, tt.wantErr)
  715. return
  716. }
  717. if !reflect.DeepEqual(got, tt.want) {
  718. t.Errorf("Client.RootFingerprint() = %v, want %v", got, tt.want)
  719. }
  720. })
  721. }
  722. }
  723. func TestClient_RootFingerprintWithServer(t *testing.T) {
  724. srv := startCABootstrapServer()
  725. defer srv.Close()
  726. client, err := NewClient(srv.URL+"/sign", WithRootFile("testdata/secrets/root_ca.crt"))
  727. assert.FatalError(t, err)
  728. fp, err := client.RootFingerprint()
  729. assert.FatalError(t, err)
  730. assert.Equals(t, "ef742f95dc0d8aa82d3cca4017af6dac3fce84290344159891952d18c53eefe7", fp)
  731. }