app.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package commands
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "os"
  8. "unicode"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/certificates/authority"
  11. "github.com/smallstep/certificates/ca"
  12. "github.com/smallstep/cli/errs"
  13. "github.com/urfave/cli"
  14. )
  15. // AppCommand is the action used as the top action.
  16. var AppCommand = cli.Command{
  17. Name: "start",
  18. Action: appAction,
  19. UsageText: `**step-ca** <config>
  20. [**--password-file**=<file>]`,
  21. Flags: []cli.Flag{
  22. cli.StringFlag{
  23. Name: "password-file",
  24. Usage: `path to the <file> containing the password to decrypt the
  25. intermediate private key.`,
  26. },
  27. },
  28. }
  29. // AppAction is the action used when the top command runs.
  30. func appAction(ctx *cli.Context) error {
  31. passFile := ctx.String("password-file")
  32. // If zero cmd line args show help, if >1 cmd line args show error.
  33. if ctx.NArg() == 0 {
  34. return cli.ShowAppHelp(ctx)
  35. }
  36. if err := errs.NumberOfArguments(ctx, 1); err != nil {
  37. return err
  38. }
  39. configFile := ctx.Args().Get(0)
  40. config, err := authority.LoadConfiguration(configFile)
  41. if err != nil {
  42. fatal(err)
  43. }
  44. var password []byte
  45. if passFile != "" {
  46. if password, err = ioutil.ReadFile(passFile); err != nil {
  47. fatal(errors.Wrapf(err, "error reading %s", passFile))
  48. }
  49. password = bytes.TrimRightFunc(password, unicode.IsSpace)
  50. }
  51. srv, err := ca.New(config, ca.WithConfigFile(configFile), ca.WithPassword(password))
  52. if err != nil {
  53. fatal(err)
  54. }
  55. go ca.StopReloaderHandler(srv)
  56. if err = srv.Run(); err != nil && err != http.ErrServerClosed {
  57. fatal(err)
  58. }
  59. return nil
  60. }
  61. // fatal writes the passed error on the standard error and exits with the exit
  62. // code 1. If the environment variable STEPDEBUG is set to 1 it shows the
  63. // stack trace of the error.
  64. func fatal(err error) {
  65. if os.Getenv("STEPDEBUG") == "1" {
  66. fmt.Fprintf(os.Stderr, "%+v\n", err)
  67. } else {
  68. fmt.Fprintln(os.Stderr, err)
  69. }
  70. os.Exit(2)
  71. }