api_test.go 51 KB

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