client.go 49 KB

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