client_test.go 26 KB

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