security

package module
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 27, 2026 License: MIT Imports: 8 Imported by: 0

README

go-security

Go Reference Go Report Card CI Status Coverage Go Version License OWASP

Enterprise-grade security framework for Go applications, aligned with the OWASP ASVS v4.0 and OWASP Top 10 (2021).

Features

Package Concern OWASP Mapping
jwt/ JSON Web Token issuance & verification A01:2021, ASVS 3.4
oauth2/ OAuth 2.1 / OIDC client flows A01:2021, A07:2021, ASVS 3.4
apikey/ API key generation, hashing, rotation A07:2021, ASVS 3.2
hmac/ HMAC-SHA256/384/512 with constant-time compare ASVS 6.2
rbac/ Role-Based Access Control with hierarchy A01:2021, ASVS 4.1
permission/ Permission & ABAC engine (wildcard, deny-by-default) A01:2021, ASVS 4.1–4.3
password/ Password hashing (argon2id/bcrypt/scrypt) & policy A02:2021, A07:2021, ASVS 2.4
csrf/ Double-submit cookie CSRF protection A01:2021, ASVS 4.2
cors/ Configurable CORS middleware A05:2021, ASVS 14.5
ratelimit/ Token-bucket & sliding-window rate limiters A04:2021, ASVS 11.1
headers/ OWASP secure HTTP response headers A05:2021, ASVS 14.1
ipwhitelist/ CIDR IP allow/deny lists with trusted-proxy handling ASVS 14.3
signature/ HMAC/RSA request signing with replay protection ASVS 9.2
totp/ TOTP (RFC 6238) & HOTP (RFC 4226) for 2FA A07:2021, ASVS 2.1
cookie/ AES-GCM encrypted cookies with HMAC authentication A02:2021, ASVS 3.4
encrypt/ AES-256-GCM encryption at rest with key rotation A02:2021, ASVS 6.2
jwks/ Remote JWKS fetcher with caching & auto-refresh A07:2021, ASVS 3.4
oidc/ OpenID Connect discovery & ID token verification A07:2021, ASVS 3.4
session/ Session management with pluggable store (memory, Redis) A01:2021, A07:2021, ASVS 3.3

Quick Start

go get github.com/natifdevelopment/go-security
JWT
import "github.com/natifdevelopment/go-security/jwt"

signer, err := jwt.NewHS256([]byte("32-byte-secret-32-byte-secret-xxxxx"))
token, err := signer.Sign(ctx, jwt.StandardClaims{
    Subject:   "user-123",
    Issuer:    "my-api",
    Audience:  []string{"my-api"},
    ExpiresAt: time.Now().Add(15 * time.Minute),
})

claims, err := signer.Verify(ctx, token)
import "github.com/natifdevelopment/go-security/password"

h := password.NewArgon2id()
hash, err := h.Hash(ctx, []byte("correct horse battery staple"))
ok := h.Verify(ctx, hash, []byte("correct horse battery staple"))
RBAC + Permission
import (
    "github.com/natifdevelopment/go-security/rbac"
    "github.com/natifdevelopment/go-security/permission"
)

engine := rbac.New(
    rbac.Role("admin").Inherits("editor").Allows("doc:*", "user:*"),
    rbac.Role("editor").Allows("doc:read", "doc:write"),
)
allowed := engine.Allow("admin", permission.Action("doc:delete"))
Rate Limiter
import (
    "net/http"
    "github.com/natifdevelopment/go-security/ratelimit"
)

limiter := ratelimit.NewTokenBucket(100, 10) // 100 capacity, 10/s refill
h := ratelimit.Middleware(limiter, ratelimit.ByIP())(myHandler)
Secure Headers
import "github.com/natifdevelopment/go-security/headers"

h := headers.Middleware(headers.OWASPDefaults())(myHandler)
CORS
import "github.com/natifdevelopment/go-security/cors"

h := cors.Middleware(cors.Config{
    AllowOrigins:     []string{"https://app.example.com"},
    AllowMethods:     []string{"GET", "POST"},
    AllowCredentials: true,
})(myHandler)
CSRF
import "github.com/natifdevelopment/go-security/csrf"

