feat(docker-watcher): phase 12 - hardening
Blue-green zero-downtime deploys, promote flow validation. Dual auth: local (bcrypt + JWT) and OAuth2/OIDC (any provider). Auth middleware, login page, auth settings UI. Structured logging (slog JSON), config export to YAML. Graceful shutdown with deploy draining. Multi-stage Dockerfile and production docker-compose.yml. Swap phase order: Volumes & Env before UI Polish.
This commit is contained in:
@@ -0,0 +1,111 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// ErrInvalidCredentials indicates that the supplied username/password is wrong.
|
||||
var ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
|
||||
// ErrInvalidToken indicates that the JWT is invalid or expired.
|
||||
var ErrInvalidToken = errors.New("invalid or expired token")
|
||||
|
||||
// TokenExpiry is the lifetime of a JWT session token.
|
||||
const TokenExpiry = 24 * time.Hour
|
||||
|
||||
// jwtClaims extends jwt.RegisteredClaims with application-specific fields.
|
||||
type jwtClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
UserID string `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
// LocalAuth handles password hashing and JWT token management for local auth mode.
|
||||
type LocalAuth struct {
|
||||
jwtSecret []byte
|
||||
}
|
||||
|
||||
// NewLocalAuth creates a LocalAuth deriving the JWT signing key from the encryption key
|
||||
// using HMAC-SHA256.
|
||||
func NewLocalAuth(encKey [32]byte) *LocalAuth {
|
||||
mac := hmac.New(sha256.New, encKey[:])
|
||||
mac.Write([]byte("docker-watcher-jwt-secret"))
|
||||
return &LocalAuth{
|
||||
jwtSecret: mac.Sum(nil),
|
||||
}
|
||||
}
|
||||
|
||||
// HashPassword hashes a plaintext password using bcrypt.
|
||||
func HashPassword(password string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hash password: %w", err)
|
||||
}
|
||||
return string(hash), nil
|
||||
}
|
||||
|
||||
// CheckPassword compares a plaintext password against a bcrypt hash.
|
||||
func CheckPassword(hash, password string) error {
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)); err != nil {
|
||||
return ErrInvalidCredentials
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GenerateToken creates a signed JWT for the given user claims.
|
||||
func (la *LocalAuth) GenerateToken(claims Claims) (SessionToken, error) {
|
||||
expiresAt := time.Now().Add(TokenExpiry)
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwtClaims{
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(expiresAt),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
Issuer: "docker-watcher",
|
||||
},
|
||||
UserID: claims.UserID,
|
||||
Username: claims.Username,
|
||||
Role: claims.Role,
|
||||
})
|
||||
|
||||
signed, err := token.SignedString(la.jwtSecret)
|
||||
if err != nil {
|
||||
return SessionToken{}, fmt.Errorf("sign token: %w", err)
|
||||
}
|
||||
|
||||
return SessionToken{
|
||||
Token: signed,
|
||||
ExpiresAt: expiresAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ValidateToken parses and validates a JWT, returning the embedded claims.
|
||||
func (la *LocalAuth) ValidateToken(tokenString string) (Claims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &jwtClaims{}, func(token *jwt.Token) (any, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return la.jwtSecret, nil
|
||||
})
|
||||
if err != nil {
|
||||
return Claims{}, ErrInvalidToken
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*jwtClaims)
|
||||
if !ok || !token.Valid {
|
||||
return Claims{}, ErrInvalidToken
|
||||
}
|
||||
|
||||
return Claims{
|
||||
UserID: claims.UserID,
|
||||
Username: claims.Username,
|
||||
Role: claims.Role,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// contextKey is the type for context value keys used by the auth package.
|
||||
type contextKey string
|
||||
|
||||
const claimsKey contextKey = "auth_claims"
|
||||
|
||||
// Middleware returns an HTTP middleware that protects routes by requiring a valid JWT.
|
||||
// It extracts the token from the Authorization header (Bearer scheme) or the "token"
|
||||
// query parameter (for SSE connections).
|
||||
// Unauthenticated requests receive a 401 JSON response.
|
||||
func Middleware(la *LocalAuth) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
tokenStr := extractToken(r)
|
||||
if tokenStr == "" {
|
||||
http.Error(w, `{"success":false,"error":"authentication required"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := la.ValidateToken(tokenStr)
|
||||
if err != nil {
|
||||
http.Error(w, `{"success":false,"error":"invalid or expired token"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), claimsKey, claims)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// AdminOnly returns an HTTP middleware that requires the authenticated user to have
|
||||
// the "admin" role.
|
||||
func AdminOnly(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
claims, ok := ClaimsFromContext(r.Context())
|
||||
if !ok || claims.Role != "admin" {
|
||||
http.Error(w, `{"success":false,"error":"admin access required"}`, http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// ClaimsFromContext retrieves the authenticated user's claims from the request context.
|
||||
func ClaimsFromContext(ctx context.Context) (Claims, bool) {
|
||||
claims, ok := ctx.Value(claimsKey).(Claims)
|
||||
return claims, ok
|
||||
}
|
||||
|
||||
// extractToken gets the JWT from the Authorization header or "token" query param.
|
||||
func extractToken(r *http.Request) string {
|
||||
// Try Authorization: Bearer <token>
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if strings.HasPrefix(authHeader, "Bearer ") {
|
||||
return strings.TrimPrefix(authHeader, "Bearer ")
|
||||
}
|
||||
|
||||
// Fall back to query parameter (used by SSE and browser-based connections).
|
||||
return r.URL.Query().Get("token")
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package auth
|
||||
|
||||
import "time"
|
||||
|
||||
// User represents an authenticated user stored in the database.
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
PasswordHash string `json:"-"`
|
||||
Email string `json:"email"`
|
||||
Role string `json:"role"` // admin, viewer
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// AuthSettings holds the authentication configuration (single-row pattern).
|
||||
type AuthSettings struct {
|
||||
AuthMode string `json:"auth_mode"` // local, oidc
|
||||
OIDCClientID string `json:"oidc_client_id"`
|
||||
OIDCClientSecret string `json:"-"`
|
||||
OIDCIssuerURL string `json:"oidc_issuer_url"`
|
||||
OIDCRedirectURL string `json:"oidc_redirect_url"`
|
||||
}
|
||||
|
||||
// Claims represents the JWT token claims.
|
||||
type Claims struct {
|
||||
UserID string `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
// SessionToken is the response sent to the client after successful authentication.
|
||||
type SessionToken struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
// LoginRequest is the expected JSON body for the login endpoint.
|
||||
type LoginRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// OIDCProvider wraps an OIDC provider and OAuth2 configuration.
|
||||
type OIDCProvider struct {
|
||||
provider *oidc.Provider
|
||||
oauth2Config oauth2.Config
|
||||
verifier *oidc.IDTokenVerifier
|
||||
}
|
||||
|
||||
// OIDCConfig holds the configuration needed to set up an OIDC provider.
|
||||
type OIDCConfig struct {
|
||||
IssuerURL string
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
RedirectURL string
|
||||
}
|
||||
|
||||
// OIDCUserInfo represents the user information extracted from an OIDC ID token.
|
||||
type OIDCUserInfo struct {
|
||||
Subject string `json:"sub"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"preferred_username"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// NewOIDCProvider initializes an OIDC provider using the discovery URL.
|
||||
func NewOIDCProvider(ctx context.Context, cfg OIDCConfig) (*OIDCProvider, error) {
|
||||
provider, err := oidc.NewProvider(ctx, cfg.IssuerURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create oidc provider: %w", err)
|
||||
}
|
||||
|
||||
oauth2Config := oauth2.Config{
|
||||
ClientID: cfg.ClientID,
|
||||
ClientSecret: cfg.ClientSecret,
|
||||
RedirectURL: cfg.RedirectURL,
|
||||
Endpoint: provider.Endpoint(),
|
||||
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
|
||||
}
|
||||
|
||||
verifier := provider.Verifier(&oidc.Config{ClientID: cfg.ClientID})
|
||||
|
||||
return &OIDCProvider{
|
||||
provider: provider,
|
||||
oauth2Config: oauth2Config,
|
||||
verifier: verifier,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// AuthCodeURL returns the URL to redirect the user to for OIDC authentication.
|
||||
func (op *OIDCProvider) AuthCodeURL(state string) string {
|
||||
return op.oauth2Config.AuthCodeURL(state)
|
||||
}
|
||||
|
||||
// Exchange trades an authorization code for tokens and returns the user info
|
||||
// extracted from the ID token.
|
||||
func (op *OIDCProvider) Exchange(ctx context.Context, code string) (OIDCUserInfo, error) {
|
||||
token, err := op.oauth2Config.Exchange(ctx, code)
|
||||
if err != nil {
|
||||
return OIDCUserInfo{}, fmt.Errorf("exchange code: %w", err)
|
||||
}
|
||||
|
||||
rawIDToken, ok := token.Extra("id_token").(string)
|
||||
if !ok {
|
||||
return OIDCUserInfo{}, fmt.Errorf("no id_token in response")
|
||||
}
|
||||
|
||||
idToken, err := op.verifier.Verify(ctx, rawIDToken)
|
||||
if err != nil {
|
||||
return OIDCUserInfo{}, fmt.Errorf("verify id_token: %w", err)
|
||||
}
|
||||
|
||||
var userInfo OIDCUserInfo
|
||||
if err := idToken.Claims(&userInfo); err != nil {
|
||||
return OIDCUserInfo{}, fmt.Errorf("parse id_token claims: %w", err)
|
||||
}
|
||||
|
||||
return userInfo, nil
|
||||
}
|
||||
Reference in New Issue
Block a user