validators

package
v1.0.0-rc07 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package validators provides built-in validators for common validation tasks.

This package contains validators for:

  • Cluster and organization names (ClusterNameValidator, OrganizationNameValidator)
  • Configuration values (ConfigValidator)
  • File paths and operations (FileValidator)
  • Security-related inputs (SecurityValidator)

Usage

Validators can be registered with a ValidationEngine:

engine := validation.NewValidationEngine()
engine.Register(validators.NewClusterNameValidator())
engine.Register(validators.NewConfigValidator())
engine.Register(validators.NewFileValidator())
engine.Register(validators.NewSecurityValidator())

Or registered globally:

validation.Register(validators.NewClusterNameValidator())

ClusterNameValidator

Validates cluster and organization names according to security requirements:

  • Must start with alphanumeric character
  • Can contain alphanumeric, hyphen, underscore, or dot
  • Maximum 63 characters
  • No path traversal sequences (..)
  • No path separators (/ or \)

Example:

validator := validators.NewClusterNameValidator()
result, err := validator.Validate(ctx, "my-cluster-01")
if err != nil {
    log.Fatal(err)
}
if !result.Valid {
    for _, issue := range result.Errors {
        fmt.Printf("Error: %s\n", issue.Message)
    }
}

ConfigValidator

Validates configuration values based on type:

  • email: Email address format
  • domain: Domain name format
  • fqdn: Fully qualified domain name
  • url: URL format and security (HTTPS for external)
  • ip: IP address (IPv4 or IPv6)
  • cidr: CIDR notation
  • port: Port number (1-65535)
  • cluster-name: Delegates to ClusterNameValidator

Example:

validator := validators.NewConfigValidator()
result, err := validator.Validate(ctx, map[string]interface{}{
    "type":  "email",
    "value": "admin@example.com",
})

FileValidator

Validates file paths and file system operations:

  • Path traversal prevention
  • Path length limits
  • File existence and permissions
  • Read/write/delete operation validation

Example:

validator := validators.NewFileValidator()
result, err := validator.Validate(ctx, map[string]interface{}{
    "operation": "read",
    "path":      "/path/to/file.yaml",
})

SecurityValidator

Validates security-related inputs:

  • Shell input injection prevention
  • Environment variable validation
  • Editor whitelist validation
  • Command safety checks
  • Secret detection

Example:

validator := validators.NewSecurityValidator()
result, err := validator.Validate(ctx, map[string]interface{}{
    "type":  "shell-input",
    "value": "user-input",
})

Custom Validators

You can create custom validators by implementing the validation.Validator interface:

type MyValidator struct{}

func (v *MyValidator) Name() string {
    return "my-validator"
}

func (v *MyValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
    result := &validation.ValidationResult{Valid: true}
    // Perform validation...
    return result, nil
}

Performance

All validators are designed to be fast (<100μs per validation) and thread-safe. They can be safely used concurrently from multiple goroutines.

Example (ServiceValidator)

Example_serviceValidator demonstrates basic service validation.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	// Create a service validator for Loki
	validator := validators.NewServiceValidator("loki")

	// Validate a service configuration
	config := map[string]interface{}{
		"enabled":   true,
		"namespace": "loki-system",
		"name":      "loki",
	}

	result, err := validator.Validate(context.Background(), config)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if result.Valid {
		fmt.Println("Service configuration is valid")
	} else {
		fmt.Println("Service configuration is invalid")
		for _, e := range result.Errors {
			fmt.Printf("Error: %s - %s\n", e.Field, e.Message)
		}
	}

}
Output:
Service configuration is valid
Example (ServiceValidator_baseServiceConfig)

Example_serviceValidator_baseServiceConfig demonstrates using BaseServiceConfig.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	validator := validators.NewServiceValidator("prometheus")

	// Use BaseServiceConfig struct
	config := &validators.BaseServiceConfig{
		Enabled:   true,
		Namespace: "prometheus-system",
		Name:      "prometheus",
	}

	result, _ := validator.Validate(context.Background(), config)

	if result.Valid {
		fmt.Println("Configuration is valid")
	}

}
Output:
Configuration is valid
Example (ServiceValidator_disabledService)

Example_serviceValidator_disabledService demonstrates validation of disabled services.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	validator := validators.NewServiceValidator("loki")

	config := map[string]interface{}{
		"enabled":   false,
		"namespace": "loki-system",
		"name":      "loki",
	}

	result, _ := validator.Validate(context.Background(), config)

	// Disabled services are still valid
	fmt.Printf("Valid: %v\n", result.Valid)

	// But they have info messages
	if len(result.Info) > 0 {
		fmt.Printf("Info: %s\n", result.Info[0].Message)
	}

}
Output:
Valid: true
Info: service 'loki' is disabled
Example (ServiceValidator_invalidNamespace)

