4
0

client_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. package ca
  2. import (
  3. "bytes"
  4. "crypto/x509"
  5. "encoding/json"
  6. "encoding/pem"
  7. "fmt"
  8. "net/http"
  9. "net/http/httptest"
  10. "net/url"
  11. "reflect"
  12. "testing"
  13. "time"
  14. "github.com/smallstep/certificates/api"
  15. "github.com/smallstep/certificates/authority"
  16. )
  17. const (
  18. rootPEM = `-----BEGIN CERTIFICATE-----
  19. MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
  20. MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
  21. YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMT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TXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
  38. HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
  39. WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
  40. yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
  41. -----END CERTIFICATE-----`
  42. certPEM = `-----BEGIN CERTIFICATE-----
  43. MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE
  44. BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl
  45. cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMTI5MTMyNzQzWhcNMTQwNTI5MDAwMDAw
  46. WjBpMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN
  47. TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEYMBYGA1UEAwwPbWFp
  48. bC5nb29nbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfRrObuSW5T7q
  49. 5CnSEqefEmtH4CCv6+5EckuriNr1CjfVvqzwfAhopXkLrq45EQm8vkmf7W96XJhC
  50. 7ZM0dYi1/qOCAU8wggFLMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAa
  51. BgNVHREEEzARgg9tYWlsLmdvb2dsZS5jb20wCwYDVR0PBAQDAgeAMGgGCCsGAQUF
  52. BwEBBFwwWjArBggrBgEFBQcwAoYfaHR0cDovL3BraS5nb29nbGUuY29tL0dJQUcy
  53. LmNydDArBggrBgEFBQcwAYYfaHR0cDovL2NsaWVudHMxLmdvb2dsZS5jb20vb2Nz
  54. cDAdBgNVHQ4EFgQUiJxtimAuTfwb+aUtBn5UYKreKvMwDAYDVR0TAQH/BAIwADAf
  55. BgNVHSMEGDAWgBRK3QYWG7z2aLV29YG2u2IaulqBLzAXBgNVHSAEEDAOMAwGCisG
  56. AQQB1nkCBQEwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3BraS5nb29nbGUuY29t
  57. L0dJQUcyLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAH6RYHxHdcGpMpFE3oxDoFnP+
  58. gtuBCHan2yE2GRbJ2Cw8Lw0MmuKqHlf9RSeYfd3BXeKkj1qO6TVKwCh+0HdZk283
  59. TZZyzmEOyclm3UGFYe82P/iDFt+CeQ3NpmBg+GoaVCuWAARJN/KfglbLyyYygcQq
  60. 0SgeDh8dRKUiaW3HQSoYvTvdTuqzwK4CXsr3b5/dAOY8uMuG/IAR3FgwTbZ1dtoW
  61. RvOTa8hYiU6A475WuZKyEHcwnGYe57u2I2KbMgcKjPniocj4QzgYsVAVKW3IwaOh
  62. yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
  63. -----END CERTIFICATE-----`
  64. csrPEM = `-----BEGIN CERTIFICATE REQUEST-----
  65. MIIEYjCCAkoCAQAwHTEbMBkGA1UEAxMSdGVzdC5zbWFsbHN0ZXAuY29tMIICIjAN
  66. BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAuCpifZfoZhYNywfpnPa21NezXgtn
  67. wrWBFE6xhVzE7YDSIqtIsj8aR7R8zwEymxfv5j5298LUy/XSmItVH31CsKyfcGqN
  68. QM0PZr9XY3z5V6qchGMqjzt/jqlYMBHujcxIFBfz4HATxSgKyvHqvw14ESsS2huu
  69. 7jowx+XTKbFYgKcXrjBkvOej5FXD3ehkg0jDA2UAJNdfKmrc1BBEaaqOtfh7eyU2
  70. HU7+5gxH8C27IiCAmNj719E0B99Nu2MUw6aLFIM4xAcRga33Avevx6UuXZZIEepe
  71. V1sihrkcnDK9Vsxkme5erXzvAoOiRusiC2iIomJHJrdRM5ReEU+N+Tl1Kxq+rk7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yl8eE1+ZFOganixGwCtl4Tt
  88. DCbKzWTW8lqVdp9Kyf7XEhhc2R8C5w==
  89. -----END CERTIFICATE REQUEST-----`
  90. )
  91. func parseCertificate(data string) *x509.Certificate {
  92. block, _ := pem.Decode([]byte(data))
  93. if block == nil {
  94. panic("failed to parse certificate PEM")
  95. }
  96. cert, err := x509.ParseCertificate(block.Bytes)
  97. if err != nil {
  98. panic("failed to parse certificate: " + err.Error())
  99. }
  100. return cert
  101. }
  102. func parseCertificateRequest(data string) *x509.CertificateRequest {
  103. block, _ := pem.Decode([]byte(csrPEM))
  104. if block == nil {
  105. panic("failed to parse certificate request PEM")
  106. }
  107. csr, err := x509.ParseCertificateRequest(block.Bytes)
  108. if err != nil {
  109. panic("failed to parse certificate request: " + err.Error())
  110. }
  111. return csr
  112. }
  113. func equalJSON(t *testing.T, a interface{}, b interface{}) bool {
  114. if reflect.DeepEqual(a, b) {
  115. return true
  116. }
  117. ab, err := json.Marshal(a)
  118. if err != nil {
  119. t.Error(err)
  120. return false
  121. }
  122. bb, err := json.Marshal(b)
  123. if err != nil {
  124. t.Error(err)
  125. return false
  126. }
  127. return bytes.Equal(ab, bb)
  128. }
  129. func TestClient_Health(t *testing.T) {
  130. ok := &api.HealthResponse{Status: "ok"}
  131. nok := api.InternalServerError(fmt.Errorf("Internal Server Error"))
  132. tests := []struct {
  133. name string
  134. response interface{}
  135. responseCode int
  136. wantErr bool
  137. }{
  138. {"ok", ok, 200, false},
  139. {"not ok", nok, 500, true},
  140. }
  141. srv := httptest.NewServer(nil)
  142. defer srv.Close()
  143. for _, tt := range tests {
  144. t.Run(tt.name, func(t *testing.T) {
  145. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  146. if err != nil {
  147. t.Errorf("NewClient() error = %v", err)
  148. return
  149. }
  150. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  151. w.WriteHeader(tt.responseCode)
  152. api.JSON(w, tt.response)
  153. })
  154. got, err := c.Health()
  155. if (err != nil) != tt.wantErr {
  156. fmt.Printf("%+v", err)
  157. t.Errorf("Client.Health() error = %v, wantErr %v", err, tt.wantErr)
  158. return
  159. }
  160. switch {
  161. case err != nil:
  162. if got != nil {
  163. t.Errorf("Client.Health() = %v, want nil", got)
  164. }
  165. if !reflect.DeepEqual(err, tt.response) {
  166. t.Errorf("Client.Health() error = %v, want %v", err, tt.response)
  167. }
  168. default:
  169. if !reflect.DeepEqual(got, tt.response) {
  170. t.Errorf("Client.Health() = %v, want %v", got, tt.response)
  171. }
  172. }
  173. })
  174. }
  175. }
  176. func TestClient_Root(t *testing.T) {
  177. ok := &api.RootResponse{
  178. RootPEM: api.Certificate{Certificate: parseCertificate(rootPEM)},
  179. }
  180. notFound := api.NotFound(fmt.Errorf("Not Found"))
  181. tests := []struct {
  182. name string
  183. shasum string
  184. response interface{}
  185. responseCode int
  186. wantErr bool
  187. }{
  188. {"ok", "a047a37fa2d2e118a4f5095fe074d6cfe0e352425a7632bf8659c03919a6c81d", ok, 200, false},
  189. {"not found", "invalid", notFound, 404, true},
  190. }
  191. srv := httptest.NewServer(nil)
  192. defer srv.Close()
  193. for _, tt := range tests {
  194. t.Run(tt.name, func(t *testing.T) {
  195. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  196. if err != nil {
  197. t.Errorf("NewClient() error = %v", err)
  198. return
  199. }
  200. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  201. expected := "/root/" + tt.shasum
  202. if req.RequestURI != expected {
  203. t.Errorf("RequestURI = %s, want %s", req.RequestURI, expected)
  204. }
  205. w.WriteHeader(tt.responseCode)
  206. api.JSON(w, tt.response)
  207. })
  208. got, err := c.Root(tt.shasum)
  209. if (err != nil) != tt.wantErr {
  210. t.Errorf("Client.Root() error = %v, wantErr %v", err, tt.wantErr)
  211. return
  212. }
  213. switch {
  214. case err != nil:
  215. if got != nil {
  216. t.Errorf("Client.Root() = %v, want nil", got)
  217. }
  218. if !reflect.DeepEqual(err, tt.response) {
  219. t.Errorf("Client.Root() error = %v, want %v", err, tt.response)
  220. }
  221. default:
  222. if !reflect.DeepEqual(got, tt.response) {
  223. t.Errorf("Client.Root() = %v, want %v", got, tt.response)
  224. }
  225. }
  226. })
  227. }
  228. }
  229. func TestClient_Sign(t *testing.T) {
  230. ok := &api.SignResponse{
  231. ServerPEM: api.Certificate{Certificate: parseCertificate(certPEM)},
  232. CaPEM: api.Certificate{Certificate: parseCertificate(rootPEM)},
  233. }
  234. request := &api.SignRequest{
  235. CsrPEM: api.CertificateRequest{CertificateRequest: parseCertificateRequest(csrPEM)},
  236. OTT: "the-ott",
  237. NotBefore: time.Now(),
  238. NotAfter: time.Now().AddDate(0, 1, 0),
  239. }
  240. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  241. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  242. tests := []struct {
  243. name string
  244. request *api.SignRequest
  245. response interface{}
  246. responseCode int
  247. wantErr bool
  248. }{
  249. {"ok", request, ok, 200, false},
  250. {"unauthorized", request, unauthorized, 401, true},
  251. {"empty request", &api.SignRequest{}, badRequest, 403, true},
  252. {"nil request", nil, badRequest, 403, true},
  253. }
  254. srv := httptest.NewServer(nil)
  255. defer srv.Close()
  256. for _, tt := range tests {
  257. t.Run(tt.name, func(t *testing.T) {
  258. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  259. if err != nil {
  260. t.Errorf("NewClient() error = %v", err)
  261. return
  262. }
  263. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  264. body := new(api.SignRequest)
  265. if err := api.ReadJSON(req.Body, body); err != nil {
  266. api.WriteError(w, badRequest)
  267. return
  268. } else if !equalJSON(t, body, tt.request) {
  269. if tt.request == nil {
  270. if !reflect.DeepEqual(body, &api.SignRequest{}) {
  271. t.Errorf("Client.Sign() request = %v, wants %v", body, tt.request)
  272. }
  273. } else {
  274. t.Errorf("Client.Sign() request = %v, wants %v", body, tt.request)
  275. }
  276. }
  277. w.WriteHeader(tt.responseCode)
  278. api.JSON(w, tt.response)
  279. })
  280. got, err := c.Sign(tt.request)
  281. if (err != nil) != tt.wantErr {
  282. fmt.Printf("%+v", err)
  283. t.Errorf("Client.Sign() error = %v, wantErr %v", err, tt.wantErr)
  284. return
  285. }
  286. switch {
  287. case err != nil:
  288. if got != nil {
  289. t.Errorf("Client.Sign() = %v, want nil", got)
  290. }
  291. if !reflect.DeepEqual(err, tt.response) {
  292. t.Errorf("Client.Sign() error = %v, want %v", err, tt.response)
  293. }
  294. default:
  295. if !reflect.DeepEqual(got, tt.response) {
  296. t.Errorf("Client.Sign() = %v, want %v", got, tt.response)
  297. }
  298. }
  299. })
  300. }
  301. }
  302. func TestClient_Renew(t *testing.T) {
  303. ok := &api.SignResponse{
  304. ServerPEM: api.Certificate{Certificate: parseCertificate(certPEM)},
  305. CaPEM: api.Certificate{Certificate: parseCertificate(rootPEM)},
  306. }
  307. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  308. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  309. tests := []struct {
  310. name string
  311. response interface{}
  312. responseCode int
  313. wantErr bool
  314. }{
  315. {"ok", ok, 200, false},
  316. {"unauthorized", unauthorized, 401, true},
  317. {"empty request", badRequest, 403, true},
  318. {"nil request", badRequest, 403, true},
  319. }
  320. srv := httptest.NewServer(nil)
  321. defer srv.Close()
  322. for _, tt := range tests {
  323. t.Run(tt.name, func(t *testing.T) {
  324. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  325. if err != nil {
  326. t.Errorf("NewClient() error = %v", err)
  327. return
  328. }
  329. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  330. w.WriteHeader(tt.responseCode)
  331. api.JSON(w, tt.response)
  332. })
  333. got, err := c.Renew(nil)
  334. if (err != nil) != tt.wantErr {
  335. fmt.Printf("%+v", err)
  336. t.Errorf("Client.Renew() error = %v, wantErr %v", err, tt.wantErr)
  337. return
  338. }
  339. switch {
  340. case err != nil:
  341. if got != nil {
  342. t.Errorf("Client.Renew() = %v, want nil", got)
  343. }
  344. if !reflect.DeepEqual(err, tt.response) {
  345. t.Errorf("Client.Renew() error = %v, want %v", err, tt.response)
  346. }
  347. default:
  348. if !reflect.DeepEqual(got, tt.response) {
  349. t.Errorf("Client.Renew() = %v, want %v", got, tt.response)
  350. }
  351. }
  352. })
  353. }
  354. }
  355. func TestClient_Provisioners(t *testing.T) {
  356. ok := &api.ProvisionersResponse{
  357. Provisioners: []*authority.Provisioner{},
  358. }
  359. internalServerError := api.InternalServerError(fmt.Errorf("Internal Server Error"))
  360. tests := []struct {
  361. name string
  362. args []ProvisionerOption
  363. expectedURI string
  364. response interface{}
  365. responseCode int
  366. wantErr bool
  367. }{
  368. {"ok", nil, "/provisioners", ok, 200, false},
  369. {"ok with cursor", []ProvisionerOption{WithProvisionerCursor("abc")}, "/provisioners?cursor=abc", ok, 200, false},
  370. {"ok with limit", []ProvisionerOption{WithProvisionerLimit(10)}, "/provisioners?limit=10", ok, 200, false},
  371. {"ok with cursor+limit", []ProvisionerOption{WithProvisionerCursor("abc"), WithProvisionerLimit(10)}, "/provisioners?cursor=abc&limit=10", ok, 200, false},
  372. {"fail", nil, "/provisioners", internalServerError, 500, true},
  373. }
  374. srv := httptest.NewServer(nil)
  375. defer srv.Close()
  376. for _, tt := range tests {
  377. t.Run(tt.name, func(t *testing.T) {
  378. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  379. if err != nil {
  380. t.Errorf("NewClient() error = %v", err)
  381. return
  382. }
  383. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  384. if req.RequestURI != tt.expectedURI {
  385. t.Errorf("RequestURI = %s, want %s", req.RequestURI, tt.expectedURI)
  386. }
  387. w.WriteHeader(tt.responseCode)
  388. api.JSON(w, tt.response)
  389. })
  390. got, err := c.Provisioners(tt.args...)
  391. if (err != nil) != tt.wantErr {
  392. t.Errorf("Client.Provisioners() error = %v, wantErr %v", err, tt.wantErr)
  393. return
  394. }
  395. switch {
  396. case err != nil:
  397. if got != nil {
  398. t.Errorf("Client.Provisioners() = %v, want nil", got)
  399. }
  400. if !reflect.DeepEqual(err, tt.response) {
  401. t.Errorf("Client.Provisioners() error = %v, want %v", err, tt.response)
  402. }
  403. default:
  404. if !reflect.DeepEqual(got, tt.response) {
  405. t.Errorf("Client.Provisioners() = %v, want %v", got, tt.response)
  406. }
  407. }
  408. })
  409. }
  410. }
  411. func TestClient_ProvisionerKey(t *testing.T) {
  412. ok := &api.ProvisionerKeyResponse{
  413. Key: "an encrypted key",
  414. }
  415. notFound := api.NotFound(fmt.Errorf("Not Found"))
  416. tests := []struct {
  417. name string
  418. kid string
  419. response interface{}
  420. responseCode int
  421. wantErr bool
  422. }{
  423. {"ok", "kid", ok, 200, false},
  424. {"fail", "invalid", notFound, 500, true},
  425. }
  426. srv := httptest.NewServer(nil)
  427. defer srv.Close()
  428. for _, tt := range tests {
  429. t.Run(tt.name, func(t *testing.T) {
  430. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  431. if err != nil {
  432. t.Errorf("NewClient() error = %v", err)
  433. return
  434. }
  435. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  436. expected := "/provisioners/" + tt.kid + "/encrypted-key"
  437. if req.RequestURI != expected {
  438. t.Errorf("RequestURI = %s, want %s", req.RequestURI, expected)
  439. }
  440. w.WriteHeader(tt.responseCode)
  441. api.JSON(w, tt.response)
  442. })
  443. got, err := c.ProvisionerKey(tt.kid)
  444. if (err != nil) != tt.wantErr {
  445. t.Errorf("Client.ProvisionerKey() error = %v, wantErr %v", err, tt.wantErr)
  446. return
  447. }
  448. switch {
  449. case err != nil:
  450. if got != nil {
  451. t.Errorf("Client.ProvisionerKey() = %v, want nil", got)
  452. }
  453. if !reflect.DeepEqual(err, tt.response) {
  454. t.Errorf("Client.ProvisionerKey() error = %v, want %v", err, tt.response)
  455. }
  456. default:
  457. if !reflect.DeepEqual(got, tt.response) {
  458. t.Errorf("Client.ProvisionerKey() = %v, want %v", got, tt.response)
  459. }
  460. }
  461. })
  462. }
  463. }
  464. func TestClient_Roots(t *testing.T) {
  465. ok := &api.RootsResponse{
  466. Certificates: []api.Certificate{
  467. {Certificate: parseCertificate(rootPEM)},
  468. },
  469. }
  470. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  471. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  472. tests := []struct {
  473. name string
  474. response interface{}
  475. responseCode int
  476. wantErr bool
  477. }{
  478. {"ok", ok, 200, false},
  479. {"unauthorized", unauthorized, 401, true},
  480. {"empty request", badRequest, 403, true},
  481. {"nil request", badRequest, 403, true},
  482. }
  483. srv := httptest.NewServer(nil)
  484. defer srv.Close()
  485. for _, tt := range tests {
  486. t.Run(tt.name, func(t *testing.T) {
  487. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  488. if err != nil {
  489. t.Errorf("NewClient() error = %v", err)
  490. return
  491. }
  492. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  493. w.WriteHeader(tt.responseCode)
  494. api.JSON(w, tt.response)
  495. })
  496. got, err := c.Roots()
  497. if (err != nil) != tt.wantErr {
  498. fmt.Printf("%+v", err)
  499. t.Errorf("Client.Roots() error = %v, wantErr %v", err, tt.wantErr)
  500. return
  501. }
  502. switch {
  503. case err != nil:
  504. if got != nil {
  505. t.Errorf("Client.Roots() = %v, want nil", got)
  506. }
  507. if !reflect.DeepEqual(err, tt.response) {
  508. t.Errorf("Client.Roots() error = %v, want %v", err, tt.response)
  509. }
  510. default:
  511. if !reflect.DeepEqual(got, tt.response) {
  512. t.Errorf("Client.Roots() = %v, want %v", got, tt.response)
  513. }
  514. }
  515. })
  516. }
  517. }
  518. func TestClient_Federation(t *testing.T) {
  519. ok := &api.FederationResponse{
  520. Certificates: []api.Certificate{
  521. {Certificate: parseCertificate(rootPEM)},
  522. },
  523. }
  524. unauthorized := api.Unauthorized(fmt.Errorf("Unauthorized"))
  525. badRequest := api.BadRequest(fmt.Errorf("Bad Request"))
  526. tests := []struct {
  527. name string
  528. response interface{}
  529. responseCode int
  530. wantErr bool
  531. }{
  532. {"ok", ok, 200, false},
  533. {"unauthorized", unauthorized, 401, true},
  534. {"empty request", badRequest, 403, true},
  535. {"nil request", badRequest, 403, true},
  536. }
  537. srv := httptest.NewServer(nil)
  538. defer srv.Close()
  539. for _, tt := range tests {
  540. t.Run(tt.name, func(t *testing.T) {
  541. c, err := NewClient(srv.URL, WithTransport(http.DefaultTransport))
  542. if err != nil {
  543. t.Errorf("NewClient() error = %v", err)
  544. return
  545. }
  546. srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  547. w.WriteHeader(tt.responseCode)
  548. api.JSON(w, tt.response)
  549. })
  550. got, err := c.Federation()
  551. if (err != nil) != tt.wantErr {
  552. fmt.Printf("%+v", err)
  553. t.Errorf("Client.Federation() error = %v, wantErr %v", err, tt.wantErr)
  554. return
  555. }
  556. switch {
  557. case err != nil:
  558. if got != nil {
  559. t.Errorf("Client.Federation() = %v, want nil", got)
  560. }
  561. if !reflect.DeepEqual(err, tt.response) {
  562. t.Errorf("Client.Federation() error = %v, want %v", err, tt.response)
  563. }
  564. default:
  565. if !reflect.DeepEqual(got, tt.response) {
  566. t.Errorf("Client.Federation() = %v, want %v", got, tt.response)
  567. }
  568. }
  569. })
  570. }
  571. }
  572. func Test_parseEndpoint(t *testing.T) {
  573. expected1 := &url.URL{Scheme: "https", Host: "ca.smallstep.com"}
  574. expected2 := &url.URL{Scheme: "https", Host: "ca.smallstep.com", Path: "/1.0/sign"}
  575. type args struct {
  576. endpoint string
  577. }
  578. tests := []struct {
  579. name string
  580. args args
  581. want *url.URL
  582. wantErr bool
  583. }{
  584. {"ok", args{"https://ca.smallstep.com"}, expected1, false},
  585. {"ok no scheme", args{"//ca.smallstep.com"}, expected1, false},
  586. {"ok only host", args{"ca.smallstep.com"}, expected1, false},
  587. {"ok no bars", args{"https://ca.smallstep.com"}, expected1, false},
  588. {"ok schema, host and path", args{"https://ca.smallstep.com/1.0/sign"}, expected2, false},
  589. {"ok no bars with path", args{"https://ca.smallstep.com/1.0/sign"}, expected2, false},
  590. {"ok host and path", args{"ca.smallstep.com/1.0/sign"}, expected2, false},
  591. {"ok host and port", args{"ca.smallstep.com:443"}, &url.URL{Scheme: "https", Host: "ca.smallstep.com:443"}, false},
  592. {"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},
  593. {"fail bad url", args{"://ca.smallstep.com"}, nil, true},
  594. {"fail no host", args{"https://"}, nil, true},
  595. }
  596. for _, tt := range tests {
  597. t.Run(tt.name, func(t *testing.T) {
  598. got, err := parseEndpoint(tt.args.endpoint)
  599. if (err != nil) != tt.wantErr {
  600. t.Errorf("parseEndpoint() error = %v, wantErr %v", err, tt.wantErr)
  601. return
  602. }
  603. if !reflect.DeepEqual(got, tt.want) {
  604. t.Errorf("parseEndpoint() = %v, want %v", got, tt.want)
  605. }
  606. })
  607. }
  608. }