client.go 52 KB

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