api_test.go 50 KB

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