security

package
v0.0.0-...-cf3d621 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2025 License: Apache-2.0 Imports: 11 Imported by: 0

README

Security Module for nFlow Runtime

This module provides transparent security features for nFlow Runtime without modifying the core engine. It includes static analysis of JavaScript code and automatic encryption of sensitive data.

Features

1. Static Code Analysis
  • Detects dangerous patterns in JavaScript before execution
  • Configurable severity levels (high, medium, low)
  • Can block execution based on security policies
  • Patterns detected:
    • eval() and Function() constructor usage
    • File system access attempts
    • Process spawning attempts
    • Network access
    • Infinite loops
    • Global scope modifications
    • Potentially dangerous regex patterns
2. Data Encryption
  • AES-256-GCM encryption for sensitive data
  • Automatic detection of sensitive information
  • Two modes:
    • In-place encryption: Replaces sensitive values directly
    • Metadata mode: Adds encryption metadata without modifying structure
  • Built-in patterns for:
    • Email addresses
    • Phone numbers
    • Social Security Numbers (SSN)
    • Credit card numbers
    • API keys and tokens
    • JWT tokens
  • Support for custom patterns
3. Performance Optimizations
  • Thread-safe implementation
  • Buffer pooling for encryption
  • Concurrent operation support
  • Minimal overhead when disabled

Configuration

Add to your config.toml:

[security]
# Static Analysis
enable_static_analysis = true
block_on_high_severity = true
log_security_warnings = true

# Encryption
enable_encryption = true
encryption_key = "your-32-byte-key-here"
encrypt_sensitive_data = true
encrypt_in_place = true

# Always encrypt these fields
always_encrypt_fields = ["password", "token", "secret"]

# Custom patterns
[security.custom_patterns]
employee_id = "EMP\\d{6}"

Usage

Basic Integration
// Create security middleware
config := &security.Config{
    EnableStaticAnalysis: true,
    EnableEncryption: true,
    EncryptionKey: "your-secure-key",
}

sm, err := security.NewSecurityMiddleware(config)
if err != nil {
    log.Fatal(err)
}

// Analyze JavaScript before execution
err = sm.AnalyzeScript(jsCode, "script-id")
if err != nil {
    // Script blocked due to security issues
    return err
}

// Process response data
secureData, err := sm.ProcessResponse(responseData)
if err != nil {
    return err
}
Generating Encryption Keys
// Generate a secure key
key, err := encryption.GenerateKeyString()
if err != nil {
    log.Fatal(err)
}
fmt.Println("Add this to config.toml:", key)

Performance

Benchmark results on MacBook Pro M1:

BenchmarkAnalyzer_SafeScript-8          50000    25483 ns/op
BenchmarkAnalyzer_DangerousScript-8     30000    45632 ns/op
BenchmarkEncryption_Small-8            300000     4521 ns/op
BenchmarkEncryption_Large-8             10000   125634 ns/op
BenchmarkInterceptor_MediumData-8       20000    65432 ns/op

Security Considerations

  1. Encryption Keys:

    • Store encryption keys securely (use environment variables or key management systems)
    • Rotate keys periodically
    • Never commit keys to version control
  2. False Positives:

    • Use allowed_patterns to whitelist safe patterns
    • Adjust severity levels based on your security requirements
  3. Performance:

    • Enable only the features you need
    • Use caching for static analysis results
    • Consider using metadata mode for large responses

Testing

Run all tests:

go test ./security/...

Run benchmarks:

go test -bench=. ./security/...

Run with race detection:

go test -race ./security/...

Contributing

When adding new features:

  1. Maintain backward compatibility
  2. Add comprehensive tests
  3. Include benchmarks for performance-critical code
  4. Update documentation
  5. Ensure thread-safety

License

Same as nFlow Runtime (MIT)

Documentation

Overview

Package security provides a unified middleware layer for all security features. This integrates static analysis and data encryption transparently with the engine.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Static Analysis
	EnableStaticAnalysis bool     `toml:"enable_static_analysis"`
	BlockOnHighSeverity  bool     `toml:"block_on_high_severity"`
	LogSecurityWarnings  bool     `toml:"log_security_warnings"`
	AllowedPatterns      []string `toml:"allowed_patterns"` // Patterns to whitelist

	// Encryption
	EnableEncryption     bool              `toml:"enable_encryption"`
	EncryptionKey        string            `toml:"encryption_key"`
	EncryptSensitiveData bool              `toml:"encrypt_sensitive_data"`
	EncryptInPlace       bool              `toml:"encrypt_in_place"`
	SensitivePatterns    []string          `toml:"sensitive_patterns"`
	AlwaysEncryptFields  []string          `toml:"always_encrypt_fields"`
	CustomPatterns       map[string]string `toml:"custom_patterns"`

	// Log Sanitization
	EnableLogSanitization bool              `toml:"enable_log_sanitization"`
	LogMaskingChar        string            `toml:"log_masking_char"`
	LogPreserveLength     bool              `toml:"log_preserve_length"`
	LogShowType           bool              `toml:"log_show_type"`
	LogCustomPatterns     map[string]string `toml:"log_custom_patterns"`

	// Performance
	CacheAnalysisResults bool          `toml:"cache_analysis_results"`
	CacheTTL             time.Duration `toml:"cache_ttl"`
}

