client.go 49 KB

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