Skip to content

Security: Youngermaster/go-fiber-auth-docker-postgres-jwt

Security

SECURITY.md

Security Policy

Overview

This document outlines the security measures implemented in this Go Fiber + JWT authentication boilerplate and provides best practices for deployment.

Security Features Implemented

1. Authentication & Authorization

JWT Token Security

  • HS256 Signing Algorithm: Industry-standard JWT signing
  • 72-hour Token Expiration: Automatic token invalidation after 3 days
  • Secure Token Claims: Includes user_id, username, and exp (expiration)
  • Token Validation Middleware: Protects sensitive endpoints from unauthorized access

Password Security

  • Bcrypt Hashing: Passwords are hashed using bcrypt with cost factor 14
  • Strong Password Requirements:
    • Minimum 8 characters (increased from 6)
    • Maximum 100 characters
  • Timing Attack Mitigation: Dummy hash check performed even when user is not found during login
  • No Password Exposure: Password hashes are never returned in API responses

2. Rate Limiting

Login Endpoint Protection

  • 5 requests per minute per IP address
  • Prevents brute force attacks on authentication endpoint
  • Returns 429 (Too Many Requests) when limit is exceeded
  • IP-based tracking using client IP address

3. Input Validation

User Input

  • Username: 3-50 characters, required
  • Email: Valid email format, required
  • Password: 8-100 characters, required
  • Names: Optional field, max 255 characters

Product Input

  • Title: 1-255 characters, required
  • Description: 1-2000 characters, required
  • Amount: Minimum 0, required
  • User ownership tracking automatically enforced

4. Authorization Controls

Resource Ownership

  • Products: Users can only delete products they created
  • User Profiles: Users can only update/delete their own profiles
  • Proper HTTP Status Codes:
    • 401 Unauthorized: Invalid credentials
    • 403 Forbidden: Insufficient permissions
    • 409 Conflict: Duplicate user/email

5. CORS Configuration

AllowOrigins:     "http://localhost:3000,http://localhost:3001"
AllowMethods:     "GET,POST,PATCH,DELETE"
AllowHeaders:     "Origin,Content-Type,Accept,Authorization"
AllowCredentials: true
MaxAge:           300

Important: Update AllowOrigins for production to include only your trusted domains.

6. Database Security

  • Parameterized Queries: GORM prevents SQL injection
  • Soft Deletes: Data preservation with DeletedAt timestamps
  • Unique Constraints: Username and email uniqueness enforced at DB level
  • Configurable Host: Database host configurable via DB_HOST environment variable

7. Pagination

  • GetAllProducts: Implements pagination to prevent resource exhaustion
    • Default: 10 items per page
    • Maximum: 100 items per page
    • Provides total count and page metadata

Environment Variables Security

Required Variables

DB_HOST=db                    # Database host (default: "db" for Docker)
DB_PORT=5432                  # Database port
DB_USER=your_db_user          # Database username
DB_PASSWORD=strong_password   # Strong database password
DB_NAME=your_db_name          # Database name
SECRET=your-strong-secret-key # JWT secret (MUST be 32+ characters)

Critical Security Requirements

  1. JWT Secret:

    • MUST be at least 32 characters long
    • Use cryptographically random characters
    • Generate using: openssl rand -base64 32
    • NEVER commit to version control
    • Different secret for each environment
  2. Database Credentials:

    • Use strong, unique passwords
    • Different credentials for dev/staging/production
    • Never use default credentials
  3. Environment File Management:

    • .env should be in .gitignore
    • Use .env.example as a template only
    • Never commit actual secrets

API Security Best Practices

Endpoint Protection Status

Public Endpoints (No Authentication Required)

  • GET /api/ - Health check
  • POST /api/auth/login - User login (rate-limited)
  • GET /api/user/:id - Get user (password hash excluded)
  • POST /api/user/ - Create user
  • GET /api/product/ - Get all products (paginated)
  • GET /api/product/:id - Get single product

Protected Endpoints (JWT Required)

  • PATCH /api/user/:id - Update user (ownership validated)
  • DELETE /api/user/:id - Delete user (password confirmation required)
  • POST /api/product/ - Create product (auto-assigns to user)
  • DELETE /api/product/:id - Delete product (ownership validated)

Deployment Security Checklist

Before Production Deployment

  • Generate a strong JWT secret (32+ characters)
  • Update CORS AllowOrigins to production domain(s)
  • Set strong database passwords
  • Enable HTTPS/TLS at reverse proxy level (nginx, Traefik, etc.)
  • Configure firewall rules to restrict database access
  • Review and update rate limiting thresholds
  • Enable database backups
  • Set up monitoring and alerting
  • Review and update Docker security (non-root user, security scanning)
  • Implement log rotation and secure log storage
  • Consider adding request size limits
  • Add security headers (helmet middleware)
  • Implement API versioning for future changes

Additional Recommendations

  1. HTTPS Only

    • Always use HTTPS in production
    • Set Secure flag on cookies if using cookie-based auth
    • Use HSTS headers
  2. Monitoring & Logging

    • Log authentication attempts
    • Monitor rate limit violations
    • Alert on suspicious activity patterns
    • Do NOT log sensitive data (passwords, tokens)
  3. Database

    • Enable SSL/TLS for database connections in production
    • Regular backups with encryption
    • Principle of least privilege for DB users
  4. Docker Security

    • Run containers as non-root user
    • Use official base images only
    • Scan images for vulnerabilities
    • Keep base images updated
  5. API Security

    • Consider implementing API keys for third-party access
    • Add request body size limits
    • Implement request signing for sensitive operations
    • Consider adding 2FA for user accounts

Known Limitations

Current Implementation

  1. No Token Refresh: Tokens expire after 72 hours with no refresh mechanism

    • Recommendation: Implement refresh tokens for better UX
  2. IP-Based Rate Limiting: Can be bypassed with distributed attacks

    • Recommendation: Consider using Redis for distributed rate limiting
  3. No Email Verification: Users can register without email verification

    • Recommendation: Add email verification flow
  4. No Password Reset: No forgot password functionality

    • Recommendation: Implement secure password reset with email
  5. No Account Lockout: No temporary lockout after multiple failed attempts

    • Recommendation: Add account lockout after N failed login attempts
  6. Soft Delete Conflicts: Username/email may conflict with soft-deleted records

    • Recommendation: Handle unique constraints properly with soft deletes

Vulnerability Reporting

If you discover a security vulnerability, please email the maintainer directly. Do not open a public issue.

Security Updates

This project uses the following security-critical dependencies:

  • golang.org/x/crypto - Password hashing (bcrypt)
  • github.com/golang-jwt/jwt/v5 - JWT token generation and validation
  • github.com/gofiber/fiber/v2 - Web framework
  • gorm.io/gorm - ORM with SQL injection protection

Keep dependencies updated regularly:

go get -u ./...
go mod tidy

Additional Resources

License

This security documentation is provided as-is with the project. Follow these guidelines to ensure secure deployment.

There aren’t any published security advisories