# Security Policy

## Supported Versions

We provide security updates for the following versions of go-jdenticon:

| Version | Supported          |
| ------- | ------------------ |
| 1.2.x   | :white_check_mark: |
| 1.1.x   | :white_check_mark: |
| 1.0.x   | :x: (EOL)          |
| < 1.0   | :x: (Pre-release)  |

## Reporting a Vulnerability

**Please do NOT report security vulnerabilities through public GitHub issues.**

If you discover a security vulnerability in go-jdenticon, please report it to us responsibly:

### Preferred Method: GitHub Private Vulnerability Reporting

1. Go to the [Security tab](../../security) of this repository
2. Click "Report a vulnerability" 
3. Fill out the vulnerability report form with as much detail as possible

### Alternative Method: Email

If GitHub private reporting is not available, you can email the maintainer at:
**kev@kev.codes**

### What to Include

Please include the following information in your report:

- **Description**: Clear description of the vulnerability
- **Version**: Affected version(s) of go-jdenticon
- **Component**: Which part of the library is affected (core API, CLI tool, specific renderer, etc.)
- **Impact**: Your assessment of the potential impact and severity
- **Reproduction**: Step-by-step instructions to reproduce the issue
- **Proof of Concept**: If applicable, minimal code example demonstrating the vulnerability
- **Suggested Fix**: If you have ideas for how to address the issue

### Our Commitment

- **Initial Response**: We will acknowledge your report within **48 hours**
- **Progress Updates**: We will provide status updates every **7 days** until resolution
- **Verification**: We will work with you to understand and verify the issue
- **Timeline**: We aim to release security patches within **30 days** for critical issues, **90 days** for lower severity issues
- **Credit**: We will credit you in our security advisory unless you prefer to remain anonymous

### Disclosure Timeline

We follow responsible disclosure practices:

1. **Day 0**: Vulnerability reported privately
2. **Days 1-7**: Initial triage and verification
3. **Days 8-30**: Development and testing of fix (for critical issues)
4. **Day of Release**: Security advisory published with fixed version
5. **30 days post-release**: Full technical details may be shared publicly

### Scope

This security policy covers:

- **Core Library**: The main go-jdenticon Go API (`jdenticon` package)
- **CLI Tool**: The command-line interface (`cmd/jdenticon`)
- **Internal Components**: Engine, renderers, and utilities
- **Documentation**: If documentation could lead users to implement insecure patterns

### Out of Scope

The following are generally considered out of scope:

- Vulnerabilities in third-party dependencies (please report these upstream)
- Issues that require physical access to the system
- Social engineering attacks
- Issues in example code that is clearly marked as "example only"

---

## Security Guide

### Overview

The go-jdenticon library generates deterministic identicons (geometric avatar images) from input strings. This guide provides comprehensive security information for developers, operators, and security teams integrating or deploying the library.

**⚠️ Important**: This library is designed for generating visual representations of data, **not for cryptographic or authentication purposes**. The output should never be used for security-critical decisions.

### Security Features

go-jdenticon includes several built-in security protections:

- **Resource Limits**: Configurable limits on input size, icon size, and complexity
- **Input Validation**: Comprehensive validation of all user inputs
- **Path Traversal Protection**: CLI tool prevents writing files outside intended directories  
- **Memory Protection**: Built-in protections against memory exhaustion attacks
- **Defense in Depth**: Multiple layers of validation throughout the system

### Threat Model

#### Primary Security Concerns

The main security risks for an identicon generation library are related to **resource availability** rather than data confidentiality:

##### 1. Denial of Service (DoS) Attacks
- **CPU Exhaustion**: Malicious inputs designed to consume excessive processing time
- **Memory Exhaustion**: Requests for extremely large images that exhaust available memory  
- **Disk Exhaustion**: (CLI only) Repeated generation of large files filling storage

##### 2. Input Validation Vulnerabilities
- **Malformed Inputs**: Invalid color strings, non-UTF8 characters, or edge cases in parsers
- **Path Traversal**: (CLI only) Attempts to write files outside intended directories