Example_serviceValidator_invalidNamespace demonstrates namespace validation errors.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	validator := validators.NewServiceValidator("loki")

	// Invalid namespace with uppercase letters
	config := map[string]interface{}{
		"enabled":   true,
		"namespace": "Loki-System",
		"name":      "loki",
	}

	result, _ := validator.Validate(context.Background(), config)

	if !result.Valid {
		for _, e := range result.Errors {
			fmt.Printf("%s: %s\n", e.Field, e.Message)
			if len(e.Suggestions) > 0 {
				fmt.Printf("Suggestion: %s\n", e.Suggestions[0])
			}
		}
	}

}
Output:
service.namespace: invalid namespace format: Loki-System
Suggestion: Convert namespace to lowercase
Example (ServiceValidator_namingConvention)

Example_serviceValidator_namingConvention demonstrates the naming convention.

package main

import (
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	// Service validators follow the "service:{service_name}" convention
	lokiValidator := validators.NewServiceValidator("loki")
	prometheusValidator := validators.NewServiceValidator("prometheus")
	certManagerValidator := validators.NewServiceValidator("cert-manager")

	fmt.Printf("Loki validator name: %s\n", lokiValidator.Name())
	fmt.Printf("Prometheus validator name: %s\n", prometheusValidator.Name())
	fmt.Printf("Cert-manager validator name: %s\n", certManagerValidator.Name())

}
Output:
Loki validator name: service:loki
Prometheus validator name: service:prometheus
Cert-manager validator name: service:cert-manager
Example (ServiceValidator_suggestions)

Example_serviceValidator_suggestions demonstrates error suggestions.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	validator := validators.NewServiceValidator("loki")

	// Configuration with multiple errors
	config := map[string]interface{}{
		"enabled":   true,
		"namespace": "loki_system", // Underscore instead of hyphen
		"name":      "",            // Empty name
	}

	result, _ := validator.Validate(context.Background(), config)

	if !result.Valid {
		for _, e := range result.Errors {
			fmt.Printf("Error: %s\n", e.Message)
			fmt.Println("Suggestions:")
			for _, s := range e.Suggestions {
				fmt.Printf("  - %s\n", s)
			}
			fmt.Println()
		}
	}

}
Output:
Error: invalid namespace format: loki_system
Suggestions:
  - Replace underscores with hyphens
  - Namespace must contain only lowercase letters, numbers, and hyphens
  - Namespace must start and end with alphanumeric character

Error: service name is required
Suggestions:
  - Provide a name for the service
  - Example: name: loki
Example (ServiceValidator_withExtension)

Example_serviceValidator_withExtension demonstrates using an extension validator.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation"
	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	// Create base service validator
	validator := validators.NewServiceValidator("loki")

	// Create an extension validator for Loki-specific validation
	lokiValidator := validation.NewValidatorFunc("loki-storage", func(ctx context.Context, value interface{}) (*validation.ValidationResult, error) {
		result := validation.NewValidationResult()

		// Check for Loki-specific fields
		if m, ok := value.(map[string]interface{}); ok {
			if storageType, ok := m["storage_type"].(string); ok {
				if storageType != "s3" && storageType != "swift" {
					result.AddError("storage_type",
						fmt.Sprintf("invalid storage type: %s", storageType),
						"Use 's3' or 'swift' for Loki storage")
				}
			}
		}

		return result, nil
	})

	// Set the extension validator
	validator.SetExtensionValidator(lokiValidator)

	// Validate with extension
	config := map[string]interface{}{
		"enabled":      true,
		"namespace":    "loki-system",
		"name":         "loki",
		"storage_type": "invalid",
	}

	result, _ := validator.Validate(context.Background(), config)

	if !result.Valid {
		for _, e := range result.Errors {
			fmt.Printf("%s: %s\n", e.Field, e.Message)
		}
	}

}
Output:
storage_type: invalid storage type: invalid

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BaseServiceConfig

type BaseServiceConfig struct {
	Enabled   bool
	Namespace string
	Name      string
}

BaseServiceConfig is a basic implementation of ServiceConfig for testing.

func (*BaseServiceConfig) GetEnabled

func (c *BaseServiceConfig) GetEnabled() bool

GetEnabled returns the enabled status.

func (*BaseServiceConfig) GetName

func (c *BaseServiceConfig) GetName() string

GetName returns the service name.

func (*BaseServiceConfig) GetNamespace

func (c *BaseServiceConfig) GetNamespace() string

GetNamespace returns the namespace.

type ClusterNameValidator

type ClusterNameValidator struct {
	// contains filtered or unexported fields
}

ClusterNameValidator validates cluster names according to Kubernetes naming conventions.

Requirements (from Phase 2 Validation Consolidation):

  • Length: 1-63 characters
  • Character set: lowercase alphanumeric and hyphens only
  • Must not start or end with hyphen
  • Provides actionable suggestions for common mistakes

Validates: Requirements 2.1, 2.2, 2.3, 2.4, 2.10

func NewClusterNameValidator

