client.go 49 KB

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