##### 3. Resource Consumption Attacks
- **Large Input Strings**: Extremely long input strings that consume CPU during processing
- **Complex Generation**: Inputs that trigger computationally expensive generation paths

#### Built-in Protections

go-jdenticon includes comprehensive protections against these threats:

- ✅ **Configurable Resource Limits**: Input size, image dimensions, and complexity limits
- ✅ **Robust Input Validation**: All inputs are validated before processing
- ✅ **Path Traversal Protection**: CLI tool sanitizes output paths
- ✅ **Memory Bounds Checking**: Internal limits prevent memory exhaustion
- ✅ **Defense in Depth**: Multiple validation layers throughout the system

## Secure Usage Guidelines

### For Go API Consumers

#### 1. Treat All Inputs as Untrusted

**Always validate and sanitize user-provided data** before passing it to the library:

```go
// ❌ DANGEROUS: Direct use of user input
userInput := getUserInput() // Could be malicious
icon, err := jdenticon.Generate(ctx, userInput, 256)

// ✅ SECURE: Validate and sanitize first
userInput := strings.TrimSpace(getUserInput())
if len(userInput) > 100 { // Your application limit
    return errors.New("input too long")
}
if !isValidInput(userInput) { // Your validation logic
    return errors.New("invalid input")
}
icon, err := jdenticon.Generate(ctx, userInput, 256)
```

#### 2. Never Use Sensitive Data as Input

**Do not use PII, passwords, or secrets** as identicon input:

```go
// ❌ DANGEROUS: Using sensitive data
email := "user@example.com"
password := "secret123"
icon, _ := jdenticon.Generate(ctx, password, 256) // DON'T DO THIS

// ✅ SECURE: Use non-sensitive identifiers
userID := "user-12345"
icon, err := jdenticon.Generate(ctx, userID, 256)
```

#### 3. Always Handle Errors

**Check for errors** - they may indicate security limit violations:

```go
// ✅ SECURE: Proper error handling
icon, err := jdenticon.Generate(ctx, input, size)
if err != nil {
    // Log the error - could indicate attack attempt
    log.Printf("Icon generation failed: %v", err)
    
    // Handle gracefully based on error type
    var sizeErr *jdenticon.ErrValueTooLarge
    if errors.As(err, &sizeErr) {
        return handleResourceLimitError(sizeErr)
    }
    
    return handleGeneralError(err)
}
```

#### 4. Configure Resource Limits Explicitly

**Don't rely on defaults** - set limits appropriate for your environment:

```go
config := jdenticon.Config{
    MaxIconSize: 1024,    // Maximum 1024×1024 pixels
    MaxInputLength: 256,  // Maximum 256 byte input strings
    MaxComplexity: 50,    // Reduce computational complexity
    // ... other config options
}

// Use 0 for default limits, positive values for custom limits, -1 to disable
icon, err := jdenticon.ToSVGWithConfig(ctx, "user@example.com", 512, config)
```

**Default Security Limits:**
- **Icon Size:** 4096×4096 pixels maximum (~64MB memory usage)
- **Input Length:** 1MB maximum input string length
- **Complexity:** 100 maximum computational complexity score

### For Web Applications

#### 1. Content Security Policy for SVG Output

When serving SVG identicons, use proper Content-Security-Policy:

```html
<!-- ✅ SECURE: Restrict SVG capabilities -->
<meta http-equiv="Content-Security-Policy" 
      content="img-src 'self' data:; object-src 'none';">

<img src="data:image/svg+xml;base64,..." alt="User Avatar">
```

#### 2. Cache Generated Icons

**Avoid regenerating identical icons** to prevent resource exhaustion:

```go
// ✅ SECURE: Use generator with caching
generator, err := jdenticon.NewGeneratorWithCacheSize(1000)
if err != nil {
    return err
}

// Icons with same input will be cached
icon1, _ := generator.Generate(ctx, "user123", 64)
icon2, _ := generator.Generate(ctx, "user123", 64) // Served from cache
```