Config holds all security configuration

type ScriptAnalysisResult

type ScriptAnalysisResult struct {
	Issues    []analyzer.SecurityIssue
	Timestamp time.Time
}

ScriptAnalysisResult caches analysis results

type SecurityMetrics

type SecurityMetrics struct {
	ScriptsAnalyzed      uint64
	ScriptsBlocked       uint64
	HighSeverityIssues   uint64
	MediumSeverityIssues uint64
	LowSeverityIssues    uint64
	DataEncrypted        uint64
	LogsProcessed        uint64
	LogsSanitized        uint64
	AnalysisTime         time.Duration
	EncryptionTime       time.Duration
}

SecurityMetrics tracks security-related metrics

type SecurityMiddleware

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

SecurityMiddleware provides unified security features for nFlow Runtime

func NewSecurityMiddleware

func NewSecurityMiddleware(config *Config) (*SecurityMiddleware, error)

NewSecurityMiddleware creates a new security middleware instance

func (*SecurityMiddleware) AnalyzeScript

func (sm *SecurityMiddleware) AnalyzeScript(script string, scriptID string) error

AnalyzeScript performs static analysis on JavaScript code before execution

func (*SecurityMiddleware) DecryptField

func (sm *SecurityMiddleware) DecryptField(value string) (string, error)

DecryptField decrypts a specific field value

func (*SecurityMiddleware) EncryptField

func (sm *SecurityMiddleware) EncryptField(fieldName string, value string) (string, error)

EncryptField encrypts a specific field value

func (*SecurityMiddleware) GetMetrics

func (sm *SecurityMiddleware) GetMetrics() SecurityMetrics

GetMetrics returns current security metrics

func (*SecurityMiddleware) IsEnabled

func (sm *SecurityMiddleware) IsEnabled() bool

IsEnabled returns whether security features are enabled

func (*SecurityMiddleware) MarshalMetricsJSON

func (sm *SecurityMiddleware) MarshalMetricsJSON() ([]byte, error)

MarshalMetricsJSON returns metrics as JSON

func (*SecurityMiddleware) ProcessResponse

func (sm *SecurityMiddleware) ProcessResponse(data interface{}) (interface{}, error)

ProcessResponse encrypts sensitive data in responses

func (*SecurityMiddleware) ResetMetrics

func (sm *SecurityMiddleware) ResetMetrics()

ResetMetrics resets all security metrics

func (*SecurityMiddleware) SanitizeLog

func (sm *SecurityMiddleware) SanitizeLog(logMessage string) string

SanitizeLog sanitizes a log message to remove sensitive data

func (*SecurityMiddleware) SanitizeLogs

func (sm *SecurityMiddleware) SanitizeLogs(logMessages []string) []string

SanitizeLogs sanitizes multiple log messages

func (*SecurityMiddleware) SetEnabled

func (sm *SecurityMiddleware) SetEnabled(analysis, encryption bool)

SetEnabled enables or disables security features

func (*SecurityMiddleware) WrapEchoHandler

func (sm *SecurityMiddleware) WrapEchoHandler(next echo.HandlerFunc) echo.HandlerFunc

WrapEchoHandler wraps an Echo handler with security features

func (*SecurityMiddleware) WrapGojaVM

func (sm *SecurityMiddleware) WrapGojaVM(vm *goja.Runtime, scriptID string) error

WrapGojaVM wraps a Goja VM to add security hooks

Directories

Path Synopsis
Package analyzer provides static analysis capabilities for JavaScript code to detect potentially dangerous patterns before execution.
Package analyzer provides static analysis capabilities for JavaScript code to detect potentially dangerous patterns before execution.
Package encryption provides AES-256-GCM encryption for sensitive data.
Package encryption provides AES-256-GCM encryption for sensitive data.
Package interceptor provides automatic detection and encryption of sensitive data in workflow responses.
Package interceptor provides automatic detection and encryption of sensitive data in workflow responses.
Package sanitizer provides log sanitization capabilities to prevent sensitive data exposure in logs.
Package sanitizer provides log sanitization capabilities to prevent sensitive data exposure in logs.

Jump to

Keyboard shortcuts

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