func NewClusterNameValidator() *ClusterNameValidator

NewClusterNameValidator creates a new cluster name validator.

func (*ClusterNameValidator) Name

func (v *ClusterNameValidator) Name() string

Name returns the validator name.

func (*ClusterNameValidator) Priority

func (v *ClusterNameValidator) Priority() int

Priority returns the validator priority. Cluster name validation is fast (format check), so it has high priority.

func (*ClusterNameValidator) Validate

func (v *ClusterNameValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error)

Validate validates a cluster name according to Kubernetes naming conventions.

The validator checks:

  • Name is not empty
  • Length is between 1 and 63 characters
  • Contains only lowercase alphanumeric characters and hyphens
  • Does not start or end with a hyphen

Returns a ValidationResult with errors and actionable suggestions.

type ConfigStructureValidator

type ConfigStructureValidator struct{}

ConfigStructureValidator validates that configuration uses the canonical schema 2 field structure only.

Validates: Requirements 1.4

func NewConfigStructureValidator

func NewConfigStructureValidator() *ConfigStructureValidator

NewConfigStructureValidator creates a new configuration structure validator.

func (*ConfigStructureValidator) Name

func (v *ConfigStructureValidator) Name() string

Name returns the validator name.

func (*ConfigStructureValidator) Priority

func (v *ConfigStructureValidator) Priority() int

Priority returns the validator priority. Config structure validation is fast (format check), so it has high priority.

func (*ConfigStructureValidator) Validate

func (v *ConfigStructureValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error)

Validate validates that the configuration uses the canonical schema 2 field structure.

type ConfigValidator

type ConfigValidator struct {
	// contains filtered or unexported fields
}

ConfigValidator validates configuration values.

func NewConfigValidator

func NewConfigValidator() *ConfigValidator

NewConfigValidator creates a new configuration validator.

func (*ConfigValidator) Name

func (v *ConfigValidator) Name() string

Name returns the validator name.

func (*ConfigValidator) Priority

func (v *ConfigValidator) Priority() int

Priority returns the validator priority. Config validation involves business logic checks, so it has normal priority.

func (*ConfigValidator) Validate

func (v *ConfigValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error)

Validate validates a configuration value based on the context. The value should be a map with "type" and "value" keys.

type FileValidator

type FileValidator struct {
	// contains filtered or unexported fields
}

FileValidator validates file paths and file system operations.

func NewFileValidator

func NewFileValidator() *FileValidator

NewFileValidator creates a new file validator.

func (*FileValidator) Name

func (v *FileValidator) Name() string

Name returns the validator name.

func (*FileValidator) Priority

func (v *FileValidator) Priority() int

Priority returns the validator priority. File validation involves file I/O, so it has low priority.

func (*FileValidator) SetAllowedExtensions

func (v *FileValidator) SetAllowedExtensions(extensions []string)

SetAllowedExtensions sets the allowed file extensions.

func (*FileValidator) SetMaxPathLength

func (v *FileValidator) SetMaxPathLength(length int)

SetMaxPathLength sets the maximum allowed path length.

func (*FileValidator) Validate

func (v *FileValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error)

Validate validates a file path or file operation. The value should be a map with "operation" and "path" keys.

type GitOpsValidator

type GitOpsValidator struct {
	// contains filtered or unexported fields
}

GitOpsValidator validates GitOps repository structure and configuration.

Requirements (from Phase 2 Validation Consolidation):

  • Validates GitOps repository structure
  • Checks for required files and directories
  • Validates manifest structure
  • Provides actionable suggestions for fixing issues

Validates: Requirements 2.6, 2.10

func NewGitOpsValidator

func NewGitOpsValidator() *GitOpsValidator

NewGitOpsValidator creates a new GitOps validator.

func NewGitOpsValidatorWithFileSystem

func NewGitOpsValidatorWithFileSystem(fileSystem fs.FileSystem) *GitOpsValidator

NewGitOpsValidatorWithFileSystem creates a new GitOps validator with a custom FileSystem.

func (*GitOpsValidator) Name

func (v *GitOpsValidator) Name() string

Name returns the validator name.

func (*GitOpsValidator) Priority

func (v *GitOpsValidator) Priority() int

Priority returns the validator priority. GitOps validation involves file I/O, so it has low priority.

func (*GitOpsValidator) SetRequiredDirectories

func (v *GitOpsValidator) SetRequiredDirectories(dirs []string)

SetRequiredDirectories sets the list of required directories.

func (*GitOpsValidator) SetRequiredFiles

func (v *GitOpsValidator) SetRequiredFiles(files []string)

SetRequiredFiles sets the list of required files.

func (*GitOpsValidator) Validate

func (v *GitOpsValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error)

Validate validates GitOps configuration.

The value should be a map with the following keys:

  • "git_dir": Path to the GitOps repository directory
  • "git_url": URL of the GitOps repository (optional)
  • "gitops_base_repo": URL of the GitOps base repository (optional)