### For CLI Tool Users

#### 1. Validate Output Paths

The CLI tool includes path traversal protection, but you should still validate:

```bash
# ✅ SECURE: Use absolute paths in trusted directories
jdenticon generate "user123" --output /var/www/avatars/user123.svg

# ❌ POTENTIALLY RISKY: Don't use user-controlled paths
# jdenticon generate "$USER_INPUT" --output "$USER_PATH"
```

#### 2. Run with Minimal Privileges

```bash
# ✅ SECURE: Create dedicated user for CLI operations
sudo useradd -r -s /bin/false jdenticon-user
sudo -u jdenticon-user jdenticon generate "user123" --output avatar.svg
```

### Deployment Security

#### Container Security

When deploying in containers, apply resource limits:

```yaml
# docker-compose.yml or Kubernetes deployment
resources:
  limits:
    memory: "512Mi"
    cpu: "500m"
  requests:
    memory: "256Mi"
    cpu: "250m"
```

#### Monitoring and Alerting

Monitor these metrics for security:

- Generation error rates (potential attack indicators)
- Resource limit violations
- Unusual input patterns or sizes
- Memory/CPU usage spikes

```go
// Example monitoring code
func monitorGeneration(input string, size int, err error) {
    if err != nil {
        securityLog.Printf("Generation failed: input_len=%d, size=%d, error=%v", 
            len(input), size, err)
        
        // Check for potential attack patterns
        if len(input) > 1000 || size > 2048 {
            alertSecurityTeam("Suspicious identicon generation attempt", input, size, err)
        }
    }
}
```

### Platform-Specific Considerations

#### 32-bit Systems
- Integer overflow protections are in place for hash parsing
- Memory limits may need adjustment for smaller address space

#### Container Environments
- Apply CPU and memory limits as defense in depth
- Monitor for container escape attempts through resource exhaustion

### Security Limitations & Known Issues

1. **Cryptographic Attacks**: The output is deterministic and predictable - not suitable for security purposes
2. **Information Leakage**: Identical inputs produce identical outputs - avoid using sensitive data
3. **Side-Channel Attacks**: Processing time may vary based on input complexity
4. **Dependency Vulnerabilities**: Keep Go toolchain and any external dependencies updated

### Security Updates

Security updates are distributed through:

- **GitHub Releases**: All security fixes are released as new versions
- **GitHub Security Advisories**: Critical issues are published as security advisories
- **Go Module Proxy**: Updates are automatically available through `go get -u`

### Emergency Response

#### If You Suspect an Attack

1. **Monitor**: Check logs for patterns of failed generations or resource limit violations
2. **Investigate**: Look for common source IPs or unusual input patterns  
3. **Respond**: Apply rate limiting, blocking, or input filtering as appropriate
4. **Document**: Keep records for potential security team review

## Security Best Practices Summary

### For Developers ✅
- Always validate inputs before passing to the library
- Handle all errors returned by library functions
- Never use sensitive data as identicon input
- Configure resource limits explicitly for your environment
- Use proper Content-Security-Policy when serving SVGs

### For Operators ✅
- Apply container-level resource limits as defense in depth
- Monitor generation metrics and error rates
- Keep dependencies updated with vulnerability scanning
- Run CLI tools with minimal privileges
- Set up alerting for suspicious patterns

### For Security Teams ✅
- Review configuration limits match threat model
- Include go-jdenticon in vulnerability scanning processes
- Monitor for new security advisories
- Test disaster recovery procedures for DoS scenarios
- Validate secure coding practices in applications using the library

---

### Questions?

If you have questions about this security policy or need clarification on whether an issue should be reported as a security vulnerability, please open a regular GitHub issue with the tag "security-question" (this is for questions about the policy, not for reporting actual vulnerabilities).

---

**Last Updated**: 2025-06-24  
**Policy Version**: 1.0