h := csrf.Middleware([]byte("32-byte-secret-32-byte-secret-xxxxx"))(myHandler)
IP Whitelist
import "github.com/natifdevelopment/go-security/ipwhitelist"

wl, _ := ipwhitelist.New(ipwhitelist.Allow("10.0.0.0/8"), ipwhitelist.Allow("192.168.0.0/16"))
h := wl.Middleware()(myHandler)
Request Signature
import "github.com/natifdevelopment/go-security/signature"

signer := signature.NewHMACSigner([]byte("secret"))
sig, err := signer.Sign(ctx, signature.Request{
    Method:  "POST",
    Path:    "/api/v1/orders",
    Body:    bodyBytes,
    Headers: map[string]string{"X-Custom": "v"},
})

verifier := signature.NewHMACVerifier([]byte("secret"), signature.WithTolerance(5*time.Minute))
err := verifier.Verify(ctx, signature.Request{...}, sig)
API Key
import "github.com/natifdevelopment/go-security/apikey"

mgr := apikey.NewManager()
key, hash, err := mgr.Generate(ctx, "svc-payments")
stored := apikey.Verify(ctx, hash, key) // constant-time
HMAC
import "github.com/natifdevelopment/go-security/hmac"

mac := hmac.SHA256(secret, message)
ok := hmac.VerifySHA256(secret, message, mac) // constant-time
TOTP (2FA)
import "github.com/natifdevelopment/go-security/totp"

secret, _ := totp.GenerateSecretDefault()
t, _ := totp.New(totp.WithSecret(secret))
code, _ := t.Generate()
ok, _ := t.Validate(code) // constant-time
uri := t.ProvisioningURI("user@example.com", "MyApp") // for QR code
import "github.com/natifdevelopment/go-security/cookie"

m, _ := cookie.New(cookie.NewConfig(cookie.WithKey(key32Bytes)))
_ = m.Set(w, "session", "user-id-123")
val, _ := m.Get(r, "session") // AES-GCM encrypted, tamper-proof
Encryption at Rest
import "github.com/natifdevelopment/go-security/encrypt"

c, _ := encrypt.New(key32Bytes)
ciphertext, _ := c.Encrypt(ctx, plaintext)
decrypted, _ := c.Decrypt(ctx, ciphertext) // AES-256-GCM
JWKS (Remote Key Fetching)
import "github.com/natifdevelopment/go-security/jwks"

fetcher, _ := jwks.New(jwks.Config{
    URL: "https://auth.example.com/application/o/myapp/jwks/",
})
defer fetcher.Close()

// Fetch a key by kid:
key, _ := fetcher.FetchByKeyID(ctx, "my-key-id")

// Or convert to jwt.KeySet for use with jwt.Signer:
ks, _ := fetcher.AsKeySet()
OIDC (Discovery + ID Token Verification)
import "github.com/natifdevelopment/go-security/oidc"

provider, _ := oidc.NewProvider(ctx, "https://auth.example.com/application/o/myapp/")
defer provider.Close()

// Verify an ID token:
claims, _ := provider.VerifyIDToken(ctx, idToken, oidc.VerifyOptions{
    ClientID: "my-client-id",
    Issuer:   "https://auth.example.com/application/o/myapp/",
})

// Fetch user info:
userInfo, _ := provider.UserInfo(ctx, accessToken)
Session Management
import "github.com/natifdevelopment/go-security/session"

// In-memory store (development):
store := session.NewMemoryStore()
mgr, _ := session.New(session.Config{
    Store:          store,
    SessionTTL:     24 * time.Hour,
    CookieSecure:   true,
    CookieHTTPOnly: true,
})

// Create a session:
sess, _ := mgr.Create(ctx, "user-123", map[string]any{"role": "admin"})
mgr.SetCookie(w, sess.ID)

// Validate:
sess, err := mgr.Validate(ctx, sessionID)

// Rotate (session fixation protection):
sess, _ = mgr.Rotate(ctx, oldSessionID)

// Destroy (logout):
mgr.Destroy(ctx, sessionID)
mgr.ClearCookie(w)

// Redis store (production):
// store := session.NewRedisStore(redisClient, "sess:")

Architecture

┌──────────────────────────────────────────────────────────────┐
│  CONSUMER LAYER  (net/http middleware, framework adapters)   │
└────────────────────────────┬─────────────────────────────────┘
                             │
┌────────────────────────────▼─────────────────────────────────┐
│  FACADE LAYER  (per-package public API + functional options) │
│  jwt │ oauth2 │ apikey │ hmac │ rbac │ permission │ password │
│  csrf │ cors │ ratelimit │ headers │ ipwhitelist │ signature │
│  jwks │ oidc │ session │ totp │ cookie │ encrypt │
└────────────────────────────┬─────────────────────────────────┘
                             │
┌────────────────────────────▼─────────────────────────────────┐
│  PRIMITIVE LAYER  (crypto/rand, crypto/hmac, crypto/subtle,  │
│  golang.org/x/crypto/argon2, golang-jwt, x/oauth2, x/time)   │
└──────────────────────────────────────────────────────────────┘

Package Structure

go-security/
├── jwt/            # JSON Web Token (JWS)
├── oauth2/         # OAuth 2.1 / OIDC client
├── apikey/         # API key lifecycle
├── hmac/           # HMAC primitives
├── rbac/           # Role-Based Access Control
├── permission/     # Permission & ABAC engine
├── password/       # Password hashing & policy
├── csrf/           # CSRF protection
├── cors/           # CORS middleware
├── ratelimit/      # Rate limiters
├── headers/        # Secure HTTP headers
├── ipwhitelist/    # IP allow/deny lists
├── signature/      # Request signing & replay protection
├── totp/           # TOTP & HOTP (2FA)
├── cookie/         # AES-GCM encrypted cookies
├── encrypt/        # AES-256-GCM encryption at rest
├── jwks/           # Remote JWKS fetcher with caching
├── oidc/           # OpenID Connect discovery & ID token verify
├── session/        # Session management (memory, Redis)
├── examples/       # Usage examples
└── doc.go          # Root package documentation

OWASP Compliance

This framework implements controls from:

  • OWASP ASVS v4.0 — Application Security Verification Standard
  • OWASP Top 10 (2021) — A01 Broken Access Control, A02 Cryptographic Failures, A04 Insecure Design, A05 Security Misconfiguration, A07 Identification & Auth Failures
  • OWASP Cryptographic Storage Cheat Sheet — argon2id for passwords
  • OWASP JWT Cheat Sheetnone rejection, short TTL, audience validation
  • OWASP Secure Headers Project — HSTS, CSP, X-Content-Type-Options, etc.

Security

  • All secret comparisons use crypto/subtle.ConstantTimeCompare
  • All token/key generation uses crypto/rand
  • Deny-by-default in all authorization engines
  • Replay protection for signed requests (timestamp + nonce)
  • No secrets in errors or logs

Report security vulnerabilities privately to the maintainers.

License

MIT — © 2026 Natif Development

Documentation

Overview

Package security is the root module for the go-security enterprise security framework.

It is a collection of independently importable sub-packages that together cover the most common application-security concerns of modern HTTP services, aligned with the OWASP Application Security Verification Standard (ASVS v4.0) and the OWASP Top 10 (2021).

Sub-packages

  • jwt — JSON Web Token issuance, verification & validation (JWS)
  • oauth2 — OAuth 2.1 / OIDC client helpers (auth-code, PKCE, refresh)
  • apikey — API key generation, hashing, rotation & verification
  • hmac — HMAC-SHA256/384/512 with constant-time comparison
  • rbac — Role-Based Access Control engine with role hierarchy
  • permission — Permission & ABAC engine with wildcard & deny-by-default
  • password — Password hashing (argon2id, bcrypt, scrypt) & policy
  • csrf — Double-submit cookie CSRF protection (SameSite aware)
  • cors — Configurable CORS middleware (OWASP compliant)
  • ratelimit — Token-bucket & sliding-window rate limiters
  • headers — OWASP secure HTTP response headers middleware
  • ipwhitelist — CIDR-based IP allow/deny lists with trusted-proxy handling
  • signature — HMAC/RSA request signing with replay protection
  • jwks — Remote JWKS fetcher with caching & auto-refresh
  • oidc — OpenID Connect discovery & ID token verification
  • session — Session management with pluggable store (memory, Redis)
  • totp — TOTP/HOTP 2FA (RFC 6238/4226)
  • cookie — AES-GCM encrypted secure cookies
  • encrypt — AES-256-GCM encryption with key rotation

Design Principles

  • Fail-secure: when in doubt, deny / reject
  • Context-first: all I/O operations accept context.Context
  • Functional options for configurable APIs
  • Immutable after construction where possible
  • Constant-time comparisons for all secret comparisons
  • No sensitive data in errors or logs
  • Accept interfaces, return structs

Quick Start

import (
    "github.com/natifdevelopment/go-security/jwt"
    "github.com/natifdevelopment/go-security/oidc"
    "github.com/natifdevelopment/go-security/session"
    "github.com/natifdevelopment/go-security/password"
    "github.com/natifdevelopment/go-security/rbac"
)

See each sub-package's doc.go for detailed usage examples.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Finding

type Finding struct {
	ID             int        `json:"id"`
	Severity       string     `json:"severity"`
	Category       string     `json:"category"`
	Title          string     `json:"title"`
	Description    string     `json:"description"`
	Location       string     `json:"location"`
	Status         string     `json:"status"`
	Recommendation string     `json:"recommendation"`
	CvssScore      float64    `json:"cvss_score"`
	DiscoveredAt   time.Time  `json:"discovered_at"`
	UpdatedAt      time.Time  `json:"updated_at"`
	ResolvedAt     *time.Time `json:"resolved_at,omitempty"`
}

Finding represents a security finding

type ScanHistory

type ScanHistory struct {
	ID          int       `json:"id"`
	Type        string    `json:"type"`
	Date        time.Time `json:"date"`
	IssuesFound int       `json:"issuesFound"`
	Duration    string    `json:"duration"`
	Status      string    `json:"status"`
	Score       int       `json:"score"`
	InitiatedBy string    `json:"initiatedBy"`
}

ScanHistory represents a scan history record

type ScanResult

type ScanResult struct {
	TotalFindings int       `json:"total_findings"`
	CriticalCount int       `json:"critical_count"`
	HighCount     int       `json:"high_count"`
	MediumCount   int       `json:"medium_count"`
	LowCount      int       `json:"low_count"`
	Findings      []Finding `json:"findings"`
	SecurityScore int       `json:"security_score"`
	ScanDuration  string    `json:"scan_duration"`
	ScanType      string    `json:"scan_type"`
	ScannedAt     time.Time `json:"scanned_at"`
}

ScanResult represents the result of a security scan

type Scanner

type Scanner struct {
	RootPath string
	Findings []Finding
}

Scanner represents the internal security scanner

func NewScanner

func NewScanner(rootPath string) *Scanner

NewScanner creates a new security scanner

func (*Scanner) GetRecentScans

func (s *Scanner) GetRecentScans(limit int) []ScanHistory

GetRecentScans returns recent scan history

func (*Scanner) LoadFindingsFromFile

func (s *Scanner) LoadFindingsFromFile(filePath string) error

LoadFindingsFromFile loads findings from a JSON file

func (*Scanner) RunFullScan

func (s *Scanner) RunFullScan() *ScanResult

RunFullScan runs a comprehensive security scan

func (*Scanner) SaveFindingsToFile

func (s *Scanner) SaveFindingsToFile(filePath string) error

SaveFindingsToFile saves findings to a JSON file

Directories

Path Synopsis
Package apikey provides generation, verification and rotation of opaque API keys with constant-time comparison and optional HMAC-SHA256 peppering.
Package apikey provides generation, verification and rotation of opaque API keys with constant-time comparison and optional HMAC-SHA256 peppering.
Package cookie provides secure HTTP cookie encoding and decoding with AES-GCM encryption and HMAC authentication.
Package cookie provides secure HTTP cookie encoding and decoding with AES-GCM encryption and HMAC authentication.
Package cors provides an OWASP-compliant Cross-Origin Resource Sharing (CORS) middleware for net/http servers.
Package cors provides an OWASP-compliant Cross-Origin Resource Sharing (CORS) middleware for net/http servers.
Package csrf implements Cross-Site Request Forgery (CSRF) protection for net/http servers using the Double-Submit Cookie pattern with SameSite cookie awareness and HMAC-signed tokens.
Package csrf implements Cross-Site Request Forgery (CSRF) protection for net/http servers using the Double-Submit Cookie pattern with SameSite cookie awareness and HMAC-signed tokens.
Package encrypt provides AES-GCM authenticated encryption for data-at-rest protection, with support for multiple key sizes, key derivation from passphrases (PBKDF2-HMAC-SHA256), and transparent key rotation.
Package encrypt provides AES-GCM authenticated encryption for data-at-rest protection, with support for multiple key sizes, key derivation from passphrases (PBKDF2-HMAC-SHA256), and transparent key rotation.
Package headers provides net/http middleware that applies the HTTP response headers recommended by the OWASP Secure Headers Project.
Package headers provides net/http middleware that applies the HTTP response headers recommended by the OWASP Secure Headers Project.
Package hmac provides HMAC-SHA256/384/512 primitives with constant-time comparison, suitable for request signing, webhook verification and any scenario requiring message authentication.
Package hmac provides HMAC-SHA256/384/512 primitives with constant-time comparison, suitable for request signing, webhook verification and any scenario requiring message authentication.
Package ipwhitelist provides IP-based allowlist and denylist filtering for HTTP services.
Package ipwhitelist provides IP-based allowlist and denylist filtering for HTTP services.
Package jwks provides a caching fetcher for JSON Web Key Sets (JWKS) retrieved from a remote OpenID Connect / OAuth 2.1 provider.
Package jwks provides a caching fetcher for JSON Web Key Sets (JWKS) retrieved from a remote OpenID Connect / OAuth 2.1 provider.
Package jwt provides JSON Web Token (JWS) issuance and verification with support for HMAC (HS256/384/512), RSA (RS256/384/512) and ECDSA (ES256/384/512) algorithms.
Package jwt provides JSON Web Token (JWS) issuance and verification with support for HMAC (HS256/384/512), RSA (RS256/384/512) and ECDSA (ES256/384/512) algorithms.
Package oauth2 provides OAuth 2.1 / OpenID Connect client helpers built on top of golang.org/x/oauth2, adding PKCE (S256), ID-token verification and secure defaults.
Package oauth2 provides OAuth 2.1 / OpenID Connect client helpers built on top of golang.org/x/oauth2, adding PKCE (S256), ID-token verification and secure defaults.
Package oidc provides OpenID Connect (OIDC) discovery and ID token verification helpers built on top of github.com/natifdevelopment/go-security/jwt and github.com/natifdevelopment/go-security/jwks.
Package oidc provides OpenID Connect (OIDC) discovery and ID token verification helpers built on top of github.com/natifdevelopment/go-security/jwt and github.com/natifdevelopment/go-security/jwks.
Package password provides secure password hashing and policy validation for the go-security framework.
Package password provides secure password hashing and policy validation for the go-security framework.
Package permission provides an Attribute-Based Access Control (ABAC) engine with wildcard resource matching, attribute conditions and deny-by-default semantics with explicit-deny-wins resolution.
Package permission provides an Attribute-Based Access Control (ABAC) engine with wildcard resource matching, attribute conditions and deny-by-default semantics with explicit-deny-wins resolution.
Package ratelimit provides thread-safe, per-key rate limiters and an net/http middleware for protecting HTTP services from abusive traffic.
Package ratelimit provides thread-safe, per-key rate limiters and an net/http middleware for protecting HTTP services from abusive traffic.
Package rbac provides a Role-Based Access Control engine with role hierarchy, dynamic role management and user-to-role assignment.
Package rbac provides a Role-Based Access Control engine with role hierarchy, dynamic role management and user-to-role assignment.
Package session provides generic session management with pluggable storage backends (in-memory and Redis).
Package session provides generic session management with pluggable storage backends (in-memory and Redis).
Package signature provides request signing and verification with replay protection for HTTP-style requests.
Package signature provides request signing and verification with replay protection for HTTP-style requests.
Package totp implements time-based (RFC 6238) and counter-based (RFC 4226) one-time passwords for two-factor authentication (2FA).
Package totp implements time-based (RFC 6238) and counter-based (RFC 4226) one-time passwords for two-factor authentication (2FA).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL