client.go 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  1. package ca
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "crypto/ecdsa"
  7. "crypto/elliptic"
  8. "crypto/rand"
  9. "crypto/sha256"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "crypto/x509/pkix"
  13. "encoding/hex"
  14. "encoding/json"
  15. "encoding/pem"
  16. "fmt"
  17. "io"
  18. "net/http"
  19. "net/url"
  20. "os"
  21. "path/filepath"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "github.com/pkg/errors"
  26. "golang.org/x/net/http2"
  27. "google.golang.org/protobuf/encoding/protojson"
  28. "google.golang.org/protobuf/proto"
  29. "github.com/smallstep/cli-utils/step"
  30. "go.step.sm/crypto/jose"
  31. "go.step.sm/crypto/keyutil"
  32. "go.step.sm/crypto/pemutil"
  33. "go.step.sm/crypto/randutil"
  34. "go.step.sm/crypto/x509util"
  35. "github.com/smallstep/certificates/api"
  36. "github.com/smallstep/certificates/authority"
  37. "github.com/smallstep/certificates/authority/provisioner"
  38. "github.com/smallstep/certificates/ca/client"
  39. "github.com/smallstep/certificates/ca/identity"
  40. "github.com/smallstep/certificates/errs"
  41. )
  42. // DisableIdentity is a global variable to disable the identity.
  43. var DisableIdentity = false
  44. // UserAgent will set the User-Agent header in the client requests.
  45. var UserAgent = "step-http-client/1.0"
  46. type uaClient struct {
  47. Client *http.Client
  48. }
  49. func newClient(transport http.RoundTripper, timeout time.Duration) *uaClient {
  50. return &uaClient{
  51. Client: &http.Client{
  52. Transport: transport,
  53. Timeout: timeout,
  54. },
  55. }
  56. }
  57. //nolint:gosec // used in bootstrap protocol
  58. func newInsecureClient() *uaClient {
  59. return &uaClient{
  60. Client: &http.Client{
  61. Transport: getDefaultTransport(&tls.Config{InsecureSkipVerify: true}),
  62. },
  63. }
  64. }
  65. func (c *uaClient) GetTransport() http.RoundTripper {
  66. return c.Client.Transport
  67. }
  68. func (c *uaClient) SetTransport(tr http.RoundTripper) {
  69. c.Client.Transport = tr
  70. }
  71. func (c *uaClient) Get(u string) (*http.Response, error) {
  72. return c.GetWithContext(context.Background(), u)
  73. }
  74. func (c *uaClient) GetWithContext(ctx context.Context, u string) (*http.Response, error) {
  75. req, err := http.NewRequestWithContext(ctx, "GET", u, http.NoBody)
  76. if err != nil {
  77. return nil, errors.Wrapf(err, "create GET %s request failed", u)
  78. }
  79. return c.Do(req)
  80. }
  81. func (c *uaClient) Post(u, contentType string, body io.Reader) (*http.Response, error) {
  82. return c.PostWithContext(context.Background(), u, contentType, body)
  83. }
  84. func (c *uaClient) PostWithContext(ctx context.Context, u, contentType string, body io.Reader) (*http.Response, error) {
  85. req, err := http.NewRequestWithContext(ctx, "POST", u, body)
  86. if err != nil {
  87. return nil, errors.Wrapf(err, "create POST %s request failed", u)
  88. }
  89. req.Header.Set("Content-Type", contentType)
  90. return c.Do(req)
  91. }
  92. // requestIDHeader is the header name used for propagating request IDs from
  93. // the CA client to the CA and back again.
  94. const requestIDHeader = "X-Request-Id"
  95. // newRequestID generates a new random UUIDv4 request ID. If it fails,
  96. // the request ID will be the empty string.
  97. func newRequestID() string {
  98. requestID, err := randutil.UUIDv4()
  99. if err != nil {
  100. return ""
  101. }
  102. return requestID
  103. }
  104. // enforceRequestID checks if the X-Request-Id HTTP header is filled. If it's
  105. // empty, the context is searched for a request ID. If that's also empty, a new
  106. // request ID is generated.
  107. func enforceRequestID(r *http.Request) {
  108. if requestID := r.Header.Get(requestIDHeader); requestID == "" {
  109. if reqID, ok := client.RequestIDFromContext(r.Context()); ok {
  110. // TODO(hs): ensure the request ID from the context is fresh, and thus hasn't been
  111. // used before by the client (unless it's a retry for the same request)?
  112. requestID = reqID
  113. } else {
  114. requestID = newRequestID()
  115. }
  116. r.Header.Set(requestIDHeader, requestID)
  117. }
  118. }
  119. func (c *uaClient) Do(req *http.Request) (*http.Response, error) {
  120. req.Header.Set("User-Agent", UserAgent)
  121. enforceRequestID(req)
  122. return c.Client.Do(req)
  123. }
  124. // RetryFunc defines the method used to retry a request. If it returns true, the
  125. // request will be retried once.
  126. type RetryFunc func(code int) bool
  127. // ClientOption is the type of options passed to the Client constructor.
  128. type ClientOption func(o *clientOptions) error
  129. type clientOptions struct {
  130. transport http.RoundTripper
  131. timeout time.Duration
  132. rootSHA256 string
  133. rootFilename string
  134. rootBundle []byte
  135. certificate tls.Certificate
  136. getClientCertificate func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
  137. retryFunc RetryFunc
  138. x5cJWK *jose.JSONWebKey
  139. x5cCertFile string
  140. x5cCertStrs []string
  141. x5cCert *x509.Certificate
  142. x5cSubject string
  143. }
  144. func (o *clientOptions) apply(opts []ClientOption) (err error) {
  145. o.applyDefaultIdentity()
  146. for _, fn := range opts {
  147. if err = fn(o); err != nil {
  148. return
  149. }
  150. }
  151. return
  152. }
  153. // applyDefaultIdentity sets the options for the default identity if the
  154. // identity file is present. The identity is enabled by default.
  155. func (o *clientOptions) applyDefaultIdentity() {
  156. if DisableIdentity {
  157. return
  158. }
  159. // Do not load an identity if something fails
  160. i, err := identity.LoadDefaultIdentity()
  161. if err != nil {
  162. return
  163. }
  164. if err := i.Validate(); err != nil {
  165. return
  166. }
  167. crt, err := i.TLSCertificate()
  168. if err != nil {
  169. return
  170. }
  171. o.certificate = crt
  172. o.getClientCertificate = i.GetClientCertificateFunc()
  173. }
  174. // checkTransport checks if other ways to set up a transport have been provided.
  175. // If they have it returns an error.
  176. func (o *clientOptions) checkTransport() error {
  177. if o.transport != nil || o.rootFilename != "" || o.rootSHA256 != "" || o.rootBundle != nil {
  178. return errors.New("multiple transport methods have been configured")
  179. }
  180. return nil
  181. }
  182. // getTransport returns the transport configured in the clientOptions.
  183. func (o *clientOptions) getTransport(endpoint string) (tr http.RoundTripper, err error) {
  184. if o.transport != nil {
  185. tr = o.transport
  186. }
  187. if o.rootFilename != "" {
  188. if tr, err = getTransportFromFile(o.rootFilename); err != nil {
  189. return nil, err
  190. }
  191. }
  192. if o.rootSHA256 != "" {
  193. if tr, err = getTransportFromSHA256(endpoint, o.rootSHA256); err != nil {
  194. return nil, err
  195. }
  196. }
  197. if o.rootBundle != nil {
  198. if tr, err = getTransportFromCABundle(o.rootBundle); err != nil {
  199. return nil, err
  200. }
  201. }
  202. // As the last option attempt to load the default root ca
  203. if tr == nil {
  204. rootFile := getRootCAPath()
  205. if _, err := os.Stat(rootFile); err == nil {
  206. if tr, err = getTransportFromFile(rootFile); err != nil {
  207. return nil, err
  208. }
  209. }
  210. if tr == nil {
  211. return nil, errors.New("a transport, a root cert, or a root sha256 must be used")
  212. }
  213. }
  214. // Add client certificate if available
  215. if o.certificate.Certificate != nil {
  216. switch tr := tr.(type) {
  217. case *http.Transport:
  218. if tr.TLSClientConfig == nil {
  219. tr.TLSClientConfig = &tls.Config{
  220. MinVersion: tls.VersionTLS12,
  221. }
  222. }
  223. if len(tr.TLSClientConfig.Certificates) == 0 && tr.TLSClientConfig.GetClientCertificate == nil {
  224. tr.TLSClientConfig.Certificates = []tls.Certificate{o.certificate}
  225. tr.TLSClientConfig.GetClientCertificate = o.getClientCertificate
  226. }
  227. case *http2.Transport:
  228. if tr.TLSClientConfig == nil {
  229. tr.TLSClientConfig = &tls.Config{
  230. MinVersion: tls.VersionTLS12,
  231. }
  232. }
  233. if len(tr.TLSClientConfig.Certificates) == 0 && tr.TLSClientConfig.GetClientCertificate == nil {
  234. tr.TLSClientConfig.Certificates = []tls.Certificate{o.certificate}
  235. tr.TLSClientConfig.GetClientCertificate = o.getClientCertificate
  236. }
  237. default:
  238. return nil, errors.Errorf("unsupported transport type %T", tr)
  239. }
  240. }
  241. return tr, nil
  242. }
  243. // WithTransport adds a custom transport to the Client. It will fail if a
  244. // previous option to create the transport has been configured.
  245. func WithTransport(tr http.RoundTripper) ClientOption {
  246. return func(o *clientOptions) error {
  247. if err := o.checkTransport(); err != nil {
  248. return err
  249. }
  250. o.transport = tr
  251. return nil
  252. }
  253. }
  254. // WithInsecure adds a insecure transport that bypasses TLS verification.
  255. func WithInsecure() ClientOption {
  256. return func(o *clientOptions) error {
  257. o.transport = &http.Transport{
  258. Proxy: http.ProxyFromEnvironment,
  259. TLSClientConfig: &tls.Config{
  260. MinVersion: tls.VersionTLS12,
  261. //nolint:gosec // insecure option
  262. InsecureSkipVerify: true,
  263. },
  264. }
  265. return nil
  266. }
  267. }
  268. // WithRootFile will create the transport using the given root certificate. It
  269. // will fail if a previous option to create the transport has been configured.
  270. func WithRootFile(filename string) ClientOption {
  271. return func(o *clientOptions) error {
  272. if err := o.checkTransport(); err != nil {
  273. return err
  274. }
  275. o.rootFilename = filename
  276. return nil
  277. }
  278. }
  279. // WithRootSHA256 will create the transport using an insecure client to retrieve
  280. // the root certificate using its fingerprint. It will fail if a previous option
  281. // to create the transport has been configured.
  282. func WithRootSHA256(sum string) ClientOption {
  283. return func(o *clientOptions) error {
  284. if err := o.checkTransport(); err != nil {
  285. return err
  286. }
  287. o.rootSHA256 = sum
  288. return nil
  289. }
  290. }
  291. // WithCABundle will create the transport using the given root certificates. It
  292. // will fail if a previous option to create the transport has been configured.
  293. func WithCABundle(bundle []byte) ClientOption {
  294. return func(o *clientOptions) error {
  295. if err := o.checkTransport(); err != nil {
  296. return err
  297. }
  298. o.rootBundle = bundle
  299. return nil
  300. }
  301. }
  302. // WithCertificate will set the given certificate as the TLS client certificate
  303. // in the client.
  304. func WithCertificate(cert tls.Certificate) ClientOption {
  305. return func(o *clientOptions) error {
  306. o.certificate = cert
  307. return nil
  308. }
  309. }
  310. // WithAdminX5C will set the given file as the X5C certificate for use
  311. // by the client.
  312. func WithAdminX5C(certs []*x509.Certificate, key interface{}, passwordFile string) ClientOption {
  313. return func(o *clientOptions) error {
  314. // Get private key from given key file
  315. var (
  316. err error
  317. opts []jose.Option
  318. )
  319. if passwordFile != "" {
  320. opts = append(opts, jose.WithPasswordFile(passwordFile))
  321. }
  322. blk, err := pemutil.Serialize(key)
  323. if err != nil {
  324. return errors.Wrap(err, "error serializing private key")
  325. }
  326. o.x5cJWK, err = jose.ParseKey(pem.EncodeToMemory(blk), opts...)
  327. if err != nil {
  328. return err
  329. }
  330. o.x5cCertStrs, err = jose.ValidateX5C(certs, o.x5cJWK.Key)
  331. if err != nil {
  332. return errors.Wrap(err, "error validating x5c certificate chain and key for use in x5c header")
  333. }
  334. o.x5cCert = certs[0]
  335. switch leaf := certs[0]; {
  336. case leaf.Subject.CommonName != "":
  337. o.x5cSubject = leaf.Subject.CommonName
  338. case len(leaf.DNSNames) > 0:
  339. o.x5cSubject = leaf.DNSNames[0]
  340. case len(leaf.EmailAddresses) > 0:
  341. o.x5cSubject = leaf.EmailAddresses[0]
  342. }
  343. return nil
  344. }
  345. }
  346. // WithRetryFunc defines a method used to retry a request.
  347. func WithRetryFunc(fn RetryFunc) ClientOption {
  348. return func(o *clientOptions) error {
  349. o.retryFunc = fn
  350. return nil
  351. }
  352. }
  353. // WithTimeout defines the time limit for requests made by this client. The
  354. // timeout includes connection time, any redirects, and reading the response
  355. // body.
  356. func WithTimeout(d time.Duration) ClientOption {
  357. return func(o *clientOptions) error {
  358. o.timeout = d
  359. return nil
  360. }
  361. }
  362. func getTransportFromFile(filename string) (http.RoundTripper, error) {
  363. data, err := os.ReadFile(filename)
  364. if err != nil {
  365. return nil, errors.Wrapf(err, "error reading %s", filename)
  366. }
  367. pool := x509.NewCertPool()
  368. if !pool.AppendCertsFromPEM(data) {
  369. return nil, errors.Errorf("error parsing %s: no certificates found", filename)
  370. }
  371. return getDefaultTransport(&tls.Config{
  372. MinVersion: tls.VersionTLS12,
  373. PreferServerCipherSuites: true,
  374. RootCAs: pool,
  375. }), nil
  376. }
  377. func getTransportFromSHA256(endpoint, sum string) (http.RoundTripper, error) {
  378. u, err := parseEndpoint(endpoint)
  379. if err != nil {
  380. return nil, err
  381. }
  382. caClient := &Client{endpoint: u}
  383. root, err := caClient.Root(sum)
  384. if err != nil {
  385. return nil, err
  386. }
  387. pool := x509.NewCertPool()
  388. pool.AddCert(root.RootPEM.Certificate)
  389. return getDefaultTransport(&tls.Config{
  390. MinVersion: tls.VersionTLS12,
  391. PreferServerCipherSuites: true,
  392. RootCAs: pool,
  393. }), nil
  394. }
  395. func getTransportFromCABundle(bundle []byte) (http.RoundTripper, error) {
  396. pool := x509.NewCertPool()
  397. if !pool.AppendCertsFromPEM(bundle) {
  398. return nil, errors.New("error parsing ca bundle: no certificates found")
  399. }
  400. return getDefaultTransport(&tls.Config{
  401. MinVersion: tls.VersionTLS12,
  402. PreferServerCipherSuites: true,
  403. RootCAs: pool,
  404. }), nil
  405. }
  406. // parseEndpoint parses and validates the given endpoint. It supports general
  407. // URLs like https://ca.smallstep.com[:port][/path], and incomplete URLs like
  408. // ca.smallstep.com[:port][/path].
  409. func parseEndpoint(endpoint string) (*url.URL, error) {
  410. u, err := url.Parse(endpoint)
  411. if err != nil {
  412. return nil, errors.Wrapf(err, "error parsing endpoint '%s'", endpoint)
  413. }
  414. // URLs are generally parsed as:
  415. // [scheme:][//[userinfo@]host][/]path[?query][#fragment]
  416. // But URLs that do not start with a slash after the scheme are interpreted as
  417. // scheme:opaque[?query][#fragment]
  418. if u.Opaque == "" {
  419. if u.Scheme == "" {
  420. u.Scheme = "https"
  421. }
  422. if u.Host == "" {
  423. // endpoint looks like ca.smallstep.com or ca.smallstep.com/1.0/sign
  424. if u.Path != "" {
  425. parts := strings.SplitN(u.Path, "/", 2)
  426. u.Host = parts[0]
  427. if len(parts) == 2 {
  428. u.Path = parts[1]
  429. } else {
  430. u.Path = ""
  431. }
  432. return parseEndpoint(u.String())
  433. }
  434. return nil, errors.Errorf("error parsing endpoint: url '%s' is not valid", endpoint)
  435. }
  436. return u, nil
  437. }
  438. // scheme:opaque[?query][#fragment]
  439. // endpoint looks like ca.smallstep.com:443 or ca.smallstep.com:443/1.0/sign
  440. return parseEndpoint("https://" + endpoint)
  441. }
  442. // ProvisionerOption is the type of options passed to the Provisioner method.
  443. type ProvisionerOption func(o *ProvisionerOptions) error
  444. // ProvisionerOptions stores options for the provisioner CRUD API.
  445. type ProvisionerOptions struct {
  446. Cursor string
  447. Limit int
  448. ID string
  449. Name string
  450. }
  451. // Apply caches provisioner options on a struct for later use.
  452. func (o *ProvisionerOptions) Apply(opts []ProvisionerOption) (err error) {
  453. for _, fn := range opts {
  454. if err = fn(o); err != nil {
  455. return
  456. }
  457. }
  458. return
  459. }
  460. func (o *ProvisionerOptions) rawQuery() string {
  461. v := url.Values{}
  462. if o.Cursor != "" {
  463. v.Set("cursor", o.Cursor)
  464. }
  465. if o.Limit > 0 {
  466. v.Set("limit", strconv.Itoa(o.Limit))
  467. }
  468. if o.ID != "" {
  469. v.Set("id", o.ID)
  470. }
  471. if o.Name != "" {
  472. v.Set("name", o.Name)
  473. }
  474. return v.Encode()
  475. }
  476. // WithProvisionerCursor will request the provisioners starting with the given cursor.
  477. func WithProvisionerCursor(cursor string) ProvisionerOption {
  478. return func(o *ProvisionerOptions) error {
  479. o.Cursor = cursor
  480. return nil
  481. }
  482. }
  483. // WithProvisionerLimit will request the given number of provisioners.
  484. func WithProvisionerLimit(limit int) ProvisionerOption {
  485. return func(o *ProvisionerOptions) error {
  486. o.Limit = limit
  487. return nil
  488. }
  489. }
  490. // WithProvisionerID will request the given provisioner.
  491. func WithProvisionerID(id string) ProvisionerOption {
  492. return func(o *ProvisionerOptions) error {
  493. o.ID = id
  494. return nil
  495. }
  496. }
  497. // WithProvisionerName will request the given provisioner.
  498. func WithProvisionerName(name string) ProvisionerOption {
  499. return func(o *ProvisionerOptions) error {
  500. o.Name = name
  501. return nil
  502. }
  503. }
  504. // Client implements an HTTP client for the CA server.
  505. type Client struct {
  506. client *uaClient
  507. endpoint *url.URL
  508. retryFunc RetryFunc
  509. timeout time.Duration
  510. opts []ClientOption
  511. }
  512. // NewClient creates a new Client with the given endpoint and options.
  513. func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
  514. u, err := parseEndpoint(endpoint)
  515. if err != nil {
  516. return nil, err
  517. }
  518. // Retrieve transport from options.
  519. o := defaultClientOptions()
  520. if err := o.apply(opts); err != nil {
  521. return nil, err
  522. }
  523. tr, err := o.getTransport(endpoint)
  524. if err != nil {
  525. return nil, err
  526. }
  527. return &Client{
  528. client: newClient(tr, o.timeout),
  529. endpoint: u,
  530. retryFunc: o.retryFunc,
  531. timeout: o.timeout,
  532. opts: opts,
  533. }, nil
  534. }
  535. func (c *Client) retryOnError(r *http.Response) bool {
  536. if c.retryFunc != nil {
  537. if c.retryFunc(r.StatusCode) {
  538. o := defaultClientOptions()
  539. if err := o.apply(c.opts); err != nil {
  540. return false
  541. }
  542. tr, err := o.getTransport(c.endpoint.String())
  543. if err != nil {
  544. return false
  545. }
  546. r.Body.Close()
  547. c.client.SetTransport(tr)
  548. return true
  549. }
  550. }
  551. return false
  552. }
  553. // GetCaURL returns the configured CA url.
  554. func (c *Client) GetCaURL() string {
  555. return c.endpoint.String()
  556. }
  557. // GetRootCAs returns the RootCAs certificate pool from the configured
  558. // transport.
  559. func (c *Client) GetRootCAs() *x509.CertPool {
  560. switch t := c.client.GetTransport().(type) {
  561. case *http.Transport:
  562. if t.TLSClientConfig != nil {
  563. return t.TLSClientConfig.RootCAs
  564. }
  565. return nil
  566. case *http2.Transport:
  567. if t.TLSClientConfig != nil {
  568. return t.TLSClientConfig.RootCAs
  569. }
  570. return nil
  571. default:
  572. return nil
  573. }
  574. }
  575. // SetTransport updates the transport of the internal HTTP client.
  576. func (c *Client) SetTransport(tr http.RoundTripper) {
  577. c.client.SetTransport(tr)
  578. }
  579. // Version performs the version request to the CA with an empty context and returns the
  580. // api.VersionResponse struct.
  581. func (c *Client) Version() (*api.VersionResponse, error) {
  582. return c.VersionWithContext(context.Background())
  583. }
  584. // VersionWithContext performs the version request to the CA with the provided context
  585. // and returns the api.VersionResponse struct.
  586. func (c *Client) VersionWithContext(ctx context.Context) (*api.VersionResponse, error) {
  587. var retried bool
  588. u := c.endpoint.ResolveReference(&url.URL{Path: "/version"})
  589. retry:
  590. resp, err := c.client.GetWithContext(ctx, u.String())
  591. if err != nil {
  592. return nil, clientError(err)
  593. }
  594. if resp.StatusCode >= 400 {
  595. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  596. retried = true
  597. goto retry
  598. }
  599. return nil, readError(resp)
  600. }
  601. var version api.VersionResponse
  602. if err := readJSON(resp.Body, &version); err != nil {
  603. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Version; error reading %s", u)
  604. }
  605. return &version, nil
  606. }
  607. // Health performs the health request to the CA with an empty context
  608. // and returns the api.HealthResponse struct.
  609. func (c *Client) Health() (*api.HealthResponse, error) {
  610. return c.HealthWithContext(context.Background())
  611. }
  612. // HealthWithContext performs the health request to the CA with the provided context
  613. // and returns the api.HealthResponse struct.
  614. func (c *Client) HealthWithContext(ctx context.Context) (*api.HealthResponse, error) {
  615. var retried bool
  616. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  617. retry:
  618. resp, err := c.client.GetWithContext(ctx, u.String())
  619. if err != nil {
  620. return nil, clientError(err)
  621. }
  622. if resp.StatusCode >= 400 {
  623. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  624. retried = true
  625. goto retry
  626. }
  627. return nil, readError(resp)
  628. }
  629. var health api.HealthResponse
  630. if err := readJSON(resp.Body, &health); err != nil {
  631. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Health; error reading %s", u)
  632. }
  633. return &health, nil
  634. }
  635. // Root performs the root request to the CA with an empty context and the provided
  636. // SHA256 and returns the api.RootResponse struct. It uses an insecure client, but
  637. // it checks the resulting root certificate with the given SHA256, returning an error
  638. // if they do not match.
  639. func (c *Client) Root(sha256Sum string) (*api.RootResponse, error) {
  640. return c.RootWithContext(context.Background(), sha256Sum)
  641. }
  642. // RootWithContext performs the root request to the CA with an empty context and the provided
  643. // SHA256 and returns the api.RootResponse struct. It uses an insecure client, but
  644. // it checks the resulting root certificate with the given SHA256, returning an error
  645. // if they do not match.
  646. func (c *Client) RootWithContext(ctx context.Context, sha256Sum string) (*api.RootResponse, error) {
  647. var retried bool
  648. sha256Sum = strings.ToLower(strings.ReplaceAll(sha256Sum, "-", ""))
  649. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  650. retry:
  651. resp, err := newInsecureClient().GetWithContext(ctx, u.String())
  652. if err != nil {
  653. return nil, clientError(err)
  654. }
  655. if resp.StatusCode >= 400 {
  656. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  657. retried = true
  658. goto retry
  659. }
  660. return nil, readError(resp)
  661. }
  662. var root api.RootResponse
  663. if err := readJSON(resp.Body, &root); err != nil {
  664. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Root; error reading %s", u)
  665. }
  666. // verify the sha256
  667. sum := sha256.Sum256(root.RootPEM.Raw)
  668. if !strings.EqualFold(sha256Sum, strings.ToLower(hex.EncodeToString(sum[:]))) {
  669. return nil, errs.BadRequest("root certificate fingerprint does not match")
  670. }
  671. return &root, nil
  672. }
  673. // Sign performs the sign request to the CA with an empty context and returns
  674. // the api.SignResponse struct.
  675. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  676. return c.SignWithContext(context.Background(), req)
  677. }
  678. // SignWithContext performs the sign request to the CA with the provided context
  679. // and returns the api.SignResponse struct.
  680. func (c *Client) SignWithContext(ctx context.Context, req *api.SignRequest) (*api.SignResponse, error) {
  681. var retried bool
  682. body, err := json.Marshal(req)
  683. if err != nil {
  684. return nil, errs.Wrap(http.StatusInternalServerError, err, "client.Sign; error marshaling request")
  685. }
  686. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  687. retry:
  688. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  689. if err != nil {
  690. return nil, clientError(err)
  691. }
  692. if resp.StatusCode >= 400 {
  693. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  694. retried = true
  695. goto retry
  696. }
  697. return nil, readError(resp)
  698. }
  699. var sign api.SignResponse
  700. if err := readJSON(resp.Body, &sign); err != nil {
  701. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Sign; error reading %s", u)
  702. }
  703. // Add tls.ConnectionState:
  704. // We'll extract the root certificate from the verified chains
  705. sign.TLS = resp.TLS
  706. return &sign, nil
  707. }
  708. // Renew performs the renew request to the CA with an empty context and
  709. // returns the api.SignResponse struct.
  710. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  711. return c.RenewWithContext(context.Background(), tr)
  712. }
  713. // RenewWithContext performs the renew request to the CA with the provided context
  714. // and returns the api.SignResponse struct.
  715. func (c *Client) RenewWithContext(ctx context.Context, tr http.RoundTripper) (*api.SignResponse, error) {
  716. var retried bool
  717. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  718. httpClient := &http.Client{Transport: tr}
  719. retry:
  720. req, err := http.NewRequestWithContext(ctx, "POST", u.String(), http.NoBody)
  721. if err != nil {
  722. return nil, err
  723. }
  724. req.Header.Set("Content-Type", "application/json")
  725. resp, err := httpClient.Do(req)
  726. if err != nil {
  727. return nil, clientError(err)
  728. }
  729. if resp.StatusCode >= 400 {
  730. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  731. retried = true
  732. goto retry
  733. }
  734. return nil, readError(resp)
  735. }
  736. var sign api.SignResponse
  737. if err := readJSON(resp.Body, &sign); err != nil {
  738. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Renew; error reading %s", u)
  739. }
  740. return &sign, nil
  741. }
  742. // RenewWithToken performs the renew request to the CA with the given
  743. // authorization token and and empty context and returns the api.SignResponse struct.
  744. // This method is generally used to renew an expired certificate.
  745. func (c *Client) RenewWithToken(token string) (*api.SignResponse, error) {
  746. return c.RenewWithTokenAndContext(context.Background(), token)
  747. }
  748. // RenewWithTokenAndContext performs the renew request to the CA with the given
  749. // authorization token and context and returns the api.SignResponse struct.
  750. // This method is generally used to renew an expired certificate.
  751. func (c *Client) RenewWithTokenAndContext(ctx context.Context, token string) (*api.SignResponse, error) {
  752. var retried bool
  753. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  754. req, err := http.NewRequestWithContext(ctx, "POST", u.String(), http.NoBody)
  755. if err != nil {
  756. return nil, errors.Wrapf(err, "create POST %s request failed", u)
  757. }
  758. req.Header.Add("Authorization", "Bearer "+token)
  759. retry:
  760. resp, err := c.client.Do(req)
  761. if err != nil {
  762. return nil, clientError(err)
  763. }
  764. if resp.StatusCode >= 400 {
  765. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  766. retried = true
  767. goto retry
  768. }
  769. return nil, readError(resp)
  770. }
  771. var sign api.SignResponse
  772. if err := readJSON(resp.Body, &sign); err != nil {
  773. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.RenewWithToken; error reading %s", u)
  774. }
  775. return &sign, nil
  776. }
  777. // Rekey performs the rekey request to the CA with an empty context and
  778. // returns the api.SignResponse struct.
  779. func (c *Client) Rekey(req *api.RekeyRequest, tr http.RoundTripper) (*api.SignResponse, error) {
  780. return c.RekeyWithContext(context.Background(), req, tr)
  781. }
  782. // RekeyWithContext performs the rekey request to the CA with the provided context
  783. // and returns the api.SignResponse struct.
  784. func (c *Client) RekeyWithContext(ctx context.Context, req *api.RekeyRequest, tr http.RoundTripper) (*api.SignResponse, error) {
  785. var retried bool
  786. body, err := json.Marshal(req)
  787. if err != nil {
  788. return nil, errors.Wrap(err, "error marshaling request")
  789. }
  790. u := c.endpoint.ResolveReference(&url.URL{Path: "/rekey"})
  791. httpClient := &http.Client{Transport: tr}
  792. retry:
  793. httpReq, err := http.NewRequestWithContext(ctx, "POST", u.String(), bytes.NewReader(body))
  794. if err != nil {
  795. return nil, err
  796. }
  797. httpReq.Header.Set("Content-Type", "application/json")
  798. resp, err := httpClient.Do(httpReq)
  799. if err != nil {
  800. return nil, clientError(err)
  801. }
  802. if resp.StatusCode >= 400 {
  803. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  804. retried = true
  805. goto retry
  806. }
  807. return nil, readError(resp)
  808. }
  809. var sign api.SignResponse
  810. if err := readJSON(resp.Body, &sign); err != nil {
  811. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Rekey; error reading %s", u)
  812. }
  813. return &sign, nil
  814. }
  815. // Revoke performs the revoke request to the CA with an empty context and returns
  816. // the api.RevokeResponse struct.
  817. func (c *Client) Revoke(req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  818. return c.RevokeWithContext(context.Background(), req, tr)
  819. }
  820. // RevokeWithContext performs the revoke request to the CA with the provided context and
  821. // returns the api.RevokeResponse struct.
  822. func (c *Client) RevokeWithContext(ctx context.Context, req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  823. var retried bool
  824. body, err := json.Marshal(req)
  825. if err != nil {
  826. return nil, errors.Wrap(err, "error marshaling request")
  827. }
  828. var uaClient *uaClient
  829. retry:
  830. if tr != nil {
  831. uaClient = newClient(tr, c.timeout)
  832. } else {
  833. uaClient = c.client
  834. }
  835. u := c.endpoint.ResolveReference(&url.URL{Path: "/revoke"})
  836. resp, err := uaClient.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  837. if err != nil {
  838. return nil, clientError(err)
  839. }
  840. if resp.StatusCode >= 400 {
  841. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  842. retried = true
  843. goto retry
  844. }
  845. return nil, readError(resp)
  846. }
  847. var revoke api.RevokeResponse
  848. if err := readJSON(resp.Body, &revoke); err != nil {
  849. return nil, errors.Wrapf(err, "error reading %s", u)
  850. }
  851. return &revoke, nil
  852. }
  853. // Provisioners performs the provisioners request to the CA with an empty context
  854. // and returns the api.ProvisionersResponse struct with a map of provisioners.
  855. //
  856. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  857. // paginate the provisioners.
  858. func (c *Client) Provisioners(opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  859. return c.ProvisionersWithContext(context.Background(), opts...)
  860. }
  861. // ProvisionersWithContext performs the provisioners request to the CA with the provided context
  862. // and returns the api.ProvisionersResponse struct with a map of provisioners.
  863. //
  864. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  865. // paginate the provisioners.
  866. func (c *Client) ProvisionersWithContext(ctx context.Context, opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  867. var retried bool
  868. o := new(ProvisionerOptions)
  869. if err := o.Apply(opts); err != nil {
  870. return nil, err
  871. }
  872. u := c.endpoint.ResolveReference(&url.URL{
  873. Path: "/provisioners",
  874. RawQuery: o.rawQuery(),
  875. })
  876. retry:
  877. resp, err := c.client.GetWithContext(ctx, u.String())
  878. if err != nil {
  879. return nil, clientError(err)
  880. }
  881. if resp.StatusCode >= 400 {
  882. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  883. retried = true
  884. goto retry
  885. }
  886. return nil, readError(resp)
  887. }
  888. var provisioners api.ProvisionersResponse
  889. if err := readJSON(resp.Body, &provisioners); err != nil {
  890. return nil, errors.Wrapf(err, "error reading %s", u)
  891. }
  892. return &provisioners, nil
  893. }
  894. // ProvisionerKey performs the request to the CA with an empty context to get
  895. // the encrypted key for the given provisioner kid and returns the api.ProvisionerKeyResponse
  896. // struct with the encrypted key.
  897. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  898. return c.ProvisionerKeyWithContext(context.Background(), kid)
  899. }
  900. // ProvisionerKeyWithContext performs the request to the CA with the provided context to get
  901. // the encrypted key for the given provisioner kid and returns the api.ProvisionerKeyResponse
  902. // struct with the encrypted key.
  903. func (c *Client) ProvisionerKeyWithContext(ctx context.Context, kid string) (*api.ProvisionerKeyResponse, error) {
  904. var retried bool
  905. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  906. retry:
  907. resp, err := c.client.GetWithContext(ctx, u.String())
  908. if err != nil {
  909. return nil, clientError(err)
  910. }
  911. if resp.StatusCode >= 400 {
  912. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  913. retried = true
  914. goto retry
  915. }
  916. return nil, readError(resp)
  917. }
  918. var key api.ProvisionerKeyResponse
  919. if err := readJSON(resp.Body, &key); err != nil {
  920. return nil, errors.Wrapf(err, "error reading %s", u)
  921. }
  922. return &key, nil
  923. }
  924. // Roots performs the get roots request to the CA with an empty context
  925. // and returns the api.RootsResponse struct.
  926. func (c *Client) Roots() (*api.RootsResponse, error) {
  927. return c.RootsWithContext(context.Background())
  928. }
  929. // RootsWithContext performs the get roots request to the CA with the provided context
  930. // and returns the api.RootsResponse struct.
  931. func (c *Client) RootsWithContext(ctx context.Context) (*api.RootsResponse, error) {
  932. var retried bool
  933. u := c.endpoint.ResolveReference(&url.URL{Path: "/roots"})
  934. retry:
  935. resp, err := c.client.GetWithContext(ctx, u.String())
  936. if err != nil {
  937. return nil, clientError(err)
  938. }
  939. if resp.StatusCode >= 400 {
  940. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  941. retried = true
  942. goto retry
  943. }
  944. return nil, readError(resp)
  945. }
  946. var roots api.RootsResponse
  947. if err := readJSON(resp.Body, &roots); err != nil {
  948. return nil, errors.Wrapf(err, "error reading %s", u)
  949. }
  950. return &roots, nil
  951. }
  952. // Federation performs the get federation request to the CA with an empty context
  953. // and returns the api.FederationResponse struct.
  954. func (c *Client) Federation() (*api.FederationResponse, error) {
  955. return c.FederationWithContext(context.Background())
  956. }
  957. // FederationWithContext performs the get federation request to the CA with the provided context
  958. // and returns the api.FederationResponse struct.
  959. func (c *Client) FederationWithContext(ctx context.Context) (*api.FederationResponse, error) {
  960. var retried bool
  961. u := c.endpoint.ResolveReference(&url.URL{Path: "/federation"})
  962. retry:
  963. resp, err := c.client.GetWithContext(ctx, u.String())
  964. if err != nil {
  965. return nil, clientError(err)
  966. }
  967. if resp.StatusCode >= 400 {
  968. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  969. retried = true
  970. goto retry
  971. }
  972. return nil, readError(resp)
  973. }
  974. var federation api.FederationResponse
  975. if err := readJSON(resp.Body, &federation); err != nil {
  976. return nil, errors.Wrapf(err, "error reading %s", u)
  977. }
  978. return &federation, nil
  979. }
  980. // SSHSign performs the POST /ssh/sign request to the CA with an empty context
  981. // and returns the api.SSHSignResponse struct.
  982. func (c *Client) SSHSign(req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  983. return c.SSHSignWithContext(context.Background(), req)
  984. }
  985. // SSHSignWithContext performs the POST /ssh/sign request to the CA with the provided context
  986. // and returns the api.SSHSignResponse struct.
  987. func (c *Client) SSHSignWithContext(ctx context.Context, req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  988. var retried bool
  989. body, err := json.Marshal(req)
  990. if err != nil {
  991. return nil, errors.Wrap(err, "error marshaling request")
  992. }
  993. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/sign"})
  994. retry:
  995. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  996. if err != nil {
  997. return nil, clientError(err)
  998. }
  999. if resp.StatusCode >= 400 {
  1000. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1001. retried = true
  1002. goto retry
  1003. }
  1004. return nil, readError(resp)
  1005. }
  1006. var sign api.SSHSignResponse
  1007. if err := readJSON(resp.Body, &sign); err != nil {
  1008. return nil, errors.Wrapf(err, "error reading %s", u)
  1009. }
  1010. return &sign, nil
  1011. }
  1012. // SSHRenew performs the POST /ssh/renew request to the CA with an empty context
  1013. // and returns the api.SSHRenewResponse struct.
  1014. func (c *Client) SSHRenew(req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
  1015. return c.SSHRenewWithContext(context.Background(), req)
  1016. }
  1017. // SSHRenewWithContext performs the POST /ssh/renew request to the CA with the provided context
  1018. // and returns the api.SSHRenewResponse struct.
  1019. func (c *Client) SSHRenewWithContext(ctx context.Context, req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
  1020. var retried bool
  1021. body, err := json.Marshal(req)
  1022. if err != nil {
  1023. return nil, errors.Wrap(err, "error marshaling request")
  1024. }
  1025. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/renew"})
  1026. retry:
  1027. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1028. if err != nil {
  1029. return nil, clientError(err)
  1030. }
  1031. if resp.StatusCode >= 400 {
  1032. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1033. retried = true
  1034. goto retry
  1035. }
  1036. return nil, readError(resp)
  1037. }
  1038. var renew api.SSHRenewResponse
  1039. if err := readJSON(resp.Body, &renew); err != nil {
  1040. return nil, errors.Wrapf(err, "error reading %s", u)
  1041. }
  1042. return &renew, nil
  1043. }
  1044. // SSHRekey performs the POST /ssh/rekey request to the CA with an empty context
  1045. // and returns the api.SSHRekeyResponse struct.
  1046. func (c *Client) SSHRekey(req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
  1047. return c.SSHRekeyWithContext(context.Background(), req)
  1048. }
  1049. // SSHRekeyWithContext performs the POST /ssh/rekey request to the CA with the provided context
  1050. // and returns the api.SSHRekeyResponse struct.
  1051. func (c *Client) SSHRekeyWithContext(ctx context.Context, req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
  1052. var retried bool
  1053. body, err := json.Marshal(req)
  1054. if err != nil {
  1055. return nil, errors.Wrap(err, "error marshaling request")
  1056. }
  1057. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/rekey"})
  1058. retry:
  1059. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1060. if err != nil {
  1061. return nil, clientError(err)
  1062. }
  1063. if resp.StatusCode >= 400 {
  1064. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1065. retried = true
  1066. goto retry
  1067. }
  1068. return nil, readError(resp)
  1069. }
  1070. var rekey api.SSHRekeyResponse
  1071. if err := readJSON(resp.Body, &rekey); err != nil {
  1072. return nil, errors.Wrapf(err, "error reading %s", u)
  1073. }
  1074. return &rekey, nil
  1075. }
  1076. // SSHRevoke performs the POST /ssh/revoke request to the CA with an empty context
  1077. // and returns the api.SSHRevokeResponse struct.
  1078. func (c *Client) SSHRevoke(req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
  1079. return c.SSHRevokeWithContext(context.Background(), req)
  1080. }
  1081. // SSHRevokeWithContext performs the POST /ssh/revoke request to the CA with the provided context
  1082. // and returns the api.SSHRevokeResponse struct.
  1083. func (c *Client) SSHRevokeWithContext(ctx context.Context, req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
  1084. var retried bool
  1085. body, err := json.Marshal(req)
  1086. if err != nil {
  1087. return nil, errors.Wrap(err, "error marshaling request")
  1088. }
  1089. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/revoke"})
  1090. retry:
  1091. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1092. if err != nil {
  1093. return nil, clientError(err)
  1094. }
  1095. if resp.StatusCode >= 400 {
  1096. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1097. retried = true
  1098. goto retry
  1099. }
  1100. return nil, readError(resp)
  1101. }
  1102. var revoke api.SSHRevokeResponse
  1103. if err := readJSON(resp.Body, &revoke); err != nil {
  1104. return nil, errors.Wrapf(err, "error reading %s", u)
  1105. }
  1106. return &revoke, nil
  1107. }
  1108. // SSHRoots performs the GET /ssh/roots request to the CA with an empty context
  1109. // and returns the api.SSHRootsResponse struct.
  1110. func (c *Client) SSHRoots() (*api.SSHRootsResponse, error) {
  1111. return c.SSHRootsWithContext(context.Background())
  1112. }
  1113. // SSHRootsWithContext performs the GET /ssh/roots request to the CA with the provided context
  1114. // and returns the api.SSHRootsResponse struct.
  1115. func (c *Client) SSHRootsWithContext(ctx context.Context) (*api.SSHRootsResponse, error) {
  1116. var retried bool
  1117. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/roots"})
  1118. retry:
  1119. resp, err := c.client.GetWithContext(ctx, u.String())
  1120. if err != nil {
  1121. return nil, clientError(err)
  1122. }
  1123. if resp.StatusCode >= 400 {
  1124. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1125. retried = true
  1126. goto retry
  1127. }
  1128. return nil, readError(resp)
  1129. }
  1130. var keys api.SSHRootsResponse
  1131. if err := readJSON(resp.Body, &keys); err != nil {
  1132. return nil, errors.Wrapf(err, "error reading %s", u)
  1133. }
  1134. return &keys, nil
  1135. }
  1136. // SSHFederation performs the get /ssh/federation request to the CA with an empty context
  1137. // and returns the api.SSHRootsResponse struct.
  1138. func (c *Client) SSHFederation() (*api.SSHRootsResponse, error) {
  1139. return c.SSHFederationWithContext(context.Background())
  1140. }
  1141. // SSHFederationWithContext performs the get /ssh/federation request to the CA with the provided context
  1142. // and returns the api.SSHRootsResponse struct.
  1143. func (c *Client) SSHFederationWithContext(ctx context.Context) (*api.SSHRootsResponse, error) {
  1144. var retried bool
  1145. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/federation"})
  1146. retry:
  1147. resp, err := c.client.GetWithContext(ctx, u.String())
  1148. if err != nil {
  1149. return nil, clientError(err)
  1150. }
  1151. if resp.StatusCode >= 400 {
  1152. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1153. retried = true
  1154. goto retry
  1155. }
  1156. return nil, readError(resp)
  1157. }
  1158. var keys api.SSHRootsResponse
  1159. if err := readJSON(resp.Body, &keys); err != nil {
  1160. return nil, errors.Wrapf(err, "error reading %s", u)
  1161. }
  1162. return &keys, nil
  1163. }
  1164. // SSHConfig performs the POST /ssh/config request to the CA with an empty context
  1165. // to get the ssh configuration templates.
  1166. func (c *Client) SSHConfig(req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  1167. return c.SSHConfigWithContext(context.Background(), req)
  1168. }
  1169. // SSHConfigWithContext performs the POST /ssh/config request to the CA with the provided context
  1170. // to get the ssh configuration templates.
  1171. func (c *Client) SSHConfigWithContext(ctx context.Context, req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  1172. var retried bool
  1173. body, err := json.Marshal(req)
  1174. if err != nil {
  1175. return nil, errors.Wrap(err, "error marshaling request")
  1176. }
  1177. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/config"})
  1178. retry:
  1179. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1180. if err != nil {
  1181. return nil, clientError(err)
  1182. }
  1183. if resp.StatusCode >= 400 {
  1184. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1185. retried = true
  1186. goto retry
  1187. }
  1188. return nil, readError(resp)
  1189. }
  1190. var cfg api.SSHConfigResponse
  1191. if err := readJSON(resp.Body, &cfg); err != nil {
  1192. return nil, errors.Wrapf(err, "error reading %s", u)
  1193. }
  1194. return &cfg, nil
  1195. }
  1196. // SSHCheckHost performs the POST /ssh/check-host request to the CA with an empty context,
  1197. // the principal and a token and returns the api.SSHCheckPrincipalResponse.
  1198. func (c *Client) SSHCheckHost(principal, token string) (*api.SSHCheckPrincipalResponse, error) {
  1199. return c.SSHCheckHostWithContext(context.Background(), principal, token)
  1200. }
  1201. // SSHCheckHostWithContext performs the POST /ssh/check-host request to the CA with the provided context,
  1202. // principal and token and returns the api.SSHCheckPrincipalResponse.
  1203. func (c *Client) SSHCheckHostWithContext(ctx context.Context, principal, token string) (*api.SSHCheckPrincipalResponse, error) {
  1204. var retried bool
  1205. body, err := json.Marshal(&api.SSHCheckPrincipalRequest{
  1206. Type: provisioner.SSHHostCert,
  1207. Principal: principal,
  1208. Token: token,
  1209. })
  1210. if err != nil {
  1211. return nil, errs.Wrap(http.StatusInternalServerError, err, "error marshaling request",
  1212. errs.WithMessage("Failed to marshal the check-host request"))
  1213. }
  1214. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/check-host"})
  1215. retry:
  1216. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1217. if err != nil {
  1218. return nil, clientError(err)
  1219. }
  1220. if resp.StatusCode >= 400 {
  1221. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1222. retried = true
  1223. goto retry
  1224. }
  1225. return nil, readError(resp)
  1226. }
  1227. var check api.SSHCheckPrincipalResponse
  1228. if err := readJSON(resp.Body, &check); err != nil {
  1229. return nil, errs.Wrapf(http.StatusInternalServerError, err, "error reading %s response",
  1230. []any{u, errs.WithMessage("Failed to parse response from /ssh/check-host endpoint")}...)
  1231. }
  1232. return &check, nil
  1233. }
  1234. // SSHGetHosts performs the GET /ssh/get-hosts request to the CA with an empty context.
  1235. func (c *Client) SSHGetHosts() (*api.SSHGetHostsResponse, error) {
  1236. return c.SSHGetHostsWithContext(context.Background())
  1237. }
  1238. // SSHGetHostsWithContext performs the GET /ssh/get-hosts request to the CA with the provided context.
  1239. func (c *Client) SSHGetHostsWithContext(ctx context.Context) (*api.SSHGetHostsResponse, error) {
  1240. var retried bool
  1241. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/hosts"})
  1242. retry:
  1243. resp, err := c.client.GetWithContext(ctx, u.String())
  1244. if err != nil {
  1245. return nil, clientError(err)
  1246. }
  1247. if resp.StatusCode >= 400 {
  1248. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1249. retried = true
  1250. goto retry
  1251. }
  1252. return nil, readError(resp)
  1253. }
  1254. var hosts api.SSHGetHostsResponse
  1255. if err := readJSON(resp.Body, &hosts); err != nil {
  1256. return nil, errors.Wrapf(err, "error reading %s", u)
  1257. }
  1258. return &hosts, nil
  1259. }
  1260. // SSHBastion performs the POST /ssh/bastion request to the CA with an empty context.
  1261. func (c *Client) SSHBastion(req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
  1262. return c.SSHBastionWithContext(context.Background(), req)
  1263. }
  1264. // SSHBastionWithContext performs the POST /ssh/bastion request to the CA with the provided context.
  1265. func (c *Client) SSHBastionWithContext(ctx context.Context, req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
  1266. var retried bool
  1267. body, err := json.Marshal(req)
  1268. if err != nil {
  1269. return nil, errors.Wrap(err, "client.SSHBastion; error marshaling request")
  1270. }
  1271. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/bastion"})
  1272. retry:
  1273. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1274. if err != nil {
  1275. return nil, clientError(err)
  1276. }
  1277. if resp.StatusCode >= 400 {
  1278. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1279. retried = true
  1280. goto retry
  1281. }
  1282. return nil, readError(resp)
  1283. }
  1284. var bastion api.SSHBastionResponse
  1285. if err := readJSON(resp.Body, &bastion); err != nil {
  1286. return nil, errors.Wrapf(err, "client.SSHBastion; error reading %s", u)
  1287. }
  1288. return &bastion, nil
  1289. }
  1290. // RootFingerprint is a helper method that returns the current root fingerprint.
  1291. // It does an health connection and gets the fingerprint from the TLS verified chains.
  1292. func (c *Client) RootFingerprint() (string, error) {
  1293. return c.RootFingerprintWithContext(context.Background())
  1294. }
  1295. // RootFingerprintWithContext is a helper method that returns the current root fingerprint.
  1296. // It does an health connection and gets the fingerprint from the TLS verified chains.
  1297. func (c *Client) RootFingerprintWithContext(ctx context.Context) (string, error) {
  1298. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  1299. resp, err := c.client.GetWithContext(ctx, u.String())
  1300. if err != nil {
  1301. return "", clientError(err)
  1302. }
  1303. defer resp.Body.Close()
  1304. if resp.TLS == nil || len(resp.TLS.VerifiedChains) == 0 {
  1305. return "", errors.New("missing verified chains")
  1306. }
  1307. lastChain := resp.TLS.VerifiedChains[len(resp.TLS.VerifiedChains)-1]
  1308. if len(lastChain) == 0 {
  1309. return "", errors.New("missing verified chains")
  1310. }
  1311. return x509util.Fingerprint(lastChain[len(lastChain)-1]), nil
  1312. }
  1313. // CreateSignRequest is a helper function that given an x509 OTT returns a
  1314. // simple but secure sign request as well as the private key used.
  1315. func CreateSignRequest(ott string) (*api.SignRequest, crypto.PrivateKey, error) {
  1316. token, err := jose.ParseSigned(ott)
  1317. if err != nil {
  1318. return nil, nil, errors.Wrap(err, "error parsing ott")
  1319. }
  1320. var claims authority.Claims
  1321. if err := token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  1322. return nil, nil, errors.Wrap(err, "error parsing ott")
  1323. }
  1324. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1325. if err != nil {
  1326. return nil, nil, errors.Wrap(err, "error generating key")
  1327. }
  1328. dnsNames, ips, emails, uris := x509util.SplitSANs(claims.SANs)
  1329. if claims.Email != "" {
  1330. emails = append(emails, claims.Email)
  1331. }
  1332. template := &x509.CertificateRequest{
  1333. Subject: pkix.Name{
  1334. CommonName: claims.Subject,
  1335. },
  1336. SignatureAlgorithm: x509.ECDSAWithSHA256,
  1337. DNSNames: dnsNames,
  1338. IPAddresses: ips,
  1339. EmailAddresses: emails,
  1340. URIs: uris,
  1341. }
  1342. csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
  1343. if err != nil {
  1344. return nil, nil, errors.Wrap(err, "error creating certificate request")
  1345. }
  1346. cr, err := x509.ParseCertificateRequest(csr)
  1347. if err != nil {
  1348. return nil, nil, errors.Wrap(err, "error parsing certificate request")
  1349. }
  1350. if err := cr.CheckSignature(); err != nil {
  1351. return nil, nil, errors.Wrap(err, "error signing certificate request")
  1352. }
  1353. return &api.SignRequest{
  1354. CsrPEM: api.CertificateRequest{CertificateRequest: cr},
  1355. OTT: ott,
  1356. }, pk, nil
  1357. }
  1358. // CreateCertificateRequest creates a new CSR with the given common name and
  1359. // SANs. If no san is provided the commonName will set also a SAN.
  1360. func CreateCertificateRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1361. key, err := keyutil.GenerateDefaultKey()
  1362. if err != nil {
  1363. return nil, nil, err
  1364. }
  1365. return createCertificateRequest(commonName, sans, key)
  1366. }
  1367. // CreateIdentityRequest returns a new CSR to create the identity. If an
  1368. // identity was already present it reuses the private key.
  1369. func CreateIdentityRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1370. var identityKey crypto.PrivateKey
  1371. if i, err := identity.LoadDefaultIdentity(); err == nil && i.Key != "" {
  1372. if k, err := pemutil.Read(i.Key); err == nil {
  1373. identityKey = k
  1374. }
  1375. }
  1376. if identityKey == nil {
  1377. return CreateCertificateRequest(commonName, sans...)
  1378. }
  1379. return createCertificateRequest(commonName, sans, identityKey)
  1380. }
  1381. // LoadDefaultIdentity is a wrapper for identity.LoadDefaultIdentity.
  1382. func LoadDefaultIdentity() (*identity.Identity, error) {
  1383. return identity.LoadDefaultIdentity()
  1384. }
  1385. // WriteDefaultIdentity is a wrapper for identity.WriteDefaultIdentity.
  1386. func WriteDefaultIdentity(certChain []api.Certificate, key crypto.PrivateKey) error {
  1387. return identity.WriteDefaultIdentity(certChain, key)
  1388. }
  1389. func createCertificateRequest(commonName string, sans []string, key crypto.PrivateKey) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1390. if len(sans) == 0 {
  1391. sans = []string{commonName}
  1392. }
  1393. dnsNames, ips, emails, uris := x509util.SplitSANs(sans)
  1394. template := &x509.CertificateRequest{
  1395. Subject: pkix.Name{
  1396. CommonName: commonName,
  1397. },
  1398. DNSNames: dnsNames,
  1399. IPAddresses: ips,
  1400. EmailAddresses: emails,
  1401. URIs: uris,
  1402. }
  1403. csr, err := x509.CreateCertificateRequest(rand.Reader, template, key)
  1404. if err != nil {
  1405. return nil, nil, err
  1406. }
  1407. cr, err := x509.ParseCertificateRequest(csr)
  1408. if err != nil {
  1409. return nil, nil, err
  1410. }
  1411. if err := cr.CheckSignature(); err != nil {
  1412. return nil, nil, err
  1413. }
  1414. return &api.CertificateRequest{CertificateRequest: cr}, key, nil
  1415. }
  1416. // getRootCAPath returns the path where the root CA is stored based on the
  1417. // STEPPATH environment variable.
  1418. func getRootCAPath() string {
  1419. return filepath.Join(step.Path(), "certs", "root_ca.crt")
  1420. }
  1421. func readJSON(r io.ReadCloser, v interface{}) error {
  1422. defer r.Close()
  1423. return json.NewDecoder(r).Decode(v)
  1424. }
  1425. func readProtoJSON(r io.ReadCloser, m proto.Message) error {
  1426. defer r.Close()
  1427. data, err := io.ReadAll(r)
  1428. if err != nil {
  1429. return err
  1430. }
  1431. return protojson.Unmarshal(data, m)
  1432. }
  1433. func readError(r *http.Response) error {
  1434. defer r.Body.Close()
  1435. apiErr := new(errs.Error)
  1436. if err := json.NewDecoder(r.Body).Decode(apiErr); err != nil {
  1437. return fmt.Errorf("failed decoding CA error response: %w", err)
  1438. }
  1439. apiErr.RequestID = r.Header.Get("X-Request-Id")
  1440. return apiErr
  1441. }
  1442. func clientError(err error) error {
  1443. var uerr *url.Error
  1444. if errors.As(err, &uerr) {
  1445. return fmt.Errorf("client %s %s failed: %w",
  1446. strings.ToUpper(uerr.Op), uerr.URL, uerr.Err)
  1447. }
  1448. return fmt.Errorf("client request failed: %w", err)
  1449. }