client.go 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  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. RootCAs: pool,
  391. }), nil
  392. }
  393. func getTransportFromSHA256(endpoint, sum string) (http.RoundTripper, error) {
  394. u, err := parseEndpoint(endpoint)
  395. if err != nil {
  396. return nil, err
  397. }
  398. caClient := &Client{endpoint: u}
  399. root, err := caClient.Root(sum)
  400. if err != nil {
  401. return nil, err
  402. }
  403. pool := x509.NewCertPool()
  404. pool.AddCert(root.RootPEM.Certificate)
  405. return getDefaultTransport(&tls.Config{
  406. MinVersion: tls.VersionTLS12,
  407. RootCAs: pool,
  408. }), nil
  409. }
  410. func getTransportFromCABundle(bundle []byte) (http.RoundTripper, error) {
  411. pool := x509.NewCertPool()
  412. if !pool.AppendCertsFromPEM(bundle) {
  413. return nil, errors.New("error parsing ca bundle: no certificates found")
  414. }
  415. return getDefaultTransport(&tls.Config{
  416. MinVersion: tls.VersionTLS12,
  417. RootCAs: pool,
  418. }), nil
  419. }
  420. // parseEndpoint parses and validates the given endpoint. It supports general
  421. // URLs like https://ca.smallstep.com[:port][/path], and incomplete URLs like
  422. // ca.smallstep.com[:port][/path].
  423. func parseEndpoint(endpoint string) (*url.URL, error) {
  424. u, err := url.Parse(endpoint)
  425. if err != nil {
  426. return nil, errors.Wrapf(err, "error parsing endpoint '%s'", endpoint)
  427. }
  428. // URLs are generally parsed as:
  429. // [scheme:][//[userinfo@]host][/]path[?query][#fragment]
  430. // But URLs that do not start with a slash after the scheme are interpreted as
  431. // scheme:opaque[?query][#fragment]
  432. if u.Opaque == "" {
  433. if u.Scheme == "" {
  434. u.Scheme = "https"
  435. }
  436. if u.Host == "" {
  437. // endpoint looks like ca.smallstep.com or ca.smallstep.com/1.0/sign
  438. if u.Path != "" {
  439. parts := strings.SplitN(u.Path, "/", 2)
  440. u.Host = parts[0]
  441. if len(parts) == 2 {
  442. u.Path = parts[1]
  443. } else {
  444. u.Path = ""
  445. }
  446. return parseEndpoint(u.String())
  447. }
  448. return nil, errors.Errorf("error parsing endpoint: url '%s' is not valid", endpoint)
  449. }
  450. return u, nil
  451. }
  452. // scheme:opaque[?query][#fragment]
  453. // endpoint looks like ca.smallstep.com:443 or ca.smallstep.com:443/1.0/sign
  454. return parseEndpoint("https://" + endpoint)
  455. }
  456. // ProvisionerOption is the type of options passed to the Provisioner method.
  457. type ProvisionerOption func(o *ProvisionerOptions) error
  458. // ProvisionerOptions stores options for the provisioner CRUD API.
  459. type ProvisionerOptions struct {
  460. Cursor string
  461. Limit int
  462. ID string
  463. Name string
  464. }
  465. // Apply caches provisioner options on a struct for later use.
  466. func (o *ProvisionerOptions) Apply(opts []ProvisionerOption) (err error) {
  467. for _, fn := range opts {
  468. if err = fn(o); err != nil {
  469. return
  470. }
  471. }
  472. return
  473. }
  474. func (o *ProvisionerOptions) rawQuery() string {
  475. v := url.Values{}
  476. if o.Cursor != "" {
  477. v.Set("cursor", o.Cursor)
  478. }
  479. if o.Limit > 0 {
  480. v.Set("limit", strconv.Itoa(o.Limit))
  481. }
  482. if o.ID != "" {
  483. v.Set("id", o.ID)
  484. }
  485. if o.Name != "" {
  486. v.Set("name", o.Name)
  487. }
  488. return v.Encode()
  489. }
  490. // WithProvisionerCursor will request the provisioners starting with the given cursor.
  491. func WithProvisionerCursor(cursor string) ProvisionerOption {
  492. return func(o *ProvisionerOptions) error {
  493. o.Cursor = cursor
  494. return nil
  495. }
  496. }
  497. // WithProvisionerLimit will request the given number of provisioners.
  498. func WithProvisionerLimit(limit int) ProvisionerOption {
  499. return func(o *ProvisionerOptions) error {
  500. o.Limit = limit
  501. return nil
  502. }
  503. }
  504. // WithProvisionerID will request the given provisioner.
  505. func WithProvisionerID(id string) ProvisionerOption {
  506. return func(o *ProvisionerOptions) error {
  507. o.ID = id
  508. return nil
  509. }
  510. }
  511. // WithProvisionerName will request the given provisioner.
  512. func WithProvisionerName(name string) ProvisionerOption {
  513. return func(o *ProvisionerOptions) error {
  514. o.Name = name
  515. return nil
  516. }
  517. }
  518. // Client implements an HTTP client for the CA server.
  519. type Client struct {
  520. client *uaClient
  521. endpoint *url.URL
  522. retryFunc RetryFunc
  523. timeout time.Duration
  524. opts []ClientOption
  525. transportDecorator TransportDecorator
  526. }
  527. // NewClient creates a new Client with the given endpoint and options.
  528. func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
  529. u, err := parseEndpoint(endpoint)
  530. if err != nil {
  531. return nil, err
  532. }
  533. // Retrieve transport from options.
  534. o := defaultClientOptions()
  535. if err := o.apply(opts); err != nil {
  536. return nil, err
  537. }
  538. tr, err := o.getTransport(endpoint)
  539. if err != nil {
  540. return nil, err
  541. }
  542. return &Client{
  543. client: newClient(tr, o.timeout),
  544. endpoint: u,
  545. retryFunc: o.retryFunc,
  546. timeout: o.timeout,
  547. opts: opts,
  548. transportDecorator: o.transportDecorator,
  549. }, nil
  550. }
  551. func (c *Client) retryOnError(r *http.Response) bool {
  552. if c.retryFunc != nil {
  553. if c.retryFunc(r.StatusCode) {
  554. o := defaultClientOptions()
  555. if err := o.apply(c.opts); err != nil {
  556. return false
  557. }
  558. tr, err := o.getTransport(c.endpoint.String())
  559. if err != nil {
  560. return false
  561. }
  562. r.Body.Close()
  563. c.client.SetTransport(tr)
  564. return true
  565. }
  566. }
  567. return false
  568. }
  569. // GetCaURL returns the configured CA url.
  570. func (c *Client) GetCaURL() string {
  571. return c.endpoint.String()
  572. }
  573. // GetRootCAs returns the RootCAs certificate pool from the configured
  574. // transport.
  575. func (c *Client) GetRootCAs() *x509.CertPool {
  576. switch t := c.client.GetTransport().(type) {
  577. case *http.Transport:
  578. if t.TLSClientConfig != nil {
  579. return t.TLSClientConfig.RootCAs
  580. }
  581. return nil
  582. case *http2.Transport:
  583. if t.TLSClientConfig != nil {
  584. return t.TLSClientConfig.RootCAs
  585. }
  586. return nil
  587. default:
  588. return nil
  589. }
  590. }
  591. // SetTransport updates the transport of the internal HTTP client.
  592. func (c *Client) SetTransport(tr http.RoundTripper) {
  593. c.client.SetTransport(tr)
  594. }
  595. // CloseIdleConnections closes any connections on its Transport which were
  596. // previously connected from previous requests but are now sitting idle in a
  597. // "keep-alive" state. It does not interrupt any connections currently in use.
  598. func (c *Client) CloseIdleConnections() {
  599. c.client.CloseIdleConnections()
  600. }
  601. // Version performs the version request to the CA with an empty context and returns the
  602. // api.VersionResponse struct.
  603. func (c *Client) Version() (*api.VersionResponse, error) {
  604. return c.VersionWithContext(context.Background())
  605. }
  606. // VersionWithContext performs the version request to the CA with the provided context
  607. // and returns the api.VersionResponse struct.
  608. func (c *Client) VersionWithContext(ctx context.Context) (*api.VersionResponse, error) {
  609. var retried bool
  610. u := c.endpoint.ResolveReference(&url.URL{Path: "/version"})
  611. retry:
  612. resp, err := c.client.GetWithContext(ctx, u.String())
  613. if err != nil {
  614. return nil, clientError(err)
  615. }
  616. if resp.StatusCode >= 400 {
  617. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  618. retried = true
  619. goto retry
  620. }
  621. return nil, readError(resp)
  622. }
  623. var version api.VersionResponse
  624. if err := readJSON(resp.Body, &version); err != nil {
  625. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Version; error reading %s", u)
  626. }
  627. return &version, nil
  628. }
  629. // Health performs the health request to the CA with an empty context
  630. // and returns the api.HealthResponse struct.
  631. func (c *Client) Health() (*api.HealthResponse, error) {
  632. return c.HealthWithContext(context.Background())
  633. }
  634. // HealthWithContext performs the health request to the CA with the provided context
  635. // and returns the api.HealthResponse struct.
  636. func (c *Client) HealthWithContext(ctx context.Context) (*api.HealthResponse, error) {
  637. var retried bool
  638. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  639. retry:
  640. resp, err := c.client.GetWithContext(ctx, u.String())
  641. if err != nil {
  642. return nil, clientError(err)
  643. }
  644. if resp.StatusCode >= 400 {
  645. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  646. retried = true
  647. goto retry
  648. }
  649. return nil, readError(resp)
  650. }
  651. var health api.HealthResponse
  652. if err := readJSON(resp.Body, &health); err != nil {
  653. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Health; error reading %s", u)
  654. }
  655. return &health, nil
  656. }
  657. // Root 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) Root(sha256Sum string) (*api.RootResponse, error) {
  662. return c.RootWithContext(context.Background(), sha256Sum)
  663. }
  664. // RootWithContext performs the root request to the CA with an empty context and the provided
  665. // SHA256 and returns the api.RootResponse struct. It uses an insecure client, but
  666. // it checks the resulting root certificate with the given SHA256, returning an error
  667. // if they do not match.
  668. func (c *Client) RootWithContext(ctx context.Context, sha256Sum string) (*api.RootResponse, error) {
  669. var retried bool
  670. sha256Sum = strings.ToLower(strings.ReplaceAll(sha256Sum, "-", ""))
  671. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  672. retry:
  673. resp, err := newInsecureClient().GetWithContext(ctx, u.String())
  674. if err != nil {
  675. return nil, clientError(err)
  676. }
  677. if resp.StatusCode >= 400 {
  678. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  679. retried = true
  680. goto retry
  681. }
  682. return nil, readError(resp)
  683. }
  684. var root api.RootResponse
  685. if err := readJSON(resp.Body, &root); err != nil {
  686. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Root; error reading %s", u)
  687. }
  688. // verify the sha256
  689. sum := sha256.Sum256(root.RootPEM.Raw)
  690. if !strings.EqualFold(sha256Sum, strings.ToLower(hex.EncodeToString(sum[:]))) {
  691. return nil, errs.BadRequest("root certificate fingerprint does not match")
  692. }
  693. return &root, nil
  694. }
  695. // Sign performs the sign request to the CA with an empty context and returns
  696. // the api.SignResponse struct.
  697. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  698. return c.SignWithContext(context.Background(), req)
  699. }
  700. // SignWithContext performs the sign request to the CA with the provided context
  701. // and returns the api.SignResponse struct.
  702. func (c *Client) SignWithContext(ctx context.Context, req *api.SignRequest) (*api.SignResponse, error) {
  703. var retried bool
  704. body, err := json.Marshal(req)
  705. if err != nil {
  706. return nil, errs.Wrap(http.StatusInternalServerError, err, "client.Sign; error marshaling request")
  707. }
  708. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  709. retry:
  710. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  711. if err != nil {
  712. return nil, clientError(err)
  713. }
  714. if resp.StatusCode >= 400 {
  715. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  716. retried = true
  717. goto retry
  718. }
  719. return nil, readError(resp)
  720. }
  721. var sign api.SignResponse
  722. if err := readJSON(resp.Body, &sign); err != nil {
  723. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Sign; error reading %s", u)
  724. }
  725. // Add tls.ConnectionState:
  726. // We'll extract the root certificate from the verified chains
  727. sign.TLS = resp.TLS
  728. return &sign, nil
  729. }
  730. // Renew performs the renew request to the CA with an empty context and
  731. // returns the api.SignResponse struct.
  732. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  733. return c.RenewWithContext(context.Background(), tr)
  734. }
  735. // RenewWithContext performs the renew request to the CA with the provided context
  736. // and returns the api.SignResponse struct.
  737. func (c *Client) RenewWithContext(ctx context.Context, tr http.RoundTripper) (*api.SignResponse, error) {
  738. var retried bool
  739. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  740. httpClient := &http.Client{Transport: tr}
  741. retry:
  742. req, err := http.NewRequestWithContext(ctx, "POST", u.String(), http.NoBody)
  743. if err != nil {
  744. return nil, err
  745. }
  746. req.Header.Set("Content-Type", "application/json")
  747. resp, err := httpClient.Do(req)
  748. if err != nil {
  749. return nil, clientError(err)
  750. }
  751. if resp.StatusCode >= 400 {
  752. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  753. retried = true
  754. goto retry
  755. }
  756. return nil, readError(resp)
  757. }
  758. var sign api.SignResponse
  759. if err := readJSON(resp.Body, &sign); err != nil {
  760. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Renew; error reading %s", u)
  761. }
  762. return &sign, nil
  763. }
  764. // RenewWithToken performs the renew request to the CA with the given
  765. // authorization token and and empty context and returns the api.SignResponse struct.
  766. // This method is generally used to renew an expired certificate.
  767. func (c *Client) RenewWithToken(token string) (*api.SignResponse, error) {
  768. return c.RenewWithTokenAndContext(context.Background(), token)
  769. }
  770. // RenewWithTokenAndContext performs the renew request to the CA with the given
  771. // authorization token and context and returns the api.SignResponse struct.
  772. // This method is generally used to renew an expired certificate.
  773. func (c *Client) RenewWithTokenAndContext(ctx context.Context, token string) (*api.SignResponse, error) {
  774. var retried bool
  775. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  776. req, err := http.NewRequestWithContext(ctx, "POST", u.String(), http.NoBody)
  777. if err != nil {
  778. return nil, errors.Wrapf(err, "create POST %s request failed", u)
  779. }
  780. req.Header.Add("Authorization", "Bearer "+token)
  781. retry:
  782. resp, err := c.client.Do(req)
  783. if err != nil {
  784. return nil, clientError(err)
  785. }
  786. if resp.StatusCode >= 400 {
  787. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  788. retried = true
  789. goto retry
  790. }
  791. return nil, readError(resp)
  792. }
  793. var sign api.SignResponse
  794. if err := readJSON(resp.Body, &sign); err != nil {
  795. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.RenewWithToken; error reading %s", u)
  796. }
  797. return &sign, nil
  798. }
  799. // Rekey performs the rekey request to the CA with an empty context and
  800. // returns the api.SignResponse struct.
  801. func (c *Client) Rekey(req *api.RekeyRequest, tr http.RoundTripper) (*api.SignResponse, error) {
  802. return c.RekeyWithContext(context.Background(), req, tr)
  803. }
  804. // RekeyWithContext performs the rekey request to the CA with the provided context
  805. // and returns the api.SignResponse struct.
  806. func (c *Client) RekeyWithContext(ctx context.Context, req *api.RekeyRequest, tr http.RoundTripper) (*api.SignResponse, error) {
  807. var retried bool
  808. body, err := json.Marshal(req)
  809. if err != nil {
  810. return nil, errors.Wrap(err, "error marshaling request")
  811. }
  812. u := c.endpoint.ResolveReference(&url.URL{Path: "/rekey"})
  813. httpClient := &http.Client{Transport: tr}
  814. retry:
  815. httpReq, err := http.NewRequestWithContext(ctx, "POST", u.String(), bytes.NewReader(body))
  816. if err != nil {
  817. return nil, err
  818. }
  819. httpReq.Header.Set("Content-Type", "application/json")
  820. resp, err := httpClient.Do(httpReq)
  821. if err != nil {
  822. return nil, clientError(err)
  823. }
  824. if resp.StatusCode >= 400 {
  825. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  826. retried = true
  827. goto retry
  828. }
  829. return nil, readError(resp)
  830. }
  831. var sign api.SignResponse
  832. if err := readJSON(resp.Body, &sign); err != nil {
  833. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Rekey; error reading %s", u)
  834. }
  835. return &sign, nil
  836. }
  837. // Revoke performs the revoke request to the CA with an empty context and returns
  838. // the api.RevokeResponse struct.
  839. func (c *Client) Revoke(req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  840. return c.RevokeWithContext(context.Background(), req, tr)
  841. }
  842. // RevokeWithContext performs the revoke request to the CA with the provided context and
  843. // returns the api.RevokeResponse struct.
  844. func (c *Client) RevokeWithContext(ctx context.Context, req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  845. var retried bool
  846. body, err := json.Marshal(req)
  847. if err != nil {
  848. return nil, errors.Wrap(err, "error marshaling request")
  849. }
  850. var uaClient *uaClient
  851. retry:
  852. if tr != nil {
  853. uaClient = newClient(tr, c.timeout)
  854. } else {
  855. uaClient = c.client
  856. }
  857. u := c.endpoint.ResolveReference(&url.URL{Path: "/revoke"})
  858. resp, err := uaClient.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  859. if err != nil {
  860. return nil, clientError(err)
  861. }
  862. if resp.StatusCode >= 400 {
  863. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  864. retried = true
  865. goto retry
  866. }
  867. return nil, readError(resp)
  868. }
  869. var revoke api.RevokeResponse
  870. if err := readJSON(resp.Body, &revoke); err != nil {
  871. return nil, errors.Wrapf(err, "error reading %s", u)
  872. }
  873. return &revoke, nil
  874. }
  875. // Provisioners performs the provisioners request to the CA with an empty context
  876. // and returns the api.ProvisionersResponse struct with a map of provisioners.
  877. //
  878. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  879. // paginate the provisioners.
  880. func (c *Client) Provisioners(opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  881. return c.ProvisionersWithContext(context.Background(), opts...)
  882. }
  883. // ProvisionersWithContext performs the provisioners request to the CA with the provided context
  884. // and returns the api.ProvisionersResponse struct with a map of provisioners.
  885. //
  886. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  887. // paginate the provisioners.
  888. func (c *Client) ProvisionersWithContext(ctx context.Context, opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  889. var retried bool
  890. o := new(ProvisionerOptions)
  891. if err := o.Apply(opts); err != nil {
  892. return nil, err
  893. }
  894. u := c.endpoint.ResolveReference(&url.URL{
  895. Path: "/provisioners",
  896. RawQuery: o.rawQuery(),
  897. })
  898. retry:
  899. resp, err := c.client.GetWithContext(ctx, u.String())
  900. if err != nil {
  901. return nil, clientError(err)
  902. }
  903. if resp.StatusCode >= 400 {
  904. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  905. retried = true
  906. goto retry
  907. }
  908. return nil, readError(resp)
  909. }
  910. var provisioners api.ProvisionersResponse
  911. if err := readJSON(resp.Body, &provisioners); err != nil {
  912. return nil, errors.Wrapf(err, "error reading %s", u)
  913. }
  914. return &provisioners, nil
  915. }
  916. // ProvisionerKey performs the request to the CA with an empty context to get
  917. // the encrypted key for the given provisioner kid and returns the api.ProvisionerKeyResponse
  918. // struct with the encrypted key.
  919. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  920. return c.ProvisionerKeyWithContext(context.Background(), kid)
  921. }
  922. // ProvisionerKeyWithContext performs the request to the CA with the provided context to get
  923. // the encrypted key for the given provisioner kid and returns the api.ProvisionerKeyResponse
  924. // struct with the encrypted key.
  925. func (c *Client) ProvisionerKeyWithContext(ctx context.Context, kid string) (*api.ProvisionerKeyResponse, error) {
  926. var retried bool
  927. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  928. retry:
  929. resp, err := c.client.GetWithContext(ctx, u.String())
  930. if err != nil {
  931. return nil, clientError(err)
  932. }
  933. if resp.StatusCode >= 400 {
  934. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  935. retried = true
  936. goto retry
  937. }
  938. return nil, readError(resp)
  939. }
  940. var key api.ProvisionerKeyResponse
  941. if err := readJSON(resp.Body, &key); err != nil {
  942. return nil, errors.Wrapf(err, "error reading %s", u)
  943. }
  944. return &key, nil
  945. }
  946. // Roots performs the get roots request to the CA with an empty context
  947. // and returns the api.RootsResponse struct.
  948. func (c *Client) Roots() (*api.RootsResponse, error) {
  949. return c.RootsWithContext(context.Background())
  950. }
  951. // RootsWithContext performs the get roots request to the CA with the provided context
  952. // and returns the api.RootsResponse struct.
  953. func (c *Client) RootsWithContext(ctx context.Context) (*api.RootsResponse, error) {
  954. var retried bool
  955. u := c.endpoint.ResolveReference(&url.URL{Path: "/roots"})
  956. retry:
  957. resp, err := c.client.GetWithContext(ctx, u.String())
  958. if err != nil {
  959. return nil, clientError(err)
  960. }
  961. if resp.StatusCode >= 400 {
  962. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  963. retried = true
  964. goto retry
  965. }
  966. return nil, readError(resp)
  967. }
  968. var roots api.RootsResponse
  969. if err := readJSON(resp.Body, &roots); err != nil {
  970. return nil, errors.Wrapf(err, "error reading %s", u)
  971. }
  972. return &roots, nil
  973. }
  974. // Federation performs the get federation request to the CA with an empty context
  975. // and returns the api.FederationResponse struct.
  976. func (c *Client) Federation() (*api.FederationResponse, error) {
  977. return c.FederationWithContext(context.Background())
  978. }
  979. // FederationWithContext performs the get federation request to the CA with the provided context
  980. // and returns the api.FederationResponse struct.
  981. func (c *Client) FederationWithContext(ctx context.Context) (*api.FederationResponse, error) {
  982. var retried bool
  983. u := c.endpoint.ResolveReference(&url.URL{Path: "/federation"})
  984. retry:
  985. resp, err := c.client.GetWithContext(ctx, u.String())
  986. if err != nil {
  987. return nil, clientError(err)
  988. }
  989. if resp.StatusCode >= 400 {
  990. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  991. retried = true
  992. goto retry
  993. }
  994. return nil, readError(resp)
  995. }
  996. var federation api.FederationResponse
  997. if err := readJSON(resp.Body, &federation); err != nil {
  998. return nil, errors.Wrapf(err, "error reading %s", u)
  999. }
  1000. return &federation, nil
  1001. }
  1002. // SSHSign performs the POST /ssh/sign request to the CA with an empty context
  1003. // and returns the api.SSHSignResponse struct.
  1004. func (c *Client) SSHSign(req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  1005. return c.SSHSignWithContext(context.Background(), req)
  1006. }
  1007. // SSHSignWithContext performs the POST /ssh/sign request to the CA with the provided context
  1008. // and returns the api.SSHSignResponse struct.
  1009. func (c *Client) SSHSignWithContext(ctx context.Context, req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  1010. var retried bool
  1011. body, err := json.Marshal(req)
  1012. if err != nil {
  1013. return nil, errors.Wrap(err, "error marshaling request")
  1014. }
  1015. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/sign"})
  1016. retry:
  1017. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1018. if err != nil {
  1019. return nil, clientError(err)
  1020. }
  1021. if resp.StatusCode >= 400 {
  1022. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1023. retried = true
  1024. goto retry
  1025. }
  1026. return nil, readError(resp)
  1027. }
  1028. var sign api.SSHSignResponse
  1029. if err := readJSON(resp.Body, &sign); err != nil {
  1030. return nil, errors.Wrapf(err, "error reading %s", u)
  1031. }
  1032. return &sign, nil
  1033. }
  1034. // SSHRenew performs the POST /ssh/renew request to the CA with an empty context
  1035. // and returns the api.SSHRenewResponse struct.
  1036. func (c *Client) SSHRenew(req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
  1037. return c.SSHRenewWithContext(context.Background(), req)
  1038. }
  1039. // SSHRenewWithContext performs the POST /ssh/renew request to the CA with the provided context
  1040. // and returns the api.SSHRenewResponse struct.
  1041. func (c *Client) SSHRenewWithContext(ctx context.Context, req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
  1042. var retried bool
  1043. body, err := json.Marshal(req)
  1044. if err != nil {
  1045. return nil, errors.Wrap(err, "error marshaling request")
  1046. }
  1047. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/renew"})
  1048. retry:
  1049. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1050. if err != nil {
  1051. return nil, clientError(err)
  1052. }
  1053. if resp.StatusCode >= 400 {
  1054. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1055. retried = true
  1056. goto retry
  1057. }
  1058. return nil, readError(resp)
  1059. }
  1060. var renew api.SSHRenewResponse
  1061. if err := readJSON(resp.Body, &renew); err != nil {
  1062. return nil, errors.Wrapf(err, "error reading %s", u)
  1063. }
  1064. return &renew, nil
  1065. }
  1066. // SSHRekey performs the POST /ssh/rekey request to the CA with an empty context
  1067. // and returns the api.SSHRekeyResponse struct.
  1068. func (c *Client) SSHRekey(req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
  1069. return c.SSHRekeyWithContext(context.Background(), req)
  1070. }
  1071. // SSHRekeyWithContext performs the POST /ssh/rekey request to the CA with the provided context
  1072. // and returns the api.SSHRekeyResponse struct.
  1073. func (c *Client) SSHRekeyWithContext(ctx context.Context, req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
  1074. var retried bool
  1075. body, err := json.Marshal(req)
  1076. if err != nil {
  1077. return nil, errors.Wrap(err, "error marshaling request")
  1078. }
  1079. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/rekey"})
  1080. retry:
  1081. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1082. if err != nil {
  1083. return nil, clientError(err)
  1084. }
  1085. if resp.StatusCode >= 400 {
  1086. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1087. retried = true
  1088. goto retry
  1089. }
  1090. return nil, readError(resp)
  1091. }
  1092. var rekey api.SSHRekeyResponse
  1093. if err := readJSON(resp.Body, &rekey); err != nil {
  1094. return nil, errors.Wrapf(err, "error reading %s", u)
  1095. }
  1096. return &rekey, nil
  1097. }
  1098. // SSHRevoke performs the POST /ssh/revoke request to the CA with an empty context
  1099. // and returns the api.SSHRevokeResponse struct.
  1100. func (c *Client) SSHRevoke(req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
  1101. return c.SSHRevokeWithContext(context.Background(), req)
  1102. }
  1103. // SSHRevokeWithContext performs the POST /ssh/revoke request to the CA with the provided context
  1104. // and returns the api.SSHRevokeResponse struct.
  1105. func (c *Client) SSHRevokeWithContext(ctx context.Context, req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
  1106. var retried bool
  1107. body, err := json.Marshal(req)
  1108. if err != nil {
  1109. return nil, errors.Wrap(err, "error marshaling request")
  1110. }
  1111. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/revoke"})
  1112. retry:
  1113. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1114. if err != nil {
  1115. return nil, clientError(err)
  1116. }
  1117. if resp.StatusCode >= 400 {
  1118. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1119. retried = true
  1120. goto retry
  1121. }
  1122. return nil, readError(resp)
  1123. }
  1124. var revoke api.SSHRevokeResponse
  1125. if err := readJSON(resp.Body, &revoke); err != nil {
  1126. return nil, errors.Wrapf(err, "error reading %s", u)
  1127. }
  1128. return &revoke, nil
  1129. }
  1130. // SSHRoots performs the GET /ssh/roots request to the CA with an empty context
  1131. // and returns the api.SSHRootsResponse struct.
  1132. func (c *Client) SSHRoots() (*api.SSHRootsResponse, error) {
  1133. return c.SSHRootsWithContext(context.Background())
  1134. }
  1135. // SSHRootsWithContext performs the GET /ssh/roots request to the CA with the provided context
  1136. // and returns the api.SSHRootsResponse struct.
  1137. func (c *Client) SSHRootsWithContext(ctx context.Context) (*api.SSHRootsResponse, error) {
  1138. var retried bool
  1139. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/roots"})
  1140. retry:
  1141. resp, err := c.client.GetWithContext(ctx, u.String())
  1142. if err != nil {
  1143. return nil, clientError(err)
  1144. }
  1145. if resp.StatusCode >= 400 {
  1146. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1147. retried = true
  1148. goto retry
  1149. }
  1150. return nil, readError(resp)
  1151. }
  1152. var keys api.SSHRootsResponse
  1153. if err := readJSON(resp.Body, &keys); err != nil {
  1154. return nil, errors.Wrapf(err, "error reading %s", u)
  1155. }
  1156. return &keys, nil
  1157. }
  1158. // SSHFederation performs the get /ssh/federation request to the CA with an empty context
  1159. // and returns the api.SSHRootsResponse struct.
  1160. func (c *Client) SSHFederation() (*api.SSHRootsResponse, error) {
  1161. return c.SSHFederationWithContext(context.Background())
  1162. }
  1163. // SSHFederationWithContext performs the get /ssh/federation request to the CA with the provided context
  1164. // and returns the api.SSHRootsResponse struct.
  1165. func (c *Client) SSHFederationWithContext(ctx context.Context) (*api.SSHRootsResponse, error) {
  1166. var retried bool
  1167. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/federation"})
  1168. retry:
  1169. resp, err := c.client.GetWithContext(ctx, u.String())
  1170. if err != nil {
  1171. return nil, clientError(err)
  1172. }
  1173. if resp.StatusCode >= 400 {
  1174. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1175. retried = true
  1176. goto retry
  1177. }
  1178. return nil, readError(resp)
  1179. }
  1180. var keys api.SSHRootsResponse
  1181. if err := readJSON(resp.Body, &keys); err != nil {
  1182. return nil, errors.Wrapf(err, "error reading %s", u)
  1183. }
  1184. return &keys, nil
  1185. }
  1186. // SSHConfig performs the POST /ssh/config request to the CA with an empty context
  1187. // to get the ssh configuration templates.
  1188. func (c *Client) SSHConfig(req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  1189. return c.SSHConfigWithContext(context.Background(), req)
  1190. }
  1191. // SSHConfigWithContext performs the POST /ssh/config request to the CA with the provided context
  1192. // to get the ssh configuration templates.
  1193. func (c *Client) SSHConfigWithContext(ctx context.Context, req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  1194. var retried bool
  1195. body, err := json.Marshal(req)
  1196. if err != nil {
  1197. return nil, errors.Wrap(err, "error marshaling request")
  1198. }
  1199. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/config"})
  1200. retry:
  1201. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1202. if err != nil {
  1203. return nil, clientError(err)
  1204. }
  1205. if resp.StatusCode >= 400 {
  1206. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1207. retried = true
  1208. goto retry
  1209. }
  1210. return nil, readError(resp)
  1211. }
  1212. var cfg api.SSHConfigResponse
  1213. if err := readJSON(resp.Body, &cfg); err != nil {
  1214. return nil, errors.Wrapf(err, "error reading %s", u)
  1215. }
  1216. return &cfg, nil
  1217. }
  1218. // SSHCheckHost performs the POST /ssh/check-host request to the CA with an empty context,
  1219. // the principal and a token and returns the api.SSHCheckPrincipalResponse.
  1220. func (c *Client) SSHCheckHost(principal, token string) (*api.SSHCheckPrincipalResponse, error) {
  1221. return c.SSHCheckHostWithContext(context.Background(), principal, token)
  1222. }
  1223. // SSHCheckHostWithContext performs the POST /ssh/check-host request to the CA with the provided context,
  1224. // principal and token and returns the api.SSHCheckPrincipalResponse.
  1225. func (c *Client) SSHCheckHostWithContext(ctx context.Context, principal, token string) (*api.SSHCheckPrincipalResponse, error) {
  1226. var retried bool
  1227. body, err := json.Marshal(&api.SSHCheckPrincipalRequest{
  1228. Type: provisioner.SSHHostCert,
  1229. Principal: principal,
  1230. Token: token,
  1231. })
  1232. if err != nil {
  1233. return nil, errs.Wrap(http.StatusInternalServerError, err, "error marshaling request",
  1234. errs.WithMessage("Failed to marshal the check-host request"))
  1235. }
  1236. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/check-host"})
  1237. retry:
  1238. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1239. if err != nil {
  1240. return nil, clientError(err)
  1241. }
  1242. if resp.StatusCode >= 400 {
  1243. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1244. retried = true
  1245. goto retry
  1246. }
  1247. return nil, readError(resp)
  1248. }
  1249. var check api.SSHCheckPrincipalResponse
  1250. if err := readJSON(resp.Body, &check); err != nil {
  1251. return nil, errs.Wrapf(http.StatusInternalServerError, err, "error reading %s response",
  1252. []any{u, errs.WithMessage("Failed to parse response from /ssh/check-host endpoint")}...)
  1253. }
  1254. return &check, nil
  1255. }
  1256. // SSHGetHosts performs the GET /ssh/get-hosts request to the CA with an empty context.
  1257. func (c *Client) SSHGetHosts() (*api.SSHGetHostsResponse, error) {
  1258. return c.SSHGetHostsWithContext(context.Background())
  1259. }
  1260. // SSHGetHostsWithContext performs the GET /ssh/get-hosts request to the CA with the provided context.
  1261. func (c *Client) SSHGetHostsWithContext(ctx context.Context) (*api.SSHGetHostsResponse, error) {
  1262. var retried bool
  1263. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/hosts"})
  1264. retry:
  1265. resp, err := c.client.GetWithContext(ctx, u.String())
  1266. if err != nil {
  1267. return nil, clientError(err)
  1268. }
  1269. if resp.StatusCode >= 400 {
  1270. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1271. retried = true
  1272. goto retry
  1273. }
  1274. return nil, readError(resp)
  1275. }
  1276. var hosts api.SSHGetHostsResponse
  1277. if err := readJSON(resp.Body, &hosts); err != nil {
  1278. return nil, errors.Wrapf(err, "error reading %s", u)
  1279. }
  1280. return &hosts, nil
  1281. }
  1282. // SSHBastion performs the POST /ssh/bastion request to the CA with an empty context.
  1283. func (c *Client) SSHBastion(req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
  1284. return c.SSHBastionWithContext(context.Background(), req)
  1285. }
  1286. // SSHBastionWithContext performs the POST /ssh/bastion request to the CA with the provided context.
  1287. func (c *Client) SSHBastionWithContext(ctx context.Context, req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
  1288. var retried bool
  1289. body, err := json.Marshal(req)
  1290. if err != nil {
  1291. return nil, errors.Wrap(err, "client.SSHBastion; error marshaling request")
  1292. }
  1293. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/bastion"})
  1294. retry:
  1295. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1296. if err != nil {
  1297. return nil, clientError(err)
  1298. }
  1299. if resp.StatusCode >= 400 {
  1300. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1301. retried = true
  1302. goto retry
  1303. }
  1304. return nil, readError(resp)
  1305. }
  1306. var bastion api.SSHBastionResponse
  1307. if err := readJSON(resp.Body, &bastion); err != nil {
  1308. return nil, errors.Wrapf(err, "client.SSHBastion; error reading %s", u)
  1309. }
  1310. return &bastion, nil
  1311. }
  1312. // RootFingerprint is a helper method that returns the current root fingerprint.
  1313. // It does an health connection and gets the fingerprint from the TLS verified chains.
  1314. func (c *Client) RootFingerprint() (string, error) {
  1315. return c.RootFingerprintWithContext(context.Background())
  1316. }
  1317. // RootFingerprintWithContext is a helper method that returns the current root fingerprint.
  1318. // It does an health connection and gets the fingerprint from the TLS verified chains.
  1319. func (c *Client) RootFingerprintWithContext(ctx context.Context) (string, error) {
  1320. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  1321. resp, err := c.client.GetWithContext(ctx, u.String())
  1322. if err != nil {
  1323. return "", clientError(err)
  1324. }
  1325. defer resp.Body.Close()
  1326. if resp.TLS == nil || len(resp.TLS.VerifiedChains) == 0 {
  1327. return "", errors.New("missing verified chains")
  1328. }
  1329. lastChain := resp.TLS.VerifiedChains[len(resp.TLS.VerifiedChains)-1]
  1330. if len(lastChain) == 0 {
  1331. return "", errors.New("missing verified chains")
  1332. }
  1333. return x509util.Fingerprint(lastChain[len(lastChain)-1]), nil
  1334. }
  1335. // CreateSignRequest is a helper function that given an x509 OTT returns a
  1336. // simple but secure sign request as well as the private key used.
  1337. func CreateSignRequest(ott string) (*api.SignRequest, crypto.PrivateKey, error) {
  1338. token, err := jose.ParseSigned(ott)
  1339. if err != nil {
  1340. return nil, nil, errors.Wrap(err, "error parsing ott")
  1341. }
  1342. var claims authority.Claims
  1343. if err := token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  1344. return nil, nil, errors.Wrap(err, "error parsing ott")
  1345. }
  1346. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1347. if err != nil {
  1348. return nil, nil, errors.Wrap(err, "error generating key")
  1349. }
  1350. dnsNames, ips, emails, uris := x509util.SplitSANs(claims.SANs)
  1351. if claims.Email != "" {
  1352. emails = append(emails, claims.Email)
  1353. }
  1354. template := &x509.CertificateRequest{
  1355. Subject: pkix.Name{
  1356. CommonName: claims.Subject,
  1357. },
  1358. SignatureAlgorithm: x509.ECDSAWithSHA256,
  1359. DNSNames: dnsNames,
  1360. IPAddresses: ips,
  1361. EmailAddresses: emails,
  1362. URIs: uris,
  1363. }
  1364. csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
  1365. if err != nil {
  1366. return nil, nil, errors.Wrap(err, "error creating certificate request")
  1367. }
  1368. cr, err := x509.ParseCertificateRequest(csr)
  1369. if err != nil {
  1370. return nil, nil, errors.Wrap(err, "error parsing certificate request")
  1371. }
  1372. if err := cr.CheckSignature(); err != nil {
  1373. return nil, nil, errors.Wrap(err, "error signing certificate request")
  1374. }
  1375. return &api.SignRequest{
  1376. CsrPEM: api.CertificateRequest{CertificateRequest: cr},
  1377. OTT: ott,
  1378. }, pk, nil
  1379. }
  1380. // CreateCertificateRequest creates a new CSR with the given common name and
  1381. // SANs. If no san is provided the commonName will set also a SAN.
  1382. func CreateCertificateRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1383. key, err := keyutil.GenerateDefaultKey()
  1384. if err != nil {
  1385. return nil, nil, err
  1386. }
  1387. return createCertificateRequest(commonName, sans, key)
  1388. }
  1389. // CreateIdentityRequest returns a new CSR to create the identity. If an
  1390. // identity was already present it reuses the private key.
  1391. func CreateIdentityRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1392. var identityKey crypto.PrivateKey
  1393. if i, err := identity.LoadDefaultIdentity(); err == nil && i.Key != "" {
  1394. if k, err := pemutil.Read(i.Key); err == nil {
  1395. identityKey = k
  1396. }
  1397. }
  1398. if identityKey == nil {
  1399. return CreateCertificateRequest(commonName, sans...)
  1400. }
  1401. return createCertificateRequest(commonName, sans, identityKey)
  1402. }
  1403. // LoadDefaultIdentity is a wrapper for identity.LoadDefaultIdentity.
  1404. func LoadDefaultIdentity() (*identity.Identity, error) {
  1405. return identity.LoadDefaultIdentity()
  1406. }
  1407. // WriteDefaultIdentity is a wrapper for identity.WriteDefaultIdentity.
  1408. func WriteDefaultIdentity(certChain []api.Certificate, key crypto.PrivateKey) error {
  1409. return identity.WriteDefaultIdentity(certChain, key)
  1410. }
  1411. func createCertificateRequest(commonName string, sans []string, key crypto.PrivateKey) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1412. if len(sans) == 0 {
  1413. sans = []string{commonName}
  1414. }
  1415. dnsNames, ips, emails, uris := x509util.SplitSANs(sans)
  1416. template := &x509.CertificateRequest{
  1417. Subject: pkix.Name{
  1418. CommonName: commonName,
  1419. },
  1420. DNSNames: dnsNames,
  1421. IPAddresses: ips,
  1422. EmailAddresses: emails,
  1423. URIs: uris,
  1424. }
  1425. csr, err := x509.CreateCertificateRequest(rand.Reader, template, key)
  1426. if err != nil {
  1427. return nil, nil, err
  1428. }
  1429. cr, err := x509.ParseCertificateRequest(csr)
  1430. if err != nil {
  1431. return nil, nil, err
  1432. }
  1433. if err := cr.CheckSignature(); err != nil {
  1434. return nil, nil, err
  1435. }
  1436. return &api.CertificateRequest{CertificateRequest: cr}, key, nil
  1437. }
  1438. // getRootCAPath returns the path where the root CA is stored based on the
  1439. // STEPPATH environment variable.
  1440. func getRootCAPath() string {
  1441. return filepath.Join(step.Path(), "certs", "root_ca.crt")
  1442. }
  1443. func readJSON(r io.ReadCloser, v interface{}) error {
  1444. defer r.Close()
  1445. return json.NewDecoder(r).Decode(v)
  1446. }
  1447. func readProtoJSON(r io.ReadCloser, m proto.Message) error {
  1448. defer r.Close()
  1449. data, err := io.ReadAll(r)
  1450. if err != nil {
  1451. return err
  1452. }
  1453. return protojson.Unmarshal(data, m)
  1454. }
  1455. func readError(r *http.Response) error {
  1456. defer r.Body.Close()
  1457. apiErr := new(errs.Error)
  1458. if err := json.NewDecoder(r.Body).Decode(apiErr); err != nil {
  1459. return fmt.Errorf("failed decoding CA error response: %w", err)
  1460. }
  1461. apiErr.RequestID = r.Header.Get("X-Request-Id")
  1462. return apiErr
  1463. }
  1464. func clientError(err error) error {
  1465. var uerr *url.Error
  1466. if errors.As(err, &uerr) {
  1467. return fmt.Errorf("client %s %s failed: %w",
  1468. strings.ToUpper(uerr.Op), uerr.URL, uerr.Err)
  1469. }
  1470. return fmt.Errorf("client request failed: %w", err)
  1471. }
  1472. func decorateRoundTripper(tr http.RoundTripper, td TransportDecorator) http.RoundTripper {
  1473. if td != nil {
  1474. return td(tr)
  1475. }
  1476. return tr
  1477. }