Returns a ValidationResult with errors and actionable suggestions.

type NetworkConfig

type NetworkConfig struct {
	SubnetNodes    string
	SubnetPods     string
	SubnetServices string
	DNSNameservers []string
	VRRPEnabled    bool
	VRRPIP         string
	VIPInterface   string
}

NetworkConfig represents network configuration for validation. This is a simplified version to avoid import cycles with internal/config.

Note: This type mirrors the fields from internal/config.Networking that are relevant for network validation. When using this validator with actual config objects, you'll need to convert the config.Networking to NetworkConfig.

Example conversion:

networkConfig := &validators.NetworkConfig{
    SubnetNodes:    cfg.Networking.SubnetNodes,
    SubnetPods:     cfg.Networking.SubnetPods,
    SubnetServices: cfg.Networking.SubnetServices,
    DNSNameservers: cfg.Networking.DNSNameservers,
    VRRPEnabled:    cfg.Networking.VRRPEnabled,
    VRRPIP:         cfg.Networking.VRRPIP,
    VIPInterface:   cfg.Networking.VIPInterface,
}

type NetworkValidator

type NetworkValidator struct{}

NetworkValidator validates network configuration including CIDR ranges and IP addresses.

Requirements (from Phase 2 Validation Consolidation):

  • Validate CIDR format for pod and service networks
  • Check for CIDR overlap between pod and service networks
  • Validate DNS server IP addresses
  • Provide network configuration suggestions

Validates: Requirements 2.5, 2.10

Example

ExampleNetworkValidator demonstrates how to use the NetworkValidator.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation"
	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	// Create validation engine
	engine := validation.NewValidationEngine()

	// Register network validator
	networkValidator := validators.NewNetworkValidator()
	engine.MustRegister(networkValidator)

	// Create network configuration
	networkConfig := &validators.NetworkConfig{
		SubnetPods:     "10.244.0.0/16",
		SubnetServices: "10.96.0.0/12",
		DNSNameservers: []string{"8.8.8.8", "8.8.4.4"},
	}

	// Validate the configuration
	result, err := engine.Validate(context.Background(), "network", networkConfig)
	if err != nil {
		fmt.Printf("Validation error: %v\n", err)
		return
	}

	// Check validation result
	if result.Valid {
		fmt.Println("Network configuration is valid")
	} else {
		fmt.Println("Network configuration has errors:")
		for _, e := range result.Errors {
			fmt.Printf("  - %s: %s\n", e.Field, e.Message)
		}
	}

}
Output:
Network configuration is valid
Example (InvalidConfiguration)

ExampleNetworkValidator_invalidConfiguration demonstrates validation with errors.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	// Create validator
	validator := validators.NewNetworkValidator()

	// Create invalid configuration (overlapping CIDRs)
	networkConfig := &validators.NetworkConfig{
		SubnetPods:     "10.96.1.0/24", // Overlaps with service CIDR
		SubnetServices: "10.96.0.0/12", // Contains pod CIDR
		DNSNameservers: []string{"invalid-ip"},
	}

	// Validate
	result, _ := validator.Validate(context.Background(), networkConfig)

	// Display errors
	fmt.Printf("Valid: %v\n", result.Valid)
	fmt.Printf("Errors: %d\n", len(result.Errors))

}
Output:
Valid: false
Errors: 2
Example (Suggestions)

ExampleNetworkValidator_suggestions demonstrates error suggestions.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	validator := validators.NewNetworkValidator()

	// Invalid CIDR format
	networkConfig := &validators.NetworkConfig{
		SubnetPods: "10.244.0.0", // Missing prefix length
	}

	result, _ := validator.Validate(context.Background(), networkConfig)

	if !result.Valid && len(result.Errors) > 0 {
		fmt.Println("Error:", result.Errors[0].Message)
		fmt.Println("Suggestions:")
		for _, s := range result.Errors[0].Suggestions {
			fmt.Printf("  - %s\n", s)
		}
	}

}
Output:
Error: invalid CIDR format: 10.244.0.0
Suggestions:
  - Use CIDR notation: <ip>/<prefix>
  - Example: 10.244.0.0/16 or 2001:db8::/32
  - Ensure the IP address and prefix length are valid

func NewNetworkValidator

func NewNetworkValidator() *NetworkValidator

NewNetworkValidator creates a new network validator.

func (*NetworkValidator) Name

func (v *NetworkValidator) Name() string

Name returns the validator name.

func (*NetworkValidator) Priority

func (v *NetworkValidator) Priority() int

Priority returns the validator priority. Network validation involves CIDR parsing and overlap checks, which are moderately complex, so it has normal priority.

func (*NetworkValidator) Validate

func (v *NetworkValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error)

Validate validates network configuration including CIDR ranges and IP addresses.

The validator checks:

  • Pod CIDR format (if specified)
  • Service CIDR format (if specified)
  • CIDR overlap between pod and service networks
  • DNS server IP address validity

