client_test.go 22 KB

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