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. func TestNewCertificate(t *testing.T) {
  160. cert := parseCertificate(rootPEM)
  161. if !reflect.DeepEqual(Certificate{Certificate: cert}, NewCertificate(cert)) {
  162. t.Errorf("NewCertificate failed, got %v, wants %v", NewCertificate(cert), Certificate{Certificate: cert})
  163. }
  164. }
  165. func TestCertificate_MarshalJSON(t *testing.T) {
  166. type fields struct {
  167. Certificate *x509.Certificate
  168. }
  169. tests := []struct {
  170. name string
  171. fields fields
  172. want []byte
  173. wantErr bool
  174. }{
  175. {"nil", fields{Certificate: nil}, []byte("null"), false},
  176. {"empty", fields{Certificate: &x509.Certificate{Raw: nil}}, []byte(`"-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n"`), false},
  177. {"root", fields{Certificate: parseCertificate(rootPEM)}, []byte(`"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `\n"`), false},
  178. {"cert", fields{Certificate: parseCertificate(certPEM)}, []byte(`"` + strings.ReplaceAll(certPEM, "\n", `\n`) + `\n"`), false},
  179. }
  180. for _, tt := range tests {
  181. t.Run(tt.name, func(t *testing.T) {
  182. c := Certificate{
  183. Certificate: tt.fields.Certificate,
  184. }
  185. got, err := c.MarshalJSON()
  186. if (err != nil) != tt.wantErr {
  187. t.Errorf("Certificate.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  188. return
  189. }
  190. if !reflect.DeepEqual(got, tt.want) {
  191. t.Errorf("Certificate.MarshalJSON() = %s, want %s", got, tt.want)
  192. }
  193. })
  194. }
  195. }
  196. func TestCertificate_UnmarshalJSON(t *testing.T) {
  197. tests := []struct {
  198. name string
  199. data []byte
  200. wantCert bool
  201. wantErr bool
  202. }{
  203. {"no data", nil, false, true},
  204. {"incomplete string 1", []byte(`"foobar`), false, true}, {"incomplete string 2", []byte(`foobar"`), false, true},
  205. {"invalid string", []byte(`"foobar"`), false, true},
  206. {"invalid bytes 0", []byte{}, false, true}, {"invalid bytes 1", []byte{1}, false, true},
  207. {"empty csr", []byte(`"-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE----\n"`), false, true},
  208. {"invalid type", []byte(`"` + strings.ReplaceAll(csrPEM, "\n", `\n`) + `"`), false, true},
  209. {"empty string", []byte(`""`), false, false},
  210. {"json null", []byte(`null`), false, false},
  211. {"valid root", []byte(`"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `"`), true, false},
  212. {"valid cert", []byte(`"` + strings.ReplaceAll(certPEM, "\n", `\n`) + `"`), true, false},
  213. }
  214. for _, tt := range tests {
  215. t.Run(tt.name, func(t *testing.T) {
  216. var c Certificate
  217. if err := c.UnmarshalJSON(tt.data); (err != nil) != tt.wantErr {
  218. t.Errorf("Certificate.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  219. }
  220. if tt.wantCert && c.Certificate == nil {
  221. t.Error("Certificate.UnmarshalJSON() failed, Certificate is nil")
  222. }
  223. })
  224. }
  225. }
  226. func TestCertificate_UnmarshalJSON_json(t *testing.T) {
  227. tests := []struct {
  228. name string
  229. data string
  230. wantCert bool
  231. wantErr bool
  232. }{
  233. {"invalid type (bool)", `{"crt":true}`, false, true},
  234. {"invalid type (number)", `{"crt":123}`, false, true},
  235. {"invalid type (object)", `{"crt":{}}`, false, true},
  236. {"empty crt (null)", `{"crt":null}`, false, false},
  237. {"empty crt (string)", `{"crt":""}`, false, false},
  238. {"empty crt", `{"crt":"-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE----\n"}`, false, true},
  239. {"valid crt", `{"crt":"` + strings.ReplaceAll(certPEM, "\n", `\n`) + `"}`, true, false},
  240. }
  241. type request struct {
  242. Cert Certificate `json:"crt"`
  243. }
  244. for _, tt := range tests {
  245. t.Run(tt.name, func(t *testing.T) {
  246. var body request
  247. if err := json.Unmarshal([]byte(tt.data), &body); (err != nil) != tt.wantErr {
  248. t.Errorf("json.Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
  249. }
  250. switch tt.wantCert {
  251. case true:
  252. if body.Cert.Certificate == nil {
  253. t.Error("json.Unmarshal() failed, Certificate is nil")
  254. }
  255. case false:
  256. if body.Cert.Certificate != nil {
  257. t.Error("json.Unmarshal() failed, Certificate is not nil")
  258. }
  259. }
  260. })
  261. }
  262. }
  263. func TestNewCertificateRequest(t *testing.T) {
  264. csr := parseCertificateRequest(csrPEM)
  265. if !reflect.DeepEqual(CertificateRequest{CertificateRequest: csr}, NewCertificateRequest(csr)) {
  266. t.Errorf("NewCertificateRequest failed, got %v, wants %v", NewCertificateRequest(csr), CertificateRequest{CertificateRequest: csr})
  267. }
  268. }
  269. func TestCertificateRequest_MarshalJSON(t *testing.T) {
  270. type fields struct {
  271. CertificateRequest *x509.CertificateRequest
  272. }
  273. tests := []struct {
  274. name string
  275. fields fields
  276. want []byte
  277. wantErr bool
  278. }{
  279. {"nil", fields{CertificateRequest: nil}, []byte("null"), false},
  280. {"empty", fields{CertificateRequest: &x509.CertificateRequest{}}, []byte(`"-----BEGIN CERTIFICATE REQUEST-----\n-----END CERTIFICATE REQUEST-----\n"`), false},
  281. {"csr", fields{CertificateRequest: parseCertificateRequest(csrPEM)}, []byte(`"` + strings.ReplaceAll(csrPEM, "\n", `\n`) + `\n"`), false},
  282. }
  283. for _, tt := range tests {
  284. t.Run(tt.name, func(t *testing.T) {
  285. c := CertificateRequest{
  286. CertificateRequest: tt.fields.CertificateRequest,
  287. }
  288. got, err := c.MarshalJSON()
  289. if (err != nil) != tt.wantErr {
  290. t.Errorf("CertificateRequest.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  291. return
  292. }
  293. if !reflect.DeepEqual(got, tt.want) {
  294. t.Errorf("CertificateRequest.MarshalJSON() = %s, want %s", got, tt.want)
  295. }
  296. })
  297. }
  298. }
  299. func TestCertificateRequest_UnmarshalJSON(t *testing.T) {
  300. tests := []struct {
  301. name string
  302. data []byte
  303. wantCert bool
  304. wantErr bool
  305. }{
  306. {"no data", nil, false, true},
  307. {"incomplete string 1", []byte(`"foobar`), false, true}, {"incomplete string 2", []byte(`foobar"`), false, true},
  308. {"invalid string", []byte(`"foobar"`), false, true},
  309. {"invalid bytes 0", []byte{}, false, true}, {"invalid bytes 1", []byte{1}, false, true},
  310. {"empty csr", []byte(`"-----BEGIN CERTIFICATE REQUEST-----\n-----END CERTIFICATE REQUEST----\n"`), false, true},
  311. {"invalid type", []byte(`"` + strings.ReplaceAll(rootPEM, "\n", `\n`) + `"`), false, true},
  312. {"empty string", []byte(`""`), false, false},
  313. {"json null", []byte(`null`), false, false},
  314. {"valid csr", []byte(`"` + strings.ReplaceAll(csrPEM, "\n", `\n`) + `"`), true, false},
  315. }
  316. for _, tt := range tests {
  317. t.Run(tt.name, func(t *testing.T) {
  318. var c CertificateRequest
  319. if err := c.UnmarshalJSON(tt.data); (err != nil) != tt.wantErr {
  320. t.Errorf("CertificateRequest.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  321. }
  322. if tt.wantCert && c.CertificateRequest == nil {
  323. t.Error("CertificateRequest.UnmarshalJSON() failed, CertificateRequet is nil")
  324. }
  325. })
  326. }
  327. }
  328. func TestCertificateRequest_UnmarshalJSON_json(t *testing.T) {
  329. tests := []struct {
  330. name string
  331. data string
  332. wantCert bool
  333. wantErr bool
  334. }{
  335. {"invalid type (bool)", `{"csr":true}`, false, true},
  336. {"invalid type (number)", `{"csr":123}`, false, true},
  337. {"invalid type (object)", `{"csr":{}}`, false, true},
  338. {"empty csr (null)", `{"csr":null}`, false, false},
  339. {"empty csr (string)", `{"csr":""}`, false, false},
  340. {"empty csr", `{"csr":"-----BEGIN CERTIFICATE REQUEST-----\n-----END CERTIFICATE REQUEST----\n"}`, false, true},
  341. {"valid csr", `{"csr":"` + strings.ReplaceAll(csrPEM, "\n", `\n`) + `"}`, true, false},
  342. }
  343. type request struct {
  344. CSR CertificateRequest `json:"csr"`
  345. }
  346. for _, tt := range tests {
  347. t.Run(tt.name, func(t *testing.T) {
  348. var body request
  349. if err := json.Unmarshal([]byte(tt.data), &body); (err != nil) != tt.wantErr {
  350. t.Errorf("json.Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
  351. }
  352. switch tt.wantCert {
  353. case true:
  354. if body.CSR.CertificateRequest == nil {
  355. t.Error("json.Unmarshal() failed, CertificateRequest is nil")
  356. }
  357. case false:
  358. if body.CSR.CertificateRequest != nil {
  359. t.Error("json.Unmarshal() failed, CertificateRequest is not nil")
  360. }
  361. }
  362. })
  363. }
  364. }
  365. func TestSignRequest_Validate(t *testing.T) {
  366. csr := parseCertificateRequest(csrPEM)
  367. bad := parseCertificateRequest(csrPEM)
  368. bad.Signature[0]++
  369. type fields struct {
  370. CsrPEM CertificateRequest
  371. OTT string
  372. NotBefore time.Time
  373. NotAfter time.Time
  374. }
  375. tests := []struct {
  376. name string
  377. fields fields
  378. err error
  379. }{
  380. {"missing csr", fields{CertificateRequest{}, "foobarzar", time.Time{}, time.Time{}}, errors.New("missing csr")},
  381. {"invalid csr", fields{CertificateRequest{bad}, "foobarzar", time.Time{}, time.Time{}}, errors.New("invalid csr")},
  382. {"missing ott", fields{CertificateRequest{csr}, "", time.Time{}, time.Time{}}, errors.New("missing ott")},
  383. }
  384. for _, tt := range tests {
  385. t.Run(tt.name, func(t *testing.T) {
  386. s := &SignRequest{
  387. CsrPEM: tt.fields.CsrPEM,
  388. OTT: tt.fields.OTT,
  389. NotAfter: NewTimeDuration(tt.fields.NotAfter),
  390. NotBefore: NewTimeDuration(tt.fields.NotBefore),
  391. }
  392. if err := s.Validate(); err != nil {
  393. if assert.NotNil(t, tt.err) {
  394. assert.HasPrefix(t, err.Error(), tt.err.Error())
  395. }
  396. } else {
  397. assert.Nil(t, tt.err)
  398. }
  399. })
  400. }
  401. }
  402. type mockProvisioner struct {
  403. ret1, ret2, ret3 interface{}
  404. err error
  405. getID func() string
  406. getIDForToken func() string
  407. getTokenID func(string) (string, error)
  408. getName func() string
  409. getType func() provisioner.Type
  410. getEncryptedKey func() (string, string, bool)
  411. init func(provisioner.Config) error
  412. authorizeRenew func(ctx context.Context, cert *x509.Certificate) error
  413. authorizeRevoke func(ctx context.Context, token string) error
  414. authorizeSign func(ctx context.Context, ott string) ([]provisioner.SignOption, error)
  415. authorizeRenewal func(*x509.Certificate) error
  416. authorizeSSHSign func(ctx context.Context, token string) ([]provisioner.SignOption, error)
  417. authorizeSSHRevoke func(ctx context.Context, token string) error
  418. authorizeSSHRenew func(ctx context.Context, token string) (*ssh.Certificate, error)
  419. authorizeSSHRekey func(ctx context.Context, token string) (*ssh.Certificate, []provisioner.SignOption, error)
  420. }
  421. func (m *mockProvisioner) GetID() string {
  422. if m.getID != nil {
  423. return m.getID()
  424. }
  425. return m.ret1.(string)
  426. }
  427. func (m *mockProvisioner) GetIDForToken() string {
  428. if m.getIDForToken != nil {
  429. return m.getIDForToken()
  430. }
  431. return m.ret1.(string)
  432. }
  433. func (m *mockProvisioner) GetTokenID(token string) (string, error) {
  434. if m.getTokenID != nil {
  435. return m.getTokenID(token)
  436. }
  437. if m.ret1 == nil {
  438. return "", m.err
  439. }
  440. return m.ret1.(string), m.err
  441. }
  442. func (m *mockProvisioner) GetName() string {
  443. if m.getName != nil {
  444. return m.getName()
  445. }
  446. return m.ret1.(string)
  447. }
  448. func (m *mockProvisioner) GetType() provisioner.Type {
  449. if m.getType != nil {
  450. return m.getType()
  451. }
  452. return m.ret1.(provisioner.Type)
  453. }
  454. func (m *mockProvisioner) GetEncryptedKey() (string, string, bool) {
  455. if m.getEncryptedKey != nil {
  456. return m.getEncryptedKey()
  457. }
  458. return m.ret1.(string), m.ret2.(string), m.ret3.(bool)
  459. }
  460. func (m *mockProvisioner) Init(c provisioner.Config) error {
  461. if m.init != nil {
  462. return m.init(c)
  463. }
  464. return m.err
  465. }
  466. func (m *mockProvisioner) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  467. if m.authorizeRenew != nil {
  468. return m.authorizeRenew(ctx, cert)
  469. }
  470. return m.err
  471. }
  472. func (m *mockProvisioner) AuthorizeRevoke(ctx context.Context, token string) error {
  473. if m.authorizeRevoke != nil {
  474. return m.authorizeRevoke(ctx, token)
  475. }
  476. return m.err
  477. }
  478. func (m *mockProvisioner) AuthorizeSign(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
  479. if m.authorizeSign != nil {
  480. return m.authorizeSign(ctx, ott)
  481. }
  482. return m.ret1.([]provisioner.SignOption), m.err
  483. }
  484. func (m *mockProvisioner) AuthorizeRenewal(c *x509.Certificate) error {
  485. if m.authorizeRenewal != nil {
  486. return m.authorizeRenewal(c)
  487. }
  488. return m.err
  489. }
  490. func (m *mockProvisioner) AuthorizeSSHSign(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  491. if m.authorizeSSHSign != nil {
  492. return m.authorizeSSHSign(ctx, token)
  493. }
  494. return m.ret1.([]provisioner.SignOption), m.err
  495. }
  496. func (m *mockProvisioner) AuthorizeSSHRevoke(ctx context.Context, token string) error {
  497. if m.authorizeSSHRevoke != nil {
  498. return m.authorizeSSHRevoke(ctx, token)
  499. }
  500. return m.err
  501. }
  502. func (m *mockProvisioner) AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  503. if m.authorizeSSHRenew != nil {
  504. return m.authorizeSSHRenew(ctx, token)
  505. }
  506. return m.ret1.(*ssh.Certificate), m.err
  507. }
  508. func (m *mockProvisioner) AuthorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []provisioner.SignOption, error) {
  509. if m.authorizeSSHRekey != nil {
  510. return m.authorizeSSHRekey(ctx, token)
  511. }
  512. return m.ret1.(*ssh.Certificate), m.ret2.([]provisioner.SignOption), m.err
  513. }
  514. type mockAuthority struct {
  515. ret1, ret2 interface{}
  516. err error
  517. authorizeSign func(ott string) ([]provisioner.SignOption, error)
  518. getTLSOptions func() *authority.TLSOptions
  519. root func(shasum string) (*x509.Certificate, error)
  520. sign func(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
  521. renew func(cert *x509.Certificate) ([]*x509.Certificate, error)
  522. rekey func(oldCert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error)
  523. loadProvisionerByCertificate func(cert *x509.Certificate) (provisioner.Interface, error)
  524. loadProvisionerByName func(name string) (provisioner.Interface, error)
  525. getProvisioners func(nextCursor string, limit int) (provisioner.List, string, error)
  526. revoke func(context.Context, *authority.RevokeOptions) error
  527. getEncryptedKey func(kid string) (string, error)
  528. getRoots func() ([]*x509.Certificate, error)
  529. getFederation func() ([]*x509.Certificate, error)
  530. signSSH func(ctx context.Context, key ssh.PublicKey, opts provisioner.SignSSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  531. signSSHAddUser func(ctx context.Context, key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error)
  532. renewSSH func(ctx context.Context, cert *ssh.Certificate) (*ssh.Certificate, error)
  533. rekeySSH func(ctx context.Context, cert *ssh.Certificate, key ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  534. getSSHHosts func(ctx context.Context, cert *x509.Certificate) ([]authority.Host, error)
  535. getSSHRoots func(ctx context.Context) (*authority.SSHKeys, error)
  536. getSSHFederation func(ctx context.Context) (*authority.SSHKeys, error)
  537. getSSHConfig func(ctx context.Context, typ string, data map[string]string) ([]templates.Output, error)
  538. checkSSHHost func(ctx context.Context, principal, token string) (bool, error)
  539. getSSHBastion func(ctx context.Context, user string, hostname string) (*authority.Bastion, error)
  540. version func() authority.Version
  541. }
  542. // TODO: remove once Authorize is deprecated.
  543. func (m *mockAuthority) Authorize(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
  544. return m.AuthorizeSign(ott)
  545. }
  546. func (m *mockAuthority) AuthorizeSign(ott string) ([]provisioner.SignOption, error) {
  547. if m.authorizeSign != nil {
  548. return m.authorizeSign(ott)
  549. }
  550. return m.ret1.([]provisioner.SignOption), m.err
  551. }
  552. func (m *mockAuthority) GetTLSOptions() *authority.TLSOptions {
  553. if m.getTLSOptions != nil {
  554. return m.getTLSOptions()
  555. }
  556. return m.ret1.(*authority.TLSOptions)
  557. }
  558. func (m *mockAuthority) Root(shasum string) (*x509.Certificate, error) {
  559. if m.root != nil {
  560. return m.root(shasum)
  561. }
  562. return m.ret1.(*x509.Certificate), m.err
  563. }
  564. func (m *mockAuthority) Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  565. if m.sign != nil {
  566. return m.sign(cr, opts, signOpts...)
  567. }
  568. return []*x509.Certificate{m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate)}, m.err
  569. }
  570. func (m *mockAuthority) Renew(cert *x509.Certificate) ([]*x509.Certificate, error) {
  571. if m.renew != nil {
  572. return m.renew(cert)
  573. }
  574. return []*x509.Certificate{m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate)}, m.err
  575. }
  576. func (m *mockAuthority) Rekey(oldcert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error) {
  577. if m.rekey != nil {
  578. return m.rekey(oldcert, pk)
  579. }
  580. return []*x509.Certificate{m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate)}, m.err
  581. }
  582. func (m *mockAuthority) GetProvisioners(nextCursor string, limit int) (provisioner.List, string, error) {
  583. if m.getProvisioners != nil {
  584. return m.getProvisioners(nextCursor, limit)
  585. }
  586. return m.ret1.(provisioner.List), m.ret2.(string), m.err
  587. }
  588. func (m *mockAuthority) LoadProvisionerByCertificate(cert *x509.Certificate) (provisioner.Interface, error) {
  589. if m.loadProvisionerByCertificate != nil {
  590. return m.loadProvisionerByCertificate(cert)
  591. }
  592. return m.ret1.(provisioner.Interface), m.err
  593. }
  594. func (m *mockAuthority) LoadProvisionerByName(name string) (provisioner.Interface, error) {
  595. if m.loadProvisionerByName != nil {
  596. return m.loadProvisionerByName(name)
  597. }
  598. return m.ret1.(provisioner.Interface), m.err
  599. }
  600. func (m *mockAuthority) Revoke(ctx context.Context, opts *authority.RevokeOptions) error {
  601. if m.revoke != nil {
  602. return m.revoke(ctx, opts)
  603. }
  604. return m.err
  605. }
  606. func (m *mockAuthority) GetEncryptedKey(kid string) (string, error) {
  607. if m.getEncryptedKey != nil {
  608. return m.getEncryptedKey(kid)
  609. }
  610. return m.ret1.(string), m.err
  611. }
  612. func (m *mockAuthority) GetRoots() ([]*x509.Certificate, error) {
  613. if m.getRoots != nil {
  614. return m.getRoots()
  615. }
  616. return m.ret1.([]*x509.Certificate), m.err
  617. }
  618. func (m *mockAuthority) GetFederation() ([]*x509.Certificate, error) {
  619. if m.getFederation != nil {
  620. return m.getFederation()
  621. }
  622. return m.ret1.([]*x509.Certificate), m.err
  623. }
  624. func (m *mockAuthority) SignSSH(ctx context.Context, key ssh.PublicKey, opts provisioner.SignSSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  625. if m.signSSH != nil {
  626. return m.signSSH(ctx, key, opts, signOpts...)
  627. }
  628. return m.ret1.(*ssh.Certificate), m.err
  629. }
  630. func (m *mockAuthority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error) {
  631. if m.signSSHAddUser != nil {
  632. return m.signSSHAddUser(ctx, key, cert)
  633. }
  634. return m.ret1.(*ssh.Certificate), m.err
  635. }
  636. func (m *mockAuthority) RenewSSH(ctx context.Context, cert *ssh.Certificate) (*ssh.Certificate, error) {
  637. if m.renewSSH != nil {
  638. return m.renewSSH(ctx, cert)
  639. }
  640. return m.ret1.(*ssh.Certificate), m.err
  641. }
  642. func (m *mockAuthority) RekeySSH(ctx context.Context, cert *ssh.Certificate, key ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  643. if m.rekeySSH != nil {
  644. return m.rekeySSH(ctx, cert, key, signOpts...)
  645. }
  646. return m.ret1.(*ssh.Certificate), m.err
  647. }
  648. func (m *mockAuthority) GetSSHHosts(ctx context.Context, cert *x509.Certificate) ([]authority.Host, error) {
  649. if m.getSSHHosts != nil {
  650. return m.getSSHHosts(ctx, cert)
  651. }
  652. return m.ret1.([]authority.Host), m.err
  653. }
  654. func (m *mockAuthority) GetSSHRoots(ctx context.Context) (*authority.SSHKeys, error) {
  655. if m.getSSHRoots != nil {
  656. return m.getSSHRoots(ctx)
  657. }
  658. return m.ret1.(*authority.SSHKeys), m.err
  659. }
  660. func (m *mockAuthority) GetSSHFederation(ctx context.Context) (*authority.SSHKeys, error) {
  661. if m.getSSHFederation != nil {
  662. return m.getSSHFederation(ctx)
  663. }
  664. return m.ret1.(*authority.SSHKeys), m.err
  665. }
  666. func (m *mockAuthority) GetSSHConfig(ctx context.Context, typ string, data map[string]string) ([]templates.Output, error) {
  667. if m.getSSHConfig != nil {
  668. return m.getSSHConfig(ctx, typ, data)
  669. }
  670. return m.ret1.([]templates.Output), m.err
  671. }
  672. func (m *mockAuthority) CheckSSHHost(ctx context.Context, principal, token string) (bool, error) {
  673. if m.checkSSHHost != nil {
  674. return m.checkSSHHost(ctx, principal, token)
  675. }
  676. return m.ret1.(bool), m.err
  677. }
  678. func (m *mockAuthority) GetSSHBastion(ctx context.Context, user, hostname string) (*authority.Bastion, error) {
  679. if m.getSSHBastion != nil {
  680. return m.getSSHBastion(ctx, user, hostname)
  681. }
  682. return m.ret1.(*authority.Bastion), m.err
  683. }
  684. func (m *mockAuthority) Version() authority.Version {
  685. if m.version != nil {
  686. return m.version()
  687. }
  688. return m.ret1.(authority.Version)
  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. }