client_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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 = `-----BEGIN CERTIFICATE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AdZ5AgUBMA0GCSqGSIb3DQEB
  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. 7jowx+XTKbFYgKcX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  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. api.JSONStatus(w, tt.response, tt.responseCode)
  154. })
  155. got, err := c.Health()
  156. if (err != nil) != tt.wantErr {
  157. fmt.Printf("%+v", err)
  158. t.Errorf("Client.Health() error = %v, wantErr %v", err, tt.wantErr)
  159. return
  160. }
  161. switch {
  162. case err != nil:
  163. if got != nil {
  164. t.Errorf("Client.Health() = %v, want nil", got)
  165. }
  166. if !reflect.DeepEqual(err, tt.response) {
  167. t.Errorf("Client.Health() error = %v, want %v", err, tt.response)
  168. }
  169. default:
  170. if !reflect.DeepEqual(got, tt.response) {
  171. t.Errorf("Client.Health() = %v, want %v", got, tt.response)
  172. }
  173. }
  174. })
  175. }
  176. }
  177. func TestClient_Root(t *testing.T) {
  178. ok := &api.RootResponse{
  179. RootPEM: api.Certificate{Certificate: parseCertificate(rootPEM)},
  180. }
  181. notFound := api.NotFound(fmt.Errorf("Not Found"))
  182. tests := []struct {
  183. name string
  184. shasum string
  185. response interface{}
  186. responseCode int
  187. wantErr bool
  188. }{
  189. {"ok", "a047a37fa2d2e118a4f5095fe074d6cfe0e352425a7632bf8659c03919a6c81d", ok, 200, false},
  190. {"not found", "invalid", notFound, 404, true},
  191. }
  192. srv := httptest.NewServer(nil)
  193. defer srv.Close()
  194. for _, tt := range tests {
  195. t.Run(tt.name, func(t *testing.T) {
  196. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  197. if err != nil {
  198. t.Errorf("NewClient() error = %v", err)
  199. return
  200. }
  201. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  202. expected := "/root/" + tt.shasum
  203. if req.RequestURI != expected {
  204. t.Errorf("RequestURI = %s, want %s", req.RequestURI, expected)
  205. }
  206. api.JSONStatus(w, tt.response, tt.responseCode)
  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. api.JSONStatus(w, tt.response, tt.responseCode)
  278. })
  279. got, err := c.Sign(tt.request)
  280. if (err != nil) != tt.wantErr {
  281. fmt.Printf("%+v", err)
  282. t.Errorf("Client.Sign() error = %v, wantErr %v", err, tt.wantErr)
  283. return
  284. }
  285. switch {
  286. case err != nil:
  287. if got != nil {
  288. t.Errorf("Client.Sign() = %v, want nil", got)
  289. }
  290. if !reflect.DeepEqual(err, tt.response) {
  291. t.Errorf("Client.Sign() error = %v, want %v", err, tt.response)
  292. }
  293. default:
  294. if !reflect.DeepEqual(got, tt.response) {
  295. t.Errorf("Client.Sign() = %v, want %v", got, tt.response)
  296. }
  297. }
  298. })
  299. }
  300. }
  301. func TestClient_Revoke(t *testing.T) {
  302. ok := &api.RevokeResponse{Status: "ok"}
  303. request := &api.RevokeRequest{
  304. Serial: "sn",
  305. OTT: "the-ott",
  306. ReasonCode: 4,
  307. }
  308. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  309. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  310. tests := []struct {
  311. name string
  312. request *api.RevokeRequest
  313. response interface{}
  314. responseCode int
  315. wantErr bool
  316. }{
  317. {"ok", request, ok, 200, false},
  318. {"unauthorized", request, unauthorized, 401, true},
  319. {"nil request", nil, badRequest, 403, true},
  320. }
  321. srv := httptest.NewServer(nil)
  322. defer srv.Close()
  323. for _, tt := range tests {
  324. t.Run(tt.name, func(t *testing.T) {
  325. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  326. if err != nil {
  327. t.Errorf("NewClient() error = %v", err)
  328. return
  329. }
  330. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  331. body := new(api.RevokeRequest)
  332. if err := api.ReadJSON(req.Body, body); err != nil {
  333. api.WriteError(w, badRequest)
  334. return
  335. } else if !equalJSON(t, body, tt.request) {
  336. if tt.request == nil {
  337. if !reflect.DeepEqual(body, &api.RevokeRequest{}) {
  338. t.Errorf("Client.Revoke() request = %v, wants %v", body, tt.request)
  339. }
  340. } else {
  341. t.Errorf("Client.Revoke() request = %v, wants %v", body, tt.request)
  342. }
  343. }
  344. api.JSONStatus(w, tt.response, tt.responseCode)
  345. })
  346. got, err := c.Revoke(tt.request, nil)
  347. if (err != nil) != tt.wantErr {
  348. fmt.Printf("%+v", err)
  349. t.Errorf("Client.Revoke() error = %v, wantErr %v", err, tt.wantErr)
  350. return
  351. }
  352. switch {
  353. case err != nil:
  354. if got != nil {
  355. t.Errorf("Client.Revoke() = %v, want nil", got)
  356. }
  357. if !reflect.DeepEqual(err, tt.response) {
  358. t.Errorf("Client.Revoke() error = %v, want %v", err, tt.response)
  359. }
  360. default:
  361. if !reflect.DeepEqual(got, tt.response) {
  362. t.Errorf("Client.Revoke() = %v, want %v", got, tt.response)
  363. }
  364. }
  365. })
  366. }
  367. }
  368. func TestClient_Renew(t *testing.T) {
  369. ok := &api.SignResponse{
  370. ServerPEM: api.Certificate{Certificate: parseCertificate(certPEM)},
  371. CaPEM: api.Certificate{Certificate: parseCertificate(rootPEM)},
  372. }
  373. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  374. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  375. tests := []struct {
  376. name string
  377. response interface{}
  378. responseCode int
  379. wantErr bool
  380. }{
  381. {"ok", ok, 200, false},
  382. {"unauthorized", unauthorized, 401, true},
  383. {"empty request", badRequest, 403, true},
  384. {"nil request", badRequest, 403, true},
  385. }
  386. srv := httptest.NewServer(nil)
  387. defer srv.Close()
  388. for _, tt := range tests {
  389. t.Run(tt.name, func(t *testing.T) {
  390. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  391. if err != nil {
  392. t.Errorf("NewClient() error = %v", err)
  393. return
  394. }
  395. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  396. api.JSONStatus(w, tt.response, tt.responseCode)
  397. })
  398. got, err := c.Renew(nil)
  399. if (err != nil) != tt.wantErr {
  400. fmt.Printf("%+v", err)
  401. t.Errorf("Client.Renew() error = %v, wantErr %v", err, tt.wantErr)
  402. return
  403. }
  404. switch {
  405. case err != nil:
  406. if got != nil {
  407. t.Errorf("Client.Renew() = %v, want nil", got)
  408. }
  409. if !reflect.DeepEqual(err, tt.response) {
  410. t.Errorf("Client.Renew() error = %v, want %v", err, tt.response)
  411. }
  412. default:
  413. if !reflect.DeepEqual(got, tt.response) {
  414. t.Errorf("Client.Renew() = %v, want %v", got, tt.response)
  415. }
  416. }
  417. })
  418. }
  419. }
  420. func TestClient_Provisioners(t *testing.T) {
  421. ok := &api.ProvisionersResponse{
  422. Provisioners: provisioner.List{},
  423. }
  424. internalServerError := api.InternalServerError(fmt.Errorf("Internal Server Error"))
  425. tests := []struct {
  426. name string
  427. args []ProvisionerOption
  428. expectedURI string
  429. response interface{}
  430. responseCode int
  431. wantErr bool
  432. }{
  433. {"ok", nil, "/provisioners", ok, 200, false},
  434. {"ok with cursor", []ProvisionerOption{WithProvisionerCursor("abc")}, "/provisioners?cursor=abc", ok, 200, false},
  435. {"ok with limit", []ProvisionerOption{WithProvisionerLimit(10)}, "/provisioners?limit=10", ok, 200, false},
  436. {"ok with cursor+limit", []ProvisionerOption{WithProvisionerCursor("abc"), WithProvisionerLimit(10)}, "/provisioners?cursor=abc&limit=10", ok, 200, false},
  437. {"fail", nil, "/provisioners", internalServerError, 500, true},
  438. }
  439. srv := httptest.NewServer(nil)
  440. defer srv.Close()
  441. for _, tt := range tests {
  442. t.Run(tt.name, func(t *testing.T) {
  443. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  444. if err != nil {
  445. t.Errorf("NewClient() error = %v", err)
  446. return
  447. }
  448. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  449. if req.RequestURI != tt.expectedURI {
  450. t.Errorf("RequestURI = %s, want %s", req.RequestURI, tt.expectedURI)
  451. }
  452. api.JSONStatus(w, tt.response, tt.responseCode)
  453. })
  454. got, err := c.Provisioners(tt.args...)
  455. if (err != nil) != tt.wantErr {
  456. t.Errorf("Client.Provisioners() error = %v, wantErr %v", err, tt.wantErr)
  457. return
  458. }
  459. switch {
  460. case err != nil:
  461. if got != nil {
  462. t.Errorf("Client.Provisioners() = %v, want nil", got)
  463. }
  464. if !reflect.DeepEqual(err, tt.response) {
  465. t.Errorf("Client.Provisioners() error = %v, want %v", err, tt.response)
  466. }
  467. default:
  468. if !reflect.DeepEqual(got, tt.response) {
  469. t.Errorf("Client.Provisioners() = %v, want %v", got, tt.response)
  470. }
  471. }
  472. })
  473. }
  474. }
  475. func TestClient_ProvisionerKey(t *testing.T) {
  476. ok := &api.ProvisionerKeyResponse{
  477. Key: "an encrypted key",
  478. }
  479. notFound := api.NotFound(fmt.Errorf("Not Found"))
  480. tests := []struct {
  481. name string
  482. kid string
  483. response interface{}
  484. responseCode int
  485. wantErr bool
  486. }{
  487. {"ok", "kid", ok, 200, false},
  488. {"fail", "invalid", notFound, 500, true},
  489. }
  490. srv := httptest.NewServer(nil)
  491. defer srv.Close()
  492. for _, tt := range tests {
  493. t.Run(tt.name, func(t *testing.T) {
  494. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  495. if err != nil {
  496. t.Errorf("NewClient() error = %v", err)
  497. return
  498. }
  499. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  500. expected := "/provisioners/" + tt.kid + "/encrypted-key"
  501. if req.RequestURI != expected {
  502. t.Errorf("RequestURI = %s, want %s", req.RequestURI, expected)
  503. }
  504. api.JSONStatus(w, tt.response, tt.responseCode)
  505. })
  506. got, err := c.ProvisionerKey(tt.kid)
  507. if (err != nil) != tt.wantErr {
  508. t.Errorf("Client.ProvisionerKey() error = %v, wantErr %v", err, tt.wantErr)
  509. return
  510. }
  511. switch {
  512. case err != nil:
  513. if got != nil {
  514. t.Errorf("Client.ProvisionerKey() = %v, want nil", got)
  515. }
  516. if !reflect.DeepEqual(err, tt.response) {
  517. t.Errorf("Client.ProvisionerKey() error = %v, want %v", err, tt.response)
  518. }
  519. default:
  520. if !reflect.DeepEqual(got, tt.response) {
  521. t.Errorf("Client.ProvisionerKey() = %v, want %v", got, tt.response)
  522. }
  523. }
  524. })
  525. }
  526. }
  527. func TestClient_Roots(t *testing.T) {
  528. ok := &api.RootsResponse{
  529. Certificates: []api.Certificate{
  530. {Certificate: parseCertificate(rootPEM)},
  531. },
  532. }
  533. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  534. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  535. tests := []struct {
  536. name string
  537. response interface{}
  538. responseCode int
  539. wantErr bool
  540. }{
  541. {"ok", ok, 200, false},
  542. {"unauthorized", unauthorized, 401, true},
  543. {"empty request", badRequest, 403, true},
  544. {"nil request", badRequest, 403, true},
  545. }
  546. srv := httptest.NewServer(nil)
  547. defer srv.Close()
  548. for _, tt := range tests {
  549. t.Run(tt.name, func(t *testing.T) {
  550. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  551. if err != nil {
  552. t.Errorf("NewClient() error = %v", err)
  553. return
  554. }
  555. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  556. api.JSONStatus(w, tt.response, tt.responseCode)
  557. })
  558. got, err := c.Roots()
  559. if (err != nil) != tt.wantErr {
  560. fmt.Printf("%+v", err)
  561. t.Errorf("Client.Roots() error = %v, wantErr %v", err, tt.wantErr)
  562. return
  563. }
  564. switch {
  565. case err != nil:
  566. if got != nil {
  567. t.Errorf("Client.Roots() = %v, want nil", got)
  568. }
  569. if !reflect.DeepEqual(err, tt.response) {
  570. t.Errorf("Client.Roots() error = %v, want %v", err, tt.response)
  571. }
  572. default:
  573. if !reflect.DeepEqual(got, tt.response) {
  574. t.Errorf("Client.Roots() = %v, want %v", got, tt.response)
  575. }
  576. }
  577. })
  578. }
  579. }
  580. func TestClient_Federation(t *testing.T) {
  581. ok := &api.FederationResponse{
  582. Certificates: []api.Certificate{
  583. {Certificate: parseCertificate(rootPEM)},
  584. },
  585. }
  586. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  587. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  588. tests := []struct {
  589. name string
  590. response interface{}
  591. responseCode int
  592. wantErr bool
  593. }{
  594. {"ok", ok, 200, false},
  595. {"unauthorized", unauthorized, 401, true},
  596. {"empty request", badRequest, 403, true},
  597. {"nil request", badRequest, 403, true},
  598. }
  599. srv := httptest.NewServer(nil)
  600. defer srv.Close()
  601. for _, tt := range tests {
  602. t.Run(tt.name, func(t *testing.T) {
  603. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  604. if err != nil {
  605. t.Errorf("NewClient() error = %v", err)
  606. return
  607. }
  608. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  609. api.JSONStatus(w, tt.response, tt.responseCode)
  610. })
  611. got, err := c.Federation()
  612. if (err != nil) != tt.wantErr {
  613. fmt.Printf("%+v", err)
  614. t.Errorf("Client.Federation() error = %v, wantErr %v", err, tt.wantErr)
  615. return
  616. }
  617. switch {
  618. case err != nil:
  619. if got != nil {
  620. t.Errorf("Client.Federation() = %v, want nil", got)
  621. }
  622. if !reflect.DeepEqual(err, tt.response) {
  623. t.Errorf("Client.Federation() error = %v, want %v", err, tt.response)
  624. }
  625. default:
  626. if !reflect.DeepEqual(got, tt.response) {
  627. t.Errorf("Client.Federation() = %v, want %v", got, tt.response)
  628. }
  629. }
  630. })
  631. }
  632. }
  633. func Test_parseEndpoint(t *testing.T) {
  634. expected1 := &url.URL{Scheme: "https", Host: "ca.smallstep.com"}
  635. expected2 := &url.URL{Scheme: "https", Host: "ca.smallstep.com", Path: "/1.0/sign"}
  636. type args struct {
  637. endpoint string
  638. }
  639. tests := []struct {
  640. name string
  641. args args
  642. want *url.URL
  643. wantErr bool
  644. }{
  645. {"ok", args{"https://ca.smallstep.com"}, expected1, false},
  646. {"ok no scheme", args{"//ca.smallstep.com"}, expected1, false},
  647. {"ok only host", args{"ca.smallstep.com"}, expected1, false},
  648. {"ok no bars", args{"https://ca.smallstep.com"}, expected1, false},
  649. {"ok schema, host and path", args{"https://ca.smallstep.com/1.0/sign"}, expected2, false},
  650. {"ok no bars with path", args{"https://ca.smallstep.com/1.0/sign"}, expected2, false},
  651. {"ok host and path", args{"ca.smallstep.com/1.0/sign"}, expected2, false},
  652. {"ok host and port", args{"ca.smallstep.com:443"}, &url.URL{Scheme: "https", Host: "ca.smallstep.com:443"}, false},
  653. {"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},
  654. {"fail bad url", args{"://ca.smallstep.com"}, nil, true},
  655. {"fail no host", args{"https://"}, nil, true},
  656. }
  657. for _, tt := range tests {
  658. t.Run(tt.name, func(t *testing.T) {
  659. got, err := parseEndpoint(tt.args.endpoint)
  660. if (err != nil) != tt.wantErr {
  661. t.Errorf("parseEndpoint() error = %v, wantErr %v", err, tt.wantErr)
  662. return
  663. }
  664. if !reflect.DeepEqual(got, tt.want) {
  665. t.Errorf("parseEndpoint() = %v, want %v", got, tt.want)
  666. }
  667. })
  668. }
  669. }
  670. func TestClient_RootFingerprint(t *testing.T) {
  671. ok := &api.HealthResponse{Status: "ok"}
  672. nok := api.InternalServerError(fmt.Errorf("Internal Server Error"))
  673. httpsServer := httptest.NewTLSServer(nil)
  674. defer httpsServer.Close()
  675. httpsServerFingerprint := x509util.Fingerprint(httpsServer.Certificate())
  676. httpServer := httptest.NewServer(nil)
  677. defer httpServer.Close()
  678. tests := []struct {
  679. name string
  680. server *httptest.Server
  681. response interface{}
  682. responseCode int
  683. want string
  684. wantErr bool
  685. }{
  686. {"ok", httpsServer, ok, 200, httpsServerFingerprint, false},
  687. {"ok with error", httpsServer, nok, 500, httpsServerFingerprint, false},
  688. {"fail", httpServer, ok, 200, "", true},
  689. }
  690. for _, tt := range tests {
  691. t.Run(tt.name, func(t *testing.T) {
  692. tr := tt.server.Client().Transport
  693. c, err := NewClient(tt.server.URL, WithTransport(tr))
  694. if err != nil {
  695. t.Errorf("NewClient() error = %v", err)
  696. return
  697. }
  698. tt.server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  699. api.JSONStatus(w, tt.response, tt.responseCode)
  700. })
  701. got, err := c.RootFingerprint()
  702. if (err != nil) != tt.wantErr {
  703. fmt.Printf("%+v", err)
  704. t.Errorf("Client.RootFingerprint() error = %v, wantErr %v", err, tt.wantErr)
  705. return
  706. }
  707. if !reflect.DeepEqual(got, tt.want) {
  708. t.Errorf("Client.RootFingerprint() = %v, want %v", got, tt.want)
  709. }
  710. })
  711. }
  712. }
  713. func TestClient_RootFingerprintWithServer(t *testing.T) {
  714. srv := startCABootstrapServer()
  715. defer srv.Close()
  716. client, err := NewClient(srv.URL+"/sign", WithRootFile("testdata/secrets/root_ca.crt"))
  717. assert.FatalError(t, err)
  718. fp, err := client.RootFingerprint()
  719. assert.FatalError(t, err)
  720. assert.Equals(t, "ef742f95dc0d8aa82d3cca4017af6dac3fce84290344159891952d18c53eefe7", fp)
  721. }