Returns a ValidationResult with errors and actionable suggestions.

type OpenTofuValidator

type OpenTofuValidator struct{}

OpenTofuValidator validates OpenTofu backend configuration.

func NewOpenTofuValidator

func NewOpenTofuValidator() *OpenTofuValidator

NewOpenTofuValidator creates a new OpenTofu validator.

func (*OpenTofuValidator) Name

func (v *OpenTofuValidator) Name() string

Name returns the validator name.

func (*OpenTofuValidator) Priority

func (v *OpenTofuValidator) Priority() int

Priority returns the validator priority.

func (*OpenTofuValidator) Validate

func (v *OpenTofuValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error)

Validate validates OpenTofu backend configuration.

type OrganizationNameValidator

type OrganizationNameValidator struct {
	// contains filtered or unexported fields
}

OrganizationNameValidator validates organization names using the same rules as cluster names.

func NewOrganizationNameValidator

func NewOrganizationNameValidator() *OrganizationNameValidator

NewOrganizationNameValidator creates a new organization name validator.

func (*OrganizationNameValidator) Name

Name returns the validator name.

func (*OrganizationNameValidator) Priority

func (v *OrganizationNameValidator) Priority() int

Priority returns the validator priority. Organization name validation is fast (format check), so it has high priority.

func (*OrganizationNameValidator) Validate

func (v *OrganizationNameValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error)

Validate validates an organization name.

type ProviderValidator

type ProviderValidator struct {
	// contains filtered or unexported fields
}

ProviderValidator validates cloud provider configurations.

Requirements (from Phase 2 Validation Consolidation):

  • Validates provider-specific configuration
  • Checks required fields for each provider
  • Validates credentials format
  • Provides actionable suggestions for fixing issues

Validates: Requirements 2.8, 2.10

func NewProviderValidator

func NewProviderValidator() *ProviderValidator

NewProviderValidator creates a new provider validator.

func (*ProviderValidator) Name

func (v *ProviderValidator) Name() string

Name returns the validator name.

func (*ProviderValidator) Priority

func (v *ProviderValidator) Priority() int

Priority returns the validator priority. Provider validation involves business logic checks, so it has normal priority.

func (*ProviderValidator) SetSupportedProviders

func (v *ProviderValidator) SetSupportedProviders(providers []string)

SetSupportedProviders sets the list of supported providers.

func (*ProviderValidator) Validate

func (v *ProviderValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error)

Validate validates cloud provider configuration.

The value should be a map with the following keys:

  • "provider": Provider name (required)
  • "config": Provider-specific configuration (required)

Returns a ValidationResult with errors and actionable suggestions.

type SOPSKeyValidator

type SOPSKeyValidator struct {
	// contains filtered or unexported fields
}

SOPSKeyValidator validates SOPS encryption keys.

This validator checks:

  • Key file exists and is readable
  • Age key format (starts with "AGE-SECRET-KEY-")
  • File permissions (warns if not 0600)

Example usage:

validator := validators.NewSOPSKeyValidator(fileSystem)
result, err := validator.Validate(ctx, "/path/to/key.txt")
Example

ExampleSOPSKeyValidator demonstrates basic SOPS key validation.

package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
	"github.com/opencenter-cloud/opencenter-cli/internal/util/errors"
	"github.com/opencenter-cloud/opencenter-cli/internal/util/fs"
)

func main() {
	// Create a temporary directory for testing
	tmpDir, err := os.MkdirTemp("", "sops-example-*")
	if err != nil {
		fmt.Printf("Error creating temp dir: %v\n", err)
		return
	}
	defer os.RemoveAll(tmpDir)

	// Create a valid Age key file
	keyPath := filepath.Join(tmpDir, "age-key.txt")
	validKey := "AGE-SECRET-KEY-1ZYXWVUTSRQPONMLKJIHGFEDCBA9876543210ZYXWVUTSRQPONMLKJIHGFE"
	if err := os.WriteFile(keyPath, []byte(validKey), 0600); err != nil {
		fmt.Printf("Error writing key file: %v\n", err)
		return
	}

	// Create validator
	errorHandler := errors.NewDefaultErrorHandlerWithoutMasking()
	fileSystem := fs.NewDefaultFileSystem(errorHandler)
	validator := validators.NewSOPSKeyValidator(fileSystem)

	// Validate the key
	result, err := validator.Validate(context.Background(), keyPath)
	if err != nil {
		fmt.Printf("Validation error: %v\n", err)
		return
	}

	if result.Valid {
		fmt.Println("SOPS key is valid")
	} else {
		fmt.Println("SOPS key validation failed")
		for _, e := range result.Errors {
			fmt.Printf("Error: %s\n", e.Message)
		}
	}

}
Output:
SOPS key is valid
Example (InsecurePermissions)

ExampleSOPSKeyValidator_insecurePermissions demonstrates validation with insecure permissions.

