client.go 51 KB

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