ca.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. package ca
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "fmt"
  8. "log"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "reflect"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/go-chi/chi/v5"
  17. "github.com/go-chi/chi/v5/middleware"
  18. "github.com/pkg/errors"
  19. "github.com/smallstep/certificates/acme"
  20. acmeAPI "github.com/smallstep/certificates/acme/api"
  21. acmeNoSQL "github.com/smallstep/certificates/acme/db/nosql"
  22. "github.com/smallstep/certificates/api"
  23. "github.com/smallstep/certificates/authority"
  24. "github.com/smallstep/certificates/authority/admin"
  25. adminAPI "github.com/smallstep/certificates/authority/admin/api"
  26. "github.com/smallstep/certificates/authority/config"
  27. "github.com/smallstep/certificates/db"
  28. "github.com/smallstep/certificates/internal/metrix"
  29. "github.com/smallstep/certificates/logging"
  30. "github.com/smallstep/certificates/monitoring"
  31. "github.com/smallstep/certificates/scep"
  32. scepAPI "github.com/smallstep/certificates/scep/api"
  33. "github.com/smallstep/certificates/server"
  34. "github.com/smallstep/nosql"
  35. "go.step.sm/cli-utils/step"
  36. "go.step.sm/crypto/x509util"
  37. )
  38. type options struct {
  39. configFile string
  40. linkedCAToken string
  41. quiet bool
  42. password []byte
  43. issuerPassword []byte
  44. sshHostPassword []byte
  45. sshUserPassword []byte
  46. database db.AuthDB
  47. }
  48. func (o *options) apply(opts []Option) {
  49. for _, fn := range opts {
  50. fn(o)
  51. }
  52. }
  53. // Option is the type of options passed to the CA constructor.
  54. type Option func(o *options)
  55. // WithConfigFile sets the given name as the configuration file name in the CA
  56. // options.
  57. func WithConfigFile(name string) Option {
  58. return func(o *options) {
  59. o.configFile = name
  60. }
  61. }
  62. // WithPassword sets the given password as the configured password in the CA
  63. // options.
  64. func WithPassword(password []byte) Option {
  65. return func(o *options) {
  66. o.password = password
  67. }
  68. }
  69. // WithSSHHostPassword sets the given password to decrypt the key used to sign
  70. // ssh host certificates.
  71. func WithSSHHostPassword(password []byte) Option {
  72. return func(o *options) {
  73. o.sshHostPassword = password
  74. }
  75. }
  76. // WithSSHUserPassword sets the given password to decrypt the key used to sign
  77. // ssh user certificates.
  78. func WithSSHUserPassword(password []byte) Option {
  79. return func(o *options) {
  80. o.sshUserPassword = password
  81. }
  82. }
  83. // WithIssuerPassword sets the given password as the configured certificate
  84. // issuer password in the CA options.
  85. func WithIssuerPassword(password []byte) Option {
  86. return func(o *options) {
  87. o.issuerPassword = password
  88. }
  89. }
  90. // WithDatabase sets the given authority database to the CA options.
  91. func WithDatabase(d db.AuthDB) Option {
  92. return func(o *options) {
  93. o.database = d
  94. }
  95. }
  96. // WithLinkedCAToken sets the token used to authenticate with the linkedca.
  97. func WithLinkedCAToken(token string) Option {
  98. return func(o *options) {
  99. o.linkedCAToken = token
  100. }
  101. }
  102. // WithQuiet sets the quiet flag.
  103. func WithQuiet(quiet bool) Option {
  104. return func(o *options) {
  105. o.quiet = quiet
  106. }
  107. }
  108. // CA is the type used to build the complete certificate authority. It builds
  109. // the HTTP server, set ups the middlewares and the HTTP handlers.
  110. type CA struct {
  111. auth *authority.Authority
  112. config *config.Config
  113. srv *server.Server
  114. insecureSrv *server.Server
  115. metricsSrv *server.Server
  116. opts *options
  117. renewer *TLSRenewer
  118. compactStop chan struct{}
  119. }
  120. // New creates and initializes the CA with the given configuration and options.
  121. func New(cfg *config.Config, opts ...Option) (*CA, error) {
  122. ca := &CA{
  123. config: cfg,
  124. opts: new(options),
  125. compactStop: make(chan struct{}),
  126. }
  127. ca.opts.apply(opts)
  128. return ca.Init(cfg)
  129. }
  130. // Init initializes the CA with the given configuration.
  131. func (ca *CA) Init(cfg *config.Config) (*CA, error) {
  132. // Set password, it's ok to set nil password, the ca will prompt for them if
  133. // they are required.
  134. opts := []authority.Option{
  135. authority.WithPassword(ca.opts.password),
  136. authority.WithSSHHostPassword(ca.opts.sshHostPassword),
  137. authority.WithSSHUserPassword(ca.opts.sshUserPassword),
  138. authority.WithIssuerPassword(ca.opts.issuerPassword),
  139. }
  140. if ca.opts.linkedCAToken != "" {
  141. opts = append(opts, authority.WithLinkedCAToken(ca.opts.linkedCAToken))
  142. }
  143. if ca.opts.database != nil {
  144. opts = append(opts, authority.WithDatabase(ca.opts.database))
  145. }
  146. if ca.opts.quiet {
  147. opts = append(opts, authority.WithQuietInit())
  148. }
  149. var meter *metrix.Meter
  150. if ca.config.MetricsAddress != "" {
  151. meter = metrix.New()
  152. opts = append(opts, authority.WithMeter(meter))
  153. }
  154. webhookTransport := http.DefaultTransport.(*http.Transport).Clone()
  155. opts = append(opts, authority.WithWebhookClient(&http.Client{Transport: webhookTransport}))
  156. auth, err := authority.New(cfg, opts...)
  157. if err != nil {
  158. return nil, err
  159. }
  160. ca.auth = auth
  161. tlsConfig, clientTLSConfig, err := ca.getTLSConfig(auth)
  162. if err != nil {
  163. return nil, err
  164. }
  165. webhookTransport.TLSClientConfig = clientTLSConfig
  166. // Using chi as the main router
  167. mux := chi.NewRouter()
  168. handler := http.Handler(mux)
  169. insecureMux := chi.NewRouter()
  170. insecureHandler := http.Handler(insecureMux)
  171. // Add HEAD middleware
  172. mux.Use(middleware.GetHead)
  173. insecureMux.Use(middleware.GetHead)
  174. // Add regular CA api endpoints in / and /1.0
  175. api.Route(mux)
  176. mux.Route("/1.0", func(r chi.Router) {
  177. api.Route(r)
  178. })
  179. // Mount the CRL to the insecure mux
  180. insecureMux.Get("/crl", api.CRL)
  181. insecureMux.Get("/1.0/crl", api.CRL)
  182. // Add ACME api endpoints in /acme and /1.0/acme
  183. dns := cfg.DNSNames[0]
  184. u, err := url.Parse("https://" + cfg.Address)
  185. if err != nil {
  186. return nil, err
  187. }
  188. port := u.Port()
  189. if port != "" && port != "443" {
  190. dns = fmt.Sprintf("%s:%s", dns, port)
  191. }
  192. // ACME Router is only available if we have a database.
  193. var acmeDB acme.DB
  194. var acmeLinker acme.Linker
  195. if cfg.DB != nil {
  196. acmeDB, err = acmeNoSQL.New(auth.GetDatabase().(nosql.DB))
  197. if err != nil {
  198. return nil, errors.Wrap(err, "error configuring ACME DB interface")
  199. }
  200. acmeLinker = acme.NewLinker(dns, "acme")
  201. mux.Route("/acme", func(r chi.Router) {
  202. acmeAPI.Route(r)
  203. })
  204. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  205. // of the ACME spec.
  206. mux.Route("/2.0/acme", func(r chi.Router) {
  207. acmeAPI.Route(r)
  208. })
  209. }
  210. // Admin API Router
  211. if cfg.AuthorityConfig.EnableAdmin {
  212. adminDB := auth.GetAdminDatabase()
  213. if adminDB != nil {
  214. acmeAdminResponder := adminAPI.NewACMEAdminResponder()
  215. policyAdminResponder := adminAPI.NewPolicyAdminResponder()
  216. webhookAdminResponder := adminAPI.NewWebhookAdminResponder()
  217. mux.Route("/admin", func(r chi.Router) {
  218. adminAPI.Route(
  219. r,
  220. adminAPI.WithACMEResponder(acmeAdminResponder),
  221. adminAPI.WithPolicyResponder(policyAdminResponder),
  222. adminAPI.WithWebhookResponder(webhookAdminResponder),
  223. )
  224. })
  225. }
  226. }
  227. var scepAuthority *scep.Authority
  228. if ca.shouldServeSCEPEndpoints() {
  229. // get the SCEP authority configuration. Validation is
  230. // performed within the authority instantiation process.
  231. scepAuthority = auth.GetSCEP()
  232. // According to the RFC (https://tools.ietf.org/html/rfc8894#section-7.10),
  233. // SCEP operations are performed using HTTP, so that's why the API is mounted
  234. // to the insecure mux.
  235. scepPrefix := "scep"
  236. insecureMux.Route("/"+scepPrefix, func(r chi.Router) {
  237. scepAPI.Route(r)
  238. })
  239. // The RFC also mentions usage of HTTPS, but seems to advise
  240. // against it, because of potential interoperability issues.
  241. // Currently I think it's not bad to use HTTPS also, so that's
  242. // why I've kept the API endpoints in both muxes and both HTTP
  243. // as well as HTTPS can be used to request certificates
  244. // using SCEP.
  245. mux.Route("/"+scepPrefix, func(r chi.Router) {
  246. scepAPI.Route(r)
  247. })
  248. }
  249. // helpful routine for logging all routes
  250. //dumpRoutes(mux)
  251. //dumpRoutes(insecureMux)
  252. // Add monitoring if configured
  253. if len(cfg.Monitoring) > 0 {
  254. m, err := monitoring.New(cfg.Monitoring)
  255. if err != nil {
  256. return nil, err
  257. }
  258. handler = m.Middleware(handler)
  259. insecureHandler = m.Middleware(insecureHandler)
  260. }
  261. // Add logger if configured
  262. if len(cfg.Logger) > 0 {
  263. logger, err := logging.New("ca", cfg.Logger)
  264. if err != nil {
  265. return nil, err
  266. }
  267. handler = logger.Middleware(handler)
  268. insecureHandler = logger.Middleware(insecureHandler)
  269. }
  270. // Create context with all the necessary values.
  271. baseContext := buildContext(auth, scepAuthority, acmeDB, acmeLinker)
  272. ca.srv = server.New(cfg.Address, handler, tlsConfig)
  273. ca.srv.BaseContext = func(net.Listener) context.Context {
  274. return baseContext
  275. }
  276. // only start the insecure server if the insecure address is configured
  277. // and, currently, also only when it should serve SCEP endpoints.
  278. if ca.shouldServeInsecureServer() {
  279. // TODO: instead opt for having a single server.Server but two
  280. // http.Servers handling the HTTP and HTTPS handler? The latter
  281. // will probably introduce more complexity in terms of graceful
  282. // reload.
  283. ca.insecureSrv = server.New(cfg.InsecureAddress, insecureHandler, nil)
  284. ca.insecureSrv.BaseContext = func(net.Listener) context.Context {
  285. return baseContext
  286. }
  287. }
  288. if meter != nil {
  289. ca.metricsSrv = server.New(ca.config.MetricsAddress, meter, nil)
  290. ca.metricsSrv.BaseContext = func(net.Listener) context.Context {
  291. return baseContext
  292. }
  293. }
  294. return ca, nil
  295. }
  296. // shouldServeInsecureServer returns whether or not the insecure
  297. // server should also be started. This is (currently) only the case
  298. // if the insecure address has been configured AND when a SCEP
  299. // provisioner is configured or when a CRL is configured.
  300. func (ca *CA) shouldServeInsecureServer() bool {
  301. switch {
  302. case ca.config.InsecureAddress == "":
  303. return false
  304. case ca.shouldServeSCEPEndpoints():
  305. return true
  306. case ca.config.CRL.IsEnabled():
  307. return true
  308. default:
  309. return false
  310. }
  311. }
  312. // buildContext builds the server base context.
  313. func buildContext(a *authority.Authority, scepAuthority *scep.Authority, acmeDB acme.DB, acmeLinker acme.Linker) context.Context {
  314. ctx := authority.NewContext(context.Background(), a)
  315. if authDB := a.GetDatabase(); authDB != nil {
  316. ctx = db.NewContext(ctx, authDB)
  317. }
  318. if adminDB := a.GetAdminDatabase(); adminDB != nil {
  319. ctx = admin.NewContext(ctx, adminDB)
  320. }
  321. if scepAuthority != nil {
  322. ctx = scep.NewContext(ctx, scepAuthority)
  323. }
  324. if acmeDB != nil {
  325. ctx = acme.NewContext(ctx, acmeDB, acme.NewClient(), acmeLinker, nil)
  326. }
  327. return ctx
  328. }
  329. // Run starts the CA calling to the server ListenAndServe method.
  330. func (ca *CA) Run() error {
  331. var wg sync.WaitGroup
  332. errs := make(chan error, 1)
  333. if !ca.opts.quiet {
  334. authorityInfo := ca.auth.GetInfo()
  335. log.Printf("Starting %s", step.Version())
  336. log.Printf("Documentation: https://u.step.sm/docs/ca")
  337. log.Printf("Community Discord: https://u.step.sm/discord")
  338. if step.Contexts().GetCurrent() != nil {
  339. log.Printf("Current context: %s", step.Contexts().GetCurrent().Name)
  340. }
  341. log.Printf("Config file: %s", ca.getConfigFileOutput())
  342. baseURL := fmt.Sprintf("https://%s%s",
  343. authorityInfo.DNSNames[0],
  344. ca.config.Address[strings.LastIndex(ca.config.Address, ":"):])
  345. log.Printf("The primary server URL is %s", baseURL)
  346. log.Printf("Root certificates are available at %s/roots.pem", baseURL)
  347. if len(authorityInfo.DNSNames) > 1 {
  348. log.Printf("Additional configured hostnames: %s",
  349. strings.Join(authorityInfo.DNSNames[1:], ", "))
  350. }
  351. for _, crt := range authorityInfo.RootX509Certs {
  352. log.Printf("X.509 Root Fingerprint: %s", x509util.Fingerprint(crt))
  353. }
  354. if authorityInfo.SSHCAHostPublicKey != nil {
  355. log.Printf("SSH Host CA Key: %s\n", bytes.TrimSpace(authorityInfo.SSHCAHostPublicKey))
  356. }
  357. if authorityInfo.SSHCAUserPublicKey != nil {
  358. log.Printf("SSH User CA Key: %s\n", bytes.TrimSpace(authorityInfo.SSHCAUserPublicKey))
  359. }
  360. }
  361. wg.Add(1)
  362. go func() {
  363. defer wg.Done()
  364. ca.runCompactJob()
  365. }()
  366. if ca.insecureSrv != nil {
  367. wg.Add(1)
  368. go func() {
  369. defer wg.Done()
  370. errs <- ca.insecureSrv.ListenAndServe()
  371. }()
  372. }
  373. if ca.metricsSrv != nil {
  374. wg.Add(1)
  375. go func() {
  376. defer wg.Done()
  377. errs <- ca.metricsSrv.ListenAndServe()
  378. }()
  379. }
  380. wg.Add(1)
  381. go func() {
  382. defer wg.Done()
  383. errs <- ca.srv.ListenAndServe()
  384. }()
  385. // wait till error occurs; ensures the servers keep listening
  386. err := <-errs
  387. wg.Wait()
  388. return err
  389. }
  390. // Stop stops the CA calling to the server Shutdown method.
  391. func (ca *CA) Stop() error {
  392. close(ca.compactStop)
  393. ca.renewer.Stop()
  394. if err := ca.auth.Shutdown(); err != nil {
  395. log.Printf("error stopping ca.Authority: %+v\n", err)
  396. }
  397. var insecureShutdownErr error
  398. if ca.insecureSrv != nil {
  399. insecureShutdownErr = ca.insecureSrv.Shutdown()
  400. }
  401. secureErr := ca.srv.Shutdown()
  402. if insecureShutdownErr != nil {
  403. return insecureShutdownErr
  404. }
  405. return secureErr
  406. }
  407. // Reload reloads the configuration of the CA and calls to the server Reload
  408. // method.
  409. func (ca *CA) Reload() error {
  410. cfg, err := config.LoadConfiguration(ca.opts.configFile)
  411. if err != nil {
  412. return errors.Wrap(err, "error reloading ca configuration")
  413. }
  414. logContinue := func(reason string) {
  415. log.Println(reason)
  416. log.Println("Continuing to run with the original configuration.")
  417. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  418. }
  419. // Do not allow reload if the database configuration has changed.
  420. if !reflect.DeepEqual(ca.config.DB, cfg.DB) {
  421. logContinue("Reload failed because the database configuration has changed.")
  422. return errors.New("error reloading ca: database configuration cannot change")
  423. }
  424. newCA, err := New(cfg,
  425. WithPassword(ca.opts.password),
  426. WithSSHHostPassword(ca.opts.sshHostPassword),
  427. WithSSHUserPassword(ca.opts.sshUserPassword),
  428. WithIssuerPassword(ca.opts.issuerPassword),
  429. WithLinkedCAToken(ca.opts.linkedCAToken),
  430. WithQuiet(ca.opts.quiet),
  431. WithConfigFile(ca.opts.configFile),
  432. WithDatabase(ca.auth.GetDatabase()),
  433. )
  434. if err != nil {
  435. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  436. return errors.Wrap(err, "error reloading ca")
  437. }
  438. if ca.insecureSrv != nil {
  439. if err = ca.insecureSrv.Reload(newCA.insecureSrv); err != nil {
  440. logContinue("Reload failed because insecure server could not be replaced.")
  441. return errors.Wrap(err, "error reloading insecure server")
  442. }
  443. }
  444. if ca.metricsSrv != nil {
  445. if err = ca.metricsSrv.Reload(newCA.metricsSrv); err != nil {
  446. logContinue("Reload failed because metrics server could not be replaced.")
  447. return errors.Wrap(err, "error reloading metrics server")
  448. }
  449. }
  450. if err = ca.srv.Reload(newCA.srv); err != nil {
  451. logContinue("Reload failed because server could not be replaced.")
  452. return errors.Wrap(err, "error reloading server")
  453. }
  454. // 1. Stop previous renewer
  455. // 2. Safely shutdown any internal resources (e.g. key manager)
  456. // 3. Replace ca properties
  457. // Do not replace ca.srv
  458. ca.renewer.Stop()
  459. ca.auth.CloseForReload()
  460. ca.auth = newCA.auth
  461. ca.config = newCA.config
  462. ca.opts = newCA.opts
  463. ca.renewer = newCA.renewer
  464. return nil
  465. }
  466. // get TLSConfig returns separate TLSConfigs for server and client with the
  467. // same self-renewing certificate.
  468. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, *tls.Config, error) {
  469. // Create initial TLS certificate
  470. tlsCrt, err := auth.GetTLSCertificate()
  471. if err != nil {
  472. return nil, nil, err
  473. }
  474. // Start tls renewer with the new certificate.
  475. // If a renewer was started, attempt to stop it before.
  476. if ca.renewer != nil {
  477. ca.renewer.Stop()
  478. }
  479. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  480. if err != nil {
  481. return nil, nil, err
  482. }
  483. ca.renewer.Run()
  484. var serverTLSConfig *tls.Config
  485. if ca.config.TLS != nil {
  486. serverTLSConfig = ca.config.TLS.TLSConfig()
  487. } else {
  488. serverTLSConfig = &tls.Config{
  489. MinVersion: tls.VersionTLS12,
  490. }
  491. }
  492. // GetCertificate will only be called if the client supplies SNI
  493. // information or if tlsConfig.Certificates is empty.
  494. // When client requests are made using an IP address (as opposed to a domain
  495. // name) the server does not receive any SNI and may fallback to using the
  496. // first entry in the Certificates attribute; by setting the attribute to
  497. // empty we are implicitly forcing GetCertificate to be the only mechanism
  498. // by which the server can find it's own leaf Certificate.
  499. serverTLSConfig.Certificates = []tls.Certificate{}
  500. clientTLSConfig := serverTLSConfig.Clone()
  501. serverTLSConfig.GetCertificate = ca.renewer.GetCertificateForCA
  502. clientTLSConfig.GetClientCertificate = ca.renewer.GetClientCertificate
  503. // initialize a certificate pool with root CA certificates to trust when doing mTLS.
  504. certPool := x509.NewCertPool()
  505. // initialize a certificate pool with root CA certificates to trust when connecting
  506. // to webhook servers
  507. rootCAsPool, err := x509.SystemCertPool()
  508. if err != nil {
  509. return nil, nil, err
  510. }
  511. for _, crt := range auth.GetRootCertificates() {
  512. certPool.AddCert(crt)
  513. rootCAsPool.AddCert(crt)
  514. }
  515. // adding the intermediate CA certificates to the pool will allow clients that
  516. // do mTLS but don't send an intermediate to successfully connect. The intermediates
  517. // added here are used when building a certificate chain.
  518. intermediates := tlsCrt.Certificate[1:]
  519. for _, certBytes := range intermediates {
  520. cert, err := x509.ParseCertificate(certBytes)
  521. if err != nil {
  522. return nil, nil, err
  523. }
  524. certPool.AddCert(cert)
  525. rootCAsPool.AddCert(cert)
  526. }
  527. // Add support for mutual tls to renew certificates
  528. serverTLSConfig.ClientAuth = tls.VerifyClientCertIfGiven
  529. serverTLSConfig.ClientCAs = certPool
  530. clientTLSConfig.RootCAs = rootCAsPool
  531. return serverTLSConfig, clientTLSConfig, nil
  532. }
  533. // shouldServeSCEPEndpoints returns if the CA should be
  534. // configured with endpoints for SCEP. This is assumed to be
  535. // true if a SCEPService exists, which is true in case at
  536. // least one SCEP provisioner was configured.
  537. func (ca *CA) shouldServeSCEPEndpoints() bool {
  538. return ca.auth.GetSCEP() != nil
  539. }
  540. //nolint:unused // useful for debugging
  541. func dumpRoutes(mux chi.Routes) {
  542. // helpful routine for logging all routes
  543. walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
  544. fmt.Printf("%s %s\n", method, route)
  545. return nil
  546. }
  547. if err := chi.Walk(mux, walkFunc); err != nil {
  548. fmt.Printf("Logging err: %s\n", err.Error())
  549. }
  550. }
  551. func (ca *CA) getConfigFileOutput() string {
  552. if ca.config.WasLoadedFromFile() {
  553. return ca.config.Filepath()
  554. }
  555. return "loaded from token"
  556. }
  557. // runCompactJob will run the value log garbage collector if the nosql database
  558. // supports it.
  559. func (ca *CA) runCompactJob() {
  560. caDB, ok := ca.auth.GetDatabase().(*db.DB)
  561. if !ok {
  562. return
  563. }
  564. compactor, ok := caDB.DB.(nosql.Compactor)
  565. if !ok {
  566. return
  567. }
  568. // Compact database at start.
  569. runCompact(compactor)
  570. // Compact database every minute.
  571. ticker := time.NewTicker(time.Minute)
  572. defer ticker.Stop()
  573. for {
  574. select {
  575. case <-ca.compactStop:
  576. return
  577. case <-ticker.C:
  578. runCompact(compactor)
  579. }
  580. }
  581. }
  582. // runCompact executes the compact job until it returns an error.
  583. func runCompact(c nosql.Compactor) {
  584. for err := error(nil); err == nil; {
  585. err = c.Compact(0.7)
  586. }
  587. }