|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "os/user" |
| 9 | + "path/filepath" |
| 10 | + "regexp" |
| 11 | + "runtime" |
| 12 | + "slices" |
| 13 | + "time" |
| 14 | + |
| 15 | + "filippo.io/age" |
| 16 | + "github.com/fystack/mpcium/pkg/common/pathutil" |
| 17 | + "github.com/fystack/mpcium/pkg/encryption" |
| 18 | + "github.com/fystack/mpcium/pkg/types" |
| 19 | + "github.com/urfave/cli/v3" |
| 20 | +) |
| 21 | + |
| 22 | +// AuthorizerIdentity struct to store authorizer metadata |
| 23 | +type AuthorizerIdentity struct { |
| 24 | + Name string `json:"name"` |
| 25 | + Algorithm string `json:"algorithm,omitempty"` |
| 26 | + PublicKey string `json:"public_key"` |
| 27 | + CreatedAt string `json:"created_at"` |
| 28 | + CreatedBy string `json:"created_by"` |
| 29 | + MachineOS string `json:"machine_os"` |
| 30 | + MachineName string `json:"machine_name"` |
| 31 | +} |
| 32 | + |
| 33 | +// validateAuthorizerName checks if the authorizer name is valid (no spaces, special characters) |
| 34 | +func validateAuthorizerName(name string) error { |
| 35 | + if name == "" { |
| 36 | + return fmt.Errorf("name cannot be empty") |
| 37 | + } |
| 38 | + |
| 39 | + // Only allow alphanumeric characters, hyphens, and underscores |
| 40 | + validNamePattern := regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) |
| 41 | + if !validNamePattern.MatchString(name) { |
| 42 | + return fmt.Errorf("name can only contain alphanumeric characters, hyphens, and underscores (no spaces or special characters)") |
| 43 | + } |
| 44 | + |
| 45 | + return nil |
| 46 | +} |
| 47 | + |
| 48 | +func generateAuthorizerIdentity(ctx context.Context, c *cli.Command) error { |
| 49 | + name := c.String("name") |
| 50 | + outputDir := c.String("output-dir") |
| 51 | + encrypt := c.Bool("encrypt") |
| 52 | + overwrite := c.Bool("overwrite") |
| 53 | + algorithm := c.String("algorithm") |
| 54 | + |
| 55 | + // Validate authorizer name |
| 56 | + if err := validateAuthorizerName(name); err != nil { |
| 57 | + return err |
| 58 | + } |
| 59 | + |
| 60 | + if algorithm == "" { |
| 61 | + algorithm = string(types.EventInitiatorKeyTypeEd25519) |
| 62 | + } |
| 63 | + |
| 64 | + if !slices.Contains( |
| 65 | + []string{string(types.EventInitiatorKeyTypeEd25519), string(types.EventInitiatorKeyTypeP256)}, |
| 66 | + algorithm, |
| 67 | + ) { |
| 68 | + return fmt.Errorf("invalid algorithm: %s. Must be %s or %s", |
| 69 | + algorithm, |
| 70 | + types.EventInitiatorKeyTypeEd25519, |
| 71 | + types.EventInitiatorKeyTypeP256, |
| 72 | + ) |
| 73 | + } |
| 74 | + |
| 75 | + // Create output directory if it doesn't exist |
| 76 | + if err := os.MkdirAll(outputDir, 0750); err != nil { |
| 77 | + return fmt.Errorf("failed to create output directory: %w", err) |
| 78 | + } |
| 79 | + |
| 80 | + // Check if files already exist before proceeding |
| 81 | + identityPath := filepath.Join(outputDir, fmt.Sprintf("%s.authorizer.identity.json", name)) |
| 82 | + keyPath := filepath.Join(outputDir, fmt.Sprintf("%s.authorizer.key", name)) |
| 83 | + encKeyPath := keyPath + ".age" |
| 84 | + |
| 85 | + // Check for existing identity file |
| 86 | + if _, err := os.Stat(identityPath); err == nil && !overwrite { |
| 87 | + return fmt.Errorf( |
| 88 | + "identity file already exists: %s (use --overwrite to force)", |
| 89 | + identityPath, |
| 90 | + ) |
| 91 | + } |
| 92 | + |
| 93 | + // Check for existing key files |
| 94 | + if _, err := os.Stat(keyPath); err == nil && !overwrite { |
| 95 | + return fmt.Errorf("key file already exists: %s (use --overwrite to force)", keyPath) |
| 96 | + } |
| 97 | + |
| 98 | + if encrypt { |
| 99 | + if _, err := os.Stat(encKeyPath); err == nil && !overwrite { |
| 100 | + return fmt.Errorf( |
| 101 | + "encrypted key file already exists: %s (use --overwrite to force)", |
| 102 | + encKeyPath, |
| 103 | + ) |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + // Generate keys based on algorithm |
| 108 | + var keyData encryption.KeyData |
| 109 | + var err error |
| 110 | + |
| 111 | + if algorithm == string(types.EventInitiatorKeyTypeEd25519) { |
| 112 | + keyData, err = encryption.GenerateEd25519Keys() |
| 113 | + } else if algorithm == string(types.EventInitiatorKeyTypeP256) { |
| 114 | + keyData, err = encryption.GenerateP256Keys() |
| 115 | + } |
| 116 | + |
| 117 | + if err != nil { |
| 118 | + return fmt.Errorf("failed to generate %s keys: %w", algorithm, err) |
| 119 | + } |
| 120 | + |
| 121 | + // Get current user |
| 122 | + currentUser, err := user.Current() |
| 123 | + if err != nil { |
| 124 | + return fmt.Errorf("failed to get current user: %w", err) |
| 125 | + } |
| 126 | + |
| 127 | + // Get hostname |
| 128 | + hostname, err := os.Hostname() |
| 129 | + if err != nil { |
| 130 | + hostname = "unknown" |
| 131 | + } |
| 132 | + |
| 133 | + // Create Identity object |
| 134 | + identity := AuthorizerIdentity{ |
| 135 | + Name: name, |
| 136 | + Algorithm: algorithm, |
| 137 | + PublicKey: keyData.PublicKeyHex, |
| 138 | + CreatedAt: time.Now().UTC().Format(time.RFC3339), |
| 139 | + CreatedBy: currentUser.Username, |
| 140 | + MachineOS: runtime.GOOS, |
| 141 | + MachineName: hostname, |
| 142 | + } |
| 143 | + |
| 144 | + // Save identity JSON |
| 145 | + identityBytes, err := json.MarshalIndent(identity, "", " ") |
| 146 | + if err != nil { |
| 147 | + return fmt.Errorf("failed to marshal identity JSON: %w", err) |
| 148 | + } |
| 149 | + |
| 150 | + if err := os.WriteFile(identityPath, identityBytes, 0600); err != nil { |
| 151 | + return fmt.Errorf("failed to save identity file: %w", err) |
| 152 | + } |
| 153 | + |
| 154 | + // Handle private key (with optional encryption) |
| 155 | + if encrypt { |
| 156 | + // Use requestPassword function instead of inline password handling |
| 157 | + passphrase, err := requestPassword() |
| 158 | + if err != nil { |
| 159 | + return err |
| 160 | + } |
| 161 | + |
| 162 | + // Create encrypted key file |
| 163 | + encKeyPath := keyPath + ".age" |
| 164 | + |
| 165 | + // Validate the encrypted key path for security |
| 166 | + if err := pathutil.ValidateFilePath(encKeyPath); err != nil { |
| 167 | + return fmt.Errorf("invalid encrypted key file path: %w", err) |
| 168 | + } |
| 169 | + |
| 170 | + outFile, err := os.Create(encKeyPath) |
| 171 | + if err != nil { |
| 172 | + return fmt.Errorf("failed to create encrypted private key file: %w", err) |
| 173 | + } |
| 174 | + defer outFile.Close() |
| 175 | + |
| 176 | + // Set up age encryption |
| 177 | + recipient, err := age.NewScryptRecipient(passphrase) |
| 178 | + if err != nil { |
| 179 | + return fmt.Errorf("failed to create scrypt recipient: %w", err) |
| 180 | + } |
| 181 | + |
| 182 | + identityWriter, err := age.Encrypt(outFile, recipient) |
| 183 | + if err != nil { |
| 184 | + return fmt.Errorf("failed to create age encryption writer: %w", err) |
| 185 | + } |
| 186 | + |
| 187 | + // Write the encrypted private key |
| 188 | + if _, err := identityWriter.Write([]byte(keyData.PrivateKeyHex)); err != nil { |
| 189 | + return fmt.Errorf("failed to write encrypted private key: %w", err) |
| 190 | + } |
| 191 | + |
| 192 | + if err := identityWriter.Close(); err != nil { |
| 193 | + return fmt.Errorf("failed to finalize age encryption: %w", err) |
| 194 | + } |
| 195 | + |
| 196 | + fmt.Println("✅ Successfully generated authorizer identity:") |
| 197 | + fmt.Println("- Encrypted Private Key:", encKeyPath) |
| 198 | + fmt.Println("- Identity JSON:", identityPath) |
| 199 | + return nil |
| 200 | + } else { |
| 201 | + fmt.Println("WARNING: You are generating the private key without encryption.") |
| 202 | + fmt.Println("This is less secure. Consider using --encrypt flag for better security.") |
| 203 | + |
| 204 | + if err := os.WriteFile(keyPath, []byte(keyData.PrivateKeyHex), 0600); err != nil { |
| 205 | + return fmt.Errorf("failed to save private key: %w", err) |
| 206 | + } |
| 207 | + } |
| 208 | + |
| 209 | + fmt.Println("✅ Successfully generated authorizer identity:") |
| 210 | + fmt.Println("- Private Key:", keyPath) |
| 211 | + fmt.Println("- Identity JSON:", identityPath) |
| 212 | + return nil |
| 213 | +} |
0 commit comments