api_test.go 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  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. "github.com/smallstep/assert"
  30. "github.com/smallstep/certificates/authority"
  31. "github.com/smallstep/certificates/authority/provisioner"
  32. "github.com/smallstep/certificates/errs"
  33. "github.com/smallstep/certificates/logging"
  34. "github.com/smallstep/certificates/templates"
  35. "go.step.sm/crypto/jose"
  36. "go.step.sm/crypto/x509util"
  37. "golang.org/x/crypto/ssh"
  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. type mockAuthority struct {
  162. ret1, ret2 interface{}
  163. err error
  164. authorizeSign func(ott string) ([]provisioner.SignOption, error)
  165. getTLSOptions func() *authority.TLSOptions
  166. root func(shasum string) (*x509.Certificate, error)
  167. sign func(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
  168. renew func(cert *x509.Certificate) ([]*x509.Certificate, error)
  169. rekey func(oldCert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error)
  170. loadProvisionerByCertificate func(cert *x509.Certificate) (provisioner.Interface, error)
  171. loadProvisionerByName func(name string) (provisioner.Interface, error)
  172. getProvisioners func(nextCursor string, limit int) (provisioner.List, string, error)
  173. revoke func(context.Context, *authority.RevokeOptions) error
  174. getEncryptedKey func(kid string) (string, error)
  175. getRoots func() ([]*x509.Certificate, error)
  176. getFederation func() ([]*x509.Certificate, error)
  177. signSSH func(ctx context.Context, key ssh.PublicKey, opts provisioner.SignSSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  178. signSSHAddUser func(ctx context.Context, key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error)
  179. renewSSH func(ctx context.Context, cert *ssh.Certificate) (*ssh.Certificate, error)
  180. rekeySSH func(ctx context.Context, cert *ssh.Certificate, key ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  181. getSSHHosts func(ctx context.Context, cert *x509.Certificate) ([]authority.Host, error)
  182. getSSHRoots func(ctx context.Context) (*authority.SSHKeys, error)
  183. getSSHFederation func(ctx context.Context) (*authority.SSHKeys, error)
  184. getSSHConfig func(ctx context.Context, typ string, data map[string]string) ([]templates.Output, error)
  185. checkSSHHost func(ctx context.Context, principal, token string) (bool, error)
  186. getSSHBastion func(ctx context.Context, user string, hostname string) (*authority.Bastion, error)
  187. version func() authority.Version
  188. }
  189. // TODO: remove once Authorize is deprecated.
  190. func (m *mockAuthority) Authorize(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
  191. return m.AuthorizeSign(ott)
  192. }
  193. func (m *mockAuthority) AuthorizeSign(ott string) ([]provisioner.SignOption, error) {
  194. if m.authorizeSign != nil {
  195. return m.authorizeSign(ott)
  196. }
  197. return m.ret1.([]provisioner.SignOption), m.err
  198. }
  199. func (m *mockAuthority) GetTLSOptions() *authority.TLSOptions {
  200. if m.getTLSOptions != nil {
  201. return m.getTLSOptions()
  202. }
  203. return m.ret1.(*authority.TLSOptions)
  204. }
  205. func (m *mockAuthority) Root(shasum string) (*x509.Certificate, error) {
  206. if m.root != nil {
  207. return m.root(shasum)
  208. }
  209. return m.ret1.(*x509.Certificate), m.err
  210. }
  211. func (m *mockAuthority) Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  212. if m.sign != nil {
  213. return m.sign(cr, opts, signOpts...)
  214. }
  215. return []*x509.Certificate{m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate)}, m.err
  216. }
  217. func (m *mockAuthority) Renew(cert *x509.Certificate) ([]*x509.Certificate, error) {
  218. if m.renew != nil {
  219. return m.renew(cert)
  220. }
  221. return []*x509.Certificate{m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate)}, m.err
  222. }
  223. func (m *mockAuthority) Rekey(oldcert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error) {
  224. if m.rekey != nil {
  225. return m.rekey(oldcert, pk)
  226. }
  227. return []*x509.Certificate{m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate)}, m.err
  228. }
  229. func (m *mockAuthority) GetProvisioners(nextCursor string, limit int) (provisioner.List, string, error) {
  230. if m.getProvisioners != nil {
  231. return m.getProvisioners(nextCursor, limit)
  232. }
  233. return m.ret1.(provisioner.List), m.ret2.(string), m.err
  234. }
  235. func (m *mockAuthority) LoadProvisionerByCertificate(cert *x509.Certificate) (provisioner.Interface, error) {
  236. if m.loadProvisionerByCertificate != nil {
  237. return m.loadProvisionerByCertificate(cert)
  238. }
  239. return m.ret1.(provisioner.Interface), m.err
  240. }
  241. func (m *mockAuthority) LoadProvisionerByName(name string) (provisioner.Interface, error) {
  242. if m.loadProvisionerByName != nil {
  243. return m.loadProvisionerByName(name)
  244. }
  245. return m.ret1.(provisioner.Interface), m.err
  246. }
  247. func (m *mockAuthority) Revoke(ctx context.Context, opts *authority.RevokeOptions) error {
  248. if m.revoke != nil {
  249. return m.revoke(ctx, opts)
  250. }
  251. return m.err
  252. }
  253. func (m *mockAuthority) GetEncryptedKey(kid string) (string, error) {
  254. if m.getEncryptedKey != nil {
  255. return m.getEncryptedKey(kid)
  256. }
  257. return m.ret1.(string), m.err
  258. }
  259. func (m *mockAuthority) GetRoots() ([]*x509.Certificate, error) {
  260. if m.getRoots != nil {
  261. return m.getRoots()
  262. }
  263. return m.ret1.([]*x509.Certificate), m.err
  264. }
  265. func (m *mockAuthority) GetFederation() ([]*x509.Certificate, error) {
  266. if m.getFederation != nil {
  267. return m.getFederation()
  268. }
  269. return m.ret1.([]*x509.Certificate), m.err
  270. }
  271. func (m *mockAuthority) SignSSH(ctx context.Context, key ssh.PublicKey, opts provisioner.SignSSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  272. if m.signSSH != nil {
  273. return m.signSSH(ctx, key, opts, signOpts...)
  274. }
  275. return m.ret1.(*ssh.Certificate), m.err
  276. }
  277. func (m *mockAuthority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error) {
  278. if m.signSSHAddUser != nil {
  279. return m.signSSHAddUser(ctx, key, cert)
  280. }
  281. return m.ret1.(*ssh.Certificate), m.err
  282. }
  283. func (m *mockAuthority) RenewSSH(ctx context.Context, cert *ssh.Certificate) (*ssh.Certificate, error) {
  284. if m.renewSSH != nil {
  285. return m.renewSSH(ctx, cert)
  286. }
  287. return m.ret1.(*ssh.Certificate), m.err
  288. }
  289. func (m *mockAuthority) RekeySSH(ctx context.Context, cert *ssh.Certificate, key ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  290. if m.rekeySSH != nil {
  291. return m.rekeySSH(ctx, cert, key, signOpts...)
  292. }
  293. return m.ret1.(*ssh.Certificate), m.err
  294. }
  295. func (m *mockAuthority) GetSSHHosts(ctx context.Context, cert *x509.Certificate) ([]authority.Host, error) {
  296. if m.getSSHHosts != nil {
  297. return m.getSSHHosts(ctx, cert)
  298. }
  299. return m.ret1.([]authority.Host), m.err
  300. }
  301. func (m *mockAuthority) GetSSHRoots(ctx context.Context) (*authority.SSHKeys, error) {
  302. if m.getSSHRoots != nil {
  303. return m.getSSHRoots(ctx)
  304. }
  305. return m.ret1.(*authority.SSHKeys), m.err
  306. }
  307. func (m *mockAuthority) GetSSHFederation(ctx context.Context) (*authority.SSHKeys, error) {
  308. if m.getSSHFederation != nil {
  309. return m.getSSHFederation(ctx)
  310. }
  311. return m.ret1.(*authority.SSHKeys), m.err
  312. }
  313. func (m *mockAuthority) GetSSHConfig(ctx context.Context, typ string, data map[string]string) ([]templates.Output, error) {
  314. if m.getSSHConfig != nil {
  315. return m.getSSHConfig(ctx, typ, data)
  316. }
  317. return m.ret1.([]templates.Output), m.err
  318. }
  319. func (m *mockAuthority) CheckSSHHost(ctx context.Context, principal, token string) (bool, error) {
  320. if m.checkSSHHost != nil {
  321. return m.checkSSHHost(ctx, principal, token)
  322. }
  323. return m.ret1.(bool), m.err
  324. }
  325. func (m *mockAuthority) GetSSHBastion(ctx context.Context, user, hostname string) (*authority.Bastion, error) {
  326. if m.getSSHBastion != nil {
  327. return m.getSSHBastion(ctx, user, hostname)
  328. }
  329. return m.ret1.(*authority.Bastion), m.err
  330. }
  331. func (m *mockAuthority) Version() authority.Version {
  332. if m.version != nil {
  333. return m.version()
  334. }
  335. return m.ret1.(authority.Version)
  336. }
  337. func TestNewCertificate(t *testing.T) {
  338. cert := parseCertificate(rootPEM)
  339. if !reflect.DeepEqual(Certificate{Certificate: cert}, NewCertificate(cert)) {
  340. t.Errorf("NewCertificate failed, got %v, wants %v", NewCertificate(cert), Certificate{Certificate: cert})
  341. }
  342. }
  343. func TestCertificate_MarshalJSON(t *testing.T) {
  344. type fields struct {
  345. Certificate *x509.Certificate
  346. }
  347. tests := []struct {
  348. name string
  349. fields fields
  350. want []byte
  351. wantErr bool
  352. }{
  353. {"nil", fields{Certificate: nil}, []byte("null"), false},
  354. {"empty", fields{Certificate: &x509.Certificate{Raw: nil}}, []byte(`"-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n"`), false},
  355. {"root", fields{Certificate: parseCertificate(rootPEM)}, []byte(`"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n"`), false},
  356. {"cert", fields{Certificate: parseCertificate(certPEM)}, []byte(`"` + strings.ReplaceAll(certPEM, "\n", `\n`) + `\n"`), false},
  357. }
  358. for _, tt := range tests {
  359. t.Run(tt.name, func(t *testing.T) {
  360. c := Certificate{
  361. Certificate: tt.fields.Certificate,
  362. }
  363. got, err := c.MarshalJSON()
  364. if (err != nil) != tt.wantErr {
  365. t.Errorf("Certificate.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  366. return
  367. }
  368. if !reflect.DeepEqual(got, tt.want) {
  369. t.Errorf("Certificate.MarshalJSON() = %s, want %s", got, tt.want)
  370. }
  371. })
  372. }
  373. }
  374. func TestCertificate_UnmarshalJSON(t *testing.T) {
  375. tests := []struct {
  376. name string
  377. data []byte
  378. wantCert bool
  379. wantErr bool
  380. }{
  381. {"no data", nil, false, true},
  382. {"incomplete string 1", []byte(`"foobar`), false, true}, {"incomplete string 2", []byte(`foobar"`), false, true},
  383. {"invalid string", []byte(`"foobar"`), false, true},
  384. {"invalid bytes 0", []byte{}, false, true}, {"invalid bytes 1", []byte{1}, false, true},
  385. {"empty csr", []byte(`"-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE----\n"`), false, true},
  386. {"invalid type", []byte(`"` + strings.ReplaceAll(csrPEM, "\n", `\n`) + `"`), false, true},
  387. {"empty string", []byte(`""`), false, false},
  388. {"json null", []byte(`null`), false, false},
  389. {"valid root", []byte(`"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `"`), true, false},
  390. {"valid cert", []byte(`"` + strings.ReplaceAll(certPEM, "\n", `\n`) + `"`), true, false},
  391. }
  392. for _, tt := range tests {
  393. t.Run(tt.name, func(t *testing.T) {
  394. var c Certificate
  395. if err := c.UnmarshalJSON(tt.data); (err != nil) != tt.wantErr {
  396. t.Errorf("Certificate.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  397. }
  398. if tt.wantCert && c.Certificate == nil {
  399. t.Error("Certificate.UnmarshalJSON() failed, Certificate is nil")
  400. }
  401. })
  402. }
  403. }
  404. func TestCertificate_UnmarshalJSON_json(t *testing.T) {
  405. tests := []struct {
  406. name string
  407. data string
  408. wantCert bool
  409. wantErr bool
  410. }{
  411. {"invalid type (bool)", `{"crt":true}`, false, true},
  412. {"invalid type (number)", `{"crt":123}`, false, true},
  413. {"invalid type (object)", `{"crt":{}}`, false, true},
  414. {"empty crt (null)", `{"crt":null}`, false, false},
  415. {"empty crt (string)", `{"crt":""}`, false, false},
  416. {"empty crt", `{"crt":"-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE----\n"}`, false, true},
  417. {"valid crt", `{"crt":"` + strings.ReplaceAll(certPEM, "\n", `\n`) + `"}`, true, false},
  418. }
  419. type request struct {
  420. Cert Certificate `json:"crt"`
  421. }
  422. for _, tt := range tests {
  423. t.Run(tt.name, func(t *testing.T) {
  424. var body request
  425. if err := json.Unmarshal([]byte(tt.data), &body); (err != nil) != tt.wantErr {
  426. t.Errorf("json.Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
  427. }
  428. switch tt.wantCert {
  429. case true:
  430. if body.Cert.Certificate == nil {
  431. t.Error("json.Unmarshal() failed, Certificate is nil")
  432. }
  433. case false:
  434. if body.Cert.Certificate != nil {
  435. t.Error("json.Unmarshal() failed, Certificate is not nil")
  436. }
  437. }
  438. })
  439. }
  440. }
  441. func TestNewCertificateRequest(t *testing.T) {
  442. csr := parseCertificateRequest(csrPEM)
  443. if !reflect.DeepEqual(CertificateRequest{CertificateRequest: csr}, NewCertificateRequest(csr)) {
  444. t.Errorf("NewCertificateRequest failed, got %v, wants %v", NewCertificateRequest(csr), CertificateRequest{CertificateRequest: csr})
  445. }
  446. }
  447. func TestCertificateRequest_MarshalJSON(t *testing.T) {
  448. type fields struct {
  449. CertificateRequest *x509.CertificateRequest
  450. }
  451. tests := []struct {
  452. name string
  453. fields fields
  454. want []byte
  455. wantErr bool
  456. }{
  457. {"nil", fields{CertificateRequest: nil}, []byte("null"), false},
  458. {"empty", fields{CertificateRequest: &x509.CertificateRequest{}}, []byte(`"-----BEGIN CERTIFICATE REQUEST-----\n-----END CERTIFICATE REQUEST-----\n"`), false},
  459. {"csr", fields{CertificateRequest: parseCertificateRequest(csrPEM)}, []byte(`"` + strings.ReplaceAll(csrPEM, "\n", `\n`) + `\n"`), false},
  460. }
  461. for _, tt := range tests {
  462. t.Run(tt.name, func(t *testing.T) {
  463. c := CertificateRequest{
  464. CertificateRequest: tt.fields.CertificateRequest,
  465. }
  466. got, err := c.MarshalJSON()
  467. if (err != nil) != tt.wantErr {
  468. t.Errorf("CertificateRequest.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  469. return
  470. }
  471. if !reflect.DeepEqual(got, tt.want) {
  472. t.Errorf("CertificateRequest.MarshalJSON() = %s, want %s", got, tt.want)
  473. }
  474. })
  475. }
  476. }
  477. func TestCertificateRequest_UnmarshalJSON(t *testing.T) {
  478. tests := []struct {
  479. name string
  480. data []byte
  481. wantCert bool
  482. wantErr bool
  483. }{
  484. {"no data", nil, false, true},
  485. {"incomplete string 1", []byte(`"foobar`), false, true}, {"incomplete string 2", []byte(`foobar"`), false, true},
  486. {"invalid string", []byte(`"foobar"`), false, true},
  487. {"invalid bytes 0", []byte{}, false, true}, {"invalid bytes 1", []byte{1}, false, true},
  488. {"empty csr", []byte(`"-----BEGIN CERTIFICATE REQUEST-----\n-----END CERTIFICATE REQUEST----\n"`), false, true},
  489. {"invalid type", []byte(`"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `"`), false, true},
  490. {"empty string", []byte(`""`), false, false},
  491. {"json null", []byte(`null`), false, false},
  492. {"valid csr", []byte(`"` + strings.ReplaceAll(csrPEM, "\n", `\n`) + `"`), true, false},
  493. }
  494. for _, tt := range tests {
  495. t.Run(tt.name, func(t *testing.T) {
  496. var c CertificateRequest
  497. if err := c.UnmarshalJSON(tt.data); (err != nil) != tt.wantErr {
  498. t.Errorf("CertificateRequest.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  499. }
  500. if tt.wantCert && c.CertificateRequest == nil {
  501. t.Error("CertificateRequest.UnmarshalJSON() failed, CertificateRequet is nil")
  502. }
  503. })
  504. }
  505. }
  506. func TestCertificateRequest_UnmarshalJSON_json(t *testing.T) {
  507. tests := []struct {
  508. name string
  509. data string
  510. wantCert bool
  511. wantErr bool
  512. }{
  513. {"invalid type (bool)", `{"csr":true}`, false, true},
  514. {"invalid type (number)", `{"csr":123}`, false, true},
  515. {"invalid type (object)", `{"csr":{}}`, false, true},
  516. {"empty csr (null)", `{"csr":null}`, false, false},
  517. {"empty csr (string)", `{"csr":""}`, false, false},
  518. {"empty csr", `{"csr":"-----BEGIN CERTIFICATE REQUEST-----\n-----END CERTIFICATE REQUEST----\n"}`, false, true},
  519. {"valid csr", `{"csr":"` + strings.ReplaceAll(csrPEM, "\n", `\n`) + `"}`, true, false},
  520. }
  521. type request struct {
  522. CSR CertificateRequest `json:"csr"`
  523. }
  524. for _, tt := range tests {
  525. t.Run(tt.name, func(t *testing.T) {
  526. var body request
  527. if err := json.Unmarshal([]byte(tt.data), &body); (err != nil) != tt.wantErr {
  528. t.Errorf("json.Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
  529. }
  530. switch tt.wantCert {
  531. case true:
  532. if body.CSR.CertificateRequest == nil {
  533. t.Error("json.Unmarshal() failed, CertificateRequest is nil")
  534. }
  535. case false:
  536. if body.CSR.CertificateRequest != nil {
  537. t.Error("json.Unmarshal() failed, CertificateRequest is not nil")
  538. }
  539. }
  540. })
  541. }
  542. }
  543. func TestSignRequest_Validate(t *testing.T) {
  544. csr := parseCertificateRequest(csrPEM)
  545. bad := parseCertificateRequest(csrPEM)
  546. bad.Signature[0]++
  547. type fields struct {
  548. CsrPEM CertificateRequest
  549. OTT string
  550. NotBefore time.Time
  551. NotAfter time.Time
  552. }
  553. tests := []struct {
  554. name string
  555. fields fields
  556. err error
  557. }{
  558. {"missing csr", fields{CertificateRequest{}, "foobarzar", time.Time{}, time.Time{}}, errors.New("missing csr")},
  559. {"invalid csr", fields{CertificateRequest{bad}, "foobarzar", time.Time{}, time.Time{}}, errors.New("invalid csr")},
  560. {"missing ott", fields{CertificateRequest{csr}, "", time.Time{}, time.Time{}}, errors.New("missing ott")},
  561. }
  562. for _, tt := range tests {
  563. t.Run(tt.name, func(t *testing.T) {
  564. s := &SignRequest{
  565. CsrPEM: tt.fields.CsrPEM,
  566. OTT: tt.fields.OTT,
  567. NotAfter: NewTimeDuration(tt.fields.NotAfter),
  568. NotBefore: NewTimeDuration(tt.fields.NotBefore),
  569. }
  570. if err := s.Validate(); err != nil {
  571. if assert.NotNil(t, tt.err) {
  572. assert.HasPrefix(t, err.Error(), tt.err.Error())
  573. }
  574. } else {
  575. assert.Nil(t, tt.err)
  576. }
  577. })
  578. }
  579. }
  580. type mockProvisioner struct {
  581. ret1, ret2, ret3 interface{}
  582. err error
  583. getID func() string
  584. getIDForToken func() string
  585. getTokenID func(string) (string, error)
  586. getName func() string
  587. getType func() provisioner.Type
  588. getEncryptedKey func() (string, string, bool)
  589. init func(provisioner.Config) error
  590. authorizeRenew func(ctx context.Context, cert *x509.Certificate) error
  591. authorizeRevoke func(ctx context.Context, token string) error
  592. authorizeSign func(ctx context.Context, ott string) ([]provisioner.SignOption, error)
  593. authorizeRenewal func(*x509.Certificate) error
  594. authorizeSSHSign func(ctx context.Context, token string) ([]provisioner.SignOption, error)
  595. authorizeSSHRevoke func(ctx context.Context, token string) error
  596. authorizeSSHRenew func(ctx context.Context, token string) (*ssh.Certificate, error)
  597. authorizeSSHRekey func(ctx context.Context, token string) (*ssh.Certificate, []provisioner.SignOption, error)
  598. }
  599. func (m *mockProvisioner) GetID() string {
  600. if m.getID != nil {
  601. return m.getID()
  602. }
  603. return m.ret1.(string)
  604. }
  605. func (m *mockProvisioner) GetIDForToken() string {
  606. if m.getIDForToken != nil {
  607. return m.getIDForToken()
  608. }
  609. return m.ret1.(string)
  610. }
  611. func (m *mockProvisioner) GetTokenID(token string) (string, error) {
  612. if m.getTokenID != nil {
  613. return m.getTokenID(token)
  614. }
  615. if m.ret1 == nil {
  616. return "", m.err
  617. }
  618. return m.ret1.(string), m.err
  619. }
  620. func (m *mockProvisioner) GetName() string {
  621. if m.getName != nil {
  622. return m.getName()
  623. }
  624. return m.ret1.(string)
  625. }
  626. func (m *mockProvisioner) GetType() provisioner.Type {
  627. if m.getType != nil {
  628. return m.getType()
  629. }
  630. return m.ret1.(provisioner.Type)
  631. }
  632. func (m *mockProvisioner) GetEncryptedKey() (string, string, bool) {
  633. if m.getEncryptedKey != nil {
  634. return m.getEncryptedKey()
  635. }
  636. return m.ret1.(string), m.ret2.(string), m.ret3.(bool)
  637. }
  638. func (m *mockProvisioner) Init(c provisioner.Config) error {
  639. if m.init != nil {
  640. return m.init(c)
  641. }
  642. return m.err
  643. }
  644. func (m *mockProvisioner) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  645. if m.authorizeRenew != nil {
  646. return m.authorizeRenew(ctx, cert)
  647. }
  648. return m.err
  649. }
  650. func (m *mockProvisioner) AuthorizeRevoke(ctx context.Context, token string) error {
  651. if m.authorizeRevoke != nil {
  652. return m.authorizeRevoke(ctx, token)
  653. }
  654. return m.err
  655. }
  656. func (m *mockProvisioner) AuthorizeSign(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
  657. if m.authorizeSign != nil {
  658. return m.authorizeSign(ctx, ott)
  659. }
  660. return m.ret1.([]provisioner.SignOption), m.err
  661. }
  662. func (m *mockProvisioner) AuthorizeRenewal(c *x509.Certificate) error {
  663. if m.authorizeRenewal != nil {
  664. return m.authorizeRenewal(c)
  665. }
  666. return m.err
  667. }
  668. func (m *mockProvisioner) AuthorizeSSHSign(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  669. if m.authorizeSSHSign != nil {
  670. return m.authorizeSSHSign(ctx, token)
  671. }
  672. return m.ret1.([]provisioner.SignOption), m.err
  673. }
  674. func (m *mockProvisioner) AuthorizeSSHRevoke(ctx context.Context, token string) error {
  675. if m.authorizeSSHRevoke != nil {
  676. return m.authorizeSSHRevoke(ctx, token)
  677. }
  678. return m.err
  679. }
  680. func (m *mockProvisioner) AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  681. if m.authorizeSSHRenew != nil {
  682. return m.authorizeSSHRenew(ctx, token)
  683. }
  684. return m.ret1.(*ssh.Certificate), m.err
  685. }
  686. func (m *mockProvisioner) AuthorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []provisioner.SignOption, error) {
  687. if m.authorizeSSHRekey != nil {
  688. return m.authorizeSSHRekey(ctx, token)
  689. }
  690. return m.ret1.(*ssh.Certificate), m.ret2.([]provisioner.SignOption), m.err
  691. }
  692. func Test_caHandler_Route(t *testing.T) {
  693. type fields struct {
  694. Authority Authority
  695. }
  696. type args struct {
  697. r Router
  698. }
  699. tests := []struct {
  700. name string
  701. fields fields
  702. args args
  703. }{
  704. {"ok", fields{&mockAuthority{}}, args{chi.NewRouter()}},
  705. }
  706. for _, tt := range tests {
  707. t.Run(tt.name, func(t *testing.T) {
  708. h := &caHandler{
  709. Authority: tt.fields.Authority,
  710. }
  711. h.Route(tt.args.r)
  712. })
  713. }
  714. }
  715. func Test_caHandler_Health(t *testing.T) {
  716. req := httptest.NewRequest("GET", "http://example.com/health", nil)
  717. w := httptest.NewRecorder()
  718. h := New(&mockAuthority{}).(*caHandler)
  719. h.Health(w, req)
  720. res := w.Result()
  721. if res.StatusCode != 200 {
  722. t.Errorf("caHandler.Health StatusCode = %d, wants 200", res.StatusCode)
  723. }
  724. body, err := io.ReadAll(res.Body)
  725. res.Body.Close()
  726. if err != nil {
  727. t.Errorf("caHandler.Health unexpected error = %v", err)
  728. }
  729. expected := []byte("{\"status\":\"ok\"}\n")
  730. if !bytes.Equal(body, expected) {
  731. t.Errorf("caHandler.Health Body = %s, wants %s", body, expected)
  732. }
  733. }
  734. func Test_caHandler_Root(t *testing.T) {
  735. tests := []struct {
  736. name string
  737. root *x509.Certificate
  738. err error
  739. statusCode int
  740. }{
  741. {"ok", parseCertificate(rootPEM), nil, 200},
  742. {"fail", nil, fmt.Errorf("not found"), 404},
  743. }
  744. // Request with chi context
  745. chiCtx := chi.NewRouteContext()
  746. chiCtx.URLParams.Add("sha", "efc7d6b475a56fe587650bcdb999a4a308f815ba44db4bf0371ea68a786ccd36")
  747. req := httptest.NewRequest("GET", "http://example.com/root/efc7d6b475a56fe587650bcdb999a4a308f815ba44db4bf0371ea68a786ccd36", nil)
  748. req = req.WithContext(context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx))
  749. expected := []byte(`{"ca":"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n"}`)
  750. for _, tt := range tests {
  751. t.Run(tt.name, func(t *testing.T) {
  752. h := New(&mockAuthority{ret1: tt.root, err: tt.err}).(*caHandler)
  753. w := httptest.NewRecorder()
  754. h.Root(w, req)
  755. res := w.Result()
  756. if res.StatusCode != tt.statusCode {
  757. t.Errorf("caHandler.Root StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  758. }
  759. body, err := io.ReadAll(res.Body)
  760. res.Body.Close()
  761. if err != nil {
  762. t.Errorf("caHandler.Root unexpected error = %v", err)
  763. }
  764. if tt.statusCode == 200 {
  765. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  766. t.Errorf("caHandler.Root Body = %s, wants %s", body, expected)
  767. }
  768. }
  769. })
  770. }
  771. }
  772. func Test_caHandler_Sign(t *testing.T) {
  773. csr := parseCertificateRequest(csrPEM)
  774. valid, err := json.Marshal(SignRequest{
  775. CsrPEM: CertificateRequest{csr},
  776. OTT: "foobarzar",
  777. })
  778. if err != nil {
  779. t.Fatal(err)
  780. }
  781. invalid, err := json.Marshal(SignRequest{
  782. CsrPEM: CertificateRequest{csr},
  783. OTT: "",
  784. })
  785. if err != nil {
  786. t.Fatal(err)
  787. }
  788. 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"]}`)
  789. 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"]}`)
  790. tests := []struct {
  791. name string
  792. input string
  793. certAttrOpts []provisioner.SignOption
  794. autherr error
  795. cert *x509.Certificate
  796. root *x509.Certificate
  797. signErr error
  798. statusCode int
  799. expected []byte
  800. }{
  801. {"ok", string(valid), nil, nil, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated, expected1},
  802. {"ok with Provisioner", string(valid), nil, nil, parseCertificate(stepCertPEM), parseCertificate(rootPEM), nil, http.StatusCreated, expected2},
  803. {"json read error", "{", nil, nil, nil, nil, nil, http.StatusBadRequest, nil},
  804. {"validate error", string(invalid), nil, nil, nil, nil, nil, http.StatusBadRequest, nil},
  805. {"authorize error", string(valid), nil, fmt.Errorf("an error"), nil, nil, nil, http.StatusUnauthorized, nil},
  806. {"sign error", string(valid), nil, nil, nil, nil, fmt.Errorf("an error"), http.StatusForbidden, nil},
  807. }
  808. for _, tt := range tests {
  809. t.Run(tt.name, func(t *testing.T) {
  810. h := New(&mockAuthority{
  811. ret1: tt.cert, ret2: tt.root, err: tt.signErr,
  812. authorizeSign: func(ott string) ([]provisioner.SignOption, error) {
  813. return tt.certAttrOpts, tt.autherr
  814. },
  815. getTLSOptions: func() *authority.TLSOptions {
  816. return nil
  817. },
  818. }).(*caHandler)
  819. req := httptest.NewRequest("POST", "http://example.com/sign", strings.NewReader(tt.input))
  820. w := httptest.NewRecorder()
  821. h.Sign(logging.NewResponseLogger(w), req)
  822. res := w.Result()
  823. if res.StatusCode != tt.statusCode {
  824. t.Errorf("caHandler.Root StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  825. }
  826. body, err := io.ReadAll(res.Body)
  827. res.Body.Close()
  828. if err != nil {
  829. t.Errorf("caHandler.Root unexpected error = %v", err)
  830. }
  831. if tt.statusCode < http.StatusBadRequest {
  832. if !bytes.Equal(bytes.TrimSpace(body), tt.expected) {
  833. t.Errorf("caHandler.Root Body = %s, wants %s", body, tt.expected)
  834. }
  835. }
  836. })
  837. }
  838. }
  839. func Test_caHandler_Renew(t *testing.T) {
  840. cs := &tls.ConnectionState{
  841. PeerCertificates: []*x509.Certificate{parseCertificate(certPEM)},
  842. }
  843. // Prepare root and leaf for renew after expiry test.
  844. now := time.Now()
  845. rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader)
  846. if err != nil {
  847. t.Fatal(err)
  848. }
  849. leafPub, leafPriv, err := ed25519.GenerateKey(rand.Reader)
  850. if err != nil {
  851. t.Fatal(err)
  852. }
  853. root := &x509.Certificate{
  854. Subject: pkix.Name{CommonName: "Test Root CA"},
  855. PublicKey: rootPub,
  856. KeyUsage: x509.KeyUsageCertSign,
  857. BasicConstraintsValid: true,
  858. IsCA: true,
  859. NotBefore: now.Add(-2 * time.Hour),
  860. NotAfter: now.Add(time.Hour),
  861. }
  862. root, err = x509util.CreateCertificate(root, root, rootPub, rootPriv)
  863. if err != nil {
  864. t.Fatal(err)
  865. }
  866. expiredLeaf := &x509.Certificate{
  867. Subject: pkix.Name{CommonName: "Leaf certificate"},
  868. PublicKey: leafPub,
  869. KeyUsage: x509.KeyUsageDigitalSignature,
  870. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
  871. NotBefore: now.Add(-time.Hour),
  872. NotAfter: now.Add(-time.Minute),
  873. EmailAddresses: []string{"test@example.org"},
  874. }
  875. expiredLeaf, err = x509util.CreateCertificate(expiredLeaf, root, leafPub, rootPriv)
  876. if err != nil {
  877. t.Fatal(err)
  878. }
  879. // Generate renew after expiry token
  880. so := new(jose.SignerOptions)
  881. so.WithType("JWT")
  882. so.WithHeader("x5cInsecure", []string{base64.StdEncoding.EncodeToString(expiredLeaf.Raw)})
  883. sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.EdDSA, Key: leafPriv}, so)
  884. if err != nil {
  885. t.Fatal(err)
  886. }
  887. generateX5cToken := func(claims jose.Claims) string {
  888. s, err := jose.Signed(sig).Claims(claims).CompactSerialize()
  889. if err != nil {
  890. t.Fatal(err)
  891. }
  892. return s
  893. }
  894. tests := []struct {
  895. name string
  896. tls *tls.ConnectionState
  897. header http.Header
  898. cert *x509.Certificate
  899. root *x509.Certificate
  900. err error
  901. statusCode int
  902. }{
  903. {"ok", cs, nil, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  904. {"ok renew after expiry", &tls.ConnectionState{}, http.Header{
  905. "Authorization": []string{"Bearer " + generateX5cToken(jose.Claims{
  906. NotBefore: jose.NewNumericDate(now), Expiry: jose.NewNumericDate(now.Add(5 * time.Minute)),
  907. })},
  908. }, expiredLeaf, root, nil, http.StatusCreated},
  909. {"no tls", nil, nil, nil, nil, nil, http.StatusBadRequest},
  910. {"no peer certificates", &tls.ConnectionState{}, nil, nil, nil, nil, http.StatusBadRequest},
  911. {"renew error", cs, nil, nil, nil, errs.Forbidden("an error"), http.StatusForbidden},
  912. {"fail expired token", &tls.ConnectionState{}, http.Header{
  913. "Authorization": []string{"Bearer " + generateX5cToken(jose.Claims{
  914. NotBefore: jose.NewNumericDate(now.Add(-time.Hour)), Expiry: jose.NewNumericDate(now.Add(-time.Minute)),
  915. })},
  916. }, expiredLeaf, root, errs.Forbidden("an error"), http.StatusUnauthorized},
  917. {"fail invalid root", &tls.ConnectionState{}, http.Header{
  918. "Authorization": []string{"Bearer " + generateX5cToken(jose.Claims{
  919. NotBefore: jose.NewNumericDate(now.Add(-time.Hour)), Expiry: jose.NewNumericDate(now.Add(-time.Minute)),
  920. })},
  921. }, expiredLeaf, parseCertificate(rootPEM), errs.Forbidden("an error"), http.StatusUnauthorized},
  922. }
  923. for _, tt := range tests {
  924. t.Run(tt.name, func(t *testing.T) {
  925. h := New(&mockAuthority{
  926. ret1: tt.cert, ret2: tt.root, err: tt.err,
  927. getRoots: func() ([]*x509.Certificate, error) {
  928. return []*x509.Certificate{tt.root}, nil
  929. },
  930. getTLSOptions: func() *authority.TLSOptions {
  931. return nil
  932. },
  933. }).(*caHandler)
  934. req := httptest.NewRequest("POST", "http://example.com/renew", nil)
  935. req.TLS = tt.tls
  936. req.Header = tt.header
  937. w := httptest.NewRecorder()
  938. h.Renew(logging.NewResponseLogger(w), req)
  939. res := w.Result()
  940. if res.StatusCode != tt.statusCode {
  941. t.Errorf("caHandler.Renew StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  942. }
  943. body, err := io.ReadAll(res.Body)
  944. res.Body.Close()
  945. if err != nil {
  946. t.Errorf("caHandler.Renew unexpected error = %v", err)
  947. }
  948. if tt.statusCode < http.StatusBadRequest {
  949. expected := []byte(`{"crt":"` + strings.ReplaceAll(string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: tt.cert.Raw})), "\n", `\n`) + `",` +
  950. `"ca":"` + strings.ReplaceAll(string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: tt.root.Raw})), "\n", `\n`) + `",` +
  951. `"certChain":["` +
  952. strings.ReplaceAll(string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: tt.cert.Raw})), "\n", `\n`) + `","` +
  953. strings.ReplaceAll(string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: tt.root.Raw})), "\n", `\n`) + `"]}`)
  954. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  955. t.Errorf("caHandler.Root Body = \n%s, wants \n%s", body, expected)
  956. }
  957. }
  958. })
  959. }
  960. }
  961. func Test_caHandler_Rekey(t *testing.T) {
  962. cs := &tls.ConnectionState{
  963. PeerCertificates: []*x509.Certificate{parseCertificate(certPEM)},
  964. }
  965. csr := parseCertificateRequest(csrPEM)
  966. valid, err := json.Marshal(RekeyRequest{
  967. CsrPEM: CertificateRequest{csr},
  968. })
  969. if err != nil {
  970. t.Fatal(err)
  971. }
  972. tests := []struct {
  973. name string
  974. input string
  975. tls *tls.ConnectionState
  976. cert *x509.Certificate
  977. root *x509.Certificate
  978. err error
  979. statusCode int
  980. }{
  981. {"ok", string(valid), cs, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  982. {"no tls", string(valid), nil, nil, nil, nil, http.StatusBadRequest},
  983. {"no peer certificates", string(valid), &tls.ConnectionState{}, nil, nil, nil, http.StatusBadRequest},
  984. {"rekey error", string(valid), cs, nil, nil, errs.Forbidden("an error"), http.StatusForbidden},
  985. {"json read error", "{", cs, nil, nil, nil, http.StatusBadRequest},
  986. }
  987. 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"]}`)
  988. for _, tt := range tests {
  989. t.Run(tt.name, func(t *testing.T) {
  990. h := New(&mockAuthority{
  991. ret1: tt.cert, ret2: tt.root, err: tt.err,
  992. getTLSOptions: func() *authority.TLSOptions {
  993. return nil
  994. },
  995. }).(*caHandler)
  996. req := httptest.NewRequest("POST", "http://example.com/rekey", strings.NewReader(tt.input))
  997. req.TLS = tt.tls
  998. w := httptest.NewRecorder()
  999. h.Rekey(logging.NewResponseLogger(w), req)
  1000. res := w.Result()
  1001. if res.StatusCode != tt.statusCode {
  1002. t.Errorf("caHandler.Rekey StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  1003. }
  1004. body, err := io.ReadAll(res.Body)
  1005. res.Body.Close()
  1006. if err != nil {
  1007. t.Errorf("caHandler.Rekey unexpected error = %v", err)
  1008. }
  1009. if tt.statusCode < http.StatusBadRequest {
  1010. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  1011. t.Errorf("caHandler.Rekey Body = %s, wants %s", body, expected)
  1012. }
  1013. }
  1014. })
  1015. }
  1016. }
  1017. func Test_caHandler_Provisioners(t *testing.T) {
  1018. type fields struct {
  1019. Authority Authority
  1020. }
  1021. type args struct {
  1022. w http.ResponseWriter
  1023. r *http.Request
  1024. }
  1025. req, err := http.NewRequest("GET", "http://example.com/provisioners?cursor=foo&limit=20", http.NoBody)
  1026. if err != nil {
  1027. t.Fatal(err)
  1028. }
  1029. reqLimitFail, err := http.NewRequest("GET", "http://example.com/provisioners?limit=abc", http.NoBody)
  1030. if err != nil {
  1031. t.Fatal(err)
  1032. }
  1033. var key jose.JSONWebKey
  1034. if err := json.Unmarshal([]byte(pubKey), &key); err != nil {
  1035. t.Fatal(err)
  1036. }
  1037. p := provisioner.List{
  1038. &provisioner.JWK{
  1039. Type: "JWK",
  1040. Name: "max",
  1041. EncryptedKey: "abc",
  1042. Key: &key,
  1043. },
  1044. &provisioner.JWK{
  1045. Type: "JWK",
  1046. Name: "mariano",
  1047. EncryptedKey: "def",
  1048. Key: &key,
  1049. },
  1050. }
  1051. pr := ProvisionersResponse{
  1052. Provisioners: p,
  1053. }
  1054. tests := []struct {
  1055. name string
  1056. fields fields
  1057. args args
  1058. statusCode int
  1059. }{
  1060. {"ok", fields{&mockAuthority{ret1: p, ret2: ""}}, args{httptest.NewRecorder(), req}, 200},
  1061. {"fail", fields{&mockAuthority{ret1: p, ret2: "", err: fmt.Errorf("the error")}}, args{httptest.NewRecorder(), req}, 500},
  1062. {"limit fail", fields{&mockAuthority{ret1: p, ret2: ""}}, args{httptest.NewRecorder(), reqLimitFail}, 400},
  1063. }
  1064. expected, err := json.Marshal(pr)
  1065. if err != nil {
  1066. t.Fatal(err)
  1067. }
  1068. expectedError400 := errs.BadRequest("limit 'abc' is not an integer")
  1069. expectedError400Bytes, err := json.Marshal(expectedError400)
  1070. assert.FatalError(t, err)
  1071. expectedError500 := errs.InternalServer("force")
  1072. expectedError500Bytes, err := json.Marshal(expectedError500)
  1073. assert.FatalError(t, err)
  1074. for _, tt := range tests {
  1075. t.Run(tt.name, func(t *testing.T) {
  1076. h := &caHandler{
  1077. Authority: tt.fields.Authority,
  1078. }
  1079. h.Provisioners(tt.args.w, tt.args.r)
  1080. rec := tt.args.w.(*httptest.ResponseRecorder)
  1081. res := rec.Result()
  1082. if res.StatusCode != tt.statusCode {
  1083. t.Errorf("caHandler.Provisioners StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  1084. }
  1085. body, err := io.ReadAll(res.Body)
  1086. res.Body.Close()
  1087. if err != nil {
  1088. t.Errorf("caHandler.Provisioners unexpected error = %v", err)
  1089. }
  1090. if tt.statusCode < http.StatusBadRequest {
  1091. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  1092. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expected)
  1093. }
  1094. } else {
  1095. switch tt.statusCode {
  1096. case 400:
  1097. if !bytes.Equal(bytes.TrimSpace(body), expectedError400Bytes) {
  1098. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expectedError400Bytes)
  1099. }
  1100. case 500:
  1101. if !bytes.Equal(bytes.TrimSpace(body), expectedError500Bytes) {
  1102. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expectedError500Bytes)
  1103. }
  1104. default:
  1105. t.Errorf("caHandler.Provisioner unexpected status code = %d", tt.statusCode)
  1106. }
  1107. }
  1108. })
  1109. }
  1110. }
  1111. func Test_caHandler_ProvisionerKey(t *testing.T) {
  1112. type fields struct {
  1113. Authority Authority
  1114. }
  1115. type args struct {
  1116. w http.ResponseWriter
  1117. r *http.Request
  1118. }
  1119. // Request with chi context
  1120. chiCtx := chi.NewRouteContext()
  1121. chiCtx.URLParams.Add("kid", "oV1p0MJeGQ7qBlK6B-oyfVdBRjh_e7VSK_YSEEqgW00")
  1122. req := httptest.NewRequest("GET", "http://example.com/provisioners/oV1p0MJeGQ7qBlK6B-oyfVdBRjh_e7VSK_YSEEqgW00/encrypted-key", nil)
  1123. req = req.WithContext(context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx))
  1124. tests := []struct {
  1125. name string
  1126. fields fields
  1127. args args
  1128. statusCode int
  1129. }{
  1130. {"ok", fields{&mockAuthority{ret1: privKey}}, args{httptest.NewRecorder(), req}, 200},
  1131. {"fail", fields{&mockAuthority{ret1: "", err: fmt.Errorf("not found")}}, args{httptest.NewRecorder(), req}, 404},
  1132. }
  1133. expected := []byte(`{"key":"` + privKey + `"}`)
  1134. expectedError404 := errs.NotFound("force")
  1135. expectedError404Bytes, err := json.Marshal(expectedError404)
  1136. assert.FatalError(t, err)
  1137. for _, tt := range tests {
  1138. t.Run(tt.name, func(t *testing.T) {
  1139. h := &caHandler{
  1140. Authority: tt.fields.Authority,
  1141. }
  1142. h.ProvisionerKey(tt.args.w, tt.args.r)
  1143. rec := tt.args.w.(*httptest.ResponseRecorder)
  1144. res := rec.Result()
  1145. if res.StatusCode != tt.statusCode {
  1146. t.Errorf("caHandler.Provisioners StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  1147. }
  1148. body, err := io.ReadAll(res.Body)
  1149. res.Body.Close()
  1150. if err != nil {
  1151. t.Errorf("caHandler.Provisioners unexpected error = %v", err)
  1152. }
  1153. if tt.statusCode < http.StatusBadRequest {
  1154. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  1155. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expected)
  1156. }
  1157. } else {
  1158. if !bytes.Equal(bytes.TrimSpace(body), expectedError404Bytes) {
  1159. t.Errorf("caHandler.Provisioners Body = %s, wants %s", body, expectedError404Bytes)
  1160. }
  1161. }
  1162. })
  1163. }
  1164. }
  1165. func Test_caHandler_Roots(t *testing.T) {
  1166. cs := &tls.ConnectionState{
  1167. PeerCertificates: []*x509.Certificate{parseCertificate(certPEM)},
  1168. }
  1169. tests := []struct {
  1170. name string
  1171. tls *tls.ConnectionState
  1172. cert *x509.Certificate
  1173. root *x509.Certificate
  1174. err error
  1175. statusCode int
  1176. }{
  1177. {"ok", cs, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  1178. {"no peer certificates", &tls.ConnectionState{}, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  1179. {"fail", cs, nil, nil, fmt.Errorf("an error"), http.StatusForbidden},
  1180. }
  1181. expected := []byte(`{"crts":["` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n"]}`)
  1182. for _, tt := range tests {
  1183. t.Run(tt.name, func(t *testing.T) {
  1184. h := New(&mockAuthority{ret1: []*x509.Certificate{tt.root}, err: tt.err}).(*caHandler)
  1185. req := httptest.NewRequest("GET", "http://example.com/roots", nil)
  1186. req.TLS = tt.tls
  1187. w := httptest.NewRecorder()
  1188. h.Roots(w, req)
  1189. res := w.Result()
  1190. if res.StatusCode != tt.statusCode {
  1191. t.Errorf("caHandler.Roots StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  1192. }
  1193. body, err := io.ReadAll(res.Body)
  1194. res.Body.Close()
  1195. if err != nil {
  1196. t.Errorf("caHandler.Roots unexpected error = %v", err)
  1197. }
  1198. if tt.statusCode < http.StatusBadRequest {
  1199. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  1200. t.Errorf("caHandler.Roots Body = %s, wants %s", body, expected)
  1201. }
  1202. }
  1203. })
  1204. }
  1205. }
  1206. func Test_caHandler_Federation(t *testing.T) {
  1207. cs := &tls.ConnectionState{
  1208. PeerCertificates: []*x509.Certificate{parseCertificate(certPEM)},
  1209. }
  1210. tests := []struct {
  1211. name string
  1212. tls *tls.ConnectionState
  1213. cert *x509.Certificate
  1214. root *x509.Certificate
  1215. err error
  1216. statusCode int
  1217. }{
  1218. {"ok", cs, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  1219. {"no peer certificates", &tls.ConnectionState{}, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
  1220. {"fail", cs, nil, nil, fmt.Errorf("an error"), http.StatusForbidden},
  1221. }
  1222. expected := []byte(`{"crts":["` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n"]}`)
  1223. for _, tt := range tests {
  1224. t.Run(tt.name, func(t *testing.T) {
  1225. h := New(&mockAuthority{ret1: []*x509.Certificate{tt.root}, err: tt.err}).(*caHandler)
  1226. req := httptest.NewRequest("GET", "http://example.com/federation", nil)
  1227. req.TLS = tt.tls
  1228. w := httptest.NewRecorder()
  1229. h.Federation(w, req)
  1230. res := w.Result()
  1231. if res.StatusCode != tt.statusCode {
  1232. t.Errorf("caHandler.Federation StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  1233. }
  1234. body, err := io.ReadAll(res.Body)
  1235. res.Body.Close()
  1236. if err != nil {
  1237. t.Errorf("caHandler.Federation unexpected error = %v", err)
  1238. }
  1239. if tt.statusCode < http.StatusBadRequest {
  1240. if !bytes.Equal(bytes.TrimSpace(body), expected) {
  1241. t.Errorf("caHandler.Federation Body = %s, wants %s", body, expected)
  1242. }
  1243. }
  1244. })
  1245. }
  1246. }
  1247. func Test_fmtPublicKey(t *testing.T) {
  1248. p256, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1249. if err != nil {
  1250. t.Fatal(err)
  1251. }
  1252. rsa1024, err := rsa.GenerateKey(rand.Reader, 1024)
  1253. if err != nil {
  1254. t.Fatal(err)
  1255. }
  1256. edPub, edPriv, err := ed25519.GenerateKey(rand.Reader)
  1257. if err != nil {
  1258. t.Fatal(err)
  1259. }
  1260. var dsa2048 dsa.PrivateKey
  1261. if err := dsa.GenerateParameters(&dsa2048.Parameters, rand.Reader, dsa.L2048N256); err != nil {
  1262. t.Fatal(err)
  1263. }
  1264. if err := dsa.GenerateKey(&dsa2048, rand.Reader); err != nil {
  1265. t.Fatal(err)
  1266. }
  1267. type args struct {
  1268. pub, priv interface{}
  1269. cert *x509.Certificate
  1270. }
  1271. tests := []struct {
  1272. name string
  1273. args args
  1274. want string
  1275. }{
  1276. {"p256", args{p256.Public(), p256, nil}, "ECDSA P-256"},
  1277. {"rsa1024", args{rsa1024.Public(), rsa1024, nil}, "RSA 1024"},
  1278. {"ed25519", args{edPub, edPriv, nil}, "Ed25519"},
  1279. {"dsa2048", args{cert: &x509.Certificate{PublicKeyAlgorithm: x509.DSA, PublicKey: &dsa2048.PublicKey}}, "DSA 2048"},
  1280. {"unknown", args{cert: &x509.Certificate{PublicKeyAlgorithm: x509.ECDSA, PublicKey: []byte("12345678")}}, "ECDSA unknown"},
  1281. }
  1282. for _, tt := range tests {
  1283. t.Run(tt.name, func(t *testing.T) {
  1284. var cert *x509.Certificate
  1285. if tt.args.cert != nil {
  1286. cert = tt.args.cert
  1287. } else {
  1288. cert = mustCertificate(t, tt.args.pub, tt.args.priv)
  1289. }
  1290. if got := fmtPublicKey(cert); got != tt.want {
  1291. t.Errorf("fmtPublicKey() = %v, want %v", got, tt.want)
  1292. }
  1293. })
  1294. }
  1295. }
  1296. func mustCertificate(t *testing.T, pub, priv interface{}) *x509.Certificate {
  1297. template := x509.Certificate{
  1298. SerialNumber: big.NewInt(1),
  1299. Subject: pkix.Name{
  1300. Organization: []string{"Acme Co"},
  1301. },
  1302. NotBefore: time.Now(),
  1303. NotAfter: time.Now().Add(24 * time.Hour),
  1304. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  1305. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  1306. BasicConstraintsValid: true,
  1307. }
  1308. der, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, priv)
  1309. if err != nil {
  1310. t.Fatal(err)
  1311. }
  1312. cert, err := x509.ParseCertificate(der)
  1313. if err != nil {
  1314. t.Fatal(err)
  1315. }
  1316. return cert
  1317. }