api_test.go 38 KB

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