api_test.go 51 KB

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