client.go 49 KB

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