app.go 2.3 KB

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