4
0

api_test.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/dsa"
  6. "crypto/ecdsa"
  7. "crypto/elliptic"
  8. "crypto/rand"
  9. "crypto/rsa"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "crypto/x509/pkix"
  13. "encoding/json"
  14. "encoding/pem"
  15. "fmt"
  16. "io/ioutil"
  17. "math/big"
  18. "net/http"
  19. "net/http/httptest"
  20. "reflect"
  21. "strings"
  22. "testing"
  23. "time"
  24. "github.com/go-chi/chi"
  25. "github.com/pkg/errors"
  26. "github.com/smallstep/assert"
  27. "github.com/smallstep/certificates/authority"
  28. "github.com/smallstep/certificates/authority/provisioner"
  29. "github.com/smallstep/certificates/errs"
  30. "github.com/smallstep/certificates/logging"
  31. "github.com/smallstep/certificates/sshutil"
  32. "github.com/smallstep/certificates/templates"
  33. "github.com/smallstep/cli/crypto/tlsutil"
  34. "github.com/smallstep/cli/jose"
  35. "golang.org/x/crypto/ssh"
  36. )
  37. const (
  38. rootPEM = `-----BEGIN CERTIFICATE-----
  39. MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
  40. MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
  41. YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
  42. EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
  43. bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
  44. AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP
  45. VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv
  46. h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE
  47. ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ
  48. EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC
  49. DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7
  50. qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD
  51. VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g
  52. K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI
  53. KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n
  54. ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
  55. BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
  56. /iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
  57. zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
  58. HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
  59. WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
  60. yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
  61. -----END CERTIFICATE-----`
  62. certPEM = `-----BEGIN CERTIFICATE-----
  63. MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE
  64. BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl
  65. cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMTI5MTMyNzQzWhcNMTQwNTI5MDAwMDAw
  66. WjBpMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN
  67. TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEYMBYGA1UEAwwPbWFp
  68. bC5nb29nbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfRrObuSW5T7q
  69. 5CnSEqefEmtH4CCv6+5EckuriNr1CjfVvqzwfAhopXkLrq45EQm8vkmf7W96XJhC
  70. 7ZM0dYi1/qOCAU8wggFLMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAa
  71. BgNVHREEEzARgg9tYWlsLmdvb2dsZS5jb20wCwYDVR0PBAQDAgeAMGgGCCsGAQUF
  72. BwEBBFwwWjArBggrBgEFBQcwAoYfaHR0cDovL3BraS5nb29nbGUuY29tL0dJQUcy
  73. LmNydDArBggrBgEFBQcwAYYfaHR0cDovL2NsaWVudHMxLmdvb2dsZS5jb20vb2Nz
  74. cDAdBgNVHQ4EFgQUiJxtimAuTfwb+aUtBn5UYKreKvMwDAYDVR0TAQH/BAIwADAf
  75. BgNVHSMEGDAWgBRK3QYWG7z2aLV29YG2u2IaulqBLzAXBgNVHSAEEDAOMAwGCisG
  76. AQQB1nkCBQEwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3BraS5nb29nbGUuY29t
  77. L0dJQUcyLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAH6RYHxHdcGpMpFE3oxDoFnP+
  78. gtuBCHan2yE2GRbJ2Cw8Lw0MmuKqHlf9RSeYfd3BXeKkj1qO6TVKwCh+0HdZk283
  79. TZZyzmEOyclm3UGFYe82P/iDFt+CeQ3NpmBg+GoaVCuWAARJN/KfglbLyyYygcQq
  80. 0SgeDh8dRKUiaW3HQSoYvTvdTuqzwK4CXsr3b5/dAOY8uMuG/IAR3FgwTbZ1dtoW
  81. RvOTa8hYiU6A475WuZKyEHcwnGYe57u2I2KbMgcKjPniocj4QzgYsVAVKW3IwaOh
  82. yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
  83. -----END CERTIFICATE-----`
  84. csrPEM = `-----BEGIN CERTIFICATE REQUEST-----
  85. MIIEYjCCAkoCAQAwHTEbMBkGA1UEAxMSdGVzdC5zbWFsbHN0ZXAuY29tMIICIjAN
  86. BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAuCpifZfoZhYNywfpnPa21NezXgtn
  87. wrWBFE6xhVzE7YDSIqtIsj8aR7R8zwEymxfv5j5298LUy/XSmItVH31CsKyfcGqN
  88. QM0PZr9XY3z5V6qchGMqjzt/jqlYMBHujcxIFBfz4HATxSgKyvHqvw14ESsS2huu
  89. 7jowx+XTKbFYgKcXrjBkvOej5FXD3ehkg0jDA2UAJNdfKmrc1BBEaaqOtfh7eyU2
  90. HU7+5gxH8C27IiCAmNj719E0B99Nu2MUw6aLFIM4xAcRga33Avevx6UuXZZIEepe
  91. V1sihrkcnDK9Vsxkme5erXzvAoOiRusiC2iIomJHJrdRM5ReEU+N+Tl1Kxq+rk7H
  92. /qAq78wVm07M1/GGi9SUMObZS4WuJpM6whlikIAEbv9iV+CK0sv/Jr/AADdGMmQU
  93. lwk+Q0ZNE8p4ZuWILv/dtLDtDVBpnrrJ9e8duBtB0lGcG8MdaUCQ346EI4T0Sgx0
  94. hJ+wMq8zYYFfPIZEHC8o9p1ywWN9ySpJ8Zj/5ubmx9v2bY67GbuVFEa8iAp+S00x
  95. /Z8nD6/JsoKtexuHyGr3ixWFzlBqXDuugukIDFUOVDCbuGw4Io4/hEMu4Zz0TIFk
  96. Uu/wf2z75Tt8EkosKLu2wieKcY7n7Vhog/0tqexqWlWtJH0tvq4djsGoSvA62WPs
  97. 0iXXj+aZIARPNhECAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4ICAQA0vyHIndAkIs/I
  98. Nnz5yZWCokRjokoKv3Aj4VilyjncL+W0UIPULLU/47ZyoHVSUj2t8gknr9xu/Kd+
  99. g/2z0RiF3CIp8IUH49w/HYWaR95glzVNAAzr8qD9UbUqloLVQW3lObSRGtezhdZO
  100. sspw5dC+inhAb1LZhx8PVxB3SAeJ8h11IEBr0s2Hxt9viKKd7YPtIFZkZdOkVx4R
  101. if1DMawj1P6fEomf8z7m+dmbUYTqqosbCbRL01mzEga/kF6JyH/OzpNlcsAiyM8e
  102. BxPWH6TtPqwmyy4y7j1outmM0RnyUw5A0HmIbWh+rHpXiHVsnNqse0XfzmaxM8+z
  103. dxYeDax8aMWZKfvY1Zew+xIxl7DtEy1BpxrZcawumJYt5+LL+bwF/OtL0inQLnw8
  104. zyqydsXNdrpIQJnfmWPld7ThWbQw2FBE70+nFSxHeG2ULnpF3M9xf6ZNAF4gqaNE
  105. Q7vMNPBWrJWu+A++vHY61WGET+h4lY3GFr2I8OE4IiHPQi1D7Y0+fwOmStwuRPM4
  106. 2rARcJChNdiYBkkuvs4kixKTTjdXhB8RQtuBSrJ0M1tzq2qMbm7F8G01rOg4KlXU
  107. 58jHzJwr1K7cx0lpWfGTtc5bseCGtTKmDBXTziw04yl8eE1+ZFOganixGwCtl4Tt
  108. DCbKzWTW8lqVdp9Kyf7XEhhc2R8C5w==
  109. -----END CERTIFICATE REQUEST-----`
  110. stepCertPEM = `-----BEGIN CERTIFICATE-----
  111. MIIChTCCAiugAwIBAgIRAJ3O5T28Rdj2lr/UPjf+GAUwCgYIKoZIzj0EAwIwJDEi
  112. MCAGA1UEAxMZU21hbGxzdGVwIEludGVybWVkaWF0ZSBDQTAeFw0xOTAyMjAyMDE1
  113. NDNaFw0xOTAyMjEyMDE1NDNaMHExCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTEW
  114. MBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEcMBoGA1UEChMTU21hbGxzdGVwIExhYnMg
  115. SW5jLjEfMB0GA1UEAxMWaW50ZXJuYWwuc21hbGxzdGVwLmNvbTBZMBMGByqGSM49
  116. AgEGCCqGSM49AwEHA0IABC0aKrTNl+gXFuNkXisqX4/foLO3VMt+Kphngziim+fz
  117. aJhiS9JU+oFYLTNW6HWGUD8CNzfwrmWlVsAmiJwHKlKjgfAwge0wDgYDVR0PAQH/
  118. BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAdBgNVHQ4EFgQU
  119. JheKvlZqNv1IcgaC8WOS1Zg0i1QwHwYDVR0jBBgwFoAUu97PaFQPfuyKOeew7Hg4
  120. 5WFIAVMwIQYDVR0RBBowGIIWaW50ZXJuYWwuc21hbGxzdGVwLmNvbTBZBgwrBgEE
  121. AYKkZMYoQAEESTBHAgEBBBVtYXJpYW5vQHNtYWxsc3RlcC5jb20EK2pPMzdkdERi
  122. a3UtUW5hYnM1VlIwWXc2WUZGdjl3ZUExOGRwM2h0dmRFanMwCgYIKoZIzj0EAwID
  123. SAAwRQIhAIrn17fP5CBrGtKuhyPiq6eSwryBCf8ki+k17u5a+E/LAiB24Y2E0Put
  124. nIHOI54lAqDeF7A0y73fPRVCiJEWmuxz0g==
  125. -----END CERTIFICATE-----`
  126. pubKey = `{
  127. "use": "sig",
  128. "kty": "EC",
  129. "kid": "oV1p0MJeGQ7qBlK6B-oyfVdBRjh_e7VSK_YSEEqgW00",
  130. "crv": "P-256",
  131. "alg": "ES256",
  132. "x": "p9QX4tzjxUrB0fgqRWLKUuPolDtBW681f2Qyh-uVNhk",
  133. "y": "CNSEloc4oLDFTX0Vywj0WiqOlh516sFQwCj6WtM8LT8"
  134. }`
  135. privKey = "eyJhbGciOiJQQkVTMi1IUzI1NitBMTI4S1ciLCJjdHkiOiJqd2sranNvbiIsImVuYyI6IkEyNTZHQ00iLCJwMmMiOjEwMDAwMCwicDJzIjoiNEhBYjE0WDQ5OFM4LWxSb29JTnpqZyJ9.RbkJXGzI3kOsaP20KmZs0ELFLgpRddAE49AJHlEblw-uH_gg6SV3QA.M3MArEpHgI171lhm.gBlFySpzK9F7riBJbtLSNkb4nAw_gWokqs1jS-ZK1qxuqTK-9mtX5yILjRnftx9P9uFp5xt7rvv4Mgom1Ed4V9WtIyfNP_Cz3Pme1Eanp5nY68WCe_yG6iSB1RJdMDBUb2qBDZiBdhJim1DRXsOfgedOrNi7GGbppMlD77DEpId118owR5izA-c6Q_hg08hIE3tnMAnebDNQoF9jfEY99_AReVRH8G4hgwZEPCfXMTb3J-lowKGG4vXIbK5knFLh47SgOqG4M2M51SMS-XJ7oBz1Vjoamc90QIqKV51rvZ5m0N_sPFtxzcfV4E9yYH3XVd4O-CG4ydVKfKVyMtQ.mcKFZqBHp_n7Ytj2jz9rvw"
  136. )
  137. func parseCertificate(data string) *x509.Certificate {
  138. block, _ := pem.Decode([]byte(data))
  139. if block == nil {
  140. panic("failed to parse certificate PEM")
  141. }
  142. cert, err := x509.ParseCertificate(block.Bytes)
  143. if err != nil {
  144. panic("failed to parse certificate: " + err.Error())
  145. }
  146. return cert
  147. }
  148. func parseCertificateRequest(data string) *x509.CertificateRequest {
  149. block, _ := pem.Decode([]byte(data))
  150. if block == nil {
  151. panic("failed to parse certificate request PEM")
  152. }
  153. csr, err := x509.ParseCertificateRequest(block.Bytes)
  154. if err != nil {
  155. panic("failed to parse certificate request: " + err.Error())
  156. }
  157. return csr
  158. }
  159. func TestNewCertificate(t *testing.T) {
  160. cert := parseCertificate(rootPEM)
  161. if !reflect.DeepEqual(Certificate{Certificate: cert}, NewCertificate(cert)) {
  162. t.Errorf("NewCertificate failed, got %v, wants %v", NewCertificate(cert), Certificate{Certificate: cert})
  163. }
  164. }
  165. func TestCertificate_MarshalJSON(t *testing.T) {
  166. type fields struct {
  167. Certificate *x509.Certificate
  168. }
  169. tests := []struct {
  170. name string
  171. fields fields
  172. want []byte
  173. wantErr bool
  174. }{
  175. {"nil", fields{Certificate: nil}, []byte("null"), false},
  176. {"empty", fields{Certificate: &x509.Certificate{Raw: nil}}, []byte(`"-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n"`), false},
  177. {"root", fields{Certificate: parseCertificate(rootPEM)}, []byte(`"` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n"`), false},
  178. {"cert", fields{Certificate: parseCertificate(certPEM)}, []byte(`"` + strings.Replace(certPEM, "\n", `\n`, -1) + `\n"`), false},
  179. }
  180. for _, tt := range tests {
  181. t.Run(tt.name, func(t *testing.T) {
  182. c := Certificate{
  183. Certificate: tt.fields.Certificate,
  184. }
  185. got, err := c.MarshalJSON()
  186. if (err != nil) != tt.wantErr {
  187. t.Errorf("Certificate.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  188. return
  189. }
  190. if !reflect.DeepEqual(got, tt.want) {
  191. t.Errorf("Certificate.MarshalJSON() = %s, want %s", got, tt.want)
  192. }
  193. })
  194. }
  195. }
  196. func TestCertificate_UnmarshalJSON(t *testing.T) {
  197. tests := []struct {
  198. name string
  199. data []byte
  200. wantCert bool
  201. wantErr bool
  202. }{
  203. {"no data", nil, false, true},
  204. {"incomplete string 1", []byte(`"foobar`), false, true}, {"incomplete string 2", []byte(`foobar"`), false, true},
  205. {"invalid string", []byte(`"foobar"`), false, true},
  206. {"invalid bytes 0", []byte{}, false, true}, {"invalid bytes 1", []byte{1}, false, true},
  207. {"empty csr", []byte(`"-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE----\n"`), false, true},
  208. {"invalid type", []byte(`"` + strings.Replace(csrPEM, "\n", `\n`, -1) + `"`), false, true},
  209. {"empty string", []byte(`""`), false, false},
  210. {"json null", []byte(`null`), false, false},
  211. {"valid root", []byte(`"` + strings.Replace(rootPEM, "\n", `\n`, -1) + `"`), true, false},
  212. {"valid cert", []byte(`"` + strings.Replace(certPEM, "\n", `\n`, -1) + `"`), true, false},
  213. }
  214. for _, tt := range tests {
  215. t.Run(tt.name, func(t *testing.T) {
  216. var c Certificate
  217. if err := c.UnmarshalJSON(tt.data); (err != nil) != tt.wantErr {
  218. t.Errorf("Certificate.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  219. }
  220. if tt.wantCert && c.Certificate == nil {
  221. t.Error("Certificate.UnmarshalJSON() failed, Certificate is nil")
  222. }
  223. })
  224. }
  225. }
  226. func TestCertificate_UnmarshalJSON_json(t *testing.T) {
  227. tests := []struct {
  228. name string
  229. data string
  230. wantCert bool
  231. wantErr bool
  232. }{
  233. {"invalid type (bool)", `{"crt":true}`, false, true},
  234. {"invalid type (number)", `{"crt":123}`, false, true},
  235. {"invalid type (object)", `{"crt":{}}`, false, true},
  236. {"empty crt (null)", `{"crt":null}`, false, false},
  237. {"empty crt (string)", `{"crt":""}`, false, false},
  238. {"empty crt", `{"crt":"-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE----\n"}`, false, true},
  239. {"valid crt", `{"crt":"` + strings.Replace(certPEM, "\n", `\n`, -1) + `"}`, true, false},
  240. }
  241. type request struct {
  242. Cert Certificate `json:"crt"`
  243. }
  244. for _, tt := range tests {
  245. t.Run(tt.name, func(t *testing.T) {
  246. var body request
  247. if err := json.Unmarshal([]byte(tt.data), &body); (err != nil) != tt.wantErr {
  248. t.Errorf("json.Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
  249. }
  250. switch tt.wantCert {
  251. case true:
  252. if body.Cert.Certificate == nil {
  253. t.Error("json.Unmarshal() failed, Certificate is nil")
  254. }
  255. case false:
  256. if body.Cert.Certificate != nil {
  257. t.Error("json.Unmarshal() failed, Certificate is not nil")
  258. }
  259. }
  260. })
  261. }
  262. }
  263. func TestNewCertificateRequest(t *testing.T) {
  264. csr := parseCertificateRequest(csrPEM)
  265. if !reflect.DeepEqual(CertificateRequest{CertificateRequest: csr}, NewCertificateRequest(csr)) {
  266. t.Errorf("NewCertificateRequest failed, got %v, wants %v", NewCertificateRequest(csr), CertificateRequest{CertificateRequest: csr})
  267. }
  268. }
  269. func TestCertificateRequest_MarshalJSON(t *testing.T) {
  270. type fields struct {
  271. CertificateRequest *x509.CertificateRequest
  272. }
  273. tests := []struct {
  274. name string
  275. fields fields
  276. want []byte
  277. wantErr bool
  278. }{
  279. {"nil", fields{CertificateRequest: nil}, []byte("null"), false},
  280. {"empty", fields{CertificateRequest: &x509.CertificateRequest{}}, []byte(`"-----BEGIN CERTIFICATE REQUEST-----\n-----END CERTIFICATE REQUEST-----\n"`), false},
  281. {"csr", fields{CertificateRequest: parseCertificateRequest(csrPEM)}, []byte(`"` + strings.Replace(csrPEM, "\n", `\n`, -1) + `\n"`), false},
  282. }
  283. for _, tt := range tests {
  284. t.Run(tt.name, func(t *testing.T) {
  285. c := CertificateRequest{
  286. CertificateRequest: tt.fields.CertificateRequest,
  287. }
  288. got, err := c.MarshalJSON()
  289. if (err != nil) != tt.wantErr {
  290. t.Errorf("CertificateRequest.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  291. return
  292. }
  293. if !reflect.DeepEqual(got, tt.want) {
  294. t.Errorf("CertificateRequest.MarshalJSON() = %s, want %s", got, tt.want)
  295. }
  296. })
  297. }
  298. }
  299. func TestCertificateRequest_UnmarshalJSON(t *testing.T) {
  300. tests := []struct {
  301. name string
  302. data []byte
  303. wantCert bool
  304. wantErr bool
  305. }{
  306. {"no data", nil, false, true},
  307. {"incomplete string 1", []byte(`"foobar`), false, true}, {"incomplete string 2", []byte(`foobar"`), false, true},
  308. {"invalid string", []byte(`"foobar"`), false, true},
  309. {"invalid bytes 0", []byte{}, false, true}, {"invalid bytes 1", []byte{1}, false, true},
  310. {"empty csr", []byte(`"-----BEGIN CERTIFICATE REQUEST-----\n-----END CERTIFICATE REQUEST----\n"`), false, true},
  311. {"invalid type", []byte(`"` + strings.Replace(rootPEM, "\n", `\n`, -1) + `"`), false, true},
  312. {"empty string", []byte(`""`), false, false},
  313. {"json null", []byte(`null`), false, false},
  314. {"valid csr", []byte(`"` + strings.Replace(csrPEM, "\n", `\n`, -1) + `"`), true, false},
  315. }
  316. for _, tt := range tests {
  317. t.Run(tt.name, func(t *testing.T) {
  318. var c CertificateRequest
  319. if err := c.UnmarshalJSON(tt.data); (err != nil) != tt.wantErr {
  320. t.Errorf("CertificateRequest.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  321. }
  322. if tt.wantCert && c.CertificateRequest == nil {
  323. t.Error("CertificateRequest.UnmarshalJSON() failed, CertificateRequet is nil")
  324. }
  325. })
  326. }
  327. }
  328. func TestCertificateRequest_UnmarshalJSON_json(t *testing.T) {
  329. tests := []struct {
  330. name string
  331. data string
  332. wantCert bool
  333. wantErr bool
  334. }{
  335. {"invalid type (bool)", `{"csr":true}`, false, true},
  336. {"invalid type (number)", `{"csr":123}`, false, true},
  337. {"invalid type (object)", `{"csr":{}}`, false, true},
  338. {"empty csr (null)", `{"csr":null}`, false, false},
  339. {"empty csr (string)", `{"csr":""}`, false, false},
  340. {"empty csr", `{"csr":"-----BEGIN CERTIFICATE REQUEST-----\n-----END CERTIFICATE REQUEST----\n"}`, false, true},
  341. {"valid csr", `{"csr":"` + strings.Replace(csrPEM, "\n", `\n`, -1) + `"}`, true, false},
  342. }
  343. type request struct {
  344. CSR CertificateRequest `json:"csr"`
  345. }
  346. for _, tt := range tests {
  347. t.Run(tt.name, func(t *testing.T) {
  348. var body request
  349. if err := json.Unmarshal([]byte(tt.data), &body); (err != nil) != tt.wantErr {
  350. t.Errorf("json.Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
  351. }
  352. switch tt.wantCert {
  353. case true:
  354. if body.CSR.CertificateRequest == nil {
  355. t.Error("json.Unmarshal() failed, CertificateRequest is nil")
  356. }
  357. case false:
  358. if body.CSR.CertificateRequest != nil {
  359. t.Error("json.Unmarshal() failed, CertificateRequest is not nil")
  360. }
  361. }
  362. })
  363. }
  364. }
  365. func TestSignRequest_Validate(t *testing.T) {
  366. csr := parseCertificateRequest(csrPEM)
  367. bad := parseCertificateRequest(csrPEM)
  368. bad.Signature[0]++
  369. type fields struct {
  370. CsrPEM CertificateRequest
  371. OTT string
  372. NotBefore time.Time
  373. NotAfter time.Time
  374. }
  375. tests := []struct {
  376. name string
  377. fields fields
  378. err error
  379. }{
  380. {"missing csr", fields{CertificateRequest{}, "foobarzar", time.Time{}, time.Time{}}, errors.New("missing csr")},
  381. {"invalid csr", fields{CertificateRequest{bad}, "foobarzar", time.Time{}, time.Time{}}, errors.New("invalid csr")},
  382. {"missing ott", fields{CertificateRequest{csr}, "", time.Time{}, time.Time{}}, errors.New("missing ott")},
  383. }
  384. for _, tt := range tests {
  385. t.Run(tt.name, func(t *testing.T) {
  386. s := &SignRequest{
  387. CsrPEM: tt.fields.CsrPEM,
  388. OTT: tt.fields.OTT,
  389. NotAfter: NewTimeDuration(tt.fields.NotAfter),
  390. NotBefore: NewTimeDuration(tt.fields.NotBefore),
  391. }
  392. if err := s.Validate(); err != nil {
  393. if assert.NotNil(t, tt.err) {
  394. assert.HasPrefix(t, err.Error(), tt.err.Error())
  395. }
  396. } else {
  397. assert.Nil(t, tt.err)
  398. }
  399. })
  400. }
  401. }
  402. type mockProvisioner struct {
  403. ret1, ret2, ret3 interface{}
  404. err error
  405. getID func() string
  406. getTokenID func(string) (string, error)
  407. getName func() string
  408. getType func() provisioner.Type
  409. getEncryptedKey func() (string, string, bool)
  410. init func(provisioner.Config) error
  411. authorizeRenew func(ctx context.Context, cert *x509.Certificate) error
  412. authorizeRevoke func(ctx context.Context, token string) error
  413. authorizeSign func(ctx context.Context, ott string) ([]provisioner.SignOption, error)
  414. authorizeRenewal func(*x509.Certificate) error
  415. authorizeSSHSign func(ctx context.Context, token string) ([]provisioner.SignOption, error)
  416. authorizeSSHRevoke func(ctx context.Context, token string) error
  417. authorizeSSHRenew func(ctx context.Context, token string) (*ssh.Certificate, error)
  418. authorizeSSHRekey func(ctx context.Context, token string) (*ssh.Certificate, []provisioner.SignOption, error)
  419. }
  420. func (m *mockProvisioner) GetID() string {
  421. if m.getID != nil {
  422. return m.getID()
  423. }
  424. return m.ret1.(string)
  425. }
  426. func (m *mockProvisioner) GetTokenID(token string) (string, error) {
  427. if m.getTokenID != nil {
  428. return m.getTokenID(token)
  429. }
  430. if m.ret1 == nil {
  431. return "", m.err
  432. }
  433. return m.ret1.(string), m.err
  434. }
  435. func (m *mockProvisioner) GetName() string {
  436. if m.getName != nil {
  437. return m.getName()
  438. }
  439. return m.ret1.(string)
  440. }
  441. func (m *mockProvisioner) GetType() provisioner.Type {
  442. if m.getType != nil {
  443. return m.getType()
  444. }
  445. return m.ret1.(provisioner.Type)
  446. }
  447. func (m *mockProvisioner) GetEncryptedKey() (string, string, bool) {
  448. if m.getEncryptedKey != nil {
  449. return m.getEncryptedKey()
  450. }
  451. return m.ret1.(string), m.ret2.(string), m.ret3.(bool)
  452. }
  453. func (m *mockProvisioner) Init(c provisioner.Config) error {
  454. if m.init != nil {
  455. return m.init(c)
  456. }
  457. return m.err
  458. }
  459. func (m *mockProvisioner) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  460. if m.authorizeRenew != nil {
  461. return m.authorizeRenew(ctx, cert)
  462. }
  463. return m.err
  464. }
  465. func (m *mockProvisioner) AuthorizeRevoke(ctx context.Context, token string) error {
  466. if m.authorizeRevoke != nil {
  467. return m.authorizeRevoke(ctx, token)
  468. }
  469. return m.err
  470. }
  471. func (m *mockProvisioner) AuthorizeSign(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
  472. if m.authorizeSign != nil {
  473. return m.authorizeSign(ctx, ott)
  474. }
  475. return m.ret1.([]provisioner.SignOption), m.err
  476. }
  477. func (m *mockProvisioner) AuthorizeRenewal(c *x509.Certificate) error {
  478. if m.authorizeRenewal != nil {
  479. return m.authorizeRenewal(c)
  480. }
  481. return m.err
  482. }
  483. func (m *mockProvisioner) AuthorizeSSHSign(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  484. if m.authorizeSSHSign != nil {
  485. return m.authorizeSSHSign(ctx, token)
  486. }
  487. return m.ret1.([]provisioner.SignOption), m.err
  488. }
  489. func (m *mockProvisioner) AuthorizeSSHRevoke(ctx context.Context, token string) error {
  490. if m.authorizeSSHRevoke != nil {
  491. return m.authorizeSSHRevoke(ctx, token)
  492. }
  493. return m.err
  494. }
  495. func (m *mockProvisioner) AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  496. if m.authorizeSSHRenew != nil {
  497. return m.authorizeSSHRenew(ctx, token)
  498. }
  499. return m.ret1.(*ssh.Certificate), m.err
  500. }
  501. func (m *mockProvisioner) AuthorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []provisioner.SignOption, error) {
  502. if m.authorizeSSHRekey != nil {
  503. return m.authorizeSSHRekey(ctx, token)
  504. }
  505. return m.ret1.(*ssh.Certificate), m.ret2.([]provisioner.SignOption), m.err
  506. }
  507. type mockAuthority struct {
  508. ret1, ret2 interface{}
  509. err error
  510. authorizeSign func(ott string) ([]provisioner.SignOption, error)
  511. getTLSOptions func() *tlsutil.TLSOptions
  512. root func(shasum string) (*x509.Certificate, error)
  513. sign func(cr *x509.CertificateRequest, opts provisioner.Options, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
  514. renew func(cert *x509.Certificate) ([]*x509.Certificate, error)
  515. loadProvisionerByCertificate func(cert *x509.Certificate) (provisioner.Interface, error)
  516. loadProvisionerByID func(provID string) (provisioner.Interface, error)
  517. getProvisioners func(nextCursor string, limit int) (provisioner.List, string, error)
  518. revoke func(context.Context, *authority.RevokeOptions) error
  519. getEncryptedKey func(kid string) (string, error)
  520. getRoots func() ([]*x509.Certificate, error)
  521. getFederation func() ([]*x509.Certificate, error)
  522. signSSH func(ctx context.Context, key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  523. signSSHAddUser func(ctx context.Context, key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error)
  524. renewSSH func(ctx context.Context, cert *ssh.Certificate) (*ssh.Certificate, error)
  525. rekeySSH func(ctx context.Context, cert *ssh.Certificate, key ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  526. getSSHHosts func(ctx context.Context, cert *x509.Certificate) ([]sshutil.Host, error)
  527. getSSHRoots func(ctx context.Context) (*authority.SSHKeys, error)
  528. getSSHFederation func(ctx context.Context) (*authority.SSHKeys, error)
  529. getSSHConfig func(ctx context.Context, typ string, data map[string]string) ([]templates.Output, error)
  530. checkSSHHost func(ctx context.Context, principal, token string) (bool, error)
  531. getSSHBastion func(ctx context.Context, user string, hostname string) (*authority.Bastion, error)
  532. version func() authority.Version
  533. }
  534. // TODO: remove once Authorize is deprecated.
  535. func (m *mockAuthority) Authorize(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
  536. return m.AuthorizeSign(ott)
  537. }
  538. func (m *mockAuthority) AuthorizeSign(ott string) ([]provisioner.SignOption, error) {
  539. if m.authorizeSign != nil {
  540. return m.authorizeSign(ott)
  541. }
  542. return m.ret1.([]provisioner.SignOption), m.err
  543. }
  544. func (m *mockAuthority) GetTLSOptions() *tlsutil.TLSOptions {
  545. if m.getTLSOptions != nil {
  546. return m.getTLSOptions()
  547. }
  548. return m.ret1.(*tlsutil.TLSOptions)
  549. }
  550. func (m *mockAuthority) Root(shasum string) (*x509.Certificate, error) {
  551. if m.root != nil {
  552. return m.root(shasum)
  553. }
  554. return m.ret1.(*x509.Certificate), m.err
  555. }
  556. func (m *mockAuthority) Sign(cr *x509.CertificateRequest, opts provisioner.Options, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  557. if m.sign != nil {
  558. return m.sign(cr, opts, signOpts...)
  559. }
  560. return []*x509.Certificate{m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate)}, m.err
  561. }
  562. func (m *mockAuthority) Renew(cert *x509.Certificate) ([]*x509.Certificate, error) {
  563. if m.renew != nil {
  564. return m.renew(cert)
  565. }
  566. return []*x509.Certificate{m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate)}, m.err
  567. }
  568. func (m *mockAuthority) GetProvisioners(nextCursor string, limit int) (provisioner.List, string, error) {
  569. if m.getProvisioners != nil {
  570. return m.getProvisioners(nextCursor, limit)
  571. }
  572. return m.ret1.(provisioner.List), m.ret2.(string), m.err
  573. }
  574. func (m *mockAuthority) LoadProvisionerByCertificate(cert *x509.Certificate) (provisioner.Interface, error) {
  575. if m.loadProvisionerByCertificate != nil {
  576. return m.loadProvisionerByCertificate(cert)
  577. }
  578. return m.ret1.(provisioner.Interface), m.err
  579. }
  580. func (m *mockAuthority) LoadProvisionerByID(provID string) (provisioner.Interface, error) {
  581. if m.loadProvisionerByID != nil {
  582. return m.loadProvisionerByID(provID)
  583. }
  584. return m.ret1.(provisioner.Interface), m.err
  585. }
  586. func (m *mockAuthority) Revoke(ctx context.Context, opts *authority.RevokeOptions) error {
  587. if m.revoke != nil {
  588. return m.revoke(ctx, opts)
  589. }
  590. return m.err
  591. }
  592. func (m *mockAuthority) GetEncryptedKey(kid string) (string, error) {
  593. if m.getEncryptedKey != nil {
  594. return m.getEncryptedKey(kid)
  595. }
  596. return m.ret1.(string), m.err
  597. }
  598. func (m *mockAuthority) GetRoots() ([]*x509.Certificate, error) {
  599. if m.getRoots != nil {
  600. return m.getRoots()
  601. }
  602. return m.ret1.([]*x509.Certificate), m.err
  603. }
  604. func (m *mockAuthority) GetFederation() ([]*x509.Certificate, error) {
  605. if m.getFederation != nil {
  606. return m.getFederation()
  607. }
  608. return m.ret1.([]*x509.Certificate), m.err
  609. }
  610. func (m *mockAuthority) SignSSH(ctx context.Context, key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  611. if m.signSSH != nil {
  612. return m.signSSH(ctx, key, opts, signOpts...)
  613. }
  614. return m.ret1.(*ssh.Certificate), m.err
  615. }
  616. func (m *mockAuthority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error) {
  617. if m.signSSHAddUser != nil {
  618. return m.signSSHAddUser(ctx, key, cert)
  619. }
  620. return m.ret1.(*ssh.Certificate), m.err
  621. }
  622. func (m *mockAuthority) RenewSSH(ctx context.Context, cert *ssh.Certificate) (*ssh.Certificate, error) {
  623. if m.renewSSH != nil {
  624. return m.renewSSH(ctx, cert)
  625. }
  626. return m.ret1.(*ssh.Certificate), m.err
  627. }
  628. func (m *mockAuthority) RekeySSH(ctx context.Context, cert *ssh.Certificate, key ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  629. if m.rekeySSH != nil {
  630. return m.rekeySSH(ctx, cert, key, signOpts...)
  631. }
  632. return m.ret1.(*ssh.Certificate), m.err
  633. }
  634. func (m *mockAuthority) GetSSHHosts(ctx context.Context, cert *x509.Certificate) ([]sshutil.Host, error) {
  635. if m.getSSHHosts != nil {
  636. return m.getSSHHosts(ctx, cert)
  637. }
  638. return m.ret1.([]sshutil.Host), m.err
  639. }
  640. func (m *mockAuthority) GetSSHRoots(ctx context.Context) (*authority.SSHKeys, error) {
  641. if m.getSSHRoots != nil {
  642. return m.getSSHRoots(ctx)
  643. }
  644. return m.ret1.(*authority.SSHKeys), m.err
  645. }
  646. func (m *mockAuthority) GetSSHFederation(ctx context.Context) (*authority.SSHKeys, error) {
  647. if m.getSSHFederation != nil {
  648. return m.getSSHFederation(ctx)
  649. }
  650. return m.ret1.(*authority.SSHKeys), m.err
  651. }
  652. func (m *mockAuthority) GetSSHConfig(ctx context.Context, typ string, data map[string]string) ([]templates.Output, error) {
  653. if m.getSSHConfig != nil {
  654. return m.getSSHConfig(ctx, typ, data)
  655. }
  656. return m.ret1.([]templates.Output), m.err
  657. }
  658. func (m *mockAuthority) CheckSSHHost(ctx context.Context, principal, token string) (bool, error) {
  659. if m.checkSSHHost != nil {
  660. return m.checkSSHHost(ctx, principal, token)
  661. }
  662. return m.ret1.(bool), m.err
  663. }
  664. func (m *mockAuthority) GetSSHBastion(ctx context.Context, user string, hostname string) (*authority.Bastion, error) {
  665. if m.getSSHBastion != nil {
  666. return m.getSSHBastion(ctx, user, hostname)
  667. }
  668. return m.ret1.(*authority.Bastion), m.err
  669. }
  670. func (m *mockAuthority) Version() authority.Version {
  671. if m.version != nil {
  672. return m.version()
  673. }
  674. return m.ret1.(authority.Version)
  675. }
  676. func Test_caHandler_Route(t *testing.T) {
  677. type fields struct {
  678. Authority Authority
  679. }
  680. type args struct {
  681. r Router
  682. }
  683. tests := []struct {
  684. name string
  685. fields fields
  686. args args
  687. }{
  688. {"ok", fields{&mockAuthority{}}, args{chi.NewRouter()}},
  689. }
  690. for _, tt := range tests {
  691. t.Run(tt.name, func(t *testing.T) {
  692. h := &caHandler{
  693. Authority: tt.fields.Authority,
  694. }
  695. h.Route(tt.args.r)
  696. })
  697. }
  698. }
  699. func Test_caHandler_Health(t *testing.T) {
  700. req := httptest.NewRequest("GET", "http://example.com/health", nil)
  701. w := httptest.NewRecorder()
  702. h := New(&mockAuthority{}).(*caHandler)
  703. h.Health(w, req)
  704. res := w.Result()
  705. if res.StatusCode != 200 {
  706. t.Errorf("caHandler.Health StatusCode = %d, wants 200", res.StatusCode)
  707. }
  708. body, err := ioutil.ReadAll(res.Body)
  709. res.Body.Close()
  710. if err != nil {
  711. t.Errorf("caHandler.Health unexpected error = %v", err)
  712. }
  713. expected := []byte("{\"status\":\"ok\"}\n")
  714. if !bytes.Equal(body, expected) {
  715. t.Errorf("caHandler.Health Body = %s, wants %s", body, expected)
  716. }
  717. }
  718. func Test_caHandler_Root(t *testing.T) {
  719. tests := []struct {
  720. name string
  721. root *x509.Certificate
  722. err error
  723. statusCode int
  724. }{
  725. {"ok", parseCertificate(rootPEM), nil, 200},
  726. {"fail", nil, fmt.Errorf("not found"), 404},
  727. }
  728. // Request with chi context
  729. chiCtx := chi.NewRouteContext()
  730. chiCtx.URLParams.Add("sha", "efc7d6b475a56fe587650bcdb999a4a308f815ba44db4bf0371ea68a786ccd36")
  731. req := httptest.NewRequest("GET", "http://example.com/root/efc7d6b475a56fe587650bcdb999a4a308f815ba44db4bf0371ea68a786ccd36", nil)
  732. req = req.WithContext(context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx))
  733. expected := []byte(`{"ca":"` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n"}`)
  734. for _, tt := range tests {
  735. t.Run(tt.name, func(t *testing.T) {
  736. h := New(&mockAuthority{ret1: tt.root, err: tt.err}).(*caHandler)
  737. w := httptest.NewRecorder()
  738. h.Root(w, req)
  739. res := w.Result()
  740. if res.StatusCode != tt.statusCode {
  741. t.Errorf("caHandler.Root StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  742. }
  743. body, err := ioutil.ReadAll(res.Body)
  744. res.Body.Close()
  745. if err != nil {
  746. t.Errorf("caHandler.Root unexpected error = %v", err)
  747. }
  748. if tt.statusCode == 200 {
  749. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  750. t.Errorf("caHandler.Root Body = %s, wants %s", body, expected)
  751. }
  752. }
  753. })
  754. }
  755. }
  756. func Test_caHandler_Sign(t *testing.T) {
  757. csr := parseCertificateRequest(csrPEM)
  758. valid, err := json.Marshal(SignRequest{
  759. CsrPEM: CertificateRequest{csr},
  760. OTT: "foobarzar",
  761. })
  762. if err != nil {
  763. t.Fatal(err)
  764. }
  765. invalid, err := json.Marshal(SignRequest{
  766. CsrPEM: CertificateRequest{csr},
  767. OTT: "",
  768. })
  769. if err != nil {
  770. t.Fatal(err)
  771. }
  772. expected1 := []byte(`{"crt":"` + strings.Replace(certPEM, "\n", `\n`, -1) + `\n","ca":"` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n","certChain":["` + strings.Replace(certPEM, "\n", `\n`, -1) + `\n","` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n"]}`)
  773. expected2 := []byte(`{"crt":"` + strings.Replace(stepCertPEM, "\n", `\n`, -1) + `\n","ca":"` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n","certChain":["` + strings.Replace(stepCertPEM, "\n", `\n`, -1) + `\n","` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n"]}`)
  774. tests := []struct {
  775. name string
  776. input string
  777. certAttrOpts []provisioner.SignOption
  778. autherr error
  779. cert *x509.Certificate
  780. root *x509.Certificate
  781. signErr error
  782. statusCode int
  783. expected []byte
  784. }{
  785. {"ok", string(valid), nil, nil, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated, expected1},
  786. {"ok with Provisioner", string(valid), nil, nil, parseCertificate(stepCertPEM), parseCertificate(rootPEM), nil, http.StatusCreated, expected2},
  787. {"json read error", "{", nil, nil, nil, nil, nil, http.StatusBadRequest, nil},
  788. {"validate error", string(invalid), nil, nil, nil, nil, nil, http.StatusBadRequest, nil},
  789. {"authorize error", string(valid), nil, fmt.Errorf("an error"), nil, nil, nil, http.StatusUnauthorized, nil},
  790. {"sign error", string(valid), nil, nil, nil, nil, fmt.Errorf("an error"), http.StatusForbidden, nil},
  791. }
  792. for _, tt := range tests {
  793. t.Run(tt.name, func(t *testing.T) {
  794. h := New(&mockAuthority{
  795. ret1: tt.cert, ret2: tt.root, err: tt.signErr,
  796. authorizeSign: func(ott string) ([]provisioner.SignOption, error) {
  797. return tt.certAttrOpts, tt.autherr
  798. },
  799. getTLSOptions: func() *tlsutil.TLSOptions {
  800. return nil
  801. },
  802. }).(*caHandler)
  803. req := httptest.NewRequest("POST", "http://example.com/sign", strings.NewReader(tt.input))
  804. w := httptest.NewRecorder()
  805. h.Sign(logging.NewResponseLogger(w), req)
  806. res := w.Result()
  807. if res.StatusCode != tt.statusCode {
  808. t.Errorf("caHandler.Root StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  809. }
  810. body, err := ioutil.ReadAll(res.Body)
  811. res.Body.Close()
  812. if err != nil {
  813. t.Errorf("caHandler.Root unexpected error = %v", err)
  814. }
  815. if tt.statusCode < http.StatusBadRequest {
  816. if !bytes.Equal(bytes.TrimSpace(body), tt.expected) {
  817. t.Errorf("caHandler.Root Body = %s, wants %s", body, tt.expected)
  818. }
  819. }
  820. })
  821. }
  822. }
  823. func Test_caHandler_Renew(t *testing.T) {
  824. cs := &tls.ConnectionState{
  825. PeerCertificates: []*x509.Certificate{parseCertificate(certPEM)},
  826. }
  827. tests := []struct {
  828. name string
  829. tls *tls.ConnectionState
  830. cert *x509.Certificate
  831. root *x509.Certificate
  832. err error
  833. statusCode int
  834. }{
  835. {"ok", cs, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  836. {"no tls", nil, nil, nil, nil, http.StatusBadRequest},
  837. {"no peer certificates", &tls.ConnectionState{}, nil, nil, nil, http.StatusBadRequest},
  838. {"renew error", cs, nil, nil, errs.Forbidden("an error"), http.StatusForbidden},
  839. }
  840. expected := []byte(`{"crt":"` + strings.Replace(certPEM, "\n", `\n`, -1) + `\n","ca":"` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n","certChain":["` + strings.Replace(certPEM, "\n", `\n`, -1) + `\n","` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n"]}`)
  841. for _, tt := range tests {
  842. t.Run(tt.name, func(t *testing.T) {
  843. h := New(&mockAuthority{
  844. ret1: tt.cert, ret2: tt.root, err: tt.err,
  845. getTLSOptions: func() *tlsutil.TLSOptions {
  846. return nil
  847. },
  848. }).(*caHandler)
  849. req := httptest.NewRequest("POST", "http://example.com/renew", nil)
  850. req.TLS = tt.tls
  851. w := httptest.NewRecorder()
  852. h.Renew(logging.NewResponseLogger(w), req)
  853. res := w.Result()
  854. if res.StatusCode != tt.statusCode {
  855. t.Errorf("caHandler.Renew StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  856. }
  857. body, err := ioutil.ReadAll(res.Body)
  858. res.Body.Close()
  859. if err != nil {
  860. t.Errorf("caHandler.Renew unexpected error = %v", err)
  861. }
  862. if tt.statusCode < http.StatusBadRequest {
  863. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  864. t.Errorf("caHandler.Root Body = %s, wants %s", body, expected)
  865. }
  866. }
  867. })
  868. }
  869. }
  870. func Test_caHandler_Provisioners(t *testing.T) {
  871. type fields struct {
  872. Authority Authority
  873. }
  874. type args struct {
  875. w http.ResponseWriter
  876. r *http.Request
  877. }
  878. req, err := http.NewRequest("GET", "http://example.com/provisioners?cursor=foo&limit=20", nil)
  879. if err != nil {
  880. t.Fatal(err)
  881. }
  882. reqLimitFail, err := http.NewRequest("GET", "http://example.com/provisioners?limit=abc", nil)
  883. if err != nil {
  884. t.Fatal(err)
  885. }
  886. var key jose.JSONWebKey
  887. if err := json.Unmarshal([]byte(pubKey), &key); err != nil {
  888. t.Fatal(err)
  889. }
  890. p := provisioner.List{
  891. &provisioner.JWK{
  892. Type: "JWK",
  893. Name: "max",
  894. EncryptedKey: "abc",
  895. Key: &key,
  896. },
  897. &provisioner.JWK{
  898. Type: "JWK",
  899. Name: "mariano",
  900. EncryptedKey: "def",
  901. Key: &key,
  902. },
  903. }
  904. pr := ProvisionersResponse{
  905. Provisioners: p,
  906. }
  907. tests := []struct {
  908. name string
  909. fields fields
  910. args args
  911. statusCode int
  912. }{
  913. {"ok", fields{&mockAuthority{ret1: p, ret2: ""}}, args{httptest.NewRecorder(), req}, 200},
  914. {"fail", fields{&mockAuthority{ret1: p, ret2: "", err: fmt.Errorf("the error")}}, args{httptest.NewRecorder(), req}, 500},
  915. {"limit fail", fields{&mockAuthority{ret1: p, ret2: ""}}, args{httptest.NewRecorder(), reqLimitFail}, 400},
  916. }
  917. expected, err := json.Marshal(pr)
  918. if err != nil {
  919. t.Fatal(err)
  920. }
  921. expectedError400 := errs.BadRequest("force")
  922. expectedError400Bytes, err := json.Marshal(expectedError400)
  923. assert.FatalError(t, err)
  924. expectedError500 := errs.InternalServer("force")
  925. expectedError500Bytes, err := json.Marshal(expectedError500)
  926. assert.FatalError(t, err)
  927. for _, tt := range tests {
  928. t.Run(tt.name, func(t *testing.T) {
  929. h := &caHandler{
  930. Authority: tt.fields.Authority,
  931. }
  932. h.Provisioners(tt.args.w, tt.args.r)
  933. rec := tt.args.w.(*httptest.ResponseRecorder)
  934. res := rec.Result()
  935. if res.StatusCode != tt.statusCode {
  936. t.Errorf("caHandler.Provisioners StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  937. }
  938. body, err := ioutil.ReadAll(res.Body)
  939. res.Body.Close()
  940. if err != nil {
  941. t.Errorf("caHandler.Provisioners unexpected error = %v", err)
  942. }
  943. if tt.statusCode < http.StatusBadRequest {
  944. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  945. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expected)
  946. }
  947. } else {
  948. switch tt.statusCode {
  949. case 400:
  950. if !bytes.Equal(bytes.TrimSpace(body), expectedError400Bytes) {
  951. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expectedError400Bytes)
  952. }
  953. case 500:
  954. if !bytes.Equal(bytes.TrimSpace(body), expectedError500Bytes) {
  955. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expectedError500Bytes)
  956. }
  957. default:
  958. t.Errorf("caHandler.Provisioner unexpected status code = %d", tt.statusCode)
  959. }
  960. }
  961. })
  962. }
  963. }
  964. func Test_caHandler_ProvisionerKey(t *testing.T) {
  965. type fields struct {
  966. Authority Authority
  967. }
  968. type args struct {
  969. w http.ResponseWriter
  970. r *http.Request
  971. }
  972. // Request with chi context
  973. chiCtx := chi.NewRouteContext()
  974. chiCtx.URLParams.Add("kid", "oV1p0MJeGQ7qBlK6B-oyfVdBRjh_e7VSK_YSEEqgW00")
  975. req := httptest.NewRequest("GET", "http://example.com/provisioners/oV1p0MJeGQ7qBlK6B-oyfVdBRjh_e7VSK_YSEEqgW00/encrypted-key", nil)
  976. req = req.WithContext(context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx))
  977. tests := []struct {
  978. name string
  979. fields fields
  980. args args
  981. statusCode int
  982. }{
  983. {"ok", fields{&mockAuthority{ret1: privKey}}, args{httptest.NewRecorder(), req}, 200},
  984. {"fail", fields{&mockAuthority{ret1: "", err: fmt.Errorf("not found")}}, args{httptest.NewRecorder(), req}, 404},
  985. }
  986. expected := []byte(`{"key":"` + privKey + `"}`)
  987. expectedError404 := errs.NotFound("force")
  988. expectedError404Bytes, err := json.Marshal(expectedError404)
  989. assert.FatalError(t, err)
  990. for _, tt := range tests {
  991. t.Run(tt.name, func(t *testing.T) {
  992. h := &caHandler{
  993. Authority: tt.fields.Authority,
  994. }
  995. h.ProvisionerKey(tt.args.w, tt.args.r)
  996. rec := tt.args.w.(*httptest.ResponseRecorder)
  997. res := rec.Result()
  998. if res.StatusCode != tt.statusCode {
  999. t.Errorf("caHandler.Provisioners StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  1000. }
  1001. body, err := ioutil.ReadAll(res.Body)
  1002. res.Body.Close()
  1003. if err != nil {
  1004. t.Errorf("caHandler.Provisioners unexpected error = %v", err)
  1005. }
  1006. if tt.statusCode < http.StatusBadRequest {
  1007. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  1008. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expected)
  1009. }
  1010. } else {
  1011. if !bytes.Equal(bytes.TrimSpace(body), expectedError404Bytes) {
  1012. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expectedError404Bytes)
  1013. }
  1014. }
  1015. })
  1016. }
  1017. }
  1018. func Test_caHandler_Roots(t *testing.T) {
  1019. cs := &tls.ConnectionState{
  1020. PeerCertificates: []*x509.Certificate{parseCertificate(certPEM)},
  1021. }
  1022. tests := []struct {
  1023. name string
  1024. tls *tls.ConnectionState
  1025. cert *x509.Certificate
  1026. root *x509.Certificate
  1027. err error
  1028. statusCode int
  1029. }{
  1030. {"ok", cs, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  1031. {"no peer certificates", &tls.ConnectionState{}, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  1032. {"fail", cs, nil, nil, fmt.Errorf("an error"), http.StatusForbidden},
  1033. }
  1034. expected := []byte(`{"crts":["` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n"]}`)
  1035. for _, tt := range tests {
  1036. t.Run(tt.name, func(t *testing.T) {
  1037. h := New(&mockAuthority{ret1: []*x509.Certificate{tt.root}, err: tt.err}).(*caHandler)
  1038. req := httptest.NewRequest("GET", "http://example.com/roots", nil)
  1039. req.TLS = tt.tls
  1040. w := httptest.NewRecorder()
  1041. h.Roots(w, req)
  1042. res := w.Result()
  1043. if res.StatusCode != tt.statusCode {
  1044. t.Errorf("caHandler.Roots StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  1045. }
  1046. body, err := ioutil.ReadAll(res.Body)
  1047. res.Body.Close()
  1048. if err != nil {
  1049. t.Errorf("caHandler.Roots unexpected error = %v", err)
  1050. }
  1051. if tt.statusCode < http.StatusBadRequest {
  1052. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  1053. t.Errorf("caHandler.Roots Body = %s, wants %s", body, expected)
  1054. }
  1055. }
  1056. })
  1057. }
  1058. }
  1059. func Test_caHandler_Federation(t *testing.T) {
  1060. cs := &tls.ConnectionState{
  1061. PeerCertificates: []*x509.Certificate{parseCertificate(certPEM)},
  1062. }
  1063. tests := []struct {
  1064. name string
  1065. tls *tls.ConnectionState
  1066. cert *x509.Certificate
  1067. root *x509.Certificate
  1068. err error
  1069. statusCode int
  1070. }{
  1071. {"ok", cs, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  1072. {"no peer certificates", &tls.ConnectionState{}, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  1073. {"fail", cs, nil, nil, fmt.Errorf("an error"), http.StatusForbidden},
  1074. }
  1075. expected := []byte(`{"crts":["` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n"]}`)
  1076. for _, tt := range tests {
  1077. t.Run(tt.name, func(t *testing.T) {
  1078. h := New(&mockAuthority{ret1: []*x509.Certificate{tt.root}, err: tt.err}).(*caHandler)
  1079. req := httptest.NewRequest("GET", "http://example.com/federation", nil)
  1080. req.TLS = tt.tls
  1081. w := httptest.NewRecorder()
  1082. h.Federation(w, req)
  1083. res := w.Result()
  1084. if res.StatusCode != tt.statusCode {
  1085. t.Errorf("caHandler.Federation StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  1086. }
  1087. body, err := ioutil.ReadAll(res.Body)
  1088. res.Body.Close()
  1089. if err != nil {
  1090. t.Errorf("caHandler.Federation unexpected error = %v", err)
  1091. }
  1092. if tt.statusCode < http.StatusBadRequest {
  1093. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  1094. t.Errorf("caHandler.Federation Body = %s, wants %s", body, expected)
  1095. }
  1096. }
  1097. })
  1098. }
  1099. }
  1100. func Test_fmtPublicKey(t *testing.T) {
  1101. p256, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1102. if err != nil {
  1103. t.Fatal(err)
  1104. }
  1105. rsa1024, err := rsa.GenerateKey(rand.Reader, 1024)
  1106. if err != nil {
  1107. t.Fatal(err)
  1108. }
  1109. var dsa2048 dsa.PrivateKey
  1110. if err := dsa.GenerateParameters(&dsa2048.Parameters, rand.Reader, dsa.L2048N256); err != nil {
  1111. t.Fatal(err)
  1112. }
  1113. if err := dsa.GenerateKey(&dsa2048, rand.Reader); err != nil {
  1114. t.Fatal(err)
  1115. }
  1116. type args struct {
  1117. pub, priv interface{}
  1118. cert *x509.Certificate
  1119. }
  1120. tests := []struct {
  1121. name string
  1122. args args
  1123. want string
  1124. }{
  1125. {"p256", args{p256.Public(), p256, nil}, "ECDSA P-256"},
  1126. {"rsa1024", args{rsa1024.Public(), rsa1024, nil}, "RSA 1024"},
  1127. {"dsa2048", args{cert: &x509.Certificate{PublicKeyAlgorithm: x509.DSA, PublicKey: &dsa2048.PublicKey}}, "DSA 2048"},
  1128. {"unknown", args{cert: &x509.Certificate{PublicKeyAlgorithm: x509.ECDSA, PublicKey: []byte("12345678")}}, "ECDSA unknown"},
  1129. }
  1130. for _, tt := range tests {
  1131. t.Run(tt.name, func(t *testing.T) {
  1132. var cert *x509.Certificate
  1133. if tt.args.cert != nil {
  1134. cert = tt.args.cert
  1135. } else {
  1136. cert = mustCertificate(t, tt.args.pub, tt.args.priv)
  1137. }
  1138. if got := fmtPublicKey(cert); got != tt.want {
  1139. t.Errorf("fmtPublicKey() = %v, want %v", got, tt.want)
  1140. }
  1141. })
  1142. }
  1143. }
  1144. func mustCertificate(t *testing.T, pub, priv interface{}) *x509.Certificate {
  1145. template := x509.Certificate{
  1146. SerialNumber: big.NewInt(1),
  1147. Subject: pkix.Name{
  1148. Organization: []string{"Acme Co"},
  1149. },
  1150. NotBefore: time.Now(),
  1151. NotAfter: time.Now().Add(24 * time.Hour),
  1152. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  1153. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  1154. BasicConstraintsValid: true,
  1155. }
  1156. der, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, priv)
  1157. if err != nil {
  1158. t.Fatal(err)
  1159. }
  1160. cert, err := x509.ParseCertificate(der)
  1161. if err != nil {
  1162. t.Fatal(err)
  1163. }
  1164. return cert
  1165. }