4
0

api_test.go 51 KB

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