package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
	"github.com/opencenter-cloud/opencenter-cli/internal/util/errors"
	"github.com/opencenter-cloud/opencenter-cli/internal/util/fs"
)

func main() {
	// Create a temporary directory for testing
	tmpDir, err := os.MkdirTemp("", "sops-example-*")
	if err != nil {
		fmt.Printf("Error creating temp dir: %v\n", err)
		return
	}
	defer os.RemoveAll(tmpDir)

	// Create a valid key file with insecure permissions
	keyPath := filepath.Join(tmpDir, "age-key.txt")
	validKey := "AGE-SECRET-KEY-1ZYXWVUTSRQPONMLKJIHGFEDCBA9876543210ZYXWVUTSRQPONMLKJIHGFE"
	if err := os.WriteFile(keyPath, []byte(validKey), 0644); err != nil {
		fmt.Printf("Error writing key file: %v\n", err)
		return
	}

	// Create validator
	errorHandler := errors.NewDefaultErrorHandlerWithoutMasking()
	fileSystem := fs.NewDefaultFileSystem(errorHandler)
	validator := validators.NewSOPSKeyValidator(fileSystem)

	// Validate the key
	result, err := validator.Validate(context.Background(), keyPath)
	if err != nil {
		fmt.Printf("Validation error: %v\n", err)
		return
	}

	if result.Valid {
		fmt.Println("Key format is valid")
	}

	if result.HasWarnings() {
		fmt.Println("Warnings:")
		for _, w := range result.Warnings {
			fmt.Printf("  %s\n", w.Message)
		}
	}

}
Output:
Key format is valid
Warnings:
  insecure key file permissions: 644 (should be 0600)
Example (InvalidFormat)

ExampleSOPSKeyValidator_invalidFormat demonstrates validation of an invalid key format.

package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
	"github.com/opencenter-cloud/opencenter-cli/internal/util/errors"
	"github.com/opencenter-cloud/opencenter-cli/internal/util/fs"
)

func main() {
	// Create a temporary directory for testing
	tmpDir, err := os.MkdirTemp("", "sops-example-*")
	if err != nil {
		fmt.Printf("Error creating temp dir: %v\n", err)
		return
	}
	defer os.RemoveAll(tmpDir)

	// Create an invalid key file
	keyPath := filepath.Join(tmpDir, "invalid-key.txt")
	invalidKey := "INVALID-KEY-FORMAT"
	if err := os.WriteFile(keyPath, []byte(invalidKey), 0600); err != nil {
		fmt.Printf("Error writing key file: %v\n", err)
		return
	}

	// Create validator
	errorHandler := errors.NewDefaultErrorHandlerWithoutMasking()
	fileSystem := fs.NewDefaultFileSystem(errorHandler)
	validator := validators.NewSOPSKeyValidator(fileSystem)

	// Validate the key
	result, err := validator.Validate(context.Background(), keyPath)
	if err != nil {
		fmt.Printf("Validation error: %v\n", err)
		return
	}

	if !result.Valid {
		fmt.Println("Validation failed:")
		for _, e := range result.Errors {
			fmt.Printf("  %s\n", e.Message)
		}
	}

}
Output:
Validation failed:
  invalid Age key format
Example (MissingFile)

ExampleSOPSKeyValidator_missingFile demonstrates validation of a missing key file.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
	"github.com/opencenter-cloud/opencenter-cli/internal/util/errors"
	"github.com/opencenter-cloud/opencenter-cli/internal/util/fs"
)

func main() {
	// Create validator
	errorHandler := errors.NewDefaultErrorHandlerWithoutMasking()
	fileSystem := fs.NewDefaultFileSystem(errorHandler)
	validator := validators.NewSOPSKeyValidator(fileSystem)

	// Validate a non-existent key file
	result, err := validator.Validate(context.Background(), "/nonexistent/key.txt")
	if err != nil {
		fmt.Printf("Validation error: %v\n", err)
		return
	}

	if !result.Valid {
		fmt.Println("Validation failed:")
		for _, e := range result.Errors {
			fmt.Printf("  %s\n", e.Message)
			if len(e.Suggestions) > 0 {
				fmt.Println("  Suggestions:")
				for _, s := range e.Suggestions {
					fmt.Printf("    - %s\n", s)
				}
			}
		}
	}

}
Output:
Validation failed:
  SOPS key file not found: /nonexistent/key.txt
  Suggestions:
    - Generate a new Age key: age-keygen -o /nonexistent/key.txt
    - Or use: opencenter secrets keys generate
    - Verify the file path is correct
Example (WithEngine)

ExampleSOPSKeyValidator_withEngine demonstrates using the validator with ValidationEngine.

package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation"
	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
	"github.com/opencenter-cloud/opencenter-cli/internal/util/errors"
	"github.com/opencenter-cloud/opencenter-cli/internal/util/fs"
)

