api_test.go 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "crypto/dsa" //nolint
  7. "crypto/ecdsa"
  8. "crypto/ed25519"
  9. "crypto/elliptic"
  10. "crypto/rand"
  11. "crypto/rsa"
  12. "crypto/tls"
  13. "crypto/x509"
  14. "crypto/x509/pkix"
  15. "encoding/json"
  16. "encoding/pem"
  17. "fmt"
  18. "io/ioutil"
  19. "math/big"
  20. "net/http"
  21. "net/http/httptest"
  22. "reflect"
  23. "strings"
  24. "testing"
  25. "time"
  26. "github.com/go-chi/chi"
  27. "github.com/pkg/errors"
  28. "github.com/smallstep/assert"
  29. "github.com/smallstep/certificates/authority"
  30. "github.com/smallstep/certificates/authority/provisioner"
  31. "github.com/smallstep/certificates/errs"
  32. "github.com/smallstep/certificates/logging"
  33. "github.com/smallstep/certificates/templates"
  34. "go.step.sm/crypto/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.ReplaceAll(rootPEM, "\n", `\n`) + `\n"`), false},
  178. {"cert", fields{Certificate: parseCertificate(certPEM)}, []byte(`"` + strings.ReplaceAll(certPEM, "\n", `\n`) + `\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.ReplaceAll(csrPEM, "\n", `\n`) + `"`), false, true},
  209. {"empty string", []byte(`""`), false, false},
  210. {"json null", []byte(`null`), false, false},
  211. {"valid root", []byte(`"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `"`), true, false},
  212. {"valid cert", []byte(`"` + strings.ReplaceAll(certPEM, "\n", `\n`) + `"`), 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.ReplaceAll(certPEM, "\n", `\n`) + `"}`, 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.ReplaceAll(csrPEM, "\n", `\n`) + `\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.ReplaceAll(rootPEM, "\n", `\n`) + `"`), false, true},
  312. {"empty string", []byte(`""`), false, false},
  313. {"json null", []byte(`null`), false, false},
  314. {"valid csr", []byte(`"` + strings.ReplaceAll(csrPEM, "\n", `\n`) + `"`), 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.ReplaceAll(csrPEM, "\n", `\n`) + `"}`, 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. getIDForToken func() string
  407. getTokenID func(string) (string, error)
  408. getName func() string
  409. getType func() provisioner.Type
  410. getEncryptedKey func() (string, string, bool)
  411. init func(provisioner.Config) error
  412. authorizeRenew func(ctx context.Context, cert *x509.Certificate) error
  413. authorizeRevoke func(ctx context.Context, token string) error
  414. authorizeSign func(ctx context.Context, ott string) ([]provisioner.SignOption, error)
  415. authorizeRenewal func(*x509.Certificate) error
  416. authorizeSSHSign func(ctx context.Context, token string) ([]provisioner.SignOption, error)
  417. authorizeSSHRevoke func(ctx context.Context, token string) error
  418. authorizeSSHRenew func(ctx context.Context, token string) (*ssh.Certificate, error)
  419. authorizeSSHRekey func(ctx context.Context, token string) (*ssh.Certificate, []provisioner.SignOption, error)
  420. }
  421. func (m *mockProvisioner) GetID() string {
  422. if m.getID != nil {
  423. return m.getID()
  424. }
  425. return m.ret1.(string)
  426. }
  427. func (m *mockProvisioner) GetIDForToken() string {
  428. if m.getIDForToken != nil {
  429. return m.getIDForToken()
  430. }
  431. return m.ret1.(string)
  432. }
  433. func (m *mockProvisioner) GetTokenID(token string) (string, error) {
  434. if m.getTokenID != nil {
  435. return m.getTokenID(token)
  436. }
  437. if m.ret1 == nil {
  438. return "", m.err
  439. }
  440. return m.ret1.(string), m.err
  441. }
  442. func (m *mockProvisioner) GetName() string {
  443. if m.getName != nil {
  444. return m.getName()
  445. }
  446. return m.ret1.(string)
  447. }
  448. func (m *mockProvisioner) GetType() provisioner.Type {
  449. if m.getType != nil {
  450. return m.getType()
  451. }
  452. return m.ret1.(provisioner.Type)
  453. }
  454. func (m *mockProvisioner) GetEncryptedKey() (string, string, bool) {
  455. if m.getEncryptedKey != nil {
  456. return m.getEncryptedKey()
  457. }
  458. return m.ret1.(string), m.ret2.(string), m.ret3.(bool)
  459. }
  460. func (m *mockProvisioner) Init(c provisioner.Config) error {
  461. if m.init != nil {
  462. return m.init(c)
  463. }
  464. return m.err
  465. }
  466. func (m *mockProvisioner) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  467. if m.authorizeRenew != nil {
  468. return m.authorizeRenew(ctx, cert)
  469. }
  470. return m.err
  471. }
  472. func (m *mockProvisioner) AuthorizeRevoke(ctx context.Context, token string) error {
  473. if m.authorizeRevoke != nil {
  474. return m.authorizeRevoke(ctx, token)
  475. }
  476. return m.err
  477. }
  478. func (m *mockProvisioner) AuthorizeSign(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
  479. if m.authorizeSign != nil {
  480. return m.authorizeSign(ctx, ott)
  481. }
  482. return m.ret1.([]provisioner.SignOption), m.err
  483. }
  484. func (m *mockProvisioner) AuthorizeRenewal(c *x509.Certificate) error {
  485. if m.authorizeRenewal != nil {
  486. return m.authorizeRenewal(c)
  487. }
  488. return m.err
  489. }
  490. func (m *mockProvisioner) AuthorizeSSHSign(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  491. if m.authorizeSSHSign != nil {
  492. return m.authorizeSSHSign(ctx, token)
  493. }
  494. return m.ret1.([]provisioner.SignOption), m.err
  495. }
  496. func (m *mockProvisioner) AuthorizeSSHRevoke(ctx context.Context, token string) error {
  497. if m.authorizeSSHRevoke != nil {
  498. return m.authorizeSSHRevoke(ctx, token)
  499. }
  500. return m.err
  501. }
  502. func (m *mockProvisioner) AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  503. if m.authorizeSSHRenew != nil {
  504. return m.authorizeSSHRenew(ctx, token)
  505. }
  506. return m.ret1.(*ssh.Certificate), m.err
  507. }
  508. func (m *mockProvisioner) AuthorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []provisioner.SignOption, error) {
  509. if m.authorizeSSHRekey != nil {
  510. return m.authorizeSSHRekey(ctx, token)
  511. }
  512. return m.ret1.(*ssh.Certificate), m.ret2.([]provisioner.SignOption), m.err
  513. }
  514. type mockAuthority struct {
  515. ret1, ret2 interface{}
  516. err error
  517. authorizeSign func(ott string) ([]provisioner.SignOption, error)
  518. getTLSOptions func() *authority.TLSOptions
  519. root func(shasum string) (*x509.Certificate, error)
  520. sign func(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
  521. renew func(cert *x509.Certificate) ([]*x509.Certificate, error)
  522. rekey func(oldCert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error)
  523. loadProvisionerByCertificate func(cert *x509.Certificate) (provisioner.Interface, error)
  524. loadProvisionerByName func(name string) (provisioner.Interface, error)
  525. getProvisioners func(nextCursor string, limit int) (provisioner.List, string, error)
  526. revoke func(context.Context, *authority.RevokeOptions) error
  527. getEncryptedKey func(kid string) (string, error)
  528. getRoots func() ([]*x509.Certificate, error)
  529. getFederation func() ([]*x509.Certificate, error)
  530. signSSH func(ctx context.Context, key ssh.PublicKey, opts provisioner.SignSSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  531. signSSHAddUser func(ctx context.Context, key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error)
  532. renewSSH func(ctx context.Context, cert *ssh.Certificate) (*ssh.Certificate, error)
  533. rekeySSH func(ctx context.Context, cert *ssh.Certificate, key ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  534. getSSHHosts func(ctx context.Context, cert *x509.Certificate) ([]authority.Host, error)
  535. getSSHRoots func(ctx context.Context) (*authority.SSHKeys, error)
  536. getSSHFederation func(ctx context.Context) (*authority.SSHKeys, error)
  537. getSSHConfig func(ctx context.Context, typ string, data map[string]string) ([]templates.Output, error)
  538. checkSSHHost func(ctx context.Context, principal, token string) (bool, error)
  539. getSSHBastion func(ctx context.Context, user string, hostname string) (*authority.Bastion, error)
  540. version func() authority.Version
  541. }
  542. func (m *mockAuthority) GenerateCertificateRevocationList(force bool) ([]byte, error) {
  543. panic("implement me")
  544. }
  545. // TODO: remove once Authorize is deprecated.
  546. func (m *mockAuthority) Authorize(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
  547. return m.AuthorizeSign(ott)
  548. }
  549. func (m *mockAuthority) AuthorizeSign(ott string) ([]provisioner.SignOption, error) {
  550. if m.authorizeSign != nil {
  551. return m.authorizeSign(ott)
  552. }
  553. return m.ret1.([]provisioner.SignOption), m.err
  554. }
  555. func (m *mockAuthority) GetTLSOptions() *authority.TLSOptions {
  556. if m.getTLSOptions != nil {
  557. return m.getTLSOptions()
  558. }
  559. return m.ret1.(*authority.TLSOptions)
  560. }
  561. func (m *mockAuthority) Root(shasum string) (*x509.Certificate, error) {
  562. if m.root != nil {
  563. return m.root(shasum)
  564. }
  565. return m.ret1.(*x509.Certificate), m.err
  566. }
  567. func (m *mockAuthority) Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  568. if m.sign != nil {
  569. return m.sign(cr, opts, signOpts...)
  570. }
  571. return []*x509.Certificate{m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate)}, m.err
  572. }
  573. func (m *mockAuthority) Renew(cert *x509.Certificate) ([]*x509.Certificate, error) {
  574. if m.renew != nil {
  575. return m.renew(cert)
  576. }
  577. return []*x509.Certificate{m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate)}, m.err
  578. }
  579. func (m *mockAuthority) Rekey(oldcert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error) {
  580. if m.rekey != nil {
  581. return m.rekey(oldcert, pk)
  582. }
  583. return []*x509.Certificate{m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate)}, m.err
  584. }
  585. func (m *mockAuthority) GetProvisioners(nextCursor string, limit int) (provisioner.List, string, error) {
  586. if m.getProvisioners != nil {
  587. return m.getProvisioners(nextCursor, limit)
  588. }
  589. return m.ret1.(provisioner.List), m.ret2.(string), m.err
  590. }
  591. func (m *mockAuthority) LoadProvisionerByCertificate(cert *x509.Certificate) (provisioner.Interface, error) {
  592. if m.loadProvisionerByCertificate != nil {
  593. return m.loadProvisionerByCertificate(cert)
  594. }
  595. return m.ret1.(provisioner.Interface), m.err
  596. }
  597. func (m *mockAuthority) LoadProvisionerByName(name string) (provisioner.Interface, error) {
  598. if m.loadProvisionerByName != nil {
  599. return m.loadProvisionerByName(name)
  600. }
  601. return m.ret1.(provisioner.Interface), m.err
  602. }
  603. func (m *mockAuthority) Revoke(ctx context.Context, opts *authority.RevokeOptions) error {
  604. if m.revoke != nil {
  605. return m.revoke(ctx, opts)
  606. }
  607. return m.err
  608. }
  609. func (m *mockAuthority) GetEncryptedKey(kid string) (string, error) {
  610. if m.getEncryptedKey != nil {
  611. return m.getEncryptedKey(kid)
  612. }
  613. return m.ret1.(string), m.err
  614. }
  615. func (m *mockAuthority) GetRoots() ([]*x509.Certificate, error) {
  616. if m.getRoots != nil {
  617. return m.getRoots()
  618. }
  619. return m.ret1.([]*x509.Certificate), m.err
  620. }
  621. func (m *mockAuthority) GetFederation() ([]*x509.Certificate, error) {
  622. if m.getFederation != nil {
  623. return m.getFederation()
  624. }
  625. return m.ret1.([]*x509.Certificate), m.err
  626. }
  627. func (m *mockAuthority) SignSSH(ctx context.Context, key ssh.PublicKey, opts provisioner.SignSSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  628. if m.signSSH != nil {
  629. return m.signSSH(ctx, key, opts, signOpts...)
  630. }
  631. return m.ret1.(*ssh.Certificate), m.err
  632. }
  633. func (m *mockAuthority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error) {
  634. if m.signSSHAddUser != nil {
  635. return m.signSSHAddUser(ctx, key, cert)
  636. }
  637. return m.ret1.(*ssh.Certificate), m.err
  638. }
  639. func (m *mockAuthority) RenewSSH(ctx context.Context, cert *ssh.Certificate) (*ssh.Certificate, error) {
  640. if m.renewSSH != nil {
  641. return m.renewSSH(ctx, cert)
  642. }
  643. return m.ret1.(*ssh.Certificate), m.err
  644. }
  645. func (m *mockAuthority) RekeySSH(ctx context.Context, cert *ssh.Certificate, key ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  646. if m.rekeySSH != nil {
  647. return m.rekeySSH(ctx, cert, key, signOpts...)
  648. }
  649. return m.ret1.(*ssh.Certificate), m.err
  650. }
  651. func (m *mockAuthority) GetSSHHosts(ctx context.Context, cert *x509.Certificate) ([]authority.Host, error) {
  652. if m.getSSHHosts != nil {
  653. return m.getSSHHosts(ctx, cert)
  654. }
  655. return m.ret1.([]authority.Host), m.err
  656. }
  657. func (m *mockAuthority) GetSSHRoots(ctx context.Context) (*authority.SSHKeys, error) {
  658. if m.getSSHRoots != nil {
  659. return m.getSSHRoots(ctx)
  660. }
  661. return m.ret1.(*authority.SSHKeys), m.err
  662. }
  663. func (m *mockAuthority) GetSSHFederation(ctx context.Context) (*authority.SSHKeys, error) {
  664. if m.getSSHFederation != nil {
  665. return m.getSSHFederation(ctx)
  666. }
  667. return m.ret1.(*authority.SSHKeys), m.err
  668. }
  669. func (m *mockAuthority) GetSSHConfig(ctx context.Context, typ string, data map[string]string) ([]templates.Output, error) {
  670. if m.getSSHConfig != nil {
  671. return m.getSSHConfig(ctx, typ, data)
  672. }
  673. return m.ret1.([]templates.Output), m.err
  674. }
  675. func (m *mockAuthority) CheckSSHHost(ctx context.Context, principal, token string) (bool, error) {
  676. if m.checkSSHHost != nil {
  677. return m.checkSSHHost(ctx, principal, token)
  678. }
  679. return m.ret1.(bool), m.err
  680. }
  681. func (m *mockAuthority) GetSSHBastion(ctx context.Context, user, hostname string) (*authority.Bastion, error) {
  682. if m.getSSHBastion != nil {
  683. return m.getSSHBastion(ctx, user, hostname)
  684. }
  685. return m.ret1.(*authority.Bastion), m.err
  686. }
  687. func (m *mockAuthority) Version() authority.Version {
  688. if m.version != nil {
  689. return m.version()
  690. }
  691. return m.ret1.(authority.Version)
  692. }
  693. func Test_caHandler_Route(t *testing.T) {
  694. type fields struct {
  695. Authority Authority
  696. }
  697. type args struct {
  698. r Router
  699. }
  700. tests := []struct {
  701. name string
  702. fields fields
  703. args args
  704. }{
  705. {"ok", fields{&mockAuthority{}}, args{chi.NewRouter()}},
  706. }
  707. for _, tt := range tests {
  708. t.Run(tt.name, func(t *testing.T) {
  709. h := &caHandler{
  710. Authority: tt.fields.Authority,
  711. }
  712. h.Route(tt.args.r)
  713. })
  714. }
  715. }
  716. func Test_caHandler_Health(t *testing.T) {
  717. req := httptest.NewRequest("GET", "http://example.com/health", nil)
  718. w := httptest.NewRecorder()
  719. h := New(&mockAuthority{}).(*caHandler)
  720. h.Health(w, req)
  721. res := w.Result()
  722. if res.StatusCode != 200 {
  723. t.Errorf("caHandler.Health StatusCode = %d, wants 200", res.StatusCode)
  724. }
  725. body, err := ioutil.ReadAll(res.Body)
  726. res.Body.Close()
  727. if err != nil {
  728. t.Errorf("caHandler.Health unexpected error = %v", err)
  729. }
  730. expected := []byte("{\"status\":\"ok\"}\n")
  731. if !bytes.Equal(body, expected) {
  732. t.Errorf("caHandler.Health Body = %s, wants %s", body, expected)
  733. }
  734. }
  735. func Test_caHandler_Root(t *testing.T) {
  736. tests := []struct {
  737. name string
  738. root *x509.Certificate
  739. err error
  740. statusCode int
  741. }{
  742. {"ok", parseCertificate(rootPEM), nil, 200},
  743. {"fail", nil, fmt.Errorf("not found"), 404},
  744. }
  745. // Request with chi context
  746. chiCtx := chi.NewRouteContext()
  747. chiCtx.URLParams.Add("sha", "efc7d6b475a56fe587650bcdb999a4a308f815ba44db4bf0371ea68a786ccd36")
  748. req := httptest.NewRequest("GET", "http://example.com/root/efc7d6b475a56fe587650bcdb999a4a308f815ba44db4bf0371ea68a786ccd36", nil)
  749. req = req.WithContext(context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx))
  750. expected := []byte(`{"ca":"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n"}`)
  751. for _, tt := range tests {
  752. t.Run(tt.name, func(t *testing.T) {
  753. h := New(&mockAuthority{ret1: tt.root, err: tt.err}).(*caHandler)
  754. w := httptest.NewRecorder()
  755. h.Root(w, req)
  756. res := w.Result()
  757. if res.StatusCode != tt.statusCode {
  758. t.Errorf("caHandler.Root StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  759. }
  760. body, err := ioutil.ReadAll(res.Body)
  761. res.Body.Close()
  762. if err != nil {
  763. t.Errorf("caHandler.Root unexpected error = %v", err)
  764. }
  765. if tt.statusCode == 200 {
  766. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  767. t.Errorf("caHandler.Root Body = %s, wants %s", body, expected)
  768. }
  769. }
  770. })
  771. }
  772. }
  773. func Test_caHandler_Sign(t *testing.T) {
  774. csr := parseCertificateRequest(csrPEM)
  775. valid, err := json.Marshal(SignRequest{
  776. CsrPEM: CertificateRequest{csr},
  777. OTT: "foobarzar",
  778. })
  779. if err != nil {
  780. t.Fatal(err)
  781. }
  782. invalid, err := json.Marshal(SignRequest{
  783. CsrPEM: CertificateRequest{csr},
  784. OTT: "",
  785. })
  786. if err != nil {
  787. t.Fatal(err)
  788. }
  789. expected1 := []byte(`{"crt":"` + strings.ReplaceAll(certPEM, "\n", `\n`) + `\n","ca":"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n","certChain":["` + strings.ReplaceAll(certPEM, "\n", `\n`) + `\n","` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n"]}`)
  790. expected2 := []byte(`{"crt":"` + strings.ReplaceAll(stepCertPEM, "\n", `\n`) + `\n","ca":"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n","certChain":["` + strings.ReplaceAll(stepCertPEM, "\n", `\n`) + `\n","` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n"]}`)
  791. tests := []struct {
  792. name string
  793. input string
  794. certAttrOpts []provisioner.SignOption
  795. autherr error
  796. cert *x509.Certificate
  797. root *x509.Certificate
  798. signErr error
  799. statusCode int
  800. expected []byte
  801. }{
  802. {"ok", string(valid), nil, nil, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated, expected1},
  803. {"ok with Provisioner", string(valid), nil, nil, parseCertificate(stepCertPEM), parseCertificate(rootPEM), nil, http.StatusCreated, expected2},
  804. {"json read error", "{", nil, nil, nil, nil, nil, http.StatusBadRequest, nil},
  805. {"validate error", string(invalid), nil, nil, nil, nil, nil, http.StatusBadRequest, nil},
  806. {"authorize error", string(valid), nil, fmt.Errorf("an error"), nil, nil, nil, http.StatusUnauthorized, nil},
  807. {"sign error", string(valid), nil, nil, nil, nil, fmt.Errorf("an error"), http.StatusForbidden, nil},
  808. }
  809. for _, tt := range tests {
  810. t.Run(tt.name, func(t *testing.T) {
  811. h := New(&mockAuthority{
  812. ret1: tt.cert, ret2: tt.root, err: tt.signErr,
  813. authorizeSign: func(ott string) ([]provisioner.SignOption, error) {
  814. return tt.certAttrOpts, tt.autherr
  815. },
  816. getTLSOptions: func() *authority.TLSOptions {
  817. return nil
  818. },
  819. }).(*caHandler)
  820. req := httptest.NewRequest("POST", "http://example.com/sign", strings.NewReader(tt.input))
  821. w := httptest.NewRecorder()
  822. h.Sign(logging.NewResponseLogger(w), req)
  823. res := w.Result()
  824. if res.StatusCode != tt.statusCode {
  825. t.Errorf("caHandler.Root StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  826. }
  827. body, err := ioutil.ReadAll(res.Body)
  828. res.Body.Close()
  829. if err != nil {
  830. t.Errorf("caHandler.Root unexpected error = %v", err)
  831. }
  832. if tt.statusCode < http.StatusBadRequest {
  833. if !bytes.Equal(bytes.TrimSpace(body), tt.expected) {
  834. t.Errorf("caHandler.Root Body = %s, wants %s", body, tt.expected)
  835. }
  836. }
  837. })
  838. }
  839. }
  840. func Test_caHandler_Renew(t *testing.T) {
  841. cs := &tls.ConnectionState{
  842. PeerCertificates: []*x509.Certificate{parseCertificate(certPEM)},
  843. }
  844. tests := []struct {
  845. name string
  846. tls *tls.ConnectionState
  847. cert *x509.Certificate
  848. root *x509.Certificate
  849. err error
  850. statusCode int
  851. }{
  852. {"ok", cs, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  853. {"no tls", nil, nil, nil, nil, http.StatusBadRequest},
  854. {"no peer certificates", &tls.ConnectionState{}, nil, nil, nil, http.StatusBadRequest},
  855. {"renew error", cs, nil, nil, errs.Forbidden("an error"), http.StatusForbidden},
  856. }
  857. expected := []byte(`{"crt":"` + strings.ReplaceAll(certPEM, "\n", `\n`) + `\n","ca":"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n","certChain":["` + strings.ReplaceAll(certPEM, "\n", `\n`) + `\n","` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n"]}`)
  858. for _, tt := range tests {
  859. t.Run(tt.name, func(t *testing.T) {
  860. h := New(&mockAuthority{
  861. ret1: tt.cert, ret2: tt.root, err: tt.err,
  862. getTLSOptions: func() *authority.TLSOptions {
  863. return nil
  864. },
  865. }).(*caHandler)
  866. req := httptest.NewRequest("POST", "http://example.com/renew", nil)
  867. req.TLS = tt.tls
  868. w := httptest.NewRecorder()
  869. h.Renew(logging.NewResponseLogger(w), req)
  870. res := w.Result()
  871. if res.StatusCode != tt.statusCode {
  872. t.Errorf("caHandler.Renew StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  873. }
  874. body, err := ioutil.ReadAll(res.Body)
  875. res.Body.Close()
  876. if err != nil {
  877. t.Errorf("caHandler.Renew unexpected error = %v", err)
  878. }
  879. if tt.statusCode < http.StatusBadRequest {
  880. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  881. t.Errorf("caHandler.Root Body = %s, wants %s", body, expected)
  882. }
  883. }
  884. })
  885. }
  886. }
  887. func Test_caHandler_Rekey(t *testing.T) {
  888. cs := &tls.ConnectionState{
  889. PeerCertificates: []*x509.Certificate{parseCertificate(certPEM)},
  890. }
  891. csr := parseCertificateRequest(csrPEM)
  892. valid, err := json.Marshal(RekeyRequest{
  893. CsrPEM: CertificateRequest{csr},
  894. })
  895. if err != nil {
  896. t.Fatal(err)
  897. }
  898. tests := []struct {
  899. name string
  900. input string
  901. tls *tls.ConnectionState
  902. cert *x509.Certificate
  903. root *x509.Certificate
  904. err error
  905. statusCode int
  906. }{
  907. {"ok", string(valid), cs, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  908. {"no tls", string(valid), nil, nil, nil, nil, http.StatusBadRequest},
  909. {"no peer certificates", string(valid), &tls.ConnectionState{}, nil, nil, nil, http.StatusBadRequest},
  910. {"rekey error", string(valid), cs, nil, nil, errs.Forbidden("an error"), http.StatusForbidden},
  911. {"json read error", "{", cs, nil, nil, nil, http.StatusBadRequest},
  912. }
  913. expected := []byte(`{"crt":"` + strings.ReplaceAll(certPEM, "\n", `\n`) + `\n","ca":"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n","certChain":["` + strings.ReplaceAll(certPEM, "\n", `\n`) + `\n","` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n"]}`)
  914. for _, tt := range tests {
  915. t.Run(tt.name, func(t *testing.T) {
  916. h := New(&mockAuthority{
  917. ret1: tt.cert, ret2: tt.root, err: tt.err,
  918. getTLSOptions: func() *authority.TLSOptions {
  919. return nil
  920. },
  921. }).(*caHandler)
  922. req := httptest.NewRequest("POST", "http://example.com/rekey", strings.NewReader(tt.input))
  923. req.TLS = tt.tls
  924. w := httptest.NewRecorder()
  925. h.Rekey(logging.NewResponseLogger(w), req)
  926. res := w.Result()
  927. if res.StatusCode != tt.statusCode {
  928. t.Errorf("caHandler.Rekey StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  929. }
  930. body, err := ioutil.ReadAll(res.Body)
  931. res.Body.Close()
  932. if err != nil {
  933. t.Errorf("caHandler.Rekey unexpected error = %v", err)
  934. }
  935. if tt.statusCode < http.StatusBadRequest {
  936. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  937. t.Errorf("caHandler.Rekey Body = %s, wants %s", body, expected)
  938. }
  939. }
  940. })
  941. }
  942. }
  943. func Test_caHandler_Provisioners(t *testing.T) {
  944. type fields struct {
  945. Authority Authority
  946. }
  947. type args struct {
  948. w http.ResponseWriter
  949. r *http.Request
  950. }
  951. req, err := http.NewRequest("GET", "http://example.com/provisioners?cursor=foo&limit=20", nil)
  952. if err != nil {
  953. t.Fatal(err)
  954. }
  955. reqLimitFail, err := http.NewRequest("GET", "http://example.com/provisioners?limit=abc", nil)
  956. if err != nil {
  957. t.Fatal(err)
  958. }
  959. var key jose.JSONWebKey
  960. if err := json.Unmarshal([]byte(pubKey), &key); err != nil {
  961. t.Fatal(err)
  962. }
  963. p := provisioner.List{
  964. &provisioner.JWK{
  965. Type: "JWK",
  966. Name: "max",
  967. EncryptedKey: "abc",
  968. Key: &key,
  969. },
  970. &provisioner.JWK{
  971. Type: "JWK",
  972. Name: "mariano",
  973. EncryptedKey: "def",
  974. Key: &key,
  975. },
  976. }
  977. pr := ProvisionersResponse{
  978. Provisioners: p,
  979. }
  980. tests := []struct {
  981. name string
  982. fields fields
  983. args args
  984. statusCode int
  985. }{
  986. {"ok", fields{&mockAuthority{ret1: p, ret2: ""}}, args{httptest.NewRecorder(), req}, 200},
  987. {"fail", fields{&mockAuthority{ret1: p, ret2: "", err: fmt.Errorf("the error")}}, args{httptest.NewRecorder(), req}, 500},
  988. {"limit fail", fields{&mockAuthority{ret1: p, ret2: ""}}, args{httptest.NewRecorder(), reqLimitFail}, 400},
  989. }
  990. expected, err := json.Marshal(pr)
  991. if err != nil {
  992. t.Fatal(err)
  993. }
  994. expectedError400 := errs.BadRequest("force")
  995. expectedError400Bytes, err := json.Marshal(expectedError400)
  996. assert.FatalError(t, err)
  997. expectedError500 := errs.InternalServer("force")
  998. expectedError500Bytes, err := json.Marshal(expectedError500)
  999. assert.FatalError(t, err)
  1000. for _, tt := range tests {
  1001. t.Run(tt.name, func(t *testing.T) {
  1002. h := &caHandler{
  1003. Authority: tt.fields.Authority,
  1004. }
  1005. h.Provisioners(tt.args.w, tt.args.r)
  1006. rec := tt.args.w.(*httptest.ResponseRecorder)
  1007. res := rec.Result()
  1008. if res.StatusCode != tt.statusCode {
  1009. t.Errorf("caHandler.Provisioners StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  1010. }
  1011. body, err := ioutil.ReadAll(res.Body)
  1012. res.Body.Close()
  1013. if err != nil {
  1014. t.Errorf("caHandler.Provisioners unexpected error = %v", err)
  1015. }
  1016. if tt.statusCode < http.StatusBadRequest {
  1017. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  1018. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expected)
  1019. }
  1020. } else {
  1021. switch tt.statusCode {
  1022. case 400:
  1023. if !bytes.Equal(bytes.TrimSpace(body), expectedError400Bytes) {
  1024. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expectedError400Bytes)
  1025. }
  1026. case 500:
  1027. if !bytes.Equal(bytes.TrimSpace(body), expectedError500Bytes) {
  1028. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expectedError500Bytes)
  1029. }
  1030. default:
  1031. t.Errorf("caHandler.Provisioner unexpected status code = %d", tt.statusCode)
  1032. }
  1033. }
  1034. })
  1035. }
  1036. }
  1037. func Test_caHandler_ProvisionerKey(t *testing.T) {
  1038. type fields struct {
  1039. Authority Authority
  1040. }
  1041. type args struct {
  1042. w http.ResponseWriter
  1043. r *http.Request
  1044. }
  1045. // Request with chi context
  1046. chiCtx := chi.NewRouteContext()
  1047. chiCtx.URLParams.Add("kid", "oV1p0MJeGQ7qBlK6B-oyfVdBRjh_e7VSK_YSEEqgW00")
  1048. req := httptest.NewRequest("GET", "http://example.com/provisioners/oV1p0MJeGQ7qBlK6B-oyfVdBRjh_e7VSK_YSEEqgW00/encrypted-key", nil)
  1049. req = req.WithContext(context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx))
  1050. tests := []struct {
  1051. name string
  1052. fields fields
  1053. args args
  1054. statusCode int
  1055. }{
  1056. {"ok", fields{&mockAuthority{ret1: privKey}}, args{httptest.NewRecorder(), req}, 200},
  1057. {"fail", fields{&mockAuthority{ret1: "", err: fmt.Errorf("not found")}}, args{httptest.NewRecorder(), req}, 404},
  1058. }
  1059. expected := []byte(`{"key":"` + privKey + `"}`)
  1060. expectedError404 := errs.NotFound("force")
  1061. expectedError404Bytes, err := json.Marshal(expectedError404)
  1062. assert.FatalError(t, err)
  1063. for _, tt := range tests {
  1064. t.Run(tt.name, func(t *testing.T) {
  1065. h := &caHandler{
  1066. Authority: tt.fields.Authority,
  1067. }
  1068. h.ProvisionerKey(tt.args.w, tt.args.r)
  1069. rec := tt.args.w.(*httptest.ResponseRecorder)
  1070. res := rec.Result()
  1071. if res.StatusCode != tt.statusCode {
  1072. t.Errorf("caHandler.Provisioners StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  1073. }
  1074. body, err := ioutil.ReadAll(res.Body)
  1075. res.Body.Close()
  1076. if err != nil {
  1077. t.Errorf("caHandler.Provisioners unexpected error = %v", err)
  1078. }
  1079. if tt.statusCode < http.StatusBadRequest {
  1080. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  1081. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expected)
  1082. }
  1083. } else {
  1084. if !bytes.Equal(bytes.TrimSpace(body), expectedError404Bytes) {
  1085. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expectedError404Bytes)
  1086. }
  1087. }
  1088. })
  1089. }
  1090. }
  1091. func Test_caHandler_Roots(t *testing.T) {
  1092. cs := &tls.ConnectionState{
  1093. PeerCertificates: []*x509.Certificate{parseCertificate(certPEM)},
  1094. }
  1095. tests := []struct {
  1096. name string
  1097. tls *tls.ConnectionState
  1098. cert *x509.Certificate
  1099. root *x509.Certificate
  1100. err error
  1101. statusCode int
  1102. }{
  1103. {"ok", cs, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  1104. {"no peer certificates", &tls.ConnectionState{}, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  1105. {"fail", cs, nil, nil, fmt.Errorf("an error"), http.StatusForbidden},
  1106. }
  1107. expected := []byte(`{"crts":["` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n"]}`)
  1108. for _, tt := range tests {
  1109. t.Run(tt.name, func(t *testing.T) {
  1110. h := New(&mockAuthority{ret1: []*x509.Certificate{tt.root}, err: tt.err}).(*caHandler)
  1111. req := httptest.NewRequest("GET", "http://example.com/roots", nil)
  1112. req.TLS = tt.tls
  1113. w := httptest.NewRecorder()
  1114. h.Roots(w, req)
  1115. res := w.Result()
  1116. if res.StatusCode != tt.statusCode {
  1117. t.Errorf("caHandler.Roots StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  1118. }
  1119. body, err := ioutil.ReadAll(res.Body)
  1120. res.Body.Close()
  1121. if err != nil {
  1122. t.Errorf("caHandler.Roots unexpected error = %v", err)
  1123. }
  1124. if tt.statusCode < http.StatusBadRequest {
  1125. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  1126. t.Errorf("caHandler.Roots Body = %s, wants %s", body, expected)
  1127. }
  1128. }
  1129. })
  1130. }
  1131. }
  1132. func Test_caHandler_Federation(t *testing.T) {
  1133. cs := &tls.ConnectionState{
  1134. PeerCertificates: []*x509.Certificate{parseCertificate(certPEM)},
  1135. }
  1136. tests := []struct {
  1137. name string
  1138. tls *tls.ConnectionState
  1139. cert *x509.Certificate
  1140. root *x509.Certificate
  1141. err error
  1142. statusCode int
  1143. }{
  1144. {"ok", cs, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  1145. {"no peer certificates", &tls.ConnectionState{}, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  1146. {"fail", cs, nil, nil, fmt.Errorf("an error"), http.StatusForbidden},
  1147. }
  1148. expected := []byte(`{"crts":["` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n"]}`)
  1149. for _, tt := range tests {
  1150. t.Run(tt.name, func(t *testing.T) {
  1151. h := New(&mockAuthority{ret1: []*x509.Certificate{tt.root}, err: tt.err}).(*caHandler)
  1152. req := httptest.NewRequest("GET", "http://example.com/federation", nil)
  1153. req.TLS = tt.tls
  1154. w := httptest.NewRecorder()
  1155. h.Federation(w, req)
  1156. res := w.Result()
  1157. if res.StatusCode != tt.statusCode {
  1158. t.Errorf("caHandler.Federation StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  1159. }
  1160. body, err := ioutil.ReadAll(res.Body)
  1161. res.Body.Close()
  1162. if err != nil {
  1163. t.Errorf("caHandler.Federation unexpected error = %v", err)
  1164. }
  1165. if tt.statusCode < http.StatusBadRequest {
  1166. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  1167. t.Errorf("caHandler.Federation Body = %s, wants %s", body, expected)
  1168. }
  1169. }
  1170. })
  1171. }
  1172. }
  1173. func Test_fmtPublicKey(t *testing.T) {
  1174. p256, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1175. if err != nil {
  1176. t.Fatal(err)
  1177. }
  1178. rsa1024, err := rsa.GenerateKey(rand.Reader, 1024)
  1179. if err != nil {
  1180. t.Fatal(err)
  1181. }
  1182. edPub, edPriv, err := ed25519.GenerateKey(rand.Reader)
  1183. if err != nil {
  1184. t.Fatal(err)
  1185. }
  1186. var dsa2048 dsa.PrivateKey
  1187. if err := dsa.GenerateParameters(&dsa2048.Parameters, rand.Reader, dsa.L2048N256); err != nil {
  1188. t.Fatal(err)
  1189. }
  1190. if err := dsa.GenerateKey(&dsa2048, rand.Reader); err != nil {
  1191. t.Fatal(err)
  1192. }
  1193. type args struct {
  1194. pub, priv interface{}
  1195. cert *x509.Certificate
  1196. }
  1197. tests := []struct {
  1198. name string
  1199. args args
  1200. want string
  1201. }{
  1202. {"p256", args{p256.Public(), p256, nil}, "ECDSA P-256"},
  1203. {"rsa1024", args{rsa1024.Public(), rsa1024, nil}, "RSA 1024"},
  1204. {"ed25519", args{edPub, edPriv, nil}, "Ed25519"},
  1205. {"dsa2048", args{cert: &x509.Certificate{PublicKeyAlgorithm: x509.DSA, PublicKey: &dsa2048.PublicKey}}, "DSA 2048"},
  1206. {"unknown", args{cert: &x509.Certificate{PublicKeyAlgorithm: x509.ECDSA, PublicKey: []byte("12345678")}}, "ECDSA unknown"},
  1207. }
  1208. for _, tt := range tests {
  1209. t.Run(tt.name, func(t *testing.T) {
  1210. var cert *x509.Certificate
  1211. if tt.args.cert != nil {
  1212. cert = tt.args.cert
  1213. } else {
  1214. cert = mustCertificate(t, tt.args.pub, tt.args.priv)
  1215. }
  1216. if got := fmtPublicKey(cert); got != tt.want {
  1217. t.Errorf("fmtPublicKey() = %v, want %v", got, tt.want)
  1218. }
  1219. })
  1220. }
  1221. }
  1222. func mustCertificate(t *testing.T, pub, priv interface{}) *x509.Certificate {
  1223. template := x509.Certificate{
  1224. SerialNumber: big.NewInt(1),
  1225. Subject: pkix.Name{
  1226. Organization: []string{"Acme Co"},
  1227. },
  1228. NotBefore: time.Now(),
  1229. NotAfter: time.Now().Add(24 * time.Hour),
  1230. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  1231. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  1232. BasicConstraintsValid: true,
  1233. }
  1234. der, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, priv)
  1235. if err != nil {
  1236. t.Fatal(err)
  1237. }
  1238. cert, err := x509.ParseCertificate(der)
  1239. if err != nil {
  1240. t.Fatal(err)
  1241. }
  1242. return cert
  1243. }