package vault import ( "fmt" "os" "path/filepath" "regexp" "git.eeqj.de/sneak/secret/internal/secret" "github.com/spf13/afero" ) // Register the GetCurrentVault function with the secret package func init() { secret.RegisterGetCurrentVaultFunc(func(fs afero.Fs, stateDir string) (secret.VaultInterface, error) { return GetCurrentVault(fs, stateDir) }) } // isValidVaultName validates vault names according to the format [a-z0-9\.\-\_]+ // Note: We don't allow slashes in vault names unlike secret names func isValidVaultName(name string) bool { if name == "" { return false } matched, _ := regexp.MatchString(`^[a-z0-9\.\-\_]+$`, name) return matched } // resolveVaultSymlink resolves the currentvault symlink by reading either the symlink target or file contents // This function is designed to work on both Unix and Windows systems, as well as with in-memory filesystems func resolveVaultSymlink(fs afero.Fs, symlinkPath string) (string, error) { secret.Debug("resolveVaultSymlink starting", "symlink_path", symlinkPath) // First try to handle the path as a real symlink (works on Unix systems) if _, ok := fs.(*afero.OsFs); ok { secret.Debug("Trying real filesystem symlink resolution") // Check if it's a real symlink first (will work on Unix) linkTarget, err := os.Readlink(symlinkPath) if err == nil { // Successfully read as symlink (Unix path) secret.Debug("Successfully read as real symlink", "target", linkTarget) // Convert relative paths to absolute if needed if !filepath.IsAbs(linkTarget) { linkTarget = filepath.Join(filepath.Dir(symlinkPath), linkTarget) } secret.Debug("Resolved symlink path", "path", linkTarget) return linkTarget, nil } secret.Debug("Not a real symlink or on Windows, trying as regular file", "error", err) } // For Windows or in-memory filesystems, or when symlink reading fails: // Read the path from a regular file (our fallback approach) secret.Debug("Reading symlink target from file") content, err := afero.ReadFile(fs, symlinkPath) if err != nil { secret.Debug("Failed to read from file", "error", err) return "", fmt.Errorf("failed to read vault path: %w", err) } targetPath := string(content) secret.Debug("Read target path from file", "target_path", targetPath) return targetPath, nil } // GetCurrentVault gets the currently selected vault func GetCurrentVault(fs afero.Fs, stateDir string) (*Vault, error) { secret.Debug("Getting current vault", "state_dir", stateDir) // Check if current vault symlink exists currentVaultPath := filepath.Join(stateDir, "currentvault") secret.Debug("Checking current vault symlink", "path", currentVaultPath) _, err := fs.Stat(currentVaultPath) if err != nil { secret.Debug("Failed to stat current vault symlink", "error", err, "path", currentVaultPath) return nil, fmt.Errorf("failed to read current vault symlink: %w", err) } secret.Debug("Current vault symlink exists") // Resolve symlink to get target path secret.Debug("Resolving vault symlink") targetPath, err := resolveVaultSymlink(fs, currentVaultPath) if err != nil { secret.Debug("Failed to resolve vault symlink", "error", err) return nil, fmt.Errorf("failed to resolve vault symlink: %w", err) } secret.Debug("Resolved vault symlink", "target_path", targetPath) // Extract vault name from target path vaultName := filepath.Base(targetPath) secret.Debug("Extracted vault name", "vault_name", vaultName) secret.Debug("Current vault resolved", "vault_name", vaultName, "target_path", targetPath) // Create and return Vault instance secret.Debug("Creating NewVault instance") vault := NewVault(fs, vaultName, stateDir) secret.Debug("Created NewVault instance successfully") return vault, nil } // ListVaults returns a list of available vault names func ListVaults(fs afero.Fs, stateDir string) ([]string, error) { vaultsDir := filepath.Join(stateDir, "vaults.d") // Check if vaults directory exists exists, err := afero.DirExists(fs, vaultsDir) if err != nil { return nil, fmt.Errorf("failed to check vaults directory: %w", err) } if !exists { return []string{}, nil } // Read directory contents files, err := afero.ReadDir(fs, vaultsDir) if err != nil { return nil, fmt.Errorf("failed to read vaults directory: %w", err) } var vaults []string for _, file := range files { if file.IsDir() { vaults = append(vaults, file.Name()) } } return vaults, nil } // CreateVault creates a new vault with the given name func CreateVault(fs afero.Fs, stateDir string, name string) (*Vault, error) { secret.Debug("Creating new vault", "name", name, "state_dir", stateDir) // Validate vault name if !isValidVaultName(name) { secret.Debug("Invalid vault name provided", "vault_name", name) return nil, fmt.Errorf("invalid vault name '%s': must match pattern [a-z0-9.\\-_]+", name) } secret.Debug("Vault name validation passed", "vault_name", name) // Create vault directory structure vaultDir := filepath.Join(stateDir, "vaults.d", name) secret.Debug("Creating vault directory structure", "vault_dir", vaultDir) // Check if vault already exists exists, err := afero.DirExists(fs, vaultDir) if err != nil { return nil, fmt.Errorf("failed to check if vault exists: %w", err) } if exists { return nil, fmt.Errorf("vault %s already exists", name) } // Create vault directory if err := fs.MkdirAll(vaultDir, 0700); err != nil { return nil, fmt.Errorf("failed to create vault directory: %w", err) } // Create subdirectories secretsDir := filepath.Join(vaultDir, "secrets.d") if err := fs.MkdirAll(secretsDir, 0700); err != nil { return nil, fmt.Errorf("failed to create secrets directory: %w", err) } unlockKeysDir := filepath.Join(vaultDir, "unlock.d") if err := fs.MkdirAll(unlockKeysDir, 0700); err != nil { return nil, fmt.Errorf("failed to create unlock keys directory: %w", err) } // Select the new vault as current secret.Debug("Selecting newly created vault as current", "name", name) if err := SelectVault(fs, stateDir, name); err != nil { return nil, fmt.Errorf("failed to select new vault: %w", err) } secret.Debug("Successfully created vault", "name", name) return NewVault(fs, name, stateDir), nil } // SelectVault selects the given vault as the current vault func SelectVault(fs afero.Fs, stateDir string, name string) error { secret.Debug("Selecting vault", "vault_name", name, "state_dir", stateDir) // Validate vault name if !isValidVaultName(name) { secret.Debug("Invalid vault name provided", "vault_name", name) return fmt.Errorf("invalid vault name '%s': must match pattern [a-z0-9.\\-_]+", name) } secret.Debug("Vault name validation passed", "vault_name", name) // Check if vault exists vaultDir := filepath.Join(stateDir, "vaults.d", name) exists, err := afero.DirExists(fs, vaultDir) if err != nil { return fmt.Errorf("failed to check if vault exists: %w", err) } if !exists { return fmt.Errorf("vault %s does not exist", name) } // Create/update current vault symlink currentVaultPath := filepath.Join(stateDir, "currentvault") // Remove existing symlink if it exists if exists, _ := afero.Exists(fs, currentVaultPath); exists { secret.Debug("Removing existing current vault symlink", "path", currentVaultPath) if err := fs.Remove(currentVaultPath); err != nil { secret.Debug("Failed to remove existing symlink", "error", err, "path", currentVaultPath) } } // Create new symlink pointing to the vault targetPath := vaultDir secret.Debug("Creating vault symlink", "target", targetPath, "link", currentVaultPath) // For real filesystems, try to create a real symlink first if _, ok := fs.(*afero.OsFs); ok { if err := os.Symlink(targetPath, currentVaultPath); err != nil { // If symlink creation fails, fall back to writing target path to file secret.Debug("Failed to create real symlink, falling back to file", "error", err) if err := afero.WriteFile(fs, currentVaultPath, []byte(targetPath), 0600); err != nil { return fmt.Errorf("failed to create vault symlink: %w", err) } } } else { // For in-memory filesystems, write target path to file if err := afero.WriteFile(fs, currentVaultPath, []byte(targetPath), 0600); err != nil { return fmt.Errorf("failed to create vault symlink: %w", err) } } secret.Debug("Successfully selected vault", "vault_name", name) return nil }