4
0

api_test.go 54 KB

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