GoChat implements multiple layers of security to protect against common WebSocket vulnerabilities and abuse.
- Origin Validation
- Rate Limiting
- Message Size Limits
- Security Scanning
- Security Best Practices
- Reporting Security Issues
The server validates the Origin header of all WebSocket connection requests to prevent Cross-Site WebSocket Hijacking (CSWSH) attacks.
- Every WebSocket upgrade request must include a valid
Originheader - The origin is normalized (scheme and host are lowercased)
- Only origins in the allowed list can establish connections
- Requests from disallowed origins are rejected with a 403 Forbidden response
- The server logs all blocked connection attempts
AllowedOrigins: []string{
"http://localhost:8080",
}Modify the allowed origins in internal/server/config.go:
AllowedOrigins: []string{
"http://localhost:8080",
"https://yourdomain.com",
"https://www.yourdomain.com",
}WARNING: Never use this in production!
AllowedOrigins: []string{"*"}- Prevents CSWSH attacks: Malicious websites cannot connect to your chat server
- Whitelist approach: Only explicitly allowed origins can connect
- Production requirement: Always configure actual domain names, never use
* - Multiple domains: Include all legitimate frontend domains (www, subdomains, etc.)
# This should succeed (if localhost:8080 is allowed)
websocat ws://localhost:8080/ws -H "Origin: http://localhost:8080"
# This should fail (origin not in allowed list)
websocat ws://localhost:8080/ws -H "Origin: http://malicious-site.com"GoChat implements per-connection token bucket rate limiting to prevent message flooding and abuse.
- Each client connection has its own rate limiter
- The limiter starts with a burst of tokens
- Each message sent consumes 1 token
- Tokens refill at a configured rate
- When a client runs out of tokens, the connection is closed
RateLimit: RateLimitConfig{
Burst: 5, // Allow 5 messages immediately
RefillInterval: time.Second, // Refill 5 tokens per second
}This allows:
- Burst: Up to 5 messages instantly
- Sustained rate: 5 messages per second
- Recovery: Full burst capacity restored every second
Normal Usage:
- Client sends 3 messages per second
- Result: No issues, well within limits
Burst Traffic:
- Client sends 5 messages instantly
- Result: Allowed (uses burst capacity)
- Tokens refill over the next second
Abuse Attempt:
- Client attempts to send 100 messages instantly
- Result: First 5 succeed, connection closed after token exhaustion
Sustained Flooding:
- Client sends 10 messages per second continuously
- Result: First 5 succeed, then connection closed
Modify the configuration in internal/server/config.go:
RateLimit: RateLimitConfig{
Burst: 10, // Higher burst for occasional spikes
RefillInterval: 500 * time.Millisecond, // Faster refill (10 tokens/sec)
}Recommendations:
- Chat applications: 5-10 messages/second is typically sufficient
- High-frequency trading: May need higher limits (50-100/sec)
- Public servers: Keep limits conservative to prevent abuse
- Private networks: Can be more lenient
- DoS prevention: Stops malicious clients from overwhelming the server
- Resource protection: Prevents excessive CPU and bandwidth usage
- Fair sharing: One abusive client cannot affect others
- Legitimate bursts: Allows normal usage patterns (quick replies, etc.)
The server does not currently expose rate limit information in headers, but clients are disconnected if limits are exceeded. Consider implementing exponential backoff in your client code.
Message size limits prevent memory exhaustion attacks and reduce bandwidth consumption.
- Maximum message size: 512 bytes
- Read buffer size: 1024 bytes
- Write buffer size: 1024 bytes
- WebSocket upgrader sets buffer sizes
- Configuration enforces maximum message size
- Messages exceeding the limit cause the connection to close
- No warning is sent - connection is terminated immediately
In internal/server/config.go:
MaxMessageSize: 1024, // Allow larger messages (in bytes)Note: Also update the WebSocket upgrader buffer sizes in internal/server/handlers.go if needed:
var upgrader = websocket.Upgrader{
ReadBufferSize: 2048, // Increase if needed
WriteBufferSize: 2048, // Increase if needed
CheckOrigin: checkOrigin,
}| Use Case | Recommended Size |
|---|---|
| Short chat messages | 256-512 bytes |
| Regular chat messages | 512-1024 bytes |
| Rich text/links | 1024-2048 bytes |
| JSON with metadata | 2048-4096 bytes |
JSON overhead adds to your message size:
{ "content": "Hello" }- Content: 5 bytes
- JSON structure: 15 bytes
- Total: 20 bytes
A 512-byte limit allows approximately 500 characters of message content.
GoChat uses automated security scanning tools in the CI/CD pipeline and for local development.
govulncheck - Official Go vulnerability database scanner
- Scans all dependencies for known CVEs
- Runs on every commit and pull request
- Checks against the Go vulnerability database
- Zero-configuration security monitoring
# Run locally
govulncheck ./...gosec - Security-focused Go static analyzer
- Checks for common security issues:
- SQL injection vulnerabilities
- Command injection risks
- Unsafe use of cryptography
- File permission issues
- Hardcoded credentials
- And more...
# Run locally
gosec ./...# Run comprehensive security scan
make security-scan
# This runs:
# - govulncheck for dependency vulnerabilities
# - gosec for code security issues- Regular updates: Dependencies are updated frequently
- Security patches: Critical vulnerabilities are patched immediately
- License compliance: All dependencies use permissive licenses
- Minimal dependencies: Only essential packages are used
Every commit and pull request runs:
- govulncheck - Dependency vulnerability scan
- gosec - Static security analysis
- Dependency check - License and update verification
- Test suite - Including security-focused tests
-
Always use TLS/WSS
- Never use plain WS in production
- Encrypt all traffic between clients and server
- See Deployment Guide
-
Run behind a reverse proxy
- Add additional security layers
- Implement rate limiting at proxy level
- Filter malicious requests
-
Configure allowed origins
- Never use
*(allow all) in production - List all legitimate frontend domains
- Include all subdomains and variants
- Never use
-
Monitor and log
- Track failed connection attempts
- Monitor rate limit violations
- Set up alerts for unusual patterns
-
Keep dependencies updated
- Run
govulncheckregularly - Update Go to the latest version
- Patch vulnerabilities promptly
- Run
-
Firewall configuration
- Only expose necessary ports (443 for WSS)
- Block direct access to the Go server
- Use reverse proxy as the public endpoint
-
DDoS protection
- Use a CDN or DDoS protection service
- Implement connection limits
- Rate limit at multiple layers
-
IP whitelisting (if applicable)
- Restrict access to known IP ranges
- Implement at firewall or reverse proxy level
-
Input validation
- Validate all message content
- Sanitize data before processing
- Reject malformed JSON
-
Error handling
- Don't expose internal errors to clients
- Log errors securely
- Avoid information leakage
-
Authentication (future consideration)
- Currently, GoChat has no built-in authentication
- Implement authentication at the application level
- Consider JWT tokens or session-based auth
If you discover a security vulnerability in GoChat, please follow responsible disclosure practices:
- Open a public GitHub issue
- Disclose the vulnerability publicly
- Exploit the vulnerability
-
Contact maintainers directly
- Email: (Add contact email)
- Private message on GitHub
-
Provide details
- Description of the vulnerability
- Steps to reproduce
- Potential impact
- Suggested fix (if known)
-
Allow time for a fix
- Give maintainers reasonable time to address the issue
- Coordinate disclosure timeline
- Receive credit in security advisory (if desired)
- Acknowledgment: Within 48 hours
- Initial assessment: Within 7 days
- Fix timeline: Depends on severity
- Critical: 1-7 days
- High: 1-2 weeks
- Medium: 2-4 weeks
- Low: Next release cycle
- TLS/WSS enabled with valid certificate
- Allowed origins configured (no
*) - Running behind reverse proxy
- Rate limits configured appropriately
- Message size limits set
- Security scanning in CI/CD
- Dependencies up to date
- Firewall rules configured
- Monitoring and logging enabled
- Incident response plan in place
- Getting Started - Installation and setup
- API Documentation - WebSocket API details
- Deployment Guide - Production deployment with TLS
- Development Guide - Security testing and development