Secure Coding

Purpose

Secure coding is the practice of writing code that is resilient to attack.

This guide covers the fundamental practices every engineer should follow to prevent common vulnerabilities.

Input Validation

Validate All Input

All external input is potentially malicious. Validate it before use.

Sources of external input:

Whitelist over Blacklist

Prefer whitelisting (accept known good values) over blacklisting (reject known bad values).

Blacklists are always incomplete.

# Good: whitelist
ALLOWED_ROLES = %w[admin editor viewer].freeze
raise "Invalid role" unless ALLOWED_ROLES.include?(params[:role])

# Bad: blacklist (misses edge cases)
raise "Invalid role" if params[:role].include?("admin")

Validate Type, Length and Format

Authentication

Password Handling

Session Management

Multi-Factor Authentication

Require MFA for:

Authorization

Check Authorization on Every Request

Authorization should be checked on every request, not just on the login page.

def show
  record = Record.find(params[:id])
  authorize record  # Check permission
  render json: record
end

Use Centralized Authorization

Prefer a centralized authorization framework (Pundit, CanCanCan) over dispersed conditionals.

Deny by Default

If authorization is not explicitly granted, it should be denied.

Output Encoding

Context-Appropriate Encoding

Encode output according to the context where it will be used:

ContextEncoding
HTML bodyHTML entity encode.
HTML attributeHTML attribute encode.
JavaScriptJavaScript escape.
URLURL encoding.
SQLParameterized queries.

Frameworks like Rails handle most output encoding automatically. Be careful when bypassing it with .html_safe or raw.

Error Handling

Don't Leak Sensitive Information

Error messages should not reveal:

# Bad
render json: { error: "SQL error: column 'ssn' not found" }

# Good
render json: { error: "An unexpected error occurred" }

Log Security Events

Log the following security events:

Cryptography

Use Standard Libraries

Never implement custom cryptography. Use standard, well-reviewed libraries.

Encryption in Transit

Encryption at Rest

Related Documents