4
0

client_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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. CertChainPEM: []api.Certificate{
  245. {Certificate: parseCertificate(certPEM)},
  246. {Certificate: parseCertificate(rootPEM)},
  247. },
  248. }
  249. request := &api.SignRequest{
  250. CsrPEM: api.CertificateRequest{CertificateRequest: parseCertificateRequest(csrPEM)},
  251. OTT: "the-ott",
  252. NotBefore: api.NewTimeDuration(time.Now()),
  253. NotAfter: api.NewTimeDuration(time.Now().AddDate(0, 1, 0)),
  254. }
  255. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  256. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  257. tests := []struct {
  258. name string
  259. request *api.SignRequest
  260. response interface{}
  261. responseCode int
  262. wantErr bool
  263. }{
  264. {"ok", request, ok, 200, false},
  265. {"unauthorized", request, unauthorized, 401, true},
  266. {"empty request", &api.SignRequest{}, badRequest, 403, true},
  267. {"nil request", nil, badRequest, 403, true},
  268. }
  269. srv := httptest.NewServer(nil)
  270. defer srv.Close()
  271. for _, tt := range tests {
  272. t.Run(tt.name, func(t *testing.T) {
  273. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  274. if err != nil {
  275. t.Errorf("NewClient() error = %v", err)
  276. return
  277. }
  278. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  279. body := new(api.SignRequest)
  280. if err := api.ReadJSON(req.Body, body); err != nil {
  281. api.WriteError(w, badRequest)
  282. return
  283. } else if !equalJSON(t, body, tt.request) {
  284. if tt.request == nil {
  285. if !reflect.DeepEqual(body, &api.SignRequest{}) {
  286. t.Errorf("Client.Sign() request = %v, wants %v", body, tt.request)
  287. }
  288. } else {
  289. t.Errorf("Client.Sign() request = %v, wants %v", body, tt.request)
  290. }
  291. }
  292. api.JSONStatus(w, tt.response, tt.responseCode)
  293. })
  294. got, err := c.Sign(tt.request)
  295. if (err != nil) != tt.wantErr {
  296. fmt.Printf("%+v", err)
  297. t.Errorf("Client.Sign() error = %v, wantErr %v", err, tt.wantErr)
  298. return
  299. }
  300. switch {
  301. case err != nil:
  302. if got != nil {
  303. t.Errorf("Client.Sign() = %v, want nil", got)
  304. }
  305. if !reflect.DeepEqual(err, tt.response) {
  306. t.Errorf("Client.Sign() error = %v, want %v", err, tt.response)
  307. }
  308. default:
  309. if !reflect.DeepEqual(got, tt.response) {
  310. t.Errorf("Client.Sign() = %v, want %v", got, tt.response)
  311. }
  312. }
  313. })
  314. }
  315. }
  316. func TestClient_Revoke(t *testing.T) {
  317. ok := &api.RevokeResponse{Status: "ok"}
  318. request := &api.RevokeRequest{
  319. Serial: "sn",
  320. OTT: "the-ott",
  321. ReasonCode: 4,
  322. }
  323. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  324. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  325. tests := []struct {
  326. name string
  327. request *api.RevokeRequest
  328. response interface{}
  329. responseCode int
  330. wantErr bool
  331. }{
  332. {"ok", request, ok, 200, false},
  333. {"unauthorized", request, unauthorized, 401, true},
  334. {"nil request", nil, badRequest, 403, true},
  335. }
  336. srv := httptest.NewServer(nil)
  337. defer srv.Close()
  338. for _, tt := range tests {
  339. t.Run(tt.name, func(t *testing.T) {
  340. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  341. if err != nil {
  342. t.Errorf("NewClient() error = %v", err)
  343. return
  344. }
  345. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  346. body := new(api.RevokeRequest)
  347. if err := api.ReadJSON(req.Body, body); err != nil {
  348. api.WriteError(w, badRequest)
  349. return
  350. } else if !equalJSON(t, body, tt.request) {
  351. if tt.request == nil {
  352. if !reflect.DeepEqual(body, &api.RevokeRequest{}) {
  353. t.Errorf("Client.Revoke() request = %v, wants %v", body, tt.request)
  354. }
  355. } else {
  356. t.Errorf("Client.Revoke() request = %v, wants %v", body, tt.request)
  357. }
  358. }
  359. api.JSONStatus(w, tt.response, tt.responseCode)
  360. })
  361. got, err := c.Revoke(tt.request, nil)
  362. if (err != nil) != tt.wantErr {
  363. fmt.Printf("%+v", err)
  364. t.Errorf("Client.Revoke() error = %v, wantErr %v", err, tt.wantErr)
  365. return
  366. }
  367. switch {
  368. case err != nil:
  369. if got != nil {
  370. t.Errorf("Client.Revoke() = %v, want nil", got)
  371. }
  372. if !reflect.DeepEqual(err, tt.response) {
  373. t.Errorf("Client.Revoke() error = %v, want %v", err, tt.response)
  374. }
  375. default:
  376. if !reflect.DeepEqual(got, tt.response) {
  377. t.Errorf("Client.Revoke() = %v, want %v", got, tt.response)
  378. }
  379. }
  380. })
  381. }
  382. }
  383. func TestClient_Renew(t *testing.T) {
  384. ok := &api.SignResponse{
  385. ServerPEM: api.Certificate{Certificate: parseCertificate(certPEM)},
  386. CaPEM: api.Certificate{Certificate: parseCertificate(rootPEM)},
  387. CertChainPEM: []api.Certificate{
  388. {Certificate: parseCertificate(certPEM)},
  389. {Certificate: parseCertificate(rootPEM)},
  390. },
  391. }
  392. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  393. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  394. tests := []struct {
  395. name string
  396. response interface{}
  397. responseCode int
  398. wantErr bool
  399. }{
  400. {"ok", ok, 200, false},
  401. {"unauthorized", unauthorized, 401, true},
  402. {"empty request", badRequest, 403, true},
  403. {"nil request", badRequest, 403, true},
  404. }
  405. srv := httptest.NewServer(nil)
  406. defer srv.Close()
  407. for _, tt := range tests {
  408. t.Run(tt.name, func(t *testing.T) {
  409. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  410. if err != nil {
  411. t.Errorf("NewClient() error = %v", err)
  412. return
  413. }
  414. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  415. api.JSONStatus(w, tt.response, tt.responseCode)
  416. })
  417. got, err := c.Renew(nil)
  418. if (err != nil) != tt.wantErr {
  419. fmt.Printf("%+v", err)
  420. t.Errorf("Client.Renew() error = %v, wantErr %v", err, tt.wantErr)
  421. return
  422. }
  423. switch {
  424. case err != nil:
  425. if got != nil {
  426. t.Errorf("Client.Renew() = %v, want nil", got)
  427. }
  428. if !reflect.DeepEqual(err, tt.response) {
  429. t.Errorf("Client.Renew() error = %v, want %v", err, tt.response)
  430. }
  431. default:
  432. if !reflect.DeepEqual(got, tt.response) {
  433. t.Errorf("Client.Renew() = %v, want %v", got, tt.response)
  434. }
  435. }
  436. })
  437. }
  438. }
  439. func TestClient_Provisioners(t *testing.T) {
  440. ok := &api.ProvisionersResponse{
  441. Provisioners: provisioner.List{},
  442. }
  443. internalServerError := api.InternalServerError(fmt.Errorf("Internal Server Error"))
  444. tests := []struct {
  445. name string
  446. args []ProvisionerOption
  447. expectedURI string
  448. response interface{}
  449. responseCode int
  450. wantErr bool
  451. }{
  452. {"ok", nil, "/provisioners", ok, 200, false},
  453. {"ok with cursor", []ProvisionerOption{WithProvisionerCursor("abc")}, "/provisioners?cursor=abc", ok, 200, false},
  454. {"ok with limit", []ProvisionerOption{WithProvisionerLimit(10)}, "/provisioners?limit=10", ok, 200, false},
  455. {"ok with cursor+limit", []ProvisionerOption{WithProvisionerCursor("abc"), WithProvisionerLimit(10)}, "/provisioners?cursor=abc&limit=10", ok, 200, false},
  456. {"fail", nil, "/provisioners", internalServerError, 500, true},
  457. }
  458. srv := httptest.NewServer(nil)
  459. defer srv.Close()
  460. for _, tt := range tests {
  461. t.Run(tt.name, func(t *testing.T) {
  462. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  463. if err != nil {
  464. t.Errorf("NewClient() error = %v", err)
  465. return
  466. }
  467. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  468. if req.RequestURI != tt.expectedURI {
  469. t.Errorf("RequestURI = %s, want %s", req.RequestURI, tt.expectedURI)
  470. }
  471. api.JSONStatus(w, tt.response, tt.responseCode)
  472. })
  473. got, err := c.Provisioners(tt.args...)
  474. if (err != nil) != tt.wantErr {
  475. t.Errorf("Client.Provisioners() error = %v, wantErr %v", err, tt.wantErr)
  476. return
  477. }
  478. switch {
  479. case err != nil:
  480. if got != nil {
  481. t.Errorf("Client.Provisioners() = %v, want nil", got)
  482. }
  483. if !reflect.DeepEqual(err, tt.response) {
  484. t.Errorf("Client.Provisioners() error = %v, want %v", err, tt.response)
  485. }
  486. default:
  487. if !reflect.DeepEqual(got, tt.response) {
  488. t.Errorf("Client.Provisioners() = %v, want %v", got, tt.response)
  489. }
  490. }
  491. })
  492. }
  493. }
  494. func TestClient_ProvisionerKey(t *testing.T) {
  495. ok := &api.ProvisionerKeyResponse{
  496. Key: "an encrypted key",
  497. }
  498. notFound := api.NotFound(fmt.Errorf("Not Found"))
  499. tests := []struct {
  500. name string
  501. kid string
  502. response interface{}
  503. responseCode int
  504. wantErr bool
  505. }{
  506. {"ok", "kid", ok, 200, false},
  507. {"fail", "invalid", notFound, 500, true},
  508. }
  509. srv := httptest.NewServer(nil)
  510. defer srv.Close()
  511. for _, tt := range tests {
  512. t.Run(tt.name, func(t *testing.T) {
  513. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  514. if err != nil {
  515. t.Errorf("NewClient() error = %v", err)
  516. return
  517. }
  518. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  519. expected := "/provisioners/" + tt.kid + "/encrypted-key"
  520. if req.RequestURI != expected {
  521. t.Errorf("RequestURI = %s, want %s", req.RequestURI, expected)
  522. }
  523. api.JSONStatus(w, tt.response, tt.responseCode)
  524. })
  525. got, err := c.ProvisionerKey(tt.kid)
  526. if (err != nil) != tt.wantErr {
  527. t.Errorf("Client.ProvisionerKey() error = %v, wantErr %v", err, tt.wantErr)
  528. return
  529. }
  530. switch {
  531. case err != nil:
  532. if got != nil {
  533. t.Errorf("Client.ProvisionerKey() = %v, want nil", got)
  534. }
  535. if !reflect.DeepEqual(err, tt.response) {
  536. t.Errorf("Client.ProvisionerKey() error = %v, want %v", err, tt.response)
  537. }
  538. default:
  539. if !reflect.DeepEqual(got, tt.response) {
  540. t.Errorf("Client.ProvisionerKey() = %v, want %v", got, tt.response)
  541. }
  542. }
  543. })
  544. }
  545. }
  546. func TestClient_Roots(t *testing.T) {
  547. ok := &api.RootsResponse{
  548. Certificates: []api.Certificate{
  549. {Certificate: parseCertificate(rootPEM)},
  550. },
  551. }
  552. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  553. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  554. tests := []struct {
  555. name string
  556. response interface{}
  557. responseCode int
  558. wantErr bool
  559. }{
  560. {"ok", ok, 200, false},
  561. {"unauthorized", unauthorized, 401, true},
  562. {"empty request", badRequest, 403, true},
  563. {"nil request", badRequest, 403, true},
  564. }
  565. srv := httptest.NewServer(nil)
  566. defer srv.Close()
  567. for _, tt := range tests {
  568. t.Run(tt.name, func(t *testing.T) {
  569. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  570. if err != nil {
  571. t.Errorf("NewClient() error = %v", err)
  572. return
  573. }
  574. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  575. api.JSONStatus(w, tt.response, tt.responseCode)
  576. })
  577. got, err := c.Roots()
  578. if (err != nil) != tt.wantErr {
  579. fmt.Printf("%+v", err)
  580. t.Errorf("Client.Roots() error = %v, wantErr %v", err, tt.wantErr)
  581. return
  582. }
  583. switch {
  584. case err != nil:
  585. if got != nil {
  586. t.Errorf("Client.Roots() = %v, want nil", got)
  587. }
  588. if !reflect.DeepEqual(err, tt.response) {
  589. t.Errorf("Client.Roots() error = %v, want %v", err, tt.response)
  590. }
  591. default:
  592. if !reflect.DeepEqual(got, tt.response) {
  593. t.Errorf("Client.Roots() = %v, want %v", got, tt.response)
  594. }
  595. }
  596. })
  597. }
  598. }
  599. func TestClient_Federation(t *testing.T) {
  600. ok := &api.FederationResponse{
  601. Certificates: []api.Certificate{
  602. {Certificate: parseCertificate(rootPEM)},
  603. },
  604. }
  605. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  606. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  607. tests := []struct {
  608. name string
  609. response interface{}
  610. responseCode int
  611. wantErr bool
  612. }{
  613. {"ok", ok, 200, false},
  614. {"unauthorized", unauthorized, 401, true},
  615. {"empty request", badRequest, 403, true},
  616. {"nil request", badRequest, 403, true},
  617. }
  618. srv := httptest.NewServer(nil)
  619. defer srv.Close()
  620. for _, tt := range tests {
  621. t.Run(tt.name, func(t *testing.T) {
  622. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  623. if err != nil {
  624. t.Errorf("NewClient() error = %v", err)
  625. return
  626. }
  627. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  628. api.JSONStatus(w, tt.response, tt.responseCode)
  629. })
  630. got, err := c.Federation()
  631. if (err != nil) != tt.wantErr {
  632. fmt.Printf("%+v", err)
  633. t.Errorf("Client.Federation() error = %v, wantErr %v", err, tt.wantErr)
  634. return
  635. }
  636. switch {
  637. case err != nil:
  638. if got != nil {
  639. t.Errorf("Client.Federation() = %v, want nil", got)
  640. }
  641. if !reflect.DeepEqual(err, tt.response) {
  642. t.Errorf("Client.Federation() error = %v, want %v", err, tt.response)
  643. }
  644. default:
  645. if !reflect.DeepEqual(got, tt.response) {
  646. t.Errorf("Client.Federation() = %v, want %v", got, tt.response)
  647. }
  648. }
  649. })
  650. }
  651. }
  652. func TestClient_SSHRoots(t *testing.T) {
  653. key, err := ssh.NewPublicKey(mustKey().Public())
  654. if err != nil {
  655. t.Fatal(err)
  656. }
  657. ok := &api.SSHRootsResponse{
  658. HostKeys: []api.SSHPublicKey{{PublicKey: key}},
  659. UserKeys: []api.SSHPublicKey{{PublicKey: key}},
  660. }
  661. notFound := api.NotFound(fmt.Errorf("Not Found"))
  662. tests := []struct {
  663. name string
  664. response interface{}
  665. responseCode int
  666. wantErr bool
  667. }{
  668. {"ok", ok, 200, false},
  669. {"not found", notFound, 404, true},
  670. }
  671. srv := httptest.NewServer(nil)
  672. defer srv.Close()
  673. for _, tt := range tests {
  674. t.Run(tt.name, func(t *testing.T) {
  675. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  676. if err != nil {
  677. t.Errorf("NewClient() error = %v", err)
  678. return
  679. }
  680. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  681. api.JSONStatus(w, tt.response, tt.responseCode)
  682. })
  683. got, err := c.SSHRoots()
  684. if (err != nil) != tt.wantErr {
  685. fmt.Printf("%+v", err)
  686. t.Errorf("Client.SSHKeys() error = %v, wantErr %v", err, tt.wantErr)
  687. return
  688. }
  689. switch {
  690. case err != nil:
  691. if got != nil {
  692. t.Errorf("Client.SSHKeys() = %v, want nil", got)
  693. }
  694. if !reflect.DeepEqual(err, tt.response) {
  695. t.Errorf("Client.SSHKeys() error = %v, want %v", err, tt.response)
  696. }
  697. default:
  698. if !reflect.DeepEqual(got, tt.response) {
  699. t.Errorf("Client.SSHKeys() = %v, want %v", got, tt.response)
  700. }
  701. }
  702. })
  703. }
  704. }
  705. func Test_parseEndpoint(t *testing.T) {
  706. expected1 := &url.URL{Scheme: "https", Host: "ca.smallstep.com"}
  707. expected2 := &url.URL{Scheme: "https", Host: "ca.smallstep.com", Path: "/1.0/sign"}
  708. type args struct {
  709. endpoint string
  710. }
  711. tests := []struct {
  712. name string
  713. args args
  714. want *url.URL
  715. wantErr bool
  716. }{
  717. {"ok", args{"https://ca.smallstep.com"}, expected1, false},
  718. {"ok no scheme", args{"//ca.smallstep.com"}, expected1, false},
  719. {"ok only host", args{"ca.smallstep.com"}, expected1, false},
  720. {"ok no bars", args{"https://ca.smallstep.com"}, expected1, false},
  721. {"ok schema, host and path", args{"https://ca.smallstep.com/1.0/sign"}, expected2, false},
  722. {"ok no bars with path", args{"https://ca.smallstep.com/1.0/sign"}, expected2, false},
  723. {"ok host and path", args{"ca.smallstep.com/1.0/sign"}, expected2, false},
  724. {"ok host and port", args{"ca.smallstep.com:443"}, &url.URL{Scheme: "https", Host: "ca.smallstep.com:443"}, false},
  725. {"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},
  726. {"fail bad url", args{"://ca.smallstep.com"}, nil, true},
  727. {"fail no host", args{"https://"}, nil, true},
  728. }
  729. for _, tt := range tests {
  730. t.Run(tt.name, func(t *testing.T) {
  731. got, err := parseEndpoint(tt.args.endpoint)
  732. if (err != nil) != tt.wantErr {
  733. t.Errorf("parseEndpoint() error = %v, wantErr %v", err, tt.wantErr)
  734. return
  735. }
  736. if !reflect.DeepEqual(got, tt.want) {
  737. t.Errorf("parseEndpoint() = %v, want %v", got, tt.want)
  738. }
  739. })
  740. }
  741. }
  742. func TestClient_RootFingerprint(t *testing.T) {
  743. ok := &api.HealthResponse{Status: "ok"}
  744. nok := api.InternalServerError(fmt.Errorf("Internal Server Error"))
  745. httpsServer := httptest.NewTLSServer(nil)
  746. defer httpsServer.Close()
  747. httpsServerFingerprint := x509util.Fingerprint(httpsServer.Certificate())
  748. httpServer := httptest.NewServer(nil)
  749. defer httpServer.Close()
  750. tests := []struct {
  751. name string
  752. server *httptest.Server
  753. response interface{}
  754. responseCode int
  755. want string
  756. wantErr bool
  757. }{
  758. {"ok", httpsServer, ok, 200, httpsServerFingerprint, false},
  759. {"ok with error", httpsServer, nok, 500, httpsServerFingerprint, false},
  760. {"fail", httpServer, ok, 200, "", true},
  761. }
  762. for _, tt := range tests {
  763. t.Run(tt.name, func(t *testing.T) {
  764. tr := tt.server.Client().Transport
  765. c, err := NewClient(tt.server.URL, WithTransport(tr))
  766. if err != nil {
  767. t.Errorf("NewClient() error = %v", err)
  768. return
  769. }
  770. tt.server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  771. api.JSONStatus(w, tt.response, tt.responseCode)
  772. })
  773. got, err := c.RootFingerprint()
  774. if (err != nil) != tt.wantErr {
  775. fmt.Printf("%+v", err)
  776. t.Errorf("Client.RootFingerprint() error = %v, wantErr %v", err, tt.wantErr)
  777. return
  778. }
  779. if !reflect.DeepEqual(got, tt.want) {
  780. t.Errorf("Client.RootFingerprint() = %v, want %v", got, tt.want)
  781. }
  782. })
  783. }
  784. }
  785. func TestClient_RootFingerprintWithServer(t *testing.T) {
  786. srv := startCABootstrapServer()
  787. defer srv.Close()
  788. client, err := NewClient(srv.URL+"/sign", WithRootFile("testdata/secrets/root_ca.crt"))
  789. assert.FatalError(t, err)
  790. fp, err := client.RootFingerprint()
  791. assert.FatalError(t, err)
  792. assert.Equals(t, "ef742f95dc0d8aa82d3cca4017af6dac3fce84290344159891952d18c53eefe7", fp)
  793. }