api_test.go 46 KB

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