import.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. package commands
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "github.com/pkg/errors"
  7. "github.com/urfave/cli"
  8. "google.golang.org/protobuf/encoding/protojson"
  9. "github.com/smallstep/cli-utils/command"
  10. "github.com/smallstep/cli-utils/errs"
  11. "github.com/smallstep/linkedca"
  12. "github.com/smallstep/certificates/authority/admin"
  13. adminDBNosql "github.com/smallstep/certificates/authority/admin/db/nosql"
  14. "github.com/smallstep/certificates/authority/config"
  15. "github.com/smallstep/certificates/db"
  16. )
  17. func init() {
  18. command.Register(cli.Command{
  19. Name: "import",
  20. Usage: "import provisioners and admins from an export file",
  21. UsageText: "**step-ca import** <config> <export-file> [**--dry-run**]",
  22. Action: importAction,
  23. Description: `**step-ca import** imports provisioners and admins from an export file
  24. into the CA's admin database.
  25. This command is used to migrate from a Linked CA to a standalone CA, or to
  26. migrate provisioners and admins between standalone CAs.
  27. The CA must be stopped before running this command.
  28. ## POSITIONAL ARGUMENTS
  29. <config>
  30. : The ca.json configuration file. Must have 'authority.enableAdmin: true'
  31. and a database configured.
  32. <export-file>
  33. : The export file created by 'step-ca export'.
  34. ## EXAMPLES
  35. Import provisioners and admins from an export file:
  36. '''
  37. $ step-ca import $(step path)/config/ca.json export.json
  38. '''
  39. Preview the import without making changes:
  40. '''
  41. $ step-ca import $(step path)/config/ca.json export.json --dry-run
  42. '''`,
  43. Flags: []cli.Flag{
  44. cli.BoolFlag{
  45. Name: "dry-run",
  46. Usage: "preview the import without making changes",
  47. },
  48. },
  49. })
  50. }
  51. func importAction(ctx *cli.Context) error {
  52. if err := errs.NumberOfArguments(ctx, 2); err != nil {
  53. return err
  54. }
  55. configFile := ctx.Args().Get(0)
  56. exportFile := ctx.Args().Get(1)
  57. dryRun := ctx.Bool("dry-run")
  58. // Load and validate configuration
  59. cfg, err := config.LoadConfiguration(configFile)
  60. if err != nil {
  61. return err
  62. }
  63. if err := cfg.Validate(); err != nil {
  64. return err
  65. }
  66. // Check that enableAdmin is true
  67. if cfg.AuthorityConfig == nil || !cfg.AuthorityConfig.EnableAdmin {
  68. return errors.New("authority.enableAdmin must be true to use the import command")
  69. }
  70. // Check that a database is configured
  71. if cfg.DB == nil {
  72. return errors.New("a database must be configured to use the import command")
  73. }
  74. // Read and parse export file
  75. exportData, err := os.ReadFile(exportFile)
  76. if err != nil {
  77. return errors.Wrapf(err, "error reading export file %s", exportFile)
  78. }
  79. var export linkedca.ConfigurationResponse
  80. if err := protojson.Unmarshal(exportData, &export); err != nil {
  81. return errors.Wrap(err, "error parsing export file")
  82. }
  83. if dryRun {
  84. fmt.Println("=== DRY RUN - No changes will be made ===")
  85. fmt.Println()
  86. }
  87. // Open database
  88. authDB, err := db.New(cfg.DB)
  89. if err != nil {
  90. return errors.Wrap(err, "error opening database")
  91. }
  92. defer func() {
  93. if dbShutdown, ok := authDB.(interface{ Shutdown() error }); ok {
  94. dbShutdown.Shutdown()
  95. }
  96. }()
  97. // Get the nosql.DB interface from the wrapped DB
  98. nosqlDB, ok := authDB.(*db.DB)
  99. if !ok {
  100. return errors.New("database does not support admin operations")
  101. }
  102. // Initialize admin DB
  103. adminDB, err := adminDBNosql.New(nosqlDB.DB, admin.DefaultAuthorityID)
  104. if err != nil {
  105. return errors.Wrap(err, "error initializing admin database")
  106. }
  107. // Get existing provisioners for duplicate detection
  108. existingProvs, err := adminDB.GetProvisioners(context.Background())
  109. if err != nil {
  110. return errors.Wrap(err, "error getting existing provisioners")
  111. }
  112. // Build map of existing provisioner names to IDs
  113. existingProvsByName := make(map[string]string)
  114. for _, p := range existingProvs {
  115. existingProvsByName[p.Name] = p.Id
  116. }
  117. // Get existing admins for duplicate detection
  118. existingAdmins, err := adminDB.GetAdmins(context.Background())
  119. if err != nil {
  120. return errors.Wrap(err, "error getting existing admins")
  121. }
  122. // Build set of existing admin subject+provisioner combos
  123. existingAdminKeys := make(map[string]bool)
  124. for _, a := range existingAdmins {
  125. key := a.Subject + ":" + a.ProvisionerId
  126. existingAdminKeys[key] = true
  127. }
  128. // Track old ID to new ID mappings for provisioners
  129. provIDMap := make(map[string]string)
  130. // Import provisioners first (admins reference them)
  131. fmt.Printf("Importing %d provisioner(s)...\n", len(export.Provisioners))
  132. var provsCreated, provsSkipped int
  133. for _, prov := range export.Provisioners {
  134. oldID := prov.Id
  135. // Check for duplicate by name
  136. if existingID, exists := existingProvsByName[prov.Name]; exists {
  137. fmt.Printf(" Skipping provisioner %q: already exists\n", prov.Name)
  138. provIDMap[oldID] = existingID
  139. provsSkipped++
  140. continue
  141. }
  142. if dryRun {
  143. fmt.Printf(" Would create provisioner %q (type: %s)\n", prov.Name, prov.Type.String())
  144. // For dry run, map old ID to itself since we won't create new ones
  145. provIDMap[oldID] = oldID
  146. provsCreated++
  147. continue
  148. }
  149. // Clear ID so the database generates a new one
  150. prov.Id = ""
  151. if err := adminDB.CreateProvisioner(context.Background(), prov); err != nil {
  152. return errors.Wrapf(err, "error creating provisioner %q", prov.Name)
  153. }
  154. fmt.Printf(" Created provisioner %q (type: %s)\n", prov.Name, prov.Type.String())
  155. provIDMap[oldID] = prov.Id
  156. provsCreated++
  157. }
  158. // Import admins with remapped provisioner IDs
  159. fmt.Printf("Importing %d admin(s)...\n", len(export.Admins))
  160. var adminsCreated, adminsSkipped int
  161. for _, adm := range export.Admins {
  162. // Remap provisioner ID
  163. newProvID, ok := provIDMap[adm.ProvisionerId]
  164. if !ok {
  165. fmt.Printf(" Skipping admin %q: provisioner ID %s not found in export\n", adm.Subject, adm.ProvisionerId)
  166. adminsSkipped++
  167. continue
  168. }
  169. // Check for duplicate by subject+provisioner combo
  170. key := adm.Subject + ":" + newProvID
  171. if existingAdminKeys[key] {
  172. fmt.Printf(" Skipping admin %q: already exists for this provisioner\n", adm.Subject)
  173. adminsSkipped++
  174. continue
  175. }
  176. if dryRun {
  177. fmt.Printf(" Would create admin %q (type: %s)\n", adm.Subject, adm.Type.String())
  178. adminsCreated++
  179. continue
  180. }
  181. // Clear ID and update provisioner ID
  182. adm.Id = ""
  183. adm.ProvisionerId = newProvID
  184. if err := adminDB.CreateAdmin(context.Background(), adm); err != nil {
  185. return errors.Wrapf(err, "error creating admin %q", adm.Subject)
  186. }
  187. fmt.Printf(" Created admin %q (type: %s)\n", adm.Subject, adm.Type.String())
  188. adminsCreated++
  189. }
  190. fmt.Println()
  191. fmt.Printf("Import complete: %d provisioner(s) created, %d skipped; %d admin(s) created, %d skipped\n",
  192. provsCreated, provsSkipped, adminsCreated, adminsSkipped)
  193. if dryRun {
  194. fmt.Println()
  195. fmt.Println("=== DRY RUN - No changes were made ===")
  196. fmt.Println("Run without --dry-run to perform the import.")
  197. }
  198. return nil
  199. }