api_test.go 52 KB

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