func main() {
	// Create a temporary directory for testing
	tmpDir, err := os.MkdirTemp("", "sops-example-*")
	if err != nil {
		fmt.Printf("Error creating temp dir: %v\n", err)
		return
	}
	defer os.RemoveAll(tmpDir)

	// Create a valid Age key file
	keyPath := filepath.Join(tmpDir, "age-key.txt")
	validKey := "AGE-SECRET-KEY-1ZYXWVUTSRQPONMLKJIHGFEDCBA9876543210ZYXWVUTSRQPONMLKJIHGFE"
	if err := os.WriteFile(keyPath, []byte(validKey), 0600); err != nil {
		fmt.Printf("Error writing key file: %v\n", err)
		return
	}

	// Create validation engine
	engine := validation.NewValidationEngine()

	// Register SOPS key validator
	errorHandler := errors.NewDefaultErrorHandlerWithoutMasking()
	fileSystem := fs.NewDefaultFileSystem(errorHandler)
	validator := validators.NewSOPSKeyValidator(fileSystem)
	if err := engine.Register(validator); err != nil {
		fmt.Printf("Registration error: %v\n", err)
		return
	}

	// Validate using the engine
	result, err := engine.Validate(context.Background(), "sops-key", keyPath)
	if err != nil {
		fmt.Printf("Validation error: %v\n", err)
		return
	}

	if result.Valid {
		fmt.Println("SOPS key validation passed")
	}

}
Output:
SOPS key validation passed

func NewSOPSKeyValidator

func NewSOPSKeyValidator(fileSystem fs.FileSystem) *SOPSKeyValidator

NewSOPSKeyValidator creates a new SOPS key validator.

Parameters:

  • fileSystem: FileSystem implementation for file operations

Returns:

  • *SOPSKeyValidator: New validator instance

func (*SOPSKeyValidator) Name

func (v *SOPSKeyValidator) Name() string

Name returns the validator name.

func (*SOPSKeyValidator) Priority

func (v *SOPSKeyValidator) Priority() int

Priority returns the validator priority. SOPS key validation involves file I/O, so it has low priority.

func (*SOPSKeyValidator) Validate

func (v *SOPSKeyValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error)

Validate validates a SOPS key file.

The value parameter should be a string containing the path to the key file.

Validation checks:

  1. File exists
  2. File is readable
  3. Key format is valid (starts with "AGE-SECRET-KEY-")
  4. File permissions are secure (warns if not 0600)

Parameters:

  • ctx: Context for cancellation
  • value: Key file path (string)

Returns:

  • *ValidationResult: Validation result with errors/warnings
  • error: Execution error (not validation failure)

type SecurityValidator

type SecurityValidator struct {
	// contains filtered or unexported fields
}

SecurityValidator validates security-related inputs.

Example (CommandInjection)

ExampleSecurityValidator_commandInjection demonstrates command injection detection.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	validator := validators.NewSecurityValidator()
	ctx := context.Background()

	// Attempt to validate input with command injection
	result, _ := validator.Validate(ctx, map[string]interface{}{
		"type":  "shell-input",
		"value": "cluster; rm -rf /",
	})

	fmt.Printf("Valid: %v\n", result.Valid)
	if len(result.Errors) > 0 {
		fmt.Printf("Error detected: dangerous shell metacharacter\n")
	}

}
Output:
Valid: false
Error detected: dangerous shell metacharacter
Example (PathTraversal)

ExampleSecurityValidator_pathTraversal demonstrates path traversal detection.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	validator := validators.NewSecurityValidator()
	ctx := context.Background()

	// Attempt to validate input with path traversal
	result, _ := validator.Validate(ctx, map[string]interface{}{
		"type":  "shell-input",
		"value": "../../../etc/passwd",
	})

	fmt.Printf("Valid: %v\n", result.Valid)
	if len(result.Errors) > 0 {
		fmt.Printf("Error detected: contains path traversal pattern\n")
	}

}
Output:
Valid: false
Error detected: contains path traversal pattern
Example (SafeInput)

ExampleSecurityValidator_safeInput demonstrates validation of safe input.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	validator := validators.NewSecurityValidator()
	ctx := context.Background()

	// Validate safe input
	result, _ := validator.Validate(ctx, map[string]interface{}{
		"type":  "shell-input",
		"value": "my-cluster-01",
	})

	fmt.Printf("Valid: %v\n", result.Valid)
	fmt.Printf("Errors: %d\n", len(result.Errors))

}
Output:
Valid: true
Errors: 0
Example (WithAuditLogging)

ExampleSecurityValidator_withAuditLogging demonstrates audit logging integration.

package main

import (
	"context"
	"fmt"

	"github.com/opencenter-cloud/opencenter-cli/internal/core/validation/validators"
)

