client_test.go 28 KB

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