api_test.go 46 KB

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