4
0

api_test.go 53 KB

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