client_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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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MBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
  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+XT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F4gqaNE
  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. CertChainPEM: []api.Certificate{
  234. {Certificate: parseCertificate(certPEM)},
  235. {Certificate: parseCertificate(rootPEM)},
  236. },
  237. }
  238. request := &api.SignRequest{
  239. CsrPEM: api.CertificateRequest{CertificateRequest: parseCertificateRequest(csrPEM)},
  240. OTT: "the-ott",
  241. NotBefore: api.NewTimeDuration(time.Now()),
  242. NotAfter: api.NewTimeDuration(time.Now().AddDate(0, 1, 0)),
  243. }
  244. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  245. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  246. tests := []struct {
  247. name string
  248. request *api.SignRequest
  249. response interface{}
  250. responseCode int
  251. wantErr bool
  252. }{
  253. {"ok", request, ok, 200, false},
  254. {"unauthorized", request, unauthorized, 401, true},
  255. {"empty request", &api.SignRequest{}, badRequest, 403, true},
  256. {"nil request", nil, badRequest, 403, true},
  257. }
  258. srv := httptest.NewServer(nil)
  259. defer srv.Close()
  260. for _, tt := range tests {
  261. t.Run(tt.name, func(t *testing.T) {
  262. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  263. if err != nil {
  264. t.Errorf("NewClient() error = %v", err)
  265. return
  266. }
  267. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  268. body := new(api.SignRequest)
  269. if err := api.ReadJSON(req.Body, body); err != nil {
  270. api.WriteError(w, badRequest)
  271. return
  272. } else if !equalJSON(t, body, tt.request) {
  273. if tt.request == nil {
  274. if !reflect.DeepEqual(body, &api.SignRequest{}) {
  275. t.Errorf("Client.Sign() request = %v, wants %v", body, tt.request)
  276. }
  277. } else {
  278. t.Errorf("Client.Sign() request = %v, wants %v", body, tt.request)
  279. }
  280. }
  281. api.JSONStatus(w, tt.response, tt.responseCode)
  282. })
  283. got, err := c.Sign(tt.request)
  284. if (err != nil) != tt.wantErr {
  285. fmt.Printf("%+v", err)
  286. t.Errorf("Client.Sign() error = %v, wantErr %v", err, tt.wantErr)
  287. return
  288. }
  289. switch {
  290. case err != nil:
  291. if got != nil {
  292. t.Errorf("Client.Sign() = %v, want nil", got)
  293. }
  294. if !reflect.DeepEqual(err, tt.response) {
  295. t.Errorf("Client.Sign() error = %v, want %v", err, tt.response)
  296. }
  297. default:
  298. if !reflect.DeepEqual(got, tt.response) {
  299. t.Errorf("Client.Sign() = %v, want %v", got, tt.response)
  300. }
  301. }
  302. })
  303. }
  304. }
  305. func TestClient_Revoke(t *testing.T) {
  306. ok := &api.RevokeResponse{Status: "ok"}
  307. request := &api.RevokeRequest{
  308. Serial: "sn",
  309. OTT: "the-ott",
  310. ReasonCode: 4,
  311. }
  312. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  313. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  314. tests := []struct {
  315. name string
  316. request *api.RevokeRequest
  317. response interface{}
  318. responseCode int
  319. wantErr bool
  320. }{
  321. {"ok", request, ok, 200, false},
  322. {"unauthorized", request, unauthorized, 401, true},
  323. {"nil request", nil, badRequest, 403, true},
  324. }
  325. srv := httptest.NewServer(nil)
  326. defer srv.Close()
  327. for _, tt := range tests {
  328. t.Run(tt.name, func(t *testing.T) {
  329. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  330. if err != nil {
  331. t.Errorf("NewClient() error = %v", err)
  332. return
  333. }
  334. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  335. body := new(api.RevokeRequest)
  336. if err := api.ReadJSON(req.Body, body); err != nil {
  337. api.WriteError(w, badRequest)
  338. return
  339. } else if !equalJSON(t, body, tt.request) {
  340. if tt.request == nil {
  341. if !reflect.DeepEqual(body, &api.RevokeRequest{}) {
  342. t.Errorf("Client.Revoke() request = %v, wants %v", body, tt.request)
  343. }
  344. } else {
  345. t.Errorf("Client.Revoke() request = %v, wants %v", body, tt.request)
  346. }
  347. }
  348. api.JSONStatus(w, tt.response, tt.responseCode)
  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. CertChainPEM: []api.Certificate{
  377. {Certificate: parseCertificate(certPEM)},
  378. {Certificate: parseCertificate(rootPEM)},
  379. },
  380. }
  381. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  382. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  383. tests := []struct {
  384. name string
  385. response interface{}
  386. responseCode int
  387. wantErr bool
  388. }{
  389. {"ok", ok, 200, false},
  390. {"unauthorized", unauthorized, 401, true},
  391. {"empty request", badRequest, 403, true},
  392. {"nil request", badRequest, 403, true},
  393. }
  394. srv := httptest.NewServer(nil)
  395. defer srv.Close()
  396. for _, tt := range tests {
  397. t.Run(tt.name, func(t *testing.T) {
  398. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  399. if err != nil {
  400. t.Errorf("NewClient() error = %v", err)
  401. return
  402. }
  403. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  404. api.JSONStatus(w, tt.response, tt.responseCode)
  405. })
  406. got, err := c.Renew(nil)
  407. if (err != nil) != tt.wantErr {
  408. fmt.Printf("%+v", err)
  409. t.Errorf("Client.Renew() error = %v, wantErr %v", err, tt.wantErr)
  410. return
  411. }
  412. switch {
  413. case err != nil:
  414. if got != nil {
  415. t.Errorf("Client.Renew() = %v, want nil", got)
  416. }
  417. if !reflect.DeepEqual(err, tt.response) {
  418. t.Errorf("Client.Renew() error = %v, want %v", err, tt.response)
  419. }
  420. default:
  421. if !reflect.DeepEqual(got, tt.response) {
  422. t.Errorf("Client.Renew() = %v, want %v", got, tt.response)
  423. }
  424. }
  425. })
  426. }
  427. }
  428. func TestClient_Provisioners(t *testing.T) {
  429. ok := &api.ProvisionersResponse{
  430. Provisioners: provisioner.List{},
  431. }
  432. internalServerError := api.InternalServerError(fmt.Errorf("Internal Server Error"))
  433. tests := []struct {
  434. name string
  435. args []ProvisionerOption
  436. expectedURI string
  437. response interface{}
  438. responseCode int
  439. wantErr bool
  440. }{
  441. {"ok", nil, "/provisioners", ok, 200, false},
  442. {"ok with cursor", []ProvisionerOption{WithProvisionerCursor("abc")}, "/provisioners?cursor=abc", ok, 200, false},
  443. {"ok with limit", []ProvisionerOption{WithProvisionerLimit(10)}, "/provisioners?limit=10", ok, 200, false},
  444. {"ok with cursor+limit", []ProvisionerOption{WithProvisionerCursor("abc"), WithProvisionerLimit(10)}, "/provisioners?cursor=abc&limit=10", ok, 200, false},
  445. {"fail", nil, "/provisioners", internalServerError, 500, true},
  446. }
  447. srv := httptest.NewServer(nil)
  448. defer srv.Close()
  449. for _, tt := range tests {
  450. t.Run(tt.name, func(t *testing.T) {
  451. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  452. if err != nil {
  453. t.Errorf("NewClient() error = %v", err)
  454. return
  455. }
  456. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  457. if req.RequestURI != tt.expectedURI {
  458. t.Errorf("RequestURI = %s, want %s", req.RequestURI, tt.expectedURI)
  459. }
  460. api.JSONStatus(w, tt.response, tt.responseCode)
  461. })
  462. got, err := c.Provisioners(tt.args...)
  463. if (err != nil) != tt.wantErr {
  464. t.Errorf("Client.Provisioners() error = %v, wantErr %v", err, tt.wantErr)
  465. return
  466. }
  467. switch {
  468. case err != nil:
  469. if got != nil {
  470. t.Errorf("Client.Provisioners() = %v, want nil", got)
  471. }
  472. if !reflect.DeepEqual(err, tt.response) {
  473. t.Errorf("Client.Provisioners() error = %v, want %v", err, tt.response)
  474. }
  475. default:
  476. if !reflect.DeepEqual(got, tt.response) {
  477. t.Errorf("Client.Provisioners() = %v, want %v", got, tt.response)
  478. }
  479. }
  480. })
  481. }
  482. }
  483. func TestClient_ProvisionerKey(t *testing.T) {
  484. ok := &api.ProvisionerKeyResponse{
  485. Key: "an encrypted key",
  486. }
  487. notFound := api.NotFound(fmt.Errorf("Not Found"))
  488. tests := []struct {
  489. name string
  490. kid string
  491. response interface{}
  492. responseCode int
  493. wantErr bool
  494. }{
  495. {"ok", "kid", ok, 200, false},
  496. {"fail", "invalid", notFound, 500, true},
  497. }
  498. srv := httptest.NewServer(nil)
  499. defer srv.Close()
  500. for _, tt := range tests {
  501. t.Run(tt.name, func(t *testing.T) {
  502. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  503. if err != nil {
  504. t.Errorf("NewClient() error = %v", err)
  505. return
  506. }
  507. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  508. expected := "/provisioners/" + tt.kid + "/encrypted-key"
  509. if req.RequestURI != expected {
  510. t.Errorf("RequestURI = %s, want %s", req.RequestURI, expected)
  511. }
  512. api.JSONStatus(w, tt.response, tt.responseCode)
  513. })
  514. got, err := c.ProvisionerKey(tt.kid)
  515. if (err != nil) != tt.wantErr {
  516. t.Errorf("Client.ProvisionerKey() error = %v, wantErr %v", err, tt.wantErr)
  517. return
  518. }
  519. switch {
  520. case err != nil:
  521. if got != nil {
  522. t.Errorf("Client.ProvisionerKey() = %v, want nil", got)
  523. }
  524. if !reflect.DeepEqual(err, tt.response) {
  525. t.Errorf("Client.ProvisionerKey() error = %v, want %v", err, tt.response)
  526. }
  527. default:
  528. if !reflect.DeepEqual(got, tt.response) {
  529. t.Errorf("Client.ProvisionerKey() = %v, want %v", got, tt.response)
  530. }
  531. }
  532. })
  533. }
  534. }
  535. func TestClient_Roots(t *testing.T) {
  536. ok := &api.RootsResponse{
  537. Certificates: []api.Certificate{
  538. {Certificate: parseCertificate(rootPEM)},
  539. },
  540. }
  541. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  542. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  543. tests := []struct {
  544. name string
  545. response interface{}
  546. responseCode int
  547. wantErr bool
  548. }{
  549. {"ok", ok, 200, false},
  550. {"unauthorized", unauthorized, 401, true},
  551. {"empty request", badRequest, 403, true},
  552. {"nil request", badRequest, 403, true},
  553. }
  554. srv := httptest.NewServer(nil)
  555. defer srv.Close()
  556. for _, tt := range tests {
  557. t.Run(tt.name, func(t *testing.T) {
  558. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  559. if err != nil {
  560. t.Errorf("NewClient() error = %v", err)
  561. return
  562. }
  563. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  564. api.JSONStatus(w, tt.response, tt.responseCode)
  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. api.JSONStatus(w, tt.response, tt.responseCode)
  618. })
  619. got, err := c.Federation()
  620. if (err != nil) != tt.wantErr {
  621. fmt.Printf("%+v", err)
  622. t.Errorf("Client.Federation() error = %v, wantErr %v", err, tt.wantErr)
  623. return
  624. }
  625. switch {
  626. case err != nil:
  627. if got != nil {
  628. t.Errorf("Client.Federation() = %v, want nil", got)
  629. }
  630. if !reflect.DeepEqual(err, tt.response) {
  631. t.Errorf("Client.Federation() error = %v, want %v", err, tt.response)
  632. }
  633. default:
  634. if !reflect.DeepEqual(got, tt.response) {
  635. t.Errorf("Client.Federation() = %v, want %v", got, tt.response)
  636. }
  637. }
  638. })
  639. }
  640. }
  641. func Test_parseEndpoint(t *testing.T) {
  642. expected1 := &url.URL{Scheme: "https", Host: "ca.smallstep.com"}
  643. expected2 := &url.URL{Scheme: "https", Host: "ca.smallstep.com", Path: "/1.0/sign"}
  644. type args struct {
  645. endpoint string
  646. }
  647. tests := []struct {
  648. name string
  649. args args
  650. want *url.URL
  651. wantErr bool
  652. }{
  653. {"ok", args{"https://ca.smallstep.com"}, expected1, false},
  654. {"ok no scheme", args{"//ca.smallstep.com"}, expected1, false},
  655. {"ok only host", args{"ca.smallstep.com"}, expected1, false},
  656. {"ok no bars", args{"https://ca.smallstep.com"}, expected1, false},
  657. {"ok schema, host and path", args{"https://ca.smallstep.com/1.0/sign"}, expected2, false},
  658. {"ok no bars with path", args{"https://ca.smallstep.com/1.0/sign"}, expected2, false},
  659. {"ok host and path", args{"ca.smallstep.com/1.0/sign"}, expected2, false},
  660. {"ok host and port", args{"ca.smallstep.com:443"}, &url.URL{Scheme: "https", Host: "ca.smallstep.com:443"}, false},
  661. {"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},
  662. {"fail bad url", args{"://ca.smallstep.com"}, nil, true},
  663. {"fail no host", args{"https://"}, nil, true},
  664. }
  665. for _, tt := range tests {
  666. t.Run(tt.name, func(t *testing.T) {
  667. got, err := parseEndpoint(tt.args.endpoint)
  668. if (err != nil) != tt.wantErr {
  669. t.Errorf("parseEndpoint() error = %v, wantErr %v", err, tt.wantErr)
  670. return
  671. }
  672. if !reflect.DeepEqual(got, tt.want) {
  673. t.Errorf("parseEndpoint() = %v, want %v", got, tt.want)
  674. }
  675. })
  676. }
  677. }
  678. func TestClient_RootFingerprint(t *testing.T) {
  679. ok := &api.HealthResponse{Status: "ok"}
  680. nok := api.InternalServerError(fmt.Errorf("Internal Server Error"))
  681. httpsServer := httptest.NewTLSServer(nil)
  682. defer httpsServer.Close()
  683. httpsServerFingerprint := x509util.Fingerprint(httpsServer.Certificate())
  684. httpServer := httptest.NewServer(nil)
  685. defer httpServer.Close()
  686. tests := []struct {
  687. name string
  688. server *httptest.Server
  689. response interface{}
  690. responseCode int
  691. want string
  692. wantErr bool
  693. }{
  694. {"ok", httpsServer, ok, 200, httpsServerFingerprint, false},
  695. {"ok with error", httpsServer, nok, 500, httpsServerFingerprint, false},
  696. {"fail", httpServer, ok, 200, "", true},
  697. }
  698. for _, tt := range tests {
  699. t.Run(tt.name, func(t *testing.T) {
  700. tr := tt.server.Client().Transport
  701. c, err := NewClient(tt.server.URL, WithTransport(tr))
  702. if err != nil {
  703. t.Errorf("NewClient() error = %v", err)
  704. return
  705. }
  706. tt.server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  707. api.JSONStatus(w, tt.response, tt.responseCode)
  708. })
  709. got, err := c.RootFingerprint()
  710. if (err != nil) != tt.wantErr {
  711. fmt.Printf("%+v", err)
  712. t.Errorf("Client.RootFingerprint() error = %v, wantErr %v", err, tt.wantErr)
  713. return
  714. }
  715. if !reflect.DeepEqual(got, tt.want) {
  716. t.Errorf("Client.RootFingerprint() = %v, want %v", got, tt.want)
  717. }
  718. })
  719. }
  720. }
  721. func TestClient_RootFingerprintWithServer(t *testing.T) {
  722. srv := startCABootstrapServer()
  723. defer srv.Close()
  724. client, err := NewClient(srv.URL+"/sign", WithRootFile("testdata/secrets/root_ca.crt"))
  725. assert.FatalError(t, err)
  726. fp, err := client.RootFingerprint()
  727. assert.FatalError(t, err)
  728. assert.Equals(t, "ef742f95dc0d8aa82d3cca4017af6dac3fce84290344159891952d18c53eefe7", fp)
  729. }