# Golang - Create Bulletproof Enterprise APIs ## 1. **Use HTTPS (TLS)** - Always serve your APIs over HTTPS to protect data in transit. This can be done by configuring your web server (e.g., `net/http`) to use SSL/TLS certificates. - For example, in Go, you can serve an HTTPS API with: ```go log.Fatal(http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)) ``` - Consider using **Let's Encrypt** for free SSL certificates. ### 2. **Authentication and Authorization** - **OAuth2 / JWT (JSON Web Tokens)**: Use JWT for stateless authentication. Golang provides JWT support via libraries like `github.com/dgrijalva/jwt-go` or `github.com/golang-jwt/jwt`. - Example: ```go token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { return []byte("your-256-bit-secret"), nil }) ``` - Ensure proper **role-based access control (RBAC)** or **attribute-based access control (ABAC)** depending on the user's permissions. - Implement OAuth2 for broader access management, using libraries like `golang.org/x/oauth2`. ### 3. **Rate Limiting and Throttling** - Implement rate limiting to prevent abuse or DoS (Denial of Service) attacks. You can use a library like `golang.org/x/time/rate` for rate limiting: ```go limiter := rate.NewLimiter(1, 5) // Allow 1 request per second with a burst of 5. ``` - Enforce IP-based rate limiting to prevent brute force attacks. ### 4. **Input Validation** - Always validate incoming data to avoid injection attacks like **SQL Injection**, **XSS**, or **Command Injection**. - Use proper validation mechanisms, such as `go-playground/validator` for struct validation: ```go type User struct { Name string `validate:"required"` Age int `validate:"gte=0,lte=130"` } ``` - Avoid string concatenation for SQL queries. Instead, use parameterized queries with packages like `database/sql` or `gorm`. ### 5. **Secure Dependencies** - Use minimal and well-maintained dependencies. Go’s `go.mod` and `go.sum` files help lock dependencies. - Periodically scan for vulnerabilities using tools like **Snyk** or **Dependabot**. - Update your Go version and dependencies regularly to patch security vulnerabilities. ### 6. **Error Handling and Logging** - Avoid exposing sensitive information through error messages. Ensure that user-facing errors are sanitized and generic. - Log errors internally with enough information for debugging but without exposing sensitive details (e.g., credentials, tokens). - Use Go's logging packages (`log` or `zap`) with proper configuration to log securely. ### 7. **CORS (Cross-Origin Resource Sharing)** - Configure **CORS** policies properly to ensure that only trusted domains can access your API. - Use libraries like `github.com/rs/cors` to handle CORS in Golang: ```go c := cors.New(cors.Options{ AllowedOrigins: []string{"http://example.com"}, }) handler := c.Handler(apiHandler) ``` ### 8. **CSRF (Cross-Site Request Forgery) Protection** - Implement CSRF tokens to protect against malicious actions performed by authenticated users. - For APIs that require state (e.g., session-based), consider using a CSRF protection library like `gorilla/csrf`. ### 9. **Use Secure HTTP Headers** - Set proper HTTP headers to enhance security: - **Content-Security-Policy (CSP)** - **Strict-Transport-Security (HSTS)** - **X-Content-Type-Options**: Prevent MIME-type sniffing. - **X-Frame-Options**: Prevent clickjacking attacks. - **X-XSS-Protection**: Enable cross-site scripting filter. - In Go, you can set headers with: ```go w.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains") ``` ### 10. **Prevent SQL Injection** - Always use parameterized queries with the `database/sql` package to avoid SQL Injection attacks: ```go row := db.QueryRow("SELECT name FROM users WHERE id = ?", userID) ``` ### 11. **Limit Attack Surface** - **Minimize API exposure**: Only expose the endpoints that are absolutely necessary. Avoid exposing debug endpoints in production. - Use tools like **Swagger** to document and control what endpoints are accessible. ### 12. **Monitor and Audit API Activity** - Implement logging for API access and integrate tools for monitoring and auditing, such as **Prometheus**, **Grafana**, or **AWS CloudWatch**. - Track sensitive operations and ensure that proper audit trails are in place. ### 13. **Security Headers Middleware** - Implement middleware to inject security headers for every request. Here’s an example middleware for setting headers: ```go func securityHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Frame-Options", "DENY") w.Header().Set("X-XSS-Protection", "1; mode=block") next.ServeHTTP(w, r) }) } ``` ### 14. **Use Secure Session Management** - If you're managing sessions, use secure cookies with flags like `HttpOnly` and `Secure` to prevent cookie hijacking. - Example: ```go http.SetCookie(w, &http.Cookie{ Name: "session_id", Value: "abc123", HttpOnly: true, Secure: true, }) ``` ### 15. **API Key Management** - Use API keys to restrict access to trusted clients. Rotate keys regularly and use rate limiting even on authenticated requests. - Ensure that API keys are stored securely in environment variables or secure vaults like AWS Secrets Manager. ### 16. **Security Testing** - Regularly test your API with tools like **OWASP Zap** or **Burp Suite** to identify vulnerabilities. - Integrate Static Application Security Testing (SAST) tools like **SonarQube** to find security issues in your Go codebase early. ### Summary of Key Go Libraries for API Security: - **JWT**: `github.com/golang-jwt/jwt` - **OAuth2**: `golang.org/x/oauth2` - **CORS**: `github.com/rs/cors` - **Validator**: `github.com/go-playground/validator` - **CSRF**: `github.com/gorilla/csrf`