client.go 50 KB

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