func main() {
	validator := validators.NewSecurityValidator()
	ctx := context.Background()

	// Mock audit logger that prints violations
	mockLogger := &mockAuditLogger{
		logFunc: func(ctx context.Context, actor, inputType, reason string) error {
			fmt.Printf("Audit log: actor=%s, type=%s\n", actor, inputType)
			return nil
		},
	}

	validator.SetAuditLogger(mockLogger)
	validator.SetActor("admin-user")

	// Validate malicious input - will be logged
	result, _ := validator.Validate(ctx, map[string]interface{}{
		"type":  "command",
		"value": "echo $(whoami)",
	})

	fmt.Printf("Valid: %v\n", result.Valid)

}

// mockAuditLogger is a mock implementation for examples
type mockAuditLogger struct {
	logFunc func(ctx context.Context, actor, inputType, reason string) error
}

func (m *mockAuditLogger) LogInputRejected(ctx context.Context, actor, inputType, reason string) error {
	if m.logFunc != nil {
		return m.logFunc(ctx, actor, inputType, reason)
	}
	return nil
}
Output:
Audit log: actor=admin-user, type=command
Valid: false

func NewSecurityValidator

func NewSecurityValidator() *SecurityValidator

NewSecurityValidator creates a new security validator.

func (*SecurityValidator) AddDangerousPattern

func (v *SecurityValidator) AddDangerousPattern(pattern *regexp.Regexp)

AddDangerousPattern adds a dangerous pattern to check for.

func (*SecurityValidator) Name

func (v *SecurityValidator) Name() string

Name returns the validator name.

func (*SecurityValidator) Priority

func (v *SecurityValidator) Priority() int

Priority returns the validator priority. Security validation is fast (pattern matching), so it has high priority. This ensures security checks run early in the validation pipeline.

func (*SecurityValidator) SetActor

func (v *SecurityValidator) SetActor(actor string)

SetActor sets the actor (user/system) performing the validation.

func (*SecurityValidator) SetAuditLogger

func (v *SecurityValidator) SetAuditLogger(logger interface{})

SetAuditLogger sets the audit logger for logging security violations.

func (*SecurityValidator) SetSafeEditors

func (v *SecurityValidator) SetSafeEditors(editors []string)

SetSafeEditors sets the list of safe editors.

func (*SecurityValidator) Validate

func (v *SecurityValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error)

Validate validates security-related inputs. The value should be a map with "type" and "value" keys.

type ServiceConfig

type ServiceConfig interface {
	GetEnabled() bool
	GetNamespace() string
	GetName() string
}

ServiceConfig represents the common service configuration fields. This is a minimal interface that service configurations must satisfy.

type ServiceValidator

type ServiceValidator struct {
	// contains filtered or unexported fields
}

ServiceValidator validates service configurations.

The validator checks:

  • Common service fields (name, namespace, enabled)
  • Service-specific validation via extension validators
  • Naming conventions and format requirements

Naming Convention:

  • Base validator: "service"
  • Service-specific: "service:{service_name}" (e.g., "service:loki", "service:prometheus")

Example usage:

validator := validators.NewServiceValidator("loki")
result, err := validator.Validate(ctx, serviceConfig)

func NewServiceValidator

func NewServiceValidator(serviceName string) *ServiceValidator

NewServiceValidator creates a new service validator.

Parameters:

  • serviceName: Name of the service (e.g., "loki", "prometheus", "cert-manager")

Returns:

  • *ServiceValidator: New service validator instance

Example:

validator := validators.NewServiceValidator("loki")

func (*ServiceValidator) Name

func (v *ServiceValidator) Name() string

Name returns the validator name following the "service:{service_name}" convention.

Returns:

  • string: Validator name (e.g., "service:loki", "service:prometheus")

func (*ServiceValidator) Priority

func (v *ServiceValidator) Priority() int

Priority returns the validator priority. Service validation involves business logic checks, so it has normal priority.

func (*ServiceValidator) SetExtensionValidator

func (v *ServiceValidator) SetExtensionValidator(validator validation.Validator)

SetExtensionValidator sets a service-specific extension validator.

Extension validators can provide additional validation logic specific to a particular service type (e.g., Loki storage validation, Prometheus retention).

Parameters:

  • validator: Service-specific validator (nil to remove)

Example:

lokiValidator := NewLokiStorageValidator()
serviceValidator.SetExtensionValidator(lokiValidator)

func (*ServiceValidator) Validate

func (v *ServiceValidator) Validate(ctx context.Context, value interface{}) (*validation.ValidationResult, error)

Validate validates a service configuration.

The value should be one of:

  • A map with "enabled", "namespace", and "name" keys
  • A struct implementing ServiceConfig interface
  • A struct with Enabled, Namespace, and Name fields

Parameters:

  • ctx: Context for cancellation and metadata
  • value: Service configuration to validate

Returns:

  • *ValidationResult: Validation result with errors/warnings
  • error: Execution error (not validation failure)

Example:

config := map[string]interface{}{
    "enabled": true,
    "namespace": "loki-system",
    "name": "loki",
}
result, err := validator.Validate(ctx, config)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL