client.go 51 KB

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